Top 50 Java Interview Questions and Answers
Are you preparing for a Java interview but feeling unsure about your knowledge and skills? SevenMentor’s Top 50 Java Interview Questions and Answers are designed to help you master the most common and challenging Java interview questions, so you can feel confident and prepared for your next interview. Java course in Pune covers a wide range of topics, including Java fundamentals, object-oriented programming, data structures, algorithms, and more. We also provide in-depth explanations and examples of the most common Java interview questions and answers, so you can understand the concepts and principles behind them. Investing your time in Java interview questions today can help you feel more confident and prepared for your next interview, and ultimately increase your chances of success.Java is a popular, high-level programming language that was first released in 1995 by Sun Microsystems. It is a versatile language that can be used to develop a wide range of applications, from desktop software to web applications to mobile apps. Java is also used extensively in the development of enterprise applications, such as banking systems and e-commerce websites. in summary, Java is its platform independence. This means that Java code can run on any platform that supports the Java Virtual Machine (JVM), including Windows, Mac, and Linux. Java also provides a secure and robust platform for developing applications, with features such as automatic memory management, garbage collection, and exception handling.
Top 50 Java Interview Questions and Answers
Q 1. Why is Java not completely object-oriented?
Java is not fully object-oriented because it supports primitive data types of c like int, short, byte, long, float, double, etc., which are not objects.
Q 2. What is Inheritance?
Inheritance is the process of deriving/accessing the properties(means instance variables and instance methods) of one class into another class is called inheritance.
There are 4 types of inheritance we can achieve in Java for example.
- Single level
- Multiple inheritances (not achieved directly by the class, needs to implement the interface)
Q 3. Why is multiple inheritances not achievable in Java through classes?
Multiple inheritance means one child class can extend multiple parent classes and in Java, a class cannot extend more than one class. Therefore following is invalid
Class Student extends College, Department
Here, if class College and Department both have the same method like display then the compiler will not be able to decide which display() method the Student class should inherit. Hence, to prevent ambiguity we can not achieve multiple inheritance in Java
Q 4. What is super in Java?
Super is a keyword in Java used with variables, methods as well as constructors. By using the super keyword we can access the variables, methods, and constructors of the superclass in the subclass.
Q 5. What is an interface?
The interface is the blueprint of classes and it has only an abstract method
The interface is similar to an abstract class but the only difference is that in abstraction or abstract classes, we have both abstract method and non-abstract means concrete(the method which has body part ) but in the interface, we have only abstract method. The interface is implemented in Java for the purpose of achieving abstraction and multiple inheritances in Java
Interface cannot be instantiated means we cannot create the object of the interface but we can create a reference variable of the interface
Q 6. What is the difference between the following keywords final, final, and finalize?
Final is the keyword that can be used with variables, methods, and classes. basically, finally is an access modifier that is used to apply restrictions on a class, method, or variable. Finally is the block which we can define in case of Exception Handling to execute the important code whether the exception occurs or not so as a result we can put important code finalize is the garbage collector method in Java which is used to perform clean-up processing just before an object is garbage collected.
Q 7. Explain the difference between “method overloading” and “method overriding”?
When you have multiple methods having the same name but with different parameter lists, and all methods are defined inside the same class the case is called Overloading. On the other hand, Overriding is nothing but when we have multiple methods with the same name and with the same parameters, but that method is defined in a parent and child class respectively.
For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!
Q 8. What is the difference between “==” and “equals( )” in the context of Strings in Java?
equals is the inbuilt method of the String class and it is always used to check the contents of both strings whereas the comparator operator(==) always checks the references of both strings. equals() method returns the value as true if the contents of both strings are the same. The comparator operator returns true when both references or strings point to the same object in memory.
Q 9. Explain the Strings interned method in Java.
Intern method used to create an exact copy of the heap string object in the String Constant Pool. It can be used to return a string from memory if it is created by a new keyword.
Q 10. Can we execute the code of Java if we write static public void main?
Yes, we can change the sequence of modifiers in Java
Q 11. What is a Marker Interface?
The interface which does NOT have any single abstract method, that interface is called the Marker interface. The marker interface is also called an empty/blank interface.
Q12.What is Object Cloning?
Object cloning is the process through which we can create an exact copy of an object. The clone() method of the Object class is used to perform object cloning. A cloneable interface must be implemented by the class whose object clone we want to create.If we don’t implement a Cloneable interface with class then clone() method generates a CloneNotSupportedException.
Q 13. Define Wrapper Classes in Java.
The wrapper class in Java is used to convert primitive types/values into an object and an object into a primitive. Before Java 5 this process has been performed manually but Since J2SE 5.0, both autoboxing and auto-unboxing features convert primitives into objects and objects into primitives automatically.
Q 14. Can we implement the concept of pointers in Java?
Java doesn’t support pointers but has references instead. These are essentially the same thing, with the key difference being that you’re dealing with pointers to objects and not pointers to memory locations means we can’t do things like incrementing a pointer and getting a reference to something else. Pointer arithmetic isn’t supported.
Q 15. Explain Java String Pool.
Java String pool is a Separate area in the heap memory where the value of the String or string object which is defined in the program gets stored by the JVM.So, when we use the first way(by string literal) to create a string object, the String is stored inside SCP by the JVM. Each time you create a string literal, the JVM checks the “string constant pool” first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn’t present in the pool, a new string object is created and placed in the pool. So, no memory gets wasted for repeated content of object so to avoid memory wastage and increase reusability of object, java has the concept of String literal.SCP is used for reusability purposes in Java.
Q 16. What is the need for exception handling in the program?
when an exception occurs in our program, then given that of that exception the rest of the code will not get executed even if it is correct and will not get proper output hence to maintain the proper execution of the code, we need to handle the exception
Q 17. What are inner classes and anonymous inner classes?
There are two different types of nested classes
1. Static nested classes
2. Non-static nested classes
The non-static nested classes are also called inner classes.
The inner class which does not have any name is called the anonymous inner class.
Q 18. What is the Java Collection Framework?
A Collection means a group of objects that we can represent in single units, i.e., a group. The Collection in Java is a framework that provides an architecture to store and manipulate a group of objects by using inbuilt interfaces, classes, and methods. Whereas Java Collections can be used to perform an operation on data such as searching, sorting, insertion, manipulation, and deletion.
The Java Collection framework consists of several interfaces (Set, List, Map) and classes (ArrayList, Vector, LinkedList, HashSet, LinkedHashSet, TreeSet).
Q 19. What do you understand about Thread Priority?
Thread Priority is the number that a thread gets from there parent thread at the time of thread creation and according to that priority, the number of threads gets executed. And that priority number lies between 1 to 10. The other thread which is having higher priority gets a higher chance to get selected for execution.
Q 20. Explain the feature of Java’s ‘write once and run anywhere’ nature.
When the user compiles a .java file which contains source code, that .java file goes to the Java Compiler there it compiles a java program (.java file) and converts it into class files (.class) that contain bytecodes, which is the intermediate language between source code and machine code. These bytecodes are platform-independent, which means they can run on multiple different platforms. JVMs can execute the same Java bytecode that is called ‘write once and run anywhere’. So, this means Java can be developed on any device, compiled into a standard bytecode, and be expected to run on any device equipped with a JVM (Java virtual machine).
Q 21. Is the blank .java file name a valid source file name?
Yes, it’s working because the Java compiler doesn’t consider it as a saved file name or not except our class has public specified we can save any name or empty but the class must not be public, which means that it must be the default.
Q 22. What will be the initial value of an object reference which is defined as an instance variable?
The object references mean reference variables are all initialized to null in Java.
Q 23. What is the constructor?
Constructor is a special type of member function of a class that is used to initialize the newly created object. But the constructor name should be the same as the class name and the constructor has no return type, not even void
Types of Constructors: i.e.
- default constructor
The constructor which does NOT have any argument/parameters called as default constructor
//body of cons
- parameterized constructor
The constructor which does have at least one or more arguments is called a parameterized constructor
//body of cons
Q 24. What is the purpose of a default constructor?
To initialize the values of instance variables with their default initial values, we can use the default constructor.
For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!
Q 25. Is the constructor inherited?
Constructors are not members of the class, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass by using the super keyword.
Q 26. Can you make a constructor final?
Basically, inheritance when we extend a class the child class inherits all the members of the parent class except the constructors.
In other words, constructors cannot be inherited in Java, therefore, you cannot override constructors.
So, writing the final before constructors make no sense and has no use. Therefore, java does not allow the final keyword before a constructor.
If you try, to make a constructor final a compile-time error will be generated saying “Modifier final is not allowed here”.
Q 27. Can we overload the constructors?
Yes, we can overload the constructor in Java similarly to a method overloading. When one class consists of multiple constructors having the same name but with different parameters or arguments then it is called constructor overloading
Q 28. What is the static variable?
The static var is used to refer to the common property of all objects means we can declare as static only to those instance variables which are common to all objects for example, let’s consider Student class so in Student class name, roll no can be changed according to the student but collage name can be common. Similarly, company names are common for all employee objects.
Q 29. What are the different rules that we need to follow when we create static methods in Java?
different rules are given these points:
- this and super cannot be used in static areas.
- In the static method, we cannot use non-static members
- The static method can access only static-type instance variables.
- Objects are not required to call static methods.
- a static method cannot be overridden in a subclass
Q 30. Why is the main method static?
The main() method is the starting point from where our program execution gets started. and the non-static method should always be called by the object of the class. If the main() is declared without a static keyword means if it is nonstatic then every time JVM needs to create an object of that class first otherwise JVM will not be able to call the main() method and load the class in memory that’s why main should always be static
Q 31. Can we overload the static methods?
Yes, we can overload a static method with the same name but with a different parameter list.
Q 32. What is the static block?
The block is started from the “static keyword” which is called static block, and it is used to initialize static variables of the class.
Q 33. Do we execute a program without writing the main() method?
Before Java 7 version we can execute the program without main() by using a static block, but from Java 7 onwards it is mandatory to have main() method in each and every program.
Q.34 What if the static modifier is removed from the signature of the main method?
If we do not declare the main method as static, another program will compile successfully but when we execute it, a “NoSuchMethodError” error will be thrown.
Q 35. What are the differences between this and the super keyword?
The current object of the class is represented by this keyword. Whereas The current object of the parent class is represented by the super keyword. Another key point is We can use it to access only the current class data members and member functions. On the other hand, We can super to access the data members and member functions of the super means parent class.
Q 36.Can you use this() and super() both in a constructor?
No. this() will call another constructor in the same class whereas super() will call a superclass constructor. If there is no super() in a constructor the compiler will add one implicitly.
Thus if both were allowed then there will be two super() in one constructor so you could end up calling the super constructor twice.
Q 37. Can we perform method overloading by changing the return type in Java?
NO…In java, method overloading is not possible by changing the return type of the method only because of ambiguity.
static int add(int a,int b)
static double add(int a,int b)
public static void main(String args)
System.out.println(Demo.add(11,11)); //ambiguity, here I want to call the method whose return type is double, but how could will compiler understand that i want to call the method having double return type because both methods having integer type of parameters.
Q 38 Can we overload the methods by making them static?
Q 39 Can we declare an interface as final?
No, we can not declare the interface as final. Interface in Java is similar to a class but it contains only abstract methods and fields, which are final and static. Since all the methods are abstract; therefore, we cannot instantiate the interface. To use it, we need to implement the interface using a class and provide a body to all the abstract methods in it. Also If we make an interface final we will not be able to implement its methods.
Q 40. What is the difference between the final method and the abstract method?
Uses the abstract keyword to declare the abstract method. On the other hand, Uses the final keyword to declare the final method. This helps to achieve abstraction. Whereas, This, by all means, helps to restrict other classes from accessing its properties and methods. Abstract class methods functionality can be altered in a subclass. Final class methods should be used as it is by other classes
Q 41 Is it possible to instantiate the abstract class?
No, because it consists of abstract methods which are incomplete methods, so in that class that class is also an incomplete class.
Q42. What are the differences between abstract class and interface?
Q 43 How to make a read-only class in Java?
If we make a class read-only, then we can’t modify the properties or data members’ value of the class. If we make a class read-only, then we can only read the properties or data members’ values of the class. The read-only class will contain only getter methods which return the value of the private properties to the main() function. The read-only class can contain setter methods if we want to modify the value of the private properties after reading because there is our choice to keep the setter method in the class but based on the concepts we should not contain them.
Q 44. Why has the String class been made immutable in Java?
Java uses the concept of string literal to store string objects and when we create an object using the string literal method that object is created inside SCP(String Constant Pool area) String constant pool is a separate memory area in heap memory. while storing these literals/objects inside SCP Jvm first checks whether the string object content which we define in the program is already present in the SCP area or not. If that object is already present in the SCP then no new object will be created and JVM simply returns a reference of that original object else it creates the new object and assigns a reference variable to that obj. Again when a new string literal object is created by the programmer again JVM Checks that this string object’s content is already there or not if it is present then it returns the ref of the second object into the first object and so on. This way JVM creates only one object and assigns the ref of the other entire object to the same object which it creates first. But if we try to make any change to one of the reference variables then that change may affect all the other object/reference var. So to avoid this java makes strings as immutable objects.
Q 45. Does the constructor return any value?
The constructor does not have any return type hence, it does not return any value explicitly. But internally the constructor returns the object of the class.
Q 46. Why do we need to serialize an object? OR what is the need for serialization?
Because objects can contain different types of data so we can’t write an object directly into a file. so we need to convert or to performs serialization(object-to-byte stream conversion) on that object
Q 47. What is Type casting in Java?
Casting is nothing but the conversion of one datatype to another datatype
Type casting is assigning a value of one datatype to another datatype
There are 2 types of Casting :
1. Upcasting/widening casting
Upcasting means conversion of smaller data type to larger data type also known as widening(extend). It performs automatically by Java compiler
2. Downcasting/narrowing casting
Downcasting means the conversion of a larger datatype to a smaller data type also known as narrowing(short). It performs manually by using the cast operator
Q48. When do we use Treeset over HashSet?
TreeSet is preferred for the Fast insertion and retrieval of elements. And for sorting elements.
For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!
Q 49. Define Generics in Java.
Generics s used to achieve datatype safety in the programming and it is also used to apply restrictions on different type of data to get inserted into the collection. Generic is a parametric type that can be passed as a parameter to the class, method, and interface and it is enclosed in <> brackets. and in these brackets, we need to pass the class name as a parameter always.
Q 50. What is the Sortedmap interface?
Sortedmap extends the Map interface.SortedMAp is an interface that sorts the entries of the map in ascending order. TreeMAp is an implementation class for the SortedMap interface
Note: Do watch our latest video: Click Here
Call the Trainer and Book your free demo class for Java now!!!
© Copyright 2020 | SevenMentor Pvt Ltd.