Java Interview Questions for placement

Java Interview Questions for placement

21 January 2023

21 January 2023


Q1. Explain JVM, JRE and JDK?

Answer:

JVM (Java Virtual Machine): JVM(Java Virtual Machine) acts

as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in a Java code.

JVM is a part of JRE(Java Runtime Environment).

JRE (Java Runtime Environment): JRE refers to a runtime environment in which Java bytecode can be executed. It implements the JVM (Java Virtual Machine) and provides all the class libraries and other support files that JVM uses at runtime. So JRE is a software package that contains what is required to run a Java program. Basically, it’s an implementation of the JVM which physically exists.

JDK(Java Development Kit): It is the tool necessary to compile, document and package Java programs. The JDK completely includes JRE which contains tools for Java programmers. The Java Development Kit is provided free of charge. Along with JRE, it includes an interpreter/loader, a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development. In short, it contains JRE + development tools.


Q2. Explain public static void main(String args[]).

Answer:

Public: Public is an access modifier. Public means that this Method will be accessible by any Class.

Static : It is a keyword in java which identifies it is class-based i.e it can be accessed without creating the instance of a Class. Since we want the main method to be executed without any instance also, we use static.

Void: It is the return type of the method. Void defines the method which will not return any value.

Main: This is the first method executed by JVM. The signature of the method must be the same.


Q3. Why Java is platform independent?

Answer: Platform independent practically means “write once run anywhere”. Java is called so because of its byte codes which can run on any system irrespective of its underlying operating system.


Q4. Why is Java not pure Object-oriented?

Answer: Java is not considered pure Object-oriented because it supports primitive data-types such as boolean, byte, char, int, float, double, long, short.


Q5. Define class and object. Explain them with an example using java.

Answer: 

Class: A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:

Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.

Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.

Object: It is a basic unit of Object Oriented Programming and represents the real-life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of:

State: It is represented by attributes of an object. It also reflects the properties of an object.

Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects.

Identity: It gives a unique name to an object and enables one object to interact with other objects.

 

For Example: Employee is an example of a class A specific employee with unique identification is an example of an object. class Employee { // instance variables declaration // Methods definition } An object of employee is a specific employee Employee empObj = new Employee(); One of the objects of Employee is referred by ‘empObj’


Q6. What is a method? Provide several signatures of the methods

Answer: A Java method is a set of statements to perform a task. A method is placed in a class.

Signatures of methods: The name of the method, return type and the number of parameters comprise the method signature. A method can have the following elements in its signature: – Access specifier – public, private, protected, etc. (Not mandatory) – Access modifier – static, synchronized, etc. (Not mandatory) – Return type – void, int, String, etc. (Mandatory) – Method name – show() (Mandatory) – With or without parameters – (int number, String name); (parenthesis are mandatory)

Example: filter_none brightness_4 class Test { void fun1() {} public double fun2(double x) {} public static void fun3() {} public static void fun4(String x) {} }


Q7. Explain the difference between instance variable and a class variable.

Answer: An instance variable is a variable which has one copy per object/instance. That means every object will have one copy of it. A class variable is a variable which has one copy per class. The class variables will not have a copy in the object.

Example : filter_none brightness_4 class Employee { int empNo; String empName, department; double salary; static int officePhone; } An object referred by empObj1 is created by using the following: Employee empObj1 = new Employee(); The objects referred by instance variables empObj1 and empObj2 have separate copies empNo, empName, department, and salary. However, the officePhone belongs to the class(Class Variable) and can be accessed as Employee.officePhone.


Q8. Which class is the superclass of all classes?

Answer: java.lang.Object is the root class for all the java classes and we don’t need to extend it.


Q9. What are constructors in Java?

Answer: In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor. This default constructor calls the class parent’s no-argument constructor (as it contains only one statement i.e. super();), or the Object class constructor if the class has no other parent (as Object class is a parent of all classes either directly or indirectly).

There are two types of constructors:

  • Default constructor
  • Parametrized constructor

Q10. What’s the purpose of Static methods and static variables?

Answer: When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keyword to make a method or variable shared for all objects.

Static variable: Static variables are also known as Class variables. These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block. Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create. Static variables are created at the start of program execution and destroyed automatically when execution ends. To access static variables, we need not create an object of that class.

Static methods: A static method can be accessed without creating objects. Just by using the Class name the method can be accessed. The static method can only access static variables and not local or global non-static variables.

For Example: filter_none brightness_4 public class StaticMethod { public static void printMe() { System.out.println("Static Method access directly by class name!"); } } public class MainClass { public static void main(String args[]) { StaticMethod.printMe(); } }


Q11. Why static methods cannot access non-static variables or methods?

Answer: A static method cannot access non-static variables or methods because static methods can be accessed without instantiating the class, so if the class is not instantiated the variables are not initialized and thus cannot be accessed from a static method.


Q12. What is a static class?

Answer: A class can be said to be static class if all the variables and methods of the class are static and the constructor is private. Making the constructor private will prevent the class to be instantiated. So the only possibility to access is using the Class name only.


Q13. How many types of Variable? Explain.

There are three types of variables in Java:

  1. Local Variables
  2. Instance Variables
  3. Static Variables

Local Variables: A variable defined within a block or method or constructor is called local variable.

These variable are created when the block is entered or the function is called and destroyed after exiting from the block or when the call returns from the function.

The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variables only within that block.

filter_none edit play_arrow brightness_4

// Java program to demonstrate local variables public class LocalVariable

{

public void getLocalVarValue()

{

// local variable age int localVar = 0;

localVar = localVar + 11; System.out.println("value of local variable" +

" is: " + localVar);

}

public static void main(String args[])

{

LocalVariable obj = new LocalVariable(); obj.getLocalVarValue();

}

}

Output:

value of local variable is: 11

In the above program the variable localVar is local variable to the function getLocalVarValue(). If we use the variable localVar outside getLocalVarValue() function, the compiler will produce an error as “Cannot find the symbol localVar”.

 

Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor or block.

As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.

Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.

 

filter_none edit play_arrow brightness_4

// Java program to demonstrate instance variables public class InstanceVariable {

int instanceVarId;

String instanceVarName;

public static void main(String args[])

{

InstanceVariable obj = new InstanceVariable(); obj.instanceVarId = 0001; obj.instanceVarName = "InstanceVariable1"; System.out.println("Displaying first Object:");

System.out.println("instanceVarId==" + obj.instanceVarId);

System.out.println("instanceVarName==" + obj.instanceVarName);

InstanceVariable obj1 = new InstanceVariable(); obj1.instanceVarId = 0002; obj1.instanceVarName = "InstanceVariable2"; System.out.println("Displaying Second Object:");

System.out.println("instanceVarId==" +

obj1.instanceVarId);

System.out.println("instanceVarName==" + obj1.instanceVarName);

}

}

Output:

Displaying first Object: instanceVarId==1 instanceVarName==InstanceVariable1 Displaying Second Object: instanceVarId==2 instanceVarName==InstanceVariable2

In the above program the variables i.e. instanceVarId, instanceVarName are instance variables. In case we have multiple objects as in the above program, each object will have its own copies of instance variables. It is clear from the above output that each object will have its own copy of the instance variable.

 

Static variable: Static variables are also known as Class variables.

  • These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
  • Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
  • Static variables are created at start of program execution and destroyed automatically when execution ends.

To access static variables, we need not create an object of that class, we can simply access the variable as:

filter_none edit play_arrow brightness_4

// Java program to demonstrate static variables public class StaticVar {

private static int count = 0; private int nonStaticCount = 0; public void incrementCounter()

{

count++; nonStaticCount++;

}

public static int getStaticCount()

{

return count;

}

public int getNonStaticCount()

{

return nonStaticCount;

}

public static void main(String args[])

{

StaticVar stVarObj1 = new StaticVar();

StaticVar stVarObj2 = new StaticVar(); stVarObj1.incrementCounter(); stVarObj2.incrementCounter(); System.out.println("Static count for stVarObj1: " +

stVarObj1.getStaticCount()); System.out.println("NonStatic count for stVarObj1: " +

stVarObj1.getNonStaticCount()); System.out.println("Static count for stVarObj2: " +

stVarObj2.getStaticCount()); System.out.println("NonStatic count for stVarObj2: " +

stVarObj2.getNonStaticCount());

}

}

 

Output: Static count for stVarObj1: 2 NonStatic count for stVarObj1: 1 Static count for stVarObj2: 2 NonStatic count for stVarObj2: 1

In the above program stVarObj1 and stVarObj2 share the same instance of static variable count hence if the value is incremented by one object, the incremented value will be reflected for stVarObj1 and stVarObj2.


Q.14. What is the difference between an Interface and an Abstract class?

Answer: An interface only declares the method signatures while an abstract class can have method signatures as well as method implementations.


Q.15. What is the difference between a constructor and a method?

Answer: A constructor is a special method that is used to initialize an object while a method is a regular function that performs a specific task.


Q.16. What is the difference between == and .equals() method in Java?

Answer: The == operator is used to compare the memory address of two objects while the .equals() method is used to compare the values of two objects.


Q.17. What is the difference between a static and non-static method?

Answer: A static method belongs to the class and can be called without creating an instance of the class while a non-static method belongs to an object of a class and can only be called after creating an instance of the class.


Q.18.What is the difference between a static and non-static variable?

Answer: A static variable belongs to the class and can be accessed without creating an instance of the class while a non-static variable belongs to an object of a class and can only be accessed after creating an instance of the class.


Q.19. What is the difference between a final and a static final variable?

Answer: A final variable is a constant that cannot be reassigned while a static final variable is a constant that belongs to the class and cannot be reassigned.


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

Answer: A while loop checks the condition before executing the loop while a do-while loop executes the loop at least once and then checks the condition.


Q.21. What is the difference between an Array and an ArrayList?

Answer: An array is a fixed-size data structure while an ArrayList is a dynamic data structure that can grow and shrink in size.


Q.22. What is the difference between a HashMap and a Hashtable?

Answer: A HashMap is not thread-safe while a Hashtable is thread-safe. Additionally, HashMap allows null keys and values while Hashtable does not.


Q.23. What is the difference between a String and a StringBuffer?

Answer: A String is an immutable object while a StringBuffer is a mutable object.


Q.24. What is the difference between a StringBuilder and a StringBuffer?

Answer: A StringBuilder is similar to a StringBuffer but it is not thread-safe.


Q.25. What is the difference between a Set and a List?

Answer: A Set is an unordered collection that does not allow duplicate elements while a List is an ordered collection that allows duplicate elements.


Q.26. What is the difference between a LinkedList and an ArrayList?

Answer: A LinkedList is implemented using a linked data structure while an ArrayList is implemented using an array data structure.


Q.27. What is the difference between a TreeSet and a HashSet?

Answer: A TreeSet is a sorted set while a HashSet is an unsorted set.


Q.28. What is the difference between a Queue and a Stack?

Answer: A Queue follows the FIFO (First In First Out) principle while a Stack follows the LIFO (Last In First Out) principle.


Q.29. What is the difference between a try-catch and a try-catch-finally block?

Answer: A try-catch block is used to catch and handle an exception while a try-catch-finally block is used to catch, handle and finally execute a block of code after the try-catch block.


Q.30. What is the difference between a throw and a throws keyword?

Answer: The throw keyword is used to throw an exception while


Ask Us Anything !