Java Notes - TheTestingAcademy
Java Notes - TheTestingAcademy
https://thetestingacademy.com
Java
Interview Question and Answer
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
includes everything required to develop, debug, and run Java applications. JDK
includes a Java compiler, the Java Virtual Machine (JVM), and other
development tools.
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
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
y
other libraries required to run Java-based applications, while JDK includes the
m
Java compiler and other development tools.
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
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
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
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
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.
double d = 1.23456789d;
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
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.
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
9876543210
Long c = null; // declaring a Long object that is set to null
In Java, "char" and "String" are used to represent text data, but they have some
important differences:
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.
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
1.Local Variables
2.Instance Variables
eT
3.Static Variables
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
y
m
public Person(String name) {
this.name = name;
de
}
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
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
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
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
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
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.
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.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.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
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
Here's an example:
tin
int a = 5;
int b = a++; // the value of b is 5, and a is incremented to 6
es
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.
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
int i = 0;
while (i < 10) {
System.out.println(i++);
}
Th
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
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.
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.
code if the condition is true, and another block of code if the condition is false.
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
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.
if (number > 0) {
System.out.println("The number is positive.");
es
} 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."
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
(not).
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.
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
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
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
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
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.
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
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
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.
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
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.
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
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
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
switch (integerNumber) {
case 3:
TheTestingAcademy
https://thetestingacademy.com
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
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
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.
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 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";
}
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.
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
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
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
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!";
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
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.
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};
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.
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);
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
import java.util.LinkedList;
es
}
}
}
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
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.
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
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.
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
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
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
}
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
***
****
*****
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:
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
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
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
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
Loop ended!
Note that the break statement can also be used in other types of loops (such as
eT
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
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
}
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
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
int i = 0;
while (i < numbers.length) {
System.out.println(numbers[i]);
es
i++;
}
eT
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:
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.
System.out.println(i);
i--;
}
This will output the numbers from 10 to 1
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
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
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
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
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
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().
de
in Java?
int num = 17;
ca
boolean isPrime = true;
int i = 2;
gA
}
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
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
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
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.
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
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.
de
loop?
int i = 0;
ca
do {
i++;
if (i % 2 == 0) {
gA
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.
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
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.
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
}
}
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.
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
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
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;
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
import java.util.Scanner;
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
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.
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
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
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
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
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
y
Type safety Type-safe Not type-safe
m
de
Accessing elements
ca Fast Slower than array
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
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
array. If you need to preserve the original array, you should make a copy of it
before sorting.
eT
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];
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
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
{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
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
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:
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
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.
}
}
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.
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
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
y
Overall, Strings are a fundamental part of the Java language and are widely used
m
in Java programs for storing and manipulating text.
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
the existing StringBuilder object in place. This can be more efficient than using
Strings for operations that involve a lot of modifications.
eT
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
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
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.
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
if (str1.equals(str2)) {
System.out.println("The two strings are equal");
} else {
eT
they are equal, the program outputs "The two strings are equal"; otherwise, it
outputs "The two strings are not equal".
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
method:
1.Using the + operator:
String str1 = "Hello";
eT
In this example, we use the + operator to concatenate the strings str1, ", ", str2,
and "!" into a new String object str3.
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.
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
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
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
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
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:
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
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
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:
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
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(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
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
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
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
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
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
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:
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
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:
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
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
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.
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
3.StringBuilder Class:
Th
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).
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
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
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
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.
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.
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
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.
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
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:
● Octal: 012
● Hexadecimal: 0xA
tin
● '7'
● '\n' (represents a new line character)
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.
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
simulations.
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
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
void honk() {
Th
System.out.println("Honk honk!");
}
}
myCar.year = 2022;
myCar.doors = 4;
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.
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
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("Dog is barking");
}
}
Th
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
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.
the catch block. The finally block is used to execute code that must be run
regardless of whether an exception was thrown or not.
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
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.
provides methods to add, remove, and retrieve elements based on their keys.
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.
tasks simultaneously by dividing the tasks into smaller sub-tasks that can be
executed independently.
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
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.