Core Java important interview questions and answers

Core Java Important Interview Questions and Answers
  1. What is the difference between an executable file and a .class file?
    Answer: .exe file contains machine language instructions for the microprocessor and it is system dependent. .class file contains byte code instructions for the JVM and is system independent.
  2. Why is Java suitable for internet?
    Answer: 1)It is system independent.
    2) It eliminates a lot of security protocols for data on internet.
  3. Which part of jvm will allocate memory for a java program?
    Answer: Class loader subsystem of JVM will allocate the necessary memory needed by the java program.
  4. Which algorithm is used by garbage collector to remove the unused variables or objects from memory?
    Answer: It uses many algorithms but the most commonly used algorithm is mark and sweep.
  5. How can you call garbage collector?
    Answer: Garbage collector is automatically invoked when the program is being run. It can be also called by calling gc() method of Runtime class or System class in java.
  6. What is JIT compiler?
    Answer: It is the part of JVM which increases the speed of execution of a java program.
  7. What is the difference between #include and import statement?
    Answer: #include directive makes the compiler go to the C/C++ standard library and copy the code from the header files into the program. As a result the program size increases thus wasting memory and processors time.
    import statement  makes the jvm go to the java standard library, execute the code there and substitute the result into the program.
  8. What happens if String args[] is not written in main() method?
    Answer: The code will compile but jvm cannot run the code because it cannot recognize the main() method as the method from where  it should start execution of the java program.
  9. What is the difference between float and double?
    Answer: Float can represent up to 7 digits accurately after decimal point, whereas double can represent up to 15.
  10. What is unicode?
    Answer: unicode system is an encoding standard that provides a unique number for every character, no matter what the platform, program or language is. unicode uses 2 bytes to represent a single character.
  11. How are positive and negative numbers represented internally?
    Answer: Positive numbers are represented in binary using 1’s complement notation and negative numbers are represented by using 2’s complement notation.
  12. What is the difference between >> and >>>?
    Answer: Both are used to shift the bits towards right. The difference is that >> will protect the sign bit whereas the >>> operator will not protect the sign bit. It always fills the 0 in the sign bit.
  13. What is a collection?
    Answer: A collection represents a group of statements like interger values or objects.  Examples for collections are arrays and java.util classes (Stack, LinkedList,Vector, etc).
  14. What is the difference between return and System.exit(0)?
    Answer: return statement is used inside a method to come out of it. System.exit(0) is used in any method to come out of the program.
  15. What is the difference System.exit(0) and System.exit(1)?
    Answer: System.exit(0) terminates the program normally. Whereas System.exit(1) terminates the program because of some error encountered in the program.
  16. What is the difference between System.out and System.err?
    Answer: Both represent the monitor by default and hence can be used to send data or results to the monitor. But System.out is used to display normal messages and results whereas System.err is used to display error messages.
  17. On which memory, arrays are created?
    Answer: Arrays are created on dynamic memory by JVM. There is no question of static memory in java; every thing (variable, array, object etc) is created on dynamic memory only.
  18. Can you call the main() method of a class from another class?
    Answer: Yes and at the time of calling we should pass a string type array to it.
  19. What is Object reference?
    Answer: It is a unique hexadecimal number representing the memory address of the object. It is useful to access the members of the object.
  20. What is the difference between == and equals() while comparing strings? Which one is reliable?
    Answer: == operator compares the references of the string objects. It does not compare the contents of the objects. equals() method compares the contents. While comparing the strings, equals() method should be used as it yields the correct result.
  21. What is string constant pool?
    Answer: String constant pool is a separate block of memory where the string objects are held by JVM. If a string object is created directly, using assignment operator as String s1=”Hello”, then it is stored in string constant pool.
  22. Explain the difference between the following two statements:
    1) String s = “Hello”;
    2) String s = new String(“Hello”);
    Answer: In the first statement, assignment operator is used to assign the string literal to the String variable s. In this case, JVM first of all checks whether the same object is already available in the string constant pool. If it is already available then it creates another reference to it. If the same object is not available, then it creates another object with the content “Hello” and stores it into the string constant pool.
                   In the second statement, new operator is used to create the String object. In this case, JVM always creates a new object without looking in the string constant pool.
  23. What is the difference between StringBuffer and StringBuilder classes?
    Answer: StringBuffer class is synchronized and StringBuilder is not. When the programmer wants to use several threads, he should use StringBuffer as it gives reliable results. If only one thread is used, StringBuilder is preferred, as it improves execution time.
  24. What is the difference between a class and an object?
    Answer: A class is a model for creating objects and does not exist physically. An object is anything that exists physically. Both class and objects contain variables and methods.
  25. What is hash code?
    Answer: Hashcode is a unique identification number allotted to the objects by the JVM. This hash code number is also called reference number which is created based on the location of the object in memory and is unique for all objects, except for string objects.

    How can you find the hash code of an object?
    The hashcode() method of ‘Object’ class in java.lang package is useful to find the hash code of an object.
    The object reference (hashcode) internally represents heap memory where instance variables are stored.
  26. Can we declare a class as private?
    Answer: No, if we declare a class as private, then it is not available to java compiler and hence a compile time error occurs. But, inner classes can be declared as private.
  27. When is the constructor called, before or after creating the object?
    Answer: A constructor is called concurrently when the object creation is going on. JVM first allocates memory for the object and then executed the constructor to initialize variables. By the time object creation is completed, the constructor execution is also completed.
  28. What are instance methods?
    Answer: Methods which act on the instance variables of the class. To call the instance methods, we should use the form: objectname.methodname().
  29. It is not compulsory in java to catch the value returned by a method.
  30. What are static methods?
    Answer: Methods which do not act upon the instance variables of a class. Static methods are declared as static.
  31. What is the difference between instance variables and class variables (static variables)?
    Answer: An instance variable is a variable whose separate copy is available to each object. A class variable is a variable whose single copy in memory is shared by all objects.
    Instance variables are created in the objects on heap memory. Class variables are stored on method area.
  32. Why instance variables are not available to static methods?
    Answer: After executing static methods, JVM creates the objects. So non-static variables of the objects are not available to static methods.
  33. Is it possible to compile and run a java program without writing main() method?
    Answer: Yes, it is possible by using a static block in the java program.
  34. How objects are passed to methods in java?
    Answer: Primitive data types, objects even object references – everything is passed to methods using pass by value or call by value concept. This means their bit by bit copy is passed to the methods.
  35. Explain generics
    Answer: Generics enable types(classes and interfaces) to be parameters when defining classes, interfaces and methods. Generics allow you to abstract over types. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Generics eliminate type casting.
  36. Explain Enum
    Answer: An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. The names of an enum type's fields are in uppercase letters, because they are constants. Enum in Java provides type-safety.
  37. What are factory methods?
    Answer: A factory method is a method that creates and returns an object to the class to which it belongs. A single factory method replaces several constructors in the class by accepting different options from the user, while creating the object.
  38. In how many ways can you create an object in java?
    Answer: There are four ways of creating objects in java:
    1) Using new operator.
    Employee obj = new Employee();
    2) Using factory methods:
    NumberFormat obj = NumberFormat.getNumberInstance();
    Here, we are creating NumberFormat object using the factory method getNumberInstance();
    3) Using newInstance() method. Here we should follow two steps as:
    a) First store the class name Employee as a string into an object. For this purpose, factory method forName() of the class ‘Class’ will be useful.
    Class c = Class.forName(‘Employee’);
    We should note that there is a class with the name Class in java.lang package.
    b) Next, create another object to the class whose name is in the object c. For this purpose, we need newInstance() method of the class ‘Class’ as:
    Employee obj = (Employee)c.newInstance();
    4) By cloning an already available object, we can create another object.
    Employee obj1 = new Employee();
    Employee obj2 = (Employee)obj1.clone();
  39. What is object graph?
    Answer: It is a graph showing relationship between different objects in memory.
  40. What is anonymous inner class?
    Answer: It is an inner class whose name is not written in the outer class and for which only one object is created.
  41. What is inheritance?
    Answer: Deriving new classes from existing classes such that the new classes acquire all the features of existing classes is called inheritance.
  42. Why super class members are available to sub class?
    Answer: Because, the sub class object contains a copy of super class object.
  43. What is the advantage of Inheritance?
    Answer: In inheritance a programmer reuses the super class code without rewriting it, in creation of sub classes. So, developing the classes becomes very easy. Hence, the programmers productivity is increased.
  44. What is coercion?
    Answer: It is the automatic conversion between different data types done by the compiler.
  45. What is conversion?
    Answer: It is an explicit change in the data type specified by the cast operator.
  46. What is method overloading?
    Answer: Writing two or more methods in the same class in such a way that each method has same name but with different method signatures – is called method overloading.
  47. What is method overriding?
    Answer: Writing two or more methods in super and sub classes such that the methods have same name and same signature.
  48. What is the difference between method overloading and method overriding?
    Answer:
     
    Method Overloading Method Overriding
    Two or more methods with the same name but with different signatures. Two or more methods with the same name and same signatures.
    Method overloading is done in the same class. Method overriding is done in super and sub class.
    Return type can be same or different. Return types should also be same or overriding method can also return a subtype of the type returned by the overridden method. This is called a "covariant return type".
    JVM decides which method is called depending on the difference in the method signatures. JVM decides which method is called depending on the data type(class) of the object used to call the method.
    It is done when the programmer wants to extend the already available feature. It is done when the programmer wants to provide a different implementation(body) for the same feature.
    Overloading is code refinement. Same method is refined to perform a different task. Overriding is code replacement. The sub class method overrides (replaces) the super class method.
  49. Can you override private methods?
    Answer: No. Private methods are not available in the sub classes, so they cannot be overridden.
  50. Can we take private methods and final methods as same?
    Answer: Yes. The java compiler assigns the value for the private methods at the time of compilation. Also, private methods cannot be modified at the run time. This is the same case with final methods also. Neither the private methods nor the final methods can be overriden. So, private methods can be taken as final methods.
  51. What is final?
    Answer: It is used to declare constants as:
    final double PI = 3.14159;
    It is used to prevent inheritance, as:
    final class A //sub class to A cannot be created.
  52. What is the difference between dynamic polymorphism and static polymorphism?
    Dynamic polymorphism is the polymorphism exhibited at runtime. Here, java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at runtime. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism.
    Static polymorphism is the polymorphism exhibited at compile time. Here, java compiler knows which method is called. Method overloading and method overriding using static methods; method overriding using private or final methods are examples for static polymorphism.
  53. Which is the super class for all the classes including your classes also?
    Answer: Object class
    There is a class with the name ‘Object’ in java.lang package which is the super class of all classes in java. Every class in java is a direct or indirect sub class of the Object class.
  54. Can you write an interface without any methods?
    Answer: Yes
  55. What do you call the interface without any members?
    Answer: An interface without any methods is called marking interface or tagging interface. It marks the class objects for a special purpose. For example, Cloneable (java.lang) and Serializable (java.io) are two marking interfaces. Cloneable interface indicates that a particular class objects are cloneable.
  56. Can you declare a class as abstract and final also?
    Answer: No. abstract class needs sub classes. Final key word represents sub classes which cannot be created.
  57. What is an interface?
    Answer: It is a specification of method prototypes. All the methods of the interface are public and abstract.
  58. Why the methods of interface are public and abstract by default?
    Answer: Since they should be available to third party vendors to provide implementation. They are abstract because their implementation is left for third party vendors.
  59. Can you implement one interface from another?
    Answer: No, we can’t. Implementing an interface means writing body for the methods. This cannot be done again in an interface, since none of the methods of the interface can have body.
  60. Can you write a class within an interface?
    Answer: Yes, it is possible to write a class within an interface.
  61. What is the difference between an abstract class and an interface?
    Answer:
    Abstract class Interface
    It is written when there are some common features shared by all the objects. It is written when all the features are implemented differently in different objects.
    It contains some abstract methods and also some concrete methods. It contains only abstract methods.
    An abstract class can contain instance variables also. An interface cannot contain instance variables. It contains only constants.
    All the methods of the abstract class should be implemented in its subclass. All the abstract methods of the interface should be implemented in this implementation classes.
  62. How can you call the garbage collector?
    Answer: We can call garbage collector of JVM to delete any unused variables and unreferenced objects from memory using gc() method. This gc() method appears in both Runtime and System classes of java.lang package. For example:
    System.gc();
    Runtime.getRuntime.gc();
  63. What is CLASSPATH?
    Answer: The CLASSPATH is an environment variable that tells the java compiler where to look for class files to import. CLASSPATH is generally set to a directory or a JAR.
  64. What is the scope of default access specifier?
    Answer: Default members are available within the same package, but not outside of the package. So their scope is package scope.
  65. What happens if main() method is written without String args[]?
    Answer: The code compiles but JVM cannot run it, as it cannot see the main method with String args[].
  66. What are checked exceptions?
    Answer: The exceptions that are checked at compile time by the java compiler are called ‘checked exceptions’. The exceptions that are checked by the JVM are called ‘unchecked exceptions’.
  67. What is Throwable?
    Answer: Throwable is a class that represents all errors and exceptions which may occur in java.
  68. Which is the super class for all exceptions?
    Answer: Exception is the super class of all exceptions in java.
  69. What is the difference between an exception and an error?
    Answer: An exception is an error which can be handled. It means that when an exception happens, the programmer can do something to avoid any harm. But an error is an error which cannot be handled.
  70. What is the difference between throws and throw?
    Answer: throws clause is used when the programmer does not want to handle the exception and throw it out of a method. Throw clause is used when the programmer wants to throw an exception explicitly and wants to handle it using catch block. Hence, throws and throw are contradictory.
  71. Is it possible to re-throw the exception?
    Answer: Yes, we can re-throw an exception from catch block to another class where it can be handled.
  72. Why do we need wrapper classes?
    Answer: 1. They convert primitive data types into objects and this is needed on Internet to communicate between two applications.
    2. The classes in java.util package handle only objects and hence wrapper classes help in this case also.
  73. Which of the wrapper classes contains only one constructor? (Or) which of the wrapper classes does not contain a constructor with String as parameter?
    Answer: Character
  74. What is boxing?
    Answer: Converting a primitive data type into an object is called ‘boxing’.
  75. What is unboxing?
    Answer: Converting an object into its corresponding primitive data type is called unboxing.
  76. What happens if a string like “Hello” is passed to parseInt() method?
    Answer: Ideally, a string with an integer value should be passed to parseInt() method. So, on passing “Hello” an exception called ‘NumberFormatException’ occurs since the parseInt() method cannot convert the given string “Hello” into an integer value.
  77. What is a collection framework?
    Answer: A collection framework is a class library to handle groups of objects. Collection framework is implemented in java.util package.
  78. Does a collection object store copies of other objects or their references?
    Answer: A collection object stores references of other objects.
  79. Can you store a primitive data types into a collection?
    Answer: No, collections store only objects.
  80. For-each loop: for-each loop is like a for loop which repeatedly executes a group of statements for each element of collection.
    for(variable: collection-object){
    Statements;
    }
  81. What is the difference between Iterator and ListIterator?
    Answer: Both are useful to retrieve elements from a collection. Iterator can retrieve the elements only in forward direction. But ListIterator can retrieve the elements in forward and backward direction also. So ListIterator is preferred.
  82. What is the difference between Iterator and Enumeration?
    Answer: Both are useful to retrieve elements from a collection, but Iterator has an option to remove elements from the collection.
  83. HashSet class:It represents set of elements(objects). It does not guarantee the order of elements. Also it does not allow the duplicate elements to be stored.
    It has two constructors:
    HashSet();
    HashSet(int capacity);
    HashSet(int capacity, float loadFactor);
    Capacity: Represents how many elements can be stored in the HashSet initially.
    LoadFactor: Determines the point where the capacity of the HashSet would be increased internally. The default initial capacity is 16 and the default load factor is 0.75.
  84. What is auto boxing?
    Answer: Converting a primitive data type into an object form automatically is called ‘auto boxing’. Atuo boxing is done in generic types.
  85. ArrayList class:It is like an array which can grow in memory dynamically. ArrayList is not synchronized.
  86. Vector class: A vector also stores elements (objects) similar to ArrayList, but Vector is synchronized.
  87. What is the difference between ArrayList and Vector?
    Answer:
    ArrayList Vector
    ArrayList object is not synchronized by default. Vector object is synchronized by default.
    In case of a single thread, using ArrayList is faster than vector. In case of multiple threads, using Vector is advisable. With a single thread, Vector becomes slow.
    ArrayList increases its size every time by 50 percent (half). Vector increases its size every time by doubling it.
  88. Can you synchronize the ArrayList object?
    Answer: Yes, we can use synchronizedList() method to synchronize the ArrayList, as:
    Collections.synchronizedList(new ArrayList());
  89. HashMap class: HashMap is a collection that stores elements in the form of key-value pairs. If key is provided later, its corresponding value can be easily retrieved from the HashMap. Keys should be unique. This means we cannot use duplicate data for keys in the HashMap. HashMap is not synchronized.
    The default initial capacity of this HashMap will be taken as 16 and the load factor as 0.75. Load factor represents at what level the HashMap capacity should be doubled.
  90. What is the load factor of HashMap or Hashtable?
    Answer: 0.75
  91. Hashtable class: Hashtable is similar to HashMap which can store elements in the form of key-value pairs. But Hashtable is synchronized.
  92. What is the difference between HashMap and Hashtable?
    Answer:
    HashMap Hashtable
    HashMap object is not synchronized by default. Hashtable object is synchronized by default.
    HashMap is faster in case of single thread. It is advisable in case of multiple threads.
    HashMap allows null keys and null values to be stored. Hashtable does not allow null keys or values.
    Iterator in the HashMap is fail-fast. This means Iterator will produce exception if concurrent updates are made to the HashMap. Enumeration for the Hashtable is not fail-fast. Then means even if concurrent updations are done to Hashtable, there will not be any incorrect results produced by the Enumeration.
  93. What is the difference between a Set and a List?
    Answer:
    Set List
    A set represents a collection of elements. Order of the elements may change in the set. A list represents ordered collection of elements. List preserves the order of elements in which they are entered.
    Set will not allow duplicate values to be stored. List will allow duplicate values.
    Accessing elements by their index (position number) is not possible in case of sets. Accessing elements by index is possible in lists.
    Sets will not allow null elements. Lists will allow null elements to be stored.
  94. What is the difference between System.out and System.err?
    Answer: Both are used to display messages on the monitor. System.out is used to display normal messages as: System.out.println(“Hello”);
    System.err is used to display any error messages in the program as:
    System.err.println(“This is an error”);
  95. What is the advantage of stream concept?
    Answer: Streams are mainly useful to move data from one place to another place.
  96. What is the default buffer size used by any buffered class?
    Answer: 512 bytes
  97. What is serialization?
    Answer: Serialization is the process of storing object contents into a file. The class whose objects are stored in the file should implement ‘Serializable’ interface of java.io package.
  98. Which type of variables cannot be serialized?
    Answer: static and transient variables cannot be serialized.
    Once the objects re stored into a file, they can be later retrieved and used as and when needed. This is called de-serialization.
  99. What is deserialization?
    Answer: De-Serialization is a process of reading back the objects from a file.
  100. What is IP address?
    Answer: An IP address is a unique identification number allotted to every computer on a network or internet. IP address contains some bytes which identify the network and actual computer inside the network.
  101. What is DNS?
    Answer: Domain Naming Service is a service on Internet that maps the IP addresses with corresponding website names.
  102. What is a socket?
    Answer: A socket is a point of connection between a server and a client on a network.
  103. What is a port number?
    Answer: Port number is a 2 byte number which is used to identify a socket uniquely.
  104. Which thread always runs in a Java program by default?
    Answer: main thread
  105. Why threads are called light weight?
    Answer: Threads are light weight because they utilize minimum resources of the system. This means they take less than memory and less processor time.
  106. What is the difference between single tasking and multi tasking?
    Answer: Executing only one job at a time is called single tasking. Executing several jobs at a time is called multi tasking. In single tasking, the processor time is wasted, but in multi tasking, we can utilize the processor time in an optimum way.
  107. How can you stop a thread in java?
    Answer: First of all, we should create a boolean type variable which stores ‘false’. When the user wants to stop the thread, we should store ‘true’ into the variable. The status of the variable is checked in the run() method and if it is true, the thread executes ‘return’ statement and then stops.
  108. What is the difference between ‘extends Thread’ and ‘implements Runnable’? Which one is advantageous?
    Answer: extends Thread and implements Runnable – both are functionally same. But when we write extends Thread, there is no scope to extend class,as multiple inheritance is not supported in java.
  109. What is thread synchronization?
    Answer: When a thread is already acting on an object, preventing any other thread from acting on the same object is called ‘Thread Synchronization’. Or ‘Thread Safe’. The object on ehich the threads are synchronized is called ‘synchronized object’.
  110. Explain thread life cycle.
    Answer: The two diagrams below explain the life cycle of thread.
    New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable (Ready-to-run): After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Running: A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. Waiting/Blocking: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Dead: A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
  111. What is the difference between synchronized block and synchronized keyword?
    Answer: Synchronized block is useful to synchronize a block of statements. Synchronized keyword is useful to synchronize an entire method.
  112. What is thread deadlock?
    Answer: When a thread has locked an object and waiting for another object to be released by another thread and the other thread is also waiting for the first thread to release the first object, both the threads will continue waiting forever. This is called ‘Thread deadlock’.
  113. What is the difference between the sleep() and wait() methods?
    Answer: Both the sleep() and wait() methods are used to suspend a thread execution for a specified time. When slepp() is executed inside a synchronized block, the object is still under lock. When wait() method is executed, it breaks the synchronized block, so that the object lock is removed and it is available.
  114. What is the default priority of a thread?
    Answer: When a thread is created, by default its priority will be 5.
  115. What is a daemon thread?
    Answer: A daemon thread is a thread that executes continuously. Daemon threads are service providers for other threads or objects. It generally provides a background processing.
  116. What is JDBC?
    Answer: JDBC is an API that is useful to write java programs to connect to any database, retrieve the data from the database and utilize the data in a java program.
  117. What is the database driver?
    Answer: A database is a set of classes and interfaces, written according to JDBC API to communicate with a database.
  118. How can you register a driver?
    Answer: To register a database driver, we can follow one of the 4 options:
    - By creating an object to driver class.
    - By sending driver class object to DriverManager.registerDriver() method.
    - By sending the driver class name to class.forName() method.
    - By using System class getProperty() method.
  119. What is DSN?
    Answer: Data Source Name is a name given to the database to identify it in the java program. The DSN is linked with the actual location of the database.
  120. What is resultset?
    Answer: ResultSet is an object that contains the results (rows) fo executing a SQL statement on a database.
  121. Will the performance of a JDBC program depend on the driver?
    Answer: Yes, each driver offers a different performance.
  122. What is parsing?
    Answer: Parsing represents checking the syntax and grammar of a statement as a whole and also word by word.
  123. What is the differece between Statement and PreparedStatement?
    Answer: Statement parses a statement before its execution on the database. This parsing is done every time the statement is executed and hence it may take more time when the same statement gets executed repeatedly. PreparedStatement conducts parsing only once when the same statement is executed repeatedly and hence it gives better performance.
  124. What are stored procedures?
    Answer: A stored procedure represents a set of statements that is stored and executed at database server sending the results to the client.
    create or replace procedure myproc(no in int, isal out float) as
    salary float;
    begin
    select sal into salary from emptab where eno = no;
    isal := salary + 500;
    end;

    CallableStatement stmt = con.prepareCall(“{call myproc(?,?)}”);
    stmt.setInt(1,1004);
    stmt.registerOutParameter(2,Types.FLOAT);
    stmt.execute();
    float incsal = stmt.getFloat(2);
  125. What is the use of CallableStatement?
    Answer: CallableStatement is useful to call stored procedures and functionswhich run at a database server and get the results into the client.
  126. What is scrollable result set?
    Answer: It represents a resultset object where moving in forward and backward direction is possible. It also provides methods to update the rows in the resultset.