370 Java Interview Questions – Crack your next Java interview and grab a dream job

TechVidvan is committed to make you a successful Java developer. After the detailed Java tutorials, practicals, and projects, we have come up with interesting Java interview questions and answers.

In this series, we will provide 370 Java interview questions and answers in 3 parts:

  1. Java Interview questions and answers for freshers
  2. Java Interview questions and answers for intermediates
  3. Java Interview questions and answers for experienced

java interview questions and answers for freshers

Java Interview Questions and Answers

Java has been ranked top programming languages according to the TIOBE Index.

In this article, we will discuss Java interview questions and answers for freshers. The reason we are sharing these interview questions is that you can revise all your fundamental concepts. The interviewer will surely check your Java fundamentals.

Java Interview Questions for Freshers

Q.1. What are the main features of Java?

Answer. Java programming language is the most popular and widely used language. It is due to the most remarkable features that it comes with. These features are also called the buzzwords of Java. Some of these features are:

1. Java is simple to learn and understand- Java is very easy to learn, understand, and implement. It is simple because it avoids the use of complex features of C and C++ like explicit pointers, operator overloading, manual garbage collection, storage classes, etc.

2. Java is a platform-independent language- This feature is one of the most remarkable features of Java that makes it so popular. The compiled Java code is platform-independent and it can be run on any operating system.

3. Java is an object-oriented language- Java supports all the concepts of Object-Oriented Programming and everything is treated as an object. The term object-oriented means that we organize our software or the application as a combination of different objects and these objects contain both data and methods. Java supports all the OOPS features like Class, Encapsulation, Abstraction, Inheritance, Polymorphism.

4. Java is a secure language- Java provides security as it enables tamper-free and virus free systems. Java is best known for this feature. The other reasons for Java being a secure language are:

  • Java does not support explicit pointer
  • All the Java programs run inside a virtual machine sandbox.
  • There is a Bytecode verifier that checks the code fragments for illegal code.

5. Java is a multithreaded language- Java also supports the feature of multithreading. Multithreading is a process of running multiple threads simultaneously. This feature helps developers to build interactive applications. The main advantage of multithreading is that it does not occupy memory for each thread rather there is a common/shared memory area.

6. Java is distributed- Java is a distributed language as it enables users to create distributed applications. RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used to develop distributed applications in Java.

7. Java is dynamic- Java is a dynamic language and supports the dynamic loading of classes. The classes can be loaded dynamically on demand. Java also supports dynamic compilation and automatic garbage collection(memory management). Therefore, Java is a dynamic language.

Q.2. Is Java a platform-independent language? If yes, Why?

Answer. Yes, Java is a platform-independent language. If one compiles a Java program on a machine then this compiled code can be executed on any machine in the world, irrespective of the underlying Operating system of the machine.

Java achieves the platform independence feature with the use of Byte code. Byte code is the intermediate code generated by the compiler which is basically platform-independent and can be run on any machine. The JVM(Java Virtual Machine) translates the bytecode into the machine-dependent code so that it can be executed on any Operating system. For example, we can write Java code on the Windows platform and can run the generated bytecode on Linux or any other supported platform. These can be achieved by the platform-independent feature of Java.

Q.3. What is a class in Java?

Answer. A class is a template or a blueprint that allows us to create objects from it. A class is basically a collection of data members and member functions that are common to its objects. For example, consider a class Polygon. This class has properties like color, sides, length, breadth, etc. The methods can be draw(), getArea(), getPerimeter(), etc.

Q.4. What is javac?

Answer. javac is a Java compiler that compiles the Java source code into the bytecode. It basically converts the .java files into .class files. These .class files are the bytecode which is platform-independent. Then JVM executes the bytecode to run the program. While compiling the code, we write the javac command and write the java file name. For example:

javac MyProgram.java

Q.5. What is method overloading in Java?

Answer. Method Overloading is a concept in which a class can have more than one method with the same name but with a different list of arguments. The overloaded method can contain a different number or type of arguments but the name of the methods should be the same. For example, a method add(int, int) with two parameters is different from the method add(int, int, int). We can overload a method using three different ways:

  1. Number of arguments
    add(double,double)
    add(double, double, double)
  2. Datatype of parameters
    add(int,double)
    add(float,int)
  3. Sequence of parameters
    add(float, int)
    add(int, float)

Method overloading can not be achieved by changing the return type of methods. Method overloading is an example of static polymorphism or compile-time polymorphism in Java.

Q.5. What is Method Overriding in Java?

Answer. This is a popular Java interview question. Method Overriding is a feature in which the child class overrides the method of the superclass with a different implementation. To override a method the signature of the method in the child class must be the same as that of the method in the superclass that has to be overridden. Method Overriding can only be achieved in different classes and only with the help of Inheritance. Method Overriding is an example of dynamic or runtime polymorphism.

Q.6. Does Java support Operator Overloading?

Answer. No, there is no support for operator overloading in Java. Unlike C++, Java does not support the feature of operator overloading in which one operator can be overloaded. But internally, Java overloads operators, for example, String concatenation is done by overloading the ‘+’ operator in Java.

Q.7. What is Encapsulation Java?

Answer. Encapsulation is one of the Object-Oriented features that refer to wrapping up or binding of data members and functions into a single unit called class. The main idea of this concept is to hide the implementation details from the users. We can achieve the encapsulation by making the data members private and only the same class members can access these private members. Another way to achieve encapsulation is to use getter and setter methods.

Q.8. What is Inheritance in Java?

Answer. This is an important Java interview question of oops. Inheritance is another important feature of Java in which a child class inherits all the properties and functionalities from the parent class using the ‘extends’ keyword. Using Inheritance, we can achieve reusability of the code in our Java application because the same things need not be written every time they are needed, they just need to be extended whenever required.

Java supports single, multilevel, hierarchical inheritance with the use of classes, and the multiple inheritances in Java is achieved through interfaces, not the classes.

Q.9. Does Java support Multiple Inheritance?

Answer. Multiple Inheritance is an Inheritance in which a Java class can inherit more than classes at the same time. Java does not support multiple inheritances with the classes but we can achieve it by using multiple interfaces. Java does not allow Multiple Inheritance because it causes ambiguity.

Q.10. What is an abstract class in Java?

Answer. An abstract class is a special class in Java that contains abstract methods(methods without implementation) as well as concrete methods(methods with implementation). We declare an abstract class using the abstract keyword. An abstract class can not be instantiated; we can not create objects from abstract class in Java. We can achieve partial to complete abstraction using abstract class. Let’s see the syntax of declaring an abstract class:

abstract class MyClass {
  abstract void myMethod(); //abstract method
  public void display() //concrete method
  {
    //method body  
  }
}

Q.11. What is an interface in Java?

Answer. An interface in Java is like the normal class in Java that contains the data members and methods, but unlike classes, the interface must contain only and only abstract methods in it. The abstract methods are the methods without method body or implementation. Interfaces are used to achieve full abstraction in Java. Interfaces are declared using the interface keyword. A class can implement interfaces using implements keyword and can implement all the methods of the interface.

Declaration of an interface:

interface MyInterface {
  //data members
  //abstract methods
}

Q.12. State the difference between an abstract class and the interface?

  1. The main difference between abstract class and the interface is that an abstract class may have abstract as well as non-abstract or concrete methods but the interface must have only abstract methods in it.
  2. Another difference between both of them is that abstract classes can have static methods in it but an interface does not have static methods.
  3. An abstract class is declared with an abstract keyword and we declare the interface with an interface keyword.
  4. A class in Java can implement multiple interfaces but can extend only one abstract class.
  5. An abstract class can provide partial to full abstraction but with interfaces, we get full abstraction.

Q.13. What is ‘this’ keyword?

Answer. A ‘this’ keyword is a reserved word in Java which is a kind of reference variable and used to refer to the current object of the class. Its use is to refer to the instance variable of the current class and to invoke the current class constructor. We can pass this keyword as an argument while calling a method. We can also pass it as an argument in the constructor call. We cannot assign null values to this keyword.

Q.14. What do you mean by abstraction in Java?

Answer. Abstraction is an object-oriented concept by virtue of which we can display only essential details to the users and hiding the unnecessary details from them. For example, if we want to switch on a fan we just need to press the switch we do not require to know about the internal working of the switch.

In Java, we can achieve or implement abstraction in Java using abstract classes or interfaces. We can achieve 100% abstraction with interfaces and 0 to 100% abstraction with the abstract classes.

Q.15. What is a static variable in Java?

Answer. A static variable or class level variables are variables that are used to refer to the common properties of the object. For example, the company name for the employees of the company will be the same for all. The static variables are declared using the ‘static’ keyword.

The static variables get the memory area only for one time in the class area when the class gets loaded. The static variable makes the Java program memory efficient by saving memory. The life of the static variable is the entire execution of the program.

Java Basic Interview Questions

Now, let’s discuss more basic Java interview questions, which will help you in showcasing your rock-solid fundamentals and cracking the interview.

Q.16. What is a static method?

Answer. A static method is a method that we can directly call using the class rather than objects. The static methods belong to the class rather than instances or objects. We can call static methods without creating objects of the class. The static methods are used to access static variables or fields.
The use of a static method in Java is to provide class level access to a method where the method should be callable without creating any instance of the class. We declare static methods using the static keyword. We cannot override the static methods but we can overload them.

Declaring and calling the static method:

public class MyClass {
  public static myMethod() //defining static method
  {
    //method body
  }
  public static void main(String args[]) {
    MyClass.myMethod(); //calling static method directy using the cass
  }
}

Q.17. Explain the super keyword with its use.

Answer. A super keyword is a reference word in Java that is used to refer to the objects of the immediate parent class or the superclass.

  • The use of the super keyword is to access the data members of the parent class when the child class and the parent class both contain a member with the same name. Then if we want to access the parent class data member then we use the super keyword to access it.
  • Another use of a super keyword is to access the method of the parent class when the child class overrides that method.
  • Another use of a super keyword to invoke the constructor of the parent class.

Example:

super.variableName;
super.methodname();

Q.18. What is the use of the final keyword in Java?

Answer. A final keyword in Java is a reserved wood used for a special purpose. The final keyword is used with variables, methods, and classes in Java. We will discuss each of them:

Final variable: When we declare a variable using the final keyword, then this variable acts like a constant. Once we define the value of the final variable then we cannot change its value; it becomes fixed.

Final method: When a method is declared with the final keyword, then we can not override it in the child class. Any other method of the child class cannot override the final methods.

Final class: A class when declared with the final keyword, then it cannot be extended or inherited by the child classes. The final classes are useful when we do not want a class to be used by any other class or when an application requires some security.

Q.19. What are Polymorphism and its types in Java?

Answer. Polymorphism is an Object-Oriented concept that enables an object to take many forms. When the same method behaves in different forms in the same class on the basis of the parameters passed to it, then we call it Polymorphism in Java. The word Polymorphism can be divided into two words: poly-means and morph-means forms.

Java provides two types of Polymorphism:

  1. Compile-time or static polymorphism
  2. Runtime or dynamic polymorphism

Q.20. Can you overload a main() method in Java?

Answer. Method Overloading is a feature in which a class can have the same method with different parameters list. And yes, it is possible to overload a main() method like other methods in Java, but cannot override it. When we overload the main() method, the JVM still calls the original main() method during the execution of the program.

Example:

public static void main(int args)
public static void main(char args)
public static void main(Integer[] args)
public static void main(String[] args

Q.21. What are the differences between static and non-static methods?

Answer. Non-static methods are the normal method that can access any static variables and static methods. Static methods are declared with a static keyword and can only access static data members of the main class or another class but are unable to access non-static methods and variables.
The second difference is that we can call a static method without creating an object of the class but we cannot call non-static members directly through class, we can only call by creating an object of the class.

Q.22. What is a constructor in Java?

Answer. A constructor in Java is a block of code that is used to initialize a newly created object. It is a special method that we do not call using an object, but it is automatically called when we instantiate an instance of the class. That is, when we use the new keyword to instantiate a class then the constructor gets called.

Constructors resemble methods in java but the difference is that they cannot be declared as abstract, final, static, or synchronized in Java. We can also not inherit or extend the constructors. Also, they do not return anything, not even void. One important thing to note is that the constructor must always have the same name as that of a class.

There are two types of Java constructors:

  1. Default Constructor or no-argument constructor
  2. Parameterized constructor or argument constructor

Q.23. Can you declare constructors with a final keyword?

Answer. Though constructors resemble methods in Java, there are some restrictions. The constructors cannot be declared final in Java.

Q.24. What is a static block in Java?

Answer. A block is a sequence of statements written in curly braces. A block declared with a static keyword is the static block in Java. The use of static block os to initialize the static variables. There can be multiple static blocks in a class. The static blocks are loaded into the memory when a class gets initialized. They execute only once. They are also called static initialization blocks.
Their syntax is:

static
{
  //statement/s
}

Q.25. Explain-public static void main(String args[]) in Java?

Answer. This statement is declaring a main() method of a Java class. Let’s discuss each of its keywords:

  • public-This is one of the access modifiers that means that the method is accessible anywhere by any class.
  • static- static keyword tells that we can access the main() method without creating the object of the class.
  • void- The void keyword tells that the main() method returns nothing.
  • main- This is the name of the method.
  • String args[]- args[] is the name of the String array. It contains command-line arguments in it that the users can pass while executing the program.

Q.27. What are packages in Java and what are the advantages of them?

Answer. A package in Java is an organized collection of related classes, interfaces, and sub-packages. We can think of a package as a folder that contains files. We write the package name in the starting of the code with the package keyword and when we want to use any class or interface of the package in another class or interface then we use it using the import keyword of Java.

There are two kinds of packages in Java:

  1. Built-in packages-provided by the Java API
  2. User-Defined/custom packages-created by users.

Advantages of using packages are:

  • They prevent naming conflicts.
  • They make searching or locating classes and interfaces easier.
  • They provide controlled access

Q.28. What are access modifiers in Java?

Answer. Access Modifier in Java is used to restrict the scope of variable, class, method, constructor, or an interface in Java. There are four types of access modifiers in Java:
public, private, protected, and default.

public: We use this access specifier using the public keyword in Java. The public specifier has the widest scope among all the access modifiers in Java. The members that are declared with the public access specifiers are accessible from anywhere in the class even outside the class. We can access them within the package and outside the package.

private:  We use this access specifier using the private keyword in Java. The private specifier has the most restricted scope among all the access modifiers in Java. The private data members can only be accessed from within the same class. We cannot access them outside the class, not even in the same package.

protected:  We use this access specifier using the protected keyword in Java. Its access is restricted within the classes of the same packages and the child classes of the outside packages. If we do not create a child class, then we cannot access the protected members from the outside package.

default: If we do not write any access modifier while declaring members then it is considered to be the default access modifier. The access of the default members is only within the package. We cannot access them from the outside package.

Q.29. What is an object in Java? How can you create an object in Java?

Answer. An object is a real-world entity that has characteristics and behavior. It is the most basic unit of Object-oriented programming. It has some state, behavior, and identity. An object in Java is an instance of a class that contains methods and properties in it. We can only make the data users with the use of objects.

We can create an object using the new keyword in Java like this:

ClassName objectName = new ClassName();

Q.30. What is a break statement?

Answer. A break statement is a statement that we use in the loops to terminate a loop and the control goes automatically to the immediate next statement following the loop. We can use the break statement in loops and switch statements in Java. It basically breaks the current flow of the program in some particular conditions.

Q.31. What is a continue statement?

Answer. A continue statement is a statement used with the loops in Java. Whenever this continue keyword is encountered then the control immediately jumps to the beginning of the loop without executing any statements after the continue statement. It basically stops the current iteration and moves to the next iteration.

Q.32. What is constructor chaining in Java?

Answer. Constructor Chaining in Java is the process of calling one constructor from another constructor with respect to the current object. The main aim of constructor chaining is to pass parameters using a bunch of different constructors, but the initialization takes place from a single place.

Constructor Chaining process can be performed in two ways:

  • Using this keyword to call constructors in the same class.
  • Using the super keyword to call the constructors from the base class.

Java Interview Questions and Answers

We hope you are enjoying the Java interview questions and answers. Now, we are going to focus on:

  • Java Interview questions on String
  • Java Interview questions on OOPS
  • Java Interview questions on Multithreading
  • Java Interview questions on Collections

Q.33. Tell about the types of Inheritance in Java?

Answer. Inheritance is the process of acquiring properties from the parent class. There are 5 types of Inheritances in Java which are:

1. Single Inheritance- When one child class inherits from a single base class, then it is single inheritance.
2. Hierarchical Inheritance- When more than one child classes inherit from a single parent class, then it is called the Hierarchical Inheritance.
3. Multilevel inheritance- When there is child class inheriting from a parent class and that child class then becomes a parent class for another class, then this is said to be multilevel Inheritance.
4. Multiple Inheritance- Java does not support Multiple Inheritances through the class due to the ambiguity problem caused by it. Therefore java uses Interfaces to support Multiple Inheritance. In this, one interface can inherit more than one parent interface.
5. Hybrid Inheritance- Hybrid Inheritance is a combination of different Inheritances.

Q.34. Name some Java IDEs.

Answer. A Java Integrated Development Environment is an application that allows developers to easily write as well as debug programs in Java. An IDE is basically a collection of various programming tools that are accessible via a single interface. It also has several helpful features, such as code completion and syntax highlighting. Java IDE(Integrated Development Environment) provides a Coding and Development Environment in Java.

Some of Java IDEs are:

  • NetBeans
  • Eclipse
  • Intellij
  • Android Studio
  • Enide Studio 2014
  • BlueJ
  • jEdit
  • jGRASP
  • jSource
  • jDeveloper
  • DrJava

Q.35. What do you mean by local variable and instance variable in Java?

Answer. Local Variables are the variables that are declared inside a method body or a block or a constructor. Local variables are accessible only inside the blocking which they are declared. We can declare them at the start of a java program, within the main method inside the classes, methods, or constructors.

Instance variables or class variables are the variables declared inside the class and outside the function or constructor. These variables are created at the time of object creation and are accessible to all the methods, blocks, or the constructors of the class.

Q.36. What do you mean by Exception?

Answer. An Exception is defined as an abnormal condition that occurs during the execution of the program. Exceptions can arise due to wrong inputs given by the user or if there is a wrong logic present in the program.

For example, if a user tries to divide a number by zero in his code, then the program compiles successfully but there is an arithmetic exception when he executes the program. There are two types of Exceptions in Java which are- Checked Exceptions and Unchecked Exceptions.

Q.37. Differentiate between Checked and Unchecked Exceptions.

Answer. Checked Exceptions: Checked Exceptions are the exceptions checked during the compilation of the program. If the method is throwing a checked exception then it should provide some way to handle that exception using a try-catch block or using throws keyword, otherwise, the program gives an error. Some Checked Exceptions in Java are:

  • FileNotFoundException
  • SQLException
  • IOException
  • ClassNotFoundException

Unchecked Exceptions: Unchecked Exceptions are Exceptions that are checked during the runtime of the program. If there is an exception in a program and even there is no code to handle it, then the compiler will not throw any error. They are thrown at the execution of the program. Some of the Unchecked Exceptions in Java re:

  • Arithmetic Exception
  • NullPointerException
  • ArrayIndexOutOfBoundsExcpetion
  • NumberFormatException
  • IllegalArgumentException

Q.38. Differentiate between the throw and the throws keyword.

Answer. Both throw and throws keywords are used in Exception handling in Java. The differences between both of them are:

1. The throw keyword is used inside the method body to throw an exception, while the throws keyword is present in the method signature to declare the exceptions that may arise in the method statements.
2. The throw keyword throws an exception in an explicit manner while the throws keyword declares an exception and works similar to the try-catch block.
3. The throw keyword is present before the instance of Exception class and the throws keyword is present after the Exception class names.
4. Examples:
throw new ArithmeticException(“Arithmetic”);
throws ArithmeticException;

Q.39. What is Exception Handling Java? What are some different ways to handle an exception?

Answer. Exception handling in Java ensures that the flow of the program does not break when an exception occurs. Exception handling in Java provides several ways from which we can prevent the occurrence of exceptions in our Java program. We can handle exceptions in Java using: try and catch block, finally keyword, throw and throws clauses, and custom exceptions.

Q.40. How does Java achieve high performance?

Answer. Java provides high performance by the use of JIT compiler- Just In Time compiler, that helps the compiler to compile the code on demand. The compilation will occur according to the demand; only that block will be compiled which is being called. This feature makes java deliver high performance. Another reason is the Automatic Garbage Collection in Java that also helps Java enable high performance.

Q.41. What is the use of abstract methods?

Answer. An abstract method is a method having no method body. It is declared but contains no implementation. The use of abstract methods is when we need a class to contain a particular method but want that its actual implementation occurs in its child class, then we can declare this method in the parent class as abstract. This abstract method can be used by several classes to define their own implementation of the method.

Q.42. Define JVM.

Answer. Java Virtual Machine is a virtual machine in Java that enables a computer to execute the Java code. JVM acts like a run-time engine for Java that calls the main method present in the Java program. JVM is the specification implemented in the computer system. JVM compiles the Java code and converts them to a Bytecode which is machine-independent and close to the native code.

Q.43. Differentiate between JVM, JDK, and JRE.

Answer.

  • JDK stands for Java Development Kit, while JRE stands for Java Runtime Environment, while the full form of JVM is Java Virtual Machine.
  • JVM is an environment to execute or run Java bytecode on different platforms, whereas JDK is a software development kit and JRE is a software bundle that allows Java programs to run.
  • JVM is platform-independent, but both JDK and JRE are platform dependent.
  • JDK contains tools for developing and debugging Java applications whereas JRE contains class libraries and other tools and files, whereas JVM does not contain software development tools.
  • JDK comes with the installer, on the other hand, JRE only contains the environment to execute source code whereas
  • JVM is bundled in both JDK and JRE.

Q.44. What is a NullPointerException in Java?

Answer. NullPointerException is a Runtime or Unchecked Exception in Java and it occurs when an application or a program attempts to use an object reference that has a null value. It is a situation when a programmer tries to access or modify an object that has not been initialized yet and points to nothing. It means that the object reference variable is not pointing to any value and refers to ‘null’ or nothing.

Some situations of getting NullPointerException include:

  • When we call an instance method on the object that refers to null.
  • When we try to access or modify an instance field of the object that refers to null.
  • When the reference type is an array type and we are taking the length of a null reference.
  • When the reference type is an array type and we try to access or modify the slots of a null reference.
  • If the reference type is a subtype of Throwable and we attempt to throw a null reference.

Example:

Object obj = null;
obj.toString();  // This statement will throw a NullPointerException

Q.45. What is a wrapper class in Java?

Answer. A wrapper class is a predefined class in Java that wraps the primitive data types values in the form of objects. When we create the object of a wrapper class, it stores a field and we can store primitive data types in this field. We can wrap a primitive value into an object of the wrapper class.

There are 8 wrapper classes corresponding to each primitive data type in Java. They are:

Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

All these classes are present in the java.lang package.

Q.46. State the difference between a constructor and a method in Java?

Answer. Again, a popular Java interview question. The differences between constructor and method are:

  • The constructor initializes an object of the class whereas the method exhibits the functionality of an object.
  • Constructors are invoked implicitly when the object is instantiated whereas methods are invoked explicitly by calling them.
  • The constructor does not return any value whereas the method may or may not return a value.
  • In case a constructor is not present in the class, the Java compiler provides a default constructor. But, in the case of a method, there is no default method provided.
  • The name of the constructor should be the same as that of the class. But, the Method name should not be of the same name as that of class.

Q.47. What is the need for wrapper classes in Java?

Answer. As we know that Java is an object-oriented programming language, we need to deal with objects in many situations like in Serialization, Collections, Synchronization, etc. The wrapper classes are useful in such different scenarios. Let us the need for wrapper class in Java:

1. Changing the value in Method: Java only supports the call by value, and, if we pass a primitive value, the original value will not change. But, if we convert the primitive value into an object using the wrapper class, there will be a change to the original value.

2. Synchronization: Java synchronization works with objects so we need wrapper class to get the objects.

3. Serialization: We convert the objects into byte streams and vice versa. If we have a primitive value, we can convert it into objects using wrapper classes.

4. Collection Framework: Collection framework in Java deals with only objects. All the classes of the collection framework like ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, etc deal with objects only.

Q.48. Can you overload a constructor in Java?

Answer. Yes, it is possible to overload constructors in Java. We can define multiple constructors with different parameter types, their order, and number.

Constructor overloading is a technique in Java that allows a class to have any number of constructors that differ in the parameter lists. The compiler differentiates these constructors with respect to the number of parameters in the list and their type.

Q.49. Which is the parent class for all the classes in Java?

Answer. The Object class is the superclass for all the classes in Java. In other words, all the classes in Java ultimately inherit from Object class. To prove this, let’s see an example:

class Test {
  public static void main(String args[]) {
    System.out.println("Helloworld");
  }
}

For the above program, when we type javap Test then we get the following output:

class Test extends java.lang.Object {
  Test();
  public static void main(java.lang.String[]);
}

The first line itself shows that by default it extends java.lang.Object.

Q.50. Can you overload a main() method in Java?

Answer. Yes, we can overload the main() method in Java. We need to call the overloaded main() method from the actual main() method of the class. The overloaded main method needs to be called from inside the “public static void main(String args[])” statement. As this line is the entry point when JVM launches the class.

Q.51. What do you mean by the array in Java?

Answer. This is a Java collections interview question. An array in Java is a collection of similar types of data arranged in contiguous memory locations. It is a kind container that holds data values of one single data type. For example, we can create an array holding 100 values of int type. Arrays are a fundamental construct in Java that allows us to store and access a large number of values conveniently.

Array Declaration:
In Java, here is how we can declare an array.

dataType arrayName[];

  • dataType – it can be primitive data types like int, char, double, byte, etc. or Java objects
  • arrayName – it is an identifier

Example:
double doubleArray[];
String myArray[];

Array Initialization:
To initialize an array we use:
dataType arrayName = new dataType[arraySize];

Example:
int arr[] = new int[10];
Array arr can hold 10 elements.

Q.52. What are the different data types in Java?

Answer. There are two different types of data types in Java: Primitive Data types, and reference data types. There are eight primitive data types in Java: int, short, byte, long, char, boolean, float, and double. Examples of reference data types are arrays, strings, interfaces, etc.

Q.53. What do you mean by UNICODE in Java?

Answer. Unicode System is a universal international standard character encoding that represents most of the written languages of the world. The main objective of Unicode is to combine different language encoding schemes in order to avoid confusion among computer systems that use limited encoding standards like ASCII, EBCDIC, etc. Java was designed to use Unicode Transformed Format (UTF)-16 when the UTF-16 was designed.

Q.54. What are the advantages and disadvantages of arrays?

Answer.

Advantages of arrays:

  • It is easier access to any element of an array using the index.
  • With an array, it is easy to manipulate and store large data.

Disadvantages of arrays:

  • Arrays are of fixed size. We can not increase or decrease it once we declare it.
  • An array can store only a single type of primitives.

Q.55. What is the difference between static and dynamic binding in Java?

Answer. If linking between method call and method implementation resolves at compile-time, then it is called static binding. And, if the linking gets resolved at run time then it is dynamic binding. The dynamic binding uses objects to resolve to bind, while static binding uses the type of the class and fields for binding.

Q.56. What is the difference between inner and anonymous inner classes?

Answer: A class inside a class is called nested classes in Java. An inner class is any nested class that is non-static in nature. Inner classes can access all the variables and methods of the outer class.

Anonymous inner class is any local inner class without any name. We can define and instantiate it in a single statement. Anonymous inner classes always either extend/inherit a class or implement an interface. Since there is no name of an anonymous inner class, it is not possible to create its constructor.

Q.57. What are the statements in Java?

Answer. Statements are like sentences in natural language. A statement gives a complete unit of execution. We can make the following types of expressions into a statement by terminating the expression with a semicolon

  • Assignment expressions
  • Any use of ++ or —
  • Method calls
  • Object creation expressions

The above statements are called expression statements. There are two other kinds of statements in addition to these expression statements. A declaration statement declares a variable. A control flow statement regulates the order or the flow in which statements get executed. The for loop and the if statement is some examples of control flow statements.

Q.58. What is the difference between the boolean & and && operator?

Answer. Both operands are evaluated if an expression involving the Boolean & operator is performed. After that, the & operator is applied to the operand.

When there is an evaluation of an expression involving the && operator, then the first operand is evaluated. If the first operand returns true then the second operand is evaluated. Then, the && operator is applied to the first and second operands. If the first operand results to false, then there is no evaluation of the second operand.

Q.59. How do you name Java source code files?

Answer. The name of a source code file of Java is the same as the public class or interface defined in the file. In a source code file, there is at most one public class or interface. The source code file must take the name of the public class or interface if there is a public class or interface in a source code file. And, if there is no public class or interface present in a source code file, then the file must take on a name that is different from its classes and interfaces. Source code files use the .java extension.

Q.60. If you declare a class without any access modifiers, then where it is accessible?

Answer. If we declare a class that without any access modifiers, we call the class to have a default or package access. This means that the class is only accessible by other classes and interfaces that are defined within the same package. No classes or interfaces outside the package can access this class.

Q.61. State the purpose of the Garbage Collection in Java.

Answer. The purpose of garbage collection in Java is to detect and eliminate/delete the objects that are no longer in use in the program. The objects that are no longer reachable are removed so that their resources may be reclaimed and reused.

Q.62. What is JNI? What are its advantages and disadvantages?

Answer. The full form of JNI is the Java Native Interface. With the help of JNI, we can call functions written in languages other than Java.

The advantages and disadvantages of JNI are:

Advantages:

  • When we want to use the existing library that we previously developed in another language.
  • When there is a need to call the Windows API function.
  • To increase the execution speed.
  • When we need to call the API function of some server product which is written in C or C++ from a Java client.

Disadvantages:

  • There is a difficulty in debugging runtime errors in native code.
  • There may be a potential security risk.
  • We can not call it from Applet.

Q.63. What is Serialization in Java?

Answer. Serialization in Java enables a program to read or write a whole object in byte stream and to read that byte stream back to the object. It allows Java objects and primitive data types to be encoded into a byte stream so that it is easy for streaming them to some type of network or to a file-system.

A serializable object must implement the Serializable interface that is present in the java.io package. We use ObjectOutputStream class to write this object to a byte stream and ObjectInputStream to read the object from the byte stream.

Q.64. Why does Java not have multiple inheritances?

Answer. This is one of the most important Java oops interview questions. Java introduced Java language to make it:

  • Simple and familiar
  • Object-oriented
  • Robust
  • Secure
  • Architecture neutral
  • Portable
  • High performance
  • Multi-threaded and Dynamic

The reasons for not supporting multiple inheritances mostly arise from the goal of making Java simple, object-oriented, and familiar. The creators of Java wanted that most developers could grasp the language without extensive training. For this, they worked to make the language as similar to C++ as possible without carrying over its unnecessary complexity.

According to Java designers, multiple inheritances cause more problems and confusion. So they simply cut multiple inheritances from the language. The experience of C++ language taught them that multiple inheritances just was not worth it. Due to the same reason, there is no support for Multiple Inheritance in Java.

Q.65. What is synchronization in Java and why is it important?

Answer. Synchronization in Java is the ability to control the access of multiple threads to shared resources. Without synchronization, it is not possible for a thread to access a shared object or resource while another thread is already using or updating that object’s value.

Q.66. Why has the String class been made immutable in Java?

Answer. The String class is immutable to achieve performance & thread-safety in Java.

1. Performance: Immutable objects are ideal for representing values of abstract data types like numbers, enumerated types, etc. Suppose, if the Strings were made mutable, then string pooling would not be possible because changing the String with one reference will lead to the wrong value for the other references.

2. Thread safety: Immutable objects are inherently threaded safe as we cannot modify once created. We can only use them as read-only objects. We can easily share them among multiple threads for better scalability.

Q.67. What are the differences between C++ and Java?

Answer. Both C++ and Java are similar and Object-Oriented and use almost similar syntax but there are many differences between them. The differences between C++ and Java are:

S.N C++ Java
1. C++ is a platform-dependent language. Java is a platform-independent language.
2. We can write structural programs without using classes and objects in C++. Java is a pure object-oriented language except for the use of primitive variables.
3. There is no support for documentation comments in C++. Java supports documentation comment using /**…*/
4. There is full support of pointers in C++ fully supports pointers. There is no concept of pointers in Java.
5. C++ supports the concept of multiple inheritances. Java doesn’t support multiple inheritances.
6. C++ supports destructors.  Java does not support destructors, bust uses the finalize() method.
7. There are structure and union in C++ Java does not support structures and unions but uses the Collection framework.
8. C++ requires explicit memory management Java includes automatic garbage collection

Q.68. What are finally and finalize in Java?

Answer. The finally block is used with a try-catch block that we put the code we always want to get executed even if the execution is thrown by the try-catch block. The finally block is just used to release the resources which were created by the try block.

The finalize() method is a special method of the Object class that we can override in our classes. The garbage collector calls the finalize() method to collect the garbage value when the object is getting it. We generally override this method to release the system resources when garbage value is collected from the object.

Q.69. What is Type Casting in Java?

Answer. There are some cases when we assign a value of one data type to the different data types and these two data types might not be compatible with each other. They may need conversion. If data types are compatible with each other, for example, Java does the automatic conversion of int value to long and there is no need for typecasting. But there is a need to typecast if data types are not compatible with each other.

Syntax

dataType variableName = (dataType) variableToConvert;

Q.70. What happens when an exception is thrown by the main method?

Answer. When the main() method throws an exception then Java Runtime terminates the program and prints the exception message and stack trace in the system console.

Q.71. Explain the types of constructors in Java?
Answer. There are two types of Java constructors based on the parameters passed in the constructors:

Default Constructor: The default constructor is a non-parameterized constructor that does not accept any value. The default constructor mainly initializes the instance variable with the default values. We can also use it to perform some useful task on object creation. A compiler implicitly invokes a default constructor if there is no constructor defined in the class.

Parameterized Constructor: The parameterized constructor is the constructor with arguments and one which can initialize the instance variables with the given values. We can say that the parameterized constructors are the constructors that can accept the arguments.

Q.72. Why does Java not support pointers?

Answer. The pointer is a variable that refers to some memory address. Java does not support pointers because they are unsafe, unsecured, and complex to understand. The goal of Java is to make it simple to learn and understand and also a secure language, therefore Java avoids the use of such complex and unsafe concepts.

Q.73. What is the String Pool?

Answer. The string pool is the reserved memory in the heap memory area. It is mainly used to store the strings. The main advantage of the String pool is whenever we create a string literal, JVM first checks it in the “string constant pool”. If the string is already present in the pool, then it returns a reference to the pooled instance. If the string is not present in the pool, then it creates a new String and places it in the pool. This saves memory by avoiding duplicate values.

Java Basic Programs for Interview

Now, it’s time to move towards Java interview programs, there are few popular Java codes which are frequently asked in the interviews. We recommend you to practice them while reading.

Q.74. What is the toString() method in Java?

Answer. String is an important topic during any Java interview, usually, interviewers ask multiple java string interview questions.

The toString() method in Java is used to return the string representation of an object. The compiler internally invokes the toString() method on the object when you print any object. So we can get the desired output by overriding the toString() method. We can return the values of an object by overriding the toString() method of the Object class. So, there is no need to write much code.

Consider the following example.

class Student {
  int rollno;
  String name;

  Student(int rollno, String name) {
    this.rollno = rollno;
    this.name = name;
  }

  public String toString() {
    //overriding the toString() method  
    return rollno + " " + name + " ;  
}  
public static void main(String args[])
{  
Student str1 = new Student(101,"
    Sneha”);
    Student str2 = new Student(102, "Raj”);  
     
System.out.println(str1);
//compiler writes here str1.toString()  
System.out.println(str2);
//compiler writes here str2.toString()  
}  
}  
"

Output:
101 Sneha
102 Raj

Q.75. Write a program to count the number of words in a string?

Answer. The following program counts the number of words in a String:

public class Test {
  public static void main(String args[]) {
    String str = "I am enjoying learning Java";
    String words[] = str.split(" ");
    System.out.println("The number of words in the given string are: " + words.length);
  }
}

Output:
The number of words in the given string is: 5

Q.76. What are the advantages of Java inner classes?

Answer. The advantages of Java inner classes are:

  • Nested classes show a special type of relationship and it can access all the data members and methods of the outer class including private members.
  • Nested classes develop a more readable and maintainable code because they logically group classes and interfaces in one place only.
  • Nested classes enable Code Optimization as they require less code to write.

Q.77. What are autoboxing and unboxing? When does it occur?

Answer. This is also a popular Java interview question. Autoboxing is the process of converting primitive data types to the respective wrapper class object, for example, int to Integer or char to Character. Unboxing is the reverse process of autoboxing, i.e., converting wrapper class objects to the primitive data types. For example, Integer to int or Character to char. Autoboxing and Unboxing occur automatically in Java. However, we can convert them explicitly by using valueOf() or xxxValue() methods.

It can occur whenever there is a need for a wrapper class object, but a primitive data type is present or vice versa. For example:

  • Adding primitive data types into Collection like ArrayList Set, LinkedList, etc, in Java.
  • When we need to create an object of parameterized classes, for example, ThreadLocal which expects Type.
  • Java automatically converts primitive data types to wrapper class objects whenever required and another is provided in the method calling.
  • When a primitive type is assigned to a wrapper object type.

Q.78. What is a Loop in Java? What are the three types of loops?

Answer. This is the most basic interview question that you must know mandatorily before attending any interviews. Looping is one of the most important concepts of programming that is used to implement a statement or a block of statements iteratively. There are three kinds of loops in Java, we will discuss them briefly:

a. for loops:
A for loop in Java is used to implement statements iteratively for a given number of times. We use for loops when the programmer needs to refer to the number of times to implement the statements. It consists of three statements in a single line: Initialization, test-condition, update statement. The syntax of for loop is:

for(Initialization; test-condition; update expression)

b. while Loops:
The while loop is used if we require certain statements to be implemented regularly until a condition is fulfilled. The condition gets tested before the implementation of statements in the while loop, therefore it is also called the entry controlled loop. The syntax of while loop is:

while(test-condition)
{
  //statement/s
}

c. do-while loops:
A do-while loop is the same while loop, the only difference is that in the do-while loop the condition is tested after the execution of statements. Thus in the do-while loop, statements are implemented at least once. These are also called exit controlled loops. The syntax of the do-while loop is:

do
{
   //statements
}while(test-condition)

Q.79. State the difference between the comparison done by equals method and == operator?

Answer. The difference between equals() method and == operator is the most frequently asked question. Equals() method compares the contents of two string objects and returns true if they both have the same value, whereas the == operator compares the two string objects references in Java. In the below example, equals() method returns true as the two string objects contain the same values. The == operator returns false as both the string objects are referencing to different objects:

public class Test {
  public static void main(String args[]) {
    String srt1 = “Hello World”;
    String str2 = “Hello World”;
    if (str1.equals(str2)) {
      System.out.println(“str1 and str2 are equal in values”);
    }
    if (str1 == str2) {
      //This condition is false
      System.out.println(“Both strings are referencing same object”);
    }
    else {
      // This condition is true 
      System.out.println(“Both strings are referencing different objects”);
    }
  }
}

Output:
str1 and str2 are equal in terms of values
Both strings are referencing different objects

Q.80. State the difference between error and an exception?

Answer. An error is an irrecoverable condition that occurs during the execution or runtime of the program. For example, OutOfMemory error. These are JVM errors and we can not repair or recover from them at runtime. On the other hand, Exceptions are conditions that occur because of wrong input given by the user or the bad illogical code written in the code, etc.

For example, FileNotFoundException is thrown if the specified file does not exist. Or, if there is a NullPointerException if we try to use a null reference. In most cases, it is possible to recover from an exception either by giving users feedback for entering proper values, or handling exceptions through various methods.

Q.81. What is an Infinite Loop? How an infinite loop is declared?

Answer. An infinite loop runs without any condition and runs infinitely without ending until we stop the execution. We can come out of an infinite by defining any breaking logic in the body of the statement blocks.
We can declare the Infinite loop as follows:

for (;;) {
  // Statements to execute
  // Add any loop breaking logic
}

Q.82. How can you generate random numbers in Java?

Answer. In Java we can generate random numbers in two ways:

  • Using Math.random() function, we can generate random numbers in the range of 0.1 and 1.0
  • Using Random class in the java.util package.

Q.83. What is the System class?

Answer. It is a core class in Java. Since the class is final, we cannot override its behavior through inheritance. Neither can we instantiate this class since it doesn’t provide any public constructors. Hence, all of its methods are static.

Q.84. Explain various exceptions handling keywords in Java?

Answer. There are three important exception handling keywords in Java:

try:
If a code segment has chances of having an error, we pace it within a try block. When there is an exception, it is handled and caught by the catch block. There must be a catch or a final or both blocks after the try block.

catch:
Whenever there is an exception raised in the try block, it is handled in the catch block.

finally:
The finally block executes irrespective of the exception. We can place it either after try{} or after the catch {} block.

Q.85. Can we convert byte code into source code?

Answer. Yes, it is possible to convert byte code into the source code. A decompiler in Java is a computer program that works opposite from the compiler. It can convert back the byte code or the .class file into the source code or the .java file. There are many decompilers but the most widely used JD – Java Decompiler is available both as a stand-alone GUI program and as an Eclipse plug-in.

Q.86. State the basic difference between String, StringBuffer, and StringBuilder?
Answer.

  • String class is immutable in Java, and this immutability provides security and performance.
  • StringBuffer class is mutable, hence we can add strings to it, and when required, we can also convert to an immutable String using the toString() method.
  • StringBuilder class is very similar to a StringBuffer, but StringBuffer has one disadvantage in terms of performance. This is because all of its public methods are synchronized for thread-safety.
  • If thread-safety is required, use StringBuffer class, otherwise use StringBuilder.

Q.87. Distinguish between a unary, binary, and a ternary operator. Give examples.

Answer.
1. Unary Operator: A unary operator requires a single operand. Some unary operators in Java are: unary+, unary-, ++, –, sizeof, instanceof, etc.

2. Binary Operator: Binary operator works on two operands. Some binary operators in Java are:

  • Addition(+)
  • Subtraction(-)
  • Multiplication(*)
  • Division(/)
  • Modulus(%)
  • &&, || , etc.

3. Ternary Operator: Ternary operators require three operands to work upon. The conditional operator- ?: is a ternary operator in Java.

Q.88. State the rules of Operator Precedence in Java.

Answer. Operator Precedence Hierarchy in Java evaluates all the expressions. Operator Precedence Hierarchy establishes the rules that govern the order of evaluation of operands in an expression. The rules are:

Operators: (type), *, /, and the remainder or modulus operator(%) are evaluated before + and – operators.

Any expression in parenthesis {} is evaluated first.

The precedence of the assignment operator is lower than any of the arithmetic operators.

Q.89. What is a fall through in Java?

Answer. The “fall through” is the term used in the switch statement. It refers to the way in which the switch statement executes the various case sections. Every statement that follows the selected case executes until it encounters a break statement.

Q.90. Tell the difference between Call by Value and Call by Reference in Java.

Answer. In call by value, the function creates its own copy of the passed parameters. It copies the passed values in it. If there are any changes, they remain in the copy and no changes take place in the original data.

On the other hand, in call by reference, the called function or method receives the reference to the passed parameters and it accesses the original data through this reference. Any changes that take place are directly reflected in the original data.

Q.91. What are the different types of arrays in Java? Give examples of each.

Answer. Arrays are of two types:

1. Single dimensional arrays/one-dimensional arrays- These arrays are composed of finite homogeneous elements. This is the simplest form of arrays. We give it a name and refer to the elements by using subscripts or indices.

Declaring single dimensional arrays:

datatype arrayName[] = new datatype[size];

or

datatype[] arrayName = new datatype[size];

2. Multi-dimensional arrays- These arrays are composed of elements, each of which itself is an array. The two-dimensional arrays are the simplest form of multi-dimensional arrays. Java allows more than two dimensions. The exact limit of dimensions is decided by the compiler we use.

A two-dimensional array(2D array) is an array in which each element is itself a one-dimensional array. For example, an array arr[P][Q], is an array P by Q table with P rows and Q columns, containing P x Q elements.

Declaring two-dimensional arrays:

datatype arrayName[] = new datatype[rows][columns];

or

datatype [] [] = new datatype[rows][columns];

Q.92. What are keywords in Java? How many keywords are used in Java?

Answer. Keywords in Java are the reserved words that convey a special or particular meaning to the compiler. We cannot use the keywords as an identifier in a program. There are 51 keywords in Java. For example class, int, break, for, switch, abstract, etc.

Q.93. Differentiate between actual and formal parameters in Java?

Answer. The data necessary for the function to perform the task is sent as parameters. Parameters can be actual parameters or Formal Parameters.

The difference between Actual Parameters and Formal Parameters is that Actual Parameters are the values that are passed to the function when it is invoked while Formal Parameters are the variables defined by the function that receives values when the function is called.

Actual Formal
Definition The Actual parameters are the values passed to the function when it is invoked. The Formal Parameters are the variables of a function that receives values when the function is called.
Related function We pass the actual parameters by the calling function. The formal parameters are present in the called function.
Data types In actual parameters, there is no need to mention the data types. Only values are mentioned. In formal parameters, there should be the data types of the receiving values.

Q.94. State the difference between a while and do-while statement in Java?

Answer. The while and do-while loop are the same but the difference is that in the do-while loop the loop executes for at least once. The while loop is the entry-controlled loop and the do-while loop is the exit- controlled loop.

Q.95. What is the PATH and CLASSPATH in Java?

Answer. PATH in Java is the environment variable in which we mention the locations of binaries files. Example: We add bin directory path of JDK or JRE, so that any binaries under the directory can be accessed directly without specifying absolute path. CLASSPATH is the path for Java applications where the classes you compiled will be available.

1. The path is an environment variable that the operating system uses to find the executable files. On the other hand, Classpath is an environment variable that a Java compiler uses to find the path of classes.

2. PATH is used for setting up an environment for the operating system. The Operating System will search in this PATH for executables. On the other hand, Classpath is nothing but setting up the environment for Java. Java will use it to find compiled classes.

3. Path refers to the system while classpath refers to the Developing Environment.

Q.96. What is a Singleton class and how can we create it?

Answer. A singleton class is a class that has only one object or an instance of the class at a time. The singleton class provides a global point of access to the object. If we talk about the practical applications of Singleton class, then Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects.To design a singleton class, we have to:

  1. Mark the class’s constructor as private.
  2. Write a static method with a return type as an object of this singleton class. Here, we use the concept of Lazy initialization to write this static method.

Q.97. State the difference between Array and ArrayList in Java.

Answer. An Array is a data structure that has a fixed and static length, whereas ArrayList is a Collection in Java with a variable length. We can not change or modify the length of an array once we create it in Java. But, we can change the length of an ArrayList even after creation. It is not possible to store primitives in ArrayList. An ArrayList can only store objects. But, in an array there can be both primitives and objects in Java.

Q.98. What is object cloning in Java?

Answer. The term object cloning in Java refers to the way of creating an exact copy of an object. The clone() method of the Object class clones or creates a copy of an object. The class that wants its object to be cloned, must implement the java. lang. Cloneable interface. If the class does not implement this Cloneable interface, then the clone() method generates a CloneNotSupportedException.

There are two types of Object cloning in Java: – Deep Cloning and Shallow Cloning. By default, Java uses Shallow Cloning.

Q.99. Differentiate between java.util.Date and java.sql.Date in Java?

Answer. java.sql.Date just represents the date without time information whereas java.util.Date represents information of both Date and Time. This is the major difference why there is no direct mapping of java.util.Date to java.sql.Date.

Date class that belongs to util package of Java and has is a combination of date and time while Date class that belongs to SQL package represents only the Date part.

Precisely, the Date contains information of year, month, and day and the Time means hour, minute, and second information. The java.util.Date class contains all year, month, day, hour, minute, and second information, but the class java.sql.date only represents the year, month, and day.

Q.100. Compare recursion and iteration.

Answer. In iteration, the code is executed repeatedly using the same memory space. That is, the memory space allocated once is used for each pass of the loop.

On the other hand, in recursion, since it involves function calls at each step, fresh memory is allocated for each recursive call. For this reason, i.e., because of function call overheads, the recursive function runs than its iterative counterpart.

Conclusion

We have covered the top Java interview questions with answers for freshers. The key to success in the Java interview is going through as many questions as you can.

These questions are the most frequently asked questions for any fresher.

Did you like our efforts? If yes, please rate TechVidvan on Google.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.