Skip to content
 

Imp Java Interview Questions and Answers

Java Interview Questions 1

 

Q: How can we explain the difference between a method and a constructor?

A: The difference is that the method is a normal member function in a class which can be called by the use of a dot operator and has a return module, void or not and has a name; the constructor instead is also a member unction but its role is to create objects in the class, does not return anything and does not have other name that the one of its class. This function is called with the use of the new operator.

 

Q: What does a static method mean?

A: Regardless of the number of instances a class may have there is only one method per class, not per object. Static methods can be used even if we don’t make class instances and they are final, only the objects type can be changed, these methods belong to classes and not objects. Until the original methods become final a static method from a subclass can be the shadow of a static method from a superclass. In a subclass, static methods can’t be changed into instance methods, so a nonstatic method can’t override a static one.

 

Q: What are the differences when we talk about Checked Exception and Unchecked Exception?

A: Exception itself can be a Checked Exception and also a subclass of it can be as well but not the class Runtime Exception and the subclasses that belong to it. But the Unchecked Exceptions can be either all the classes of the Runtime Exception either the Runtime Exception itself. Unchecked can be the class error too and the subclasses of it also. We can see examples for each type of Exception. If we have a Checked Exception there is this possibility it can be thrown: for instance IOException can be thrown by the java.io.FileStream’s read() method. When the Exception is Unchecked the programmer is not forced by the compiler to throw the exception or to catch it, the programmer cannot be aware even if the exception is thrown; for instance the StringIndexOutOfBoundsException can be thrown by the charAT() method. So as a conclusion there is no need for the Runtime exceptions to be caught, the Checked Exceptions have to be caught and the errors can’t be in most of the cases.

 

Q: How can inner classes be classified?

A: We can split the inner classes into four other classes: Member classes, Local classes, Nested top level classes and Anonymous classes.

The first type, the Member inner classes are similar in a way to the member variables and methods for example, they have restricted access in the member class. There is not much difference between public member classes and the Top nested ones. The difference between member and top nested level classes is the permission to a particular instance in the enclosing class that the member lasses are having.

The second type, the Local classes are also similar to their corresponding variables, the local variables, that belong to a particular block of code. It only has the influence in that block of code where they were declared and to expand that a public interface must be introduced. We can’t use the private, protected, static and public modifiers in the local classes because they don’t act exactly like members.

The third type, the Nested top level classes can be described like this: when we declare

A class inside another class and we put a static modifier then the class will be seen by the compiler exactly as like another top level class. If we have a class out of the declaring class, the nested class will be accessed with that class name and it will behave just like a package. By default the Top level inner classes can only access static variables.

The fourth, the Anonymous inner classes are an extension for the Local inner classes but they can’t have a constructor since they don’t own a name.

 

Q: What is the Externalizable interface actually doing?

A: The Externlizable interface can allow us to customize the process of serialization by the introduction of two methods: readExternal and writeExternal, they give us control in the serialization process.

 

Q: What is the role of the static fields in the process of serialization?

A: In three cases there is an exception to the general rule, meaning the serialization doesn’t work (read or write). In the first case the static fields are simply ignored as they don’t take part of a specific state, in the second case only when the base class is serializable then its fields can be handled and the third case refers to the transient fields.

 

Q: When do we really use the serialization process?

A: We have to use the serialization process when we send the objects on the network and when we have to save the current state of an object.

 

Q: Do we have to introduce any Serializable interface methods?

A: No, we don’t have to introduce any methods because the Serializable interface has to be actually empty.

 

Q: What really is the Serialization?

A: The mechanism that helps us save the current object state by converting the object to a byte stream is called Serialization.

 

Q: How do we make a custom process of Serialization and how can we control it?

A: To customize a Serialization process we should introduce an Externalizable interface that is containing the methods readExternal and writeExternal. After the introduction of the methods we must write the customization logic.

 

Q: Can an object be serialized to one file?

A: If we want an object to be serialized into a file we can introduce a Serializable interface into the class corresponding to the instances we want to serialize. These instances are to be passed then to the ObjectOutputStream of the fileoutputstream and the result is that we have a saved file of the object.

 

Q: What argument can we give to the String array in the main method?

A: Unlike the C language in Java the first element is the name of the program, the String array does not contain any element.

 

Q: What can happen in the case that we take out the static modifier from the main method’s signature?

A: In this case at the compilation of the program the following runtime error appears: “NOSuchMethodError”.

 

Q: What happens if we don’t give the method a String array argument?

A: The program will run but with an error like: “NoSuchMethodError”.

 

Q: What happens when we declare the main method as a private method?

A: The compiling will work but with an error message: “Main method not public”.

 

Q: What happens if we change the words from static public void into public static void?

A: No error message will appear, the program will run smooth.

Q: How do we define final?

A: The value of a final variable can’t be changed; it means it is in fact a constant. Also we will not be able to extend a final class or to subclass it. Also can’t override a final method if it has an inherited class.

 

Q: How can we demonstrate the when using only one line of code an array is empty and not null?

A: We can demonstrate that an array is empty by printing args.length, the result will be 0 (empty). In the case when it is null the compiler would show a NullPointerException when trying to execute the printing command args.lenght.

 

Q: When we have a main method in an application, is it possible that we also have multiple classes?

A: The answer is yes. When we mention a class at the start of the application the JVM will start searching for the Main method just in that class that we mentioned. So the Main method can have multiple classes with no problem at all.

 

Q: For being able to run Java applications what are the environment variables that must be set up?

A: There are two that must be set up: PATH and CLASSPATH.

Q: How will be the String array of the Main method when we give no arguments in the command line, null or empty?

A: It is not null for sure, so the only remaining answer is: empty.

 

Q: How does the Abstract class differ from the Interface class?

A: The interface class is limited to the declaration of instance methods and constants but the Abstract class has the instance methods with default behavior already implemented. So in this way we can say that the methods are abstract by default. The interface does not have implementation, but has public members and the abstract class has the private, protected and other flavors of the class members the methods are abstract.

 

Q: What are the uses of the thread?

A: We can introduce the thread with the aid of the Thread class or a runnable interface. Inheriting the thread from the Thread class has more advantages.

 

Q: How do we define synchronization related to multithreading?

A: The link between the synchronization and multithreading is that synchronization has the ability to manage multiple threads access to the shared resources. If there is no synchronization two different threads can modify or update the same variable and this can result in serious errors.

 

Q: What is and when is the garbage collector used?

A: The garbage collector identifies, collects and disables objects in Java that are no longer reachable by the program that needed the object. Then the resources can be reclaimed and reused by the program.

 

Q: How do we define Map and HashMap?

A: The Map is an interface while the HashhMap is a class. The Map is actually implemented by the HashMap.

 

Q: How do we explain why HashMap is not the same with HashTable?

A: In fact HashMap is almost like the Hashtable, the only difference is thet the Hashmap permits null values and Hashtable does not. Anyway it doesn’t offer any assurance that we will have a constant value for the map order. The only one that is synchronized is the Hashtable.

 

Q: What is the difference between pass by value and pass by reference?

A: Pass by value defines passing a copy of the value and pass by reference is by definition the passing of the address.

Q: How do we define an Iterator?

A: The Iterator is an interface like java.util.iterator that permits us to traverse through a collection of objects (a collection class) and se each object, take a snapshot of the collection how it is at that time. There is no need to modify the collection when using an integrator for any purpose.

 

Q: Can we say what difference does the Vector make versus the Arraylist?

A: The difference is that the Arraylist is not synchronized, while the Vector is.

 

Q: Is there a difference when we talk about Swing and AWT?

A: The Swings are faster components than AWT since they have a light weight (versus heavy weight –the AWT).

 

Q: How do we define an abstract class?

A: An abstract class is a class that can’t be instantiated, it can contain static data and can be a template. Also to become useful to us it has to be subclassed or extended. An abstract method determines that its class is by default abstract, but we can declare an abstract class even if it doesn’t contain any abstract methods.

 

Q: What does public, protected, private and default means as single modifiers or in combination and what effects do the package relationships have on the items of these modifiers?

A: The public class can be seen in every package, the private methods or even the private variables are available just for the instances of the class that declared them, the protected feature can be used by all the classes from the shared package and by the subclasses the own it and even the subclasses from another package, different from the others, but from the same feature. And the final: the default does not include private, public or protected, it is available to all classes within a package.

 

Q: Can we find multiple Main methods in a class?

A: We can’t because, once we define a Main method, when trying to define another, the compiler will warn us that we already did that.

 

Q: What does Overriding mean?

A: Overriding means defining a method in a class under the same name, argument and return as the one from the superclass, but the new definition of the method will be from the class and not the superclass. So the overrideing of methods is more public than private.

 

Q: Do we have to load the java.lang all the time?

A: There is no need to do that because the JVM imports it by default.

 

Q: Can we load the same package multiple times on the same runtime?

A: Yes there is no issue in doing this, the JVM and the compiler they both agrees with this practice. Regardless of how many times we import the same class or package the JVM will import it only once.

 

Q: Does the compiler check the imports for validity, for instance if the code contains java.lang.ABCD will the compiler check it?

A: Yes, the compiler is checking the imports for validity. For this particular example with the java.lang.ABCD import, the compiler will show an error message like it can’t resolve symbol.

 

Q: If the reference of an object is declared as the variable of an instance, which one is the initial value of the reference?

A: The initial value will be null until we can define it.

 

Q: Does private or protected apply to a top level class?

A: The answer will be no, because  a top level class can only be public or it can have no modifier at all, and in this last case the top level class have default access. The error message that will appear when a top level class is declared as private will be: “modifier private will not be allowed here”. So the same is with protected, it just can’t be.

 

Q: If we load a package does this mean that the subpackages will also load?

A: For example if we load com.MyTest.* is it true that com.Mytest.UnitTests.* will be loaded too? No, in order to achieve this the subpackages must be loaded separately.

 

Q: Is declaring and defining a variable the same thing?

A: It is not the same thing, but defining includes declaration. Declaration means mentioning the type and the name of a variable, without initializing it. Instead defining means the same but with initialization. As an example we have String s; as a declaration and String s = new String (“abcd”) as a definition.

 

Q: In which way are the objects passed by in Java, reference or value?

A: In Java we find only objects passed by value, the reference itself will be passed by value.

 

Q: Are the primitive data types passed by value in Java or by reference?

A: The same as in the case of objects they are will be passed by value.

 

Q: What is happening with the references of an object that are within that object when it is serialized?

A: The serialization is trying to determine if the references of that object are or not serializable. The other objects that are included in the original object are also serialized if that single object is serialized.

 

Q: Should we be careful when serializing an object?

A: When serializing an object we must assure that the objects included in the original object are serializable as well, if this is not the case, an error message will appear: NotSerializableException.

 

Q: What is the meaning of wrapper classes?

A: For example Integer, Double or Character are wrapper classes, meaning classes that are specialized for each primitive data type.

 

Q: What is the purpose of the wrapper classes?

A: Because the majority of the collection classes have objects in store and instead of primitive data types and because the wrapper classes have many utility methods, this is why the wrapper classes are so useful. We can make instances of these classes and put them for storage in the collection classes and use them as a collection or as method parameters.

 

Q: Is there any construct in Java to see what size an object has?

A: In Java we cannot determine exactly or directly the size of an object, in other words the sizeof operator does not exist.

 

Q: Can we find out how much time is necessary for the execution of a method in a simple way with no profiling tool?

A: Yes there is a way, we can do this if, before calling the method and right after the method returns we will look at the system time. We must make the calculations and we will have the execution time this way. Of course we won’t take an execution that can last a millisecond, but a bigger one. A code for reading the time will be:

long start = System.currentTimeMills();

method();

long end = System.currentTimeMills();

 

System.out.println(“Time taken for execution is” +(end-start));

 

Q: How will we define checked exceptions?

A: The exceptions that the compiler makes you catch are the checked exceptions, for example IOException.

 

Q: What is the way through which an exception penetrates the code?

A: For the purpose of finding a match the unhandled exceptions goes right up the stack of methods. When a wrapped code from a try block which is traced by catch blocks throws an exception, the catch block that matches is searched. If the search returns positive results that block will be called. If the search turns negative the exception goes up in the stack of methods until it finds the caller method, this continues until the catch block that corresponds to the right exception is found, in case of negative search result the program finishes.

 

Q: What is the meaning of runtime exceptions?

A: The runtime exceptions appear when the user inputs wrong data or if there is no logic in the code. The compiler doesn’t verify them when the program is compiled.

 

Q: How can we make custom exceptions?

A: We can do this by extending the class Exception.

 

Q: How can we describe error against exception?

A: An example of error can be the OutOfMemory error, an example of exception is FileNotFoundException. The difference between these two is that the error s can’t be repaired at the time of compiling, but the exceptions are just a result of wrong input information, so the error can’t be recovered but the exceptions can be corrected by introducing new data that is valid.

 

Q: What can we do if we desire that an object from our class to become an exception?

A: The only thing to do is to make our class an extension of the Exception class or other more exact type of exception.

 

Q: What do we do when we want that an instance from our class to be an exception object?

A: Actually there is nothing we can do, the reason is that Java can’t permit us to use multiple inheritance and doesn’t even give us exception interfaces.

 

Q: How can we handle the exceptions, which ways are used?

A: We can handle exceptions in two cases: First: catching the exceptions by wrapping the code in try block then in a catch block, and second we can give the handling to the method caller by making a list of the exceptions.

 

Q: Usually a catch block follows a try block, is this a requirement?

A: Not every try block gets followed by a catch block, a try block can be followed also by a finally block. Anyhow the exceptions that may appear have to be declared in the method’s throws clause.

 

Q: What is the use of Observable and Observer?

A: The objects that see Observable objects, they implement an Observer interface. The method update is called by Observable objects when they are updated to announce every observer of the changes that took place.

Q: How can we differentiate these two ways of exception handling: try catch block and stating which exceptions will be found in the throws clause?

A: In the first way we the programmers are facing the exception, and if e can have the responsibility to face with the method’s exceptions it’s easy, but if we can’t the this first way is not good for us. When we speak about the second way in which the method caller is forced by us for catching the exceptions that the method throws we can say it’s the way of the creators of libraries, who list in the throws clause all the exceptions for us to catch them.

 

Q: Does the finally block still work if at the end of the try block we write return?

A: Of course the block will execute, with the condition that there will be no exception, and after that the return will execute.

 

Q: What if we write at the end of a try block the command System.exit(0)?

A: In this approach the finally block won’t work because System.exit(0) puts us outside the program.

 

Q: Why is synchronization so important and what does it really mean?

A: Synchronization is the ability of controlling multiple thread permissions to common resources. Synchronization is important because it cancels the possibility that a thread has to modify shared objects in the same time when another thread updates or uses the same object’s value. In fact it gives us the possibility to avoid errors that are really serious.

 

Q: What is the reason for finalization?

A: Through finalization we give an unreachable object the possibility the make the cleanup process prior to the garbage collection process.

 

Q: What can be the difference between synchronized statements and synchronized methods?

A: The synchronized methods can be used for permission control of an object. After obtaining the lock for that object’s class or method then the thread will execute a synchronized method. The same the synchronized statements executes after the lock from the class or objects have acquired a lock so they are not different, but similar.

 

Q: Is it possible for applets to communicate between them?

A: Yes but under certain conditions. If the applets work in the same virtual machine they can communicate between them, the same if they have the same class they can talk through shared static variables, anyhow the main thing is to transfer the information through the static variable.

The  method getApplets() of java.applet.AppleContext. can be used to take references to the other applets by a single applet. This is done because it makes possible the communication between applets by the use of its public members.

We can have applets communicating to a server in the Internet in different virtual machines, these can deposit the data needed to be serialized.

 

Q: What does static variable mean and what is a non-static variable?

A: They are different because the static variable becomes associated with the entire class while non-static variable come together with particular instances of a class, with unique values in each instance.

 

Q: How do we define a Locale class?

A: The purpose of the Locale class is to modify the output of a program according to political, geographic and cultural conditions.

 

Q: How do we use super() and this() related to constructors?

A: Both are use to invoke constructors but the difference is the super is used for a superclass constructor and this() is used for a constructor from the same class.

Q: In what way are the do and while statements different?

A: The do statement verifies if , at the end of a loop the occurrence of the next iteration is happening and at least one time, the loop body is executed. The while statement does not verify at the loop end, but at the beginning, but the purpose is the same: for catching the next iteration.

 

Q: Does the use of garbage collector tell us for sure that the memory of the program won’t run out?

A: No, this is not the case because a program can deplete the resources of the memory before the garbage collector does its job or some objects that the program has created can be out of the garbage collectors duty, so there is no guarantee that the program will not deplete its resources when using the garbage collector.

 

Q: Can we say how Java manages the integer underflows and overflows?

A: yes, java does this by using the low order bytes because they match the size the operation requires for the type.

 

Q: What can be the default state of a thread and when is it created or started?

A: After the thread’s creation it is started and after the we can say it’s in the ready state.

 

Q: What does time slicing and preemptive scheduling mean?

A: They are ways to manage the tasks, the time slicing refers to a task that , before reentering the ready tasks pool it can execute in a slice of time that is predefined while the preemptive scheduling refers to the highest priority task that can work until other higher priority tasks are born or until the state of the task become waiting or dead. So based on different factors the scheduler manages the task executions.

 

Q: What is the meaning of a daemon thread and what method can we use for daemon thread creation?

A: The daemon thread is a thread that does the garbage collection in the java runtime system, the method for creating a daemon thread is setDaemon. The daemon thread has a low priority and works in the background.

 

Q: Through what phases do we pas while making a JDBC connection?

A: The phases necessary for a JDBC connection are: 1. The database driver must be registered using: Class.forName(” the driver class of the particulat database”)2. A database must be created using: Connection con = DriverManager.getConnection (url, username, password); 3. A query has to be created using: Statement stmt = Connection.Statement(”select * from TABLE NAME”); 4. The query must be executed: stmt.executeUpdate();

 

Q: Is there a declaration or catch rule for the declaration of methods?

A: Yes. When in a method’s body a checked exception appears, the method has to declare or catch the exception.

 

Q:  When handling exceptions, how can a try statement know what catch clause to use?

A: If the exception will be thrown in the try statement’s body, the order in which the catch clauses of the try statement show up determines how they are verified. So the first that can manage the exceptions will run, the rest of the catch clauses will not.

 

Q: Can we explain what the term “static” means in relation with method or field?

A: The term “static” wants to say that methods or variables can have only one instance per class, so they refer to the class not to the instance. When a static variable of a specific object is changed, it will affect all the instances of the class. We can reference the static methods not only with the name of a specific object in a class but also with that class name. For example in java.lang.System class have as static fields method’s like System.out.println().

 

Q: Is it true that .java files can have multiple java classes?

A: Yes, it is true, usually public classes.

 

Q: How can we make an unreachable object reachable?

A: It is possible to do this when the object is making processes that make it visible to reachable objects and the finalize() method is used for calling.

 

Q: Are there any alternatives to inheritance?

A: Yes, for example we have delegation which means sending messages forward to an instance while an instance variable is used as an inclusion of another class instance. Delegation can be a better choice than inheritance because it is safer, we know the class(it is better that a new class), we can send only the messages that we want and use only the methods that are really good, there is a disadvantage, we have to type more code and this alternative is not so versatile.

 

Q: Is there a method that has to be used by all thread?

A: Yes. The run() method has to be used by all tasks, no matter if the tasks belong th the Thread class or they use the Runnable Interface.

 

Q: What does Externalizable mean?

A: The extension of Serializable is Externalizable. It is an interface that sends compressed data to Streams using these methods: writeExternal (ObjectOutput out) and readExternal (ObjectImput in).

 

Q: What kind of modifiers are permitted for a method in an Interface?

A: The permitted modifiers are the abstract ones and the public ones.

 

Q: Is it true that an empty .java file is valid as a source file?

A: Yes, it is a one hundred percent valid.

 

Q:  How can we define the scopes of the Java variables?

A: Every variable is declared in a different context so the scope depends on the context, there are three scopes and only one can be active at a certain time:

1. Static- the static variables have no connection with any object instance, they stay in JVM as long as the class that was loaded when they were initialized stays loaded, these variables are class level.

2. Instance- these variables are object level and are initialized when the objects are created and stay visible as long as the objects are.

3. Local-they are method level variables and are visible in the time the method is executed.

Q: Can we describe next as a keyword?

A: Definitely not, next is not a keyword in Java.

 

Q: Is it true that String is a primitive data type?

A: No, in Java, in the java.lang the String class is defined, and Strings are just instances of this class.

 

Q: Is it true that main can be a keyword in Java?

A: No, main can’t be.

 

Q: What initial values do the local variables receive?

A: Even if they are object references or primitives, there is no initialization by value to the local variables and if we don’t give them a specific initialization the code will not run  and the compiler will say that there is no initialized local variable.

 

Q: What can be the default value of the object reference that is by definition an instance variable?

A: In Java all the references of an object are null by default and to be able to use them in a way or another and to not receive NullPointerExceptions where they are used  they must be sent to a valid object.

 

Q: Can we count the objects that the next part of code is creating?

MyClass c1, c2, c3;

C1 = new MyClass ();

C3 = newMyclass ();

A: The number of created objects is 2 and they are c1 and c3, c2 isn’t initialized, it is a reference and it’s only declared.

 

Q: Can delete be a Java keyword?

A: No, delete cannot be a keyword because in Java there are no explicit destructors like in C++.

 

Q: What can happens when an instance variable from any primitive type is not initialized in Java?

A: Java makes the initialization for instance variable by the default value according to the primitive type, for example if an int initialization is made to 0 then a Boolean initialization will be to false.

 

Q: Can exit be a java keyword?

A: No, if we want specifically to exit the program the exit method must be used in System object.

 

Q: Is it possible to declare a main method final?

A: Yes, it is possible, a main method will be declared final when it is public static.

 

Q: What output will come from this statement: System.out.println (“1” +3); ?

A: The output is a print of 13.

 

Q: Can we define a public class MyClass in the YourClass.java source file?

A: The answer will be no because the source file name has to be the sa name of the public class followed by the .java extension.

 

Q: If an array is defined as an instance variable what initial elements will it have?

A: The elements will have the default values just as the values of the primitive types if the array contains primitive types. For example the initial value of the elements of a Boolean array will be false while the one of an int array will be 0. In the case where the array contains any type of reference the element initialization will be null.

 

 


java interview questions total in pdf wt is output of system out println(1 3);

Leave a Reply