Friday, July 8, 2011

JAVA - JSE - 1

1)     Your understanding oops principles?
2)  Why main() in java is declared as public static void main?
PUBLIC MAIN(..) : IT is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.
STATIC java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.
VOID main does not return anything so the return type must be void-The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line. 
 3) What if the main method is declared as private?
The jvm cant find the main and will throw main not found.
      java.lang.NoClassDefFoundError:
 4) What is static in java? 
Static variable are loaded when class loader brings the class to the JVM. It is not necessary that an  object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields. 
5) What is Marker interface? How is it used in Java? 
·       Marker interface is an empty interface .
·       It is a process of storing object contents into a file.The class whose objects are stored in the file should implement 'serialiazable' interface java.io 
·       Also called marker interface or tagged interface 
·       Static and transient vaiables cannot be written into a file.
·       They are protected by the key words. 
·       Implement serializable(Empty interface) 
·       AN INTERFACE WHICH DOESNOT HAVE A BODY IS CALLEDAS AN MARKER INTERFACE
 6) What is the default value of an object reference declared as an instance variable? 
Its default value is? null? unless we define it explicitly.
7) What type of parameter passing does Java support? 
Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.
8) Can I override a static method? 
NO 
9) What is the Importance of finalize() method ?
It will close all opened connections and will destroy all the objects which are unused.
10) How setting an Object to null help Garbage Collection? 
·        You don't "set an Object to null".
·        When you do var = null,
·        What you are doing is "erasing", or removing, that reference to the Object.
·        The Object itself still exists, but that reference to it no longer does.
·        Once all references to an Object are removed, it will be Garbage Collected. 
11) When is explicit casting required ?
The casting done by a programmer is called explicit casting. Explicit casting is compulsory while converting from a higher data type to a lower data type.
12) What would you use to compare two String variables 
·        The operator == or the equals() method?
·        == compares references while .equals compares contents
13) For concatenation of strings, which method is good, StringBuffer or String?
14) Why would you say StringBuffers are less resource intensive than Strings during Concatenation?
·       As you might already know, Strings are immutable. So, when you concatenate some value to a String, you are actually creating a fresh String object that is going to hold some more data. This way you have created a new object while the old String object is still alive. As you keep concatenating values to the String, newer objects are going to get created which are going to use up the virtual memory. Whereas, if you use a StringBuffer, you are just editing the objects value rather than creating new objects.
15) What happens when you add a double value to a String? 
Then the float value will be taken as a string and will be appended if the string is having a string or will be stored as a string.
16) What will be the result if you compare StringBuffer with String if both have same values? 
·        String str="god";
·        StringBuffer sb=new StringBuffer("god");
·        System.out.println(str+" " +sb);
·        If (str == sb.toString())
·        System.out.println("TRUE");
 The output is true
17) How does substring () inside String works?
·        s1.subString(0,9) here 0 is a and 9 is b.
·        In the complete string it will read from o to 8 and will eliminate from 9 and display the string
18) What is the difference between creating String as new () and literal? 
·        If we create a string if that string is already existing then only a reference will be created.
·        If we use new it will create a new object irrespective of the previously existing things.
19) What is Singleton? is it better to make whole method synchronized or only critical section synchronized ?
20) Explain different way of using thread?
·        Mainly used on servers to mainly serve the requests made by hundreds of clients on a network
·        Threads are also used in game programming where a plane can move in directions simultaneously can fire bombs.
·        Threads can perform single tasking and multitasking(process based multitasking and thread based multitasking)
21)  Why do we need run() & start() method both. Can we achieve it with only run method? 
By using threadobject.start()  by default the run() will run.
22) What happens when I make a static method as synchronized?
Lock will be applied on the ObjectClass object        
23) Diff b/w wait and sleep() ?
      Both are used to suspend the thread from running and make it wait.Once the thread in out of non-running state ie sleep() the thread will resume its run state and if the method is synchronised then wait() will remove the lock of the thread on the object and will be out of the thread.
24) Hashmap and Hashtable?
HASH MAP:
·        They are not synchronizes
·        In case of single thread its better to use a Hash map for faster retrieval.
·        Hash map allows null values and null keys to be stored.
·        Iterator in hashmap is fail-safe.
·        This means iterator will raise exceptions if concurrent update are made to the hash map. 
HASHTABLE:
·        HashTable object is syncgronized by default
·        In case if multiple threads, Hash table is advisable. With single thread hash tabel becomes slow.
·        HashTable doesnot allow null values or keys.
·        Enumaration for the hashTabl is fail-safe.
·        This means even at concurrent updates are done to hashtable there will not be any incorrec results produced by Enumaration.
5) Where to use hashmap and where to use hashtable
26) hashcode() and equals() methods 
To identify the bucket for any , Hash map use key.hashCode() and perform some operation: 
      Bucket (index) = HashMap.indexFor HashMap.hash(key.hashCode()),entryArray.length)
      It means, two keys with different hashCode can fall under the same bucket.
27) Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
·        ArrayList() and LinkedList()
·        ArrayList and LinkedList.
·       If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time in an ArrayList. But you pay a big price in performance. Positional access requires linear-time in a LinkedList and constant-time in an ArrayList.
28) What is the difference between Enumeration and Iterator?
·        Both are used to retreive elements from collections.Iterator has methods whose names are easy to follow and Enumaration methods are difficult to remember.As Iterator has an option to remove from the collection which is not available in Enumarator. So ,Iterator is prefered to Enumarator.list() and set() usage A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements. 
29) Difference between HashMap and HashTable? Can we make hashmap synchronized?
·        The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
·        HashMap does not guarantee that the order of themap will remain constant over time.
·        HashMap is non-synchronized whereas Hashtable is synchronized.  Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. 
1.    SET: 
·    A set represents a collection of elements.
·    Order of elements may change in set 
·    Set will not allow duplicate values.
·    Accessing of elements by their index is not possible in set.
·    Set will not allow null elements.
2.    List:
·    A list represents ordered collection of elements.
·    List preserves the order of elements in which they are entered.
·    List will allow duplicate values. 
·    Accessing elements by index is possible in list.
·    List allows null elements to be stored.
1)    Synchronized means only one thread can modify a hash table at one point of time.Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
2)    Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”.However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown. HashMap can be synchronized by
       Map m = Collections.synchronizeMap(hashMap);
29) What is fail-fast property? 
·        When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: "failing immediately and visibly" sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production.
30) Vector and ArrayList()- which one to use and why 
·        Vectors are synchronized. Any method that touches the Vector's contents is thread safe.
·       ArrayList, on the other hand, is un-synchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily?
31) How hashmap works?
·        java.util.HashMap hm=new java.util.HashMap ();
·        hs.add(,);
32) What is serialization? common usage? 
·        Process of saving objects into a file 
33) Deserialization ? What is Externalizable ?
·       Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods. 
 34) What is a stored procedure? How to call stored procedure using JDBC API?
·        A stored procedure represents set of statements that is stored and executed at database server,and send the results to the client.
       CallableStatement stmt=con.prepareCall("{ call MyProc(?,?) }");
35) What is Connection pooling? What are the advantages of using a connection pool?
·        Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources.
·        In connection pooling, after a connection is created, it is placed in the pool and it is used over again so that a new connection does not have to be established.
·        If all the connections are being used, a new connection is made and is added to the pool.
·        Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database.
36) How to do database connection using JDBC thin driver ? 
·        Connection conn = DriverManager.getConnection
·        (“jdbc:oracle:thin:@//localhost:1521/orcl","scott", "tiger");
·        @//machineName:port/SID,  userid,  password --Oracle's JDBC 
·        Thin driver uses Java sockets to connect directly to Oracle.
·        It provides its own TCP/IP version of Oracle's SQL*Net protocol. 
·        Because it is 100% Java, this driver is platform independent and can also run from a Web Browser (applets).
·       Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. 
·       This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platformindependent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.
37) Compare PreparedStatement vs Statement. 
      If we need to execute a sql query repeatedly then the STATEMENT will parse every time the query before executing on the database. But PrepareStatement will parse only once and then will execute repeatedly on the database. 
38) What is Metadata and why should I use it? 
·        Database Metadata is an interface to get comprehensive information about the database as a whole.
DatabaseMetadata dmt= con.getMetaData();
39) What is RowSet? or What is the difference between RowSet and ResultSet? 
·        Result set is an object containing the results(rows) of executing a sql statement on a database.
·        A ResultSet maintains a connection to a database and because of that it can’t be serialized and also we cant pass the Resultset object from one class to other class across the network. --RowSet is a disconnected, serializable version of a JDBC ResultSet and also the RowSet extends the ResultSet interface so it has all the methods of ResultSet.
·        The RowSet can be serialized because it doesn’t have a connection to any database and also it can be sent from one class to another across the network.
·        More on RowSet:
·        A RowSet can be * connected * or *disconnected* 
·        A *disconnected* rowset gets a connection to a data source in order to fill itself with data or to propagate changes in data back to the data source, but most of the --time it does not have a connection open. While it is disconnected, it does not need a JDBC driver or the full JDBC API, so its footprint is very small.
·        Thus a rowset --is an ideal format for sending data over a network to a thin client.
·        A connected RowSet is like a wrapper around the ResultSet.
IMPLEMENTATION:
·        A CachedRowSet class—a disconnected rowset that caches its data in memory; not suitable for very large data sets, but an ideal way to provide thin Java clients, such as a Personal Digital Assistant (PDA) or Network Computer(NC), with tabular data .
·        A JDBCRowSet class—a connected rowset that serves mainly as a thin wrapper around a ResultSet object to make a JDBC driver look like a JavaBeans component
·        A WebRowSet class—a connected rowset that uses the HTTP protocol internally to talk to a Java servlet that provides data access; used to make it possible for thin web clients to retrieve and possibly update a set of rows.
40) Serialization? 
·        It is a process of storing object contents into a file.
·        The class whose objects are stored in the file should implement 'serialiazable' interface java.io --also called marker interface or tagged interface --static and transient variables cannot be written into a file. They are protected by the key words.
·        Implement serializable(Empty interface)
41) Transient variable?
·        Static and transient variables cannot be written into a file.They are protected by the key words.
·        Transient key word prevents objects form serialization
42) What do you understand by Synchronization?
·        It is the process of locking thread on the same object so that deadlocks can be avoided.
·        When already one thread in acting on a object preventing another thread from acting on the same object. 
43) User defined Exceptions?
·        Java cannot explain all the exceptions.
·        So user can write his own exceptions.
·        Class myException extends Exception
·        myException() {} 
·        myException(String str){
    super(str);
          }
44) What is the difference between the instanceof and getclass,  these two are same or not ? 
·        The instanceof operator tests whether its left-hand operand can be cast to the class named on its right and returns a boolean.
·        If the left operand is an object of a subclass of the named class, it still returns true, and if you write null instanceof Foo, you always get false.
·        I have never seen getclass, but the Object#getClass() method returns the Class object which that object was created from.
·        If you call it on any non-null reference type you get a Class object, but if you call it on a null reference you suffer a NullPointerException.
45) Explicit casting 
·        The casting done by a programmer is called explicit casting.
·        Explicit casting is compulsory while converting from a higher data type to a lower data type.
46) String and String Buffer? 
·        Objects are broadly divided into two types
           1)MUTABLE          
  2)IMMUTABLE
MUTABLE: These are those objects whose CONTENTS CAN be modified.
IMMUTABLE: these are those objects whose CONTENTS CAN-NOT be modified.STRING class objects are immutable. StringBuffer class objects are MUTABLE so they can be modified. There are methods in STRINGBUFFER which manipulate data which are not present in STRING(Character,Byte,Short,Integer,long etc).
47) What is multi-threading ?
·        Multiple threads acting on a object or objects or menthod's to increase the performance of the process. 
48) What is synchronization? 
·        It is a process of acquiring lock by a thread from multiple threads on a single object.
49) When you will synchronize a piece of your code? 
     When multiple threads are acting on it
50) What is daemon thread and which method is used to create the daemon thread? 
      A demon thread is a thread that executes constantly. Demon threads are service providers from other threads or objects. They generally provide a background process.
       -- t.setDeamon(true) is used to create a demon thread 
51) How can u make a piece of code write all the output messages to console and only errors to a given file?
·        import java.io.*;
·        class FileWrite
·        {
·        public static void main(String args[])
·        {   try{   // Create file
·        FileWriter fstream = new FileWriter("out.txt");
·        BufferedWriter out = new BufferedWriter(fstream);
·        out.write("Hello Java");  //Close the output stream
·        out.close();
·        }
·        catch (Exception e){//Catch exception if any
·        System.err.println("Error: " +e.getMessage());
·        }   }    }

1 comment:

  1. here are my list of differences:
    1) hashtable is synchronized while hashmap is not.
    2) hashmap is fast while hashtable is slow
    3) hashtable is old but hashmap is new
    4) hashtable supports enumeration while hashmap uses Iterator

    souce: difference between hashtable and hashmap in Java
    How HashMap works in Java

    ReplyDelete