Java
Java
[ INTERVIEW QUESTIONS ]
AKASH RAJAN
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
1.What is java ?
➢ Java is a high-level, class-based, object-oriented programming language that is designed to have as few
implementation dependencies as possible.
➢ It is a general-purpose programming language intended to let programmers write once, run anywhere,
meaning that compiled Java code can run on all platforms that support Java without the need to recompile.
➢ it is used to develop a wide variety of applications, including:
➢ Web applications, Mobile applications, Desktop applications, Enterprise software, Scientific applications, and
Embedded systems.
2.Explain the differ b/w JDK, JRE, JVM.
JDK :
Java Development Kit is a software development environment that includes JRE and development tools. It's
used to create Java applications and applets. JDK includes tools like a compiler, debugger, and documentation
generator.
JRE :
Java Runtime Environment is a set of software tools that provides a runtime environment for running other
software. It's used to run Java applications. JRE contains class libraries, supporting files, and the JVM.
JVM :
Java Virtual Machine is the foundation of Java programming language and ensures the program's Java source
code will be platform-agnostic. It's used to run Java bytecode. JVM is included in both JDK and JRE, and Java programs
won't run without it.
3. what are the main features of java ?
1. Simple and Easy to Learn. Java is easy to learn and simple to use as a programming language.
2. Object-Oriented Programming.
3. Platform Independence.
4. Automatic Memory Management.
5. Security.
6. Rich API.
7. Multithreading.
8. High Performance
9. Scalability
4. what is differ b/w java and javascript ?
➢ Java is an OOP programming language while Java Script is an OOP scripting language.
➢ Java creates applications that run in a virtual machine or browser while JavaScript code is run on a browser
only.
➢ Java code needs to be compiled while JavaScript code are all in text.
5. what is an object-oriented programming language?
Object-oriented programming (OOP) is a programming language that uses objects to bind data and the functions that
operate on it. The goal of OOP is to implement real-world entities like inheritance, hiding, and polymorphism. OOP
concepts include:
❖ Class
❖ Object
❖ Inheritance
❖ polymorphism
❖ encapsulation
1
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
❖ abstraction
➢ In Java, inheritance is implemented using the extends keyword. When a class inherits from another class, it is
called a subclass or child class, and the class it inherits from is called a superclass or parent class. The subclass
inherits all of the public and protected members of the superclass, including its fields, methods, and
constructors.
Eg :
class Animal {
String name;
int age;
void eat() {
System.out.println("Animal is eating");
}
}
void bark() {
System.out.println("Dog is barking");
}
}
}
}
OUTPUT :
Superclass constructor called with x = 10
Subclass constructor called with y = 20
4
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
14. Explain the difer b/w method overloading & method overriding in java ?
Method overloading is when a class has two or more methods with the same name but different parameters. This
allows us to have multiple methods with the same name that perform different tasks, depending on the arguments
passed to them.
For example, we could have a calculateArea() method that takes a single argument (the radius of a circle) and returns
the area of the circle, and we could also have a calculateArea() method that takes two arguments (the length and width
of a rectangle) and returns the area of the rectangle.
Method overriding is when a subclass provides its own implementation of a method that is already defined in the
superclass. This allows us to customize the behavior of a method in a subclass, without having to break the code that
relies on the superclass method.
For example, we could have a draw() method in a Shape class that simply prints the message "Drawing a shape". We
could then override the draw() method in a Circle subclass to print the message "Drawing a circle".
Number of Two or more methods with the same name One method in the subclass and
methods one method in the superclass
5
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
return name;
}
In this example, the data members name and age are declared as private, and public getter and setter methods are
provided to access and modify them. This way, the internal implementation of the Person class is hidden from the
outside world, and the data members can only be accessed or modified through the public methods.
16. What are the purpose of access modifiers in java ?
➢ Access modifiers in Java are used to control the access level of classes, methods, variables, and constructors.
➢ They are used to restrict access to certain parts of a program, which can help to improve security and make
the code more maintainable.
17. differ b/w public, private, protected & default in java ?
There are four access modifiers in Java:
Public:
Public members are accessible from anywhere in the program.
Private:
Private members are only accessible from within the class in which they are declared.
Protected:
Protected members are accessible from within the class in which they are declared, as well as from any
subclasses of that class.
Default:
Default members are accessible from within the package in which they are declared.
18. What is abstract class in java ?
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from
another class). Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided
by the subclass (inherited from).
abstract class Shape {
// abstract method
abstract void draw();
}
6
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
// subclass of Shape
class Circle extends Shape {
// overriding the draw() method
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
// subclass of Shape
class Rectangle extends Shape {
// overriding the draw() method
@Override
void draw() {
System.out.println("Drawing a rectangle");
}
}
// main class
public class Main {
public static void main(String[] args) {
// creating an object of Circle class
Circle circle = new Circle();
// calling the draw() method on circle object
circle.draw();
Output:
Drawing a circle
Drawing a rectangle
7
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
// Abstracted class
class Dog extends Animal {
public Dog(String name) { super(name); }
// Abstracted class
class Cat extends Animal {
public Cat(String name) { super(name); }
// Driver Class
public class AbstractionExample {
// Main Function
public static void main(String[] args)
{
Animal myDog = new Dog("Buddy");
Animal myCat = new Cat("Fluffy");
myDog.makeSound();
myCat.makeSound();
}
}
OUTPUT :
Buddy barks
Fluffy meows
8
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
A constructor in Java is a special method that is used to initialize objects. It is called when an object of a class is created.
It can be used to set initial values for object attributes.
Constructors are similar to methods, but they have some important differences:
❖ Constructors have the same name as the class they are in.
❖ Constructors do not have a return type.
❖ Constructors are called automatically when an object is created.
This constructor takes two parameters, a name and an age, and uses them to initialize the corresponding object attributes.
To create a new Person object, you would use the following code:
Default Constructor:
class Student {
int id;
String name;
// Default constructor
Student() {
id = 0;
name = "null";
}
}
To create an instance of the Student class using the default constructor, you would simply write:
Parameterized Constructor :
• A parameterized constructor allows you to initialize instance variables to specific values at the time of object
creation.
class Student {
int id;
String name;
// Parameterized constructor
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
To create an instance of the Student class using the parameterized constructor, you would write:
➢ The static keyword in Java is mainly used for memory management. The static keyword in Java is used to
share the same variable or method of a given class.
➢ The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword
belongs to the class than an instance of the class.
A static method in Java is a method that belongs to a class rather than an instance of a class. Static methods
are used to access and change static variables and other non-object-based static methods.
• Static methods are called using the class name, not the instance name.
• Static methods can only access static variables and other static methods.
• Static methods cannot access non-static variables or non-static methods.
• Static methods are typically used for utility functions, such as mathematical functions or string manipulation
functions.
➢ The final keyword is a non-access modifier used for classes, attributes and methods, which makes them
non-changeable or unmodifiable. (impossible to inherit or override).
➢ The final keyword is useful when you want a variable to always store the same value, like PI (3.14159...). The
final keyword is called a "modifier".
1. final is a keyword used in Java to restrict the modification of a variable, method, or class.
2. finally is a block used in Java to ensure that a section of code is always executed, even if an exception is
thrown.
3. finalize is a method in Java used to perform cleanup processing on an object before it is garbage collected.
10
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
➢ In Java, method overriding occurs when a subclass (child class) has the same method as the parent class. In
other words, method overriding occurs when a subclass provides a particular implementation of a method
declared by one of its parent classes.
➢ To override a method, the subclass must have the same method name, return type, and parameter list as the
method in the parent class. The overriding method can also return a subtype of the type returned by the
overridden method.
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
In this example, the Dog class overrides the move() method from the Animal class. The Dog class's move() method
prints a different message than the Animal class's move() method.
When you call the move() method on a Dog object, the Dog class's move() method is called, even though the Dog
object is an instance of the Animal class. This is because the Dog class overrides the move() method.
Method overriding is a powerful feature that allows you to customize the behavior of classes in Java. It is one of the
key features that makes Java an object-oriented programming language.
Method overloading in Java means having two or more methods (or functions) in a class with the same name
and different arguments (or parameters). It can be with a different number of arguments or different data types of
arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
11
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
Output:
22
24.9
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Packages are used to avoid naming conflicts, and to control access to classes. For example, the java.lang
package contains classes such as String, Object, and Math, which are fundamental to the Java language.
Package mypackage;
the following code imports the String class from the java.lang package:
import java.lang.String;
package mypackage.subpackage;
12
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
An import statement tells Java which class you mean when you use a short name (like List ). It tells Java
where to find the definition of that class. You can import just the classes you need from a package as shown below.
Just provide an import statement for each class that you want to use.
Import statement in Java is helpful to take a class or all classes visible for a program specified under a
package, with the help of a single statement.
import java.util.List;
import java.util.*;
import static java.lang.Math.PI;
An interface is an abstract type that is used to declare a behavior that classes must implement. They are
similar to protocols in other languages.
@Override
public void run() {
// The body of run() is provided here
}
}
13
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
32. Explain the differ b/w abstract classes and interfaces in java ?
Methods Abstract classes can have both Interfaces can only have abstract
abstract and non-abstract methods. methods.
Variables Abstract classes can have variables. Interfaces cannot have variables.
our class can implement more than one interface, so the implements keyword is followed by a comma-
separated list of the interfaces implemented by the class. By convention, the implements clause follows the extends
clause, if there is one.
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from
another class). Abstract method: can only be used in an abstract class, and it does not have a body.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not.
objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true .
Otherwise, it returns false .
For Eg :
14
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
Local variables
the method, constructor, or block is entered and destroyed when it exits.Declare inside a method,
constructor, or block. They are only accessible within the scope in which they are declared. Local variables are
created when
Instance variables
declared outside of any method, constructor, or block, but within a class. They are accessible to all
methods within the class. Instance variables are created when an object is created and destroyed when the object is
destroyed.
Static variables
declared with the static keyword. They are shared among all instances of a class. Static variables are created
when the class is loaded and destroyed when the class is unloaded.
// Instance variable
private int myInstanceVariable;
// Static variable
private static int myStaticVariable;
15
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
The volatile keyword in Java is used to indicate that a variable's value can be modified by different threads. Used
with the syntax, volatile dataType variableName = x; It ensures that changes made to a volatile variable by one thread
are immediately visible to other threads.
example.stopRunning();
}
}
Output:
# Running...
# (After 1 second)
16
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
The transient keyword is a variable modifier in Java used in the context of serialization. When applied to a
variable, it instructs the Java Virtual Machine (JVM) to exclude that variable from the serialization process. Transient
variables are not saved in the serialized form of the object.
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.util.Date;
String firstName;
String secondName;
transient String fullName;
String email;
String password;
Date dob;
/*
Constructor
*/
Student(
String firstName,
String secondName,
String email,
String password,
Date dob
){
this.firstName = firstName;
this.secondName = secondName;
this.email = email;
this.password = password;
this.dob = dob;
this.fullName = firstName + " " + secondName;
}
serialize(student);
deserialize();
}
17
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
/*
Method to serialize object
*/
private static void serialize(Student student) {
try {
System.out.println("Student serializing: " + student.toString());
FileOutputStream fileOut = new FileOutputStream("student.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(student);
out.close();
fileOut.close();
} catch (IOException i) {
i.printStackTrace();
}
}
/*
Method to deserialize object
*/
private static void deserialize() {
try {
FileInputStream fileIn = new FileInputStream("student.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Student student = (Student) in.readObject();
in.close();
fileIn.close();
System.out.println("Student deserialized: " + student.toString());
} catch (IOException | ClassNotFoundException i) {
i.printStackTrace();
}
}
/*
Method to get String value of object
*/
@Override
public String toString() {
return (
"Student{" +
"firstName='" +
firstName +
'\'' +
", secondName='" +
secondName +
'\'' +
", fullName='" +
fullName +
'\'' +
", email='" +
email +
'\'' +
", password='" +
password +
18
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
'\'' +
", dob=" +
dob +
'}'
);
}
}
RESULT:
In Java, an array is a data structure that can store a fixed-size sequence of elements of the same data type. An array
is an object in Java, which means it can be assigned to a variable, passed as a parameter to a method, and returned
as a value from a method.
For eg;
The theoretical maximum Java array size is 2,147,483,647 elements. To find the size of a Java array, query an
array's length property. The Java array size is set permanently when the array is initialized. The size or length count of
an array in Java includes both null and non-null characters.
19
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
Array
• An array is a data structure that stores a collection of items. The size of an array is fixed, meaning that it
cannot be changed once it is created.
• Arrays are accessed using indexes. The index of an element is its position in the array, starting from 0.
• Elements can be inserted into and deleted from arrays, but this can be slow and inefficient.
• Arrays can be multidimensional, meaning that they can store arrays of arrays.
• Arrays are generally faster than ArrayLists, but they are also less flexible.
ArrayList
• An ArrayList is a resizable array. This means that its size can be changed as needed.
• ArrayLists are accessed using methods, such as get(), add(), and remove().
• ArrayLists are generally slower than arrays, but they are also more flexible.
clone() is a method in the Java programming language for object duplication. In Java, objects are
manipulated through reference variables, and there is no operator for copying an object—the assignment operator
duplicates the reference, not the object. The clone() method provides this missing functionality.
System.out.println(myClass.myField); // 10
System.out.println(clonedMyClass.myField); // 10
}
}
The toString() method in Java is a pre-existing method found in the Object class. It serves the purpose of
returning a string representation of an object. By default, it produces a string comprising the object's class name,
followed by an "@" symbol and hash code.
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
In this example, the toString() method is overridden to return a string that contains the person's name and age. This
string can then be printed to the console using the System.out.println() method:
21
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
equals() method is primarily used to compare the 'value' of two objects. It's an instance method that's part
of the Object class, which is the parent class of all classes in Java. This means you can use . equals() to compare any
two objects in Java.
For Eg:
➢ The hashCode() method in Java is a built-in function used to return an integer hash code representing the
value of the object, used with the syntax,
➢ It plays a crucial role in data retrieval, especially when dealing with Java collections like HashMap and
HashSet.
getClass() in Java is a method of the Object class present in java. lang package. getClass() returns the runtime class
of the object "this". This returned class object is locked by static synchronized method of the represented class.
The Java programming language uses exceptions to handle errors and other exceptional events. the process
of responding to unwanted or unexpected events when a computer program runs. There are 5 keywords.
❖ Try
❖ Catch
❖ Throw
❖ Throws
❖ Finally
22
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
1. try Block
Enclose the code that might throw an exception within a try block. If an exception occurs within the try
block, that exception is handled by an exception handler associated with it. The try block contains at least
one catch block or finally block.
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
try{
//code that may throw exception
}finally{}
2. catch Block
Java catch block is used to handle the Exception. It must be used after the try block only. You can use
multiple catch blocks with a single try.
Syntax:
try
{
//code that cause exception;
}
catch(Exception_type e)
{
//exception handling code
}
3 finally Block
• Java finally block is a block that is used to execute important code such as closing connection,
stream, etc.
• Java finally block is always executed whether an exception is handled or not.
• Java finally block follows try or catch block.
• For each try block, there can be zero or more catch blocks, but only one finally block.
23
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
• The finally block will not be executed if the program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).
Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType1 e1) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
// Code to handle ExceptionType2
}
// ... more catch blocks if necessary ...
finally {
// Code to be executed always, whether an exception occurred or not
}
Example 1:
In this example, we have used FileInputStream to read the simple.txt file. After reading a file the
resource FileInputStream should be closed by using finally block.
24
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
throw Keyword
The throw keyword is used to explicitly throw an exception from a method or any block of code. We can
throw either checked or unchecked exceptions using the throw keyword. The throw keyword is followed by
an instance of the exception.
Syntax:
throw exception_instance;
public class ThrowExample {
try {
person.setAge(-5); // This will cause an exception
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
In the setAge method, if the age provided is negative, we throwan IllegalArgumentException with a relevant
message.
Throws keyword
The throws keyword is used to declare exceptions. It doesn’t throw an exception but specifies that a
method might throw exceptions. It's typically used to inform callers of the exceptions they might encounter.
Syntax:
Example:
25
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
Checked Exceptions
Unchecked Exceptions
26
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
• This is because the exceptions are generated due to the mistakes in the program.
• These are not a part of the ‘Exception’ class since they are runtime exceptions.
• The JVM doesn’t require the exception to be caught and handled.
• Example of Unchecked Exceptions- ‘No Such Element Exception’
In Java, the try-with-resources statement is a try statement that declares one or more resources. The
resource is as an object that must be closed after finishing the program. The try-with-resources statement ensures
that each resource is closed at the end of the statement execution.
A Java string is a sequence of characters that exists as an object of the class java. lang. Java strings are
created and manipulated through the string class. Once created, a string is immutable -- its value cannot be changed.
Strings in Java are immutable, which means that they cannot be changed once they are created. To create a
string, you can use the new keyword and the String constructor. For example, the following code creates a string
object named str and assigns it the value "Hello World":
You can also create strings using string literals. String literals are sequences of characters enclosed in double quotes.
For example, the following code creates a string object named str and assigns it the value "Hello World":
Once you have created a string object, you can manipulate it using the methods provided by the String class. Some of
the most common string manipulation methods include:
indexOf() : Returns the index of the first occurrence of a specified character or substring in the string.
lastIndexOf() : Returns the index of the last occurrence of a specified character or substring in the string.
replace() : Returns a new string that is a copy of the original string with all occurrences of a specified character
or substring replaced with another character or substring.
toUpperCase(): Returns a new string that is a copy of the original string with all characters converted to uppercase.
toLowerCase(): Returns a new string that is a copy of the original string with all characters converted to lowercase.
For example, the following code uses the length() method to print the length of the string str:
System.out.println(str.length());
The following code uses the charAt() method to print the character at index 0 in the string str:
System.out.println(str.charAt(0));
The following code uses the substring() method to print the substring of the string str that starts at index 0 and ends
at index 4:
System.out.println(str.substring(0, 4));
The following code uses the indexOf() method to print the index of the first occurrence of the character 'o' in the
string str:
System.out.println(str.indexOf('o'));
The following code uses the lastIndexOf() method to print the index of the last occurrence of the character 'o' in the
string str:
System.out.println(str.lastIndexOf('o'));
The following code uses the replace() method to print a new string that is a copy of the string str with all occurrences
of the character 'o' replaced with the character 'a':
System.out.println(str.replace('o', 'a'));
28
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
The following code uses the toUpperCase() method to print a new string that is a copy of the string str with all
characters converted to uppercase:
System.out.println(str.toUpperCase());
The following code uses the toLowerCase() method to print a new string that is a copy of the string str with all
characters converted to lowercase:
System.out.println(str.toLowerCase());
These are just a few of the many string manipulation methods that are available in Java. For more information, please
see the Java documentation for the String class.
String :
➢ String is immutable, meaning that it cannot be changed after it is created. This is because String objects are
stored in a String pool, which is a shared area of memory that is used to store all String objects in a Java
program.
StringBuilder :
➢ StringBuilder is a mutable class, meaning that it can be changed after it is created. This is because
StringBuilder objects are not stored in the String pool.
➢ StringBuilder is also thread-safe, meaning that it can be safely used by multiple threads at the same time.
This is because StringBuilder methods are synchronized.
StringBuffer :
➢ StringBuffer is also a mutable class, meaning that it can be changed after it is created. This is because
StringBuffer objects are not stored in the String pool.
➢ StringBuffer is also thread-safe, meaning that it can be safely used by multiple threads at the same time. This
is because StringBuffer methods are synchronized.
An ArrayList class is a resizable array, which is present in the “java. util package”. While built-in arrays have a
fixed size, ArrayLists can change their size dynamically. Elements can be added and removed from an ArrayList
whenever there is a need, helping the user with memory management.
Here are the steps on how to create and manipulate ArrayLists in Java:
29
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
Java Iterator Interface of java collections allows us to access elements of the collection and is used to iterate
over the elements in the collection(Map, List or Set). It helps to easily retrieve the elements of a collection and
perform operations on each element.
❖ remove() - Removes the last element returned by the next() method from the collection.
Eg :
import java.util.ArrayList;
import java.util.Iterator;
Output :
John
Doe
Jane
30
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
HashMap in Java stores the data in (Key, Value) pairs, and you can access them by an index of another type
(e.g. an Integer). One object is used as a key (index) to another object (value). If you try to insert the duplicate key in
HashMap, it will replace the element of the corresponding key.
❖ HashMaps are unsorted, which means that the order in which elements are added to the map is not
preserved.
❖ HashMaps allow for one null key and multiple null values.
❖ HashMaps provide efficient access and manipulation of data based on unique keys.
import java.util.HashMap;
Output:
{one=1, two=2}
31
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
Create a HashMap instance using the syntax HashMap<KeyType, ValueType>. KeyType specifies the type of keys, and
ValueType specifies the type of values the map will hold. For example, to create a HashMap called numberMapping
that stores key-value pairs of strings and integers, you can use the following code:
Add key-value pairs to the HashMap using the put() function. For example, to add the key-value pairs "One" to 1,
"Two" to 2, and "Three" to 3, you can use the following code:
Access elements in the HashMap using the get() function. For example, to print the value associated with the key
"John", you can use the following code:
System.out.println(hashMap.get("John"));
Remove an element from the HashMap using the remove() function. For example, to remove the element associated
with the key "Jim", you can use the following code:
hashMap.remove("Jim");
Check if an element is present in the HashMap using the containsKey() function. For example, to check if the element
associated with the key "Jim" is present, you can use the following code:
System.out.println(hashMap.containsKey("Jim"));
The Java HashMap. entrySet() method is used to convert the elements within a HashMap into a Set. This
provides a convenient way to access and manipulate the elements stored in the HashMap.
The entrySet() method is useful for iterating over the entries in a map. For example, the following code
iterates over the entries in a map and prints the keys and values:
The entrySet() method can also be used to remove entries from a map. For example, the following code removes the
entry with the key "one" from the map:
The entrySet() method is a powerful tool for working with maps in Java. It can be used to iterate over the entries in a
map, remove entries from a map, and more.
32
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
63. What is the purpose of the put() and get() methods in java HashMap ?
➢ The put()and get() methods are two of the most important methods in the Java HashMap class.
➢ The put() method is used to add a new key-value pair to the map,
➢ the get() method is used to retrieve the value associated with a given key.
➢ The put() method returns the previous value associated with the key, or null if there was no previous value.
➢ The get() method returns the value associated with the key, or null if there is no value associated with the
key.
OUTPUT:
John Doe
The remove() method removes the mapping and returns: the previous value associated with the specified key. true
if the mapping is removed.
The remove() method can be used to delete an item from a HashMap. This can be useful for a variety of reasons,
such as:
SOURCE CODE:
33
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
➢ The hash table stores the values in an unordered method with the help of hashing mechanism.
We add elements to the HashSet using the add() method, and then we print the HashSet using the println()
method. We demonstrate checking if an element exists in the HashSet using the contains() method and removing an
element using the remove() method.
SOURCE CODE:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
/ Create a HashSet
HashSet<String> names = new HashSet<>();
// Add elements to the HashSet
names.add("John");
names.add("Alice");
names.add("Bob");
// Print the HashSet
System.out.println("HashSet: " + names);
// Check if an element exists in the HashSet
boolean containsAlice = names.contains("Alice");
System.out.println("Contains 'Alice': " + containsAlice);
// Remove an element from the HashSet
names.remove("Bob");
System.out.println("After removal: " + names);
}
}
OUTPUT :
add() method in Java HashSet is used to add a specific element into a HashSet. This method will add the
element only if the specified element is not present in the HashSet else the function will return False if the element is
already present in the HashSet.
In this example, we create a new HashSet and add the element "Element 1" to it. We then check if the element
"Element 1" is present in the HashSet. The contains() method returns true, which means that the element is present
in the HashSet.
The add() method is a very useful method for adding new elements to a HashSet and for checking if an element is
already present in a HashSet.
remove() method is present in the HashSet class inside the java. util package. The HashSet remove() method is used
to remove only the specified element from the HashSet .
SOURCE CODE:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> names = new HashSet<>();
names.add("John");
names.add("Mary");
names.add("Bob");
// Remove the element "Mary" from the HashSet
names.remove("Mary");
// Print the remaining elements in the HashSet
for (String name : names) {
System.out.println(name);
}
}
}
OUTPUT :
John
Bob
35
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
A linked list in Java is a dynamic data structure whose size increases as you add the elements and decreases
as you remove the elements from the list. The elements in the linked list are stored in containers. The list holds the
link to the first container.
Here are the steps on how to create and manipulate a Java LinkedList:
The LinkedList class is part of the java.util package, so you need to import it before you can use it.
You can do this by using the new keyword, followed by the LinkedList class name.
You can add elements to the LinkedList using the add() method. The add() method takes an element as an
argument and adds it to the end of the LinkedList.
You can remove elements from the LinkedList using the remove() method. The remove() method takes an
element as an argument and removes it from the LinkedList.
You can get the size of the LinkedList using the size() method. The size() method returns the number of
elements in the LinkedList.
You can check if the LinkedList is empty using the isEmpty() method. The isEmpty() method returns true if
the LinkedList is empty, and false otherwise.
You can iterate over the LinkedList using a for-each loop. The for-each loop will iterate over each element in
the LinkedList and print it to the console.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
// Create a new LinkedList object
LinkedList<String> names = new LinkedList<>();
// Add elements to the LinkedList
names.add("John");
names.add("Mary");
names.add("Bob");
// Remove an element from the LinkedList
names.remove("Bob");
36
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
OUTPUT:
John
Mary
71. What is the purpose of the add () and remove ()methods in java LinkedList ?
The add() and remove() methods in Java LinkedList are used to add and remove elements from a linked list. The
add() method takes an element as a parameter and adds it to the end of the list. The remove() method takes an
element as a parameter and removes the first occurrence of that element from the list.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
// Add elements to the list
list.add("Hello");
list.add("World");
// Print the list
System.out.println(list);
// Remove an element from the list
list.remove("Hello");
// Print the list again
System.out.println(list);
}
}
OUTPUT
[Hello, World]
[World]
37
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
Published in the Java Collections group. Java provides a vast set of data structures for efficiently working with
element collections. One such data structure is TreeSet, an implementation of a red-black tree in Java. TreeSet
maintains a sorted order for storing unique elements.
Source Code :
import java.util.*;
public class TreeSetExample {
OUTPUT :
Alice
Carol
Dave
true
Alice
Carol
Dave
38
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
73. What is the purpose of add() and remove() methods in java TreeSets ?
The add() method in a Java TreeSet is used to add a new element to the set. If the element is already present in the
set, the add() method will do nothing and return false. Otherwise, the element will be added to the set and the method
will return true.
The remove() method in a Java TreeSet is used to remove an element from the set. If the element is not present in
the set, the remove() method will do nothing and return false. Otherwise, the element will be removed from the set
and the method will return true.
Here is an example of how to use the add() and remove() methods in a Java TreeSet:
import java.util.*;
public class TreeSetExample {
public static void main(String[] args) {
OUTPUT:
The contains() method of Java AbstractCollection is used to check whether an element is present in a Collection or
not. It takes the element as a parameter and returns True if the element is present in the collection.
SOURCE CODE:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
39
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
names.add("John");
names.add("Mary");
names.add("Bob");
// Check if the collection contains the element "John"
boolean containsJohn = names.contains("John");
// Print the result
System.out.println(containsJohn);
}
}
OUTPUT :
True
The isEmpty() method is a convenient way to check if a collection is empty. It is available in all collection
interfaces, so you can use it with any type of collection.
Source code :
import java.util.*;
public class Example {
Output :
40
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
The size() method simply retrieves the value of the internal variable that tracks the number of elements in the
ArrayList. This variable is updated every time an element is added or removed from the ArrayList.
The size() method in Java collections is used to get the number of elements in a collection. It is a very useful method
for determining the length of a collection and for iterating over its elements. The size() method is available in all
collection interfaces, including List, Set, and Map.
import java.util.*;
public class Example {
OUTPUT:
The clear() method of Java Collection Interface removes all of the elements from this collection. It returns a
Boolean value 'true', if it successfully empties the collection.
SOURCE CODE :
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
// Print the contents of the list
System.out.println(list);
// Clear the list
list.clear();
// Print the contents of the list again
System.out.println(list);
}
}
41
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
OUTPUT
[Hello, World]
[]
The toArray() method of the ArrayList is used to convert an ArrayList to an array in Java. This function either
takes in no parameter or takes in an array of Type T(T[] a) in which the element of the list will be stored. The toArray()
function returns an Object array if no argument is passed.
SOURCE CODE
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
// Convert the list to an array
String[] array = list.toArray(new String[0]);
// Print the array
for (String s : array) {
System.out.println(s);
}
}
}
Output:
Hello
World
Java Iterator Interface of java collections allows us to access elements of the collection and is used to iterate
over the elements in the collection(Map, List or Set). It helps to easily retrieve the elements of a collection and
perform operations on each element.
The Iterator interface provides three methods: hasNext(), next(), and remove().
1. The hasNext() method returns true if there are more elements in the collection, and false otherwise.
3. The remove() method removes the current element from the collection.
The iterator() method is a very useful method for iterating over collections in Java. It allows you to easily access and
manipulate the elements of a collection.
42
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
SOURCE CODE:
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
while (iterator.hasNext()) {
String name = iterator.next();
System.out.println(name);
}
}
}
OUTPUT :
Alice
Bob
Charlie
A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of
comparing two objects of the same class.
The Comparator interface in Java is used to order the objects of a user-defined class. It provides a single
method, compare(), which takes two objects as input and returns an integer value indicating whether the first object
is less than, equal to, or greater than the second object. The compare() method has the following signature:
The Comparator interface can be used to sort collections of objects using the Collections.sort() or Arrays.sort()
methods. It can also be used to create sorted sets and maps.
Here is an example of how to use the Comparator interface to sort a collection of objects:
SOURCE CODE :
import java.util.*;
public class ComparatorExample {
numbers.add(5);
numbers.add(20);
// Create a comparator to compare the objects by their values
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
};
// Sort the list using the comparator
Collections.sort(numbers, comparator);
// Print the sorted list
for (Integer number : numbers) {
System.out.println(number);
}
}
}
OUTPUT
10
20
To sort a collection of objects by multiple criteria, first define the class representing your objects. Then, create
a custom comparator class that implements the Comparator interface. Override the compare method to define how
objects should be compared based on different criteria
SOURCE CODE:
import java.util.Comparator;
public class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student student1, Student student2) {
int nameComparison = student1.getName().compareTo(student2.getName());
if (nameComparison == 0) {
return student1.getAge() - student2.getAge();
} else {
return nameComparison;
}
}
}
To use this comparator, you would simply pass it to the sort() method of a list of students:
44
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
SOURCE CODE:
students.sort(new StudentComparator());
The compareTo() method returns an integer value that represents the comparison result. If the result is less
than 0, str1 comes before str2 in lexicographical order. If the result is greater than 0, str1 comes after str2. If the result
is 0, it means that both strings are equal.
SOURCE CODE:
OUTPUT :
equals() method is primarily used to compare the 'value' of two objects. It's an instance method that's part
of the Object class, which is the parent class of all classes in Java. This means you can use . equals() to compare any
two objects in Java.
Source code :
45
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
OUTPUT:
The hashCode() method in Java is a built-in function used to return an integer hash code representing the
value of the object, used with the syntax, int hash = targetString. hashCode(); . It plays a crucial role in data retrieval,
especially when dealing with Java collections like HashMap and HashSet.
SOURCE CODE :
System.out.println(hashCode);
OUTPUT
"Hello, world!"
A thread in Java is the direction or path that is taken while a program is being executed. Generally, all the
programs have at least one thread, known as the main thread, that is provided by the JVM or Java Virtual Machine at
the starting of the program's execution.
2. By implementing the Runnable interface and passing an instance of the class to the Thread constructor.
Once a thread is created, it can be started by calling the start() method. The thread will then run concurrently with the
main thread until it finishes executing its run() method.
To create a thread by extending the Thread class, you need to create a subclass of Thread and override the run()
method. The run() method contains the code that will be executed by the thread.
To start a thread, you need to call the start() method on the thread object. The start() method causes the thread to
begin executing the run() method.
Here is an example of how to create and start a thread by extending the Thread class:
SOURCE CODE :
46
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
OUTPUT
create a thread by implementing the Runnable interface, you need to create a class that implements the Runnable
interface. The Runnable interface has a single method, run(), which contains the code that will be executed by the
thread.
To start a thread, you need to create a Thread object and pass the Runnable object to the constructor. Then, you need
to call the start() method on the Thread object.
Here is an example of how to create and start a thread by implementing the Runnable interface:
SOURCE CODE :
OUTPUT :
47
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
Process :
✓ It has its own memory space, which contains its code, data, and stack.
✓ Processes communicate with each other through inter-process communication (IPC) mechanisms, such as
pipes, sockets, and shared memory.
Thread :
✓ It shares the process's memory space, but it has its own stack.
✓ A thread can be created and destroyed by the Java Virtual Machine (JVM).
Memory space Shares the process's memory space Has its own memory space
Creation Created and destroyed by the JVM Created and destroyed by the operating
system
Synchronization in java is the capability to control the access of multiple threads to any shared resource. In
the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent
results. The synchronization is necessary for reliable communication between threads.
In Java, synchronization can be achieved using the synchronized keyword and the volatile modifier. The
synchronized Keyword: The synchronized keyword is used to define critical sections of code that should be accessed
by only one thread at a time. It can be applied to methods or code blocks.
Eg :
48
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
// Synchronize a method
public synchronized void increment() {
// ...
}
The synchronized keyword in Java is a powerful tool for achieving thread safety and synchronization in
multithreaded applications. By using synchronized blocks or synchronized methods, you can control concurrent access
to shared resources, prevent data inconsistencies, and ensure proper thread synchronization.
To synchronize a method.
public synchronized void methodName() {
// code to be synchronized
}
To be synchronized code
synchronized (object) {
// code to be synchronized
}
Here are some examples of how the synchronized keyword can be used:
// Synchronize a method
A thread in Java can exist in one of the following six states at any given time:
1. New: When a thread object is created, it is in the new state. It is not yet runnable.
2. Runnable: A thread that is ready to run is in the runnable state. It is waiting to be scheduled by the operating
system.
4. Blocked: A thread that is waiting for an event to occur, such as a lock to become available, is in the blocked
state.
5. Waiting: A thread that is waiting for another thread to finish executing is in the waiting state.
Example :
Deadlock in Java is a condition where two or more threads are blocked forever, waiting for each other. This
usually happens when multiple threads need the same locks but obtain them in different orders. Multithreaded
Programming in Java suffers from the deadlock situation because of the synchronized keyword.
Only lock resources when absolutely necessary, and release them as soon as possible.
This means that all threads should acquire locks in the same order, to avoid situations where two threads are
waiting for each other to release locks.
This means that a thread should not acquire a second lock while it is already holding another lock.
This will help to prevent situations where a thread is waiting indefinitely for a lock to be released.
These data structures are designed to be used by multiple threads without the need for locks.
This can be a complex solution, but it can be effective in preventing deadlocks in situations where other
methods are not feasible.
When multiple threads are accessing the same data, it is important to use synchronization techniques to
ensure that the data is not corrupted.
50
http://www.linkedin.com/in/akash-r-bb3435288/
JAVA Interview Preparation
When designing your code, be aware of the potential for deadlocks and take steps to avoid them.
These tips, you can help to prevent deadlocks in your Java code.
94. What is the purpose of the Wait(), notify(), notifyAll() methods in java ?
The wait(), notify(), and notifyAll() methods in Java are used to coordinate actions of multiple threads. They are part
of the Object class and are used to implement inter-thread communication.
❖ wait(): Causes the current thread to wait indefinitely until another thread invokes notify() or notifyAll() on the
same object.
❖ notify(): Wakes up a single thread that is waiting on that object's monitor.
❖ notifyAll(): Wakes up all threads that are waiting on that object's monitor.
These methods are typically used in conjunction with synchronized blocks to ensure that only one thread can access a
shared resource at a time. For example, a producer-consumer problem could be solved using wait() and notify() as
follows:
SOURCE CODE :
class Producer {
private Object lock;
class Consumer {
private Object lock;
lock.wait();
// Consume the item
}
}
}
The wait(), notify(), and notifyAll() methods are powerful tools for coordinating the actions of multiple threads.
However, they must be used carefully to avoid race conditions and deadlocks.
52
http://www.linkedin.com/in/akash-r-bb3435288/