[go: up one dir, main page]

0% found this document useful (0 votes)
9 views82 pages

Lab 6

Uploaded by

Aftab Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views82 pages

Lab 6

Uploaded by

Aftab Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 82

JAVA INTERVIEW QUESTIONS

Source : https://www.simplilearn.com/java-8-interview-questions-and-answers-
article

1. What are the differences between C++ and Java?

 Concept.

C++ is not platform-independent; the principle behind C++ programming is “write once,
compile anywhere.”

In contrast, because the byte code generated by the Java compiler is platform-
independent, it can run on any machine, Java programs are written once and run
everywhere.

 Languages Compatibility.

C++ is a programming language that is based on the C programming language. Most


other high-level languages are compatible with C++.

Most of the languages of Java are incompatible. Java is comparable to those of C and
C++.

 Interaction with the library.

It can access the native system libraries directly in C++. As a result, it’s better for
programming at the system level.

Java’s native libraries do not provide direct call support. You can use Java Native
Interface or access the libraries.
Characteristics.

C++ distinguishes itself by having features that are similar to procedural and object-
oriented languages. The characteristic that sets Java apart is automatic garbage
collection. Java doesn’t support destructors at the moment.

 The semantics of the type.

Primitive and object types in C++ have the same kind of semantics. The primitive
and object and classes of Java, on the other hand, are not consistent.

 In the context of Compiler and Interpreter.

Java refers to a compiled and interpreted language. In contrast, C++ is only a compiled
language.

In Java, the source code is the compiled output is a platform-independent byte code.

In C++, the source program is compiled into an object code that is further executed to
produce an output.

2. List the features of the Java Programming language?

A few of the significant features of Java Programming Language are:

Easy: Java is a language that is considered easy to learn. One fundamental concept of
OOP Java has a catch to understand.

Secured Feature: Java has a secured feature that helps develop a virus-free and
tamper-free system for the users.

OOP: OOP stands for Object-Oriented Programming language. OOP signifies that, in
Java, everything is considered an object.

Independent Platform: Java is not compiled into a platform-specific machine; instead, it


is compiled into platform-independent bytecode. This code is interpreted by the Virtual
Machine on which the platform runs.

4. What is a ClassLoader?
A classloader in Java is a subsystem of Java Virtual Machine, dedicated to loading
class files when a program is executed; ClassLoader is the first to load the executable
file.

Java has Bootstrap, Extension, and Application classloaders.

Also Read: What is Bootstrap and How to Embed Bootstrap into Angular?

5. What are the Memory Allocations available in JavaJava?

Java has five significant types of memory allocations.

 Class Memory

 Heap Memory

 Stack Memory

 Program Counter-Memory

 Native Method Stack Memory

6. What are the differences between Heap and Stack Memory in Java?

Stack memory in data structures is the amount of memory allocated to each individual
programme. It is a fixed memory space. Heap memory, in contrast, is the portion that
was not assigned to the Java code but will be available for use by the Java code when it
is required, which is generally during the program's runtime.

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

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

8. What is the default value stored in Local Variables?

Neither the Local Variables nor any primitives and Object references have any default
value stored in them.
Most Asked Java Coding Interview Questions

Here are some of the most asked Java interview questions.

 What is Java?

 Why is Java a platform independent language?

 What are the differences between C++ and Java?

 Why is Java not a pure object oriented language?

 List the features of the Java Programming language?

 What do you get in the Java download file?

 Explain JVM, JRE, and JDK.

 What is a ClassLoader?

 What are the Memory Allocations available in JavaJava?

 What are the differences between Heap and Stack Memory in Java?

Now, let's discuss the key Java interview questions for freshers and their answers.

Java Basic Interview Questions for Freshers

So let’s get started with the first set of basic core Java technical interview questions
which is primarly useful for freshers.

1. What are the differences between C++ and Java?

 Concept.

C++ is not platform-independent; the principle behind C++ programming is “write once,
compile anywhere.”

In contrast, because the byte code generated by the Java compiler is platform-
independent, it can run on any machine, Java programs are written once and run
everywhere.

Also Read: Learn C++ Programming


 Languages Compatibility.

C++ is a programming language that is based on the C programming language. Most


other high-level languages are compatible with C++.

Most of the languages of Java are incompatible. Java is comparable to those of C and
C++.

 Interaction with the library.

It can access the native system libraries directly in C++. As a result, it’s better for
programming at the system level.

Java’s native libraries do not provide direct call support. You can use Java Native
Interface or access the libraries.

Characteristics.

C++ distinguishes itself by having features that are similar to procedural and object-
oriented languages. The characteristic that sets Java apart is automatic garbage
collection. Java doesn’t support destructors at the moment.

 The semantics of the type.

Primitive and object types in C++ have the same kind of semantics. The primitive
and object and classes of Java, on the other hand, are not consistent.

 In the context of Compiler and Interpreter.

Java refers to a compiled and interpreted language. In contrast, C++ is only a compiled
language.

In Java, the source code is the compiled output is a platform-independent byte code.

In C++, the source program is compiled into an object code that is further executed to
produce an output.

2. List the features of the Java Programming language?

A few of the significant features of Java Programming Language are:


Easy: Java is a language that is considered easy to learn. One fundamental concept of
OOP Java has a catch to understand.

Secured Feature: Java has a secured feature that helps develop a virus-free and
tamper-free system for the users.

OOP: OOP stands for Object-Oriented Programming language. OOP signifies that, in
Java, everything is considered an object.

Independent Platform: Java is not compiled into a platform-specific machine; instead, it


is compiled into platform-independent bytecode. This code is interpreted by the Virtual
Machine on which the platform runs.

3. What do you get in the Java download file? How do they differ from one
another?

We get two major things along with the Java Download file.

JDK - Java Development Kit

JRE - Java Runtime Environment

JDK JRE

Abbreviation for Java Runtime


Abbreviation for JavaDevelopment Kit
Environment

JRE is a set of software and library


JDK is a dedicated kit for solely software development designed for executing Java
Programs
Unlike JVM, JRE is also Platform
Unlike JVM, JDK is Platform Dependent
Dependent

JRE Package is one that only


JDK package is a set of tools for debugging and Developing supports files and libraries for a
runtime environment

JRE Package does not get an


JDK package will be provided with an installer file installer but has only a runtime
environment

4. What is a ClassLoader?

A classloader in Java is a subsystem of Java Virtual Machine, dedicated to loading


class files when a program is executed; ClassLoader is the first to load the executable
file.

Java has Bootstrap, Extension, and Application classloaders.

Also Read: What is Bootstrap and How to Embed Bootstrap into Angular?

5. What are the Memory Allocations available in JavaJava?

Java has five significant types of memory allocations.

 Class Memory

 Heap Memory

 Stack Memory
 Program Counter-Memory

 Native Method Stack Memory

6. What are the differences between Heap and Stack Memory in Java?

Stack memory in data structures is the amount of memory allocated to each individual
programme. It is a fixed memory space. Heap memory, in contrast, is the portion that
was not assigned to the Java code but will be available for use by the Java code when it
is required, which is generally during the program's runtime.

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

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

8. What is the default value stored in Local Variables?

Neither the Local Variables nor any primitives and Object references have any default
value stored in them.

9. Explain the expected output of the following code segment?

public class Simplilearn


{
public static void main (String args[])
{
System.out.println(100 + 100 +“Simplilearn");
System.out.println(“E-Learning Company" + 100 + 100);
}
}

The answers for the two print statements are as follows.

 200Simplilearn

 E-Learning Company100100

10. What is an Association?


An Association can be defined as a relationship that has no ownership over another.
For example, a person can be associated with multiple banks, and a bank can be
related to various people, but no one can own the other.

Get access and complete hands-on experience on a plethora of software development skills in
our unique Job Guarantee bootcamp. Get job-ready by enrolling in our comprehensive Full
Stack Java Developer Masters program today!

11. What do you mean by aggregation?

The term aggregation refers to the relationship between two classes best described as
a “whole/part” and “has-a” relationship. This kind is the most specialized version of an
association relationship. It contains the reference to another class and is said to have
ownership of that class.

12. Define Copy Constructor in Java

A Copy Constructor in Java is a constructor that initializes an object through another


object of the same class.

13. What is a Marker Interface?

An empty interface in Java is referred to as a Marker interface. Serializable and


Cloneable are some famous examples of Marker Interface.

14. What is Object Cloning?

An ability to recreate an object entirely similar to an existing object is known as Object


Cloning in Java. Java provides a clone() method to clone a current object offering the
same functionality as the original object.

15. Can Java be said to be the complete object-oriented programming


language

No, Java cannot be treated as a complete object-oriented programming language.

16. What is an object-oriented paradigm?


A Paradigm that is based on the concepts of “Objects.” It contains data and code. Data
that is in the form of fields, and regulation, that is in the form of procedures. The exciting
feature of this paradigm is that the object’s procedures can access and often modify the
data fields themselves.

17. Define Wrapper Classes in Java.

In Java, when you declare primitive datatypes, then Wrapper classes are responsible
for converting them into objects(Reference types).

18. What is a singleton class in Java? And How to implement a singleton


class?

A class that can possess only one object at a time is called a singleton class. To
implement a singleton class given steps are to be followed:

1. Make sure that the class has only one object

2. Give global access to that object

19. Define package in Java.

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

20. Can you implement pointers in a Java Program?

Java Virtual Machine takes care of memory management implicitly. Java's primary
motto was to keep programming simple. So, accessing memory directly through
pointers is not a recommended action. Hence, pointers are eliminated in Java.

Recommended Read: The Complete Reference to Java Programming

21. Differentiate between instance and local variables.

For instance, variables are declared inside a class, and the scope of variables in
javascript is limited to only a specific object.

A local variable can be anywhere inside a method or a specific block of code. Also, the
scope is limited to the code segment where the variable is declared.
22. Explain Java String Pool.

A collection of strings in Java's Heap memory is referred to as Java String Pool. In case
you try to create a new string object, JVM first checks for the presence of the object in
the pool. If available, the same object reference is shared with the variable, else a new
object is created.

23. What is an Exception?

An Exception handling in Java is considered an unexpected event that can disrupt the
program's normal flow. These events can be fixed through the process of Exception
Handling.

24. What is the final keyword in Java?

The term final is a predefined word in Java that is used while declaring values to
variables. When a value is declared using the final keyword, then the variable's value
remains constant throughout the program's execution.

25. What happens when the main() isn't declared as static?

When the main method is not declared as static, then the program may be compiled
correctly but ends up with a severe ambiguity and throws a run time error that reads
"NoSuchMethodError."

Source : https://www.geeksforgeeks.org/java-interview-questions/

181. What are the different types of Thread Priorities in Java? And what is the default priority of a
thread assigned by JVM?

Priorities in threads is a concept where every thread is having a priority which in layman’s language one
can say every object is having priority here which is represented by numbers ranging from 1 to 10. There
are different types of thread properties in Java mentioned below:

MIN_PRIORITY

MAX_PRIORITY

NORM_PRIORITY
By default, the thread is assigned NORM_PRIORITY.

182. Why Garbage Collection is necessary in Java?

For Java, Garbage collection is necessary to avoid memory leaks which can cause the program to crash
and become unstable. There is no way to avoid garbage collection in Java. Unlike C++, Garbage
collection in Java helps programmers to focus on the development of the application instead of
managing memory resources and worrying about memory leakage. Java Virtual Machine (JVM)
automatically manages the memory periodically by running a garbage collector which frees up the
unused memory in the application. Garbage collection makes Java memory efficient because it removes
unreferenced objects from the heap memory.

183. What is the drawback of Garbage Collection?

Apart from many advantages, Garbage Collector has certain drawbacks mentioned below:

The main drawback to Garbage collection is that it can cause pauses in an application’s execution as it
works to clear the memory which slows down the performance of the application.

The Process of Garbage collection is non-deterministic which makes it difficult to predict when garbage
collection occurs which causes unpredictable behavior in applications. For Example, if we write any
program then it is hard for programmers to decide if the issue is caused by garbage collection or by any
other factors in the program.

Garbage collection can also increase memory usage if the program creates and discards a lot of short-
lived objects.

184. Explain the difference between a minor, major, and full garbage collection.

The Java Virtual Machine (JVM) removes objects that are no longer in use using a garbage collector
which periodically checks and removes these objects. There are different types of garbage collection in
the JVM, each with different characteristics and performance implications. The main types of garbage
collection are:

Minor garbage collection: Also known as young generation garbage collection, this type of garbage
collection is used to collect and reclaim memory that is used by short-lived objects (objects that are
quickly created and discarded).

Major garbage collection: Also known as old-generation garbage collection, this type of garbage
collection is used to collect and reclaim memory that is used by long-lived objects (objects that survive
multiple minor garbage collections and are promoted to the old generation).
Full garbage collection: During full garbage collection, memories from all generations are collected and
reclaimed, including memories of young and old. A full garbage collection normally takes longer to
complete than a minor or major garbage collection which causes that app to pause temporarily.

185. How will you identify major and minor garbage collections in Java?

Major garbage collection works on the survivor space and Minor garbage collection works on the Eden
space to perform a mark-and-sweep routine. And we can identify both of them based on the output
where the minor collection prints “GC”, whereas the major collection prints “Full GC” for the case where
the garbage collection logging is enabled with “-XX:PrintGCDetails” or “verbose:gc”.

186. What is a memory leak, and how does it affect garbage collection?

In Java Memory leaks can be caused by a variety of factors, such as not closing resources properly,
holding onto object references longer than necessary, or creating too many objects unnecessarily. There
are situations in which garbage collector does not collect objects because there is a reference to those
objects. In these situations where the application creates lots of objects and does not use them and
every object has some valid references, a Garbage collector in Java cannot destroy the objects. These
useless objects which do not provide any value to the program are known as Memory leaks. Memory
leaks can impact garbage collection negatively by preventing the garbage collector from reclaiming
unused memory. This behavior will lead to slow performance or sometimes system failure. In a program,
it is important to avoid memory leaks by managing resources and object references properly.

Example:

// Java Program to demonstrate memory leaks

import java.io.*;

import java.util.Vector;

class GFG {

public static void main(String[] args)

Vector a = new Vector(21312312);


Vector b = new Vector(2147412344);

Vector c = new Vector(219944);

System.out.println("Memory Leak in Java");

Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

at java.base/java.util.Vector.<init>(Vector.java:142)

at java.base/java.util.Vector.<init>(Vector.java:155)

at GFG.main(GFG.java:9)

187. Name some classes present in java.util.regex package.

Regular Expressions or Regex in Java is an API used for searching and manipulating of strings in Java. It
creates String patterns that can extract the data needed from the strings or can generalize a pattern.

There are 3 Classes present in java.util.regex mentioned below:

Pattern Class: Can define patterns

Matcher Class: Can perform match operations on text using patterns

PatternSyntaxException Class: Can indicate a syntax error in a regular expression pattern.

Also, apart from the 3 classes package consists of a single interface MatchResult Interface which can be
used for representing the result of a match operation.

188. Write a regular expression to validate a password. A password must start with an alphabet and
followed by alphanumeric characters; Its length must be in between 8 to 20.

regex = “^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&-+=()])(?=\\S+$).{8, 20}$”

Explanation:

^ used for starting character of the string.

(?=.*[0-9]) used for a digit must occur at least once.


(?=.*[a-z]) used for a lowercase alphabet must occur at least once.

(?=.*[A-Z]) used for an upper case alphabet that must occur at least once in the substring.

(?=.*[@#$%^&-+=()] used for a special character that must occur at least once.

(?=\\S+$) white spaces don’t allow in the entire string.

.{8, 20} used for at least 8 characters and at most 20 characters.

$ used for the end of the string.

189. What is JDBC?

JDBC standard API is used to link Java applications and relational databases. It provides a collection of
classes and interfaces that let programmers to use the Java programming language to communicate
with the database. The classes and interface of JDBC allow the application to send requests which are
made by users to the specified database. There are generally four components of JDBC by which it
interacts with the database:

JDBC API

JDBC Driver manager

JDBC Test Suite

JDBC-ODBC Bridge Drivers

JDBC-768

190. What is JDBC Driver?

JDBC Driver is a software component that is used to enable a Java application to interact with the
database. JDBC provides the implementation of the JDBC API for a specific database management
system, which allows it to connect the database, execute SQL statements and retrieve data. There are
four types of JDBC drivers:

JDBC-ODBC Bridge driver

Native-API driver

Network Protocol driver

Thin driver

JDBC-Driver-660
191. What are the steps to connect to the database in Java?

There are certain steps to connect the database and Java Program as mentioned below:

Import the Packages

Load the drivers using the forName() method

Register the drivers using DriverManager

Establish a connection using the Connection class object

Create a statement

Execute the query

Close the connections

192. What are the JDBC API components?

JDBC API components provide various methods and interfaces for easy communication with the
databases also it provides packages like java Se and java EE which provides the capability of write once
run anywhere (WORA).

Syntax:

java.sql.*;

193. What is JDBC Connection interface?

Java database connectivity interface (JDBC) is a software component that allows Java applications to
interact with databases. To enhance the connection, JDBC requires drivers for each database.

194. What does the JDBC ResultSet interface?

JDBC ResultSet interface is used to store the data from the database and use it in our Java Program. We
can also use ResultSet to update the data using updateXXX() methods. ResultSet object points the cursor
before the first row of the result data. Using the next() method, we can iterate through the ResultSet.

195. What is the JDBC Rowset?

A JDBC RowSet provides a way to store the data in tabular form. RowSet is an interface in java that can
be used within the java.sql package. The connection between the RowSet object and the data source is
maintained throughout its life cycle. RowSets are classified into five categories based on implementation
mentioned below:
JdbcRowSet

CachedRowSet

WebRowSet

FilteredRowSet

JoinRowSet

196. What is the role of the JDBC DriverManager class?

JDBC DriverManager class acts as an interface for users and Drivers. It is used in many ways as
mentioned below:

It is used to create a connection between a Java application and the database.

Helps to keep track of the drivers that are available.

It can help to establish a connection between a database and the appropriate drivers.

It contains all the methods that can register and deregister the database driver classes.

DriverManager.registerDriver() method can maintain the list of Driver classes that have registered
themselves.

Java Difference Interview Questions

197. Differentiate between Iterable and Iterator.

Iterable

Iterator

Iterable provides a way to iterate over a sequence of elements.

Iterator helps in iterating over a collection of elements sequentially.

iterator() method returns an Iterator. hasNext() and next() methods are required.

remove() method is optional. remove() method is required in the iterator.

Examples are List, Queue, and Set.


Examples are ListIterator, Enumeration, and ArrayIterator.

198. Differentiate between List and Set.

List

Set

Ordered

Unordered

List allows duplicates.

Set does not allow duplicate values.

List is accessed by index.

Set is accessed by hashcode.

Multiple null elements can be stored.

Null element can store only once.

Examples are ArrayList, LinkedList, etc.

Examples are HashSet and TreeSet. LinkedHashSet etc.

199. Differentiate between List and Map.


List

Map

List interface allows duplicate elements.

Map does not allow duplicate elements.

List maintains insertion order.

Map do not maintain insertion order.

Multiple null elements can be stored.

The map allows a single null key at most and any number of null values.

The list provides get() method to get the element at a specified index.

The map does not provide a get method to get the elements at a specified index.

List is Implemented by ArrayList, etc.

Map is Implemented by HashMap, TreeMap, LinkedHashMap

200. Differentiate between Queue and Stack.

Queue

Stack
Queue data structure is used to store elements, and is used to perform operations like enqueue,
dequeue from back or end of the queue.

Stack data structure is used to store elements, and is used to perform operations like push, pop from
top of the stack.

Queue data structure Implements FIFO order.

Stack data structure Implements LIFO order.

Insertion and deletion in queues take place from the opposite ends of the list. Deletion takes place from
the front of the list and insertion takes place at the rear of the list.

Insertion and deletion in stacks take place only from one end of the list called the top.

Insert operation is called enqueue operation.

Insert operation is called Push operation.

Queue is generally used to solve problems related to sequential processing.

Stack is generally used to solve problems related to recursion.

201. Differentiate between PriorityQueue and TreeSet.

Priority Queue

TreeSet

It uses Queue as an underlying data structure.


It uses a Set as an underlying data structure.

This data structure allows duplicate elements

This data structure does not allow duplicate elements

Priority Queue is Implemented by PriorityQueue class.

TreeSet is implemented by TreeSet class.

PriorityQueue comes in JDK 1.5.

TreeSet comes in JDK 1.4.

PriorityQueue<Integer> pq = new PriorityQueue<>();

reeSet<Integer> ts = new TreeSet<>();

202. Differentiate between the Singly Linked List and Doubly Linked List.

Singly Linked List

Doubly Linked List

Singly Linked List contain only two segments i.e, Data and Link.

Doubly Linked List contains three segments i.e, Data, and two pointers.

Traversal in a singly linked list is possible in only a forward direction.


Traversal in a doubly linked list is only possible in both directions forward as well as backward.

It uses less memory as every single node has only one pointer.

It requires more memory than a singly linked list as each node has two pointers.

Easy to use and insert nodes at the beginning of the list.

Slightly more complex to use and easy to insert at the end of the list.

The time complexity of insertion and deletion is O(n).

The time complexity of insertion and deletion is O(1).

Singly-Linked-List-660

Doubly-Linked-List-660

203. Differentiate between Failfast and Failsafe.

FailFast

FailSafe

Failsfast fails immediately when it detects concurrent modification during the time of iteration.

Failsafe continues to iterate over the original collection and also creates a copy to modify.

Failfast is generally used in single-threaded environments.


Failsafe is used in multithreaded environments.

Failfast does not allow any modification while iteration.

Failsafe allows modification during the time of iteration.

Failfast is fast compared to failsafe as it does not involve the copying of the collection.

Failsafe is generally slow compared to failfast.

FailFast throws ConcurrentModificationException if the collection is modified during iteration.

FailSafe does not throws any exception but instead, it creates a copy of the collection to iterate.

204. Differentiate between HashMap and TreeMap.

HashMap

TreeMap

Hasmap uses a hashtable in order to store key-value pairs.

Treemap uses Red-black trees to store key-value pair.

Hashmap does not maintain any specific order for key-value pairs.

Treemap maintains a natural ordering based on the keys.


Order of iteration is not guaranteed in the hashmap.

Iteration is of sorted order based on keys.

Hashmaps are faster for retrieval compared to Treemap.

Retrieval in Treemap is slower as it uses tree traversal to find keys.

Hashmap is implemented by using an Array of linked list.

TreeMap is implemented using a Red-black Tree.

Hashmap uses the equals() method of the Object class to compare keys.

TreeMap uses compareTo() method to compare keys.

205. Differentiate between Queue and Deque.

Queue

Deque

The queue is a linear Data structure that is used to store a collection of elements.

Deque also known as a Double-ended queue is also a linear data structure that stores a collection of
elements with operations to remove and add from both ends.

Elements in the queue can only be inserted at the end of the data structure.

Elements can be inserted from both ends of the data structure.


Queue can be implemented using Array or Linked List.

Dequeue can be implemented using Circular Array or Doubly Linked List.

Queues are generally used to implement a waiting list or task queue.

Deque is used to implement a stack or dequeuing elements from both ends.

Queue-660

Doubly-Ended-Queue-660

206. Differentiate between HashSet and TreeSet.

HashSet

TreeSet

HashSet is unordered.

TreeSet is based on natural ordering.

HashSet allows null elements.

TreeSet does not allow null elements.

HashSet is Implemented by the HashSet class.

TreeSet is Implemented by TreeSet class.


HashSet<String> hs = new HashSet<>();

TreeSet<String> ts = new TreeSet<>();

Core-Java-Interview-Questions

Java Interview Questions – FAQs

Q1. What is a Java Developer’s salary in India?

According to various resources, The average salary of a Java Backend Developer is more than 14 lakhs
per annum which is 30% higher than any other developer role. Here you can also check our latest course
on Java Backend Development!

Q2. What does Java Developer do?

A Java developer writes code, designs software solutions, and builds applications using the Java
programming language. They collaborate with teams, solve problems, and ensure code quality for
efficient and reliable software development.

Q3. What are the essential skills required for a Java developer?

A Java developer should have a strong understanding of core Java concepts such as object-oriented
programming, data types, control structures, and exception handling. Additionally, knowledge of
frameworks like Spring, Hibernate, and web development technologies like Servlets and JSP is beneficial.
Other than Technical Skills Problem-solving, debugging, and critical thinking skills are also highly valued.

Source : https://leetcode.com/discuss/interview-question/5261135/Java-Interview-Questions/

Core Java Concepts

What is the difference between JDK and JRE?

Why is Java a platform independent language?

What is the difference between an abstract class and an interface?

What is the difference between final, finally, and finalize?

What is the difference between stack and heap memory?


What is the difference between method overloading and method overriding?

What is the difference between an abstract class and an interface?

What is the difference between a private and a protected modifier?

What is constructor overloading in Java?

What is the use of super keyword in Java?

What is the difference between static methods, static variables, and static classes in Java?

What exactly is System.out.println in Java?

What part of memory - Stack or Heap - is cleaned in the garbage collection process?

Source #04 : https://www.javatpoint.com/java-interview-questions-for-5-years-experienced

Q1. Differentiate between Transient and Volatile Variable in Java.

Transient Variable

Volatile Variable

The keyword transient is used when one does not want the variable to be serialized.

The keyword volatile against the name of the variable shows that whatever content is there in the
variable, is stored in the main memory. Thus, all the read of that variable must be done using the main
memory and not from the CPU cache, and every write should also be done to the main memory.

The Transient keyword provides control and flexibility over the different object's attributes from getting
serialized.

The volatile keyword guarantees that the Java Virtual Machine does not do the re-ordering of the
variables and makes sure that the issues related to synchronization are avoided.

The variables decorated with the transient keyword are assigned default values as per their data types
when deserialization occurs.

There are no default values assigned to a volatile variable.

Static keyword can not be used with the transient variable. It is because static variables are directly
associated with the Class and not with the instances of the class, and this matters a lot during
serialization.

One can use static keyword with the volatile keyword.

Q2. Observe the following code and answer the following.

The two threads: Th1 and Th3 are given to us. Th1 is accessing the method1() method. Will Th3 be able
to access the method2() method at the same time and on the same instance?
Class ABC

synchronized void method1()

System.out.println("In method - 1");

void method2()

System.out.println("In method - 2");

Answer: Yes, Th3 will be able to access method2() as it is not decorated with the keyword synchronized
and hence does not require a lock for accessing it.

Q3. Explain the significance of … in the following method's parameters.

public void fooMethod(String... infoArgs)

// body of the method

In Java 5, the 3 dots feature was introduced. The feature is also called varargs (which means variable
arguments). It implies that the method can receive one or more than one String, as mentioned below:

fooMethod("Java", "T", "point");

fooMethod("Interview", "Java", "Questions");

fooMethod(new String[]{"Questions", "of", "Java", "Interview", "Questions"});


These received arguments can be used as an array and can be accessed by iterating

through loops as shown below:

public void someMethod(String... infoArgs)

for(String fewInfo : infoArgs)

// any operation

// The infoArgs can be acquired with the help of index-based loops too.

for( int i = 0; i < infoArgs.length; i++)

String s = info[i];

//some operation

Q4. Distinguish between the ArrayList and Vector in Java.

Vector and ArrayList are the classes of collection. Both the classes are derived from the AbstractList and
implement the List interface.

ArrayList

Vector

ArrayList is neither synchronized nor thread-safe.

Vector is, by default, synchronized and thread-safe. It means the internal state of the Class is not
affected even if the multiple threads are operating simultaneously.

Since ArrayList is not synchronized, it works quickly as compared to Vector.

There is an overhead of synchronization that comes along with Vector. Hence, it is slower than ArrayList.
Q5. Explain the significance of the equals() and hashCode() contract.

Consider a scenario of the object of HashMap. It is a known fact that the HashMap key utilizes the
hashCode() and the equals() method for finding the index or finding a key's value. Therefore, it is
required to implement these methods properly. If these methods are not implemented properly, then
hashMap will not work properly. The HashMap will pick the wrong key for updating the values.
Therefore, it is important to correctly implement the equals() and the hashCode() methods. It is done
properly only when we follow the hashCode-equals contract in a proper way.

The contract hashCode-equals contract says:

If two objects are the same or equal, then the method hashCode() should always generate the same
result for both objects.

To make sure the above contract, one has to override the method hashCode() whenever the method
equals() is overridden.

Q6. What will be printed on the console if the following print statement is run?

System.out.println(1.0/0.0);

The values 1.0 or 0.0 are double values. The Double class has a specific set of rules, such as -0.0, NaN,
Double.INFINITY, etc., which supports in arithmetic computations. The above print statement will print
Infinity on the console without giving any arithmetic exceptions.

Q7. What is the difference between the path variables and the classpath variables?

In the operating system, the path variable is present and is utilized for spotting the system executables.
The classpath variables are used for finding the .class files and are related to Java executables.

Q8. Obtain the result of the following code. Also, find the reason for that result.

public class SomeClass

// main method

public static void main(String[] argvs)


{

meth1(null);

public static void meth1(Object o)

System.out.println("Object method is getting Invoked.");

public static void meth1(String str)

System.out.println("String method is getting Invoked.");

The output of the above program is "String method is getting Invoked.".

It is a known fact that a null value can be assigned to any reference type object in Java. Therefore, the
object o, and the String str, can both take the null value. However, the output is only related to the print
statement of the method meth1(), which takes the String as a parameter. The reason behind it is the
nature of the Java compiler. The Java compiler picks that method that has more specific parameters,
which is String in our Case. Note that the Object class is a class that is the parent class of each and every
class in Java.

Q9. Identify the more appropriate approach from the given two approaches to invoke the wait() method

1) Using the loop construct

2) Using the if construct

The first approach is the more appropriate one. It is because the wait() method should be invoked using
the loop construct. It is because when any thread gets the required resources to start execution again, it
is advised to verify the condition before starting the execution.

The way of doing it is mentioned below.


synchronized (res)

while(wait condtn)

res.wait(); // resource lock is released and reacquire it after waiting

// Do the tasks

Q10. In a multi-threaded environment, can someone use a HashMap?

Yes, it is possible to use a HashMap in a multi-threaded environment. But whether the HashMap will
work properly or not depends on the user that is using it. If the initialization of the HashMap is done by
only one thread, and the rest of the other threads do only the reading from the HashMap, then the
HashMap will work fine.

The problem comes when one of the threads does the updation work by deleting, updating, or adding
the content of the map. Thus, resizing the HashMap that can lead to an infinite loop or deadlock. In such
a case, one can use ConcurrentHashMap or HashTable.

Q11. Find the result of the following code. Also, find the reason for it.

public class JTPProblem

// main method

public static void main(String[] argvs)

// the two print statements

System.out.println(0.2 == 0.1*2);

System.out.println(0.3 == 0.1*3);

Output:
System.out.println(0.2 == 0.1*2); // gives a true value

System.out.println(0.3 == 0.1*3); // gives a false value

Reason: The above-given output is because of that mismatch that is occurring because of the error that
occurs in rounding the floating-point numbers. Only the floating-point numbers that are power of 2, are
represented precisely by the binary representation. Others are rounded off. Therefore, the first print
statement gives a true value and the second one a false value.

Source #05 : https://www.guru99.com/java-interview-questions-answers.html

1) What is the difference between an Inner Class and a Sub-Class?

An Inner class is a class which is nested within another class. An Inner class has access rights for the class
which is nesting it and it can access all variables and methods defined in the outer class.

A sub-class is a class which inherits from another class called super class. Sub-class can access all public
and protected methods and fields of its super class.

👉 Free PDF Download: Java Interview Interview Questions & Answers >>

2) What are the various access specifiers for Java classes?

In Java, access specifiers are the keywords used before a class name which defines the access scope. The
types of access specifiers for classes are:

1) Public: Class,Method,Field is accessible from anywhere.

2) Protected: Method,Field can be accessed from the same class to which they belong or from the sub-
classes, and from the class of same package, but not from outside.

3) Default: Method,Field,class can be accessed only from the same package and not from outside of it’s
native package.
4) Private: Method,Field can be accessed from the same class to which they belong.

3) What’s the purpose of Static methods and static variables?

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.

4) What is data encapsulation and what’s its significance?

Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a
single unit.

Encapsulation helps programmers to follow a modular approach for software development as each
object has its own set of methods and variables and serves its functions independent of other objects.
Encapsulation also serves data hiding purpose.

5) What is a singleton class? Give a practical example of its usage.

A singleton class in java can have only one instance and hence all its methods and variables belong to
just one instance. Singleton class concept is useful for the situations when there is a need to limit the
number of objects for a class.

The best example of singleton usage scenario is when there is a limit of having only one connection to a
database due to some driver limitations or because of any licensing issues.

6) What are Loops in Java? What are three types of loops?

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

1) For Loops

For loops are used in java to execute statements repeatedly for a given number of times. For loops are
used when number of times to execute the statements is known to programmer.
2) While Loops

While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled.
In while loops, condition is checked first before execution of statements.

3) Do While Loops

Do While Loop is same as While loop with only difference that condition is checked after execution of
block of statements. Hence in case of do while loop, statements are executed at least once.

RELATED ARTICLES

Java Program to Check Prime Number

How to Reverse a String in Java using Recursion

7) What is an infinite Loop? How infinite loop is declared?

An infinite loop runs without any condition and runs infinitely. An infinite loop can be broken by defining
any breaking logic in the body of the statement blocks.

Infinite loop is declared as follows:

for (;;)

// Statements to execute

// Add any loop breaking logic

8) What is the difference between continue and break statement?

break and continue are two important keywords used in Loops. When a break keyword is used in a loop,
loop is broken instantly while when continue keyword is used, current iteration is broken and loop
continues with next iteration.
In below example, Loop is broken when counter reaches 4.

for (counter = 0; counter & lt; 10; counter++)

system.out.println(counter);

if (counter == 4) {

break;

In the below example when counter reaches 4, loop jumps to next iteration and any statements after
the continue keyword are skipped for current iteration.

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

system.out.println(counter);

if (counter == 4) {

continue;

system.out.println("This will not get printed when counter is 4");

9) What is the difference between double and float variables in Java?

In java, float takes 4 bytes in memory while Double takes 8 bytes in memory. Float is single precision
floating point decimal number while Double is double precision decimal number.

10) What is Final Keyword in Java? Give an example.


In java, a constant is declared using the keyword Final. Value can be assigned only once and after
assignment, value of a constant can’t be changed.

In below example, a constant with the name const_val is declared and assigned avalue:

Private Final int const_val=100

When a method is declared as final, it can NOT be overridden by the subclasses. This method are faster
than any other method, because they are resolved at complied time.

When a class is declares as final, it cannot be subclassed. Example String, Integer and other wrapper
classes.

11) What is ternary operator? Give an example.

Ternary operator , also called conditional operator is used to decide which value to assign to a variable
based on a Boolean value evaluation. It’s denoted as ?

In the below example, if rank is 1, status is assigned a value of “Done” else “Pending”.

public class conditionTest {

public static void main(String args[]) {

String status;

int rank = 3;

status = (rank == 1) ? "Done" : "Pending";

System.out.println(status);

12) How can you generate random numbers in Java?

Using Math.random() you can generate random numbers in the range greater than or equal to 0.1 and
less than 1.0
Using Random class in package java.util

13) What is default switch case? Give example.

In a switch statement, default case is executed when no other switch condition matches. Default case is
an optional case .It can be declared only once all other switch cases have been coded.

In the below example, when score is not 1 or 2, default case is used.

public class switchExample {

int score = 4;

public static void main(String args[]) {

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");

14) What’s the base class in Java from which all classes are derived?

java.lang.object

15) Can main() method in Java can return any data?

In java, main() method can’t return any data and hence, it’s always declared with a void return type.

16) What are Java Packages? What’s the significance of packages?


In Java, package is a collection of classes and interfaces which are bundled together as they are related
to each other. Use of packages helps developers to modularize the code and group the code for proper
re-use. Once code has been packaged in Packages, it can be imported in other classes and used.

17) Can we declare a class as Abstract without having any abstract method?

Yes we can create an abstract class by using abstract keyword before class name even if it doesn’t have
any abstract method. However, if a class has even one abstract method, it must be declared as abstract
otherwise it will give an error.

18) What’s the difference between an Abstract Class and Interface in Java?

The primary difference between an abstract class and interface is that an interface can only possess
declaration of public static methods with no concrete implementation while an abstract class can have
members with any access specifiers (public, private etc) with or without concrete implementation.

Another key difference in the use of abstract classes and interfaces is that a class which implements an
interface must implement all the methods of the interface while a class which inherits from an abstract
class doesn’t require implementation of all the methods of its super class.

A class can implement multiple interfaces but it can extend only one abstract class.

19) What are the performance implications of Interfaces over abstract classes?

Interfaces are slower in performance as compared to abstract classes as extra indirections are required
for interfaces. Another key factor for developers to take into consideration is that any class can extend
only one abstract class while a class can implement many interfaces.

Use of interfaces also puts an extra burden on the developers as any time an interface is implemented in
a class; developer is forced to implement each and every method of interface.

20) Does Importing a package imports its sub-packages as well in Java?

In java, when a package is imported, its sub-packages aren’t imported and developer needs to import
them separately if required.
For example, if a developer imports a package university.*, all classes in the package named university
are loaded but no classes from the sub-package are loaded. To load the classes from its sub-package (say
department), developer has to import it explicitly as follows:

Import university.department.*

21) Can we declare the main method of our class as private?

In java, main method must be public static in order to run any application correctly. If main method is
declared as private, developer won’t get any compilation error however, it will not get executed and will
give a runtime error.

22) How can we pass argument to a function by reference instead of pass by value?

In java, we can pass argument to a function only by value and not by reference.

23) How an object is serialized in java?

In java, to convert an object into byte stream by serialization, an interface with the name Serializable is
implemented by the class. All objects of a class implementing serializable interface get serialized and
their state is saved in byte stream.

24) When we should use serialization?

Serialization is used when data needs to be transmitted over the network. Using serialization, object’s
state is saved and converted into byte stream .The byte stream is transferred over the network and the
object is re-created at destination.

25) Is it compulsory for a Try Block to be followed by a Catch Block in Java for Exception handling?

Try block needs to be followed by either Catch block or Finally block or both. Any exception thrown from
try block needs to be either caught in the catch block or else any specific tasks to be performed before
code abortion are put in the Finally block.

Java Interview Questions and Answers for Experienced

26) Is there any way to skip Finally block of exception even if some exception occurs in the exception
block?
If an exception is raised in Try block, control passes to catch block if it exists otherwise to finally block.
Finally block is always executed when an exception occurs and the only way to avoid execution of any
statements in Finally block is by aborting the code forcibly by writing following line of code at the end of
try block:

System.exit(0);

27) When the constructor of a class is invoked?

The constructor of a class is invoked every time an object is created with new keyword.

For example, in the following class two objects are created using new keyword and hence, constructor is
invoked two times.

public class const_example {

const_example() {

system.out.println("Inside constructor");

public static void main(String args[]) {

const_example c1 = new const_example();

const_example c2 = new const_example();

28) Can a class have multiple constructors?

Yes, a class can have multiple constructors with different parameters. Which constructor gets used for
object creation depends on the arguments passed while creating the objects.

29) Can we override static methods of a class?


We cannot override static methods. Static methods belong to a class and not to individual objects and
are resolved at the time of compilation (not at runtime).Even if we try to override static method, we will
not get an complitaion error,nor the impact of overriding when running the code.

30) In the below example, what will 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();

Ans: Output will be:

Displaying from subClass

Printing from superclass

31) Is String a data type in java?

String is not a primitive data type in java. When a string is created in java, it’s actually an object of
Java.Lang.String class that gets created. After creation of this string object, all built-in methods of String
class can be used on the string object.

32) In the below example, how many String Objects are created?

String s1="I am Java Expert";

String s2="I am C Expert";

String s3="I am Java Expert";

In the above example, two objects of Java.Lang.String class are created. s1 and s3 are references to
same object.

33) Why Strings in Java are called as Immutable?

In java, string objects are called immutable as once value has been assigned to a string, it can’t be
changed and if changed, a new object is created.

In below example, reference str refers to a string object having value “Value one”.
String str="Value One";

When a new value is assigned to it, a new String object gets created and the reference is moved to the
new object.

str="New Value";

34) What’s the difference between an array and Vector?

An array groups data of same primitive type and is static in nature while vectors are dynamic in nature
and can hold data of different data types.

35) What is multi-threading?

Multi threading is a programming concept to run multiple tasks in a concurrent manner within a single
program. Threads share same process stack and running in parallel. It helps in performance
improvement of any program.

36) Why Runnable Interface is used in Java?

Runnable interface is used in java for implementing multi threaded applications. Java.Lang.Runnable
interface is implemented by a class to support multi threading.

37) What are the two ways of implementing multi-threading in Java?

Multi threaded applications can be developed in Java by using any of the following two methodologies:

1) By using Java.Lang.Runnable Interface. Classes implement this interface to enable multi threading.
There is a Run() method in this interface which is implemented.

2) By writing a class that extend Java.Lang.Thread class.

38) When a lot of changes are required in data, which one should be a preference to be used? String or
StringBuffer?

Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects unlike
String which is immutable, it’s always a good choice to use StringBuffer when data is being changed too
much. If we use String in such a case, for every data change a new String object will be created which
will be an extra overhead.

39) What’s the purpose of using Break in each case of Switch Statement?

Break is used after each case (except the last one) in a switch so that code breaks after the valid case
and doesn’t flow in the proceeding cases too.

If break isn’t used after each case, all cases after the valid case also get executed resulting in wrong
results.

40) How garbage collection is done in Java?

In java, when an object is not referenced any more, garbage collection takes place and the object is
destroyed automatically. For automatic garbage collection java calls either System.gc() method or
Runtime.gc() method.

41) How we can execute any code even before main method?

If we want to execute any statements before even creation of objects at load time of class, we can use a
static block of code in the class. Any statements inside this static block of code will get executed once at
the time of loading the class even before creation of objects in the main method.

42) Can a class be a super class and a sub-class at the same time? Give example.

If there is a hierarchy of inheritance used, a class can be a super class for another class and a sub-class
for another one at the same time.

In the example below, continent class is sub-class of world class and it’s super class of country class.

public class world {

..........

public class continenet extends world {


............

public class country extends continent {

......................

43) How objects of a class are created if no constructor is defined in the class?

Even if no explicit constructor is defined in a java class, objects get created successfully as a default
constructor is implicitly used for object creation. This constructor has no parameters.

44) In multi-threading how can we ensure that a resource isn’t used by multiple threads simultaneously?

In multi-threading, access to the resources which are shared among multiple threads can be controlled
by using the concept of synchronization. Using synchronized keyword, we can ensure that only one
thread can use shared resource at a time and others can get control of the resource only once it has
become free from the other one using it.

45) Can we call the constructor of a class more than once for an object?

Constructor is called automatically when we create an object using new keyword. It’s called only once
for an object at the time of object creation and hence, we can’t invoke the constructor again for an
object after its creation.

46) There are two classes named classA and classB. Both classes are in the same package. Can a private
member of classA can be accessed by an object of classB?

Private members of a class aren’t accessible outside the scope of that class and any other class even in
the same package can’t access them.

Source #06 : https://www.baeldung.com/java-interview-questions

Q1. Is Data Passed by Reference or by Value in Java?


Although the answer to this question is pretty simple, this question may be confusing for beginners.
First, let’s clarify what the question is about:

Passing by value – means that we pass a copy of an object as a parameter into a method.

Passing by reference – means that we pass a reference to an object as a parameter into a method.

To answer the question we have to analyze two cases. They represent two types of data that we can
pass to a method: a primitive and an object.

When we pass primitives to a method, its value is copied into a new variable. When it comes to objects,
the value of the reference is copied into a new variable. So we can say that Java is a strictly pass-by-
value language.

We can learn more about that in one of our articles: Pass-By-Value as a Parameter Passing Mechanism in
Java.

Q2. What Is the Difference Between Import and Static Imports?

We can use regular imports to import a specific class or all classes defined in a different package:

import java.util.ArrayList; //specific class

import java.util.*; //all classes in util package

Copy

We can also use them to import public nested classes of an enclosing class:

import com.baeldung.A.*

Copy

However, we should be aware that the import above doesn’t import class A itself.

There are also static imports that enable us to import static members or nested classes:

import static java.util.Collections.EMPTY_LIST;


Copy

The effect is that we can use the static variable EMPTY_LIST without prepending the fully qualified class
name, i.e. as if it was declared in the current class.

Q3. Which Access Modifiers Are Available in Java and What Is Their Purpose?

There are four access modifiers in Java:

private

default (package)

protected

public

The private modifier assures that class members won’t be accessible outside the class. It can be applied
to methods, properties, constructors, nested classes, but not to top-level classes themselves.

Unlike the private modifier, we can apply the default modifier to all types of class members and to the
class itself. We can apply default visibility by not adding any access modifier at all. If we use default
visibility our class or its members will be accessible only inside the package of our class. We should keep
in mind that the default access modifier has nothing in common with the default keyword.

Similar to the default modifier, all classes within one package can access protected members. What’s
more, the protected modifier allows subclasses to access the protected members of a superclass, even if
they are not within the same package. We can’t apply this access modifier to classes, only to class
members.

The public modifier can be used together with the class keyword and all class members. It makes classes
and class members accessible in all packages and by all classes.

We can learn more in the Java Access Modifiers article.

Q4. Which Other Modifiers Are Available in Java and What Is Their Purpose?

There are five other modifiers available in Java:


static

final

abstract

synchronized

volatile

These do not control visibility.

First of all, we can apply the static keyword to fields and methods. Static fields or methods are class
members, whereas non-static ones are object members. Class members don’t need an instance to be
invoked. They are called with the class name instead of the object reference name. This article goes into
more detail about the static keyword.

Then, we have the final keyword. We can use it with fields, methods, and classes. When final is used on
a field, it means that the field reference cannot be changed. So it can’t be reassigned to another object.
When final is applied to a class or a method, it assures us that that class or method cannot be extended
or overridden. The final keyword is explained in more detail in this article.

The next keyword is abstract. This one can describe classes and methods. When classes are abstract,
they can’t be instantiated. Instead, they are meant to be subclassed. When methods are abstract, they
are left without implementation and can be overridden in subclasses.

The synchronized keyword may be the most advanced. We can use it with the instance as well as with
static methods and code blocks. When we use this keyword, we make Java use a monitor lock to provide
synchronization on a given code fragment. More information about synchronized can be found in this
article.

The last keyword we’re going to discuss is volatile. We can only use it together with instance and static
fields. It declares that the field value must be read from and written to the main memory – bypassing
the CPU cache. All reads and writes for a volatile variable are atomic. The volatile keyword is explained
in detail in this article.

Q5. What Is the Difference Between JDK, JRE, and JVM?

JDK stands for Java Development Kit, which is a set of tools necessary for developers to write
applications in Java. There are three types of JDK environments:
Standard Edition – development kit for creating portable desktop or server applications

Enterprise Edition – an extension to the Standard Edition with support for distributed computing or web
services

Micro Edition – development platform for embedded and mobile applications

There are plenty of tools included in the JDK which help programmers with writing, debugging, or
maintaining applications. The most popular ones are a compiler (javac), an interpreter (java), an archiver
(jar), and a documentation generator (javadoc).

JRE is a Java Runtime Environment. It’s a part of the JDK, but it contains the minimum functionality to
run Java applications. It consists of a Java Virtual Machine, core classes, and supporting files. For
example, it doesn’t have any compiler.

JVM is the acronym for Java Virtual Machine, which is a virtual machine able to run programs compiled
to bytecode. It’s described by the JVM specification, as it’s important to ensure interoperability between
different implementations. The most important function of a JVM is to enable users to deploy the same
Java application into different operating systems and environments without worrying about what lies
underneath.

For more information, let’s check the Difference Between JVM, JRE, and JDK article.

Q6. What Is the Difference Between Stack and Heap?

There are two parts of memory where all variables and objects are stored by the JVM. The first is the
stack and the second is the heap.

The stack is a place where the JVM reserves blocks for local variables and additional data. The stack is a
LIFO (last in first out) structure. It means that whenever a method is called, a new block is reserved for
local variables and object references. Each new method invocation reserves the next block. When
methods finish their execution, blocks are released in the reversed manner they were started.

Every new thread has its own stack.


We should be aware that the stack has much less memory space than the heap. And when a stack is full,
the JVM will throw a StackOverflowError. It’s likely to occur when there is a bad recursive call and the
recursion goes too deep.

Every new object is created on the Java heap which is used for a dynamic allocation. There is a garbage
collector which is responsible for erasing unused objects which are divided into young (nursery) and old
spaces. Memory access to the heap is slower than access to the stack. The JVM throws an
OutOfMemoryError when the heap is full.

We can find more details in the Stack Memory and Heap Space in Java article.

Q7. What Is the Difference Between the Comparable and Comparator Interfaces?

Sometimes when we write a new class, we would like to be able to compare objects of that class. It’s
especially helpful when we want to use sorted collections. There are two ways we can do this: with the
Comparable interface or with the Comparator interface.

First, let’s look at the Comparable interface:

public interface Comparable<T> {

int compareTo(T var1);

Copy

We should implement that interface by the class whose objects we want to sort.

It has the compareTo() method and returns an integer. It can return three values: -1, 0, and 1 which
means that this object is less than, equal to or greater than the compared object.

It’s worth mentioning that the overridden compareT0() method should be consistent with the equals()
method.

On the other hand, we can use the Comparator interface. It can be passed to the sort() methods of the
Collection interface or when instantiating sorted collections. That’s why it’s mostly used to create a one-
time sorting strategy.
What’s more, it’s also useful when we use a third-party class that doesn’t implement the Comparable
interface.

Like the compareTo() method, the overridden compare() methods should be consistent with the
equals() method, but they may optionally allow comparison with nulls.

Let’s visit the Comparator and Comparable in Java article for more information.

Q8. What Is the void Type and When Do We Use It?

Every time we write a method in Java, it must have a return type. If we want the method to return no
value, we can use the void keyword.

We should also know that there is a Void class. It’s a placeholder class that may be used, for example,
when working with generics. The Void class can neither be instantiated nor extended.

Q9. What Are the Methods of the Object Class and What Do They Do?

It’s important to know what methods the Object class contains and how they work. It’s also very helpful
when we want to override those methods:

clone() – returns a copy of this object

equals() – returns true when this object is equal to the object passed as a parameter

finalize() – the garbage collector calls this method while it’s cleaning the memory

getClass() – returns the runtime class of this object

hashCode() – returns a hash code of this object. We should be aware that it should be consistent with
the equals() method

notify() – sends a notification to a single thread waiting for the object’s monitor

notifyAll() – sends a notification to all threads waiting for the object’s monitor

toString() – returns a string representation of this object

wait() – there are three overloaded versions of this method. It forces the current thread to wait the
specified amount of time until another thread calls notify() or notifyAll() on this object.
Q10. What Is an Enum and How We Can Use It?

Enum is a type of class that allows developers to specify a set of predefined constant values. To create
such a class we have to use the enum keyword. Let’s imagine an enum of days of the week:

public enum Day {

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

Copy

To iterate over all constants we can use the static values() method. What’s more, enums enable us to
define members such as properties and methods like regular classes.

Although it’s a special type of class, we can’t subclass it. An enum can, however, implement an interface.

Another interesting advantage of Enums is that they are thread-safe and so they are popularly used as
singletons.

We can find more about Enums in one of our guides.

Q11. What Is a JAR?

JAR is a shortcut for Java archive. It’s an archive file packaged using the ZIP file format. We can use it to
include the class files and auxiliary resources that are necessary for applications. It has many features:

Security – we can digitally sign JAR files

Compression – while using a JAR, we can compress files for efficient storage

Portability – we can use the same JAR file across multiple platforms

Versioning – JAR files can hold metadata about the files they contain

Sealing – we can seal a package within a JAR file. This means that all classes from one package must be
included in the same JAR file

Extensions – we can use the JAR file format to package modules or extensions for existing software

Q12. What Is a NullPointerException?


The NullPointerException is probably the most common exception in the Java world. It’s an unchecked
exception and thus extends RuntimeException. We shouldn’t try to handle it.

This exception is thrown when we try to access a variable or call a method of a null reference, like when:

invoking a method of a null reference

setting or getting a field of a null reference

checking the length of a null array reference

setting or getting an item of a null array reference

throwing null

Q13. What Are Two Types of Casting in Java? Which Exception May Be Thrown While Casting? How Can
We Avoid It?

We can distinguish two types of casting in Java. We can do upcasting which is casting an object to a
supertype or downcasting which is casting an object to a subtype.

Upcasting is very simple, as we always can do that. For example, we can upcast a String instance to the
Object type:

Object str = "string";

Copy

Alternatively, we can downcast a variable. It’s not as safe as upcasting as it involves a type check. If we
incorrectly cast an object, the JVM will throw a ClassCastExcpetion at runtime. Fortunately, we can use
the instanceof keyword to prevent invalid casting:

Object o = "string";

String str = (String) o; // it's ok

Object o2 = new Object();

String str2 = (String) o2; // ClassCastException will be thrown

if (o2 instanceof String) { // returns false


String str3 = (String) o2;

Copy

We can learn more about typecasting in this article.

3. Core Java Questions for Advanced Programmers

Q1. Why Is String an Immutable Class?

We should know that String objects are treated differently than other objects by the JVM. One
difference is that String objects are immutable. It means that we can’t change them once we have
created them. There are several reasons why they behave that way:

They are stored in the string pool which is a special part of the heap memory. It’s responsible for saving
a lot of space.

The immutability of the String class guarantees that its hash code won’t change. Due to that fact, Strings
can be effectively used as keys in hashing collections. We can be sure that we won’t overwrite any data
because of a change in hash codes.

They can be used safely across several threads. No thread can change the value of a String object, so we
get thread safety for free.

Strings are immutable to avoid serious security issues. Sensitive data such as passwords could be
changed by an unreliable source or another thread.

We can learn more about the immutability of Strings in this article.

Q2. What Is the Difference Between Dynamic Binding and Static Binding?

Binding in Java is a process of associating a method call with the proper method body. We can
distinguish two types of binding in Java: static and dynamic.

The main difference between static binding and dynamic binding is that static binding occurs at compile
time and dynamic binding at runtime.

Static binding uses class information for binding. It’s responsible for resolving class members that are
private or static and final methods and variables. Also, static binding binds overloaded methods.
Dynamic binding, on the other hand, uses object information to resolve bindings. That’s why it’s
responsible for resolving virtual and overridden methods.

Q3. What Is JIT?

JIT stands for “just in time”. It’s a component of the JRE that runs in the runtime and increases the
performance of the application. Specifically, it’s a compiler that runs just after the program’s start.

This is different from the regular Java compiler which compiles the code long before the application is
started. JIT can speed up the application in different ways.

For example, the JIT compiler is responsible for compiling bytecode into native instructions on the fly to
improve performance. Also, it can optimize the code to the targeted CPU and operating system.

Additionally, it has access to many runtime statistics which may be used for recompilation for optimal
performance. With this, it can also do some global code optimizations or rearrange code for better
cache utilization.

Q4. What Is Reflection in Java?

Reflection is a very powerful mechanism in Java. Reflection is a mechanism of Java language which
enables programmers to examine or modify the internal state of the program (properties, methods,
classes etc.) at runtime. The java.lang.reflect package provides all required components for using
reflection.

When using this feature, we can access all possible fields, methods, constructors that are included
within a class definition. We can access them irrespective of their access modifier. It means that for
example, we are able to access private members. To do that, we don’t have to know their names. All we
have to do is to use some static methods of Class.

It’s worth knowing that there is a possibility to restrict access via reflection. To do that we can use the
Java security manager and the Java security policy file. They allow us to grant permissions to classes.

When working with modules since Java 9, we should know that by default, we aren’t able to use
reflection on classes imported from another module. To allow other classes to use reflection to access
the private members of a package we have to grant the “Reflection” Permission.
This article goes into more depth about Java Reflection.

Q5. What Is a Classloader?

The classloader is one of the most important components in Java. It’s a part of the JRE.

Simply put, the classloader is responsible for loading classes into the JVM. We can distinguish three
types of classloaders:

Bootstrap classloader – it loads the core Java classes. They are located in the <JAVA_HOME>/jre/lib
directory

Extension classloader – it loads classes located in <JAVA_HOME>/jre/lib/ext or in the path defined by


the java.ext.dirs property

System classloader – it loads classes on the classpath of our application

A classloader loads classes “on demand”. It means that classes are loaded after they are called by the
program. What’s more, a classloader can load a class with a given name only once. However, if the same
class is loaded by two different class loaders, then those classes fail in an equality check.

There is more information about classloaders in the Class Loaders in Java article.

Q6. What Is the Difference Between Static and Dynamic Class Loading?

Static class loading takes place when we have source classes available at compile time. We can make use
of it by creating object instances with the new keyword.

Dynamic class loading refers to a situation when we can’t provide a class definition at the compile time.
Yet, we can do that at runtime. To create an instance of a class, we have to use the Class.forName()
method:

Class.forName("oracle.jdbc.driver.OracleDriver")

Copy

Q7. What Is the Purpose of the Serializable Interface?


We can use the Serializable interface to enable the serializability of a class, using Java’s Serialization API.
Serialization is a mechanism for saving the state of an object as a sequence of bytes while deserialization
is a mechanism for restoring the state of an object from a sequence of bytes. The serialized output holds
the object’s state and some metadata about the object’s type and types of its fields.

We should know that subtypes of serializable classes are also serializable. However, if we want to make
a class serializable, but its supertype is non-serializable we have to do two things:

implement the Serializable interface

assure that a no-argument constructor is present in the superclass

We can read more about Serialization in one of our articles.

Q8. Is There a Destructor in Java?

In Java, the garbage collector automatically deletes the unused objects to free up the memory.
Developers have no need to mark the objects for deletion, which is error-prone. So it’s sensible Java has
no destructors available.

In case the objects hold open sockets, open files, or database connections, the garbage collector is not
able to reclaim those resources. We can release the resources in the close method and use try-finally
syntax to call the method afterward before Java 7, such as the I/O classes FileInputStreamand
FileOutputStream. As of Java 7, we can implement the interface AutoCloseable and use try-with-
resources statement to write shorter and cleaner code. But it’s possible the API users forget to call the
close method, so the finalize method and Cleaner class come into existence to act as the safety net. But
please be cautioned they are not equivalent to the destructor.

It’s not assured both the finalize method and the Cleaner class will run promptly. They even get no
chance to run before the JVM exits. Although we could call System.runFinalization to suggest that JVM
run the finalize methods of any objects pending for finalization, it’s still non-deterministic.

Moreover, the finalize method can cause performance issues, deadlocks, etc. We can find more
information by looking at one of our articles: A Guide to the finalize Method in Java.

As of Java 9, the Cleaner class is added to replace the finalize method because of the downsides it has.
As a result, we have better control over the thread which does the cleaning actions.
But the java spec points out the behavior of cleaners during System.exit is implementation-specific and
Java provides no guarantees whether cleaning actions will be invoked or not.

Source #07 https://www.tutorialspoint.com/java/java_interview_questions.htm

1. What do you know about Java?

Java is a high-level programming language originally developed by Sun Microsystems and released in
1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

2. What are the supported platforms by Java Programming Language?

Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux
like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.

3. List any five features of Java?

Some features include Object Oriented, Platform Independent, Robust, Interpreted, Multi-threaded

Read also: Java features

4. Why is Java Architectural Neutral?

It's compiler generates an architecture-neutral object file format, which makes the compiled code to be
executable on many processors, with the presence of Java runtime system.

5. How Java enabled High Performance?

Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that
turns Java bytecode, which is a program that contains instructions that must be interpreted into
instructions that can be sent directly to the processor.

6. Why Java is considered dynamic?

It is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-
time information that can be used to verify and resolve accesses to objects on run-time.
7. What is Java Virtual Machine and how it is considered in context of Java's platform independent
feature?

When Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by Java virtual
Machine (JVM) on whichever platform it is being run.

8. List two Java IDE's?

The two important and commonly used Java IDE's are Netbeans and Eclipse.

9. List some Java keywords(unlike C, C++ keywords)?

Some Java keywords are import, super, finally, etc.

10. What do you mean by Object?

Object is a runtime entity and it's state is stored in fields and behavior is shown via methods. Methods
operate on an object's internal state and serve as the primary mechanism for object-to-object
communication.

11. Define class?

A class is a blue print from which individual objects are created. A class can contain fields and methods
to describe the behavior of an object.

Read also: Java - Classes and Objects

12. What kind of variables a class can consist of?

A class consist of Local variable, instance variables and class variables.

Read also: Java Variable Types

13. What is a Local Variable?


Variables defined inside methods, constructors or blocks are called local variables. The variable will be
declared and initialized within the method and it will be destroyed when the method has completed.

14. What is a Instance Variable?

Instance variables are variables within a class but outside any method. These variables are instantiated
when the class is loaded.

15. What is a Class Variable?

These are variables declared with in a class, outside any method, with the static keyword.

16. What is Singleton class?

Singleton class control object creation, limiting the number to one but allowing the flexibility to create
more objects if the situation changes.

17. What do you mean by Constructor?

Java constructor gets invoked when a new object is created. Every class has a constructor. If we do not
explicitly write a constructor for a class the java compiler builds a default constructor for that class.

18. List the three steps for creating an Object for a class?

An Object is first declared, then instantiated and then it is initialized.

19. What is the default value of byte datatype in Java?

Default value of byte datatype is 0. Read also: Java Data Types

20. What is the default value of float and double datatype in Java?

In Java, the default value of float is 0.0f and the default value of double is 0.0d.

21. When a byte datatype is used?

The byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four
times smaller than an int.
22. What is a static variable?

Class variables also known as static variables are declared with the static keyword in a class, but outside
a method, constructor or a block.

23. What do you mean by Access Modifier?

Java provides access modifiers to set access levels for classes, variables, methods and constructors. A
member has package or default accessibility when no accessibility modifier is specified.

24. What is protected access modifier?

Variables, methods and constructors which are declared protected in a superclass can be accessed only
by the subclasses in other package or any class within the package of the protected members' class.

25. What do you mean by synchronized Non Access Modifier?

Java provides these modifiers for providing functionalities other than Access Modifiers, synchronized
used to indicate that a method can be accessed by only one thread at a time.

26. According to Java Operator precedence, which operator is considered to be with highest
precedence?

Postfix operators i.e () [] . is at the highest precedence.

27. Variables used in a switch statement can be used with which datatypes?

Variables used in a switch statement can only be a string, enum, byte, short, int, or char.

28. When parseInt() method can be used?

Java parseInt() method is used to get the primitive data type of a certain String.

29. Why is String class considered immutable?

Java String class is immutable, so that once it is created a String object cannot be changed. Since String is
immutable it can safely be shared between many threads ,which is considered very important for
multithreaded programming.
30. Why is StringBuffer called mutable?

Java String class is considered as immutable, so that once it is created a String object cannot be changed.
If there is a necessity to make alot of modifications to Strings of characters then StringBuffer should be
used.

31. What is the difference between StringBuffer and StringBuilder class?

Use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread safety is
necessary then use StringBuffer objects.

32. Which package is used for pattern matching with regular expressions?

java.util.regex package is used for pattern matching with regular expressions.

33. java.util.regex consists of which classes?

java.util.regex consists of three classes − Pattern class, Matcher class and PatternSyntaxException class.

34. What is finalize() method?

It is possible to define a method that will be called just before an object's final destruction by the
garbage collector. This method is called finalize(), and it can be used to ensure that an object terminates
cleanly.

35. What is an Exception?

An exception is a problem that arises during the execution of a program. Exceptions are caught by
handlers positioned along the thread's method invocation stack.

Source #08 : https://www.edureka.co/blog/interview-questions/java-interview-questions/

Q1. What is Java?

Java is a class-based, object-oriented programming language with minimal implementation


dependencies. A general-purpose programming language, Java allows programmers to write once and
run anywhere (WORA), meaning compiled Java code can execute on all Java-supported platforms
without recompilation. Java applications are usually compiled to bytecode that works on any JVM,
regardless of computer architecture.

Q2. List the features of Java programming language.

Java is a language that is considered simple to learn. One fundamental notion of OOP Java must be
understood.

Java offers a secure feature that aids in the development of a virus-free and tamper-proof system for
users.

OOP is an abbreviation for Object-Oriented Programming language. OOP denotes that everything in Java
is considered an object.

Java is not compiled into a platform-specific machine; rather, it is compiled into platform-independent
bytecode. The Virtual Machine that

operates the platform interprets this code.

Q3. How is Java different from C++?

Java and C++ are both object-oriented programming languages, but they have some key differences.

Platform independence: Java is a platform-independent language, while C++ is a platform-dependent


language. This means that Java code can run on any platform that has a Java virtual machine (JVM),
while C++ code can only run on the platform that it was compiled for.

Memory management: Java uses automatic memory management, while C++ requires manual memory
management. This means that Java programmers do not need to worry about allocating and freeing
memory, while C++ programmers need to be careful to manage memory correctly to avoid memory
leaks.

Safety: Java is a safer language than C++. This is because Java has built-in security features that help to
protect applications from malicious code. For example, Java does not allow direct access to the
operating system, which makes it more difficult for attackers to exploit security vulnerabilities.

Performance: Java is typically not as fast as C++. This is because Java uses a virtual machine, which adds
an extra layer of abstraction between the code and the hardware. However, Java applications are
typically more portable and secure than C++ applications.

In general, Java is a good choice for developing portable, secure, and easy-to-maintain applications. C++
is a good choice for developing high-performance applications that require direct access to the
operating system.

Q4. Explain JDK, JRE and JVM?


JDK vs JRE vs JVM

JDK JRE JVM

It stands for Java Development Kit. It stands for Java Runtime Environment. It stands for Java Virtual
Machine.

It is the tool necessary to compile, document and package Java programs. JRE refers to a runtime
environment in which Java bytecode can be executed. It is an abstract machine. It is a specification
that provides a run-time environment in which Java bytecode can be executed.

It contains JRE + development tools. It’s an implementation of the JVM which physically exists.
JVM follows three notations: Specification, Implementation, and Runtime Instance.

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

main() in Java is the entry point for any Java program. It is always written as public static void
main(String[] args).

public: Public is an access modifier, which is used to specify who can access this method. Public means
that this Method will be accessible by any Class.

static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can
be accessed without creating the instance of a Class. In case, main is not made static then the compiler
will throw an error as main() is called by the JVM before any objects are made and only static methods
can be directly invoked via the class.

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

main: It is the name of the method which is searched by JVM as a starting point for an application with a
particular signature only. It is the method where the main execution occurs.

String args[]: It is the parameter passed to the main method.

Q6. What is classLoader in Java?

The Java ClassLoader subset of JVM loads class files. The classloader loads Java programs first. Three
classloaders are built into Java:

Bootstrap ClassLoader

Extension ClassLoader

System/Application ClassLoader

Q7. Why Java is platform independent?


Java is called platform independent because of its byte codes which can run on any system irrespective
of its underlying operating system.

Q8. Why Java is not 100% Object-oriented?

Java is not 100% Object-oriented because it makes use of eight primitive data types such as boolean,
byte, char, int, float, double, long, short which are not objects.

Q9. What are wrapper classes in Java?

Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type
has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data
type into an object of that class. Refer to the below image which displays different primitive type,
wrapper class and constructor argument.

Q10. What are constructors in Java?

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.

There are two types of constructors:

Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other
words, default constructors are the no argument constructors which will be created by default in case
you no other constructor is defined by the user. Its main purpose is to initialize the instance variables
with the default values. Also, it is majorly used for object creation.

Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable
of initializing the instance variables with the provided values. In other words, the constructors which
take the arguments are called parameterized constructors.

Q11. What is singleton class in Java and how can we make a class singleton?
Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class
can be made singleton by making its constructor private.

Q12. What is the difference between Array list and vector in Java?

ArrayList Vector

Array List is not synchronized. Vector is synchronized.

Array List is fast as it’s non-synchronized. Vector is slow as it is thread safe.

If an element is inserted into the Array List, it increases its Array size by 50%. Vector defaults to
doubling size of its array.

Array List does not define the increment size. Vector defines the increment size.

Array List can only use Iterator for traversing an Array List. Vector can use both Enumeration and
Iterator for traversing.

Q13. Write a Java program to rotate arrays 90 degrees clockwise by taking matrices from user input.

Here’s an example Java program that takes a matrix as user input and rotates it 90 degrees clockwise:

10

11

12

13
14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42
43

44

45

46

47

48

49

50

51

import java.util.Scanner;

public class MatrixRotation {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Get the number of rows and columns for the matrix

System.out.print("Enter the number of rows: ");

int rows = scanner.nextInt();

System.out.print("Enter the number of columns: ");

int columns = scanner.nextInt();

// Create the matrix

int[][] matrix = new int[rows][columns];

// Get the matrix elements from the user

System.out.println("Enter the matrix elements:");

for (int i = 0; i < rows; i++) {

for (int j = 0; j < columns; j++) {

matrix[i][j] = scanner.nextInt();
}

// Rotate the matrix 90 degrees clockwise

int[][] rotatedMatrix = rotateMatrixClockwise(matrix);

// Print the rotated matrix

System.out.println("Rotated matrix:");

for (int i = 0; i < columns; i++) {

for (int j = 0; j < rows; j++) {

System.out.print(rotatedMatrix[j][i] + " ");

System.out.println();

// Function to rotate the matrix 90 degrees clockwise

public static int[][] rotateMatrixClockwise(int[][] matrix) {

int rows = matrix.length;

int columns = matrix[0].length;

int[][] rotatedMatrix = new int[columns][rows];

for (int i = 0; i < rows; i++) {

for (int j = 0; j < columns; j++) {

rotatedMatrix[j][rows - 1 - i] = matrix[i][j];

return rotatedMatrix;
}

Source #09 : https://mindmajix.com/java-interview-questions

43. What are the differences between C and Java languages?

The following are the key differences between C and Java languages.

C language Java

C is a Procedural-Oriented language Java is an Object-Oriented programming language.

Functions play a crucial role in C. Objects play a vital role in Java.

It is an intermediate-level coding language. It is a high-level coding language.

It does not support OOP Concepts. Java supports OOP concepts

We can use the malloc() keyword for memory allocation. We can use the new keyword for
memory allocation.

It doesn’t support the threading concept. Java supports threading

It is not a portable language It is a portable language

Default members of C are public Default members of Java are private

C supports storage classes. Java doesn’t support storage classes.

44. What is the difference between ++a and a++ increment operators?

++a is a prefix increment operator, whereas a++ is a postfix increment operator. The prefix increment
operator returns the value ‘a’ after incrementing it. The postfix increment operator returns the ‘a’ value
before incrementing it.

The below example shows the use of the operators.

Code:

class HelloWorld {

public static void main(String args[ ])

int a, b;
// Pre-increment

a = 1;

b = ++a;

System.out.println( b );// prints 2

// Post-increment

a = 1;

b = a++;

System.out.println( b );// prints 1

Result:

java -cp /tmp/dbMsHKUKUr/HelloWorld

=== Code Execution Successful ===

45. What are the differences between JVM, JDK, and JRE?

JVM JDK JRE

It stands for Java Virtual Machine It stands for Java Development Kit It stands for Java
Runtime Environment

It is the heart of Java programming. It is a development platform and the superset of the JRE.
We use JRE for code execution

It executes programs line by line It has the JVM It has the JVM

It converts bytecodes into machine codes. It provides executables, tools, and binaries It
contains Java classes, binaries, and JVM.

46. Define left shift and right shift operators in Java.

Left Shift: The left shift is a bitwise operator in Java. In this shift, bits are moved towards the left-hand
side, and zeros are placed at the rightmost places.

The example below shows the left shift.

Code:
public class LeftShiftOperator {

public static void main(String[] args)

int a=2;//

int i;

i=a<<1;//4

System.out.println("the value of a before left

shift is: " +a);

System.out.println("the value of a after applying

left shift is: " +i);

Output:

java -cp /tmp/GIYi18A02D/LeftShiftOperator

the value of a before left shift is: 2

the value of a after applying left shift is: 4

=== Code Execution Successful ===|

Right Shift: The right shift is also the bitwise operator in Java. In this shift, bits are moved towards the
right-hand side, and zeros are placed at the leftmost place.

The example below shows the right shift.

Code:

public class RightShiftOperator {

public static void main(String[] args) {

int a=2;

int I;

i=a>>1;

System.out.println("the value of a before right shift is:


" +a);

System.out.println("the value of a after applying right

Output:

java -cp /tmp/xy76CaCCuR/RightShiftOperator

the value of a before right shift is: 2

the value of a after applying right shift is: 1

=== Code Execution Successful ===

47. What are the bitwise operators in Java?

We use bitwise operators in Java to perform bit operations.

The following are the bitwise operators in Java. They are:

Bitwise OR (A&B)

Bitwise XOR (A^B)

Bitwise AND (A|B)

Bitwise complement (~A)

Left shift ( A<<2)

Right shift (A>>2)

Unsigned right shift (>>>)

Unsigned left shift ( <<<)

48. What is a ternary operator?

We use the ternary operator in Java to replace the if-else statement. It is also known as the conditional
operator that uses three operands.

The syntax for the ternary operator is given as:

variable = (expression)? expression true:expression false

The example below shows the use of the ternary operator.


int age = 21;

String result = (age 18) ? "adult" : "minor";

49. What does the ‘u0000’ notation represent in the Unicode system of Java?

In Java, every character is represented by 2 bytes. The notation ‘u0000’ is the lowest range of the
Unicode system. The notation ‘uFFFF’ is the highest range of the Unicode system. Also, it is the default
value of the character data type.

50. Is the empty .java file a valid source file name?

Yes, an empty Java file is a valid source file name. But we cannot run an empty file since it has no codes.
Java allows saving Java files by using the .java extension. We must compile the files using the javac .java
command and run them using their class name.

51. What are Java keywords?

Java keywords, called "Reserved keywords, " act as a code key. Keywords in Java are predefined. We
cannot use a Java keyword as an object name, variable, or identifier in Java programs.

Java offers nearly 50 keywords, including abstract, default, break, new, extend, static, import, etc.
Though true, false, and null seem like keywords, they are literal.

52. What are various access specifiers in Java?

Java has four access specifiers. They are:

1. Private: We can access the methods or classes declared private within the same class.

2. Public: We can access the methods or classes declared public anywhere in a program. In other words,
we can access them within and outside the class.

3. Default: By default, all the variables, classes, and methods are of default scope. The default is
accessible only within the package.

4. Protected: We can access the methods, variables, and classes defined as private within the same class
of the same package or by the subclass of the same class.

53. What are the uses of packages in Java?

By using packages in Java, we can:

arrange the group of classes into a single API unit


ensure access protection

control the naming conflicts

locate related classes easily

reuse the existing classes

54. What is the output of the following program?

The program is given as follows:

Code:

class Java

public static void main (String args[ ])

System.out.println(10 * 20 + "MindMajix");

Output:

java -cp /tmp/tKdYXDrlIn/Java

200MindMajix

MindMajix200

=== Code Execution Successful ===

55. What are control statements in Java?

Control statements are divided into three types in Java. They are:

Decision-making Statements

Jump Statements

Iterative/looping Statements

56. What are the selection statements in Java?

Selection statements are also called conditional or branching statements. We can use the selection
statement to control the execution flow of a Java program. It allows Java programs to make decisions
based on conditions. Once the condition is satisfied, they direct the program to follow a certain path. If
not, they direct the program to follow another path.

Selection/Conditional statements in Java include:

If statement

Switch statements

If-else statement

57. What are the different types of iterative statements?

The iterative statements in Java are also called looping statements. They are a set of statements that we
can run repeatedly until the condition for the termination is not met.

Looping/iterative statements in Java include:

For loop

Do-while loop

While loop

58. What are the jump statements of Java?

We use Jump statements in Java to transfer control to another part of a program based on a condition.
Also, we use these statements to jump directly to other statements.

The jump statements used in Java are break, continue, and return.

59. Explain the ‘For-Each’ loop in Java.

The ‘For-Each’ loop is an array traversing technique used in Java, such as for and while loops. We use
this loop to iterate over a collection or array-like ArrayList.

An example of a ‘For-Each’ loop is given as follows:

Code:

class ForEachPro{
public static void main(String args[ ]){

//declaring an array

int arr[ ]={21, 22, 23, 24};

//traversing the array with for-each loop

Output:

java -cp /tmp/FD2FPUTNPJ/F8rEachpro

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

When it comes to the while loop, we test the condition first. If the condition is true, then the loop
continues. If not, execution is stopped.

When it comes to the do-while loop, we execute the condition first. We test the condition at the end of
the loop.

The syntax for the while loop is given as follows:

while(condition){

//code to be executed

The syntax for the do-while loop is given as follows:

do {

//code to be executed /

//update statement

}while (condition);

61. What are the comments in Java?

Java comments are statements that are not executed by the compiler and interpreter. We use
comments to provide information about the class, methods, variables, and statements. Moreover, we
use them to hide program code for a specific time.
There are three types of comments in Java. They are:

Documentation comments

Single-line comments

Multi-line comments

62. Describe OOP concepts in brief.

OOP is the short form for Object-Oriented Programming Language.

Simula is the first object-oriented programming language. The most popular OOP languages are Java,
PHP, C++, Python, and many more.

The following are the OOP concepts used in Java:

Abstraction

Inheritance

Encapsulation

Polymorphism

63. What is Abstraction?

Abstraction is an OOP concept that hides unnecessary data and only shows necessary data to users. In
other words, abstraction hides internal processes and indicates only the functionalities of an application.

64. Define Encapsulation.

Encapsulation is an OOP property that binds data and code into a single unit.

65. What is Inheritance in Java?

According to the inheritance property, a child class object can acquire the properties of its parent class.
We apply inheritance to acquire runtime polymorphism and also provide code reusability.

66. What is Polymorphism in Java?


Polymorphism in Java provides a way to perform one task in different possible ways. We use method
overriding and method overloading to achieve polymorphism in Java.

67. What are the advantages of OOP concepts?

The following are the advantages of OOP concepts. They are:

OOP provides data-hiding

They can stimulate real-world entities effectively.

They make development and maintenance more effortless than a procedural programming language.

68. What is the significant difference between object-oriented language and object-based language?

Object-oriented programming language supports all the features of OOP concepts. Examples of object-
oriented programming languages are Python and Java.

An object-based programming language supports the features of OOP concepts except inheritance.
JavaScript and VBScript are some examples of Object-based programming languages.

69. What will be an initial value for an object reference defined as an instance variable?

All the object references in Java are initialised to null.

70. What is the Object-oriented paradigm?

The object-oriented paradigm depends on objects that have defined methods in the class. We use this
paradigm to incorporate code reusability and modularity. Objects are defined as instances of classes
that interact with one another to design programs and applications.

The features of the object-oriented paradigm are given as follows:

Focusing on data containing methods to operate on an object’s data

Following the bottom-up approach in the program design

Building enhanced real-time approaches such as abstraction, inheritance, etc.

71. What are Java naming conventions?


Java naming convention is a rule that we follow to name identifiers such as packages, methods,
variables, and constants. Many Java communities, such as Sun Microsystems and Netscape, support
these conventions. All the fields of Java programming are given Java naming conventions.

72. What are the rules that you must follow to declare a class?

The rules that we must follow to declare a class are given as follows:

The class name must be nouns such as Thread, Java, Class, etc.

It should start with an uppercase letter.

An example of the class is given below.

public class Thread

//code

73. Define Constructor in Java.

A constructor is a special type of method with a block of code to initialize the state of an object. A
constructor is called when the instance of the object is created. Similarly, a constructor is called when a
Java object is created using the new keyword.

74. What rules that you must follow while creating a constructor in Java?

We need to follow the rules below:

The constructor should have the same name as its class name.

A constructor shouldn’t be synchronized, final, abstract, or static.

There shouldn’t be any explicit return type for a constructor.

75. What are the different types of constructors available in Java?

Java has two types of constructors. They are:

Parameterized constructor
Default constructor

Parameterized constructor: A parameterized constructor is another constructor used to initialize


instance variables with the given values. A parameterized constructor is a constructor that accepts
arguments.

Default constructor: We call a default constructor as a no-argument constructor. We use this


constructor to initialize an instance variable with a default value. Moreover, we use this constructor to
perform some useful tasks in object creation. The compiler implicitly invokes the default constructor if
no constructor exists for a particular class.

You might also like