0% found this document useful (0 votes)
4 views35 pages

java_300

The document contains a comprehensive list of 300 core Java interview questions and answers, covering fundamental concepts such as Java features, JVM, data types, OOP principles, and exception handling. It explains key topics like inheritance, polymorphism, encapsulation, and method overloading/overriding, providing clear definitions and examples. This resource serves as a valuable guide for individuals preparing for Java-related interviews.

Uploaded by

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

java_300

The document contains a comprehensive list of 300 core Java interview questions and answers, covering fundamental concepts such as Java features, JVM, data types, OOP principles, and exception handling. It explains key topics like inheritance, polymorphism, encapsulation, and method overloading/overriding, providing clear definitions and examples. This resource serves as a valuable guide for individuals preparing for Java-related interviews.

Uploaded by

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

300 Core Java Interview Questions and Answers

Basic Java Concepts


1. What is Java?
Java is the most famous programming language in the world. Developed by Sun
Microsystems (now owned by Oracle), it is a robust language that can build
websites, desktop apps, and games on the go. Perfect solution for the enterprise-
related works.

2. What are the features of Java?


With the slogan of “code once, run anywhere,” Java offers a handful of features for
developers. It is simple, platform-independent, and allows an object-oriented
approach in all works. Along with this, it is known for its enhanced security, high
performance, and dynamic multithreading.

3. Explain the Java Virtual Machine (JVM)


Java Virtual Machine is a tool that provides the runtime environment to execute the
program. While running the code, JVM calls the main method present in the code.
That means every time you write code in the prompt and run the Java class, an
object of JVM is created.

4. What is the difference between JDK, JRE, and JVM?


JDK: JDK or Java Development Kit is the entire software development environment
necessary to program Java apps. It also consists of an interpreter, compiler
archiver, documentation generator, and so on.

JRE: JRE stands for the Java Runtime Environment. It provides the runtime
environment for the program and is the actual interpretation of the JVM. It
contains libraries and other files that JVM can use.

JVM: JVM does not physically exist; instead, it is a virtual machine. It converts
bytecode into machine-readable code to execute the program. Overall, it provides
the specifications required to run the program.

5. What are the different data types in Java?


In Java, two data types are mainly available- primitive and non-primitive.
Primitive data types include int, double, char, float, etc. while, the non-
primitive data types are strings, arrays, and classes.

6. Explain the concept of a class and an object in Java.


In the OOP of Java, the class and object have some sheer differences. The class is
like the blueprint or the design of the object, and it states its attributes and
features. On the other hand, the object is the instance of the class. For example,
we can make a general class named “Car” for the cars, while the specific “Audi”
will be the object of the class.

7. What is the difference between static and non-static methods?


Static methods allocate the memory once at a time. On the other hand, the non-
static methods allocate the memory with the creation of the object. That means you
can’t call the static method without creating the object of the class, unlike the
non-static ones.

8. What is inheritance?
Inheritance is the feature of Java by which the class obtains all the attributes
and the behavior of another class, mainly called the parent class. This helps to
save a lot of time and enables the reuse of methods and fields.

9. What is polymorphism?
Practically speaking, polymorphism means to exist in many forms. You can create an
abstract or an interface and implement it in any class you want. Polymorphism
mainly can used for method overloading (compile-time polymorphism) and method
overriding (runtime polymorphism)

10. Explain the concept of encapsulation.


Practically speaking, polymorphism means to exist in many forms. You can create an
abstract or an interface and implement it in any class you want. Polymorphism
mainly can used for method overloading (compile-time polymorphism) and method
overriding (runtime polymorphism)

11. What is abstraction?


Abstraction masks the program’s detailed implementation, allowing the user to see
only the necessary functionalities. It is more like using a remote control which
hides the complexity of the process by simply exposing the buttons to manipulate.
In Java, abstract classes and interfaces are used to achieve complete abstraction.

12. What are the different access modifiers in Java?


Access modifiers in Java are specific keywords that control the visibility and
accessibility of the class and its members. These are used to keep the methods,
variables, and classes inaccessible to the users. There are four types of access
modifiers in Java: Public, Protected, Default, and Private.

13. What is the difference between == and equals()?


In Java, ‘==’ is regarded as an operator while ‘equals()’ is a method. However the
‘==’ is used to compare the reference of the objects but the ‘equal()’ method
compares the content of the string or any object.

14. Explain the concept of constructors in Java.


Constructors are special bundles of codes that are used to initialize objects.
Every time the constructor is invoked, an object of the class is created. The
constructor can be of two types – default and parameterized. No matter what, they
always have the same name as the class name.

15. What is the purpose of the super keyword?


In Java, the super keyword is used to call the fields of the superclass or parent
class. It can be used to call the parent class’s methods, constructors, or
variables. This is essential as it removes the confusion when both the superclass
and the subclass have the attributes and methods with the same name.

16. What is the "this" keyword?


The primary function of the ‘this’ keyword is to call the methods or variables of
the individual class. When there are attributes and methods with the same name in
different classes, like the parent class, this keyword removes the place of
confusion.

It can also be used to invoke the default constructor of the class.

17. What is a package in Java?


The package is like a container where classes, subclasses, interfaces, and
abstracts can be encapsulated. These built-in and user-defined packages ensure no
naming conflicts appear and make it easier to locate and store the related classes.

18. What is the use of the final keyword?


The ‘final’ keyword is used to finalize a value for the attribute that can not be
overridden by other values or methods. This ‘final’ keyword can be applied to
variables, methods, and classes.
For example, we can give the keyword ‘final’ before the variable ‘PI’ and set the
value to 3.14159. This will always store this value of the variable and cannot be
modified anymore.

19. What are interfaces in Java?


Interfaces are like abstract classes that store the attributes and the functions of
the classes like a blueprint. The interface does not contain programmable codes; it
is just implemented in other classes. This feature enables multiple inheritance,
which is not supported by inheritance in Java.

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


Having quite similar functionalities, the interface and an abstract class have some
distinct features.

Abstract class

It cannot be instantiated
It cannot have both abstract and non-abstract methods.
Other classes can implement only one abstract class.
All types of access modifiers can be used – public, private, and protected.
Interface

It can be instantiated
It can have only abstract methods by default.
Multiple implementations of interfaces are possible.
All the variables have to be ‘static’ or ‘final’.
21. What is the purpose of the static keyword?
The main purpose of static keywords in Java is memory management. Using static
keywords helps to use the memory more efficiently by creating a single copy of our
input variable or method instead of repeating them individually. This is quite
useful, especially when dealing with a massive database.

22. How do you create a singleton class in Java?


To ensure the proper application of the singleton class, first, it must be ensured
that the class deals with only one instance to provide global access to the
instance. It consists of three main phases.

In the beginning, the constructor was made private. After that, a private static
instance of the class needs to be created. Finally, a public static method is
provided to return the instance.

23. What is the difference between ArrayList and LinkedList?


ArrayList uses a dynamic array for internal element storage, while LinkedList uses
a doubly linked list. Also, the ArrayList class only acts as a list, on the
contrary, the LinkedList class can act as either a queue or a list.

However, as the ArrayList uses less memory it makes it suitable for data storage,
unlike LinkedList which is better to manipulate lists.

24. Explain the concept of method overloading.


Method overloading is a feature to assign multiple methods with the same name to a
class while parameters (type, number, or both) will be different. Using this
feature enhances code readability and flexibility.

For instance, when the user wants to add given numbers, but the number of arguments
is not fixed. In such cases, if methods are written individually it will make the
work more difficult. Here, method overloading helps to figure out the program
quickly.
25. Explain the concept of method overriding.
Method overloading is a quite useful feature in Java that helps to assign multiple
methods with the same name yet having different parameters for a specific class.
For instance, we want to create a new class or subclass, from the superclass, using
the same method. Now, method overriding will allow the subclass’s method to
override the method of the superclass.

26. What is the purpose of the transient keyword?


The ‘transient’ keyword is used to identify the attributes of the data and stop the
serialization process. Serialization mainly converts an object into a stream of
bytes.

When this keyword is added to the variable, JVM ignores the variable’s value and
stores a default value. Most of the time, it is done when the program needs to
accept the user’s login details and password.

27. What is the purpose of the synchronized keyword?


As Java supports multithreading, multiple threads can often access and modify the
same resources. This can lead to errors and unexpected results. To prevent this
issue, the ‘synchronized’ keyword is used so that a single thread can access the
resources at one time, blocking other threads.

28. How do you handle exceptions in Java?


To handle runtime errors, exception handling can be used to prevent unexpected
errors. Invalid user input, network issues, or problems in code are some of the
reasons for this.

To handle the exceptions, the ‘try’ and ‘catch’ block can be used.

public class Task2 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

int sum = 0;
int count = 0;

while (count < 10) {


try {
System.out.print("Enter a positive integer: ");
int num = scanner.nextInt();

if (num < 0) {
throw new IllegalArgumentException("Input positive integer
only");
}

sum += num;
count++;
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
scanner.nextLine();
}
}

System.out.println("Sum of the 10 positive integers: " + sum);


scanner.close();
}
}
This example shows the basic exception handling of Java. Here, when the user
mistakenly enters negative numbers, the ‘try’ and ‘çatch’ block handles the error
and the system does not crash.

29. What is the difference between throw and throws?


The ‘throw’ keyword is used when dealing with unchecked exceptions, while the
‘throws’ keyword can be used for both the checked and unchecked ones. However, the
‘throw’ keyword is usually used inside the code block, unlike the ‘throws’ used in
method signatures.

30. What is the finally block?


The ‘finally’ block is always followed by the ‘try-catch’ block. Regardless of
whether the program throws an exception, this block is being executed. Important
statements like closing files or connections are often written in this block.

OOP Concepts
31. Explain the concept of object-oriented programming (OOP).
Object-oriented programming is related to the objects rather than just the values
or logic of simple programming. Precisely, the object is a data field that has a
set of attributes and features.

This programming model simplifies complex and lengthy software developments using
the concepts of abstraction, encapsulation, inheritance, and polymorphism.

31. Explain the concept of object-oriented programming (OOP).


Object-oriented programming is related to the objects rather than just the values
or logic of simple programming. Precisely, the object is a data field that has a
set of attributes and features.

This programming model simplifies complex and lengthy software developments using
the concepts of abstraction, encapsulation, inheritance, and polymorphism.

32. What are the four main principles of OOP?


The four main principles of OOP are encapsulation, abstraction, polymorphism, and
inheritance which help the developers to create robust applications.

33. What is a class?


The class is like a blueprint of the object. The class mainly includes the
attributes and the methods that the object will have. For example, “Circle” can be
the name of a class that will create objects of a circle having different
dimensions.

public class Circle {

private double radius;


public Circle(){
radius=1.0;
}
public Circle(double radius){
this.radius=radius;
}

public double getArea(){


return radius*radius*Math.PI;
}
}
This is a class of a circle that creates the objects of a circle taking the user
input of radius.
34. What is an object?
Objects are the instances of the classes. The specific object generated has the
mentioned attributes when a class is created. It can be interacted with by invoking
methods.

35. What is the use of the ‘protected’ access modifier while dealing with
inheritance?
The access modifier ‘protected’ is used for the attributes and the methods that
need to be made accessible only by the classes of the same package. However, even
after locating in different packages, the subclasses can access these variables and
methods. This not only helps to achieve proper inheritance but is also useful in
preventing access from irrelevant classes.

36. How does composition differ from inheritance in object-oriented programming?


Inheritance is a process where the subclasses inherit all the properties and
features of the parent class. In comparison, the composition does not extend to
another class. Instead, it occurs when one object contains another object that is
dependent on it.

The relationship is known as IS-A in inheritance, but the composition implements


the HAS-A relationship.

37. What is encapsulation?


Encapsulation is mainly hiding the data attributes of a specific class so that it
cannot be accessed by the users easily. The keywords like ‘private’ and ‘protected’
are used to encapsulate the attributes.

38. What is the difference between shallow copy and deep copy in the context of
object-oriented programming?
Shallow copy happens when the user copies the references only into the objects or
variables. In this case, new memory is not allocated. However, the new memory is
allocated in deep copy, but the reference is not copied.

39. Can you explain the principle of "Single Responsibility" in object-oriented


design?
‘Single Responsibility’ means to give a single module or class a single
responsibility only. Thus, the class will do only a single job, using methods
related to that, reducing any ground for complexities.

40. What is a constructor?


A constructor is like a method that is invoked to instantiate an object. The
constructor will have the same name as the class name. Users have the flexibility
to use parameterized and non-parameterized constructors. A default constructor is
generated without an argument or parameter when the user doesn’t define it.

41. What is method overloading?


Method overloading is simply having the methods with the same names but different
parameters. They can be of different data types or have different numbers of
arguments. This increases the readability of the program as the same method can be
called with different attributes.

42. What is method overriding?


Method overriding is a form of runtime polymorphism. It means a superclass (parent
class) and a subclass (child class) can have methods with the same name and
parameters. It provides the specific implementation of the method that is provided
in the superclass.

43. What is the super keyword?


The ‘super’ keyword is used to refer to the methods of the superclass. This avoids
the confusion when the overridden methods are invoked. Another use of this keyword
is to call the constructor of the superclass from the subclasses.

44. What are the advantages and disadvantages of using inheritance in object-
oriented programming?
In Java, inheritance allows the user to reuse the code by transferring all the
attributes to the subclass from the superclass. This also helps with method
overriding, saving time, and simplifying maintenance.

Apart from this, inheritance also has a major drawback, restricting the extension
of subclasses from more than one superclass. This can sometimes reduce the
efficiency of the projects.

45. What is a static method?


A static method belongs to a single class; it can’t be overridden. This method can
only be invoked from the specific class without creating an object. That’s why the
static method can only access the static methods and variables.

46. What is a final class?


In Java, the final class is used to restrict class inheritance. The final class
cannot be inherited or extended to another class. When done so, the compiler throws
an error.

47. Can you describe the difference between method overloading and method
overriding?
Method overloading means having the same name of methods but with different data
types or parameters or even both. For example, the methods below have different
parameters and data types.

int area (int side)


double area (double side)
double area (double side1, double side2)
On the other hand, method overriding is having the same method with the same name
and parameter but with different implementations and working. For example, the
parent class named ‘Shape’ may have a method similar to this –

double area (double side1, double side2){


return side1*side2;
And, the subclass “Triangle’ can have the same method as below which shows method
overriding-

double area (double side1, double side2){


return ½*side1*side2;
48. What is an access modifier?
Access modifiers are used to provide access to the attributes and methods and
determine who can access them. It also specifies its limits so that the JVM
understands if it can invoke it from outside the class or not.

Some of the access modifiers are public, private, default, and protected

49. What is a static variable?


Static variables belong to the classes not to the objects of the class. This can be
declared once and can be shared with all the objects of the class.

50. What is a final variable?


When the final keyword is used for a variable then it becomes a final variable. The
value of the variable can not be modified. These variables are more like constants
that have a fixed, unchangeable value.
51. What is an abstract method?
Abstract methods are used when the implementations of the methods are determined in
the subclasses. Many times, the implementation of the same methods can vary based
on the classes. In that case, the abstract methods are created in the parent class.

52. What is a concrete method?


The concrete methods are the regular methods that mention the implementation of the
methods in the class. They can also be defined in the abstract classes and can also
be overridden by the subclasses.

53. What is a nested class?


Nested classes are like inner classes which can be declared inside the other
classes. Apart from general classes, interfaces can also be nested. Helping the
classes to group logically in one place enhances readability.

54. What is an inner class?


Inner classes are the nested classes that can be declared inside another class.
They have access to the objects’ fields and methods of the existing class to which
it belongs.

55. What is an anonymous inner class?


Anonymous inner class is quite similar to the general inner class. The difference
is that this class does not have any name. It is usually used to extend the
subclasses or to implement the interfaces.

56. What is a local inner class?


Local inner classes are not the members of the enclosing classes. They are declared
inside the method body to access the local methods and the variables. Also, the
scope of the local inner class is restricted within the method block.

57. What is a static nested class?


Similar to the nested classes, the static nested class is also an inner class that
is declared within another class. However, like the other nested classes, the
static ones can not access the variable and the methods of the enclosing class.

58. How does polymorphism contribute to code flexibility and extensibility in


object-oriented programming?
When polymorphism is used, it enables features like method overriding. It helps to
reuse the code, saves a lot of time, and makes the entire project’s development
faster with unique features.

59. What is a functional interface?


Functional interfaces or Single Abstract Method Interfaces only contain one
abstract method. It can have any number of static or default methods, but the
abstract method should be only one. It can be used in functions like changing a
list of objects of one kind to a list of objects of another.

60. What is a lambda expression?


Lambda expression is like a method without a name but has the implementation inside
the method. This helps to implement the functional interfaces so that one method
can represent the expression.

Java Data Types and Variables


61. What are primitive data types?
Primitive data types are the fundamental data types of the programming language.
Commonly, there are eight primitive data types – int, double, float, char, long,
boolean, short, and byte.
Here, the int, double, float, long, and short are all used for declaring the
numerical values. While the byte and char are used for textual primitives and the
boolean is used for true or false (boolean values).

62. What are reference data types?


The non-primitive data types are the reference data types as they store the memory
address of the data instead of the actual value. Some of the common examples of
reference data types are string, array, object, class, and interface.

63. What is a variable?


Variables are mainly the assigned names where the user can store the value. Each
variable can only store one data type which is essential to declare before the
variable. The variable can be primitive or non-primitive type.

64. What is a constant?


A constant is a type of variable whose value can not be changed once it is assigned
to a variable. It is more like the ‘final’ keyword. The ‘static’ and ‘final’
keywords together are used to declare a constant variable.

65. What is typecasting?


Typecasting is a process of converting one data type to another data type. In Java,
two types of typecasting are possible – widening casting and narrowing casting.
This casting system allows the conversion of data by preventing data loss.

66. What is autoboxing and unboxing?


Autoboxing and unboxing are the features that convert primitive types to Wrappers
automatically. When the primitive data types are converted to equivalent Wrapper
types, it is called autoboxing. On the other hand, unboxing is the opposite process
where the conversion of Wrappers occurs.

67. What is the char data type?


Char data type is used to store the character data in a variable. It can be
strings, letters, numbers, or any other symbol. It can be both single byte or
multibyte. However, the variable with the char data type has to be surrounded by
single quotes.

68. What is the boolean data type?


Boolean data type is used in variables to store true and false. It is not case
sensitive and it only stores data using only 1-byte space. By logic values, it is
worked by 1 representing true and 0 representing false values.

69. What is the byte data type?


Used for containing binary data, the byte data type is a group of eight bits. They
can hold values ranging from -127 to +127 for whole numbers. An example of the
simple byte data type can be ‘a’ or ‘7’.

70. What is the short data type?


Short is another data type of 16-bit signed two’s complement integer. It has the
size of two bytes and holds values from -32768 to 32767. This data type can help to
save the memory while working with the large arrays.

71. What is the int data type?


This data type has the size of 4 bytes used to store the integer values in a
variable. For integers that data type came to be named as “int”. An unsigned 32-bit
integer can be stored in this data type from -2,147,483,648 to 2,147,483,647.

72. What is the long data type?


Long is used to store the largest integer values up to 64 bits of memory. It has
the size of 8 bits. Storing values from -9, 223, 372, 036, 854, 775, 808 to 9, 223,
372, 036, 854, 775, 807, long is essential to store integer values that exceed the
integer data type.

73. What is the float data type?


To store floating points or decimal values, float data type is used. Up to the
precision of 6-7 decimal points, the float can store the value. In order to store
the value to float, along with declaring the variable to float, the letter “f”
should be added to the end of the value to save it as float.

74. What is the double data type?


Double data type is used to store 64 bits of decimal points in a variable which
means it can store double size as much as the float holds. When the letter f is not
mentioned in the float data types, JVM automatically categorizes it as a double
value.

75. What is a string in Java?


The string is nothing but a sequence of characters. In other words, the string is
an array of characters. In Java, string is not a primitive data type, rather it is
an object.

76. How do you declare a variable?


To declare a variable means to assign a value to something to store it in the
system. In order to do that, at first the data type needs to be mentioned. After
that, the name of the variable according to the user’s preference should be given.
Then the value followed by the semicolon is enough to create a variable.

Here’s a simple example of declaring a variable.

int num=10;
77. How do you initialize a variable?
Initializing a variable is the same as declaring a value. However, in order to
initialize the variable, the value must be assigned, unlike the declaration. A
simple example can solve the confusion.

int num=10;
Double num1;
Here, the first variable is declared and initialized as the value is assigned to
it. While the second one, ‘num1’, is only declared; it is not yet initialized as
there is no value given to the variable.

78. What is a literal?


In Java, literals are simple values of integers, boolean, characters, or strings.
They can be assigned directly to a variable. For instance, here the 10 is the
literal of the variable ‘num’.

int num=10;
79. What is a type conversion?
Type conversion is another name for typecasting in Java. It is used to convert one
data type to another data type. It is necessary when one type of data needs to be
stored in another variable. The type conversion must be done by mentioning the
variable that makes the program more readable.

80. What is type promotion?


As the name sounds, the type promotion promotes the data type from smaller data to
larger size of datatype. For example, changing the integer values to double or
float data types can be a type promotion as the size of the data is increased here.

81. What is a type inference?


Type inference is provided by Java 8 in its improved versions. It is the automated
ability of the compiler to look at the method declaration and the invocation to
determine the type of argument. Without mentioning the type of the argument, users
can call specific methods in Java 8.

82. What is a scope of a variable?


The scope of the variable means the areas where the variable is accessible.
According to the location of the variables, the scope of them is determined. The
variable can have local, instance, and static scopes based on their needs.

83. What is a lifetime of a variable?


The variable’s lifetime is the time a variable uses in the system’s memory. For
instance, for variables, the lifetime of the instance variable is until the end of
the program, while for the local variable, it is until the control leaves the
block. Again, the static variable has a lifetime until the object stays in the
memory.

84. Explain the difference between local variables, instance variables, and class
variables in Java.
The local variables are the ones that are declared within the method block,
conditions, or loops. They are only recognized by that part of the program and can
not be interacted with or invoked from another part.

The instance variable is the opposite of this. They are declared outside these
methods or conditionals, usually at the beginning of the class. That’s why all the
parts of the program recognize them.

Lastly, the class variables are the general variables present inside a class. They
can be both local or instance.

85. What is a local variable?


Local variables are the variables that are declared inside specific methods or
functions. These variables are not globalized; that means they are not recognized
by the other parts of the class except that block. Simply declaring a variable
inside a method can make it a local variable.

86. What is an instance variable?


Variables that are declared within the class but outside the methods are the
instance variables. They can be accessed by all parts of the class. They are quite
different from static variables and have unique values for the particular object
unlike them.

87. What is a class variable?


Class variables are the simple variables of the class. They are static variables
and belong to the class rather than specific objects. Declared with the ‘static’
keyword they are often located outside the methods.

88. What is a constant variable?


A constant is a type of variable whose value can not be changed once it is assigned
to a variable. It is more like the ‘final’ keyword. The ‘static’ and ‘final’
keywords together are used to declare a constant variable.

89. How does the final keyword affect variables in Java, and what are its
implications for the program?
The final keywords make the value of the variable unchangeable. Hence, they are
fixed and can not be modified. This is done to fix and make the variables constant
so that the work related to them can be done efficiently.

90. What is a variable declaration?


The variable declaration means to give a name to the data type where the user wants
to store a value. It is like a container. For example, here the ‘num’ is the name
of the variable having the data type of double. Here, the users can store any
decimal values by initializing it.

double num;
Control Flow Statements
91. What are control flow statements?
To control the flow of the code, Java has specialized control flow statements to
help the user to make the decision to provide a smooth program flow. The common
control flow statements are ‘if’, ‘loop’, and the ‘jump’ statements.

92. What is an if statement?


If statements are decision-making statements. If the conditions are fulfilled
according to the program, then the code inside its block is generated otherwise the
system closes. Most of the time, it gives a boolean value of true or false.

if (num > 0) {
num=num*2;

);
}
This example shows a basic if-statement. Here, if the number the user has input is
bigger than 0, then the number will be multiplied by 2. When the conditions are not
met, the program will not function.

93. What is an if-else statement?


If-else statement enables the use of more than one condition in the program. If the
first one is not fulfilled, the program will check if it satisfies the rest of the
conditions. Oftentimes the last condition is ended with an ‘else’ clause.

if (num > 0) {
num=num*2;

);
if else(num<0){
num=num/2;
}
else{
num=0;
}
This example shows that if the num variable is greater than 0, it will be
multiplied by 2. If the first condition is not fulfilled, and the num variable is
less than 0, it will be divided by 2. If none of the above conditions are
satisfied, the value of num will be 0.

94. What is an if-else-if ladder?


An if-else-if ladder is a nested if-else. It is similar to the previous example.
When many conditions are included in the program, the if-else-if ladder is used.
The program checks if the conditions are met. When the conditions are met, the
program skips the rest of the ladder and runs it.

95. What is a nested if statement?


A nested if statement is similar to the if-else statement. This is always used to
give conditions inside one condition. When both conditions are fulfilled the
program is executed.

96. What is a switch statement?


The switch statement is exactly like the if-else statement which is used to check
if the conditions are fulfilled. One of the striking differences is that the return
type of the switch statement can be only int, double float, short, long, enum, and
strings, unlike the if-else statement.

An example can help to understand the basic differences.

case '+':
return operand1+operand2;
case '-':
return operand1+operand2;
case '*':
return operand1*operand2;
case '/':
eturn operand1/operand2;
}
default:
System.out.println("Result: Invalid”);
}
This is a simple calculator that takes the user input in characters and based on
the symbol it decides if the operands need to be added, subtracted, multiplied, or
divided. When the conditions are met, it does not check the rest of the blocks.
However, if none is correctly aligned, it goes to the default option and executes
the code inside it.

97. What is a break statement?


A break statement is usually placed after the condition or loop to break the loop
or the condition. When it reaches the break statement, it stops its work in the
condition or the loop and then the rest of the code outside that block is executed.

98. What is a continue statement?


The continue statement is mainly used inside the loops. It is used when we don’t
want the current iteration anymore and need to jump to the next one of the loop.
Therefore, when the continue statement is used, it skips the rest of the code that
it was executing and continues the loop functions.

99. What is a for loop?


A for loop is used to iterate or repeat a given set of instructions multiple times
until a specific condition is fulfilled. To use the for loop, there must be
initialization, condition along with the function like increment or decrement, and
the statement inside the block.

100. What is an enhanced for loop?


The enhanced for loop is also popular as the for-each loop is used in Java to make
the code more readable and avoid silly errors and bugs. Its functions are the same
as the traditional for loop, but it is more suitable for working with the traverse
arrays.

for(int i: array ){
System.out.println(i)
}
101. What is a while loop?
The while loop is also similar to the for loop, but it is used to iterate until a
specific condition is fulfilled. When the user does not know how many times the
task shall be repeated, using a while loop is the best practice.

while (i=!10){
i++;
}
Here until the value of variable i becomes 10, the while loop will be repeated and
the task inside will also be repeated. Here the task is to increase the value of
the i by one.

102. What is a do-while loop?


The do-while loop is the same as the while loop. Used to repeat until specific
conditions are not fulfilled, it executes the code at least once before checking
the validity. Thus, when there is a need to check the condition yet perform it at
least once, even if the conditions are incorrect, do-while should be used.

103. What is an infinite loop?


An infinite loop is an endless loop that iterates until the terminating conditions
aren’t met. This type of infinite loop is usually unintentional and errors though
it can be featured for some applications.

104. What is a nested loop?


A nested loop is the inner loop inside a loop. This is essential when we perform
interactions twice with two different conditions. Usually for calculating the two
or three-dimensional matrices, the nested loop is used.

105. What is a labeled loop?


Labeling a loop means to include continue or break statements inside the loop. When
these break statements are used in the nested loop, for example, the inner loop
will be terminated. Then it will jump to the outer code and execute it.

106. What is a return statement?


When the execution of the block is completed, whether it is a method or a
conditional statement, the return statement can return the value. This will stop
the further execution of the rest of the code.

107. What's the difference between a while loop and a do-while loop, and when would
you use each?
The while loop and do-while loop functions are similar – they are used to iterate
the code block until a specific condition is fulfilled. However, do-while is
especially used when the user wants to iterate at least once even if the conditions
are satisfied.

108. What is a fall-through in a switch case?


For switch cases, there must be a break or default statement to stop the execution
when the conditions are fulfilled. If the break statement is not used in the
specific case of the switch case, the program will be executed until it finds the
next break keyword. This is called the fall-through in a switch case.

109. When do you choose a switch statement over if-else, and vice versa?
Switch statements are often used when the conditions are neither true nor false
(boolean value) but relatively certain specific values, like the calculator
example. When the operator is the symbol ‘+,’ the program should add, and so on.

On the other hand, the switch statement is better when a faster and easier approach
is needed with few values. For instance, the operation is performed if the number
is greater than 0. Otherwise, it is excluded.

110. What is a try-catch block?


A try-catch block is used to handle the exception that is thrown at the compile
time. Any error inside the try block is handled and immediately terminated. It then
jumps to the specific catch block of that try block and then executes the command
inside there.

Every try block must have a catch or finally block.

An example of a try-catch block –


try{
System.out.println("Enter an number: ");
double num=input.nextDouble();
System.out.println("The sqaure root of "+num+" is "+getSquareRoot(num));
}catch(Exception e){
System.out.println(e);
}
111. What is a finally block?
Finally is a block of code that is executed after a “try” block. It’s typically
used to clean up codes like closing files or releasing database connections.

112. What is a throw statement?


The throw statement in Java is used to throw a user-defined exception or create a
custom human-readable error. You can use a throw statement to signal that something
has gone wrong in your code, this way it can be caught and handled properly.

113. What is a throws clause?


The throws clause is used to specify certain exceptions executed from the applied
methods. It informs the programmers about handling or propagating those exceptions.
For example, you can use it to throw a warning sign like “This method could cause
these types of problems.”

114. What are checked exceptions?


Checked exceptions in Java are exceptions that are checked or declared in the
throws clause during the method execution. These exceptions represent conditions
that are outside the control of the application such as trying to read a file that
doesn’t exist.

115. What are unchecked exceptions?


Unchecked exceptions are exceptions that don’t need to be declared in a throws
clause or caught in a try-catch block. They are subclasses of RuntimeException and
represent programming errors that are unrecoverable such as logic mistakes or
improper use of an API.

116. What is a custom exception?


A custom exception is a type of exception that is defined and customized by a Java
developer through extending the Exception class (for checked exceptions) or
RuntimeException class (for unchecked exceptions). Custom exceptions allow you to
create meaningful error messages specific to your application’s needs.

117. What is a try-with-resources statement?


A try-with-resources statement in Java is a try statement used to ensure each
resource is closed after finishing the execution of a statement.

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {


// Use the resource
} catch (IOException e) {
// Handle exception
}
Here, “BufferedReader” is automatically closed when the try block finishes, even if
an exception occurs.

118. What is a multi-catch block?


A multi-catch block is a type of block used to catch multiple exceptions in a
single catch block. This simplifies the code by avoiding duplication. A multi-
clutch block is effective when you need to handle different types of exceptions
generated from a single try block.
119. What is an assertion?
An assertion is a statement used in Java programming language to verify whether
your assumptions are correct or not. If your state of a program or assumption is
false, it will throw an “AssertionError”, which helps catch bugs during
development.

120. How do you use assertions?


Run your program with the -ea (or -enableassertions) JVM option. Then, use the
assert keyword followed by the assumption you want to test. If the expression is
false, the AssertionError will be thrown. For instance:

int age = getAge();


assert age > 0 : "Age must be positive";
Here, the assertion checks if age is positive. If not, it throws an AssertionError
with the message “Age must be positive.”

Java Collections Framework


121. What is the Java Collections Framework?
The Java Collections Framework is one kind of package that combines multiple
classes and interfaces. It provides a standardized way to simplify the process of
storing, retrieving, and manipulating data in Java programs.

122. What are the main interfaces of the Java Collections Framework?
The Java Collections Framework comprises five major interfaces, which include List,
Set, Map, Queue, and Deque.

Lists maintain ordered collections and permits duplicates, while Sets ensure unique
elements. Maps manage key-value pairs and each key is unique. Queues follow the
FIFO (First-In-First-Out) principle, and Deques support insertion and removal from
both ends.

123. What is a List?


List is an interface used in Java to store elements in ordered formation. It is a
child interface of the Collection that provides methods to access, add, remove, and
manipulate elements by their index.

124. What is an ArrayList?


An Arraylist class is a part of the collections framework in Java which represents
a resizable array. Arraylists are dynamic in nature, which means you can change
elements according to your needs.

125. What is a LinkedList?


A LinkedList in Java is a class that implements the List and Deque interfaces using
a doubly-linked list. It allows you to insert and delete elements efficiently since
each element of the LinkedList is linked to the next and previous ones.

126. What is a Set?


A set is an interface in Java that restricts data storage within unique elements.
In other words, you can’t store duplicate elements, facilitating mathematical
operations like union, intersection, and difference.

127. What is a HashSet?


A HashSet is a part of the Collection framework that uses a hash table to store
unique elements. It prevents storing duplicates to ensure fast performance for
operations like adding, removing, and checking for elements.

128. What is a LinkedHashSet?


LinkedHashSet is a class used in Java to extend the HashSet through adding new
elements while maintaining the order as inserted. It uses a hash table and a link
simultaneously to maintain insertion orders.

129. What is a TreeSet?


TreeSet is an implementation of the Set interface to store elements in a sorted
order. For this, TreeSet uses a red-black tree structure where all elements are
stored in ascending order.

130. What is a Map?


In Java, a map is an interface which can be accessed from the “java.util” package.
A map stores key-value pairs, while ensuring each key is unique. It is commonly
used as HashMap, LinkedHashMap, and TreeMap, when a quick access to data is
required.

131. What is a HashMap?


HashMap is a part of the Collection framework of Java that stores data in key-value
pairs. Using the HashMap class, you can efficiently store and retrieve elements
based on the unique keys.

132. What is a LinkedHashMap?


A LinkedHasMap class in Java is an extended form of the HashMap. Similar to the
HasMap class, it stores key value pairs, while also remembering the order in which
elements were added. This is because a LinkedHashMap uses both a hash table and
linked list.

133. What is a TreeMap?


TreeMap is a class in Java which is the implementation of a red-black tree. It
stores key-value pairs in stored order based on the natural ordering of keys or a
custom operator.

134. What is a Queue?


A Queue is a first-in, first-out (FIFO) data structure used in Java to define
methods for adding, removing, and inspecting elements in the order they were added.
It is a subtype of the Collection interface.

135. What is a PriorityQueue?


A PriorityQueue is an implementation of the Queue interface, which is used to order
elements based on the priority. Using this class, you can order elements based on
their natural ordering or a custom comparator. This way, elements with higher
priority are dequeued before those with lower priority.

136. What is a Deque?


A Deque also known as a “double-ended queue” is an interface that extends the Queue
interface. It allows elements to be added or removed from both ends, making it
useful for implementing stacks and queues. Deque is part of the java.util package
and provides methods for efficient insertion, removal, and access at both ends of
the collection.

137. What is an ArrayDeque?


An ArrayDeque class in Java is an implementation of the Deque interface that uses a
resizable array. It allows elements to be added or removed from both ends
efficiently and provides a flexible, fast alternative for implementing stacks and
queues.

138. What is a Stack?


A Stack is a class in Java that represents a last-in, first-out (LIFO) data
structure. It extends the Vector class and provides methods for adding, removing,
and inspecting elements at the top of the stack. It is commonly used for tasks like
expression evaluation, backtracking, and undo mechanisms in applications.
139. What is a Vector?
A vector is a type of dynamic array that allows flexible increment and decline of
the array size. It is quite useful in implementing methods for accessing, adding,
removing, and manipulating elements. This is why vectors are suitable for
situations requiring concurrent access from multiple threads.

140. What is a Collection?


A Collection is an interface that represents a group of objects. It is used for
performing various data manipulation tasks including data query, sorting, storing,
updating, and deleting using its sub-interfaces and methods.

141. What is the difference between Collection and Collections?


A collection in Java is an interface, representing a group of objects. On the other
hand, Collections is a utility class that provides various methods for working with
collections. Generally, a collection deals with the interfaces for data structures,
while Collections supplies utility methods for common tasks related to collection.

142. How do you iterate over a collection?


The way of iterating over a collection can be different depending on specific
scenarios. For instance,
-When you want to traverse through all elements of an iterable without conditions:

for (iterable_type iterable_element : collection)


– If you have an iterable but need to traverse conditionally:

for (Iterator iterator = collection.iterator(); iterator.hasNext();)


– If the data structure doesn’t implement the iterable interface:

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


143. What is the Iterator interface?
The iterator interface is a part of the java.lang package that is used to access
elements of the collection. It enables methods for producing an iterator to iterate
over the elements in the collection.

144. What is the ListIterator interface?


The Lisiterator interface extends the Iterator interface and provides additional
functionality for iterating over lists. It allows bidirectional iteration of
elements in a list. This interface is commonly used when you need to iterate over
lists and perform operations like adding, removing, or replacing elements.

145. How do you convert an array to a list?


You can use the ‘Arrays.asList()’ method to convert an array to a list in Java.
Simply insert the array as an argument to this method and it will wrap the array in
the AbstractList class, providing a list containing all elements of the array.

146. How do you convert a list to an array?


You can simply call the ‘toArray()’ method to convert a list to an array in Java.
Use the syntax, String[] newArray = listToConvert. toArray(new String[0]).

147. What is the Comparable interface?


The comparable interface is an interface in Java that is used to specify how the
instances of a class should be compared to one another. The compareTo() method,
defined in the interface, is used for comparison.

148. What is the Comparator interface?


The Comparator interface in Java is an interface used to define custom ordering for
objects that do not implement the Comparable interface. It allows you to specify
how objects should be compared based on specific criteria.
149. How do you sort a collection?
The simplest way to sort a collection is using the sort() method. Using this method
will sort a list based on their natural ordering (if they implement the Comparable
interface) or using a custom Comparator.

150. How do you search for an element in a collection?


You can use methods like contains() or indexOf() depending on the type of
collection. These methods help to verify whether the collection contains a specific
element or retrieve its index if it exists. You can also iterate through the
collection manually and perform custom checks if needed.

151. What is the purpose of the assert statement in Java?


The main purpose of the assert statement in Java is to test your assumptions while
programming your application. If an assertion fails, it typically indicates a bug
or unexpected error in the code.

152. How do you handle concurrent modification exceptions in Java collections?


You can use an Iterator to iterate through the collection using the remove() method
instead of directly modifying it. You can also use synchronized collections from
the java.util.concurrent package or specialized concurrent collections like
ConcurrentHashMap or CopyOnWriteArrayList. These can handle concurrent
modifications safely without throwing exceptions.

Java Collections Framework


153. What is a string in Java?
A string in Java is a sequence of characters stored as an object. A string
typically represents textual data and is used for manipulating and storing text in
Java programs.

154. How do you create a string?


The simplest way to create a string in Java is using string literals, where you
have to call characters enclosed within double quotes, for instance, “Hi, Sir”. You
can also use the String class constructor.

155. What is the String class?


The string class is one of the fundamental classes in Java that represents
sequences of characters.

156. What is the difference between String and StringBuilder?


The key difference between String and StringBuilder lies in their mutability.
Strings are immutable, while StringBuilder is mutable. String is preferable when
dealing with constant values or when immutability is desired for thread safety. On
the other hand, StringBuilder is more efficient when dealing with frequent string
modifications since it avoids unnecessary object creation.

157. What is the difference between String and StringBuffer?


Strings are immutable, which means their values cannot be changed once they’re
created. Any operation that appears to modify a string actually creates a new
string object. On the other hand, StringBuffer is mutable. Therefore, you can
modify the contents of the string without creating a new object each time.

158. How do you concatenate strings in Java?


You can concatenate strings using the + or += operators. Insert the + operator
within two string characters, such as “Hi” + ‘Sir”. You can also use the concat()
method to concatenate one string to another. For this, you can use the
“Hi”.concat(“Sir”).

158. What is the substring method?


The substring in Java is a widely used method which is a part of the java.lang
package. This method allows you to extract a portion of a bigger string that
creates a small string.

160. How do you compare strings in Java?


For equality comparison between strings, you can use the String.equals() method.

String str1 = "Hello";


String str2 = "World";
if (str1.equals(str2)) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");
}
You can also use the compareTo() method to compare strings lexicographically.

int result = str1.compareTo(str2);


if (result == 0) {
System.out.println("Strings are equal");
} else if (result < 0) {
System.out.println("str1 comes before str2");
} else {
System.out.println("str1 comes after str2");
}
161. What is the equals method?
The equals() method is used to test the equality of two strings. In case the
strings have the same sequence of characters or they are equal, the method returns
‘True’, and ‘False’ if not.

162. What is the compareTo method?


The compareTo method is a method used in Java to compare two objects where one
object is the current item and another is set as a parameter. Basically, this
method compares characters of two strings based on their Unicode values.

163. What is the startsWith method?


The startsWith() is a convenience method in Java that is used to check if a string
starts with a specific value or a given string.

164. What is the endsWith method?


The endsWith() method is used to check if a string ends with a specific suffix,
where the suffix is usually represented by a string parameter. This method returns
true if the given string ends with that suffix.

165. What is the indexOf method?


The indexOf() method is used to find the index of the first occurrence of a
specified character or substring within a string. It returns the index of the first
occurrence of the specified character or substring, or -1 if the character or
substring is not found.

166. What is the lastIndexOf method?


The lastIndexOf() method is used to find the position of the last occurrence of a
specified character or substring within a string. It returns the index of the last
occurrence of the specified character or substring, or -1 if the character or
substring is not found.

167. What is the length method?


The length() method is used to determine the number of characters in a string. It
returns the length of the specified string including spaces and punctuation.

168. How do you convert a string to uppercase?


You can convert a string to uppercase using the toUpperCase() method. This method
returns a new string with all characters converted to uppercase. For example,
“banana”.toUpperCase() will return “BANANA”.

169. How do you convert a string to lowercase?


In java, using the ‘toLowerCase()’ method is the most convenient way to convert a
string to lowercase. This method returns a new string with all characters converted
to lowercase. For example, “HELLO”.toLowerCase() will return “hello”.

170. How do you trim whitespace from a string?


You can trim whitespace from a string using the trim() method, which removes
leading and trailing spaces. Besides, using strip(), stripLeading(), and
stripTrailing() methods are also effective for more specific whitespace removal.

171. How do you replace characters in a string?


You can replace characters in a string using the replace() method to replace all
occurrences of a character, or replaceAll() for replacing patterns using regex. The
replaceFirst() method is useful to replace the first occurrence.

172. How do you split a string?


You can split a string using the String.split() method, which allows you to divide
the string based on a regular expression. It’s commonly used to split strings by
spaces, commas, or other delimiters.

173. What is the toCharArray method?


The toCharArray method is a built-in function used in Java to convert a string into
a character array. It’s often used when you need to access or manipulate individual
characters within a string.

174. How do you format strings in Java?


The String.format() method is quite simple and common to format strings in Java.
You can also use the Formatter class. These methods are commonly used to embed
variables in a string with a specific format.

175. What is the valueOf method?


The valueOf method is a part of the String class in Java. This static method is
used to convert different types of data such as numbers, characters, and objects
into a string.

176. What is the intern method?


The intern method in Java is used to store a string in the string pool. Using this
method saves memory as it doesn’t allow creating a new object when there is an
identical string content existing in the string constant pool.

177. How do you check if a string is empty?


You can use the isEmpty() method to check empty strings, where the method returns
True if there is an empty string. As an alternative, you can compare a string to an
empty string with equals(“”). These are common ways to ensure a string has no
characters.

178. What is the matches method?


The matches method is a part of the Element interface in Java that checks if a
string matches a specified regular expression. The method returns true if the
string conforms to the pattern, and false otherwise.

179. What is the replaceAll method?


The replaceAll() method replaces all parts of a string that match a given regex
with a new string. It’s similar to the replace() method. However, replaceAll() uses
a regex pattern for matching, while replace() simply looks for an exact string.
180. What is the replaceFirst method?
The replaceFirst() method in Java replaces the first substring of a string that
matches a given regex with a specified replacement. It’s similar to replaceAll(),
but only affects the first occurrence of the match.

181. How do you convert a string to a byte array?


You can use the getBytes() method to convert a string to a byte array in Java. This
method encodes the string into a sequence of bytes using the default charset or a
specified charset. Load the Java.util package and input the following codes:

String str = "example";


byte[] byteArray = str.getBytes();
You can also specify a charset:

byte[] byteArray = str.getBytes(StandardCharsets.UTF_8);


182. How do you convert a byte array to a string?
To convert a byte array to a string in Java, you use the String constructor that
takes a byte array as an argument. Write the following code first:

byte[] byteArray = {65, 66, 67};


String str = new String(byteArray);
You can also specify a charset using:
String str = new String(byteArray, StandardCharsets.UTF_8);
Java Input and Output (I/O)
183. What is the Java I/O system?
The Java I/O system is a framework in Java for handling input and output
operations, such as reading from and writing to files, streams, and other sources.
It includes various classes like InputStream, OutputStream, Reader, and Writer.
This system is part of the java.io package.

184. What is a stream in Java?


A stream is a wrapper consisting of a sequence of data elements that enable
efficient reading or writing of data from a source to a destination. Streams assist
input and output operations, which allows the transfer of data between different
sources and destinations in a sequential manner.

185. What are the types of streams in Java?


There are several types of streams in Java based on directionality, data type,
source, or destination. These include input streams and output streams, byte
streams and character streams, file streams, and network streams. Each type serves
specific purposes.

186. What is the difference between byte streams and character streams?
Byte streams deal with raw binary data, reading, and writing data byte by byte. On
the other hand, character streams handle textual data to read and write characters
and strings.

187. What is the InputStream class?


The InputStream class is an abstract class that serves as the superclass for all
input stream classes. InputStream provides a common interface for reading data by
byte or in larger chunks.

188. What is the OutputStream class?


The OutputStream class in Java is an abstract class that serves as a blueprint or a
superclass for all output stream classes. It’s used for writing data bytes to
different destinations, like files, network connections, or memory buffers.

189. What is the Reader class?


The Reader class is an abstract class in Java that is used to handle character-
based input streams. It’s part of Java’s I/O library, allowing you to read text
from files, streams, or other sources.

190. What is the Writer class?


The Writer class in Java is an abstract class that serves as a superclass and is
used for writing character-based data to output destinations. You can use methods
such as write() and flush() from the Writer class to get a convenient interface for
writing characters efficiently and reliably.

191. What is the File class?


The File class is a core component in Java that represents files and directories in
the file system to perform operations like creation, deletion, renaming, and
checking existence.

192. How do you read data from a file?


For quick reading of an entire file at once, use the Files class. If you’re dealing
with a large file and need to read it line by line, go for a BufferedReader. In
case your file has data separated by a specific delimiter, you can use a Scanner
class.

193. How do you write data to a file?


To write data to a file in Java, you can use the FileWriter or BufferedWriter class
for simple text writing, FileOutputStream class for binary data, or PrintWriter
class for formatted text output.

194. What is the BufferedReader class?


The BufferedReader class in Java is used to read text from a character-input
stream. This class buffers characters to provide efficient reading of characters,
arrays, and lines.

195. What is the BufferedWriter class?


The BufferWriter class is a Java Writer subclass that is used to write text to a
character-output stream. It efficiently buffers characters that in turn, reduces
system calls and improves performance.

196. What is the FileReader class?


The FileReader class is an extension of the InputSTreamReader class in Java, which
is used to read the content of a file character by character.

197. What is the FileWriter class?


The FileWriter class in Java is used to write character data to files. It’s part of
the Java I/O package and provides functionality to write characters to a file in a
character-based manner.

198. What is the PrintWriter class?


The PrintWriter class in Java is a character-oriented class used for writing text
to a file. It’s designed to write formatted representations of objects to a text-
output stream.

199. How do you read data from the console?


You can use the Scanner class or the BufferedReader class in combination with the
InputStreamReader class to read data from the console in Java. The Scanner class is
suitable for reading inputs such as strings, integers, and floating-point numbers
from the console. The BufferedReader class is preferable to read input from the
console line by line when combined with InputStreamReader.

200. How do you write data to the console?


The System.out.println() method is quite a common and simple way to write data to
the Java console. It prints the data to the console followed by a newline
character. If you need more advanced formatting options, you can use the
PrintWriter class.

201. What is the Scanner class?


The Scanner class is found in the java.util package, which is used to read input
from various sources like the console or files. It provides methods to parse
primitive data types and strings.

202. How do you use the Scanner class to read input?


Run the java.util package and import the Scanner class from. Then, create a Scanner
object by passing the input source, like System.in for reading from the console.
Finally, use methods like nextInt(), nextLine(), or nextDouble() to retrieve
different types of input.

203. What is serialization in Java?


Serialization in Java is the process of converting an object into a stream of bytes
for saving the object to a file or sent over a network. This stream of bytes can
then be deserialized, or converted back into an object, at a later time.

204. What is the Serializable interface?


The Serializable interface in Java is a marker interface that is used to serialize
objects. When a class implements Serializable, it indicates that its objects can be
converted into a stream of bytes and written to an OutputStream.

205. How do you serialize an object?


Create an instance of ObjectOutputStream and pass an OutputStream object to its
constructor. Use the writeObject() method of the ObjectOutputStream to serialize
the object.

206. How do you deserialize an object?


When the object state is saved into a stream of byte data of files and databases,
it is called Serialization. The opposite process, deserialization, is when the byte
stream is converted to restore the object’s state. The ObjectInputStream class is
required, which contains the method readObject() to deserialize an object.

207. What is the ObjectInputStream class?


ObjectInputStream class is used to deserialize the data and the objects that are
written by the ObjectOutputStream class. To read the data using the
ObjectInputStream, the class must implement the ‘Serializable’ interface.

208. What is the ObjectOutputStream class?


ObjectOutputStreams writes the primitive data types and objects into the
ObjectStream. This process is called Serialization. In order to do this, the
ObjectOutputStream package needs to be imported.

ObjectOutputStream obj= new ObjectOutputStream(file);


In the following example, the object ‘obj’ of the ObjectOutputStream is created to
link to the file output named ‘file’.

209. What is the FileInputStream class?


FileInputStream class helps the user to read data from the file in the form of byte
sequences. Extending the InputStream abstract class, its byte-oriented features
make it more suitable for reading the image data than character data.

210. What is the FileOutputStream class?


To write data to the file taking the user input, the FileOutputStream class is
used. Both byte and character-oriented data can be stored in the file using this
class.
FileOutputStream f1 =new FileOutputStream("D:\\input1t.txt");
f1.write(“Hello”);
f1.close();
This simple example shows how an object ‘f1’ can be created and connected to the
FileOutputStream. After that, the method .write() can write the data into the file,
following .close() to close the file after the task.

211. What is the DataInputStream class?


The DataInputStream class is used to read the primitive data types from the user
input stream. It is a machine-independent way to store data in no-byte orientation
which makes it unsuitable for multi-threaded access.

212. What is the DataOutputStream class?


To write the primitive data types into binary files, the DataOutputStream class is
required. This data can’t be read by the users as it is in binary form. For this
reason, the input stream is needed to read the data from these files.

Java Concurrency
213. What is concurrency in Java?
In Java, concurrency allows the users to perform multiple tasks simultaneously and
in parallel. The ‘Concurrency’ package covers the multithreading, parallelism, and
concurrency platforms, enabling the development of concurrent applications. Using ‘
java.util.concurrent’, this package can be imported to any class to give a
multithreaded feature.

214. What is a thread in Java?


The smallest unit of the process or the separate path that the program takes while
execution is thread. Every program has at least one thread, or the ‘main’ thread.

However, Java allows multiple threads to perform many concurrent works at a time.
For example, while writing a document, the user input is taken in one thread, while
the formatting of the document is another.

215. What is the Runnable interface?


This interface of the runnable is implemented when the multiple objects of the
class need to be executed by threads. Having only one method, the interface is
simple. After the creation of the thread, the undefined, void method run() is
invoked to execute the thread separately.

216. What is the Thread class?


Thread class is extended by Object class which implements the Runnable Interface.
This class contains constructors and methods that are used to create a thread
object. It is required to perform the operations of threading.

217. How do you create a thread in Java?


For creating a thread in Java two methods can be followed. Extending the Thread
class or implementing the Runnable Interface can be used to perform multithreading.

Using the Thread class, the following approach is needed –

public class MultiThreading extends Thread{

public void run(){


System.out.println(“Run”);
}

public static void main(String args[]){


MultiThreading t1 = new MultiThreading();
start.t1();
}
}
However, if the Runnable Interface is implemented, an object of the Thread class
needs to be created separately.

class Multithreading implements Runnable{


public void run(){
System.out.println("Run");
}

public static void main(String args[]){


MultiThreading t1 = new MultiThreading();
Thread t2 =new Thread(t1);
t2.start();
}
]
218. What is the Callable interface?
A callable interface is also used to perform multiple tasks in parallel with
pinpoint precision. Actually, it is an improved version of Runnable Interface.
Giving the users enhanced control over error handling, this interface contains the
call() method which throws checked exceptions.

219. What is the Future interface?


This interface represents a result of an asynchronous computation. Under the
concurrent package, it has the methods to check if the computation is completed or
not. Apart from ensuring this, it also waits and retrieves the results by the get()
method.

220. What is the difference between Runnable and Callable?


The main highlighting difference between the runnable and the callable interface is
that one can throw exceptions handling the multithreading works efficiently, and
the other doesn’t.

Runnable Interface

It is under the java.lang package


Works with the help of the run() method
Can’t throw any exceptions or return the results of the calculations.
Callable Interface

Located in the package of java.util.concurrent


It uses the call() method to execute threads
Can throw both exceptions and processed results of the calculations.
221. What is the Executor framework?
Located in the java.util.concurrent package, the executor framework is responsible
for creating threading, managing it, and scheduling the tasks accordingly. The main
feature of this is reusing the existing threads without creating it time and again.
With the help of the factory tools, ThreadPool can be easily created.

222. What is the ExecutorService interface?


ExecutorService Interface is a subinterface of the Executive class. It is
implemented in the executor class and is used to manage concurrent tasks. When the
number of tasks is more than the available threads it also helps to queue the tasks
until a free thread is available.

223. What is the ScheduledExecutorService interface?


Being a sub-interface of the executive service interface it is also located in
java.util.concurrent package. It is used to schedule the tasks one after another
periodically so that it becomes easier to manage the simultaneous work. For this,
parameterized methods like schedule(), scheduleWithFixedDelay(), and
scheduleAtFixedRate() are commonly used.

224. What is the ThreadPoolExecutor class?


ThreadPoolExecutor class is useful in creating the instance of it to specify the
number of the threads that will remain alive after the creation. Also, it enables
the user to limit the number of threads to handle the works that are too large to
fit in the queue.

Methods like aliveCoreThreadTimeOut() can be used to terminate the core thread when
no task arrives within the alive time.

225. What is the ForkJoinPool class?

The ForkJoinPool class is a type of Executor Class that divides the larger tasks
into smaller divisions to handle them efficiently. Forks refer to the steps
required to split the tasks whereas Join is used to join the subtasks into one
result after their execution.

Extending the AbstractExecutorService class, it inherits its invokeAll() and


invokeAny() methods to perform the tasks.

226. What is a thread pool?


A thread pool is a group of threads that are working for multiple tasks with
several reuses. When a task is assigned, a thread is pulled from this pool. After
the successful completion of the task, the thread is sent back to the pool again.

227. What is the synchronized keyword?


The ‘synchronized’ keyword is used to make the code multithread-safe by controlling
the access of the threads from multiple sources. By using this keyword, the user
can allow only one thread to use the resource. This flexibility resolves the
inconsistencies and errors that may arise during simultaneous work.

228. What is a lock in Java?


The Lock is an interface of the java.util.concurrent.lock package having the
similar features as the synchronized blocks. It is used to lock a single object or
class for a specific period to prevent its accession by the other threads. Void
methods like lock() and unlock () are used in this case.

229. What is the Lock interface?


Available in the java.util.concurrent.lock package, it is one of the most used
interfaces in Java. This interface works as thread synchronization features by
locking and unlocking the objects while multiple threads work simultaneously.
Unlike the synchronized blocks, this enables a proper sequencing of the threads
with its void pre-defined methods.

230. What is the ReentrantLock class?


When accessing the shared resources, the RentractLock is required. It also
implements the Lock interface to use its lock() and unlock() methods to manipulate
the synchronization of the tasks.

It allows one to re-enter the lock on a resource more than one time. Each time the
thread enters the lock, its value is incremented by one, and with every unlock
request it is decremented by one. When the value reaches zero, the resource is
unlocked.

231. What is the Condition interface?


Condition interface is used to give the threads a condition. Until the conditions
aren’t met, the execution of the thread is suspended.

232. What is the ReadWriteLock interface?


The interface of ReadWriteLock is a special type of interface that allows several
threads to read from a source but allows only one thread to write at one time. This
feature removes the concurrent errors that might occur when writing and reading
occur simultaneously.

The methods of readLock() and writeLock() are needed to achieve this concurrency.
However, an object of the Lock class needs to be created beforehand.

233. What is the ReentrantReadWriteLock class?


The ReentrantReadWriteLock class is also implemented by the ReadWriteLock
interface. Its features are the same as the ReentrantLock class which ensures the
resources can be entered more than once.

234. What is a semaphore?


Basically, a semaphore is like a counter that limits the number of threads that can
access a shared resource. This non-negative variable gives access to the threads
when the value exceeds zero. When it is not, the access is denied.

In Java, there is an entire class, Semaphore class, containing constructors and


methods to complete this task and synchronize the multithreading.

235. What is the Semaphore class?


Belongs to the java.util.concurrent package, the Semaphore class provides all the
mechanisms of semaphore. It implements the Serializable interface and uses the
methods acquire() and release() to handle multiple threads at a time.

236. What is a deadlock?


Deadlock occurs when two or more threads are blocked. To avoid this issue,
synchronized keyword is used when working with multiple threads at a time.

237. How do you prevent deadlock?


Deadlock is a natural phenomenon that occurs when working with multiple threads
simultaneously. Some effective practices are maintained in order to avoid this. For
instance, placing the locks in the right order, avoiding unnecessary locks, and
invoking thread.join() methods can be used to prevent this.

238. What is a livelock?


Livelock is a similar concurrency issue to the deadlock. In contrast to the
deadlock, here threads do not wait infinitely; instead, they change their states
between one another. The outcome of this livelock is the threads ultimately cannot
perform their tasks.

239. What is thread starvation?


Thread starvation is the process when the threads are starved from access to the
shared resource and have to wait to execute their work. Though this waiting period
is not infinite, these threads acquired the resources whatever is available to
execute the run() method.

240. What is the ThreadLocal class?


The ThreadLocal class is used to provide the thread-local variables which are
copied when the threads access it. As in this case, each thread has a distinct copy
of the variable, there is no issue with the synchronization. All in all, it
enhances the performance and the scalability of the program.

241. What is the volatile keyword?


The volatile keyword is used to modify the value of the variable by multiple
threads. Applicable to both the primitive data types and objects, it makes the
class thread-safe.

No caching of the volatile variables happens. Rather, they are read from the main
memory. This informs the compiler to prevent it from any optimization.

242. What is the AtomicInteger class?


The AtomicInteger class mainly deals with the integer values with the atomic
operations that are done with single, uninterrupted units. To ensure a multithread-
safe environment, several methods are available.

Java Networking
243. What is Java networking?
Java networking allows the connection of two or more devices together so that they
can share the resources. This feature also allows a centralized software management
option.

244. What is the java.net package?


The package of java.net contains several classes and interfaces that help to
achieve the networking features in Java. Classes ranging from Socket, URL, URL
connections, and CookieManager along with several other interfaces, enable the user
to do low and high-level API tasks.

245. What is the URL class?


URL or Uniform Resource Located class is generally used to refer to the address of
the resource on the World Wide Web. As a URL consists of four components –
protocol, server name, port number, and file – the constructors and methods of this
class also provide this information.

However, the URL class can point to anything from simple file locations to
complicated database queries in search engines.

246. What is the URLConnection class?


URLConnection class is an abstract class that provides the link between the URL and
the application. With the help of this class, any resource from the URL object can
be read and written. All these can be done by configuring the header field.

247. What is the HttpURLConnection class?


Being a subclass of the URLConnection class, the HttpURLConnection class is
specifically used to read the HTTP protocols. From header information to the status
code, everything can be retrieved by this. A range of methods and a constructor are
available in the class for this function.

248. How do you send a GET request in Java?


To send a GET request, at first, an object of URL has to be created. Following it,
the openConnection() method needs to be invoked. Then, setting the requestMethod()
to default ‘GET’, setRequestProperty() is called to set the value to ‘ User-Agent’.
Lastly, the Reader and InputStream are used to read and process the information.

249. How do you send a POST request in Java?


For sending a POST request, the same methods and parameters are followed as used in
the GET request. The difference is that this time, you need to set the
requestMethod() to ‘POST’ now and create the instance of OutputStream to write the
required parameters.

250. What is a socket?


The socket is the endpoint of the communications between the devices. A specific
class of Socket is provided in the java.net package to simplify the processes of
the socket.
251. What is the Socket class?
The Socket class is used to create a socket. When the connection between the client
application and the server is established, an object of this class is created.

The communication between the server and the client is done by reading and writing.
Methods like getInputStream() and getOutputStream() are used to return the streams
of the sockets.

252. What is the ServerSocket class?


By establishing the connection with the client, the ServerSocket class is mainly
used to create a server socket. When the server can’t listen to the specified port,
it throws an exception. Several methods are present in the class to ensure an
efficient networking connection.

Java String Handling


253. What is the DatagramSocket class?
For connection-less socket programming using UDP, DatagramSocket is used. This
class contains connectionless sockets for sending and receiving datagram packets.
Along with this, the broadcast messages can also be sent and received.

254. What is the DatagramPacket class?


Without establishing the connection, the DatagramPacket class ensures the message
is routed from one device to the other depending on the information. Therefore,
this class is a way to provide a connectionless packet delivery service.

255. What is the InetAddress class?


The InetAddress class is used to get the IP address of the hostname. For example,
for the URL of www.vivasoftltd.com, the hostname is Vivasoft and its IP address can
be retrieved by this address.

256. How do you get the IP address of a host?


When any IP address needs to be found from a hostname, the InetAddress class is
used. It has predefined methods and constructors that can easily access this in a
few lines of code.

Here’s a simple example of which IP address can be accessed by just the URL.

import java.net;
public class example {
public static void main (Strings[]args){
InetAddress ip1 = InetAddress.getByName(“www.facebook.com”);
System.out.println(ip1.getHostAddress());
}
}
257. How do you get the hostname of an IP address?
To get the hostname, the InetAddress class has predefined methods. The
getHostName() should be included after the name of the object. With this, by giving
the URL simply, the hostname and the IP address can be retrieved.

258. What is the NetworkInterface class?


The NetworkInterface class has names and a list of IP addresses that are assigned.
It can be both software and hardware. With the help of this, the local interface
can also be identified.

259. How do you list all network interfaces?


The NetworkInterface class has predefined methods to find the list of the network
interfaces. The method getInetAddress() is used to return an enumeration of the
inetAddress of all the network interfaces.
Other than that, the getInterfaceAddress() void method can be used to retrieve the
list of all the interface addresses.

260. What is the Proxy class?


Proxy classes are implemented at runtime to implement the interfaces. It contains
certain methods and constructors to create dynamic proxy classes and objects. Every
proxy class is a subclass of the Proxy class and has an invocation handler object
with it.

261. What is the Authenticator class?


This class is used to provide authentication while visiting some URLs. This class
itself extends the Object class which knows how to find the authentication of the
network. Several accessor methods are present in the class to get the required
information.

262. How do you handle cookies in Java?


To use and handle cookies, the Cookie class is used. This class enables to create
the cookies using the constructor and adding and fetching cookies with the help of
particular methods.

263. How do you handle HTTPS connections in Java?


URL, URLConnection, and HTTPURLConnection classes are used to handle the HTTP
connections. Among them, the HTTPURLConnection class is specifically used for the
HTTP protocols. The methods of these classes are suitable when working with this
type of protocol.

264. What is the SSLContext class?


SSLContext class is used to secure the socket protocol. The implementation of this
class acts as a factory of SSLEngines.

265. How do you create a secure server in Java?


To create a secure server in Java, the server should be set up first by creating a
class for this. Then, a client also needs to be set up by the same process. Write
the necessary coding that is required. After that, run the server class first,
following the client class to encrypt the server.

266. What is the MulticastSocket class?


To send and receive the multicast datagrams, the MulticastSocket class is used. It
is a subclass of the DatagramSocket.

From joining and leaving the multicast group, this class also ensures the proper
sending and receiving of the multicast datagrams. For this, the multicast group
address and the port number should be specified.

267. How do you join a multicast group in Java?


While joining a multicast group, the object of the MulticastSocket class needs to
be created with the necessary port. Invoking the method of joinGroup() with
InetAddress as parameter, a multicast group can be joined.

268. How do you leave a multicast group in Java?


To leave a multicast group, a method of leavegroup() is used which takes objects of
SocketAddress and NetworkInterface. This feature is essential as the host receives
datagrams from the group of ports which are not needed many times.

269. What is the URLStreamHandler class?


URLStreamHandler class is the superclass for all the stream protocol handler
classes. This class ensures the connection between the particular protocol types.
Starting from HTTP to gopher, everything can be handled by using this class.
270. How do you create a custom protocol handler in Java?
By implementing the URLStreamHandler class, custom protocol handlers can be
created. The objects of the URLConnection need to be created and the getInputStream
method() is needed to be called to take the data of the handler.

271. What is the SocketChannel class?


This class is used to create the objects of the socket channels. It is a stream-
orienting of the connecting sockets. Using the open() method, a simple socket
channel can be opened.

272. What is the ServerSocketChannel class?


Located in java.nio.channels package, the ServerSocketChannel class is used to
listen to the TCP connections. Just like the SocketChannels, this class can also
create server-socket channels with the open() method.

Java Memory Management


273. What is memory management in Java?
Memory management is a process of allocating and deallocating memory to the
objects. However, in Java memory management is performed automatically and no logic
is required while programming the application.

274. What is the Java memory model?


Java memory model (JMM) mainly deals with how threads use the memory. By providing
a safe framework for multithreading, it gives the option to use synchronized
blocks, volatile variables, and memory barriers.

275. What is the heap?


In Java, the heap is the memory that is shared by the threads while executing a
program. Being a component of JVM, it dynamically allocates the memory and manages
the object when the program is run.

276. What is the stack?


Simply put, the stack is a linear data structure to store the collection of data.
Using the models of LIFO (Last-In-First-Out), it reorders the objects using classes
and interfaces. Java provides the Stack class having push, pop, and search
functions to work with the listings.

277. What is the garbage collector?


In Java, the garbage is the unnecessary objects that occupy the memory. Therefore,
to get rid of this unused code and free up the space, the garbage collector is
used.

278. What are the different garbage collection algorithms?


Garbage collection is the process of deallocating unused memory to free up the
space. There are several different algorithms to collect the garbage with different
approaches.

Serial garbage collection, parallel garbage collection, concurrent mark, and sweep
collection are some of the commonly used ones.

279. What is the finalize method?


Before destroying the object by garbage collection, this method is called to clean
up the memory by releasing the resources. From detaching event listeners to closing
the Database and Network Connections, this method is quite effective.

Once the method is used, the garbage collector permanently destroys the object.
This process is known as finalization.
280. What are strong references?
Strong references are not accessible to garbage collections. Following is an
example of a strong reference.

MyRefClass obj = new MyRefClass();


However, when the value of the object is set to null, it is no longer considered a
strong reference and is collected by the garbage collector.

281. What are soft references?


Soft references are the ones that are usually not collected. They are only
collected when the JVM runs out of memory.

To create soft references the class of SoftReference must be used.

282. What are weak references?


Weak References are the ones that are marked by the garbage collector to be
removed. To create this type of reference object the class of WeakReference should
be used. Apart from that, the value also needs to be set to null.

283. What are phantom references?


Phantom references are collected by the collectors. The finalize() method is
invoked on them and put in a reference queue where they are deleted one by one.

284. What is the ReferenceQueue class?


ReferenceQueue class is used to determine the type of reference. Only the null set
of references is listed in this queue. According to this queue, the program decides
what action it should take.

285. What is the PhantomReference class?


The phantomReference class is used to create phantom references. This explicitly
declares the object to this reference so that it can be queued in the
ReferenceQueue class. Following the list, these objects are deleted one by one.

286. What is the difference between heap memory and non-heap memory?
The unrequired objects are often stored in the heap memory before they are
collected by the garbage collectors. On the other hand, the non-heap memory is used
to store the information like loaded classes.

287. How do you analyze memory usage in Java applications?

Several methods can be followed to analyze memory usage in Java. Monitoring the CPU
usage, analyzing the garbage collection, and checking the executable methods,
classes, and threads are essential.

At first, the work might seem complex. Thus, often users hire Java developers who
are specialized to effectively analyze the memory usage of the applications.

288. What is the MemoryMXBean class?


This class is an interface that is used to access memory-related properties. The
instance of this class can be obtained by calling the ManagementFactory.

289. How do you perform garbage collection tuning?


Garbage collection tuning is required to obtain the desired results from the JVM.
To perform this there are several simple to complex processes.

It can be done simply by changing the heap size. Again, garbage collection
strategies and IAC solutions are some of the high-end processes that can be used.

290. What is the difference between the young generation and the old generation in
JVM?
Young generations are the memory where the newly created objects are stored. As the
objects are created in the Eden space, they are collected by the garbage collector
when they are not reachable anymore.

Contrastingly, the old generation is used to store long-lived objects. The objects
that are left in the garbage collection of the young generation, are prompted to
the old generation’s memory. Here, they are deleted which are of no use and are
occupying space for too long.

291. How do you monitor garbage collection activity?


To monitor the garbage collection activity, the option of JVM with the name
‘verbosegc’ is available. Another separate CUI application, ‘jstat’ is also there
to monitor this activity.

292. What is a memory leak detector?


Memory leak is a situation where the memories are used up by the unwanted objects,
yet cannot be removed from the allocated space. Therefore, a memory leak detector
is used to identify and solve this.

However, a single detector is not enough for this. Multiple diagnosing is required
for different cases to find all the memory leaks.

293. How do you use the -XX:+UseG1GC JVM option?


The -XX:+UseG1GC JVM option tells the JVM to perform G1 garbage collection. It
operates similarly to the CMS collector.

To determine the liveness of the object, G1 knows the global marking phase. After
the completion of the marking phase, G1 identifies the empty spaces which are
garbage collected.

294. What is the purpose of the jmap tool?


Jmap tools are used to print the statistics to the memory of JVM. It is usually
used in command-line options. Other than that, the use of this prints the list of
the shared objects.

295. How do you perform a heap dump?


Traversing to the JDK bin file, the JMAP command is typed with the heap dump file
name. Also by default, the heap dump is generated in the JDK file.

296. What is the jhat tool used for?


The jhat tool is used to debug the memory leaks. Examining all the reachable
objects, it determines the references that are keeping the objects alive.

297. How do you analyze a heap dump using jhat?


To use the jhat, at first, the location of the JPS of the specific device needs to
be found. Then the jhat command line is given to complete the analysis.

298. What is the purpose of the VisualVM tool?


This tool is used to see detailed information on the remote and local applications
of JVM. it provides a visual interface to view this information.

299. How do you monitor JVM performance?


JVM performance can be monitored by analyzing the CPU performance, executing
threads, and checking the Garbage Collection. At the same time, tuning of the JVM
is also required for the diagnosis practices.

300. What is the jstack tool used for?


The jstack tool is used to obtain the stack traces and their respective thread
information of the processes. It belongs to the bin folder of the OpenJDK.

301. How do you troubleshoot memory leaks?


The most common and easy way to troubleshoot memory leaks is to use the JFR (Java
Flight Recorder) tool. By recording the runtime information, it can identify and
solve the memory leaks.

302. What is the purpose of the jconsole tool?


The jconsole tool is used to provide the performance consumption-related
information of the application that is currently running. It can graphically
monitor the local and the remote programs.

You might also like