Java Interview Questions And Answers (2022)

1.
What is Java?
Java is high-level, class-based, object oriented programming language developed by Sun Microsystems, USA in 1995. Java is developed to make the language simple, portable and highly reliable.
2.
Who developed Java and when?
A team of Sun Microsystems programming headed by James Gosling was developed Java and released in 1995.
3.
Define some features of Java.
These are the features of Java -
1. Object Oriented
2. Compiled and Interpreted
3. Platform - Independent and Portable
4. Distributed
5. Multithreaded and Interactive
6. Robust and Secure
4.
Which process is used by Java to execute a program?
Java executes a program in two stage - complied and interpreted. In first stage, java compiler translates the source code into byte codes and in second stage, java interpreter generates machine code to execute the program by machine.




5.
What is Java Development Kit (JDK)?
JDK contains a large number of development tools. These tools are used for developing and running Java programs. The JDK contains Java Runtime Environment, Java Compiler, Java Interpreter, Java Archiver and other tools.
6.
What is javac?
javac is the Java Complier, which translates Java sourcecode to bytecode files.
7.
What is jdb?
jdb is the java debugger, which is used to find error in programs.
8.
Why is Java known as platform-neutral language?
Java program is compatible in different operating systems, processors. It can be easily move and run from one computer system to another.
9.
Why java is called truly Object-Oriented language?
Java is truly object oriented language, everything must be placed inside a class. All the program codes and data resides within classes and objects.
10.
What is main() method?
The main() method is the starting point of the execution of a program. Every Java application has at least one class and at least one main method. It indicates the interpreter to start the execution of a program. Without the main() method, JVM will not execute the program.




11.
What is the execution statement in Java?
The execution statement in Java is -
System.out.println("Printing message");

The println() method is a member of the out object, which is static data member of System class. This method always append a new line character to the end of the string.
12.
Define keywords with examples?
Keywords are predefined, reserved words used in Java programming that have special meanings to the compiler. They cannot be used as an identifier. Each of the keyword is associated with specific features. These words help us to use the functionality of Java language.
Examples - import, static, class, double, finally.
13.
What is the syntax of compiling a program?
Java compiler javac is used to compile the program. To compile a program write the source file name followed by javac on command promt.
Javac  Demo.java

The above command creates a file called 'Demo.class', containing the bytecodes of the program.
14.
What is the syntax of running the program?
Java Interpreter is used to run the stand alone program. To run the program type the source file name followed by java keyword.
Java Demo
The interpreter looks for the main method in the program and starts execution from there.
15.
What is JVM?
Java complier produces an intermediate code known as byte code for a machine that does not exist. This machine is called the Java Virtual Machine and it exists only inside the computer memory.
16.
What is a constant?
A constant is a variable whose value cannot change once it has been assigned. Java doesn't have built-in support for constants. In addition, a constant is cached by the JVM as well as our application, so using a constant can improve performance.
17.
What is type casting?
If there is need to store a value of one type into a variable of another type. We must cast the value to be stored by preceding it with type name in parentheses.
type variable1 = (type) variable2;

18.
What is Instanceof Operator?
The instanceOf is an object reference operator and returns true, if the object on the left hand side is an instance of the class given on the right hand side. This operator allows us to determine whether the object belongs to a particular class or not.
19.
What is branching?
When a program breaks the sequential flow and jumps to another part of the code, it is called branching. These are the decision making statements -
1.If statement
2.Switch statement
3.Conditional operator statement
20.
What is conditional operator?
Conditional Operator is used for making two way decisions.
Conditional expression ? expression1 : expression2;
If the conditional expression result is true then expression1 is evaluated otherwise expression2 is evaluated.
21.
What is Switch Statement?
If there is need to match the value from many different cases and execute the statements within the matched case. Switch statement executes line by line and read all the cases. If the case value is matched with a value passed in the switch expression, then statement within the matched case is executed.
22.
What is infinite loop?
If loop executes infinite times without any termination, it is called infinite loop.




23.
What is while loop?
While loop is used for iteration. In each iteration, it evaluates the truth expression just like If statement. If the condition evaluates to true, then the statement inside the loop is executed and control goes to the next iteration.
24.
What is for loop?
Loop is used to run a set of instruction at given number of times or until a particular condition is satisfied.
25.
What is break and continue?
The break statement is placed inside the loop to terminate the iteration and start to execute the code immediately after the loop and the continue statement is also used inside a loop. When continue statement is executed, it stops the current iteration of the loop and continue with the next iteration of the loop.




26.
What is polymorphism?
Polymorphism means multiple forms. This is the ability to take multiple forms. There are two types of polymorphism in Java - Compile Time (Static) and Run Time(Dynamic).
27.
How to instantiating an object?
The new operator is used to instantiating an object of previously specified class.
28.
What is constructors?
The constructor is declared inside a class like a function and have the same name as the class itself. It calls automatically while creating an object. It does not specify any return type.
29.
Define Methods Overloading?
If a class have multiple methods with the same name but with different parameters and behavior, it is known as method overloading.
30.
What is Static Members?
Static methods and variables are not bound to any specific object, they are common to all the objects. These members are accessed by the class name.
31.
Define Inheritance?
Inheritance is the process of driving a new class from an existing class. The existing class is called parent class and new class is called child class. The new class inherits all the properties and methods of the parent class.
32.
Define Overriding Methods?
If the method in the child class has same name, same arguments as a method in parent class, it is called method overriding.
33.
What is Finalize Methods?
Finalize method is used to free the memory from non object resources.
34.
What is Abstract Methods?
The abstract class is declared with the keyword abstract. This abstract class cannot be instantiated, it only inherited. An abstract class has at least one abstract method, preceded with the abstract keyword.
35.
Describe different forms of inheritance.
These are the different forms of Inheritance -

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
36.
How to defined methods?
Methods are declared inside a class. The general syntax of defining a method is -
type methodname(argument list) 
{
  statements
}

type is the datatype of value return by method, all the statements are written inside opening and closing braces and all arguments are separated by comma.
37.
When should we declare a method final?
If there is need to prevent child classes from overriding the methods of parent class, we should declare those methods as final.
38.
What is the difference between overloading and overriding?




Overloading is used to have same function name which behave differently depending upon parameters passed to them. Overriding function is used in inheritance when derived class function has to do some added or different tasks than the base class.
39.
What is Garbage Collection?
Garbage Collection is a process of automatically manage the heap memory. It checks the used and usused objects in memory and gets rid the unused objects.
40.
What is this keyword?
This keyword provides reference to the current object. It can be used to refer instance variable of current class, to invoke or initiate current class constructor and it can be passed as an argument in the method call.
41.
What is the use of instanceof operator in Java?
The instanceof operator is used to check whether the object is an instance of the specified class or interface.
42.
Define static methods and properties?
Static methods and properties are not bound to any specific object. It belongs to the class and commonly refer to all objects of the class. It gets memory only once at the time of class loading.
43.
What is the use of throw in Java?
'throw' keyword is used to throw an exception in java.
44.
What is the importance of finally block in Java?
The code which is important to execute whether exception is handled or not is written in finally block. The code written in finally block is always executed.
45.
What is nested class?
A class which is declared inside another class is known as Nested class. The scope of the nested is bounded by the scope of its enclosing class.




46.
Is multithreading supported in Java?
Yes, Java supports multithreading. In Java, multiple threads can be executed simultaneously, so that we can perform multiple operations at same time.
47.
What is JIT?
JIT stands for Just-In-Time. JIT is compiler that converts java bytecode into native machine code. It reduces the compilation time and improve the performance.
48.
How can you make copy of a Java object?
We can make copy of a Java object by using the clone() method. The clone() method makes exact copy of an object.
49.
Can we implement destructor in Java?
No, we cannot implement destructor in java, as java does not support destructor. Java supports garbage collection to free the memory space automatically.
50.
What are constructors in Java?
A constructor is a member function that is executed automatically whenever an object is created.
51.
Write a program to add two numbers in Java?
Here is the simple Java program to add two numbers.
public class AddTwoNumbers {

   public static void main(String[] args) {
        
      int num1 = 85, num2 = 35, sum;
      sum = num1 + num2;

      System.out.println("Sum of given numbers: "+sum);
   }
}
Output of the above code:
Sum of given numbers: 120
52.
Write a program to sum of prime numbers in Java?
A prime number is a whole number greater than 1, whose only factors are 1 and itself, like -2, 3, 5, 7, 11 etc. The given Java program calculates the sum of prime numbers between 1 and 150 using the while loop.
public class SumOfPrimeNumbers  
{  
  public static void main(String args[])   
  {  
    int sum = 0, num = 1;  
 
    while(num <= 150)  
    {  
      int i = 2, counter = 0;  
      while(i <= num/2 )  
      {  
        if(num % i == 0)  
        {  
          counter++;  
          break;  
        }  
        //increments the variable i by 1  
        i++;  
      } 
      // calculates the sum of prime numbers 
      if(counter == 0 && num != 1 )            
      {  
        sum = sum + num;  
      }
      num++;  
    }  
    //prints the sum  
    System.out.println("The Sum of Prime Numbers from 1 to 150 : " + sum);  
  } 
}   
Output of the above code:
The Sum of Prime Numbers from 1 to 150 : 2276




53.
Write a program to sum of digits of a number in Java?
In the given example, we call the recursion function to find the sum of digits of a given number.
public class SumOfDigits
{  
  // defining function 
  // to calculate the sum of digits of a number  
  static int findSum(int num)  
  {  
    return num == 0 ? 0 : num % 10 +findSum(num/10) ;  
  }  
  //driver code  
  public static void main(String args[])  
  {  
    int number = 345237;   
    System.out.println("The sum of digits: "+findSum(number));  
  }   
}  
Output of the above code:
The sum of digits: 24




54.
Write a program to swap two numbers in Java?
In the given example, we have taken a temporary variable for swapping two numbers.
import java.util.*;  
public class Swap_Numbers {  
    public static void main(String[] args) {  
       int a, b, temp;
       
       Scanner sc = new Scanner(System.in);  
       System.out.println("Enter the value of a and b: ");  
       a = sc.nextInt();  
       b = sc.nextInt();  
       System.out.println("Before swapping numbers: "+a +"  "+ b); 
       
       // Value of first is assigned to temporary 
       temp = a;  
       
       // Value of second is assigned to first
       a = b;  
       
       // Value of temporary is assigned to second 
       b = temp;  
       System.out.println("After swapping numbers: "+a +"   " + b);  
       System.out.println( );  
    }    
} 
Output of the above code:
Enter the value of a and b: 23 53
Before swapping numbers: 23  53
After swapping numbers: 53   23
55.
Write a program to remove space from string in Java?
In the given example, we have removed the white spaces from the string using Java built-in method.
// Java remove whitespaces
// using built in method  

public class RemoveSpace {
    public static void main(String[] args)
    {
        String str = "  Welcome to etutorialspoint .   ";
        System.out.println("Original String: " + str);
        // Calling the replaceAll() method
        str = str.replaceAll("\\s", "");
        System.out.println("New String: " + str);
    }
} 
Output of the above code:
Original String:   Welcome to etutorialspoint .   
New String: Welcometoetutorialspoint.




56.
Write a program to find second largest number in array in Java?
In this post, you will learn how to find the second largest number using Java arrays.
import java.util.Arrays;  
public class SecondLargestInArray{  
    public static int getSecondLargest(int[] a, int len){  
        Arrays.sort(a);  
        return a[len-2];  
    }  
    public static void main(String args[]){  
        int x[]={32,84,48,91};  
        int y[]={2,4,5,7,1,6,9};  
        System.out.println("Second Largest Number: "+getSecondLargest(x,4));  
        System.out.println("Second Largest Number: "+getSecondLargest(y,7));  
    }
    
}
Output of the above code:
Second Largest Number: 84
Second Largest Number: 7
57.
Write a program to find the GCD of two numbers in Java?
In the given Java program, we have used the while loop to find the G.C.D of two numbers. In this method, smaller integer is subtracted from the larger integer, and the result is assigned to the variable holding the larger integer. This process is continued until the condition x!=y becomes false.
public class FindGCD   
{  
    public static void main(String[] args)   
    {  
    int x=32, y=28;  
    while(x!=y)   
    {  
        if(x>y)  
        x=x-y;  
        else  
        y=y-x;  
    }  
    System.out.printf("GCD of x and y is: " +y);  
    }   
}  
Output of the above code:
GCD of x and y is: 4




58.
Write a program to calculate the area of a circle in Java?
Here is the program to calculate the area of the circle using the user-defined method.
import java.util.Scanner;

public class AreaOfCircle 
{
  public static void main(String args[]) 
  {   
      Scanner s= new Scanner(System.in);
      System.out.println("Please enter the radius : ");
      double r = s.nextDouble();      
      double a = circleArea(r);
      System.out.println("Area of Circle : " + a);      
  }
  static double circleArea(double r)
  {
	  return (22*r*r)/7;
  }
}
Output of the above code:
Please enter the radius : 22
Area of Circle : 1521.1428
59.
Write a program to count vowels in a string in Java?
In the given example, we have initialized a count variable with 0 value. When the user entered the string as input, it passed through the for loop statement and compared each character in the sentence with the characters {'a', 'e', 'i', 'o', 'u' }.
// Java program for counting vowels
import java.util.Scanner;

public class CountingVowels {
  
   public static void main(String args[]){
      int count = 0;
      System.out.println("Please enter a string :");
      Scanner sc = new Scanner(System.in);
      String string = sc.nextLine();

      for (int i=0 ; i
Output of the above code:
Please enter a string : elephant is a big animal
Total number of vowels in the given sentence : 9
60.
Write a program to find fibonacci series program in Java using for loop?
Here, you will learn how to print Fibonacci series using a for loop in Java. In this below code, f1 contains first number, i.e., 0 and f2 contains second number, i.e., 1 and n contains total Fibonacci series number count.
public class FibonacciSeries{  
    
public static void main(String args[])  
{    
 int f1=0,f2=1,n,i,count = 15;
 
 //printing 0 and 1  
 System.out.print(f1+" "+f2);  
    
 // start the loop from 2    
 for(i=2;i
Output of the above code:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377




Related Articles

Sort array in ascending order Java
Automorphic number in Java
Pascal triangle program in Java
Factorial using recursion in java
Java random number between 1 and 10
Palindrome program in Java
Floyd triangle in Java
Pyramid pattern programs in Java
Star pattern programs in Java
Number pattern programs in Java
Java program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java




Read more articles


General Knowledge



Learn Popular Language