0% found this document useful (0 votes)
21 views

101 Important Java Interview Questions For Freshers

The document provides contact details for various locations of a training academy and then discusses 11 frequently asked Java interview questions for freshers, providing explanations and code examples for each. The questions cover topics like access specifiers, subclasses vs inner classes, encapsulation, static methods, loops, the singleton pattern, break vs continue statements, infinite loops, the final keyword, differences between float and double, random number generation, and the ternary operator.

Uploaded by

bodimeg919
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

101 Important Java Interview Questions For Freshers

The document provides contact details for various locations of a training academy and then discusses 11 frequently asked Java interview questions for freshers, providing explanations and code examples for each. The questions cover topics like access specifiers, subclasses vs inner classes, encapsulation, static methods, loops, the singleton pattern, break vs continue statements, infinite loops, the final keyword, differences between float and double, random number generation, and the ternary operator.

Uploaded by

bodimeg919
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

 Chennai, Bangalore & Online: 93450 45466Coimbatore: 95978 88270Madurai: 97900

94102Pondicherry: 93635 21112

Courses
 Corporate Training
 For Business
 Testimonials
 Resources
 Contact Us
101 Important Java Interview Questions for
Freshers

Java is a platform and programming language. It tops the list of all programming languages
and offers a variety of Job options. The purpose of the understanding Java Interview
Questions for Freshers is to familiarise you with the types of questions you might be
asked during your interviews for the Java related interviews. Java Training in
Chennai at FITA Academy is the ideal setting for you to explore your profession If
you’re curious in learning the language.

1. What various access specifiers are there for Java


classes?
The terms used prior to a class name in Java that correspond to the access scope are
considered to be access classifiers.

Public available from anywhere; a field, method, or class.

When a field or method is protected, it can only be accessed within the class to which it
belongs, from subclasses, and within the same package class.

By default, only code from the same package—not code from outside the native package—
can access a class’s field or method.

The method is accessible from the same class to which it belongs via the private: field.

2. What is the difference between a Subclass and an Inner


class?
inner class

A class that is defined inside another class is known as an inner class.

It has access rights to the class that contains it, which means it can access all the outer class,
there are variables and methods declared.

subclass

A subclass, also known as a derived class, inherits from a superclass. It has access to every
superclass’s protected and open fields and methods.

Sample code demonstrating an inner class and subclass relationship:


public class OuterClass {
private int outerVariable;
public void outerMethod() {
System.out.println("This is the outer method");
}
public class InnerClass {
public void innerMethod() {
outerVariable = 10; // Accessing the outer variable
outerMethod(); // Accessing the outer method
System.out.println("This is the inner method");
}
}
}
public class SubClass extends SuperClass {
public void subClassMethod() {
protectedField = 20; // Accessing the protected field of the
superclass
publicMethod(); // Accessing the public method of the superclass
System.out.println("This is the subclass method");
}
}
// Usage of the inner class and subclass
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.innerMethod();
SubClass subObject = new SubClass();
subObject.subClassMethod();

3. What is data encapsulation and what is its significance?


Encapsulation is a type of question which is asked frequently in most Core
Java Interview Questions for Freshers.
A key idea in object-oriented programming is encapsulation, which entails grouping related
functions and properties into a single unit. It enables a modular approach to software
development, where each object has its own unique set of variables and methods,
functioning independently of other objects. Encapsulation is used for the purpose of data
hiding, providing control over the accessibility of data within an object.

Sample code demonstrating data encapsulation:

public class Person {


private String name;
private int age;
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
public void setAge(int newAge) {
age = newAge;
}
public int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(25);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
4. What do static methods and variables accomplish?
Static variables and static methods serve the purpose of sharing a variable or a
methodinstead of making unique copies for every item, divide one object of a class across
several others. By declaring a method or variable as static, it becomes shared and can be
accessed directly through the class itself rather than through an instance of the class. This
allows for efficient memory utilization and enables convenient access to common resources
or operations that are not specific to individual object instances.

5. What do Java loops do? Which three types of loops are


there?
These are the Java Basic Interview Questions to know mandatorily before attending any
interviews

Loops in Java are used to repeatedly execute a statement or a block of statements. the below
given are 3 types of loops in Java:

For Loops:
For loop are used to execute statements for a specified number of times. They are
commonly used when the number of iterations is known in advance.

While Loops:
When it is necessary to execute statements repeatedly While loops are used until a specific
condition is fulfilled. This type of condition is evaluated before the execution of the
statements.

Do-While Loops:
Do-while loops are similar to while loops, but with one difference: the condition is
evaluated after the execution of the statement block. By doing this, even if the condition is
initially false, it is ensured that the assertions are carried out at least once.

6. What is a Singleton Class? Can you provide an example?


In Java, a singleton class is a class that can have only one instance, and that single instance
alone owns all of its variables and methods. The singleton class pattern is used in situations
where there is a need to restrict the number of objects created for a class.

An example of using a singleton is when there is a requirement to havea single connection


to a database only because of driver or licencing restrictions.

public class DatabaseConnection {


private static DatabaseConnection instance;
private DatabaseConnection() {
// Private constructor to prevent direct instantiation
}
public static DatabaseConnection getInstance() {
if (instance == null) {
instance = new DatabaseConnection();
}
return instance;
}
public void connect() {
System.out.println("Connected to the database");
}
}
public class Main {
public static void main(String[] args) {
DatabaseConnection connection = DatabaseConnection.getInstance();
connection.connect();
}
}

7. Describe the distinctions between the “break” and


“continue” statements
The “break” and “continue” statements are key concepts used in loops. Providing examples
during Java interviews for freshers can help illustrate these concepts.

When a loop is discovered, the “break” command is used to end it instantly. It completely
exits the loop, regardless of the loop condition. For example:

for (int counter = 0; counter < 10; counter++) {


System.out.println(counter);
if (counter == 4) {
break;
}
}

The “continue” statement, on the other hand, is utilised to skip the current iteration of a
loop and move on to the subsequent iteration. It allows the loop to continue its execution.
For example:

for (int counter = 0; counter < 10; counter++) {


System.out.println(counter);
if (counter == 4) {
continue;
}
System.out.println("This will not be printed when counter is 4");
}

Using these statements provides control over loop execution, allowing for specific
conditions to be met for termination or skipping of iterations.

8.What is an infinite loop? How is an infinite loop declared?


An infinite loop is a loop which runs indefinitely without any condition to terminate it. To
break out of an infinite loop, a breaking logic or condition must be included within the
loop’s statement block.
An infinite loop can be declared as follows:

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

9. What is the “final” keyword in Java used for? Can you


provide an example?
Constant declaration in Java requires the usage of the “final” keyword. A final variable’s
value cannot be altered once it has been assigned.

Here’s an example of declaring a constant named const_val:

private final int const_val = 100;

Additionally, the “final” keyword has other uses in Java.When a method is marked as final,
subclasses cannot override it. Final methods are resolved at compile-time, making them
faster compared to other methods.

This is an important topic which is asked in Java Interview Questions for Freshers.

10. What are the Java float and double variables’


differences?
In Java, the float and double variables differ in their precision and memory size.

The float variable represents a single-precision floating-point decimal number and


typically occupies 4 bytes of memory. It offers less precision compared to double.

On the other hand, the double variable represents a double-precision decimal number and
usually occupies 8 bytes of memory. It provides higher precision and a larger range of
values compared to float.
You can brush up on your knowledge and succeed in your interview with the help of
these Java Interview Questions for freshers.

11. How can you generate random numbers in Java?


In Java, there are several methods for producing random numbers. One approach is by
using the Math.random() method, which generates random double values between 0.0
(inclusive) and 1.0 (exclusive). To obtain random numbers within a specific range, you can
multiply the result of Math.random() by the desired range and add an offset value.

double randomValue = Math.random(); // Generates random value between


0.0 and 1.0
double scaledValue = randomValue * (max - min) + min; // Generates
random value within a specific range

12. What is a ternary operator? Can you provide an


example?
The conditional operator, commonly referred to as the ternary operator, is used to make
decisions and assign a value to a variable based on the evaluation of a Boolean expression.

public class ConditionTest {


public static void main(String[] args) {
String status;
int rank = 3;
status = (rank == 1) ? "Done" : "Pending";
System.out.println(status);
}
}

The ternary operator is a concise way to make decisions and assign values based on
conditions in Java.

13. What is the Java basic class that all other classes are
descended from?
The Java foundation class, which all other classes are descended from is java.lang.Object.
14.What is a default case in a switch statement? Can you
provide an example?
The default case is used in a switch statement when none of the other switch conditions
match. It acts as an optional case that is executed when no other cases are satisfied.

The default case should be placed after all the other cases have been coded within the
switch statement.

public class SwitchExample {


public static void main(String[] args) {
int score = 4;
switch (score) {
case 1:
System.out.println("Score is 1");
break;
case 2:
System.out.println("Score is 2");
break;
default:
System.out.println("Default Case");
}
}
}

The default case provides a fallback option when none of the other cases match in a switch
statement.

15. What are Java packages? What is the significance of


packages?
Packages are a way to organise code in Java and group related classes, interfaces, and other
code elements together. They allow developers to modularize their code, making it easier
to manage and reuse.
Packages contain a collection of classes and interfaces that are logically related to each
other. By organizing code into packages, developers can improve code organization and
maintainability.

One of the significant benefits of using packages is the ability to control access to classes
and encapsulate code within a specific namespace. This helps prevent naming conflicts and
provides a clear boundary for accessing code from other packages.

Packages also facilitate code reuse by allowing the importation of classes and resources
from other packages. This means that once code is packaged in a particular package, it can
be easily imported into other classes and used without duplicating the code.

One of the Core Java Interview Questions that is regularly asked is this one.

16. Does the main() method in Java return any data?


The main() method in Java does not return any data.As a result, a void return type is always
stated when it is used.

17.Explain the difference between an Interface and an


Abstract Class in Java.
In Java, the following is the main difference between an abstract class and an interface:

Interface:

An interface can only declare public static method signatures without providing their
concrete implementation. It serves as a contract for classes that implement it, ensuring that
they define the specified methods. Interfaces can also declare constants and can be
implemented by multiple classes.

Abstract Class:

An abstract class can have members with various access specifiers (private, public, etc.)
and can include both abstract and concrete methods. It can provide partial implementation
of methods. Abstract classes are designed to be extended by subclasses, which are then
responsible for implementing any abstract methods defined by the abstract class.

18. Is it possible to declare a class as an Abstract class


without having any abstract methods?
Yes, it is possible to use the abstract keyword before the class name to create an abstract
class, even if it doesn’t contain any abstract methods. However, if a class contains at least
one abstract method, it must be declared as an abstract class, otherwise it will result in an
error.

19. Does importing a package also import its sub-packages


in Java?
No, when a package is imported in Java, its sub-packages are not automatically imported.
If the developer wants to use classes from the sub-packages, they need to import them
separately.

For example, if a developer imports the package university.*, it will load all the classes
from the university package, but it will not load classes from its sub-packages. To access
classes from a sub-package, the developer needs to explicitly import them, like this:

import university.department.*;

This is one of the Java Basic Interview Questions to know before attending an interview.

20. What are the performance implications of interfaces


compared to abstract classes?
Interfaces are generally considered to have slightly slower performance than abstract
classes due to the additional indirections required for interfaces. Another important
consideration for developers is that a class can only extend a single abstract class, while it
can implement multiple interfaces.
Using interfaces also imposes an additional responsibility on developers. When a class
implements an interface, the developer is obligated to implement all the methods defined
in that interface.

21. Constant declaration in Java requires the usage of the


“final” keyword. A final variable’s value cannot be altered
once it has been assigned.
In Java, it is not possible to pass arguments to a function by reference. Java only supports
passing arguments by value, where a copy of the value is passed to the function. This means
the original variable outside of the function is unaffected by changes made to the parameter
inside the function.

In contrast to certain other programming languages such as C++, Java does not provide
direct support for passing arguments by reference.

One of the significant and typical Java Interview Questions is this one.

22. Is it possible to declare the main method of a class as


private?
No, the main method should be declared as public static in order to run applications
correctly in Java. If the main method is declared as private, it will compile without any
errors. However, it will not be executed and will result in a runtime error.

23.When should we use serialization?


Serialization is commonly used when there is a need to transmit data over a network. By
using serialization, the state of an object can be converted and saved into a byte stream.
This byte stream can then be transferred through the network, and the object can be
reconstructed at the destination. Serialization is particularly useful when working with
distributed systems, client-server communication, or when storing objects persistently.

24. How does Java serialise an object?


In Java, an object can be serialized by implementing the Serializable interface. By
implementing this interface, the class is enabled to convert its objects into a byte stream
through serialization. When a class implements the Serializable interface, most of its
objects can be serialized, and their state can be stored in the byte stream. This allows the
object to be easily transmitted or stored persistently.

You can advance in your chosen career with the aid of these Java Questions and Answers.

25. Is there a way to skip the finally block even if an


exception occurs within the catch block?
In Java, the finally block is always carried out regardless of whether an exception occurs
or not. It is not possible to directly skip the finally block based on an exception in the catch
block.

However, if you want to terminate the program forcefully and avoid executing any
statements in the finally block, you can use the System.exit(0) code line at the end of the
try block. This will abruptly terminate the program and prevent the execution of subsequent
code, including the finally block. It’s important to note that using System.exit(0) should be
done with caution, as it terminates the entire Java program abruptly.

26. Does Java’s Try block have to be followed by a Catch


block in order to handle exceptions?
In Java, a Try block must be followed by either a Catch block, a Finally block, or both.
Whenever an exception is raised inside the Try block, it needs to be caught and handled in
the Catch block. Alternatively, specific tasks that need to be executed before the
termination of the code can be placed in the Finally block.

The Catch block allows for catching and handling specific exceptions, providing an
opportunity to handle exceptions gracefully or perform error logging. Code that must
always be run is specified regardless of whether an exception happens or not, in the Finally
block. It is typically used for tasks such as closing resources or releasing acquired locks.

27. Can a class have multiple constructors?


Yes, a class may have several constructors with various inputs. The constructor that gets
used for object creation depends on the arguments passed during the instantiation of the
object. This allows flexibility in creating objects with different initializations based on the
constructor used.

With the aid of these Java Interview Questions for Freshers, so that you may increase
your knowledge and succeed in your interview.

28. When is the class constructor invoked?


The class constructor is invoked every time an object is created using the new keyword.

For example, in the following class, the constructor is invoked twice when two objects are
created using the new keyword:

public class ConstExample {


ConstExample() { }
public static void main(String args[]) {
ConstExample c1 = new ConstExample();
ConstExample c2 = new ConstExample();
}
}

29. In the following example, what can be the output?

public class Superclass {


public void displayResult() {
System.out.println("Printing from superclass");
}
}
public class Subclass extends Superclass {
public void displayResult() {
System.out.println("Displaying from subclass");
super.displayResult();
}
public static void main(String args[]) {
Subclass obj = new Subclass();
obj.displayResult();
}
}

Output:

Displaying from subclass


Printing from superclass

Explanation:

The main method is invoked, creating an object of the Subclass class. The displayResult
method is then called on this object. The output will first display “Displaying from
subclass” as it is defined in the Subclass class. After that, the super.displayResult() line
calls the displayResult method of the superclass Superclass, resulting in the output
“Printing from superclass” being displayed.

It is regarded as one of the Java Basic Interview Questionsthat candidates must be


familiar with before attending an interview.

30. Is it possible to override static methods of a class?


No, static methods cannot be overridden. Static methods belong to the class itself rather
than individual objects, and they are resolved at compile-time. When we try to replace a
static method, we will not encounter a compilation error. However, the overriding will not
have any effect when executing the code.

31. In the following example, how many string objects can be produced?

String s1 = "I am Java Expert";


String s2 = "I am C Expert";
String s3 = "I am Java Expert";
Answer: Two objects of the java.lang.String class have been created in the above example.
Both s1 and s3 are references to the same object, which contains the text “I am Java
Expert”.

32. Is a string considered a data type in Java?


No, a string is not classified as a primitive data type in Java. When a string is created, it is
actually an object of the java.lang.String class that is created. Once a string object is
created, various built-in methods of the String class can be used on the string object.

One of the Core Java Interview Questions that is regularly asked is this one.

33. What distinguishes a vector from an array?


An array collects information of a static, same primitive type, but vectors are believed to
be dynamic in nature and hold the data of multiple data types.

import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
// Creating a vector
Vector names = new Vector<>();
// Adding elements to the vector
names.add("John");
names.add("Alice");
names.add("Bob");
// Accessing elements from the vector
System.out.println("First name: " + names.get(0));
System.out.println("Second name: " + names.get(1));
System.out.println("Third name: " + names.get(2));
// Changing an element in the vector
names.set(1, "Eve");
// Removing an element from the vector
names.remove(0);
// Printing all elements in the vector
System.out.println("Elements in the vector: " + names);
}
}

You can better prepare for the interview with the aid of these Java Programming
Interview Questions.

34. Why are strings known as immutable in Java?


Strings are immutable objects in Java, which means that once a value is assigned to a string,
it cannot be changed. If any modifications are made to a string, a new string object is
created with the updated value, while the original string object remains unchanged.The
integrity and security of Java’s string objects are guaranteed by their immutability.

35. What is multi-threading?


Multi-threading is a fundamental programming concept that involves
executingconcurrently running many tasks in a same programme. The same process stack
is shared by all running threads, enabling improved performance of a program. Multi-
threading is an important topic frequently asked in Java interviews.

36. Why does Java employ the Runnable interface?


The Runnable interface is used in Java to facilitate the execution of multi-threaded
applications. The java.lang.Runnable interface is created by a class to facilitate the
functionality of multi-threading.

37. Which one should be used first when several changes to


the data are required? String or StringBuffer?
Unlike Strings, which are immutable, string buffers are dynamic in nature and allow us to
change the values of StringBuffer objects. Therefore, it is always a good choice to use
StringBuffer when data needs to be changed frequently. When doing so, use a String., Each
data modification will result in the creation of a fresh String object, resulting in additional
overhead.
It is one of the crucial Java Interview Questionsthat is frequently brought up throughout
the interview.

38. What are the two ways that Java implements multi-
threading?
Java offers two different ways to construct multi-threaded applications:

Implementing the java.lang.Runnable interface: Classes can implement this interface to


enable multi-threading. The interface includes a run() method that is executed when the
thread starts.

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running using Runnable interface.");
public class RunnableExample {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}

Extending the java.lang.Thread class: Multi-threading can be achieved by creating a class


that extends the Thread class. The class can override the run() method to specify the
programme that will run when the thread begins.

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running by extending Thread class.");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}

39. How is garbage collection performed in Java?


In Java, garbage collection occurs automatically when an object is no longer referenced.
The object is then automatically removed from memory. Java triggers garbage collection
through the Runtime.gc() method or the System.gc() method.

40. Why is the “break” statement used each time a switch


statement is used?
To make sure that the code exits the switch block following the execution of the valid case,
the “break” statement is used after each case in a switch statement (except from the final
case). Without the break statement, the code would continue executing the subsequent
cases, resulting in incorrect outcomes.The execution flow is controlled and limited to the
desired scenario by utilising the break statement.

It is one of the important Java Interview Questions that come up repeatedly during the
interview.

41. How do we run Java code before the main method?


To execute statements before object creation and the main method, In the class, we can use
a static piece of code. The static block is executed once during the class loading process,
even before the main method is invoked. Any statements within this static block are
executed before the main method and object creation.

42. Can a class function simultaneously as a superclass and


a subclass? Give an instance.
When using inheritance hierarchy, a class can serve as a superclass for one class and as a
subclass for another class simultaneously.
In the example below, the “continent” class is a subclass of the “world” class and, at the
same time, a superclass for the “country” class.

public class world {


// ...
}
public class continent extends world {
// ...
}
public class country extends continent {
// ...
}

43. If a class doesn’t have a constructor, how are objects of


that class created?
Objects are successfully created even if no explicit constructor is defined in a Java class
because Creating objects automatically uses a default constructor.

It is one of the most often requested Java Interview Questions.

44. How do we make sure that in multi-threading, only one


thread is using a resource at a time?
Access to shared resources among the multiple threads can be controlled using
synchronization in multi-threading. By using the synchronized keyword, We can make sure
that only one thread at a time is using the shared resource, while other threads will gain
once the resource has been becomes free from the thread currently using it.

45. Can an object call a class’ constructor more than once?


No, the constructor of a class can only be called once for an object. It is automatically
invoked during the creation of the object using the `new` keyword, and after an object has
been constructed, we are unable to directly call its constructor again.
To succeed in the interview, thoroughly prepare for these Java Interview Questions and
Answers.

46. There are two distinct classes, which are Class A and
Class B. Both classes are in the same package and Can an
object of Class B access a private member of Class A?
A class’s private members cannot be accessed from outside of that class, and this includes
other classes in the same package. Therefore, an object of Class B cannot access the private
members of Class A.

47. Can two methods with the same name exist in the same
class?
Yes, Two methods with the same name but distinct parameters might exist in the same
class. The procedure that is called is determined by the parameters passed when calling the
method.

For example, in the following class, there are two print methods with the same name but
different parameters. The appropriate method will be called depending on the parameters
passed:

public class MethodExample {


public void print() {
System.out.println("Print method without parameters.");
}
public void print(String name) {
System.out.println("Print method with parameter.");
}
public static void main(String[] args) {
MethodExample obj1 = new MethodExample();
obj1.print();
obj1.print("xx");
}
}

48. How can we duplicate a Java object?


The idea of cloning can be used to duplicate an object. By implementing the Cloneable
interface and using the clone() method, we can create copies of objects with their current
state.

You can have a thorough understanding of the topic before the interview by reading
these Java Programming Interview Questions.

49. What benefit does employing inheritance provide?


The main upperhand of using inheritance is code reusability, as it allows subclasses to
inherit and use the code again from their superclass. Additionally, inheritance enables
polymorphism, which allows for the introduction of new functionality without impacting
existing derived classes.

Here’s a sample program demonstrating inheritance:

// Superclass
class Vehicle {
public void start() {
System.out.println("Vehicle started.");
}
}
// Subclass inheriting from Vehicle
class Car extends Vehicle {
public void accelerate() {
System.out.println("Car accelerating.");
}
}
public class Main {
public static void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car();
// Access methods from both Vehicle and Car classes
myCar.start(); // Inherited from Vehicle class
myCar.accelerate(); // Specific to Car class
}
}

50. What access specifier does a class’s by default for its


variables and methods?
the class’s standard access specifier for variables and methods is “package-protected” or
“default”. This means that the variables and methods are accessible within the same
package, but not outside of it.

51. Give a Java class example where pointers are used.


In Java, the concept of pointers is not directly available as in some other programming
languages such as C or C++. Java utilizes references instead of pointers to handle objects.
References in Java provide a safe and simplified way to access objects without the need
for explicit memory management.

The most common concept in Core Java Interview Questions for Freshers is pointers in
java

52. How may a class’ inheritance be limited so that no other


classes can inherit from it?
If we want to prevent a class from being further extended by any other class, Prior to the
class name, we can use the final keyword.

In the following example, the Stone class is declared as final, which means it cannot be
subclassed:

public final class Stone {


// Class methods and variables
}
By making a class final, we ensure that it cannot be extended or inherited by any other
class. This provides control over the class’s implementation and behavior, preventing any
modifications or extensions.

53. What is the Protected access specifier’s access range?


Prior to the class name, we can use the final keyword.A variable or method becomes
available within the same class, any other class of the same package, and also within
subclasses when it is specified with the Protected access specifier.

The Protected access modifier allows access to the member variables and methods from
within the class itself, from other classes within the same package, and from subclasses of
the class, regardless of the package they are in. This provides a level of access that is more
restrictive than the default (package-private) access, but less restrictive than public access.

Modifier CLASS PACKAGE SUBCLASS WORLD

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

Before going to any interviews, you must be familiar with these Java Basic Interview
Questions.

54. What distinctions exist between queues and stacks?


A Queue and a Stack are both data structures used for storing and retrieving elements. The
main difference between them lies in their ordering principle. The Last In First Out (LIFO)
principle is used in a stack. whereas a queue adheres to the First In First Out (FIFO) rule.

Here’s a sample program to illustrate the distinction between a Java Queue and Stack

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class QueueVsStackExample {
public static void main(String[] args) {
// Creating a Queue
Queue queue = new LinkedList<>();
// Adding elements to the Queue
queue.add("Element 1");
queue.add("Element 2");
queue.add("Element 3");
// Removing and printing elements from the Queue (FIFO)
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
System.out.println();
// Creating a Stack
Stack stack = new Stack<>();
// Adding elements to the Stack
stack.push("Element 1");
stack.push("Element 2");
stack.push("Element 3");
// Removing and printing elements from the Stack (LIFO)
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}
Output

Element 1
Element 2
Element 3
Element 3
Element 2
Element 1

55. How may variable serialisation be forbidden?


If we want to prevent certain variables of a class from being serialized, we can use the
transient keyword when declaring them. For example, the variable trans_var below
istagged as temporary and not serialised.

public class TransientExample {


private transient int trans_var;
// rest of the code
}

By declaring a variable as transient, it indicates to the Java serialization mechanism that


the variable should be excluded from the serialization process. When an object is serialized,
the transient variables are not written to the output stream. When the object is deserialized,
these variables will have their default values, as they were not saved during serialization.

It is one of the Core Java Interview Questions that is regularly asked.

56. How do you use primitive data types as objects?


By using their respective wrapper classes, primitive data types like int can be treated as
objects. For example,The wrapper class for the primitive data type int is integer.. By using
wrapper classes, primitive data types can be treated as objects and various methods can be
applied to them, similar to any other object.

Here’s an example that demonstrates the usage of the Integer wrapper class:

public class WrapperExample {


public static void main(String[] args) {
int number = 10; // primitive data type
Integer wrapperNumber = Integer.valueOf(number); // using wrapper
class
// Applying methods to the wrapper class
int result = wrapperNumber.compareTo(5);
System.out.println("Comparison result: " + result);
String binaryString = wrapperNumber.toBinaryString();
System.out.println("Binary representation: " + binaryString);
}
}

57. Which exception types are examined at compile time?


Checked exceptions are caught by the compiler at compile time. To ensure successful
compilation, checked exceptions must be handled using try-catch blocks or declared using
the throws keyword.

This is a significant subject that appears in the Java Interview Questions for Freshers

58. Describe the various states of a thread.


A thread in Java could be in any of the following states:

New: When a thread is created but not started yet, it is in the new state.

Runnable: A thread that is ready to run or is currently running is in the runnable state.

Waiting: A thread that is stand by for another thread to release a lock or for a specific
condition to be satisfied is in the waiting state.

Timed Waiting: A thread that is waiting for a certain period of time is in the timed waiting
state.

Blocked: A blocked thread that is awaiting a monitor lock to be released is in the blocked
state.

Terminated: A thread that has completed its execution or has been terminated abruptly is
in the terminated state.

59. Even if an explicit constructor is defined, may the


default constructor of a class be used?
In Java, if no explicit constructor is defined in a class, the compiler automatically provides
a default no-argument constructor. However, once an explicit constructor is defined in the
class, the default constructor is not automatically invoked. The developer can only use the
constructors that are explicitly defined in the class.

60. Can a method have a different return type but the same
method name and arguments?
In Java, method overriding requires that the method name, arguments, and return type of
the overriding method must be exactly the same as the one of the substituted approach.
Therefore, if the return type of a method is different, it cannot be considered as overriding
the method.

These Java questions and answers can help you progress in your chosen field.

61. What does the code snippet that is listed below


produce?

public class OperatorExample {


public static void main (String args[]) {
int x = 4;
System.out.println(x++);
}
}

The code uses the postfix++ operator,This initially returns the value before increasing it.
Therefore, the output will be 4.

It’s one of the Java Basic Interview Questions that they frequently ask candidates.

62. Is it feasible to claim that a Java class was properly


compiled without even having a main method?
The main method is considered to be an entry point of a Java class and is required for
executing the program. However,If a Java class lacks a main method, it can nevertheless
be successfully compiled. Note that the class cannot be executed without a main method.
With the help of Java Online Training, gain the information you need to become a Java
developer.

63. Can a static method invoke a non-static method from


within it?
No, a non-static method cannot be called directly from inside a static method. Non-static
methods belong to an instance of a class and require an object to be invoked. In a static
method, there is no instance context, so calling a non-static method directly is not possible.
To call a non-static methods from a static method, you must first construct an object of the
class and then use that object to call the non-static method.

Here’s an example:

public class Example {


public void nonStaticMethod() {
System.out.println("Non-static method");
}
public static void staticMethod() {
Example obj = new Example(); // Create an object of the class
obj.nonStaticMethod(); // Call the non-static method using the object
}
public static void main(String[] args) {
staticMethod();
}
}

With the aid of these Java Interview Questions for Freshers, you may brush up on your
knowledge and succeed in your interview.

64. What are the two environment variables that must be


established before any Java programme may be run?
To successfully run Java programs on a machine, Two environment variables need to be
properly configured, and they are as follows:
 PATH variable: The PATH variable should include the directory path where
the Java Development Kit (JDK) binaries are located. This allows the system
to locate and execute the Java compiler (javac) and Java Virtual Machine
(java) commands.

 CLASSPATH variable: The CLASSPATH variable is used by the Java


runtime environment to locate the compiled Java classes and libraries
required by the program during runtime. It should include the directories or
JAR files containing the compiled classes or libraries.

65. Can a constructor have a different name than the class


name in Java?
In Java, a constructor must have the same name as the class it belongs to. If the constructor
has a different name, it will not be recognized as a constructor by the compiler and will be
treated as a regular method.

66. What will Round(3.7) and Ceil(3.7) produce?


The output of Round(3.7) is 4, and the output of Ceil(3.7) is 4.

View these Java Programming Questions to see how well they may help you review your
knowledge.

67. Can a Java class inherit from multiple classes?


Java does not support multiple inheritance; instead, a class can only derive from one other
class.

68. Can you use Java’s go to command to jump to a


specific line?
In Java, the “goto” keyword does not exist, and the language does not support the capability
of jumping to a specific labeled line.

69. Can we revive a dead thread?


One of the Core Java Interview Questions that is regularly asked is this one.

70. Is the class declaration that follows accurate?


The provided class declaration is incorrect. In Java, a class cannot be declared as both
abstract and final at the same time. The keywords “abstract” and “final” have conflicting
meanings in Java. An abstract class is intended to be subclassed, while a final class cannot
be subclassed. Therefore, it is not possible to declare a class as both abstract and final.

71. Is JDK required for Java programmes to execute on


every computer?
The JDK (Java Development Kit) is primarily used for development purposes It is not
necessary for a machine to run a Java programme. Instead, only the JRE (Java Runtime
Environment) is necessary for running Java programs.

To help you improve your knowledge, we provide you with these Java Questions and
Answers.

72. What makes a comparison using the equals method


and the == operator different?
When two string objects are compared and their contents are found to be identical, the
equals() function returns true. On the other hand, the == operator compares the references
of the two string objects in Java.

In the below example, the equals() given that the two string objects it returns include the
same values. However, the == operator returns false as the two string objects are
referencing different objects:

public class EqualsTest {


public static void main(String args[]) {
String str1 = "Hello World";
String str2 = "Hello World";
if (str1.equals(str2)) {
System.out.println("str1 and str2 are similar in terms of values");
}
if (str1 == str2) {
System.out.println("Both strings are referencing the same object");
}
else {
System.out.println("Both strings are referencing different objects");
}
}
}

With the help of these Java Programming Interview Questions, you may more
effectively prepare for the interview.

75. Can static methods be present in an interface?


In Java, interfaces can contain static methods. Static methods in interfaces can have a
defined implementation and can be invoked directly on the interface itself, without the need
for an implementing class.

One of the Java Basic Interview Questions to be familiar with before an interview is this
one.

76. How are destructors defined in Java?


Destructors are not defined in Java as there is no need to explicitly define them. Java has a
built-in garbage collection mechanism that automatically allocates memory for discarded
items referenced, eliminating the need for explicit destructors.

77. In a class that implements an interface, is it possible to


modify the value of any variable defined in the interface?
No, we cannot change the value of any variable defined in an interface in a class
implementing that interface. All variables in an interface are by default static, public, and
final. Final variables are constants and their values cannot be changed once assigned.
Therefore, the variable values defined in an interface cannot be modified in the
implementing class.
78. Is it true that Java’s garbage collection function
prevents programmes from ever running out of memory?
The absence of memory issues with Java programmes is not a given. Although Java
provides automatic garbage collection, there is still a possibility of running out of memory
if objects are created at a faster rate than garbage collection can free up memory resources.

79. Can we use a different return type for void in the main
method?
No, for the programme to run successfully, the main method of a Java class can only have
a void return type.

However, if you need to return a value upon the completion of the main method, you can
use System.exit(int status).

80. Once an item has been garbage collected, I need to use


it again. What makes it possible?
An object that has been trash collected from the heap is permanently deleted and cannot be
accessed or referenced again. After it has been garbage collected, there is no way to get the
item back or use it.

81. What do you mean by a interface in Java?


An interface in Java serves as a blueprint for a class, containing a set of static constants
and abstract methods. Each public and abstract method in an interface, and it does not have
a constructor. Thus, an interface represents a group of related methods with empty bodies.

Example:

public interface Animal {


public void eat();
public void sleep();
public void run();
}

83. What is an association?


Association is a relationship where each object has its own lifecycle, and there is no
ownership.Think about the relationship between a teacher and a student, for instance. A
single teacher can have many pupils in their class, while a single student might have many
teachers in their class.However, there is no ownership between the objects, and each object
has an independent lifecycle. These associations can be one-to-one, one-to-many, many-
to-one, and many-to-many.

84. What is composition in Java?


Composition is a specialized form of aggregation, representing a “death” relationship. It is
a strong type of aggregation where child objects do not have their own lifecycle.All child
objects are also removed if the parent object is erased. For example, consider the
relationship between a House and its rooms. A house can contain multiple rooms, but each
room cannot belong to multiple houses. If the house is deleted, all rooms associated with
it are also deleted.

85. What is a marker interface?


A marker interface is an interface that does not contain any data members or member
functions. It is simply an empty interface. Serializable and Cloneable are two examples of
marker interfaces in Java.. A marker interface can be declared as follows:

public interface Serializable {}

86. What is constructor overloading in Java?


In Java, the practise of adding many constructors, each with a unique parameter list, to a
class is known as constructor overloading. The compiler uses the number and types of
parameters to differentiate between the overloaded constructors.

Example:

class Demo {
int i;
public Demo(int a) {
i = a;
}
public Demo(int a, int b) {
// body
}
}

87. What is a servlet?


Using a server-side technology called a Java servlet which extends the functionality of web
servers by enabling dynamic response generation and data persistence. Interfaces and
classes for writing servlets are given by the javax.servlet and javax.servlet.http
packages.The javax.servlet must be implemented by every servlet.Servlet lifecycle
methods are defined by the Servlet interface. The HttpServlet class, an extension of
GenericServlet, provides methods like doGet() and doPost() for handling HTTP-specific
services.

88. What is a Request Dispatcher?


The RequestDispatcher interface is used to forward a request to another resource, which
can be an HTML, JSP, or another servlet within the same application. It can also be used
to include the content of another resource in the response.

The RequestDispatcher interface defines two methods:

void forward()

void include()

89. How do cookies work in Servlets?


Cookies are files that the server sends to the client and stores locally on the client’s device.
Through the javax.servlet.http.Cookie class, which implements the Serializable and
Cloneable interfaces, the Servlet API offers cookie functionality. The HttpServletRequest
getCookies() method is used to retrieve an array of cookies from the request. However,
there are no methods to add or set cookies in the request. Similarly, the
HttpServletResponse addCookie(Cookie c) method is used to attach a cookie in the
response header.

90. What are the different method of session management


in servlets?
Session management in servlets involves maintaining a conversational state between the
client and server. Some common methods of session management include:

 User Authentication

 HTML Hidden Field

 Cookies

 URL Rewriting

 Session Management API

By reading through these Java Programming Interview Questions before the interview, you
can have a complete understanding of the subject.

91. What is a JDBC Driver?


Java is made possible through a software component called a JDBC Driver. applications to
interact with databases. Altogether there are mainly four types of JDBC drivers:

 JDBC-ODBC bridge driver

 Native-API driver (partially Java driver)

 Network Protocol driver (fully Java driver)

 Thin driver (fully Java driver)

 What is a JIT compiler in Java?

The JIT (Just-In-Time) compiler in Java is a program that converts Direct instructions are
provided to the CPU from Java bytecode. By default, When a Java method is called, In
Java, the JIT compiler is activated and launched. It “just in time” converts the bytecode for
the method into machine language. following compilation of the procedure, the JVM
directly summons the compiled code for execution, rather than interpreting it. The JIT
compiler plays a crucial role in optimizing the performance of Java applications at runtime.

92. Define a Java Class.


A Java class is a blueprint that defines the structure and behavior of objects. It contains
fields (variables) and methods to describe the characteristics and actions of an object.The
following is the syntax for declaring a class:

class ClassName {
// member variables
// class body with methods
}

One of the Core Java Interview Questions that is frequently asked is this particular one.

93. What is Object-Oriented Programming?


The programming paradigm known as “Object-Oriented Programming” (OOP) revolves
around objects rather than logic and functions. It focuses on organizing programs around
objects that need to be manipulated, making it suitable for large and complex codebases
that require frequent updates and maintenance.

94. What are the concepts of OOPs in Java?


The main concepts of Object-Oriented Programming (OOPs) in Java are:

Inheritance: A process where one class acquires the properties and behaviors of another
class.

Encapsulation: A mechanism for wrapping data and code together as a single unit.

Abstraction: offering a streamlined interface while concealing the implementation


specifics.

Polymorphism: The capacity of an object to assume different shapes.


95. What is an infinite loop in Java? Explain with an
example.
An infinite loop in Java is a sequence of instructions that repeatedly executes without a
functional exit condition. This can be the result of a coding error or intentional design based
on application behavior. An infinite loop will only terminate when the application is
forcibly terminated or interrupted.

Example:

public class InfiniteForLoopDemo {


public static void main(String[] args) {
for (;;) {
System.out.println("Welcome to Edureka!");
// Ctrl + C in the console will end this programme.
}
}
}

96. What is Java String Pool?


The Java String Pool refers to a collection of String objects stored in the heap memory.
When a new String object is created, the string pool checks if an identical object already
exists. If it does, the reference to the existing object is returned. If not, a fresh object is
made in the string pool, and its reference is returned.

97. What is a classloader in Java?


The Java ClassLoader is responsible for loading class files during the execution of a Java
program. When a Java program is executed, it is first loaded by the classloader. Java
provides three built-in classloaders: the Bootstrap ClassLoader, the Extension
ClassLoader, and the System/Application ClassLoader.

98. What is Polymorphism?


“Polymorphism” refers to an object, function, or variable’s ability to take on a variety of
shapes. It allows entities in a program, such as variables and functions, to have more than
one implementation. Polymorphism can be achieved through method overloading
(compile-time polymorphism) and method overriding (runtime polymorphism).

99. What is Spring?


For the Java platform, Spring is an application framework and inversion of control
container. It provides core features that can be used by any Java application, with
extensions available for the Java EE platform for developing web applications. Spring is a
lightweight and integrated framework used for developing enterprise applications in Java.

100. How to integrate Spring and Hibernate Frameworks?


To integrate Spring and Hibernate frameworks, the Spring ORM module can be used. If
Hibernate 3+ is used, where SessionFactory provides the current session, it is
recommended to avoid using HibernateTemplate or HibernateDaoSupport classes. Instead,
the DAO pattern with dependency injection should be utilized.

Additionally, Spring ORM provides support for declarative transaction management,


which is preferred over writing boilerplate code for transaction management in Hibernate.

101. How can exceptions be handled in the Spring MVC


Framework?
The Spring MVC Framework offers several approaches for robust exception handling:

Controller-Based: We can define exception handler methods within our controller classes
and annotate them with the @ExceptionHandler annotation.

Global Exception Handler: The @ControllerAdvice annotation from Spring can be used
with any class to provide a global exception handler. Exception handling is a cross-cutting
topic.

Handler Exception Resolver Implementation: In cases where we need to serve static


pages for generic exceptions, we can implement the HandlerExceptionResolver interface
provided by the Spring Framework. This allows us to create a global exception handler.
The advantage of this approach is that Spring Framework offers default implementation
classes that can be configured in the Spring bean configuration file to leverage the benefits
of Spring’s exception-handling capabilities.

To learn more about Java Programming, visit FITA Academy for the best Java Course
in Chennai or Java Training in Bangalore.

Top Interview Questions & Answers

Recent Post: 50 Significant Ways to Optimize your Google Adwords Account

REQUEST A BATCH

Quick Enquiry
+91

Select the Branch

Select the Course

Submit

Contact Us
Chennai
93450 45466
Bangalore
93450 45466
Coimbatore
95978 88270
Online
93450 45466
Madurai
97900 94102
Pondicherry
93635 21112
For Hiring
93840 47472
hr@fita.in
Corporate Training
90036 23340

Top Courses

JAVA And J2EE Training In Chennai


Dot Net Training In Chennai
Software Testing Training In Chennai
Cloud Computing Training In Chennai
AngularJS Training in Chennai
Big Data Hadoop Training In Chennai
Android Training In Chennai
IOS Training In Chennai
Web Designing Course In Chennai
PHP Training In Chennai

Digital Marketing Training In Chennai


SEO Training In Chennai

Oracle Training In Chennai


Selenium Training In Chennai
Data Science Course In Chennai
RPA Training In Chennai
DevOps Training In Chennai
C / C++ Training In Chennai
UNIX Training In Chennai
Placement Training In Chennai
German Classes In Chennai
Python Training in Chennai
Artificial Intelligence Course in Chennai
AWS Training in Chennai
Tutorials

 Python TutorialJava TutorialData Science TutorialEthical Hacking TutorialAWS


TutorialFull Stack TutorialDevOps TutorialSalesforce TutorialSelenium TutorialAngular
TutorialSoftware Testing Tutorial

Interview Questions
 Digital Marketing Interview QuestionsJava Interview QuestionsSelenium Interview
QuestionsHadoop Interview QuestionsPython Interview QuestionsAWS Interview
QuestionsDevOps Interview QuestionsOracle Interview QuestionsPHP Interview
QuestionsUI UX Designer Interview Questions and AnswersAngularJs Interview
Questions
Read More

FITA Academy Branches

Chennai
Velachery
Anna Nagar
T.Nagar
Tambaram
Thoraipakkam OMR
Porur

Bangalore
Marathahalli

Coimbatore
Saravanampatty
Singanallur

Other Locations
Madurai
Pondicherry
Contact Us

Chennai:

93450 45466

Bangalore:

93450 45466
Coimbatore:

95978 88270

Pondicherry:

93635 21112

Madurai:

97900 94102

Online:

93450 45466
 For Business
o Hire From FITA
o Careers
o Business opportunities
o Corporate Training
o Become an Instructor
 Testimonials
o FITA Academy Reviews
o Student Testimonials
o Success Stories
 Resources
o Blog
o Interview Questions
o Tutorials
o Free Placement Session
 Follow us

o
 TRENDING COURSES
JAVA Training In Chennai Software Testing Training In
Chennai Selenium Training In Chennai Python Training in
Chennai Data Science Course In Chennai Digital Marketing Course In
Chennai DevOps Training In Chennai German Classes In
Chennai Ar tif ic ial Int elligenc e Cours e in Chennai AW S Tr aining in
Chennai UI UX Design course in Chennai Tally course in Chennai Full
Stack Developer course in Chennai Salesforce Training in
Chennai ReactJS Training in Chennai CCNA course in Chennai Ethical
Hacking course in Chennai RPA Training In Chennai Cyber Security
Course in Chennai IELTS Coaching in Chennai Graphic Design Courses
in Chennai Spoken English Classes in Chennai Data Analytics Course
in Chennai

Read More

 ARE YOU LOCATED IN ANY OF THESE AREAS


Adyar, Adam bakkam, Anna Salai, Ambattur, Ashok Nagar, Am injikarai,
Anna Nagar, Besant Nagar, Chrom epet , Choolaim edu, Guindy, Egm ore,
K.K. Nagar, Kodam bakkam , Koyam bedu, Ekkattuthangal, Kilpauk,
Meenam bakkam , Medavakkam , Nandanam , Nungam bakkam ,
Madipakkam , Teynam pet, Nanganallur, Navalur, Mylapore, Pallavaram ,
Purasaiwakkam , OMR, Porur, Pallikaranai, Poonam allee, Peram bur,
Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar,
Sholinganallur, Triplicane, Thoraipakkam , Tam baram , Vadapalani,
Valasaravakkam , Villivakkam , Thiruvanm iyur, W est Mam balam ,
Velachery and Virugam bakkam .

FITA Velachery or T Nagar or T horaipakkam OMR or Anna Nagar or


Tam baram or Porur branch is just few kilom etre away from your
location. If you need the best training in Chennai, driving a couple of
extra kilom etres is worth it!

 © 2020 FITA. All rights Reserved.


93450 45466
 Request a Call Back

You might also like