Java Interview Questions and Answers

1) What if the main method is declared as private? Ans: The program compiles properly but at runtime, it will give “Main method not public.” message.
2) What if the static modifier is removed from the signature of the main method? Ans: Program compiles. But at runtime throws an error “NoSuchMethodError“.
3) What if I write static public void instead of public static void? Ans: Program compiles and runs properly.
4) What if I do not provide the String array as the argument to the method? Ans: Program compiles but throws a runtime error “NoSuchMethodError”.
5) What is the first argument of the String array in the main method? Ans: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.
6) If I do not provide any arguments on the command line, then the String array of Main method will be empty of null? Ans: It is empty. But not null.
7) How can one prove that the array is not null but empty? Ans: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
8) What environment variables do I need to set on my machine in order to be able to run Java programs? Ans: CLASSPATH and PATH are the two variables.
9) Can an application have multiple classes having the main method? Ans: JVM will look for the Main method only in the class whose name you have mentioned. Hence there is no conflict amongst the multiple classes having the main method.
10) Can I have multiple main methods in the same class? Ans: No the program fails to compile. The compiler says that the main method is already defined in the class.
11) Do I need to import java.lang package any time? Why? Ans: No. It is by default loaded internally by the JVM.
12) Can I import same package/class twice? Will the JVM load the package twice at runtime? Ans: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
13) What are Checked and UnChecked Exception? Ans: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream’s read() method• Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn’t force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String’s charAt() method• Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
14) What is Overriding? Ans: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.
15) What are different types of inner classes? Ans: Nested top-level classes, Member classes, Local classes, Anonymous classes Nested top-level classes – If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. ex, outer.inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety. Member classes – Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class. Local classes – Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface. Because local classes are not members, the modifiers public, protected, private, and static are not usable. Anonymous classes – Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.
16) Connecting to a Database and Strings Handling Ans: Constructing a String If you are constructing a string with several appends, it may be more efficient to construct it using a StringBuffer and then convert it to an immutable String object. StringBuffer buf = new StringBuffer(“Initial Text”); // Modify int index = 1; buf.insert(index, “abc”); buf.append(“def”); // Convert to string String s = buf.toString(); Getting a Substring from a String int start = 1; int end = 4; String substr = “aString”.substring(start, end); // Str
17) What is a transient variable? Ans: A transient variable is a variable that may not be serialized. If you don’t want some field not to be serialized, you can mark that field transient or static.
18) What is the difference between Serializalble and Externalizable interface? Ans: When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject()two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class’s serialization process.
19) How many methods in the Externalizable interface? Ans: There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().
20) How many methods in the Serializable interface? Ans: There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.
21) How to make a class or a bean serializable? Ans: By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class’s inheritance hierarchy implements Serializable or Externalizable, that class is serializable.
22) What is the serialization? Ans: The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage.
23) What are synchronized methods and synchronized statements? Ans: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
24) What is synchronization and why is it important? Ans: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often causes dirty data and leads to significant errors.
25) What is the purpose of finalization? Ans: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
26)  What classes of exceptions may be caught by a catch clause? Ans: A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
27) What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? Ans: The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
28) What happens when a thread cannot acquire a lock on an object? Ans: If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.
29) What restrictions are placed on method overriding? Ans: Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.
30)  What restrictions are placed on method overloading? Ans: Two methods may not have the same name and argument list but different return types.
31) How does multithreading take place on a computer with a single CPU? Ans: The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
32) How is it possible for two String objects with identical values not to be equal under the == operator? Ans: The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.
33) How are this() and super() used with constructors? Ans: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
34) What class allows you to read objects directly from a stream? Ans: The ObjectInputStream class supports the reading of objects from input streams.
35) What is the ResourceBundle class? Ans: The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.
36) What interface must an object implement before it can be written to a stream as an object? Ans: An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
37)  What is Serialization and deserialization? Ans: Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
38) What are the Object and Class classes used for? Ans: The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.
39)  Can you write Java code for declaration of multiple inheritance in Java ? Ans: Class C extends A implements B { }
40)  What do you mean by multiple inheritance in C++ ? Ans: Multiple inheritance is a feature in C++ by which one class can be of different types. Say class teachingAssistant is inherited from two classes say teacher and Student.
41) Write the Java code to declare any constant (say gravitational constant) and to get its value. Ans: Class ABC { static final float GRAVITATIONAL_CONSTANT = 9.8; public void getConstant() { system.out.println(“Gravitational_Constant: ” + GRAVITATIONAL_CONSTANT); } }
42) What are the disadvantages of using threads? Ans: DeadLock. Given two tables Student(SID, Name, Course) and Level(SID, level) write the SQL statement to get the name and SID of the student who are taking course = 3 and at freshman level. SELECT Student.name, Student.SID FROM Student, Level WHERE Student.SID = Level.SID AND Level.Level = “freshman” AND Student.Course = 3;
43) What do you mean by virtual methods? Ans: Virtual methods are used to use the polymorhism feature in C++. Say class A is inherited from class B. If we declare say fuction f() as virtual in class B and override the same function in class A then at runtime appropriate method of the class will be called depending upon the type of the object.
44) What do you mean by static methods? Ans: By using the static method there is no need creating an object of that class to use that method. We can directly call that method on that class. For example, say class A has static function f(), then we can call f() function as A.f(). There is no need of creating an object of class A.
45) What do mean by polymorphism, inheritance, encapsulation? Ans:  Polymorhism: is a feature of OOPl that at run time depending upon the type of object the appropriate method is called. Inheritance: is a feature of OOPL that represents the “is a” relationship between different objects(classes). Say in real life a manager is a employee. So in OOPL manger class is inherited from the employee class. Encapsulation: is a feature of OOPL that is used to hide the information.
46) What are the advantages of OOPL? Ans: Object oriented programming languages directly represent the real life objects. The features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful.
47) How many methods do u implement if implement the Serializable Interface? Ans: The Serializable interface is just a “marker” interface, with no methods of its own to implement.
48)  Are there any other ‘marker’ interfaces? Ans: java.rmi.Remote java.util.EventListener
49)  What is the difference between instanceof and isInstance? Ans: Instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() determines if the specified object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is nonnull and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.
50)  why do you create interfaces, and when MUST you use one? Ans: You would create interfaces when you have two or more functionalities talking to each other. Doing it this way help you in creating a protocol between the parties involved.
51)  What’s the difference between the == operator and the equals() method? What test does Object.equals() use, and why? Ans: The == operator would be used, in an object sense, to see if the two objects were actually the same object. This operator looks at the actually memory address to see if it actually the same object. The equals() method is used to compare the values of the object respectively. This is used in a higher level to see if the object values are equal. Of course the the equals() method would be overloaded in a meaningful way for whatever object that you were working with.
52) Discuss the differences between creating a new class, extending a class and implementing an interface; and when each would be appropriate. Ans:
  • Creating a new class is simply creating a class with no extensions and no implementations. The signature is as follows
public class MyClass() { }
  • Extending a class is when you want to use the functionality of another class or classes. The extended class inherits all of the functionality of the previous class.
An example of this when you create your own applet class and extend from java.applet.Applet. This gives you all of the functionality of the java.applet.Applet class. The signature would look like this public class MyClass extends MyBaseClass { }
  • Implementing an interface simply forces you to use the methods of the interface implemented. This gives you two advantages. This forces you to follow a standard(forces
you to use certain methods) and in doing so gives you a channel for polymorphism. This isn’t the only way you can do polymorphism but this is one of the ways. public class Fish implements Animal { } Given a text file, input.txt, provide the statement required to open this file with the appropriate I/O stream to be able to read and process this file. Name four methods every Java class will have. public String toString(); public Object clone(); public boolean equals(); public int hashCode();
53) What does the “abstract” keyword mean in front of a method? A class? Ans: Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it, it is called abstract method.Abstract method has no body. It has only arguments and return type. Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract.
54) Does Java have destructors? Ans: No garbage collector does the job working in the background
55) Are constructors inherited? Can a subclass call the parent’s class constructor? When? Ans: You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it’s superclasses. One of the main reasons is because you probably don’t want to overide the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language.
Mahesh J

Mahesh J

Author

Hello all! I’m a nature’s child, who loves the wild, bringing technical knowledge to you restyled.