Javatpoint Logo
Javatpoint Logo

Java Interview Questions for Freshers

In this tutorial, we are going to discuss the interview questions for the freshers' candidates. These interview questions are helpful in cracking the technical rounds of the Java interviews.

1) Discuss JVM, JRE, JDK

JVM (Java Virtual Machine): JVM acts as a run-time engine for running Java applications. It is the JVM that invokes the main method. JVM is the part of JRE(Java Runtime Environment).

JRE (Java Runtime Environment): JRE is the runtime environment in which bytecode can be executed. It does the implementation of the JVM (Java Virtual Machine) and facilitates all of the class libraries and other support files that JVM uses at runtime. So JRE is the software package that fulfills the requirement of what is required in order to run/execute a Java program.

JDK(Java Development Kit): It is the tool that is required for the compilation, documentation, and packaging of 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.


2) Discuss public static void main(String args[])

public: Public is an access modifier. Any Class will be able to access this main method because it is public.

static: It is a Java keyword that denotes a class-based object as one that may be accessed without first generating an instance of a Class. We use static because we want the main() method to run without any instances as well.

void: It is the return type of the main method. Void states that the main() method will not return any value.

main: It is the name of the method, which is main() in our case. It is the first method executed by JVM.


3) Define class and object. Explain them with an example using Java.

Class: A user-defined class serves as a template or prototype from which objects can be built. It stands for the collection of attributes or operations that are shared by all objects of a particular type. In general, these elements can be found in the following sequence in class declarations.

Object: It is a basic unit of Object-Oriented Programming and represents 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 an object's characteristics. Additionally, it reflects an object's characteristics.

Behavior: It is represented by the methods of an object. It is represented via an object's methods. It also shows how one object interacts with other objects.

Identity: It provides a thing with a special name and makes it possible for one object to communicate with another.

For Example, a student is an example of a class. A specific student with a unique identification is an example of an object.

One of the objects of Student is referred to as 'studObj'


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

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

Signatures of methods: The method's name, 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)


5) Why is Java not purely Object-oriented?

It is because the language supports primitive data types like boolean, byte, char, int, float, double, long, and short. Hence, Java is not regarded as being entirely object-oriented.


6) Explain the difference between an instance variable and a class variable.

A variable that is unique to each object or instance is known as an instance variable. This implies that each thing will only exist once. A variable with one copy per class is referred to as a class variable. There won't be a duplicate of the class variables in the object.


7) What are constructors in Java?

A constructor is a section of code that is used to initialize an object in Java. It has to be given the same name as the class. Additionally, it is automatically invoked when an object is created and has no return type.

The Java compiler automatically produces a no-argument constructor, often known as the default constructor, if a class does not explicitly define any.

When a class has no other parents, the default constructor invokes the class parent's no-argument constructor (because it only has one statement, super()); or the Object class constructor (since the Object class is either a direct or indirect parent of all classes).

There are two types of constructors:

  1. Parameterized constructor
  2. Default constructor

8) What are the different ways to create objects in Java?

The following are the different ways for the creation of objects in Java.

  • Using new keyword
  • Using new instance
  • Using clone() method
  • Using deserialization
  • Using the newInstance() method of the Constructor class

9) What's the purpose of Static methods and static variables?

We utilize static keywords to make a method or variable shared for all objects when it is necessary to share them across many objects of a class rather than create separate copies for each object.

Static variable: Another name for a static variable is a class variable.

These variables are declared in a manner similar to instance variables, with the exception that static variables are declared in a class outside of any method constructor or block using the static keyword.

No of how many objects we generate, we are only allowed to have one instance of a static variable per class.

Static variables are generated at the beginning of program execution and immediately removed at its conclusion.

We don't need to build an object of that class in order to access static variables.

Static techniques: You can call a static method without constructing any objects. The method may be accessed simply by typing in the Class name. Only static variables, not local or global non-static variables, may be accessed using the static method.

Filename: ClassMain.java

Output:

Static Method can be accessed directly using the class name!

10) Why can static methods not access non-static variables or methods?

It is because static methods may be used without instantiating the class. If the class is not instantiated, the variables are not initialized and cannot be accessible from a static method. Therefore, a static method cannot access non-static variables or methods.


11) What is a static class?

If all of the variables of the class and methods are static and the constructor is private, the class is said to be a static class. The class cannot be instantiated if the constructor is made private. Thus, the Class name is the sole way to gain access.


12) Discuss in Detail About the Types of Variables in Java.

The following are the types of variables in Java:

  • Local Variables
  • Instance Variables
  • Static Variables

Local Variables: When a variable is defined within a method or block, or constructor, then that variable is known as the local variable. These variables come into the picture when the control enters the method or block. The local variables get destroyed after exiting from the block or when the control returns from the method. The scope of these local variables exists only within the block in which the variable is declared. i.e., we can access these variables only within that block. We can never use the access specifier for the local variables.

Filename: LocVariable.java

Output:

The value of the local variable is: 1

Explanation: In the above program, the locVar variable is the local variable to the method getLocalVariableValue(). If we use the variable locVar outside the getLocalVariableValue() method, the compiler produces an error. The following program shows the same.

Filename: LocVariable1.java

Output:

/LocVariable1.java:14: error: cannot find symbol
     System.out.println("Accessing the local variable outside of the method" + locVar);
                                                                               ^
  symbol:   variable locVar
  location: class LocVariable1
1 error

Instance Variables: Non-static variables are instance variables. These variables are declared in a class outside any constructor, method, or block. Since the instance variables are declared inside a class, these variables come into the picture when the class is instantiated. When the objects of the class are destroyed, these variables are also destroyed. Unlike the local variables, we can apply the access specifiers to the instance variables. When one does not apply the access specifier, the default access specifier is used.

Filename: VariableInstance.java

Output:

Displaying the first object: 
instanceVarId = 1
instanceVarName = InstVariable1
Displaying the second object: 
instanceVarId = 2
instanceVarName = InstVariable2

In the above-mentioned program, the instance variables are instVarId, and instVarName. In the program, two objects are created, and each object will have its own copy of the instance variables. In the above program, each object will have its own copies of instance variables, and the same is reflected in the output too.

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

  • Static variables are also declared in a similar fashion as the instance variables. The difference is that instance variables do not come with the static keyword. In contrast, the static variables are declared with the static keyword inside a class and outside any block or constructor.
  • Unlike the instance variables, there is only one copy of the static variables, no matter how many objects we create of that class.
  • Static variables are created at the beginning of the program execution and get automatically destroyed when the execution ends.

To access the static variables, one does not need to create an object of that class. The static variables can be accessed using the class names. Static keyword plays a key role in the implementation of the singleton design pattern. The illustration of it is shown in the following program.

Filename: VarStatic.java

Output:

Static count for the object stVarOb1: 2
NonStatic count for the object stVarOb1: 1
Static count for the object stVarOb2: 2
NonStatic count for the object stVarOb2: 1

In the above-mentioned program, stVarOb1 and stVarOb2 share the same instance of the static variable cnt. Therefore, if the value gets incremented by any one of the objects, the incremented value gets reflected on both of the objects stVarObj1 and stVarObj2. It is because only copies of the static variables are available.


13) Distinguish between the HashMap and HashTable in Java.

Observe the following differences between the HashTable and HashMap.

HashTable is synchronized, and hence, it is thread-safe and can easily be shared with many threads. On the other hand, the HashMap is not synchronized and is not thread-safe, and hence, can not be shared (without any synchronization code) among many threads.

HashTable does not allow any null value or key, whereas HashMap allows multiple null values and one null key.

HashTable is generally not preferred over HashMap if the synchronization of thread synchronization is needed.

Refer to HashTable and HashMap for more details.


14) Is the overloading of the main() method possible in Java?

Yes, we can overload the main() method in Java. The way we overload the other methods is also the way of overloading the main() method. For launching the program, the JVM (Java Virtual Machine) looks for the signature of the method. It is the normal main() method that acts as the entry point of the program and is invoked by the JVM. The overloaded main() method has to be invoked explicitly. Observe the following.

Filename: OverloadMain.java

Output:

Main method with the array of String as the argument.
Main method with integer as the argument.

We see that the overloaded main() method with int as the argument has been called explicitly.


15) Explain Synchronization in Java.

Synchronization ensures that only one block of code is accessed at a time. There is a risk for erroneous results to be produced at the end if numerous threads access the same block of code. We can offer synchronization for the delicate block of codes to get around this problem. A thread requires a key to access synchronized code, as indicated by the term "synchronized." All Java objects have locks. A lock has only one key. A thread can access a synchronous method only if it can obtain the key of the object being locked. Locking is done on a per-object basis.


16) What is the meaning of Collections in Java?

Collections is a framework designed for storing objects and editing themes for storing objects.

The following operations can be performed using collections.

  • Sorting
  • Searching
  • Insertion
  • Manipulation
  • Deletion

A group of objects is called a collection. All interfaces and classes for the collection are available in the java.util package.


17) Mention About the Disadvantages of Synchronization.

Synchronization is not recommended for the implementation of all of the methods. It is because one of the threads accesses the synchronized code, and then the next thread must have to wait. Hence, it leads to a slow performance on the other end.


18) In Java, pointers are not used. Why?

The pointers are not used in Java because they are increase the complexity of the program and they are unsafe too. Since simplicity is one of the most popular features of the Java language, adding the concept related to pointers is contradicting to the simplicity of the language. Also, in Java, it is the responsibility of the JVM for the implicit memory allocation. Thus, in order to avoid the direct access of the memory by the user, pointers are discouraged in Java.


19) What is the Inheritance?

Inheritance is the mechanism using which one object can inherit all of the characteristics and actions of another object belonging to a different class. It is utilized for code reusability and method overriding. The concept of inheritance in Java is that new classes may be constructed on top of older ones. One can utilize the parent class's properties and methods when one inherits from the existing class. One may also add the methods and additional fields to the existing class. The parent-child connection, also known as the IS-A relationship, is represented through inheritance.

The following are the five different types of inheritance in Java.

  • Single-level inheritance
  • Multiple Inheritance (Using the Java Interfaces)
  • Multi-level inheritance
  • Hybrid Inheritance
  • Hierarchical Inheritance

20) How is an Interface different from an Abstract class?

There are various differences between an Interfaces and an Abstract class in Java.

Constituents - Interface can only contain constants, whereas an abstract class contains instance variables.

Constructor and Instantiation - An abstract class may contain a default constructor, which is invoked when the object of the subclass is created, whereas an interface never contains a constructor, and it is also not possible to create an object of an interface.

Implementation of Methods - All of the classes that do the implementation of an interface are required to provide the implementation for all the methods that are present in that interface. However, a class that extends the abstract class does not require to do the implementation of all of the methods that are present in the abstract class. Only the implementation of the abstract methods present in the abstract class is required.

Methods Types - An abstract class has both: non-abstract as well as abstract methods. On the other hand, in the case of interfaces, we see only abstract methods.


21) Explain the lifecycle of a thread in Java?

The lifecycle of a thread has the following states and follows the following order:

New - In the life cycle of a thread, it is the first state. The instance of the thread is created, and the method start() is not invoked yet. Now, the thread is considered to be alive.

Runnable - After calling the method start(), but before calling the method run(), a thread is said to be in the state of runnable. A thread may also go back to the runnable state from the sleeping or waiting state.

Running - When the thread enters the state of running after the method run() is invoked. It is when the execution of the thread starts.

Non-Runnable - Even though the thread is alive, it is not apt to run. Typically, it goes back to the state of runnable after some time.

Terminated - When the method run() does the completion of its execution, the thread enters the terminated state. Now, the thread is not alive now.


22) Distinguish between the Stack and Heap memory.

Stack Memory:

  • It is used to keep the local variables and the order of execution of methods.
  • When the memory of the stack gets filled then it returns the java.lan.StackOverFlowError.
  • Accessing the stack memory is faster than accessing the memory as compared to the heap.
  • Methods that are currently running utilize the stack space.

Heap Memory:

  • For storing objects, heap memory is used.
  • When the heap memory gets filled, then it returns java.lang.OutOfMemoryError.
  • Accessing the heap memory is slower as compared to accessing the stack memory.
  • Throughout the applications, heap space is used.

23) Can one modify the throws clause of the superclass method while overriding it in the subclass?

Yes, one can do the modification of the throws clause of the superclass method while overriding it in the subclass. But there are some rules that needs to be taken into consideration while overriding in the case of exception handling.

  • If the methods of the superclass do not declare an exception, then the overridden method of the subclass can not make the declaration of the checked expectation, but it can make the declaration of the unchecked exceptions.
  • If the method of the superclass makes the exception declaration, then the overridden method of the subclass can make the declaration of the same subclass exception or no exception but can not make the declaration of the parent exception.

24) Is it possible to change the scope of methods that are overridden in the subclass?

Yes, one is allowed to do the change scope of those methods that are overridden in the subclass in Java. However, it should be noted that one can not reduce the method accessibility. The following points should be taken into consideration while changing the method accessibility.

  • The private access specifier can be changed to public, protected, or default.
  • The protected access specifier can be changed to default or public.
  • The default access specifier can be changed to public.
  • The public access specifier can not be changed to any other access specifier. It will always remain public.

25) What are the benefits of passing 'this' into a method in lieu of the object of the current class itself?

We know that 'this' is referred to the object of the current class. Hence, it should be similar to the objects of the current class. However, there are two main benefits of passing "this" in lieu of the object of the current class.

  1. 'this' is a final variable. Hence, 'this' can not be assigned to any new value, whereas the object of the current class may not be final, and it can be changed.
  2. In the synchronized block, 'this' can be used.




You may also like:


Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA