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

Java Notes - TheTestingAcademy

Uploaded by

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

Java Notes - TheTestingAcademy

Uploaded by

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

TheTestingAcademy

https://thetestingacademy.com

Java
Interview Question and Answer

Q.1 What is Java?


Java is a high-level programming language and object oriented. It was developed
by Sun Micro systems, initially released in 1995.

y
Q.2 What are the features of Java?

m
Simple
Object-Oriented

de
Portable
Platform independent
Secured
ca
Robust
Architecture neutral
Interpreted
gA

High Performance
Multithreaded
Distributed
Dynamic
tin

Q.3 Three flavors of Java.


es

ME(Micro Edition) for mobile,


SE(Standard Edition) for desktops,
and EE(Enterprise edition) for enterprise.
eT

Q.4 What is JDK?


JDK stands for Java Development Kit. It is a software development kit that
Th

includes everything required to develop, debug, and run Java applications. JDK
includes a Java compiler, the Java Virtual Machine (JVM), and other
development tools.

Q.5 What are the components of JDK?


JDK includes several components, including the Java compiler, the Java Virtual
Machine (JVM), Java Development Tools (such as javac, jar, and javadoc), and
Java Runtime Environment (JRE).
TheTestingAcademy
https://thetestingacademy.com

Q.6 What is the difference between JDK and JRE?


JDK includes the Java compiler and other development tools, which are not
included in JRE. JRE, on the other hand, includes only the Java Virtual Machine
(JVM) and other libraries required to run Java applications.

Q.7 What is JRE?


JRE stands for Java Runtime Environment. It is a software package that includes
the Java Virtual Machine (JVM) and other libraries required to run Java-based

y
applications.

m
Q.8 What are the components of JRE?

de
JRE includes several components, including the Java Virtual Machine (JVM),
Java class libraries, and other supporting files.
ca
Q.9 What is the purpose of JRE?
The main purpose of JRE is to provide a runtime environment for Java-based
applications. It includes the Java Virtual Machine (JVM), which is responsible for
gA

interpreting Java bytecode and executing Java applications.

Q.10 What is JVM?


tin

JVM stands for Java Virtual Machine. It is an abstract machine that interprets
compiled Java bytecode and executes the code. JVM is an essential part of the
Java platform that enables Java applications to be platform-independent.
es

Q.11 What is the purpose of JVM?


eT

The main purpose of JVM is to provide a runtime environment for Java-based


applications. It interprets compiled Java bytecode and executes the code on
different platforms, allowing Java applications to run on any platform that has a
compatible JVM installed.
Th

Q.12 What are the components of JVM?


JVM has three main components: the class loader, the runtime data area, and
the execution engine. The class loader is responsible for loading classes into
JVM. The runtime data area is where data is stored during the execution of a
Java program. The execution engine is responsible for executing the bytecode
instructions.
TheTestingAcademy
https://thetestingacademy.com

Q.13 Is JVM platform-independent?


Yes, JVM is platform-independent. Because JVM interprets compiled Java
bytecode, it can run on any platform that has a compatible JVM installed,
regardless of the underlying hardware and operating system.

Q.14 What is the difference between JVM and JRE?


JVM is a component of both JDK and JRE. It is responsible for interpreting
compiled Java bytecode and executing the code. JRE includes the JVM and

y
other libraries required to run Java-based applications, while JDK includes the

m
Java compiler and other development tools.

Q.15 What are the different types of data types in Java?

de
Primitive data types - These are the basic data types that are provided by Java.
There are eight primitive data types in Java as below
ca
byte: 8-bit signed integer
short: 16-bit signed integer
gA

int: 32-bit signed integer


long: 64-bit signed integer
float: 32-bit floating-point number
double: 64-bit floating-point number
tin

char: 16-bit Unicode character


boolean: true or false
es

Non-primitive data types - These are data types that are not primitive and are
created by the programmer. Non-primitive data types are also known as
reference types because they refer to objects in memory. There are three
eT

non-primitive data types in Java As Classes, Interfaces, Arrays.

Q.16 What is the difference between primitive and non-primitive


Th

data types?
The main difference between primitive and non-primitive data types in
Java is that primitive data types are basic and predefined data types that
are provided by Java, while non-primitive data types are user-defined data
types that are created by the programmer.
TheTestingAcademy
https://thetestingacademy.com

Here are some other differences between primitive and non-primitive


data types:

Memory allocation: Primitive data types are allocated memory on the


stack, while non-primitive data types are allocated memory on the heap.

Default values: Primitive data types have default values defined by Java,
while non-primitive data types do not have default values and must be

y
initialized explicitly by the programmer.

m
Size: The size of a primitive data type is fixed, while the size of a
non-primitive data type depends on the object it is referring to.

de
Operations: Primitive data types can be used in arithmetic and logical
operations, while non-primitive data types require methods to be defined
ca
to perform operations.
gA

Passing parameters: Primitive data types are passed by value, while


non-primitive data types are passed by reference.
tin

Q.17 What is the difference between float and double in Java?


The main difference between float and double in Java is their precision and
range.
es

Float is a 32-bit floating-point data type that can represent a range of


approximately 1.4E-45 to 3.4E+38. It has a precision of about 7 decimal places.
eT

On the other hand, double is a 64-bit floating-point data type that can represent
a range of approximately 4.9E-324 to 1.8E+308. It has a precision of about 15
decimal places.
Th

In other words, double has a higher precision and larger range than float.
However, double requires more memory than float. In general, float is used
when memory usage is a concern and the required precision is not very high,
while double is used when a higher precision is required.

Here's an example that illustrates the difference:


Program:
float f = 1.23456789f;
TheTestingAcademy
https://thetestingacademy.com

double d = 1.23456789d;

System.out.println("Float: " + f);


System.out.println("Double: " + d);

Output:
Float: 1.2345679
Double: 1.23456789

y
As you can see, the float value is rounded to 7 decimal places, while the double

m
value is not rounded and retains its precision up to 8 decimal places.

de
Q.18 What is the difference between int and Integer in Java?
In Java, "int" and "Integer" are both used to represent integer values, but they
have some important differences:
ca
Data Type: "int" is a primitive data type, while "Integer" is a class.
gA

Value: "int" can only store a single value between -2^31 and 2^31-1, while
"Integer" is an object that can store a reference to an int value, which allows it to
represent a wider range of integers.
tin

Nullability: "int" cannot be null, while "Integer" can be null. This is because "int"
is a primitive type and cannot hold a null value, while "Integer" is an object that
can be set to null.
es

Usage: "int" is generally used when you need to represent a simple integer
eT

value, while "Integer" is often used when you need to use the value in a context
that requires an object, such as in collections or when passing arguments to
methods that require objects.
Th

Here's an example of using "int" and "Integer" in Java:


Program:
int a = 10; // declaring an integer variable with the value 10
Integer b = new Integer(20); // declaring an Integer object with the value 20
Integer c = null; // declaring an Integer object that is set to null
TheTestingAcademy
https://thetestingacademy.com

In summary, "int" and "Integer" are both used to represent integer values, but
"int" is a primitive data type that can store a single value, while "Integer" is an
object that can hold a reference to an int value, can be null, and is used in
contexts that require objects.

Q.19 What is the difference between long and Long in Java?


In Java, "long" and "Long" are used to represent integer values that are larger
than the maximum value that can be represented by an "int". Here are the

y
differences between "long" and "Long":

m
Data Type: "long" is a primitive data type, while "Long" is a class.

de
Value: "long" can store a single value between -2^63 and 2^63-1, while "Long"
is an object that can store a reference to a long value.
ca
Nullability: "long" cannot be null, while "Long" can be null. This is because "long"
is a primitive type and cannot hold a null value, while "Long" is an object that can
be set to null.
gA

Usage: "long" is generally used when you need to represent a simple long
integer value, while "Long" is often used when you need to use the value in a
context that requires an object, such as in collections or when passing
tin

arguments to methods that require objects.

Here's an example of using "long" and "Long" in Java:


es

long a = 1234567890L; // declaring a long variable with the value 1234567890


Long b = new Long(9876543210L); // declaring a Long object with the value
eT

9876543210
Long c = null; // declaring a Long object that is set to null

Q.20 What is the difference between char and String in Java?


Th

In Java, "char" and "String" are used to represent text data, but they have some
important differences:

Data Type: "char" is a primitive data type, while "String" is a class.

Value: "char" can only store a single character, while "String" can store a
sequence of characters.
TheTestingAcademy
https://thetestingacademy.com

Nullability: "char" cannot be null, while "String" can be null. This is because
"char" is a primitive type and cannot hold a null value, while "String" is an object
that can be set to null.

Usage: "char" is generally used when you need to represent a single character,
such as a letter or symbol, while "String" is used when you need to represent a
sequence of characters, such as a word, sentence, or paragraph.

Here's an example of using "char" and "String" in Java:

y
char a = 'A'; // declaring a char variable with the value 'A'

m
String b = "Hello"; // declaring a String object with the value "Hello"
String c = null; // declaring a String object that is set to null

de
In summary, "char" and "String" are used to represent text data in Java, but
"char" is a primitive data type that can store a single character, while "String" is a
class that can hold a sequence of characters, can be null, and is used in contexts
ca
that require objects.
gA

Q.21: What is a variable in Java?


A variable is a named container used to store data in memory. It has a data type
that defines the kind of data it can hold, such as an integer, a floating-point
number, or a string.
tin

Q.22 How many types of variable java have?


In Java, there are three types of variables:
es

1.Local Variables
2.Instance Variables
eT

3.Static Variables

Q.23 What is Local Variable?


in Java is a variable that is declared within a method, constructor, or block. Local
Th

variables are only accessible within the block they are declared in and they do
not exist once the block has finished executing.
Here is an example of a local variable declared within a method:
public class Example {
public void myMethod() {
int x = 5; // local variable
System.out.println(x);
}}
TheTestingAcademy
https://thetestingacademy.com

Q.24 What is Instance Variable?


instance variables are also variables that are associated with instances or
objects of a class. They are declared within a class but outside of any method or
constructor. Each instance of the class has its own copy of the instance
variables, which can have different values.

Here is an example of a Java class with an instance variable:


public class Person {
String name;

y
m
public Person(String name) {
this.name = name;

de
}

public void sayHello() {


ca
System.out.println("Hello, my name is " + name);
}
}
gA

In this example, name is an instance variable of the Person class. The Person
class has a constructor that takes a name argument and sets the value of the
name instance variable to that argument using the this keyword. The Person
class also has a sayHello method that uses the name instance variable to print a
tin

greeting that includes the person's name.


Here's an example of how we can create two Person objects with different
names and call the sayHello method on each object:
es

Person person1 = new Person("Alice");


Person person2 = new Person("Bob");
person1.sayHello(); // Output: Hello, my name is Alice
eT

person2.sayHello(); // Output: Hello, my name is Bob

In this example, each Person object has its own name instance variable with a
Th

different value. When we call the sayHello method on each object, it uses the
corresponding name value to print a personalized greeting.
TheTestingAcademy
https://thetestingacademy.com

Q.25 What is a static variable?


a static variable is a variable that belongs to a class, rather than an instance of
that class. This means that the variable is shared among all instances of the class
and can be accessed without creating an object of the class.
Here's an example of a static variable in Java:
public class Example {
public static int count = 0; //static variable
public Example() {
Count++;

y
}}

m
In this example, the count variable is declared as static. This means that there is
only one count variable that is shared by all instances of the Example class.

de
Every time a new instance of Example is created, the constructor is called and
the count variable is incremented. Because count is a static variable, this means
that the value of count is incremented for all instances of the Example class.
ca
For example:
Example e1 = new Example();
Example e2 = new Example();
gA

System.out.println(Example.count);
// Output: 2

In this example, count is incremented twice, once for each instance of Example
tin

created, and its value is printed as 2, since there are now two instances of the
Example class.
Regenerate response
es

Q.26 What is the difference between a constant and a variable?


eT

A constant is a value that cannot be changed once it is assigned. In Java, constants are
declared using the final keyword. A variable, on the other hand, is a container that can
hold different values at different times.
Th

Q.27 What is scope in Java?


Scope refers to the area of the program where a variable can be accessed. In Java,
there are four levels of scope: class-level scope (for instance and static variables),
method-level scope (for local variables), block-level scope (for variables declared inside
a block), and loop-level scope (for variables declared inside a loop).
TheTestingAcademy
https://thetestingacademy.com

Q.28 What is the default value of an instance variable in Java?


The default value of an instance variable depends on its data type. For numeric types,
it is 0. For boolean, it is false. For object references, it is null.

Q.29 What is the difference between a local variable and an


instance variable in Java?
In Java, there are two types of variables: local variables and instance variables. Here
are the differences between them:

y
Scope: A local variable is declared within a method or block of code and is only

m
accessible within that method or block. An instance variable, on the other hand, is
declared within a class but outside of any method and is accessible to all methods

de
within that class.

Lifetime: A local variable exists only as long as the method or block in which it is
declared is executing. Once the method or block completes, the local variable is no
ca
longer accessible. An instance variable, on the other hand, exists for the entire lifetime
of the object and can be accessed by any method within the object.
gA

Initialization: Local variables must be explicitly initialized before they can be used,
while instance variables are automatically initialized to default values if they are not
explicitly initialized. For example, an int instance variable is initialized to 0 by
default.
tin

Memory Allocation: Local variables are stored on the stack, while instance
es

variables are stored on the heap.

Here's an example of using local and instance variables in Java:


eT

public class MyClass {


int instanceVar; // instance variable
Th

public void myMethod() {


int localVar = 0; // local variable
instanceVar = 1; // assigning a value to the instance variable
// code that uses the local and instance variables
}
}

In summary, local variables are declared within a method or block, have a limited
scope and lifetime, must be explicitly initialized, and are stored on the stack.
TheTestingAcademy
https://thetestingacademy.com

Instance variables are declared within a class, have a wider scope and lifetime,
are automatically initialized to default values, and are stored on the heap.

Q.30 What is the difference between a static variable and a


non-static variable in Java?
Scope: Static variables have class-level scope, which means they can be
accessed by any instance of the class and from outside the class using the class
name. Non-static variables have instance-level scope, which means they can

y
only be accessed by the instance they belong to.

m
Memory allocation: Static variables are allocated memory when the class is
loaded by the JVM, whereas non-static variables are allocated memory when an

de
object is created from the class.

Default values: Static variables have default values (0, false or null) if they are
ca
not explicitly initialized, while non-static variables don't have default values and
must be initialized explicitly.
gA

Access modifiers: Static variables can be declared with any access modifier
(public, private, protected, or default), while non-static variables can also be
declared with any access modifier but are usually declared as private to enforce
encapsulation.
tin

Usage: Static variables are often used for constants, configuration settings, or
counters that need to be shared across instances of a class. Non-static variables
es

are used for properties that are unique to each instance of a class.
eT

Q.31 What is string concatenation in Java?


String concatenation is the process of combining two or more strings to form a
single string. In Java, you can use the "+" operator to concatenate strings.
Th

Q.32 Can you explain how the "+" operator works for string
concatenation in Java?
When the "+" operator is used with two strings, it concatenates them to form a
new string. For example, "Hello " + "world" will result in "Hello world". You can
also use the "+=" operator to concatenate a string to an existing string.
TheTestingAcademy
https://thetestingacademy.com

Q.33 What is the difference between using the "+" operator and
StringBuilder for string concatenation in Java?
Using the "+" operator to concatenate strings creates a new string object every
time it is used, which can be inefficient for large strings or frequent
concatenations. StringBuilder, on the other hand, provides a mutable sequence
of characters that can be modified without creating new objects, making it more
efficient for frequent string manipulations.

y
Q.34 Can you show an example of using StringBuilder for string

m
concatenation in Java?

de
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("world");
ca
String result = sb.toString(); // "Hello world"

Q.35 Is there a limit to the number of strings that can be


gA

concatenated using the "+" operator in Java?


There is no hard limit to the number of strings that can be concatenated using
the "+" operator, but it is generally not recommended to concatenate large
tin

numbers of strings in this way due to performance concerns.

Q.36 How can you concatenate strings with different data types
es

in Java?
You can use the String.valueOf() method to convert non-string data types to
eT

strings, and then concatenate them using the "+" operator or StringBuilder. For
example:
int num = 42;
Th

String str = "The answer is " + String.valueOf(num);

Q.37 Can you concatenate strings using the concat() method in


Java?
Yes, the concat() method is an alternative to using the "+" operator for string
concatenation. It takes a single argument, which is the string to concatenate,
and returns a new string. For example:
TheTestingAcademy
https://thetestingacademy.com

String str1 = "Hello";


String str2 = "world";
String result = str1.concat(" ").concat(str2); // "Hello world"

Q.38 What is post-increment in java?


Post-increment is an operator in Java that increments the value of a variable
after it has been used in an expression. The operator is represented by two plus
signs "++" after the variable name.

y
Here is an example of how post-increment works in Java:
int x = 5;

m
int y = x++;
In this example, the value of x is 5 and the post-increment operator "++" is used

de
to increment x after it has been used in the assignment statement. Therefore,
the value of y will be 5 because it was assigned before x was incremented. After
this code executes, the value of x will be 6.
ca
Q.39 What is Post Increment in java?
Post-increment in Java is an operator that increments the value of a variable
gA

after it has been used in an expression. It is represented by the "++" symbol


following the variable name.

Here's an example:
tin

int a = 5;
int b = a++; // the value of b is 5, and a is incremented to 6
es

In this example, the value of a is first assigned to b, and then a is incremented by


1. Therefore, the value of b is 5, and the value of a becomes 6 after the
eT

expression is evaluated.

Q.40 What is the difference between i++ and ++i in a for loop?
Th

In a for loop, i++ and ++i both increment the value of i by 1. However, i++ uses
the old value of i in the loop, while ++i uses the new value of i.

Q.41 Can post-increment and pre-increment operators be used


with non-integer data types?
No, post-increment and pre-increment operators can only be used with integer
data types.
TheTestingAcademy
https://thetestingacademy.com

Q.42 What is the output of the following code?


int i = 5;
int j = i++ + ++i;
System.out.println("i: " + i + ", j: " + j);

The output of the code will be "i: 7, j: 13". The value of i is incremented twice and

y
then added to the original value of i.

m
Q.43 Can post-increment and pre-increment operators be used
with the same variable in the same expression?

de
No, using both post-increment and pre-increment operators on the same
variable in the same expression can lead to undefined behavior.
ca
Q.44 What is the difference between post-increment and
post-decrement operators in Java?
gA

Post-increment operators increment the value of a variable after it is used in an


expression, while post-decrement operators decrement the value of a variable
after it is used in an expression.
tin

Q.45 How can post-increment and pre-increment operators be


used in a while loop in Java?
es

Post-increment and pre-increment operators can be used to increment a


counter variable in a while loop. For example:
eT

int i = 0;
while (i < 10) {
System.out.println(i++);
}
Th

This code will print the numbers 0 to 9 to the console.

Q.46 What are the advantages and disadvantages of using


post-increment?
TheTestingAcademy
https://thetestingacademy.com

Advantages of using post-increment:


:- It allows for concise and readable code, especially in loop constructs. For
example, i++ in a for loop header can be easier to read and understand than i = i
+ 1 or ++i.
:- It can be more efficient in certain cases, as it avoids creating an extra
temporary variable to store the value before the increment operation.

Disadvantages of using post-increment:

y
:- It can be less intuitive and lead to subtle bugs. Since post-increment evaluates
the expression before incrementing, it may not have the expected effect in

m
certain situations. For example, in the expression a = b + c++;, the value of c will
be incremented after the addition operation is performed, which may not be

de
what the programmer intended.
:- It may result in more difficult-to-read code when used in complex expressions,
ca
as it can be unclear whether the increment operation will occur before or after
other operations.
gA

In summary, post-increment can be useful for writing concise and efficient code,
but it can also lead to subtle bugs and reduced readability in certain situations. It
is important for programmers to understand the behavior of post-increment
and use it judiciously.
tin

Q.47 What happens if you use post-increment on a non-integer


es

data type?
String str = "Hello";
str++; // error: bad operand types for binary operator '++'
eT

In this example, we declared a string variable str and tried to use the
post-increment operator on it. However, the compiler will generate an error
Th

because the ++ operator is not defined for the String data type.

To increment the value of a non-numeric data type, you can use other
techniques such as concatenation, adding a fixed value or using a different
method that is defined for that specific data type.

Q.48 What is if-else in java?


TheTestingAcademy
https://thetestingacademy.com

‘if-else’ is a conditional statement in Java that allows you to execute a block of


code if a specified condition is true, and another block of code if the condition is
false. The syntax for if-else statement is:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}

y
Q.49 How many types of if else are there in java?

m
In Java, there are several types of if-else statements that can be used depending
on the complexity of the condition that needs to be tested.

de
● Simple if Statement.
● if-else Statement.
● Nested if-else Statement.
ca
● else-if Ladder.

Q.50 What is the difference between an if statement and an


gA

if-else statement in Java?


An if statement in Java is used to execute a block of code if a specified condition
is true. An if-else statement, on the other hand, is used to execute one block of
tin

code if the condition is true, and another block of code if the condition is false.

Q.51 Can an if-else statement be nested inside another if-else


es

statement?
Yes, an if-else statement can be nested inside another if-else statement. This is
eT

useful when you need to test multiple conditions and execute different blocks of
code depending on the outcomes of those conditions.
Th

Q.52 What is the purpose of the else-if statement in Java?


The else-if statement in Java is used to test additional conditions after the initial
if statement. It allows you to chain together multiple conditions and execute
different blocks of code depending on the outcomes of those conditions.

Q.53 What is nested if-else with an example?


TheTestingAcademy
https://thetestingacademy.com

This type of if-else statement is used when multiple conditions need to be tested
and different blocks of code need to be executed depending on the outcomes of
those conditions.

if (condition1) {
// code to be executed if condition1 is true
if (condition2) {
// code to be executed if both condition1 and condition2 are true
} else {

y
// code to be executed if condition1 is true but condition2 is false

m
}
} else {
// code to be executed if condition1 is false

de
} ca
Q.54 What is else-if Ladder with an example?
An "else-if ladder" is a conditional statement in Java that allows you to test
multiple conditions and execute different code blocks based on the result of
gA

those conditions.

Here's an example of an else-if ladder in Java:


int number = 10;
tin

if (number > 0) {
System.out.println("The number is positive.");
es

} else if (number < 0) {


System.out.println("The number is negative.");
eT

} else {
System.out.println("The number is zero.");
}
Th

In this example, the variable number is set to 10. The program then checks the
value of number against three conditions using an if-else ladder:
● If the number is greater than 0, the program prints "The number is
positive."
● If the number is less than 0, the program prints "The number is negative."
● If the number is equal to 0, the program prints "The number is zero."
TheTestingAcademy
https://thetestingacademy.com

Since the number is greater than 0 in this example, the first condition is true, and
the program will print "The number is positive."

Q.55 How can you simulate a switch statement using if-else


statements in Java?
To simulate a switch statement using if-else statements in Java, you can use a
series of if-else statements that test the value of a variable. Here's an example:

y
int num = 2;

m
if (num == 1) {
// code to be executed if num is 1
} else if (num == 2) {

de
// code to be executed if num is 2
} else if (num == 3) {
// code to be executed if num is 3
ca
} else {
// code to be executed if num is not 1, 2, or 3
}
gA

This simulates a switch statement that tests the value of num and executes a
different block of code depending on the value.
tin

Q.56 How many conditions can you test in a single if statement?


You can only test one condition in a single if statement. If you want to test
multiple conditions, you can use logical operators such as && (and), || (or), and !
es

(not).

Q.57 What is the difference between if-else and switch


eT

statements?
The main difference between if-else and switch statements is that if-else
Th

statements can test any condition, whereas switch statements can only test a
single variable against a fixed set of values.

Q.58 What happens if there is no else statement in an if-else


construct?
If there is no else statement in an if-else construct, the code block inside the if
statement will execute if the condition is true, and no code will execute if the
condition is false.
TheTestingAcademy
https://thetestingacademy.com

Q.59 What is short-circuit evaluation in Java?


Short-circuit evaluation is a feature in Java where the logical operators && (and)
and || (or) do not evaluate the second operand if the result of the operation can
be determined by evaluating the first operand alone.

Q.60 What is the purpose of the continue keyword in a loop?


The continue keyword is used to skip the remaining statements in a loop and
start the next iteration

y
Q.61 What is the ternary operator in Java?

m
The ternary operator is a shorthand for an if-else statement that returns a value.
It is represented by the ? and : symbols and has the following syntax:

de
condition ? value_if_true : value_if_false

int x = 10;
ca
int y = x > 5 ? 1 : 0;
System.out.println(y); // Output: 1
gA

Q.62 What is a switch statement in Java?


A switch statement is a control flow statement that allows a program to test an
expression against a range of possible values and execute different code blocks
tin

based on which value matches. It works by evaluating the expression once and
then comparing its value to each of the case values. If a case value matches the
expression, the corresponding code block is executed. If none of the case values
es

match, the default code block is executed.


int day = 1;
switch (day) {
eT

case 1:
System.out.println("Monday");
break;
Th

case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
Break; }
TheTestingAcademy
https://thetestingacademy.com

Q.63 Can a switch statement be used with other data types


besides integers in Java?
Starting with Java 7, switch statements can also be used with strings. However,
other data types are not supported.
String color = "red";
switch (color) {
case "red":
System.out.println("Red color");

y
break;
case "blue":

m
System.out.println("Blue color");
break;

de
default:
System.out.println("Unknown color");
break;
ca
}
Q.64 Can switch statements be nested in Java?
Yes, switch statements can be nested within each other in Java.
gA

int dayOfWeek = 3;
int hourOfDay = 14;
switch (dayOfWeek) {
tin

case 1:
switch (hourOfDay) {
case 0:
es

case 1:
case 2:
System.out.println("Late Sunday night");
eT

break;
default:
System.out.println("Sunday daytime");
Th

break;
}
break;
case 2:
System.out.println("Monday");
break;
default:
System.out.println("Invalid day");
Break;}
TheTestingAcademy
https://thetestingacademy.com

Q.65 What happens if a break statement is omitted in a switch


statement in Java?
If a break statement is omitted in a switch statement, the code will continue to
execute through each case block until a break statement or the end of the
switch statement is reached.
int day = 1;
switch (day) {
case 1:

y
System.out.println("Monday");
case 2:

m
System.out.println("Tuesday");
default:

de
System.out.println("Invalid day");
}
In this example, if the value of day is 1, both "Monday" and "Tuesday" will be
ca
printed.

Q.66 Can multiple case statements be combined in a switch


gA

statement in Java?
Yes, multiple case statements can be combined in a switch statement by
separating them with a comma. Here is an example:
tin

int day = 1;
switch (day) {
case 1:
es

case 2:
case 3:
case 4:
eT

case 5:
System.out.println("Weekday");
break;
Th

case 6:
case 7:
System.out.println("Weekend");
break;
default:
System.out.println("Invalid day");
Break;}
TheTestingAcademy
https://thetestingacademy.com

Q.67 What is the difference between a switch statement and an


if-else statement in Java?
An if-else statement in Java tests a boolean condition and executes a block of
code if the condition is true, or an optional block of code if the condition is false.
Here is an example:
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");

y
} else {
System.out.println("x is less than or equal to 5");

m
}
A switch statement in Java is used to select one of many code blocks to be

de
executed based on the value of an expression. It tests the expression against a
range of possible values and executes the corresponding code block based on
which value matches. Here is an example:
ca
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
gA

System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
tin

break;
case 3:
System.out.println("Wednesday");
es

break;
default:
eT

System.out.println("Invalid day");
break;
}
The main difference between if-else and switch statements is that if-else
Th

statements test boolean conditions, whereas switch statements test


expressions. switch statements are also more concise and readable when testing
a large number of possible values, whereas if-else statements are more flexible
and can test any boolean expression.
TheTestingAcademy
https://thetestingacademy.com

Q.68 Can the default case be placed anywhere in a switch


statement in Java? with example
It is also possible to place the default case at the beginning or in the middle of
the switch statement. However, if the default case is placed in the middle of the
switch statement, it must be followed by a break statement, or the code will
continue to execute through the subsequent cases. Here is an example:

int x = 5;

y
switch (x) {
default:

m
System.out.println("Default case");
break;

de
case 1:
System.out.println("Case 1");
break;
ca
case 2:
System.out.println("Case 2");
break;
gA

In this example, the default case is placed at the beginning of the switch
statement. If the value of x is not 1 or 2, the code in the default case will be
tin

executed.

Q.69 How can a switch statement be used with enum types in


es

Java?
In Java, enum types can be used with switch statements. Enum types are a
eT

special type of data type that allow you to define a set of named constants. Here
is an example of using a switch statement with an enum type:
enum DayOfWeek {
Th

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


SUNDAY
}

public static void main(String[] args) {


DayOfWeek dayOfWeek = DayOfWeek.WEDNESDAY;
switch (dayOfWeek) {
case MONDAY:
System.out.println("Today is Monday");
TheTestingAcademy
https://thetestingacademy.com

break;
case TUESDAY:
System.out.println("Today is Tuesday");
break;
case WEDNESDAY:
System.out.println("Today is Wednesday");
break;
case THURSDAY:
System.out.println("Today is Thursday");

y
break;

m
case FRIDAY:
System.out.println("Today is Friday");
break;

de
case SATURDAY:
System.out.println("Today is Saturday");
break;
ca
case SUNDAY:
System.out.println("Today is Sunday");
break;
gA

default:
System.out.println("Invalid day");
break;
tin

}
}
es

In this example, we define an enum type called DayOfWeek with seven named
constants representing each day of the week. We then create a variable called
dayOfWeek and assign it the value of DayOfWeek.WEDNESDAY. We use a
eT

switch statement to determine which day of the week it is and print a message
to the console.
Note that using enum types with switch statements has some advantages over
Th

using integers or strings, such as improved type safety and increased readability.

Q.70 Can a switch statement be used with boolean values in


Java?
No, a switch statement cannot be used with boolean values in Java. The switch
statement is designed to evaluate a single value against a series of constants.
Since there are only two possible values for a boolean (true and false), it is easier
TheTestingAcademy
https://thetestingacademy.com

and more readable to use an if-else statement instead of a switch statement.


Here is an example
boolean isRainy = true;
if (isRainy) {
System.out.println("Bring an umbrella");
} else {
System.out.println("No need for an umbrella");
}

y
In this example, we use an if-else statement to check whether the isRainy

m
variable is true or false. If it is true, we print "Bring an umbrella". If it is false, we
print "No need for an umbrella".
Alternatively, you can use a ternary operator to achieve the same result:

de
boolean isRainy = true;
String message = isRainy ? "Bring an umbrella" : "No need for an umbrella";
System.out.println(message);
ca
In this example, we use a ternary operator to assign the message variable either
"Bring an umbrella" or "No need for an umbrella", based on the value of the
gA

isRainy variable. We then print the value of the message variable to the console.
Note that starting with Java 12, you can use switch expressions with boolean
values. However, this is a new feature and not commonly used in Java code.
tin

Q.71 What is the purpose of a labeled break statement in a


switch statement in Java?
es

In Java, a labeled break statement in a switch statement is used to exit the


switch statement prematurely. It is typically used to terminate an outer loop or
eT

switch statement when a certain condition is met. Here is an example:


outer:
for (int i = 1; i <= 5; i++) {
switch (i) {
Th

case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
TheTestingAcademy
https://thetestingacademy.com

break;
case 4:
System.out.println("Four");
break;
case 5:
System.out.println("Five");
break outer; // exit the outer loop
}
}

y
System.out.println("Done");

m
In this example, we use a labeled break statement (break outer) to exit the outer
loop prematurely when the value of i is 5. Without the labeled break statement,

de
the loop would continue until “i” reaches 6, at which point the program would
print "Done". However, because we have labeled the outer loop, the labeled
break statement exits the entire loop, and the program prints "Done"
ca
immediately after "Five" is printed to the console.

Note that labeled break statements can be used with any type of loop or switch
gA

statement, and can have any label name (not just "outer"). However, it is
generally considered good practice to avoid using labeled break statements
whenever possible, as they can make code harder to read and understand.
tin

Q.72 Can a switch statement be used with floating-point


numbers in Java?
es

No, a switch statement cannot be used with floating-point numbers in Java.


According to Java documentation, the switch statement in Java only works with
eT

primitive data types such as byte, short, char, and int, as well as their wrapper
classes (Byte, Short, Character, and Integer), and enumerated types (enum).
If you try to use a switch statement with a floating-point number, you will get a
compilation error. One way to work around this is to convert the floating-point
Th

number to an integer, either by casting or by using the Math.round method.


Here's an example of how to convert a floating-point number to an integer and
use it in a switch statement:
double number = 3.14;
int integerNumber = (int) Math.round(number);

switch (integerNumber) {
case 3:
TheTestingAcademy
https://thetestingacademy.com

System.out.println("The number is three.");


break;
case 4:
System.out.println("The number is four.");
break;
default:
System.out.println("The number is neither three nor four.");
break;
}

y
In this example, the floating-point number 3.14 is first rounded to the nearest

m
integer using the Math.round method, resulting in the integer value 3. The
switch statement then uses this integer value to select one of the cases.

de
Q.73 What happens if no case matches the value in a switch
statement in Java?
ca
If no case matches the value in a switch statement in Java, then the code inside
the default case will be executed, if it exists. The default case is optional and is
executed if none of the other cases match the value of the expression.
gA

Here's an example:
int day = 7;
tin

String dayType;

switch (day) {
es

case 1:
case 2:
case 3:
eT

case 4:
case 5:
dayType = "Weekday";
Th

break;
case 6:
case 7:
dayType = "Weekend";
break;
default:
dayType = "Invalid day";
break;
}
TheTestingAcademy
https://thetestingacademy.com

System.out.println("The day is a " + dayType);

In this example, the variable day is assigned a value of 7. The switch statement
then checks the value of day against each case, but the only case that matches is
case 7. Therefore, the code inside case 7 is executed, which assigns the value
"Weekend" to the dayType variable. The program then prints "The day is a
Weekend".
If day had been assigned a value that did not match any of the cases (for
example, a value of 10), then the code inside the default case would have been

y
executed, which assigns the value "Invalid day" to the dayType variable. The

m
program would then print "The day is an Invalid day".

de
Q.74 How does the order of the cases affect the performance of
a switch statement in Java?
The order of the cases in a switch statement in Java has no effect on the
ca
performance of the statement. This is because the Java compiler generates a
bytecode that uses a lookup table or a hash table to efficiently match the value
of the switch expression with the corresponding case label. This lookup process
gA

is independent of the order of the cases.

Here's an example of a switch statement in Java:


int dayOfWeek = 2;
tin

String dayName;
es

switch (dayOfWeek) {
case 1:
dayName = "Sunday";
eT

break;
case 2:
dayName = "Monday";
Th

break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
TheTestingAcademy
https://thetestingacademy.com

break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";

y
}

m
System.out.println("The day is " + dayName);

de
In this example, the order of the cases does not affect the performance of the
switch statement. The compiler generates bytecode that efficiently matches the
value of dayOfWeek with the corresponding case label, regardless of their
ca
order.

Q.75 How can a switch statement be used with arrays in Java?


gA

In Java, a switch statement can be used with arrays by using the value of an
element in the array as the expression to be matched in the switch statement.
Here's an example:
tin

String[] fruits = {"apple", "banana", "orange", "grape"};

int index = 2; // index of the fruit to be printed


es

String fruitName;

switch (fruits[index]) {
eT

case "apple":
fruitName = "Apple";
break;
Th

case "banana":
fruitName = "Banana";
break;
case "orange":
fruitName = "Orange";
break;
case "grape":
fruitName = "Grape";
TheTestingAcademy
https://thetestingacademy.com

break;
default:
fruitName = "Unknown fruit";
}

System.out.println("The fruit at index " + index + " is " + fruitName);

OUTPUT :- The fruit at index 2 is Orange


In this example, we have an array of fruits and an index of the fruit we want to

y
print. We use the value of the element at the specified index as the expression in

m
the switch statement. The switch statement then matches the value of the
element with the corresponding case label and sets the fruitName variable
accordingly.

de
It's important to note that when using a switch statement with arrays in Java,
the expression used in the switch statement must have a compatible type with
the elements of the array. In this example, we used a String array, so the
ca
expression used in the switch statement must be a String.

Q.76 What is a for loop in Java?


gA

A for loop in Java is a control structure that allows you to repeatedly execute a
block of code based on a certain condition. It is commonly used when you know
the number of times you want to execute a code block.
tin

for (initialization; condition; increment/decrement) {


// code to be executed
}
es

Here, initialization is where you declare and initialize a counter variable.


condition is the condition that must be true for the loop to continue executing,
eT

and increment/decrement is the expression that is evaluated after each


iteration of the loop.
For example, let's say you want to print the numbers from 1 to 5. You can use a
Th

for loop like this:


for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
In this code, i is the counter variable, initialized to 1. The loop will continue
executing as long as i is less than or equal to 5. After each iteration, i is
incremented by 1. The code inside the loop simply prints the value of i.
The output of this code will be:
TheTestingAcademy
https://thetestingacademy.com

1
2
3
4
5

Q.77 How does a for loop differ from a while loop? with example
A for loop and a while loop are both used for iteration in Java, but they differ in
their syntax and the way they are used.

y
A for loop is used when you know the number of times you want to execute a

m
block of code. It has a specific syntax and uses a counter variable to control the
number of iterations. Here's an example:

de
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
ca
In this example, the loop will execute 5 times because the counter variable i is
initialized to 0 and incremented by 1 after each iteration until it reaches 5. The
loop will terminate when the condition i < 5 is no longer true.
gA

On the other hand, a while loop is used when you don't know how many times
you want to execute a block of code. It has a simpler syntax and uses a boolean
expression to control the number of iterations. Here's an example:
tin

int i = 0;
while (i < 5) {
System.out.println(i);
es

i++;
}
In this example, the loop will execute 5 times because the boolean expression i <
eT

5 is true for the first 5 values of i. The loop will terminate when i reaches 5.
In summary, a for loop is used when you know the number of times you want to
execute a block of code, and a while loop is used when you don't know how many
Th

times you want to execute a block of code.

Q.78 How do you write an infinite loop using for loop in Java?
for (int i = 0; ; i++) {
System.out.println(i);
}
Q.79 How do you exit a for loop in Java?
TheTestingAcademy
https://thetestingacademy.com

In Java, you can exit a for loop using the break statement. The break statement
is used to terminate the loop immediately, even if the loop's condition has not
been met.
Here's an example of using break to exit a for loop:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // exit the loop when i is equal to 5
}
System.out.println(i);

y
}

m
In the example above, the for loop runs from i=0 to i=9. However, when i is equal
to 5, the break statement is executed, and the loop is immediately terminated.
As a result, the output of the code is:

de
0
1
2
ca
3
4
Note that break only terminates the innermost loop in which it is used. If you
gA

have nested loops, you can use break to exit the inner loop and continue the
outer loop.
tin

Q.80 How do you loop through an array using a for loop in Java?
with example
es

In Java, you can loop through an array using a for loop. The for loop allows you to
iterate over each element of the array, and perform some action on each
element. Here's an example:
eT

int[] myArray = {1, 2, 3, 4, 5};

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


Th

System.out.println(myArray[i]);
}
In the example above, we have an integer array myArray containing the values 1,
2, 3, 4, 5. We use a for loop to iterate over each element of the array, from index
0 to myArray.length-1.
For each iteration of the loop, the code inside the loop body is executed. In this
case, we simply print out the value of the current array element using
System.out.println(myArray[i]). The output of the code is:
1
TheTestingAcademy
https://thetestingacademy.com

2
3
4
5
Note that we use the length property of the array myArray.length to determine
the number of iterations needed for the loop. This property gives us the number
of elements in the array, and allows us to ensure that we don't try to access an
element outside the bounds of the array.

y
Q.81 How do you loop through a string using a for loop in Java?

m
In Java, you can loop through a string using a for loop, treating the string as an
array of characters. Here's an example:

de
String myString = "Hello, World!";

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


char c = myString.charAt(i);
ca
System.out.println(c);
}
In the example above, we have a string myString containing the value "Hello,
gA

World!". We use a for loop to iterate over each character of the string, from
index 0 to myString.length()-1.
For each iteration of the loop, the code inside the loop body is executed. In this
tin

case, we use the charAt() method to get the character at the current index, and
assign it to the variable c. We then print out the value of c using
System.out.println(c). The output of the code is:
es

H
e
l
eT

l
o
,
Th

W
o
r
l
d
!
TheTestingAcademy
https://thetestingacademy.com

Note that we use the length() method of the string myString.length() to


determine the number of iterations needed for the loop. This method gives us
the number of characters in the string, and allows us to ensure that we don't try
to access a character outside the bounds of the string.

Q.82 How do you use nested for loops in Java?


In Java, you can use nested for loops to perform a set of actions multiple times
with different sets of values. A nested for loop is simply a for loop inside another
for loop. Here's an example:

y
for (int i = 0; i < 3; i++) {

m
for (int j = 0; j < 3; j++) {
System.out.println("i=" + i + ", j=" + j);

de
}
}

In the example above, we have two for loops: an outer loop that runs from i=0 to
ca
i=2, and an inner loop that runs from j=0 to j=2.
For each iteration of the outer loop, the inner loop executes its iterations from
j=0 to j=2. The code inside the inner loop body is executed for each combination
gA

of i and j. In this case, we simply print out the values of i and j using
System.out.println("i=" + i + ", j=" + j).
The output of the code is:
tin

i=0, j=0
i=0, j=1
i=0, j=2
es

i=1, j=0
i=1, j=1
i=1, j=2
eT

i=2, j=0
i=2, j=1
i=2, j=2
Th

Note that you can use nested for loops to perform more complex operations,
such as iterating over two-dimensional arrays or performing a search through a
collection of data. However, be careful with nested loops, as they can quickly
become slow and inefficient if used improperly.

Q.83 How do you use a for-each loop in Java?


TheTestingAcademy
https://thetestingacademy.com

A for-each loop in Java is a simpler way to iterate through an array or any other
collection of elements. It is also known as an enhanced for loop, and it provides a
more concise and readable way to traverse through elements.
Here is an example of how to use a for-each loop in Java:
// Initialize an array
int[] numbers = {1, 2, 3, 4, 5};

// Using for-each loop to iterate through the array


for(int num : numbers) {

y
System.out.print(num + " ");

m
}

In the above example, we have an integer array called numbers that contains five

de
elements. We use a for-each loop to iterate through the array, where each
element in the array is assigned to the variable num. The loop body simply prints
out the value of num followed by a space character.
ca
The output of the above program will be:
12345
Here, the for-each loop simplifies the iteration process and makes the code
gA

more readable, as we don't need to keep track of the array's size or index.

Q.84 How do you iterate over a HashMap using a for loop in


tin

Java?
In Java, you can iterate over a HashMap using a for loop by using the entrySet()
method of the Map interface. The entrySet() method returns a set of key-value
es

pairs in the HashMap, which you can then iterate through using a for loop.
eT

Here is an example of how to iterate over a HashMap using a for loop in Java:
// Initialize a HashMap
Map<String, Integer> studentMarks = new HashMap<>();
studentMarks.put("John", 80);
Th

studentMarks.put("Jane", 90);
studentMarks.put("Bob", 75);
studentMarks.put("Alice", 85);

// Using for loop to iterate over the HashMap


for(Map.Entry<String, Integer> entry : studentMarks.entrySet()) {
String name = entry.getKey();
int marks = entry.getValue();
TheTestingAcademy
https://thetestingacademy.com

System.out.println(name + " scored " + marks + " marks.");


}
In the above example, we have a HashMap called studentMarks that maps the
names of students to their respective marks. We use a for loop to iterate
through the entrySet() of the HashMap, where each entry in the set is assigned
to the variable entry. The loop body retrieves the key and value of each entry
using the getKey() and getValue() methods, respectively. We then use these
values to print out the name of the student and their marks.
The output of the above program will be:

y
John scored 80 marks.

m
Jane scored 90 marks.
Bob scored 75 marks.
Alice scored 85 marks.

de
Here, the for loop allows us to iterate through the HashMap in a sequential
manner and retrieve the key-value pairs of each entry.
ca
Q.85 How do you iterate over a LinkedList using a for loop in
gA

Java?
In Java, you can iterate over a LinkedList using a for loop and the enhanced for
loop, also known as the "for-each" loop. Here's an example of how to use a for
tin

loop to iterate over a LinkedList:

import java.util.LinkedList;
es

public class LinkedListExample {


public static void main(String[] args) {
eT

// Create a LinkedList of String objects


LinkedList<String> list = new LinkedList<>();
Th

// Add some elements to the LinkedList


list.add("apple");
list.add("banana");
list.add("cherry");

// Iterate over the LinkedList using a for loop


for(int i = 0; i < list.size(); i++) {
String element = list.get(i);
System.out.println(element);
TheTestingAcademy
https://thetestingacademy.com

}
}
}

In the above example, we first create a LinkedList of String objects and add some
elements to it. Then we use a for loop to iterate over the LinkedList. The for loop
uses the size() method to determine the number of elements in the LinkedList
and the get() method to retrieve each element at the specified index. Finally, we
print out each element to the console.

y
Output:

m
apple
banana
cherry

de
Q.86 How do you loop through a 2D array using a for loop in
Java?
ca
To loop through a 2D array using a for loop in Java, you can use nested for loops.
Here's an example:
gA

int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

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


for (int j = 0; j < array[i].length; j++) {
tin

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


}
System.out.println();
es

In this example, we have a 2D array called array with 3 rows and 3 columns. We
eT

use two nested for loops to iterate over each element in the array. The outer
loop iterates over each row of the array, and the inner loop iterates over each
element in the row.
Th

Inside the inner loop, we print the value of the current element using
System.out.print(). We also add a space after each value to separate them. After
the inner loop finishes iterating over the elements in a row, we print a newline
character using System.out.println() to move to the next row.
This will output the following:
123
456
789
TheTestingAcademy
https://thetestingacademy.com

This code loops through each element in the array and prints its value to the
console. You can modify the code to perform other operations on the elements
instead of printing them.

Q.87 How do you loop through a 3D array using a for loop in


Java?
To loop through a 3D array using a for loop in Java, you can use nested for loops

y
with an additional loop for the depth of the array. Here's an example:
int[][][] array = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};

m
for (int i = 0; i < array.length; i++) {

de
for (int j = 0; j < array[i].length; j++) {
for (int k = 0; k < array[i][j].length; k++) {
System.out.print(array[i][j][k] + " ");
ca
}
System.out.println();
}
gA

System.out.println();
}
In this example, we have a 3D array called array with 2 "slices", each slice has 2
rows and 2 columns. We use three nested for loops to iterate over each element
tin

in the array. The outer loop iterates over each slice of the array, the middle loop
iterates over each row in the slice, and the inner loop iterates over each element
in the row.
es

Inside the innermost loop, we print the value of the current element using
System.out.print(). We also add a space after each value to separate them. After
eT

the innermost loop finishes iterating over the elements in a row, we print a
newline character using System.out.println() to move to the next row.
After the middle loop finishes iterating over the rows in a slice, we print an
additional newline character to separate the slices.
Th

This will output the following:


12
34

56
78
TheTestingAcademy
https://thetestingacademy.com

This code loops through each element in the 3D array and prints its value to the
console. You can modify the code to perform other operations on the elements
instead of printing them.

Q.88 How do you use the continue statement in a for loop in


Java?
The continue statement in Java is used to skip over the remaining iterations of a
loop and move on to the next iteration. Here is an example of using the continue

y
statement in a for loop in Java:

m
for (int i = 1; i <= 5; i++) {
if (i == 3) {

de
continue; // Skip iteration 3 and move on to the next iteration
}
System.out.println(i);
ca
}

In this example, the for loop runs from 1 to 10, but when i equals 5, the continue
gA

statement is executed, causing the loop to skip iteration 5 and move on to


iteration 6. The output of this code would be:
1
2
tin

4
5
Q.89 How do you reverse a for loop in Java?
es

To reverse a for loop in Java, you can start the loop counter from the maximum
value and decrement it by one in each iteration until it reaches the minimum
eT

value. Here is an example of reversing a for loop in Java:


for (int i = 10; i >= 1; i--) {
System.out.println(i);
}
Th

In this example, the for loop runs from 10 to 1, decrementing the i variable by 1
in each iteration. The output of this code would be:
10
9
8
7
6
TheTestingAcademy
https://thetestingacademy.com

5
4
3
2
1

As you can see, the loop counter starts at 10 and counts down to 1, reversing the
order of the loop. You can use this technique to reverse any for loop in Java by
simply adjusting the loop counter initialization and the condition for the loop to

y
end.

m
Q.90 How do you use the for loop to print a triangle of stars in

de
Java?
To print a triangle of stars in Java using a for loop, you can use two nested for
loops. The outer loop will control the number of rows in the triangle, and the
ca
inner loop will print the stars for each row. Here is an example:
int rows = 5;
for (int i = 1; i <= rows; i++) {
gA

for (int j = 1; j <= i; j++) {


System.out.print("* ");
}
System.out.println();
tin

}
In this example, the outer loop runs from 1 to the number of rows in the triangle
(5 in this case). The inner loop prints the stars for each row, starting from 1 and
es

printing up to the current row number. The System.out.print("* ") statement


prints a single star followed by a space, and the System.out.println() statement
eT

moves to the next line after each row is printed.


The output of this code would be:
*
**
Th

***
****
*****

As you can see, the for loop is used to print a triangle of stars in Java by
controlling the number of rows and the number of stars in each row. You can
adjust the rows variable to print a triangle of stars with a different number of
rows.
TheTestingAcademy
https://thetestingacademy.com

Q.91 How do you use the for loop to print a multiplication table
in Java?
To print a multiplication table in Java using a for loop, you can use two nested for
loops. The outer loop will control the rows of the table, and the inner loop will
control the columns. Here is an example:

int size = 10;

y
for (int i = 1; i <= size; i++) {

m
for (int j = 1; j <= size; j++) {
System.out.print(i * j + "\t");

de
}
System.out.println();
}
ca
In this example, the outer loop runs from 1 to the size of the table (10 in this
case). The inner loop prints the multiplication table for each row, starting from 1
gA

and printing up to the size of the table. The System.out.print(i * j + "\t")


statement calculates the product of the current row and column and prints it
followed by a tab character. The System.out.println() statement moves to the
next line after each row is printed.
tin

The output of this code would be:


1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
es

3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
eT

5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
Th

9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

As you can see, the for loop is used to print a multiplication table in Java by
calculating the product of each row and column and printing it in a
tab-separated format. You can adjust the size variable to print a multiplication
table with a different number of rows and columns.
TheTestingAcademy
https://thetestingacademy.com

Q.92 What is a while loop in Java?


In Java, a while loop is a control flow statement that repeatedly executes a block
of code as long as the condition specified in the loop header is true. The syntax
of a while loop in Java is as follows
public class WhileLoopExample {
public static void main(String[] args) {
int i = 0; // initialization

while (i < 5) { // condition

y
System.out.println("The value of i is: " + i);

m
i++; // update
}

de
System.out.println("Loop ended!");
}
ca
}
In this example, the while loop repeatedly executes the block of code within it as
long as the condition i < 5 is true.
gA

The int i = 0; statement initializes the variable i to 0 before the loop begins.
Then, the condition i < 5 is evaluated. Since i is initially 0 and 0 is less than 5, the
block of code within the loop is executed, which prints out the value of i and then
increments it by 1 using the i++ statement.
tin

The loop continues to execute as long as the condition i < 5 remains true. After i
is incremented to 5, the condition becomes false, and the loop ends. Finally, the
statement System.out.println("Loop ended!"); is executed, which prints out a
es

message to indicate that the loop has ended. The output of this program would
be:
The value of i is: 0
eT

The value of i is: 1


The value of i is: 2
The value of i is: 3
Th

The value of i is: 4


Loop ended!

Q.93 How do you exit a while loop in Java?


To exit a while loop in Java, you can use the break statement. The break
statement immediately terminates the loop and transfers control to the
statement following the loop. Here's an example:
public class WhileLoopExample {
TheTestingAcademy
https://thetestingacademy.com

public static void main(String[] args) {


int i = 0;
while (true) {
System.out.println("The value of i is: " + i);
if (i == 4) {
break; // exit the loop
}
i++; // increment i
}

y
System.out.println("Loop ended!");

m
}
}

de
In this example, the while loop executes indefinitely because the condition true
is always true. However, the if statement within the loop checks if the value of i
is 4, and if it is, the break statement is executed, which terminates the loop
ca
immediately.
After the loop is terminated, the statement System.out.println("Loop ended!");
is executed, which prints out a message to indicate that the loop has ended. The
gA

output of this program would be:


The value of i is: 0
The value of i is: 1
tin

The value of i is: 2


The value of i is: 3
The value of i is: 4
es

Loop ended!

Note that the break statement can also be used in other types of loops (such as
eT

for loops) to exit the loop prematurely.


Th

Q.94 What is the difference between a while loop and a do-while


loop in Java?
In Java, the while loop and do-while loop are two types of looping constructs
that allow you to execute a block of code repeatedly based on a condition. The
main difference between these two loops is when the condition is checked.
TheTestingAcademy
https://thetestingacademy.com

In a while loop, the condition is checked before the loop body is executed. If the
condition is false, the loop body is skipped entirely. Here's an example:
int i = 0;

while (i < 5) {
System.out.println(i);
i++;
}

y
In this example, the loop condition i < 5 is checked before the loop body is

m
executed. If the condition is false (i.e. if i is already greater than or equal to 5),
the loop body is skipped entirely.
In a do-while loop, on the other hand, the condition is checked after the loop

de
body is executed. This means that the loop body is always executed at least once,
even if the condition is false. Here's an example:
int i = 0;
ca
do {
System.out.println(i);
gA

i++;
} while (i < 5);
tin

In this example, the loop body is executed at least once, regardless of the value
of i. The loop condition i < 5 is checked after the first iteration of the loop, and if
it is false, the loop is terminated.
es

To summarize, the key difference between a while loop and a do-while loop is
that a while loop checks the condition before the loop body is executed, while a
do-while loop checks the condition after the loop body is executed.
eT
Th

Q.95 How many times will a while loop execute if the condition is
false?
int i = 10;

while (i < 5) {
System.out.println(i);
TheTestingAcademy
https://thetestingacademy.com

i++;
}
In this example, the condition i < 5 is false from the beginning, since the value of i
is 10 and 10 is not less than 5. Therefore, the loop body is never executed, and
the program will simply move on to the next statement after the loop.
It's important to note that if the condition in a while loop is initially true but
becomes false at some point during the loop, the loop will stop executing and the
program will continue with the next statement after the loop. Here's an
example:

y
int i = 0;

m
while (i < 5) {
System.out.println(i);

de
i += 2;
}
In this example, the loop condition i < 5 is initially true, so the loop body is
ca
executed. The value of i is printed, and then it is incremented by 2 using the
statement i += 2;. This process repeats until the value of i becomes 5, at which
point the loop condition becomes false and the loop stops executing. In total, the
gA

loop executed three times with the values of i being 0, 2, and 4.

Q.96 How do you avoid an infinite loop in a while loop?


tin

To avoid an infinite loop in a while loop, you should ensure that the loop
condition will eventually become false. This means that the loop should have a
way of terminating, either through a condition being met or through a break
es

statement.
Here is an example of a while loop in Java that avoids an infinite loop:
int i = 0;
eT

while (i < 10) {


System.out.println(i);
i++;
Th

}
In this example, the loop condition is i < 10, which means the loop will only run
while i is less than 10. Once i becomes 10, the condition will be false, and the
loop will terminate.
To ensure that the loop condition will eventually become false, you should also
make sure that any variables used in the condition are updated inside the loop.
Otherwise, the loop condition may always be true, resulting in an infinite loop.

int i = 0;
TheTestingAcademy
https://thetestingacademy.com

while (i < 10) {


System.out.println(i);
i++;
if (i == 5) {
break;
}
}
In this example, the loop will run while i is less than 10. Inside the loop, we print
the value of i and increment it by 1. However, if i becomes equal to 5, the break

y
statement is executed, and the loop is terminated, even though the condition i <

m
10 is still true.
When the break statement is executed, the control flow of the program
immediately jumps out of the loop, and the program continues to execute the

de
next statement after the loop.
Note that using break to exit a loop prematurely should be used with caution, as
it can make your code harder to understand and maintain. It's generally better
ca
to design your loop condition so that it naturally terminates, rather than relying
on a break statement.
gA

Q.97 Can a while loop be used to iterate over an array in Java?


int[] numbers = {1, 2, 3, 4, 5};
tin

int i = 0;
while (i < numbers.length) {
System.out.println(numbers[i]);
es

i++;
}
eT

In this example, we have an array of integers called numbers. We initialize a


counter variable i to 0, and then use a while loop to iterate over the array. The
loop condition is i < numbers.length, which means the loop will continue as long
Th

as i is less than the length of the array.


Inside the loop, we use the System.out.println() method to print the value of the
current element in the array, which is numbers[i]. We then increment i by 1,
which allows us to move to the next element in the array.
When i becomes equal to numbers.length, the loop condition will be false, and
the loop will terminate. This ensures that we iterate over every element in the
array.
While this example uses a while loop to iterate over the array, you can also use a
for loop or a foreach loop in Java to achieve the same result.
TheTestingAcademy
https://thetestingacademy.com

Q.98 What is the difference between a while loop and a for loop
in Java?
Both while and for loops are used to repeat a block of code multiple times in
Java. However, there are some differences between them that make them
better suited for different situations.
Here's an example of a while loop that prints the numbers from 1 to 5:
int i = 1;

y
while (i <= 5) {
System.out.println(i);

m
i++;
}

de
Here's an equivalent example of a for loop that does the same thing:

for (int i = 1; i <= 5; i++) {


ca
System.out.println(i);
}
The main difference between the two loops is how they are structured.
gA

In a while loop, you explicitly initialize the loop variable before the loop, and
then update it inside the loop. The loop continues to execute as long as the loop
condition is true.
In a for loop, you declare and initialize the loop variable directly in the loop
tin

header, along with the loop condition and the loop variable update. This makes
for loops more concise and easier to read, especially for simple loops that don't
require complex initialization.
es

In general, while loops are better suited for situations where you don't know the
exact number of iterations required ahead of time, or where the loop condition
is more complex and needs to be updated manually inside the loop.
eT

for loops, on the other hand, are better suited for situations where you know the
exact number of iterations required ahead of time, or where the loop condition
can be expressed more concisely using the for loop syntax.
Th

It's worth noting that you can always convert a while loop into a for loop, and
vice versa, by adjusting the loop structure appropriately. The choice between
the two types of loops often comes down to personal preference and the
specific requirements of the task at hand.

Q.99 How do you reverse a while loop in Java?


int i = 10;
while (i >= 1) {
TheTestingAcademy
https://thetestingacademy.com

System.out.println(i);
i--;
}
This will output the numbers from 10 to 1

Q.100 Can you have nested while loops in Java?


Yes, you can have nested while loops in Java. A nested while loop is a loop inside
another loop. Here is an example of nested while loops in Java:

y
int i = 1;
while (i <= 3) {

m
int j = 1;
while (j <= 3) {

de
System.out.println("i: " + i + ", j: " + j);
j++;
}
ca
i++;
}
In this example, we have a while loop nested inside another while loop. The
gA

outer while loop counts from 1 to 3, while the inner while loop counts from 1 to
3 for each value of the outer loop.
The output of this program will be:
i: 1, j: 1
tin

i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
es

i: 2, j: 2
i: 2, j: 3
eT

i: 3, j: 1
i: 3, j: 2
i: 3, j: 3
Th

Q.101 What is the initial value of the loop variable in a while


loop?
The initial value of the loop variable in a while loop is set before the loop starts
executing. In Java, the loop variable can be declared and initialized outside of
the loop, or it can be declared and initialized inside the loop.
For example, here is a while loop with an initial value of 1 for the loop variable i:
int i = 1;
while (i <= 10) {
TheTestingAcademy
https://thetestingacademy.com

System.out.println(i);
i++;
}
In this example, i is initialized to 1 before the loop starts executing. The loop
condition checks if i is less than or equal to 10, and the loop body prints the
value of i and increments it by 1 on each iteration.
If the loop variable is not initialized before the loop, it will result in a compilation
error. It is also important to make sure that the loop variable is updated inside
the loop, so that the loop condition will eventually become false and the loop will

y
terminate.

m
Q.102 How do you skip an iteration in a while loop in Java?

de
In Java, you can use the continue statement to skip an iteration in a while loop.
The continue statement causes the loop to immediately jump to the next
iteration, skipping any code that comes after it in the loop body.
Here's an example of how to use the continue statement in a while loop:
ca
int i = 0;
while (i < 10) {
gA

i++;
if (i % 2 == 0) {
continue;
tin

}
System.out.println(i);
}
es

In this example, the loop counts from 1 to 10, but the continue statement skips
the even numbers. When i is even, the continue statement is executed, causing
eT

the loop to skip the println statement and jump to the next iteration. When i is
odd, the println statement is executed, printing the value of i.
The output of this program will be:
Th

1
3
5
7
9
As you can see, the even numbers are skipped because of the continue
statement.
TheTestingAcademy
https://thetestingacademy.com

Q.103 How do you break out of nested while loops in Java?


In Java, you can use the break statement to exit out of nested while loops. When
a break statement is executed, it immediately terminates the innermost loop
and resumes execution at the next statement after the loop.
Here's an example of how to use the break statement to exit out of nested while
loops:
int i = 1;
while (i <= 3) {

y
int j = 1;

m
while (j <= 3) {
System.out.println("i: " + i + ", j: " + j);
if (i == 2 && j == 2) {

de
break;
}
j++;
ca
}
if (i == 2 && j == 2) {
break;
gA

}
i++;
}
tin

In this example, we have a nested while loop that prints the values of i and j for
each iteration. The if statement inside the inner while loop checks if i is equal to
es

2 and j is equal to 2, and if so, it executes the break statement to exit out of the
inner while loop. Similarly, the if statement inside the outer while loop checks if i
is equal to 2 and j is equal to 2, and if so, it executes the break statement to exit
eT

out of both while loops.

The output of this program will be:


Th

i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2

As you can see, the loop terminates after printing the value of i and j for the
iteration where i is 2 and j is 2, because of the break statement.
TheTestingAcademy
https://thetestingacademy.com

Q.104 How do you print a pattern using a while loop in Java?


int row = 1;
while (row <= 5) {
int col = 1;
while (col <= row) {
System.out.print("*");
col++;
}

y
System.out.println();

m
row++;
}

de
This code will print the following pattern:
*
**
***
ca
****
*****
gA

In this example, the outer while loop iterates through each row of the pattern,
and the inner while loop iterates through each column of the current row. Inside
the inner loop, the System.out.print("*") statement prints an asterisk for each
tin

column. After printing all the columns in the current row, the inner loop adds a
newline character with System.out.println() to move to the next row. Finally, the
outer loop increments the row variable to move on to the next row until the
es

pattern is complete.
eT

Q.105 How do you find the sum of digits using a while loop in
Th

Java?
int num = 1234;
int sum = 0;

while (num != 0) {
int digit = num % 10;
sum += digit;
num /= 10;
TheTestingAcademy
https://thetestingacademy.com

System.out.println("Sum of digits: " + sum);

In this example, the while loop will iterate 4 times, once for each digit in the
number. In each iteration, the digit variable will be assigned the last digit of the
number, which will be added to the sum variable. Then the num variable will be
divided by 10 to discard the last digit and move on to the next digit. After the

y
loop finishes, the sum variable will contain the sum of all the digits in the

m
number, which will be printed to the console using System.out.println().

Q.105 How do you check if a number is prime using a while loop

de
in Java?
int num = 17;
ca
boolean isPrime = true;
int i = 2;
gA

while (i <= num / 2) {


if (num % i == 0) {
isPrime = false;
break;
tin

}
i++;
}
es

if (isPrime) {
System.out.println(num + " is a prime number");
eT

} else {
System.out.println(num + " is not a prime number");
}
Th

In this example, we are checking if the number num (which is set to 17 in this
case) is prime or not. We initialize a boolean variable isPrime to true to assume
that the number is prime, and we use a while loop to iterate through all the
numbers from 2 to num/2. We check if num is divisible by any of these numbers
using the modulo operator %. If num is divisible by any of these numbers, then it
is not a prime number, and we set isPrime to false and break out of the loop. If
num is not divisible by any of these numbers, then it is a prime number, and
isPrime remains true after the loop finishes.
TheTestingAcademy
https://thetestingacademy.com

Finally, we print out a message to the console depending on whether num is


prime or not. In this example, since num is 17 which is a prime number, the
output will be:
17 is a prime number

Q.106 What is a do-while loop in Java? with example


A do-while loop is a control flow statement in Java that allows a set of
statements to be repeatedly executed based on a given condition. The

y
difference between a do-while loop and a while loop is that the do-while loop

m
executes the statements inside the loop body at least once, regardless of
whether the condition is true or false.

de
Here's the syntax for a do-while loop in Java:

int i = 1;
ca
do {
System.out.println(i);
i++;
gA

} while (i <= 5);

In this example, the loop will run at least once, even if i is greater than 5 initially.
tin

Once inside the loop body, the statement System.out.println(i) will be executed,
and the value of i will be incremented by 1. The loop will continue to run until i is
greater than 5, at which point the loop will terminate.
es

Q.107 How does a do-while loop differ from a while loop?


The main difference between a do-while loop and a while loop in Java is that a
eT

do-while loop executes the code inside the loop at least once, while a while loop
may not execute the code inside the loop at all if the condition is initially false.
Th

Here's an example of a while loop in Java that prints the numbers 1 through 5:

int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
TheTestingAcademy
https://thetestingacademy.com

In this example, the while loop condition is evaluated first, and if i is greater than
5 initially, the loop body is not executed at all.

Now, here's an example of a do-while loop in Java that prints the numbers 1
through 5:

int i = 1;
do {
System.out.println(i);

y
i++;

m
} while (i <= 5);

In this example, the code inside the do block is executed first, regardless of the

de
initial value of i. The loop will continue to execute as long as the condition i <= 5
is true.
ca
Therefore, the primary difference between a do-while loop and a while loop is
that a do-while loop executes the code inside the loop at least once, while a
while loop may not execute the code inside the loop at all if the condition is
gA

initially false.

Q.108 How do you break out of a do-while loop?


tin

you can break out of a do-while loop using the break statement. The break
statement allows you to terminate the loop and immediately exit the loop block.
Here's an example of how to use break to break out of a do-while loop:
es

int i = 1;
do {
if (i == 3) {
eT

break; // break out of loop if i is 3


}
System.out.println(i);
Th

i++;
} while (i <= 5);

Note that break can also be used with a labeled do-while loop to break out of
nested loops. In this case, the label is used to identify the loop to break out of.
For example:

outer: do {
TheTestingAcademy
https://thetestingacademy.com

inner: do {
// some code
if (condition) {
break outer; // break out of both loops
}
// more code
} while (innerCondition);
// more code
} while (outerCondition);

y
m
In this example, break outer will terminate both the inner and outer loops.

Q.109 How do you continue to the next iteration of a do-while

de
loop?
int i = 0;
ca
do {
i++;
if (i % 2 == 0) {
gA

continue; // skip even numbers


}
System.out.println(i);
} while (i < 10);
tin

In this example, the loop will print the first 10 odd numbers (1, 3, 5, 7, 9) by using
es

the continue statement to skip the even numbers. The loop will continue to
iterate as long as the value of i is less than 10. When i is incremented to 10, the
loop will exit.
eT

When the continue statement is executed, it will skip any remaining code in the
current iteration of the loop and move on to the next iteration. In this example, if
Th

i is even, the continue statement will be executed, and the loop will move on to
the next iteration without executing the System.out.println(i) statement.

Q.110 What happens if the condition of a do-while loop is false


initially?
a do-while loop will always execute the statements inside the loop at least once,
even if the condition is false initially. After the first iteration, the condition will
TheTestingAcademy
https://thetestingacademy.com

be evaluated, and if it is true, the loop will continue to execute. If the condition is
false, the loop will exit.
Here's an example:
int i = 10;
do {
System.out.println(i);
i++;
} while (i < 5);

y
In this example, the condition i < 5 is false initially, but the statements inside the

m
loop will still be executed at least once. The output will be:10

After the first iteration, i is incremented to 11, and the condition i < 5 is

de
evaluated again. Since 11 < 5 is false, the loop will exit, and the program will
continue executing the statements after the loop.
ca
Q.111 How do you use a do-while loop to read input from the
user?
gA

A do-while loop can be used to read input from the user in Java by using the
Scanner class to read input from the console inside the loop. Here's an example:
import java.util.Scanner;
public class InputExample {
tin

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
String input;
es

do {
System.out.print("Enter some input (or 'quit' to exit): ");
eT

input = scanner.nextLine();
System.out.println("You entered: " + input);
} while (!input.equals("quit"));
scanner.close();
Th

System.out.println("Program exited.");
}
}
In this example, the loop will repeatedly ask the user to enter some input and
will print the input to the console. The loop will continue until the user enters
the string "quit". The Scanner.nextLine() method is used to read input from the
console, and the !input.equals("quit") condition is used to test whether the user
has entered the "quit" string.
TheTestingAcademy
https://thetestingacademy.com

Note that it's important to close the Scanner object after the loop has finished to
avoid resource leaks. In this example, the scanner.close() method is called after
the loop.

Q.112 How do you use a do-while loop to validate user input?


A do-while loop can be used to validate user input in Java by using conditional
statements inside the loop to check the user's input and continue looping until
the input is valid. Here's an example:

y
import java.util.Scanner;

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

de
Scanner scanner = new Scanner(System.in);
int age;
do {
System.out.print("Enter your age (must be between 0 and 120): ");
ca
while (!scanner.hasNextInt()) {
System.out.println("Invalid input. Please enter a number.");
scanner.next();
gA

}
age = scanner.nextInt();
if (age < 0 || age > 120) {
tin

System.out.println("Invalid input. Please enter a number between 0 and


120.");
}
es

} while (age < 0 || age > 120);


scanner.close();
System.out.println("You entered: " + age);
eT

}
}
Th

In this example, the loop will repeatedly ask the user to enter their age and will continue
looping until the user enters a valid input between 0 and 120. The loop first checks whether
the input is an integer using the Scanner.hasNextInt() method. If the input is not an integer,
the loop will print an error message and prompt the user to enter a valid input.
If the input is an integer, the loop checks whether the input is between 0 and 120 using an if
statement. If the input is not between 0 and 120, the loop will print an error message and
prompt the user to enter a valid input.

Q.113 Can you nest do-while loops in Java?


TheTestingAcademy
https://thetestingacademy.com

Yes, you can nest do-while loops in Java. Nesting do-while loops means that you
have a do-while loop inside another do-while loop. Here's an example:
public class NestedDoWhileExample {
public static void main(String[] args) {
int i = 1, j;
do {
j = 1;
do {
System.out.print(i + " x " + j + " = " + (i*j) + " ");

y
j++;

m
} while (j <= 10);
System.out.println();
i++;

de
} while (i <= 5);
}
}
ca
In this example, the outer loop iterates over the values of i from 1 to 5, and the
inner loop iterates over the values of j from 1 to 10 for each value of i. The loops
gA

print out the multiplication table for the numbers 1 to 5.

The inner loop prints out the product of i and j and increments the value of j until
tin

j is greater than 10. The outer loop then increments the value of i and continues
until i is greater than 5. The loops continue until all the products have been
printed to the console.
es

Note that it's important to keep track of the loop variables and ensure that the
condition for each loop is properly defined, to avoid an infinite loop.
eT

Q.114 How do you use a do-while loop to iterate over a


Th

collection?
A do-while loop can be used to iterate over a collection in Java by using an
iterator object to traverse the collection and calling the hasNext() and next()
methods inside the loop to move to the next element. Here's an example:
import java.util.ArrayList;
import java.util.Iterator;

public class CollectionIterationExample {


TheTestingAcademy
https://thetestingacademy.com

public static void main(String[] args) {


ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("Dave");
Iterator<String> iterator = names.iterator();
String name;
do {

y
if (!iterator.hasNext()) {

m
break;
}
name = iterator.next();

de
System.out.println("Hello, " + name + "!");
} while (true);
}
ca
}

In this example, the loop will iterate over an ArrayList of names and will print a
gA

greeting message to each name in the list. The loop first creates an iterator
object using the iterator() method of the ArrayList object.
The loop then uses a do-while loop with a true condition to repeatedly call the
tin

hasNext() and next() methods of the iterator object. The loop checks whether
the iterator has a next element using the hasNext() method. If there is no next
element, the loop breaks out of the loop using a break statement.
es

If there is a next element, the loop retrieves the next element using the next()
method and prints a greeting message to the console. The loop continues until
all the elements in the list have been processed.
eT

Q.115 How do you use a do-while loop to implement a


menu-driven program?
Th

import java.util.Scanner;

public class MenuDrivenProgramExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("Menu:");
TheTestingAcademy
https://thetestingacademy.com

System.out.println("1. Option 1");


System.out.println("2. Option 2");
System.out.println("3. Option 3");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("You chose Option 1.");

y
break;

m
case 2:
System.out.println("You chose Option 2.");
break;

de
case 3:
System.out.println("You chose Option 3.");
break;
ca
case 4:
System.out.println("Exiting program...");
break;
gA

default:
System.out.println("Invalid choice. Please try again.");
break;
tin

}
System.out.println();
} while (choice != 4);
es

}
}
eT

In this example, the program displays a menu to the user and prompts the user
to enter a choice. The program then uses a switch statement to execute the
appropriate action based on the user's choice.
Th

The program uses a do-while loop with a condition that checks whether the user
has chosen to exit the program. If the user enters the choice 4, the loop will exit
and the program will terminate. If the user enters an invalid choice, the program
will display an error message and prompt the user to enter a choice again.
Note that it's important to validate user input to avoid unexpected behavior or
errors in the program. In this example, we are assuming that the user will enter
an integer value, but we should also handle the case where the user enters a
non-integer value or a value that is outside the range of valid choices.
TheTestingAcademy
https://thetestingacademy.com

Q.116 What is an array in Java?


An array in Java is a data structure that stores a fixed-size sequential collection
of elements of the same type. Each element in an array is assigned a unique
index, starting from 0, that represents its position in the array.
Arrays in Java can be used to store primitive data types (such as integers,
booleans, and characters) as well as objects. They provide a way to store and
manipulate large amounts of data in a structured manner.
The length of an array in Java is fixed at the time of creation and cannot be
changed once the array is created. To access or modify an element in an array,

y
you must use the element's index, which is an integer value between 0 and the

m
length of the array minus 1.
Arrays in Java are a fundamental part of the language and are used extensively

de
in many applications, including sorting algorithms, matrix manipulation, and
database applications.

Q.117 How do you declare an array in Java?


ca
To declare an array in Java, you must specify the type of the array and the name
of the array. Here's the basic syntax:
gA

type[] arrayName;

For example, to declare an array of integers called myArray, you would write:
int[] myArray;
tin

You can also declare the size of the array at the time of declaration by specifying
the number of elements it will contain:
es

type[] arrayName = new type[size];


eT

For example, to declare an array of 10 integers called myArray, you would write:
int[] myArray = new int[10];

This creates an array of 10 integers with initial values of 0. Once you have
Th

declared an array, you can assign values to its elements using the array index.
For example:
myArray[0] = 5;
myArray[1] = 10;
myArray[2] = 15;

This sets the first three elements of myArray to 5, 10, and 15, respectively. You
can also assign values to an array at the time of declaration, like this:
TheTestingAcademy
https://thetestingacademy.com

int[] myArray = {5, 10, 15};

Q.118 What is the syntax for accessing elements in an array?


To access elements in an array in Java, you can use the array index. Here's an
example:
int[] myArray = {1, 2, 3, 4, 5};
System.out.println(myArray[0]); // Output: 1
System.out.println(myArray[1]); // Output: 2
System.out.println(myArray[2]); // Output: 3

y
m
In this example, we have an array of integers called myArray with five elements.
We then use the array index to access each element and print its value to the

de
console.
You can also use a loop to access all the elements in an array. For example, to
print all the elements in myArray, you could do:
for (int i = 0; i < myArray.length; i++) {
ca
System.out.println(myArray[i]);
}
gA

This will iterate over each element in myArray and print its value to the console.
It's important to note that you must use a valid index when accessing elements
in an array. The index must be within the bounds of the array (i.e., between 0 and
tin

the length of the array minus 1). If you try to access an index that is outside the
bounds of the array, you will get an ArrayIndexOutOfBoundsException.
es

Q.119 How do you initialize an array in Java?


You can initialize an array in Java using the following syntax:
type[] arrayName = {value1, value2, ..., valueN};
eT

Here's an example of how to initialize an array of integers:


int[] myArray = {1, 2, 3, 4, 5};
Th

This creates an array called myArray with five elements, each of which has an
initial value of 1, 2, 3, 4, or 5.
You can also use the new keyword to create and initialize an array. Here's an
example:
int[] myArray = new int[]{1, 2, 3, 4, 5};
TheTestingAcademy
https://thetestingacademy.com

This creates a new array of integers with the same values as the previous
example.
If you use the new keyword to create an array without specifying the initial
values, the array elements will be initialized to their default values (e.g., 0 for
integers, false for booleans, etc.). Here's an example:
int[] myArray = new int[5];

This creates a new array of integers with five elements, each of which has an
initial value of 0.

y
It's worth noting that you can also initialize a two-dimensional array using a

m
similar syntax:
int[][] myArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
This creates a two-dimensional array with three rows and three columns,

de
initialized with the values 1 through 9.
ca
Q.120 What is the difference between an array and an ArrayList?
In Java, an array and an ArrayList are both used to store collections of elements.
However, there are some important differences between them:
gA

1. Fixed size vs. dynamic size: An array has a fixed size, which is determined
when it is created. Once the array is created, its size cannot be changed.
On the other hand, an ArrayList has a dynamic size. It can grow or shrink
as elements are added or removed from it.
tin

2. Type safety: An array is type-safe, meaning that the type of elements that
it can contain is determined at compile time. Once an array is created, you
cannot add elements of a different type to it. In contrast, an ArrayList is
es

not type-safe. You can add elements of any type to it, and the type of
elements is determined at runtime.
eT

3. Accessing elements: Accessing elements in an array is generally faster


than accessing elements in an ArrayList. This is because an array is stored
as a contiguous block of memory, whereas an ArrayList is implemented
using an underlying array that may need to be resized or moved around in
Th

memory.
4. Additional methods: An ArrayList provides additional methods that an
array does not have, such as adding or removing elements, searching for
elements, and sorting elements.
Here's a summary of the key differences between an array and an ArrayList:
TheTestingAcademy
https://thetestingacademy.com

Feature Array ArrayList

Size Fixed Dynamic

y
Type safety Type-safe Not type-safe

m
de
Accessing elements
ca Fast Slower than array

Additional methods Limited Many additional methods


gA

In summary, arrays are best suited for situations where you need a fixed-size
collection of elements that are all of the same type, and you don't need to add or
tin

remove elements frequently. ArrayLists are better suited for situations where
you need a dynamic collection of elements that can grow or shrink as needed,
and you need additional methods for manipulating the collection.
es

Q.121 How do you find the length of an array in Java?


In Java, you can find the length of an array using the length property. Here's an
eT

example:
int[] myArray = {1, 2, 3, 4, 5};
int length = myArray.length;
System.out.println(length); // Output: 5
Th

In this example, we have an array called myArray with five elements. We use the
length property to find the length of the array and store it in a variable called
length. We then print the value of length to the console, which should be 5.
It's important to note that the length property returns the number of elements
in the array, not the size of the underlying memory allocation. If you create an
array with a size of 5, the length property will return 5 even if some of the
elements are uninitialized or contain default values.
TheTestingAcademy
https://thetestingacademy.com

Also, you cannot change the value of the length property once an array is
created. If you need to change the size of an array, you will need to create a new
array with the desired size and copy the elements from the old array to the new
array.
Q.122 How do you sort an array in Java?
In Java, you can sort an array using the Arrays.sort() method. Here's an example:
int[] myArray = {5, 2, 7, 3, 9};
Arrays.sort(myArray);

y
System.out.println(Arrays.toString(myArray)); // Output: [2, 3, 5, 7, 9]

m
In this example, we have an array called myArray with five elements. We use the
Arrays.sort() method to sort the elements in ascending order. We then print the

de
sorted array to the console using the Arrays.toString() method.
If you need to sort the elements in descending order, you can use the
Comparator.reverseOrder() method. Here's an example:
ca
Integer[] myArray = {5, 2, 7, 3, 9};
Arrays.sort(myArray, Comparator.reverseOrder());
System.out.println(Arrays.toString(myArray)); // Output: [9, 7, 5, 3, 2]
gA

In this example, we have an array of Integer objects called myArray. We use the
Arrays.sort() method with a Comparator that sorts the elements in descending
tin

order. We then print the sorted array to the console.


It's important to note that the Arrays.sort() method sorts the array in place,
meaning that it modifies the original array rather than creating a new sorted
es

array. If you need to preserve the original array, you should make a copy of it
before sorting.
eT

Q.123 What is a multidimensional array in Java?


A multidimensional array in Java is an array of arrays. It allows you to store data
in a table-like format with rows and columns. You can think of a two-dimensional
Th

array as a matrix, where each element is identified by its row and column index.
Here's an example of a two-dimensional array in Java:
int[][] myArray = new int[3][4];

In this example, we create a two-dimensional array called myArray with three


rows and four columns. The first dimension specifies the number of rows, and
the second dimension specifies the number of columns.
TheTestingAcademy
https://thetestingacademy.com

We can access the elements of the array using two indices, one for the row and
one for the column. For example, to access the element in the second row and
third column, we would write:
int element = myArray[1][2];

It's important to note that each row in a multidimensional array can have a
different length. For example, we could create a two-dimensional array where
each row has a different number of columns:
int[][] myArray = {

y
{1, 2, 3},

m
{4, 5},
{6, 7, 8, 9}
};

de
In this example, we create a two-dimensional array called myArray with three
rows. The first row has three columns, the second row has two columns, and the
third row has four columns.
ca
Multidimensional arrays can have more than two dimensions, allowing you to
create arrays of arrays of arrays, and so on. However, they can become difficult
to work with as the number of dimensions increases.
gA

Q.124 What is a jagged array in Java?


In Java, a jagged array (also called a ragged array) is a multidimensional array in
tin

which the length of each row may be different from the length of other rows.
Unlike a regular two-dimensional array, in which every row has the same
number of columns, a jagged array allows you to create arrays with different
es

lengths of rows.
Here's an example of a jagged array in Java that has three rows with different
lengths:
eT

int[][] jaggedArray = new int[][] {


{1, 2},
Th

{3, 4, 5},
{6, 7, 8, 9}
};

In this example, the first row has two columns, the second row has three
columns, and the third row has four columns.
To access an element in a jagged array, you can use the row and column indices
as usual, for example:
int element = jaggedArray[1][2]; // element is 5
TheTestingAcademy
https://thetestingacademy.com

Q.125 How do you pass an array as a parameter to a method in


Java?
In Java, you can pass an array as a parameter to a method by specifying the type
of the array and the array name in the method signature. Here's an example:
public void myMethod(int[] myArray) {
// method body
}

y
In this example, we declare a method called myMethod that takes an integer

m
array myArray as a parameter. Within the method body, you can manipulate the
elements of the array as needed.

de
To call the method and pass an array as a parameter, you can simply pass the
array name as an argument:
int[] myArray = {1, 2, 3, 4, 5};
myMethod(myArray);
ca
In this example, we create an integer array myArray and initialize it with some
values. Then, we call the myMethod method and pass myArray as a parameter.
gA
tin

Q.126 How do you return an array from a method in Java?


public int[] myMethod() {
int[] myArray = {1, 2, 3, 4, 5};
es

return myArray;
}
In this example, we declare a method called myMethod that returns an integer
eT

array. Within the method body, we create an integer array myArray and initialize
it with some values. Then, we use the return keyword followed by myArray to
return the array from the method.
Th

To use the returned array, you can assign it to a new array variable:

int[] newArray = myMethod();

In this example, we call the myMethod method and assign the returned array to
a new integer array variable called newArray.
TheTestingAcademy
https://thetestingacademy.com

Q.127 How do you find the minimum and maximum values in an


array in Java?
In Java, you can find the minimum and maximum values in an array by iterating
over the array and keeping track of the minimum and maximum values found so
far. Here are examples of how to do this:

1. Finding the minimum value in an array:


int[] myArray = {1, 2, 3, 4, 5};

y
int minValue = myArray[0];

m
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] < minValue) {

de
minValue = myArray[i];
}
}
ca
System.out.println("The minimum value in the array is: " + minValue);

In this example, we have an integer array called myArray. We set the initial
gA

minimum value to the first element of the array. Then, we use a for loop to
iterate over the remaining elements of the array. Within the loop, we check if
the current element is less than the current minimum value. If it is, we update
the minimum value to the current element. Finally, we print the minimum value
tin

found.

2. Finding the maximum value in an array:


es

int[] myArray = {1, 2, 3, 4, 5};


int maxValue = myArray[0];
eT

for (int i = 1; i < myArray.length; i++) {


if (myArray[i] > maxValue) {
maxValue = myArray[i];
Th

}
}
System.out.println("The maximum value in the array is: " + maxValue);
In this example, we have an integer array called myArray. We set the initial
maximum value to the first element of the array. Then, we use a for loop to
iterate over the remaining elements of the array. Within the loop, we check if
the current element is greater than the current maximum value. If it is, we
TheTestingAcademy
https://thetestingacademy.com

update the maximum value to the current element. Finally, we print the
maximum value found.

Q.128 What is the difference between an array and a set in Java?


In Java, an array is an ordered collection of elements of the same data type,
while a set is an unordered collection of unique elements. Here are some
examples to illustrate the difference:

1. Example of an array:

y
int[] myArray = {1, 2, 3, 4, 5};

m
In this example, we declare an integer array called myArray that contains the

de
values 1, 2, 3, 4, and 5. The elements are stored in order and can be accessed by
their index, starting at 0.

2. Example of a set:
ca
Set<Integer> mySet = new HashSet<>();
mySet.add(1);
mySet.add(2);
gA

mySet.add(3);
mySet.add(4);
mySet.add(5);
tin

Which data structure to use depends on the specific needs of your program. If
you need to store an ordered collection of elements and allow duplicates, use an
array. If you need to store a collection of unique elements and order is not
es

important, use a set.

Q.129 What is a String in Java?


eT

In Java, a String is an object that represents a sequence of characters. It is one of


the most commonly used classes in the Java API, and is used to store and
manipulate textual data.
Th

Strings in Java are immutable, which means that once a String object is created,
its contents cannot be changed. Any operation that appears to modify a String
object actually creates a new String object with the modified contents.
Here is an example of creating a String object in Java:
String myString = "Hello, world!";

In this example, we declare a String object called myString that contains the text
"Hello, world!". Note that we use double quotes to indicate that we are creating
a String object, rather than single quotes, which are used for character literals.
TheTestingAcademy
https://thetestingacademy.com

Some common operations that can be performed on String objects in Java


include:
● Concatenation: combining two or more strings into a single string
● Comparison: checking if two strings are equal or comparing their
lexicographical order
● Substring extraction: retrieving a portion of a string
● Case conversion: converting a string to upper or lower case
● Search and replace: finding and replacing occurrences of a substring
within a string

y
Overall, Strings are a fundamental part of the Java language and are widely used

m
in Java programs for storing and manipulating text.

Q.130 What is the difference between a String and a

de
StringBuilder?
The main difference between a String and a StringBuilder in Java is that Strings
ca
are immutable while StringBuilders are mutable.
An immutable object is an object whose state cannot be modified once it is
created. In the case of Strings, any operation that appears to modify the
gA

contents of a String actually creates a new String object with the modified
contents. This can be inefficient for operations that involve a lot of
modifications, since it requires the creation of many new String objects.
tin

A mutable object, on the other hand, is an object whose state can be


modified after it is created. In the case of StringBuilders, operations that modify
the contents of a StringBuilder do not create new objects; instead, they modify
es

the existing StringBuilder object in place. This can be more efficient than using
Strings for operations that involve a lot of modifications.
eT

StringBuilder sb = new StringBuilder();


sb.append("Hello, ");
sb.append("world!");
Th

String result = sb.toString(); // "Hello, world!"

In this example, we create a StringBuilder object called sb and use its append()
method to concatenate two strings. Finally, we convert the StringBuilder object
to a String using the toString() method.
Overall, Strings are best used when the text is not expected to change
frequently, while StringBuilders are best used when the text is expected to be
modified frequently.
TheTestingAcademy
https://thetestingacademy.com

Q.131 Can you explain the immutability of Strings in Java?


In Java, the immutability of Strings means that once a String object is created, its
contents cannot be modified. Any operation that appears to modify a String
actually creates a new String object with the modified contents.
Here's an example to illustrate the immutability of Strings in Java:
String str1 = "Hello";
String str2 = str1 + " world";

y
In this example, we create a String object called str1 that contains the text

m
"Hello". We then create a new String object called str2 by concatenating str1
with the text " world". However, this concatenation operation does not modify

de
the contents of str1. Instead, it creates a new String object with the contents
"Hello world" and assigns it to str2.
The immutability of Strings can have both advantages and disadvantages. On
the one hand, it makes Strings thread-safe and simplifies their use in
ca
multithreaded environments. It also enables certain optimizations, such as
string interning, where the JVM can reuse existing String objects for identical
strings to save memory.
gA

On the other hand, the immutability of Strings can make some operations less
efficient, especially when they involve a lot of modifications. For example,
concatenating many strings together using the + operator can be inefficient
tin

because it creates many new String objects.


Overall, the immutability of Strings in Java is an important characteristic that
affects how Strings are used and manipulated in Java programs.
es

Q.132 How do you create a String object in Java?


In Java, you can create a String object in several ways:
eT

1. Using string literals:


String str = "Hello, world!";
Th

2. Using the new operator:


String str = new String("Hello, world!");

Note that using string literals is more common and is generally preferred over
using the new operator, since it is more concise and can take advantage of string
interning.
3. Using the charAt() method of another String object:
String str1 = "Hello, world!";
TheTestingAcademy
https://thetestingacademy.com

char ch = str1.charAt(0);
String str2 = Character.toString(ch);

In this example, we create a new String object str2 by converting the first
character of an existing String object str1 to a String using the
Character.toString() method.

4. Using a byte array:


byte[] byteArray = {72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33};

y
String str = new String(byteArray);

m
In this example, we create a new String object str by converting a byte array to a
String using the String(byte[]) constructor.
5. Using a character array:

de
char[] charArray = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'};
String str = new String(charArray);
ca
In this example, we create a new String object str by converting a character
array to a String using the String(char[]) constructor.
gA

Q.133 How do you check if two Strings are equal in Java?


In Java, you can check if two Strings are equal in several ways:
tin

1.Using the equals() method:


String str1 = "Hello, world!";
String str2 = "Hello, world!";
es

if (str1.equals(str2)) {
System.out.println("The two strings are equal");
} else {
eT

System.out.println("The two strings are not equal");


}
In this example, we use the equals() method to check if str1 is equal to str2. If
Th

they are equal, the program outputs "The two strings are equal"; otherwise, it
outputs "The two strings are not equal".

2.Using the equalsIgnoreCase() method:


String str1 = "HELLO, world!";
String str2 = "hello, WORLD!";
if (str1.equalsIgnoreCase(str2)) {
System.out.println("The two strings are equal");
} else {
TheTestingAcademy
https://thetestingacademy.com

System.out.println("The two strings are not equal");


}

In this example, we use the equalsIgnoreCase() method to check if str1 is equal


to str2 while ignoring case differences. If they are equal, the program outputs
"The two strings are equal"; otherwise, it outputs "The two strings are not
equal".

3.Using the == operator:

y
String str1 = "Hello, world!";

m
String str2 = "Hello, world!";
if (str1 == str2) {
System.out.println("The two strings are equal");

de
} else {
System.out.println("The two strings are not equal");
}
ca
In this example, we use the == operator to check if str1 and str2 reference the
same object in memory. If they do, the program outputs "The two strings are
equal"; otherwise, it outputs "The two strings are not equal".
gA

Note that the equals() and equalsIgnoreCase() methods are generally preferred
for comparing Strings in Java, since they compare the contents of the Strings
rather than their references in memory.
tin

Q.134 How do you concatenate two Strings in Java?


In Java, you can concatenate two Strings using the + operator or the concat()
es

method:
1.Using the + operator:
String str1 = "Hello";
eT

String str2 = "world";


String str3 = str1 + ", " + str2 + "!";
System.out.println(str3); // Output: "Hello, world!"
Th

In this example, we use the + operator to concatenate the strings str1, ", ", str2,
and "!" into a new String object str3.

2. Using the concat() method:


String str1 = "Hello";
String str2 = "world";
String str3 = str1.concat(", ").concat(str2).concat("!");
System.out.println(str3); // Output: "Hello, world!"
TheTestingAcademy
https://thetestingacademy.com

In this example, we use the concat() method to concatenate the strings str1, ", ",
str2, and "!" into a new String object str3.
Note that both methods produce the same result. The + operator is generally
preferred for concatenating small numbers of strings, while the concat() method
is more efficient for concatenating large numbers of strings, since it avoids
creating multiple intermediate String objects.

Q.135 How do you convert a String to an integer in Java?

y
In Java, you can convert a String to an integer using the parseInt() method of the

m
Integer class. Here's an example:
String str = "123";

de
int num = Integer.parseInt(str);
System.out.println(num); // Output: 123
In this example, we convert the String "123" to an integer using the parseInt()
method, and store the result in the variable num. Finally, we print the value of
ca
num to the console.
Note that if the String does not contain a valid integer value, the parseInt()
method will throw a NumberFormatException. You can handle this exception
gA

using a try-catch block:


String str = "abc";
try {
tin

int num = Integer.parseInt(str);


System.out.println(num);
} catch (NumberFormatException e) {
es

System.out.println("The string does not contain a valid integer value");


}
eT

In this example, we attempt to convert the String "abc" to an integer using the
parseInt() method. Since this String does not contain a valid integer value, the
method throws a NumberFormatException. We catch this exception and print
Th

an error message to the console.

Q.136 How do you convert an integer to a String in Java?


In Java, you can convert an integer to a String using the toString() method of the
Integer class. Here's an example:
int num = 42;
String str = Integer.toString(num);
System.out.println("The integer " + num + " converted to a String is: " + str);
TheTestingAcademy
https://thetestingacademy.com

In this example, we first define an integer num with the value 42. We then use
the toString() method of the Integer class to convert num to a String and assign
it to the variable str. Finally, we print out a message that shows the original
integer value and the corresponding string representation.
Output:
The integer 42 converted to a String is: 42

Note that there are other ways to convert an integer to a String in Java, such as
using the String.valueOf() method or concatenating an empty string to the

y
integer value. However, using Integer.toString() is a straightforward and

m
commonly used method.

de
Q.137 How do you find the length of a String in Java?
In Java, you can find the length of a String by using the length() method. Here's
ca
an example:
String str = "Hello, world!";
int len = str.length();
gA

System.out.println("The length of the string \"" + str + "\" is " + len + ".");
In this example, we first define a String str with the value "Hello, world!". We
then use the length() method to find the length of the string and assign it to the
tin

variable len. Finally, we print out a message that shows the original string and its
length.
Output:
es

The length of the string "Hello, world!" is 13.

Note that the length() method returns the number of characters in the String,
eT

not including any null characters at the end of the string. Also, the length()
method is a method of the String class and can be used on any String object, not
just the str variable in this example.
Th

Q.138 How do you compare two Strings in Java?


In Java, you can compare two Strings using the equals() method or the
compareTo() method. Here are examples of both methods:
Using the equals() method:
String str1 = "Hello";
String str2 = "World";
String str3 = "Hello";
TheTestingAcademy
https://thetestingacademy.com

if (str1.equals(str2)) {
System.out.println("str1 and str2 are equal");
} else {
System.out.println("str1 and str2 are not equal");
}

if (str1.equals(str3)) {
System.out.println("str1 and str3 are equal");

y
} else {

m
System.out.println("str1 and str3 are not equal");
}

de
In this example, we define three Strings str1, str2, and str3. We then use the
equals() method to compare str1 with str2 and str1 with str3. The equals()
method returns true if the two Strings are equal and false otherwise. We use an
ca
if-else statement to print out a message indicating whether the two Strings are
equal or not.
gA

Output:

str1 and str2 are not equal


tin

str1 and str3 are equal

Using the compareTo() method:


es

String str1 = "Hello";


String str2 = "World";
String str3 = "Hello";
eT

int result1 = str1.compareTo(str2);


int result2 = str1.compareTo(str3);
Th

if (result1 == 0) {
System.out.println("str1 and str2 are equal");
} else if (result1 < 0) {
System.out.println("str1 comes before str2");
} else {
System.out.println("str1 comes after str2");
}
TheTestingAcademy
https://thetestingacademy.com

if (result2 == 0) {
System.out.println("str1 and str3 are equal");
} else if (result2 < 0) {
System.out.println("str1 comes before str3");
} else {
System.out.println("str1 comes after str3");
}

In this example, we define three Strings str1, str2, and str3. We then use the

y
compareTo() method to compare str1 with str2 and str1 with str3. The

m
compareTo() method returns an integer value that represents the difference
between the two Strings. If the two Strings are equal, the method returns 0. If
the first String comes before the second String in lexicographic order, the

de
method returns a negative value. If the first String comes after the second String
in lexicographic order, the method returns a positive value. We use an if-else
statement to print out a message indicating the result of the comparison.
ca
Output:
gA

str1 comes before str2


str1 and str3 are equal
Note that the equals() method compares the contents of the Strings for
tin

equality, while the compareTo() method compares the Strings


lexicographically. The choice of which method to use depends on what
kind of comparison you want to perform.
es

Q.139 How do you convert a String to uppercase in Java?


eT

In Java, you can convert a String to uppercase using the toUpperCase() method.
Here's an example:
String str = "Hello, world!";
String strUpper = str.toUpperCase();
Th

System.out.println("The original string is: " + str);


System.out.println("The uppercase string is: " + strUpper);

In this example, we first define a String str with the value "Hello, world!". We
then use the toUpperCase() method to convert the string to uppercase and
assign it to the variable strUpper. Finally, we print out a message that shows the
original string and its uppercase version.
TheTestingAcademy
https://thetestingacademy.com

Output:

The original string is: Hello, world!


The uppercase string is: HELLO, WORLD!

Note that the toUpperCase() method returns a new String object that contains
the uppercase version of the original string. The original string is not modified.
Also, the toUpperCase() method converts all characters in the String to
uppercase, regardless of their original case.

y
m
Q.140 How do you convert a String to lowercase in Java?

de
In Java, you can convert a String to lowercase using the toLowerCase() method.
Here's an example:
String str = "Hello, world!";
ca
String strLower = str.toLowerCase();
System.out.println("The original string is: " + str);
System.out.println("The lowercase string is: " + strLower);
gA

In this example, we first define a String str with the value "Hello, world!". We
then use the toLowerCase() method to convert the string to lowercase and
tin

assign it to the variable strLower. Finally, we print out a message that shows the
original string and its lowercase version.
es

Output:
eT

The original string is: Hello, world!


The lowercase string is: hello, world!
Note that the toLowerCase() method returns a new String object that contains
the lowercase version of the original string. The original string is not modified.
Th

Also, the toLowerCase() method converts all characters in the String to


lowercase, regardless of their original case.

Q.141 How do you remove whitespace from a String in Java?


In Java, you can remove whitespace from a String using the trim() method or by
using regular expressions. Here are examples of both methods:

Using the trim() method:


TheTestingAcademy
https://thetestingacademy.com

String str = " Hello, world! ";


String strTrimmed = str.trim();
System.out.println("The original string is: " + str);
System.out.println("The trimmed string is: " + strTrimmed);

In this example, we first define a String str with the value " Hello, world! ". We
then use the trim() method to remove the leading and trailing whitespace from
the string and assign it to the variable strTrimmed. Finally, we print out a

y
message that shows the original string and its trimmed version.

m
Output:

de
The original string is: Hello, world!
The trimmed string is: Hello, world!
ca
Q.142 How do you split a String into an array of substrings in
Java?
In Java, you can split a String into an array of substrings using the split() method.
gA

Here's an example:
String str = "The quick brown fox jumps over the lazy dog";
String[] words = str.split(" ");
tin

System.out.println("The original string is: " + str);


System.out.println("The words in the string are:");
for (String word : words) {
es

System.out.println(word);
}
eT

In this example, we first define a String str with the value "The quick brown fox
jumps over the lazy dog". We then use the split() method to split the string into
an array of substrings, using a space as the delimiter. The resulting array is
Th

assigned to the variable words. Finally, we print out a message that shows the
original string and the individual words in the string, by iterating over the words
array.

Output:

The original string is: The quick brown fox jumps over the lazy dog
The words in the string are:
The
TheTestingAcademy
https://thetestingacademy.com

quick
brown
fox
jumps
over
the
lazy
dog

y
Note that the split() method returns an array of substrings that are separated by

m
the delimiter. The delimiter itself is not included in the substrings. If you want to
include the delimiter in the substrings, you can use a capturing group in the
regular expression used as the delimiter. For example, str.split("( )") would split

de
the string at every space character and include the space character in the
resulting substrings.
ca
Q.143 How do you replace a substring within a String in Java?
In Java, you can replace a substring within a String using the replace() or
replaceAll() method. Here's an example:
gA

String str = "The quick brown fox jumps over the lazy dog";
String newStr = str.replace("quick", "slow");
System.out.println("The original string is: " + str);
tin

System.out.println("The new string is: " + newStr);

In this example, we first define a String str with the value "The quick brown fox
es

jumps over the lazy dog". We then use the replace() method to replace the
substring "quick" with "slow" and assign the result to the variable newStr.
Finally, we print out a message that shows the original string and the new string
eT

with the substring replaced.

Output:
Th

The original string is: The quick brown fox jumps over the lazy dog
The new string is: The slow brown fox jumps over the lazy dog

Note that the replace() method only replaces the first occurrence of the
substring. If you want to replace all occurrences, use the replaceAll() method
instead. For example:
String str = "The quick brown fox jumps over the lazy dog";
String newStr = str.replaceAll("o", "X");
TheTestingAcademy
https://thetestingacademy.com

System.out.println("The original string is: " + str);


System.out.println("The new string is: " + newStr);
Output:
The original string is: The quick brown fox jumps over the lazy dog
The new string is: The quick brXwn fXx jumps Xver the lazy dXg

In this example, we use the replaceAll() method to replace all occurrences of the
letter "o" with the letter "X".

y
m
Q.144 How do you check if a String contains a substring in Java?
In Java, you can check if a String contains a substring using the contains()

de
method. Here's an example:
String str = "The quick brown fox jumps over the lazy dog";
if (str.contains("fox")) {
ca
System.out.println("The string contains the substring 'fox'");
} else {
System.out.println("The string does not contain the substring 'fox'");
gA

In this example, we define a String str with the value "The quick brown fox jumps
over the lazy dog". We then use the contains() method to check if the string
tin

contains the substring "fox". If it does, we print a message saying that the string
contains the substring. Otherwise, we print a message saying that the string
does not contain the substring.
es

Output:
eT

The string contains the substring 'fox'

Note that the contains() method is case-sensitive. If you want to perform a


Th

case-insensitive search, you can convert both the string and the substring to
either uppercase or lowercase before calling the contains() method. For
example:
String str = "The quick brown fox jumps over the lazy dog";
if (str.toLowerCase().contains("FOX".toLowerCase())) {
System.out.println("The string contains the substring 'fox'");
} else {
System.out.println("The string does not contain the substring 'fox'");
TheTestingAcademy
https://thetestingacademy.com

}
Output:
The string contains the substring 'fox'

In this example, we convert both the string and the substring to lowercase using
the toLowerCase() method before calling the contains() method, so that the
search is case-insensitive.

y
m
Q.145 How do you reverse a String in Java?
In Java, you can reverse a String by converting it to a StringBuilder or

de
StringBuffer object and then using the reverse() method of that object. Here's an
example:
String str = "Hello, world!";
ca
StringBuilder sb = new StringBuilder(str);
String reversedStr = sb.reverse().toString();
System.out.println("The original string is: " + str);
gA

System.out.println("The reversed string is: " + reversedStr);


tin

In this example, we first define a String str with the value "Hello, world!". We
then create a StringBuilder object sb with the same value as str and use the
reverse() method of sb to reverse the string. Finally, we convert the
es

StringBuilder object back to a String using the toString() method and assign the
result to the variable reversedStr. We print out a message that shows the
original string and the reversed string.
eT

Output:
Th

The original string is: Hello, world!


The reversed string is: !dlrow ,olleH

Note that if you want to reverse a String in place (i.e., without creating a new
String), you can use a char array to store the characters of the String and then
reverse the array. Here's an example:

String str = "Hello, world!";


char[] charArray = str.toCharArray();
TheTestingAcademy
https://thetestingacademy.com

int i = 0, j = charArray.length - 1;
while (i < j) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
i++;
j--;
}
String reversedStr = new String(charArray);

y
System.out.println("The original string is: " + str);

m
System.out.println("The reversed string is: " + reversedStr);
Output
The original string is: Hello, world!

de
The reversed string is: !dlrow ,olleH

In this example, we first convert the String str to a char array using the
ca
toCharArray() method. We then use two pointers i and j to traverse the array
from both ends and swap the elements until we reach the middle of the array.
Finally, we convert the char array back to a String using the String(char[])
gA

constructor and assign the result to the variable reversedStr. We print out a
message that shows the original string and the reversed string.
tin

Q.146 How do you convert a String to a character array in Java?


In Java, you can convert a String to a character array using the toCharArray()
method. Here's an example:
es

String str = "Hello, world!";


char[] charArray = str.toCharArray();
System.out.println("The original string is: " + str);
eT

System.out.println("The character array is: " + Arrays.toString(charArray));

In this example, we first define a String str with the value "Hello, world!". We
Th

then use the toCharArray() method to convert the String to a char array and
assign the result to the variable charArray. Finally, we print out a message that
shows the original string and the character array using the Arrays.toString()
method to convert the array to a string.

Output:

The original string is: Hello, world!


The character array is: [H, e, l, l, o, ,, , w, o, r, l, d, !]
TheTestingAcademy
https://thetestingacademy.com

Note that the toCharArray() method creates a new char array containing a copy
of the characters in the String, so any modifications made to the array do not
affect the original String.

y
Q.147 What is the String pool in Java?

m
In Java, the String pool is a special area of memory that contains a collection of
unique String literals. When a String literal is created in Java, the JVM first

de
checks if the String already exists in the pool. If it does, then a reference to the
existing String object is returned. If not, then a new String object is created and
added to the pool for future use.
ca
Here's an example to illustrate how the String pool works:
gA

String str1 = "Hello"; // creates a new String object in the pool


String str2 = "Hello"; // returns a reference to the existing String object in the
pool
String str3 = new String("Hello"); // creates a new String object outside of the
tin

pool

System.out.println(str1 == str2); // true, because they are the same object in the
es

pool
System.out.println(str1 == str3); // false, because they are different objects in
eT

different memory locations

In this example, we create three String objects: str1 and str2 are created using
Th

String literals, while str3 is created using the new operator. When str1 is
created, a new String object with the value "Hello" is created in the String pool.
When str2 is created, the JVM checks the String pool for an existing String with
the same value, finds the one created by str1, and returns a reference to it.
Finally, when str3 is created, a new String object with the value "Hello" is
created outside of the pool, because it was explicitly created using the new
operator.
TheTestingAcademy
https://thetestingacademy.com

Note that in the example, the == operator is used to compare the objects for
reference equality, i.e., whether they refer to the same memory location. This is
different from using the equals() method, which compares the contents of the
objects for value equality.

Q.148 Can you explain the difference between the String,


StringBuffer, and StringBuilder classes?
1.String Class:

y
● String class represents an immutable sequence of characters.
● Once a String object is created, it cannot be modified.

m
● Whenever you try to modify the value of a String object, a new String
object is created.

de
● String is thread-safe, i.e., it can be shared between multiple threads
without causing any issues.
Example:
ca
String str = "Hello";
str = str + " World"; // creates a new String object
System.out.println(str); // prints "Hello World"
gA

2.StringBuffer Class:
● StringBuffer class represents a mutable sequence of characters.
● You can modify the value of a StringBuffer object without creating a new
tin

object.
● StringBuffer is thread-safe, i.e., it can be shared between multiple threads
without causing any issues.
es

Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // modifies the existing StringBuffer object
eT

System.out.println(sb.toString()); // prints "Hello World"

3.StringBuilder Class:
Th

● StringBuilder class is similar to StringBuffer, but it is not thread-safe.


● StringBuilder is preferred over StringBuffer when you do not need thread
safety because it is faster.
● You can modify the value of a StringBuilder object without creating a new
object.
Example:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // modifies the existing StringBuilder object
TheTestingAcademy
https://thetestingacademy.com

System.out.println(sb.toString()); // prints "Hello World"

In summary, String is immutable and cannot be modified, while StringBuffer and


StringBuilder are mutable and can be modified. StringBuffer is thread-safe,
while StringBuilder is not. If you need to modify a String object frequently, then
you should use StringBuffer or StringBuilder depending on whether you need
thread safety or not. If you do not need to modify a String object, then you
should use the String class.

y
Q.149 What is a keyword in Java?

m
A keyword is a reserved word in Java that has a predefined meaning and cannot
be used as an identifier or variable name.

de
Q.150 How many keywords are there in Java?
There are 50 keywords in Java, including 48 keywords that are currently in use,
ca
and two that are not used (goto and const).

Q.151 What is the difference between a keyword and an


gA

identifier in Java?
A keyword is a reserved word in Java that has a predefined meaning and cannot
be used as an identifier or variable name. An identifier is a name given to a
tin

variable, method, or class by the programmer.

Q.152 What is a Final Variable?


es

Final variable is a variable constant that cannot be changed after initialization.

Q.153 What is a final method ?


eT

Its a method which cannot be overridden. Compiler throws an error if we try to


override a method which has been declared final in the parent class.
Th

Q.154 What is a Final Class ?


A Class that cannot be sub classed.

Q.155 What are the common uses of "this" keyword in java ?


"this" keyword is a reference to the current object and can be used for following
-

1. Passing itself to another method.


2. Referring to the instance variable when local variable has the same name.
TheTestingAcademy
https://thetestingacademy.com

3. Calling another constructor in constructor chaining.

Q.156 What are transient variables in java?


Transient variables are variable that cannot be serialized.

Q.157 Explain static blocks in Java ?


A static initialization block is a normal block of code enclosed in braces, { }, and
preceded by the static keyword. Here is an example:

y
static {

m
// whatever code is needed for initialization goes here
}

de
A class can have any number of static initialization blocks, and they can appear
anywhere in the class body. The runtime system guarantees that static
initialization blocks are called in the order that they appear in the source code.
ca
Q.158 What is Volatile keyword used for ?
Volatile is a declaration that a variable can be accessed by multiple threads and
gA

hence shouldn't be cached.

Q.159 Does Declaring an object "final" makes it immutable ?


tin

Only declaring primitive types as final makes them immutable. Making objects
final means that the object handler cannot be used to target some other object
but the object is still mutable.
es

Q.160 What is "super" used for ?


Used to access members of the base class.
eT

Q.161 What is "this" keyword used for ?


Used to represent an instance of the class in which it appears.
Th

Q.162 What is "Import" used for ?


Enables the programmer to abbreviate the names of classes defined in a
package.

Q.163 What is a Static import ?


By static import , we can access the static members of a class directly without
prefixing it with the class name.
TheTestingAcademy
https://thetestingacademy.com

Q.164 Can we use both "this" and "super" in a constructor ?


No, because both this and super should be the first statement.

Q.165 Is it necessary that each try block be followed by a catch


block ?
It should be followed by either catch or finally block.

y
Q.166 What is the use of synchronized keyword?

m
This keyword is used to prevent concurrency. Synchronized keyword can be
applied to static/non-static methods or a block of code. Only one thread at a

de
time can access synchronized methods and if there are multiple threads trying
to access the same method then other threads have to wait for the execution of
a method by one thread. Synchronized keyword provides a lock on the object
ca
and thus prevents race conditions.

Q.167 Why static methods cannot access non static variables or


gA

methods?
A static method cannot access non static variables or methods because static
methods can be accessed without instantiating the class, so if the class is not
instantiated the variables are not intialized and thus cannot be accessed from a
tin

static method.

Q.168 What is throw keyword?


es

Throw keyword is used to throw the exception manually. It is mainly used when
the program fails to satisfy the given condition and it wants to warn the
application.The exception thrown should be subclass of Throwable.
eT

Q.169 What is an identifier in Java?


Th

An identifier is a name given to a variable, method, or class in Java. Identifiers


are used to uniquely identify and access programming elements in a Java
program.

Q.170 What are the rules for naming identifiers in Java?


Identifiers in Java must start with a letter, underscore, or dollar sign, and can be
followed by any combination of letters, digits, underscores, or dollar signs.
Identifiers cannot be a Java keyword, and they are case-sensitive.
TheTestingAcademy
https://thetestingacademy.com

Q.171 What is the difference between a variable name and a


variable identifier in Java?
In Java, a variable name refers to the name given to a variable by the
programmer, while a variable identifier refers to the unique identifier assigned
to the variable by the Java compiler.

Q.172 What is the purpose of camel case notation in Java

y
identifiers?
Camel case notation is a naming convention used in Java to make identifiers

m
more readable. Camel case notation involves starting the first word of an
identifier with a lowercase letter, and capitalizing the first letter of each

de
subsequent word.

Q.173 What is the naming convention for Java class identifiers?


ca
In Java, class identifiers should begin with an uppercase letter and use camel
case notation. For example, the class identifier for a class named "Person" would
be written as "Person".
gA

Q.174 What is the naming convention for Java method


identifiers?
tin

In Java, method identifiers should begin with a lowercase letter and use camel
case notation. For example, the method identifier for a method named
"calculateSum" would be written as "calculateSum".
es

Q.175 What is the naming convention for Java constant


identifiers?
eT

In Java, constant identifiers should be written in all uppercase letters, with


words separated by underscores. For example, a constant representing the
speed of light might be written as "SPEED_OF_LIGHT".
Th

Q.176 What is the naming convention for Java package


identifiers?
In Java, package identifiers should be written in all lowercase letters, with words
separated by dots. For example, a package for a set of utility classes might be
named "com.example.utils".
TheTestingAcademy
https://thetestingacademy.com

Q.177 What is the naming convention for Java interface


identifiers?
In Java, interface identifiers should begin with an uppercase "I" and use camel
case notation. For example, an interface for a calculator might be named
"ICalculator".

y
Q.178 What are literals in Java?

m
In Java, a literal refers to a fixed value that is directly used in the code without
any computation or evaluation. Literals can be of various types such as integer,

de
floating-point, character, string, boolean, and null. Here are some examples of
each type of literal in Java:

1. Integer Literal: An integer literal is a whole number that can be written in


ca
decimal, binary, octal, or hexadecimal notation. For example:
● Decimal: 10
● Binary: 0b1010
gA

● Octal: 012
● Hexadecimal: 0xA
tin

2. Floating-point Literal: A floating-point literal is a real number that can


have a fractional part. It can be written in either standard or scientific
notation. For example:
es

● Standard Notation: 3.14


● Scientific Notation: 1.23e-4
eT

3. Character Literal: A character literal represents a single character and is


written in single quotes. For example:
● 'a'
Th

● '7'
● '\n' (represents a new line character)

4. String Literal: A string literal is a sequence of characters enclosed in


double quotes. For example:
● "Hello World"
● "123"
● "Java is awesome!"
TheTestingAcademy
https://thetestingacademy.com

5. Boolean Literal: A boolean literal represents either true or false. For


example:
● true
● false

6. Null Literal: A null literal represents a reference that does not refer to any
object. It is written as the keyword "null". For example:
● null
Q.179 What are operators in Java?

y
Operators are special symbols in Java that perform specific operations on one or

m
more operands. For example, the addition operator "+" performs addition on
two operands.

de
Q.180 What are the different types of operators in Java?
Java supports several types of operators, including arithmetic, assignment,
ca
bitwise, comparison, logical, and conditional operators.

Q.181 What is an arithmetic operator in Java?


gA

Arithmetic operators perform basic arithmetic operations such as addition,


subtraction, multiplication, and division. They include + (addition), -
(subtraction), * (multiplication), / (division), and % (modulus).
tin

Q.182 What is an assignment operator in Java?


An assignment operator is used to assign a value to a variable. The most
es

common assignment operator is =, which assigns the value on the right-hand


side to the variable on the left-hand side.
eT

Q.183 What is a bitwise operator in Java?


Bitwise operators perform operations on individual bits of a number. They
include &, |, ^, ~, <<, and >>.
Th

Q.184 What is a comparison operator in Java?


A comparison operator is used to compare two values and returns a boolean
value (true or false) based on the result of the comparison. Comparison
operators include == (equal to), != (not equal to), > (greater than), < (less than),
>= (greater than or equal to), and <= (less than or equal to).

Q.185 What is a logical operator in Java?


TheTestingAcademy
https://thetestingacademy.com

Logical operators perform logical operations on boolean values. They include


&& (logical AND), || (logical OR), and ! (logical NOT).

Q.186 What is a conditional operator in Java?


The conditional operator (also known as the ternary operator) is a shorthand
way of writing an if-else statement. It takes three operands and returns one
value based on the value of a boolean expression. It is written as a ? b : c, where a
is the boolean expression, b is the value to be returned if the expression is true,
and c is the value to be returned if the expression is false.

y
Q.187 What is object-oriented programming (OOP)?

m
Object-oriented programming (OOP) is a programming paradigm based on the
concept of objects, which can contain data and code. It is a way of organizing

de
software design and development around the idea of objects, which can
represent real-world objects or concepts, such as people, animals, or events.
OOP allows for the creation of modular, reusable, and maintainable code, by
ca
breaking down complex problems into smaller, more manageable components. It
is built on four main principles: encapsulation, inheritance, polymorphism, and
abstraction.
gA

In OOP, objects have properties, which are represented by attributes or data


members, and behaviors, which are represented by methods or member
functions. Objects can interact with each other through their methods, and can
be used to model complex systems, such as user interfaces, databases, and
tin

simulations.

Q.188 What are the four main principles of OOP?


es

The four main principles of object-oriented programming (OOP) are:


1. Encapsulation: Encapsulation is the process of hiding an object's data and
methods from outside access and ensuring that they can only be accessed
eT

through a well-defined interface. This protects the object's data from


unauthorized access and modification.
2. Inheritance: Inheritance is the ability to create new classes based on
Th

existing ones. The new class inherits the properties and behaviors of the
existing class, and can also add its own unique properties and behaviors.
3. Polymorphism: Polymorphism means the ability of objects to take on
different forms, depending on the context in which they are used. In OOP,
polymorphism is achieved through method overloading and method
overriding.
4. Abstraction: Abstraction is the process of simplifying complex systems by
breaking them down into smaller, more manageable components.
TheTestingAcademy
https://thetestingacademy.com

Abstraction allows for the creation of abstract classes and interfaces,


which define a set of methods that a class must implement without
specifying how they are implemented. This allows for greater flexibility
and reusability in the design of complex software systems.

Q.189 What is inheritance and how is it used in Java? with

y
example

m
Inheritance is a fundamental concept in object-oriented programming that
allows a new class to be based on an existing class, inheriting its properties and

de
behaviors. The existing class is called the superclass, and the new class is called
the subclass. The subclass can add or modify properties and behaviors of the
superclass, or it can inherit them as is.
ca
In Java, inheritance is achieved through the use of the "extends" keyword. Here
is an example of how inheritance can be used in Java:
gA

class Vehicle {
String brand;
int year;
tin

void start() {
System.out.println("Starting the vehicle...");
}
es

}
eT

class Car extends Vehicle {


int doors;

void honk() {
Th

System.out.println("Honk honk!");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Toyota";
TheTestingAcademy
https://thetestingacademy.com

myCar.year = 2022;
myCar.doors = 4;

System.out.println("My car is a " + myCar.brand + " with " + myCar.doors + "


doors.");
myCar.start();
myCar.honk();
}}
In this example, the "Vehicle" class is the superclass, and the "Car" class is the

y
subclass. The Car class extends the Vehicle class using the "extends" keyword.

m
This means that the Car class inherits the brand and year properties, as well as
the start() method from the Vehicle class. The Car class also adds its own unique
property, doors, and method, honk().

de
In the main method, a Car object is created and its properties are set. The start()
and honk() methods can be called on the Car object, which will use the inherited
start() method from the Vehicle class and the unique honk() method from the
ca
Car class.

Q.190 What is polymorphism in Java? with example


gA

Polymorphism is the ability of objects to take on different forms, depending on


the context in which they are used. In Java, polymorphism can be achieved
through two mechanisms: method overloading and method overriding.
tin

Method Overloading:
Method overloading is a way to define multiple methods with the same name in
the same class, but with different parameter lists. The Java compiler uses the
es

method signature, which consists of the method name and parameter types, to
determine which method to call at runtime.
Here's an example of method overloading in Java:
eT

public class Calculator {


public int add(int num1, int num2) {
Th

return num1 + num2;


}

public int add(int num1, int num2, int num3) {


return num1 + num2 + num3;
}
}
TheTestingAcademy
https://thetestingacademy.com

public class Main {


public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(calculator.add(2, 3)); // Output: 5
System.out.println(calculator.add(2, 3, 4)); // Output: 9
}
}

In this example, the Calculator class defines two methods with the same name

y
"add", but with different parameter lists. When the add() method is called with

m
two arguments, the first add() method with two integer parameters is executed,
and when the add() method is called with three arguments, the second add()
method with three integer parameters is executed.

de
Method Overriding:
Method overriding is a way to define a method in a subclass that has the same
name, return type, and parameter list as a method in its superclass. When a
ca
method in the subclass is called, the method in the subclass overrides the
method in the superclass.
Here's an example of method overriding in Java:
gA

class Animal {
public void makeSound() {
tin

System.out.println("Animal is making a sound");


}
}
es

class Dog extends Animal {


public void makeSound() {
eT

System.out.println("Dog is barking");
}
}
Th

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();

myAnimal.makeSound(); // Output: Animal is making a sound


myDog.makeSound(); // Output: Dog is barking
}
TheTestingAcademy
https://thetestingacademy.com

In this example, the Animal class has a makeSound() method, and the Dog class
overrides the makeSound() method with its own implementation. When the
makeSound() method is called on the myAnimal object, the method in the Animal
class is executed, and when the makeSound() method is called on the myDog
object, the method in the Dog class is executed. This demonstrates
polymorphism in Java, where the same method name is used, but the method
behavior is different depending on the context in which it is used.

y
m
Q.191 What is a constructor in Java?
In Java, a constructor is a special method that is called when an object of a class

de
is created. It is used to initialize the instance variables of the class and perform
any other necessary initialization tasks.
Here is an example of a constructor in Java:
public class Student {
ca
private String name;
private int age;
gA

public Student(String name, int age) {


this.name = name;
this.age = age;
tin

// other methods and variables


es

Q.192 What is an exception in Java?


eT

An exception in Java is an event that occurs during the execution of a program


that disrupts the normal flow of the program's instructions.
Th

Q.193 What are the different types of exceptions in Java?


There are two types of exceptions in Java: checked exceptions and unchecked
exceptions.

Q.194 What is the difference between a checked and an


unchecked exception?
TheTestingAcademy
https://thetestingacademy.com

Checked exceptions are checked by the compiler at compile-time and must be


handled or declared in the method signature, whereas unchecked exceptions
are not checked by the compiler and do not need to be handled or declared.

Q.195 What is the difference between the "throws" and "throw"

y
keywords in Java?

m
The "throws" keyword is used to declare the exceptions that a method may
throw, whereas the "throw" keyword is used to explicitly throw an exception

de
from within a method.

Q.196 What is the purpose of the try-catch-finally block in Java?


ca
The try-catch-finally block is used to handle exceptions that may occur during
the execution of a program. The code that may throw an exception is enclosed
within the try block, and the code that handles the exception is enclosed within
gA

the catch block. The finally block is used to execute code that must be run
regardless of whether an exception was thrown or not.

Q.197 What is the purpose of the "finally" block in Java?


tin

The finally block in Java is used to execute code that must be run regardless of
whether an exception was thrown or not. The code in the finally block is
executed even if an exception is thrown or caught.
es

Q.198 What is the difference between the "printStackTrace()"


eT

and "getMessage()" methods of the Throwable class in Java?


The "printStackTrace()" method of the Throwable class is used to print the stack
trace of an exception, whereas the "getMessage()" method is used to get the
Th

error message associated with the exception.

Q.199 What is the purpose of the "throws Exception" clause in a


method signature?
The "throws Exception" clause in a method signature is used to indicate that the
method may throw an exception and that the caller of the method should handle
the exception or declare it using the "throws" keyword.
TheTestingAcademy
https://thetestingacademy.com

Q.200 What is Collection Framework in Java?


Collection Framework in Java is a unified architecture that provides a set of
interfaces, classes, and algorithms to represent and manipulate collections of
objects.

Q.201 What are the main interfaces in the Collection


Framework?
The main interfaces in the Collection Framework are: List, Set, Queue, and Map.

y
m
Q.202 What is the difference between a List and a Set?
A List is an ordered collection of elements that allows duplicates, whereas a Set

de
is an unordered collection of elements that does not allow duplicates.

Q.203 What is an Iterator and how is it used in Collection


ca
Framework?
An Iterator is an interface in the Collection Framework that provides a way to
iterate over a collection of objects. It allows you to access the elements in a
gA

collection one by one and perform operations on them.


Q.204 What is the difference between an ArrayList and a
LinkedList?
tin

An ArrayList is a resizable array implementation of the List interface, whereas a


LinkedList is a doubly-linked list implementation of the List interface. ArrayList
is generally faster for accessing elements, while LinkedList is generally faster for
es

adding or removing elements.


eT

Q.205 What is the purpose of the Map interface in Collection


Framework?
The Map interface in Collection Framework is used to store key-value pairs. It
Th

provides methods to add, remove, and retrieve elements based on their keys.

Q.206 What is the difference between HashMap and TreeMap?


HashMap is an implementation of the Map interface that provides
constant-time performance for most operations, while TreeMap is an
implementation of the SortedMap interface that provides logarithmic-time
performance for most operations and orders the keys in natural order or based
on a Comparator.
TheTestingAcademy
https://thetestingacademy.com

Q.207 What is the purpose of the Collections class in Collection


Framework?
The Collections class in Collection Framework provides a set of utility methods
for working with collections, such as sorting, searching, shuffling, and creating
synchronized collections.

y
Q.208 What is the difference between fail-fast and fail-safe

m
iterators in Collection Framework?
Fail-fast iterators throw ConcurrentModificationException if a collection is

de
modified while iterating over it, whereas fail-safe iterators do not throw any
exception and work on a copy of the collection.

Q.209 What is the difference between a HashSet and a TreeSet?


ca
HashSet is an implementation of the Set interface that uses a hash table to store
elements and does not maintain any order, whereas TreeSet is an
gA

implementation of the SortedSet interface that uses a tree structure to store


elements and maintains elements in sorted order.

Q.210 What is a thread in Java?


tin

A thread is a lightweight process that enables concurrent execution within a


program.
es

Q.211 How do you create a thread in Java?


You can create a thread in Java by implementing the Runnable interface and
passing an instance of that class to the constructor of a new Thread object.
eT

Q.212 What is Multi-Threading in Java?


Multi-Threading in Java is a feature that allows a program to perform multiple
Th

tasks simultaneously by dividing the tasks into smaller sub-tasks that can be
executed independently.

Q.213 What is the difference between a process and a thread?


A process is a complete program execution unit, whereas a thread is a part of a
process that executes concurrently with other threads within the same process.
TheTestingAcademy
https://thetestingacademy.com

Q.214 What is the difference between a user thread and a


daemon thread?
A user thread is a thread that is created and controlled by the user, whereas a
daemon thread is a thread that runs in the background and does not prevent the
program from exiting.

Q.215 What is the purpose of the synchronized keyword in Java?

y
The synchronized keyword is used to ensure that only one thread can access a
block of code or a method at a time, preventing concurrent access by multiple

m
threads.

de
Q.216 What is a race condition in multi-threading?
A race condition occurs when two or more threads access a shared resource in
an unpredictable order, leading to unexpected results.
ca
Q.217 What is a deadlock in multi-threading?
A deadlock occurs when two or more threads are blocked and waiting for each
gA

other to release resources that they need to continue executing.

Q.218 What is the purpose of the wait() and notify() methods in


Java?
tin

The wait() method causes a thread to wait until it is notified by another thread,
while the notify() method wakes up a single waiting thread and allows it to
es

continue executing.

Q.219 What is the Thread Pool in Java?


eT

A Thread Pool is a group of pre-initialized threads that are available to perform


a set of tasks. It improves performance by reducing the overhead of creating and
destroying threads.
Th

Q.220 What is the ThreadLocal class in Java?


The ThreadLocal class is used to create variables that are local to a thread and
not shared among multiple threads. Each thread that accesses the variable will
have its own private copy of the variable.

You might also like