Top Java Interview Questions & Answers

Java Interview Questions & Answers
Table of Contents

1. What is JAVA?

Java is a popular object-oriented programming language. It is defined as a complete collection of objects. By using Java, we can develop lots of applications such as gaming, mobile apps, and websites.

2. Name the Java IDEs. What are the prominent features of Java?

Eclipse and NetBeans are the IDEs of JAVA.

  • Dynamic: Java is more dynamic when compared to C++ and C. Java is designed in such a way that it is adaptable to any evolving environment.
  • Simple: Java is very easy to learn and code.
  • Object-oriented: In Java, everything is based on objects.
  • Secure: Java provides a secure platform to develop safe and virus-free applications.
  • Platform Independent: Unlike C and C++, when we compile Java code it is compiled into platform-independent byte code rather than the platform-specific machine code.
  • Portable: Java provides no implementation aspects for the specifications that make Java portable.
  • Multithreaded: With this feature, we can perform multiple tasks simultaneously in Java.
  • High-Performance: With the built-in Just-in-Time compiler, Java provides high performance.
  • Robust: Java makes more efforts to eliminate errors by concentrating more on runtime checking and compile-time checks.

3. What is a Class?

All Java codes are defined in a Class. It has variables and methods. Class is defined as a template or a blueprint that is used to create objects and also to define objects and methods.

Variables are attributes that define the state of a class.

A method is a place where the exact business logic has to be done. It contains a set of statements (or) instructions to satisfy a particular requirement.

4. Define Object in Java.

The instance of a class is called an object. Every object in Java has both state and behaviour. The state of the object is stored in fields and the behaviour of the objects is defined by methods.

5. What is the significant difference between JVM, JRE, and JDK?

  • JVM: Java Virtual Machine is the main part of Java programming, which provides platform independence. JRE and JDK both contain JVM to run our Java programs.
  • JDK: This development kit is mainly used for developing programs.
  • JRE: Java Runtime Environment is mainly used for running Java programs.

6. Define variables in Java and explain with examples.

Variables in Java can be defined as a basic storage unit of a program. It is a storage unit that holds the value during the program execution. Always the variable is assigned with a data type. For Example, int a = 10;

7. What are the different types of variables in Java?

There are mainly three different types of variables available in Java, and they are:

  • Static Variables
  • Local Variables
  • Instance Variables

Static Variables: A variable that is declared with the static keyword is called a static variable. A static variable cannot be a local variable, and the memory is allocated only once for these variables.

Local Variables: A variable that is declared inside the body of the method within the class is called a local variable. A local variable cannot be declared using the static keyword.

Instance Variables: The variable declared inside the class but outside the body of the method is called the instance variable. This variable cannot be declared as static and its value is instance-specific and cannot be shared among others.

Example

class A{  
int num=30; //instance variable  
static int age=15;  //static variable  
void method(){  
int n=90;  //local variable  
}  
} //end of class

8. What are the data types in Java?

Data types in Java specify the values and sizes that can be stored in the variables. There are mainly two types of data types; they are:

  • Primitive Data Types (predefined data types)
  • Non-primitive Data Types (referenced or user-defined data type)
Java interview questions and answers

9. What are the default values and sizes of primitive data types?

These are the most basic data types that are available in Java. The primitive data types include int, char, byte, float, double, long, short, and Boolean.

Data Type Default Size Default Value
int 4 bytes 0
char 2 bytes ‘u0000’
byte 1 byte 0
long 8 bytes 0L
float 4 bytes 0.0f
double 8 bytes 0.0d
Boolean 1 bit false

10. What are non-primitive data types?

The non-primitive data types are different from primitive data types, and these non-primitive data types include String, Array, Date, etc. But String is a built-in non-primitive data type in Java.

Non-primitive data types are created by programmers. They are not predefined in Java like primitive data types. These data types are used to store a group of values or several values.

11. How to Declare Non-Primitive Data Types in Java?

In primitive data type, we declare like this:

int p = 100; // p is an int data type that can store the only integer value.

In reference data types, an object reference variable (or simply called reference variable) is declared just like we declare a primitive variable.

School sc;

Here, School is the name of a class, and “sc” is the name of a reference variable. No object has yet been created.
We create an object of a class using a new keyword. For example, the following statement creates an object of a class School and assigns it to the reference variable “sc”.

sc = new School();
  • School name of the class.
  • sc Object reference. An object reference is a variable that stores the address of an object in the computer’s memory. An object represents an instance through which we can access a member.
  • School() Constructor of the class. The constructor of a class is generally used to initialize an object.
  • new is a special keyword that creates the memory in Java.

The declaration of an object reference variable, object creation, and initialization of a reference variable can also be done in a single-line statement like this:

School sc = new School();

12. Write the syntax for object declaration in Java.

The new keyword is used to create an object.
For example:

Classname objectname= new Classname(); // create an object for Classname.

13. What are various access specifiers present in Java?

There are four access specifiers present in Java, and they are:

  • Private - Not accessible outside object scope.
  • Public - Accessible from anywhere.
  • Default (no modifier) - Accessible from anywhere within the same package.
  • Protected - Accessible from objects and the sub-class objects.

14. Difference between == and .equals() ?

".equals" is the member of the object class that returns true if the content of objects are same whereas "==" evaluates to see if the object handlers on the left and right are pointing to the same object in memory.

15. List out the control statements in Java.

In Java control statements are divided into three types. They are:

  • Selection/Conditional Statements
  • Iterative/looping Statements
  • Jump Statements

16. What is the difference between a while loop and a do-while loop?

In the case of a while loop, the condition is tested first and then if the condition is true the loop continues if not it stops the execution. Whereas in the case of the do-while loop first the condition is executed and at the end of the loop, the condition is tested.

Java interview questions and answers

17. What are Loops in Java? What are the three types of loops?

Looping is used in programming to execute a statement or a block of statements repeatedly. There are three types of loops in Java:

  • For Loops: For loops are used in Java to execute statements repeatedly for a given number of times. For loops are used when the number of times to execute the statements is known to the programmer.
  • While Loops: While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In while loops, the condition is checked first before the execution of statements.
  • Do While Loops: Do While Loop is the same as while loop with the only difference that the condition is checked after the execution of a block of statements. Hence in the case of do while loop, statements are executed at least once.

18. Define Constructor in Java.

A constructor is a special type of method with a block of code to initialize the state of an object. A constructor is called only when the instance of the object is created. Every time in Java object is created using the new keyword and by default, the constructor is called.

19. Why the main method in Java is static?

The main reason is that the object is not required to call for a static method so, if we declare the main method as non-static we need to create an object first and then call the main() method. To save memory, we declare the main method as static in Java.

20. Define the method in Java.

In Java method is defined as a set of code that is represented by a name and can be invoked at any point in a program with the help of the method name. Every method in the program has its name which is not the same as that of a class name.

21. What happens if we declare a method as static?

If we declare a method as static, the following operations take place, and they are:

  • A static method can be invoked without creating an instance of the class.
  • Only a static method can access static data members and can change the value of a particular data member.
  • In most of the cases static method belongs to the class rather than the object of the class.

22. What is the difference between a static and a non-static method in Java?

A static method is a method that can be called directly on a class, rather than on an instance of the class. Non-static methods, also known as instance methods, can only be called on an instance of a class.

23. What is the difference between a constructor and a method in Java?

A constructor is a special method that is used to create and initialize an object of a class. A method is a block of code that can be called multiple times within a class.

24. Will the program run if we write static public void main?

Yes, the program will successfully execute if written so. Because, in Java, there is no specific rule for the order of specifiers.

Java interview questions and answers

25. Define package in Java.

The package is a collective bundle of classes and interfaces and the necessary libraries and JAR files. The use of packages helps in code reusability.

26. Why Packages are used?

Packages are used in Java to prevent naming conflicts, control access and make searching/locating and usage of classes, interfaces, etc. easier.

27. How many types of packages are there in Java?

There are two types of packages in Java

  • User-defined packages
  • Built-in packages

28. Explain public static void main(String args[]) in Java.

  • Public: The public is the access modifier responsible for mentioning who can access the element or the method and what is the limit.
  • Static: Static is a keyword used so that we can use the element without initiating the class to avoid the unnecessary allocation of the memory.
  • void: void is a keyword and is used to specify that a method doesn’t return anything. As the main function doesn’t return anything we use void.
  • main: main represents that the function declared is the main function. It helps JVM to identify that the declared function is the main function.
  • String args[]: This denotes an array of String objects. It stores Java command-line arguments that are passed to your program.

29. What is the purpose of static variables in Java?

A static variable belongs to the class rather than any specific instance. It means there is only one copy of the variable in memory, regardless of the number of objects created from the class. Static variables can be more memory efficient for shared data.
Static variables can be accessed directly in static and non-static methods.

30. What is the purpose of static methods in Java?

  • A static method belongs to the class rather than the object.
  • There is no need to create the object to call the static methods.
  • A static method can access and change the value of the static variable. However static methods cannot access non-static instance variables or call non-static methods directly.

31. Does the constructor return any value?

Yes, the constructor implicitly returns the current instance of the class. You can't use an explicit return type with the constructor.

32. What are the rules for creating a Java constructor?

  • Constructor name must be the same as its class name
  • A Constructor must have no explicit return type
  • A Java constructor cannot be abstract, static, or final.
  • We can use access modifiers while declaring a constructor. It controls object creation. In other words, we can have private, protected, public, or default constructors in Java.
Java interview questions and answers

33. What is method overloading?

Method overloading allows us to create multiple methods with the same name but different signatures. It can be done in two ways - By changing the number of arguments or by changing the data type of arguments.

34. What is the final variable?

In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that.

final int speedlimit=90;

35. What is Exception Handling?

Exception Handling is a mechanism that is used to handle runtime errors. It is used primarily to handle checked exceptions. Exception handling maintains the normal flow of the program. There are mainly two types of exceptions: checked and unchecked.

36. Mention some reasons why Exceptions occur in Java.

  • Device failure
  • Loss of Network Connection
  • Code Errors
  • Opening an Unavailable file
  • Invalid User Input
  • Physical Limitations (out-of-disk memory)

37. How many types of exceptions can occur in a Java program?

Built-in Exceptions: Built-in exceptions in Java are provided by the Java Libraries. These exceptions can be further divided into two subcategories i.e., checked and unchecked Exceptions.

  • ArrayIndexOutOfBoundsExceptions
  • ClassNotFoundException
  • FileNotFoundException
  • IOException
  • NullPointerException
  • ArithmeticException
  • InterruptedException
  • RuntimeException

User-Defined Exceptions: User-defined exceptions are defined by the programmers themselves to handle some specific situations or errors that are not covered by built-in exceptions.

38. What is the difference between a Checked Exception and an Unchecked Exception?

Checked Exception - The classes that extend the Throwable class except RuntimeException and Error are known as checked exceptions, e.g., IOException, ClassNotFoundException. Checked exceptions are checked at compile-time.

Unchecked Exception - The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, etc. Unchecked exceptions are not checked at compile-time.

39. What is finally block?

The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not. In other words, we can say that finally block is the block that is always executed. Finally, the block follows the try or catch block.

40. Can a finally block be used without a catch?

Yes, finally block can be used without a catch but it must be followed by a try block then.

41. What is the purpose of the new keyword?

Java's new keyword is used to create new objects.

42. What are loops in java?

Loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition.

43. How to write a program in Java using a for loop?

public class ForLoopClass {  
	public static void main(String[] args) {  
 	//Code of Java for loop  
  	for(int i=1;i<=10;i++) {  
    System.out.println(i);   
}  }  }  

44. What is Nested For Loop? Write a program to demonstrate the example of a nested for loop.

If we have a “for loop” inside another “for loop”, it is known as a nested for loop. The inner loop executes completely whenever the outer loop executes.

public class NestedForLoop {  
public static void main(String[] args) {  
//loop of i  
for(int i=1;i<=3;i++){  
//loop of j  
for(int j=1;j<=3;j++){  
        System.out.println(i+" "+j);  
}//end of i  
}//end of j  
}  }  

45. What is the use of for-each loop in Java? Write its syntax.

The for-each loop is used to traverse an array or collection in Java. It provides a clear and concise way to iterate over each element making code less error-prone and more straightforward. Also, there’s no need to manage the index or determine the size of the array.

Syntax

for(data_type variable : array_name){    
//code to be executed    
}  

46. What are the limitations of each loop?

The for-each loop can move only forward. There is no way to iterate backward. As there is no access to the index, in situations where you need the index of an element, this loop is not suitable.

47. What is a Java switch statement? Write its syntax.

The Java switch statement executes one statement from multiple conditions. It is like an if-else-if ladder statement.

Syntax

switch(expression)
{    
case value1:    
 //code to be executed;    
 break;  //optional  
case value2:    
 //code to be executed;    
 break;  //optional  
default:     
  //code to be executed if all cases are not matched;  
}    

48. What are Jumping Statements in Java?

Jump statements are used to transfer the control of the program to the specific statements. In other words, jump statements transfer the execution control to the other part of the program. There are two types of jump statements in Java - break and continue.

49. What is a Java break statement?

The break statement is used to break the current flow of the program and transfer the control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program. It can only be written inside the loop or switch statement.

50. What is Java's continued statement?

Unlike the break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of the loop and jumps to the next iteration of the loop immediately.

not found

Become a Master in Your Chosen Field by Earning Advanced Skills

Best Learning, More Earning

Proleed Academy

Proleed serves / offers professionally designed IT training courses
globally.

Copyright © 2023 - Proleed Academy | All Rights Reserved.