What is Java?
Java is a programming language and a platform. Java is a high level, robust,
object-oriented and secure programming language.
Java Platforms / Editions
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as
[Link], [Link], [Link], [Link], [Link], [Link] etc. It includes core topics
like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream,
Networking, AWT, Swing, Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and enterprise
applications. It is built on top of the Java SE platform. It includes topics like
Servlet, JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface
API.
Difference between JDK, JRE, and JVM
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
because it doesn't physically exist. It is a specification that provides a runtime
environment in which Java bytecode can be executed. It can also run those
programs which are written in other languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK
are platform dependent because the configuration of each OS is different from
each other. However, Java is platform independent. There are three notions of
the JVM: specification, implementation, and instance.
The JVM performs the following main tasks:
○ Loads code
○ Verifies code
○ Executes code
○ Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE.
The Java Runtime Environment is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment. It is
the implementation of JVM. It physically exists. It contains a set of libraries +
other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides
Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released
by Oracle Corporation:
○ Standard Edition Java Platform
○ Enterprise Edition Java Platform
○ Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java
Application.
Java Variables
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in
java: local, instance and static.
There are two types of data types in Java: primitive and non-primitive.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it
is a name of the memory location. It is a combination of "vary + able" which
means its value can be changed.
int data=50;//Here data is variable
[Link](data);
Types of Variables
There are three types of variables in Java:
○ local variable
○ instance variable
○ static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the class
aren't even aware that the variable exists.
A local variable cannot be defined with "static" keyword.
Example of Local Variable
File Name: [Link]
public class LocalVariableExample {
public static void main(String[] args)
{
//defining a Local Variable
int num = 10;
[Link](" Variable: " + num);
}
}
Output: 10
2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not
shared among instances.
Example of Instance Variable
File Name: [Link]
import [Link].*;
public class InstanceVariableDemo {
//Defining Instance Variables
public String name;
public int age=19;
//Creadting a default Constructor initializing Instance Variable
public InstanceVariableDemo()
{
[Link] = "Deepak";
}
public static void main(String[] args)
{
// Object Creation
InstanceVariableDemo obj = new InstanceVariableDemo();
[Link]("Student Name is: " + [Link]);
[Link]("Age: "+ [Link]);
}
}
Output:
Student Name is: Deepak
Age: 19
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local.
You can create a single copy of the static variable and share it among all the
instances of the class. Memory allocation for static variables happens only once
when the class is loaded in the memory.
Example Static variable
class Student{
//static variable
static int age;
}
public class StaticVariableExample{
public static void main(String args[]){
//Two objects, s1 and s2, of the Student class are created.
Student s1 = new Student();
Student s2 = new Student();
//Both objects share the same static variable age.
[Link] = 24;
[Link] = 21;
[Link] = 23;
[Link]("S1\'s age is: " + [Link]);
[Link]("S2\'s age is: " + [Link]);
}
}
Initially:
○ [Link] = 24 modifies the shared age variable to 24.
○ [Link] = 21 then updates the shared age variable to 21.
Finally:
○ [Link] = 23 explicitly sets the shared age variable to 23.
At this point, the age value is 23, regardless of whether it is accessed through
s1, s2, or Student.
Output:
S1's age is: 23
S2's age is: 23
HW:
Java Variable Example: Add Two Numbers
Data Types in Java
Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes,
Interfaces, and Arrays.
Let's understand in detail about the two major data types of Java in the following
paragraphs.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java language.
Java is a statically-typed programming language. It means, all
variables must be declared before its use. That is why we need to
declare variable's type and name.
In Java, there are mainly eight primitive data types and let's understand about
them in detail in the following paragraphs.
Java Primitive data types:
1. boolean data type
2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type
Boolean Data Type
In Java, the boolean data type represents a single bit of information with two
possible states: true or false. It is used to store the result of logical expressions or
conditions. Unlike other primitive data types like int or double, boolean does not
have a specific size or range. It is typically implemented as a single bit, although
the exact implementation may vary across platforms.
Example:
Boolean a = false;
Boolean b = true;
One key feature of the boolean data type is its use in controlling program flow. It
is commonly employed in conditional statements such as if, while, and for loops
to determine the execution path based on the evaluation of a boolean
expression. For instance, an if statement executes a block of code if the boolean
expression evaluates to true, and skips it if the expression is false.
Byte Data Type
The byte data type in Java is a primitive data type that represents an 8-bit
signed two's complement integer. It has a range of values from -128 to 127. Its
default value is 0. The byte data type is commonly used when working with raw
binary data or when memory conservation is a concern, as it occupies less
memory than larger integer types like int or long.
Example:
byte a = 10, byte b = -20
One common use of the byte data type is in reading and writing binary data,
such as files or network streams. Since binary data is often represented using
bytes, the byte data type provides a convenient way to work with such data.
Additionally, the byte data type is sometimes used in performance-critical
applications where memory usage needs to be minimized.
Short Data Type
The short data type in Java is a primitive data type that represents a 16-bit
signed two's complement integer. It has a range of values from -32,768 to
32,767. Similar to the byte data type, short is used when memory conservation is
a concern, but more precision than byte is required. Its default value is 0.
Example:
short s = 10000, short r = -5000
In Java, short variables are declared using the short keyword. For example, short
myShort = 1000; declares a short variable named myShort and initializes it with
the value 1000. As with the byte data type, short variables must be explicitly cast
when used in expressions with larger integer types to avoid loss of precision.
Int Data Type
The int data type in Java is a primitive data type that represents a 32-bit signed
two's complement integer. It has a range of values from -2,147,483,648 to
2,147,483,647. The int data type is one of the most commonly used data types in
Java and is typically used to store whole numbers without decimal points. Its
default value is 0.
Example:
int a = 100000, int b = -200000
In Java, int variables are declared using the int keyword. For example, int myInt =
100; declares an int variable named myInt and initializes it with the value 100. int
variables can be used in mathematical expressions, assigned to other int
variables, and used in conditional statements.
Long Data Type
The long data type in Java is a primitive data type that represents a 64-bit signed
two's complement integer. It has a wider range of values than int, ranging from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Its default value is 0.0F.
The long data type is used when int is not large enough to hold the desired
value, or when a larger range of integer values is needed.
Example:
long a = 100000L, long b = -200000L
The long data type is commonly used in applications where large integer values
are required, such as in scientific computations, financial applications, and
systems programming. It provides greater precision and a larger range than int,
making it suitable for scenarios where int is insufficient.
Float Data Type
The float data type in Java is a primitive data type that represents single-
precision 32-bit IEEE 754 floating-point numbers. It can represent a wide range
of decimal values, but it is not suitable for precise values such as currency. The
float data type is useful for applications where a higher range of values is needed,
and precision is not critical.
Example:
float f1 = 234.5f
One of the key characteristics of the float data type is its ability to represent a
wide range of values, both positive and negative, including very small and very
large values. However, due to its limited precision (approximately 6-7 significant
decimal digits), it is not suitable for applications where exact decimal values are
required.
Double Data Type
The double data type in Java is a primitive data type that represents double-
precision 64-bit IEEE 754 floating-point numbers. Its default value is 0.0d. It
provides a wider range of values and greater precision compared to the float
data type, making it suitable for applications where accurate representation of
decimal values is required.
Example:
double d1 = 12.3
One of the key advantages of the double data type is its ability to represent a
wider range of values with greater precision compared to float. It can accurately
represent values with up to approximately 15-16 significant decimal digits,
making it suitable for applications that require high precision, such as financial
calculations, scientific computations, and graphics programming.
Char Data Type
The char data type in Java is a primitive data type that represents a single 16-bit
Unicode character. It can store any character from the Unicode character set,
that allows Java to support internationalization and representation of characters
from various languages and writing systems.
Example:
char letterA = 'A'
The char data type is commonly used to represent characters, such as letters,
digits, and symbols, in Java programs. It can also be used to perform arithmetic
operations, as the Unicode values of characters can be treated as integers. For
example, you can perform addition or subtraction operations on char variables to
manipulate their Unicode values.
Non-Primitive Data Types in Java
In Java, non-primitive data types, also known as reference data types, are used to
store complex objects rather than simple values. Unlike primitive data types that
store the actual values, reference data types store references or memory
addresses that point to the location of the object in memory. This distinction is
important because it affects how these data types are stored, passed, and
manipulated in Java programs.
Class
One common non-primitive data type in Java is the class. Classes are used to
create objects, which are instances of the class. A class defines the properties and
behaviors of objects, including variables (fields) and methods. For example, you
might create a Person class to represent a person, with variables for the person's
name, age, and address, and methods to set and get these values.
Interface
Interfaces are another important non-primitive data type in Java. An interface
defines a contract for what a class implementing the interface must provide,
without specifying how it should be implemented. Interfaces are used to achieve
abstraction and multiple inheritance in Java, allowing classes to be more flexible
and reusable.
Arrays
Arrays are a fundamental non-primitive data type in Java that allow you to store
multiple values of the same type in a single variable. Arrays have a fixed size,
which is specified when the array is created, and can be accessed using an index.
Arrays are commonly used to store lists of values or to represent matrices and
other multi-dimensional data structures.
Enum
Java also includes other non-primitive data types, such as enums and collections.
Enums are used to define a set of named constants, providing a way to represent
a fixed set of values. Collections are a framework of classes and interfaces that
provide dynamic data structures such as lists, sets, and maps, which can grow or
shrink in size as needed.
Overall, non-primitive data types in Java are essential for creating complex and
flexible programs. They allow you to create and manipulate objects, define
relationships between objects, and represent complex data structures. By
understanding how to use non-primitive data types effectively, you can write
more efficient and maintainable Java code.
Why char uses 2 byte in Java and what is \u0000 ?
It is because Java uses Unicode system not ASCII code system. The \u0000 is the
lowest range of Unicode system. To get detail explanation about Unicode visit
next page.
Operators in Java
There are many types of operators in Java which are given below:
○ Unary Operator,
○ Arithmetic Operator,
○ Shift Operator,
○ Relational Operator,
○ Bitwise Operator,
○ Logical Operator,
○ Ternary Operator and
○ Assignment Operator.
Java Keywords
Java keywords are also known as reserved words. Keywords are particular words
that act as a key to a code. These are predefined words by Java so they cannot be
used as a variable or object name or class name.
List of Java Keywords
A list of Java keywords or reserved words are given below:
1. abstract: Java abstract keyword is used to declare an abstract class. An
abstract class can provide the implementation of the interface. It can have
abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean
type. It can hold True and False values only.
3. break: Java break keyword is used to break the loop or switch statement. It
breaks the current flow of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit
data values.
5. case: Java case keyword is used with the switch statements to mark blocks
of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try
statements. It must be used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold
unsigned 16-bit Unicode characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues
the current flow of the program and skips the remaining code at the
specified condition.
10. default: Java default keyword is used to specify the default block of code in
a switch statement.
11. do: Java do keyword is used in the control statement to declare a loop. It
can iterate a part of the program several times.
12. double: Java double keyword is used to declare a variable that can hold 64-
bit floating-point number.
13. else: Java else keyword is used to indicate the alternative branches in an if
statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum
constructors are always private or default.
15. extends: Java extends keyword is used to indicate that a class is derived
from another class or interface.
16. final: Java final keyword is used to indicate that a variable holds a constant
value. It is used with a variable. It is used to restrict the user from updating
the value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch
structure. This block is always executed whether an exception is handled
or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit
floating-point number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If
the number of iteration is fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the
condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and
accessible to the current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is
an instance of the specified class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit
signed integer.
25. interface: Java interface keyword is used to declare an interface. It can
have only abstract methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit
integer.
27. native: Java native keyword is used to specify that a method is
implemented in native code using JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value.
30. package: Java package keyword is used to declare a Java package that
includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate
that a method or variable may be accessed only in the class in which it is
declared.
32. protected: Java protected keyword is an access modifier. It can be
accessible within the package and outside the package but through
inheritance only. It can't be applied with the class.
33. public: Java public keyword is an access modifier. It is used to indicate that
an item is accessible anywhere. It has the widest scope among all other
modifiers.
34. return: Java return keyword is used to return from a method when its
execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit
integer.
36. static: Java static keyword is used to indicate that a variable or method is a
class method. The static keyword in Java is mainly used for memory
management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to
ensure portability.
38. super: Java super keyword is a reference variable that is used to refer to
parent class objects. It can be used to invoke the immediate parent class
method.
39. switch: The Java switch keyword contains a switch statement that
executes code based on test value. The switch statement tests the equality
of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the
critical sections or methods in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method
or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception.
The throw keyword is mainly used to throw custom exceptions. It is
followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked
exceptions can be propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define
any data member as transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.
[Link]: Java void keyword is used to specify that a method does not have a
return value.
47. volatile: Java volatile keyword is used to indicate that a variable may
change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop
iterates a part of the program several times. If the number of iteration is
not fixed, it is recommended to use the while loop.
49.
Java Control Statements | Control Flow in
Java
Java compiler executes the code from top to bottom. The statements in the code
are executed according to the order in which they appear. However, Java
provides statements that can be used to control the flow of Java code. Such
statements are called control flow statements. It is one of the fundamental
features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
1. Decision Making statements
○ if statements - Yes or No
○ switch statement - Browser selection
2. Loop statements
○ do while loop
○ while loop
○ for loop
○ for-each loop
3. Jump statements
○ break statement
○ continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to
execute and when. Decision-making statements evaluate the Boolean
expression and control the program flow depending upon the result of the
condition provided. There are two types of decision-making statements in Java,
i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the
program is diverted depending upon the specific condition. The condition of the
If statement gives a Boolean value, either true or false. In Java, there are four
types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Let's understand the if-statements one by one.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It
evaluates a Boolean expression and enables the program to enter a block of
code if the expression evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the
java code.
public class Main {
int x = 10;
int y = 12;
public void checkSum() {
if (x + y > 30) {
[Link]("x + y is greater than 30");
}
else{
[Link]("x + y is less than 30");
}
}
public static void main(String[] args) {
Main student = new Main();
[Link]();
}
}
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another
block of code, i.e., else block. The else block is executed if the condition of the if-
block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.
[Link]
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
[Link]("x + y is less than 10");
} else {
[Link]("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if
statements. In other words, we can say that it is the chain of if-else statements
that create a decision tree where the program may enter in the block of code
where the condition is true. We can also define an else statement at the end of
the chain.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.
Why This Works:
● The public keyword is removed from the Student class. This avoids the
restriction that the file name must match the class name.
● Most online compilers use a default file name like [Link], and this
code will compile and run successfully in that setup.
[Link]
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
[Link]("city is meerut");
}else if (city == "Noida") {
[Link]("city is noida");
}else if(city == "Agra") {
[Link]("city is agra");
}else {
[Link](city);
}
}
}
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement
inside another if or else-if statement.
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
public class Main {
public static void main(String[] args) {
String address = "Delhi, India";
if ([Link]("India")) {
if ([Link]("Delhi")) {
[Link]("Your city is DELHI");
} else if ([Link]("Noida")) {
[Link]("Your city is Noida");
} else {
[Link]([Link](",")[0]);
}
} else {
[Link]("You are not living in India");
}
}
}
Question: Write a program to check if a number is positive.
Question: Write a program to check if a number is even or odd.
Question: Write a program to check the grade of a student based on marks:
● Marks >= 90: "A"
● Marks >= 75: "B"
● Marks >= 50: "C"
● Otherwise: "Fail"
Question: Write a program to check if a person is eligible to vote. Eligibility:
● Age >= 18
● Citizenship: "India"
Practice Questions
1. Simple if Statement: Check if a number is divisible by 5.
2. if-else Statement: Write a program to check if a person can drive based on
age (age >= 18).
3. if-else-if Ladder: Determine the category of a person based on age:
○ Age < 13: "Child"
○ Age >= 13 and < 20: "Teenager"
○ Age >= 20: "Adult"
4. Nested if Statement: Write a program to check if a student has passed a
subject. Conditions:
○ Marks >= 40
○ Attendances >= 75%
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch
statement contains multiple blocks of code called cases and a single case is
executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.
Points to be noted about switch statement:
○ The case variables can be int, short, byte, char, or enumeration. String
type is also supported since version 7 of Java
○ Cases cannot be duplicate
○ Default statement is executed when any of the case doesn't match the
value of expression. It is optional.
○ Break statement terminates the switch block when the condition is
satisfied.
It is optional, if not used, next case is executed.
○ While using switch statements, we must notice that the case
expression will be of the same type as the variable. However, it will also
be a constant value.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
[Link]
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
[Link]("number is 0");
break;
case 1:
[Link]("number is 1");
break;
default:
[Link](num);
}
}
}
Output:
if ([Link](BROWSER_CHROME)) {
[Link]().setup();
driver = new ChromeDriver();
} else if ([Link](BROWSER_HEADLESS)) {
[Link]().setup();
ChromeOptions options = new ChromeOptions();
// [Link]("--headless=new");
driver = new ChromeDriver(options);
} else if ([Link](BROWSER_FIREFOX)) {
[Link]().setup();
driver = new FirefoxDriver();
} else if ([Link](BROWSER_SAFARI)) {
driver = new SafariDriver();
} else if ([Link](BROWSER_EDGE)) {
[Link]().setup();
driver = new EdgeDriver();
}
else {
throw new IllegalStateException("INVALID BROWSER: " + browser);
}
switch (browser) {
case BROWSER_CHROME: {
[Link]().setup();
driver = new ChromeDriver();
break;
}
case BROWSER_HEADLESS: {
[Link]().setup();
ChromeOptions options = new ChromeOptions();
// [Link]("--headless=new");
driver = new ChromeDriver(options);
break;
}
case BROWSER_FIREFOX: {
[Link]().setup();
driver = new FirefoxDriver();
break;
}
case BROWSER_SAFARI: {
driver = new SafariDriver();
break;
}
case BROWSER_EDGE: {
[Link]().setup();
driver = new EdgeDriver();
break;
}
// case BROWSER_OPERA: {
// [Link]().setup();
// driver = new OperaDriver();
// break;
// }
default:
throw new IllegalStateException("INVALID BROWSER: " + browser);
}
Calculator ?
While using switch statements, we must notice that the case expression will be
of the same type as the variable. However, it will also be a constant value. The
switch permits only int, string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly
while some condition evaluates to true. However, loop statements are used to
execute the set of instructions in a repeated order. The execution of the set of
instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.
Java for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable,
check the condition, and increment/decrement in a single line of code. We
use the for loop only when we exactly know the number of times, we want to
execute the block of code.
for(initialization, condition, increment/decrement) {
//block of statements
}
Here’s how you can use a for loop to print numbers from 1 to 10 in Java:
java
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
[Link](i);
}
}
}
Explanation:
1. Initialization: int i = 1 initializes the loop variable i to 1.
2. Condition: i <= 10 checks whether the value of i is less than or equal
to 10. The loop runs as long as this condition is true.
3. Increment: i++ increments the value of i by 1 after each iteration.
4. Action: [Link](i) prints the current value of i in each
iteration.
When you run this code, it will print the numbers from 1 to 10, each on a new
line.
The flow chart for the for-loop is given below.
Consider the following example to understand the proper functioning of the for
loop in java.
[Link]
public class Calculattion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
[Link]("The sum of first 10 natural numbers is " + sum);
}
}
Output:
The sum of first 10 natural numbers is 55
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable. The
syntax to use the for-each loop in java is given below.
for(data_type var : array_name/collection_name){
//statements
}
Consider the following example to understand the functioning of the for-each
loop in Java.
[Link]
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
[Link]("Printing the content of the array names:\n");
for(String name:names) {
[Link](name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
Java while loop
The while loop is also used to iterate over the number of statements multiple
times. However, if we don't know the number of iterations in advance, it is
recommended to use a while loop. Unlike for loop, the initialization and
increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the
start of the loop. If the condition is true, then the loop body will be executed;
otherwise, the statements after the loop will be executed.
The syntax of the while loop is given below.
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
Consider the following example.
Here's how the for loop in your code can be converted to a while loop:
java
public class Main {
public static void main(String[] args) {
int i = 1; // Initialization
while (i <= 10) { // Condition
[Link](i); // action
i++; // Increment
Explanation:
1. Initialization: int i = 1; is done before the while loop.
2. Condition: while (i <= 10) checks if the value of i is less than or equal
to 10. The loop continues as long as this condition is true.
3. Action: [Link](i) prints the current value of i.
4. Increment: i++; increments the value of i by 1 in each iteration.
This will also print the numbers from 1 to 10, each on a new line, just like the for
loop.
Calculation .java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
while(i<=10) {
[Link](i);
i = i + 2;
}
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
The main purpose and difference between a for loop and a while loop in Java lies in
how they are typically used and the context in which they are preferred:
For Loop
The for loop is best suited for situations where the number of iterations is known
beforehand. It combines initialization, condition checking, and increment/decrement in
a single line, making it concise and ideal for counter-based loops.
Syntax:
java
for (initialization; condition; increment/decrement) {
// Loop body
}
Use Case:
● When the number of iterations is fixed.
● Iterating over arrays, lists, or performing tasks a known number of times.
Example:
java
for (int i = 1; i <= 5; i++) {
[Link](i); // Prints numbers 1 to 5
}
While Loop
The while loop is better for situations where the number of iterations is not known in
advance. It checks the condition before each iteration, and the loop continues as long
as the condition evaluates to true.
Syntax:
java
while (condition) {
// Loop body
}
Use Case:
● When the number of iterations is unknown.
● Used when you need to loop based on a dynamic condition, such as user input or
real-time checks.
Example:
java
int i = 1;
while (i <= 5) {
[Link](i); // Prints numbers 1 to 5
i++;
}
Key Differences
Feature For Loop While Loop
Best Use Fixed number of iterations. Unknown number of iterations.
Case
Structure Compact: Initialization, Less compact: Initialization and
condition, and update in one update must be outside the loop.
line.
Condition Checked before each iteration. Checked before each iteration.
Check
Common Counter-based loops, array Loops with dynamic conditions or
Usage traversal. user inputs.
General Rule
● Use a for loop when you know how many times the loop should run.
● Use a while loop when the loop needs to continue until a specific condition is
met, and the number of iterations is not predetermined.
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the
loop statements. When the number of iteration is not known and we have to
execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while
loop in Java.
[Link]
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
do {
[Link](i);
i = i + 2;
}while(i<=10);
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Comparison Table
Feature for Loop while Loop do-while Loop
Condition Before the loop Before the loop body. After the loop body.
Check body.
Execution Executes 0 or more Executes 0 or more Executes 1 or more
Guarantee times. times. times.
Use Case Fixed number of Unknown iterations, At least one iteration
iterations. condition-based. required.
Structure Compact (header Initialization and Initialization and
combines logic). increment external. increment external.
Examples Iterating over Waiting for a Validating user input
arrays, counters. condition to be met. or menus.
For Loop Questions
1. Basic Iteration:
Write a for loop to print numbers from 1 to 10.
2. Sum of Numbers:
Write a for loop to calculate the sum of the first 10
natural numbers.
3. Even Numbers:
Write a for loop to print all even numbers between 1 and
20.
4. Reverse Order:
Write a for loop to print numbers from 10 to 1 in
descending order.
5. Factorial:
Write a for loop to calculate the factorial of a given
number (e.g., 5! = 120).
6. Multiplication Table:
Write a for loop to print the multiplication table of a
given number.
7. Iterating Over an Array:
Use a for loop to iterate over an array of integers and
print each element.
While Loop Questions
1. Print 1 to 10:
Write a while loop to print numbers from 1 to 10.
2. Sum of Digits:
Write a while loop to calculate the sum of the digits of a
number (e.g., 123 → 6).
3. Number Guessing Game:
Use a while loop to implement a number guessing
game where the user guesses a random number until
they get it right.
4. Reverse a Number:
Write a while loop to reverse a number (e.g., 123 → 321).
5. Count Digits:
Write a while loop to count the number of digits in a
number.
6. Fibonacci Series:
Use a while loop to generate the first 10 terms of the
Fibonacci series.
7. Find Maximum:
Use a while loop to find the maximum value in a list of
integers entered by the user (terminate on a negative
number).
Do-While Loop Questions
1. At Least One Iteration:
Write a do-while loop to print numbers from 1 to 10.
2. Menu-Driven Program:
Create a program using a do-while loop where the user
can repeatedly choose operations (e.g., addition,
subtraction, exit).
3. Validate User Input:
Write a do-while loop to ask the user for a positive
number. Repeat until they enter a valid number.
4. Print a Message:
Write a do-while loop to print "Hello, World!" 5 times.
5. Sum of Numbers:
Write a do-while loop to calculate the sum of numbers
entered by the user. Stop when they enter 0.
6. Guess the Password:
Use a do-while loop to prompt the user to guess a
password until they enter the correct one.
7. Repeat Prompt:
Create a do-while loop that repeatedly asks if the user
wants to continue (yes/no) until they type "no".
Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to
the other part of the program. There are two types of jump statements in Java,
i.e., break and continue.
Java break statement
As the name suggests, the break statement is used to break the current flow of
the program and transfer the control to the next statement outside a loop or
switch statement. However, it breaks only the inner loop in the case of the
nested loop.
The break statement cannot be used independently in the Java program, i.e., it
can only be written inside the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with
the for loop.
[Link]
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
[Link](i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
[Link]
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
[Link](k);
if(k==5) {
break a;
}
}
}
}
}
}
Output:
0
1
2
3
4
5
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas,
it skips the specific part of the loop and jumps to the next iteration of the loop
immediately.
Consider the following example to understand the functioning of the continue
statement in Java.
public class ContinueExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
[Link](j);
}
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Exception handling : runtime and compile time -
Video link
is a mechanism in programming to handle runtime errors, ensuring the program continues
to execute without abrupt termination. In Selenium Java automation, exception handling is
crucial to manage unexpected errors during test execution, such as NoSuchElementException,
TimeoutException, etc.
How to use Exception Handling in Selenium with Java
Using Try-Catch Block
Enclose the Selenium code in a try block and handle exceptions in the catch block.
java
try {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
WebElement element = [Link]([Link]("nonExistingId"));
[Link]();
} catch (NoSuchElementException e) {
[Link]("Element not found: " + [Link]());
} finally {
[Link](); // Ensures the driver is closed
}
Using Multiple Catch Blocks
Handle specific exceptions separately for better clarity and debugging.
java
try {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
WebElement element = [Link]([Link]("nonExistingId"));
[Link]();
} catch (NoSuchElementException e) {
[Link]("No such element found.");
} catch (TimeoutException e) {
[Link]("Operation timed out.");
} catch (Exception e) {
[Link]("An unexpected error occurred: " + [Link]());
}
Using Throws Keyword
If you don’t want to handle the exception directly, declare it using the throws keyword, and let
the calling method handle it.
Eg. [Link]
java
public void performAction() throws NoSuchElementException {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
WebElement element = [Link]([Link]("nonExistingId"));
[Link]();
[Link]();
}
Custom Exception Handling
Create custom exceptions to make your automation more descriptive.
java
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public void testCustomException() throws CustomException {
try {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
WebElement element = [Link]([Link]("nonExistingId"));
[Link]();
} catch (NoSuchElementException e) {
throw new CustomException("Custom Exception: Element not found.");
}
}
// interview
Retry Logic with Exception Handling
Retry the operation if an exception occurs.
java
public void retryOperation() {
WebDriver driver = new ChromeDriver();
int attempts = 0;
boolean success = false;
while (attempts < 3 && !success) {
try {
[Link]("[Link]
WebElement element = [Link]([Link]("retryElementId"));
[Link]();
success = true; // Exit loop if successful
} catch (NoSuchElementException e) {
[Link]("Attempt " + (attempts + 1) + " failed.");
attempts++;
}
}
[Link]();
}
Common Selenium Exceptions
● NoSuchElementException: When an element cannot be located.
● TimeoutException: When a command takes longer than the specified time.
● StaleElementReferenceException: When the referenced element is no longer attached
to the DOM.
● ElementNotInteractableException: When the element is not interactable.
● WebDriverException: Generic WebDriver-related errors.
Best Practices
● Always use specific exceptions instead of catching generic exceptions.
● Use meaningful error messages in the catch block.
● Implement logging mechanisms to log errors for debugging.
● Use finally to clean up resources (e.g., closing the browser).
● Avoid overusing try-catch; instead, write robust scripts that reduce exceptions.
try {
// click by default in build function
:[Link]([Link]("/html[1]/body[1]/div[2]/div[1]/div[6]/div[1]/form[2]/div[5]/div[1]/
div[3]/div[2]/div[1]/div[3]/div[1]/div[2]/div[3]/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/
div[1]/div[3]/div[1]/div[1]/div[1]/div[2]/div[1]/div[13]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/
span[1]/*[name()='svg'][1]/*[name()='rect'][1]")).click();
// click by javascript
WebElement element = [Link]([Link]("(//label[normalize-
space()='Warehouse'])[1]"));
((JavascriptExecutor)
driver).executeScript("arguments[0].scrollIntoView(true);", element);
// click by actions:[Link](Vieww).click().build().perform();
WebElement View =[Link]([Link]("/html[1]/body[1]/div[2]/div[1]/div[6]/div[1]/
form[2]/div[5]/div[1]/div[3]/div[2]/div[1]/div[3]/div[1]/div[2]/div[3]/div[1]/div[1]/div[2]/div[2]/div[2]/
div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[2]/div[1]/div[13]/div[1]/div[1]/div[1]/div[1]/
div[1]/div[1]/div[1]/span[1]/*[name()='svg'][1]/*[name()='rect'][1]"));
[Link](View).click().build().perform();
[Link](3000);
WebElement Vieww = [Link]([Link]("/html[1]/body[1]/div[2]/div[1]/div[6]/div[1]/
form[2]/div[5]/div[1]/div[3]/div[2]/div[1]/div[3]/div[1]/div[2]/div[3]/div[1]/div[1]/div[2]/div[2]/div[2]/
div[1]/div[1]/div[1]/div[1]/div[3]/div[2]/div[1]/div[1]/div[2]/div[1]/div[13]/div[1]/div[1]/div[1]/div[1]/
div[1]/div[1]/div[1]/span[1]/*[name()='svg'][1]/*[name()='rect'][1]"));
[Link](Vieww).click().build().perform();
[Link](3000);
} catch (Exception e) {
[Link]("Unable to click on checkbox button");
}
Collections Framework
In Selenium, the Collections Framework (including List, Set, and Map) is commonly used to
store, manage, and interact with groups of WebElements, test data, or configurations in an
organized manner. Here's an overview of how these collections are applied in Selenium
automation:
1. List in Selenium
A List in Java is an ordered collection that allows duplicate elements. It is particularly useful
for:
● Storing multiple WebElements fetched using locators.
● Iterating through these elements to perform actions.
Example:
java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ListExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
// Finding all links on the page
List<WebElement> links = [Link]([Link]("a"));
// Iterating through the list and printing link text
for (WebElement link : links) {
[Link]([Link]());
}
[Link]();
}
}
2. Set in Selenium
A Set is a collection that does not allow duplicate elements. This is helpful when:
● You want to avoid duplicate entries, such as collecting unique dropdown values or
unique links.
● You need to filter out duplicates from a list of WebElements or strings.
Example:
java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class SetExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
// Fetching all links
List<WebElement> links = [Link]([Link]("a"));
Set<String> uniqueLinks = new HashSet<>();
// Adding unique link texts to the Set
for (WebElement link : links) {
[Link]([Link]());
}
// Printing the unique link texts
for (String text : uniqueLinks) {
[Link](text);
}
[Link]();
}
}
3. Map in Selenium
A Map is a collection that maps keys to values, with each key being unique. It is useful for:
● Storing key-value pairs like configuration properties (e.g., browser type, base URL).
● Associating WebElements with their names or descriptions for easy retrieval.
Example:
java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MapExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
// Creating a map of element descriptions to WebElements
Map<String, WebElement> elementMap = new HashMap<>();
[Link]("Search Box",
[Link]([Link]("q")));
[Link]("Submit Button",
[Link]([Link]("btnK")));
// Performing actions using the map
[Link]("Search Box").sendKeys("Selenium");
[Link]("Submit Button").click();
[Link]();
}
}
Use Cases Summary
Collectio Description & Use Case
n
List Ordered collection; used for working with groups of WebElements like links,
buttons, or dropdown options.
Set Ensures uniqueness; used to filter duplicates from WebElements or strings.
Map Key-value pair; used for associating WebElements with meaningful identifiers or
storing configurations.
Using these collections effectively in Selenium enhances the readability, reusability, and
maintainability of test scripts.
Here’s a deeper dive into the Collections Framework (List, Set, Map) used in Selenium with
detailed explanations, examples, and interview questions.
1. List in Selenium
When to Use List?
● To store and iterate through multiple WebElements (e.g., links, buttons, or options in a
dropdown).
● When the order of elements is important.
Key Methods:
● add(): Adds an element to the list.
● get(int index): Retrieves an element at a specific index.
● size(): Returns the number of elements in the list.
● remove(int index): Removes an element at a specified index.
Example:
java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ListExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
// Fetching all buttons on the page
List<WebElement> buttons =
[Link]([Link]("button"));
// Printing button text using index
for (int i = 0; i < [Link](); i++) {
[Link]("Button " + (i + 1) + ": " +
[Link](i).getText());
}
[Link]();
}
}
Interview Questions:
1. Why do we use a List in Selenium?
○ To store multiple WebElements, such as links or dropdown options, while
preserving their order.
2. How can you interact with the last element in a List?
○ Use [Link]([Link]() - 1).
3. What happens if you try to access an index out of bounds in a List?
○ Throws IndexOutOfBoundsException.
2. Set in Selenium
When to Use Set?
● When you want to store unique elements (e.g., unique dropdown options, links, or
attribute values).
● When duplicates are not allowed.
Key Methods:
● add(): Adds an element to the set.
● size(): Returns the number of elements in the set.
● contains(): Checks if a specific element is in the set.
Example:
java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class SetExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
// Fetching all links
List<WebElement> links = [Link]([Link]("a"));
Set<String> uniqueLinks = new HashSet<>();
// Adding unique link texts to the Set
for (WebElement link : links) {
[Link]([Link]());
}
// Printing unique link texts
for (String linkText : uniqueLinks) {
[Link](linkText);
}
[Link]();
}
}
Interview Questions:
1. Why use a Set over a List in Selenium?
○ To ensure uniqueness of elements and avoid duplicate data.
2. What is the difference between HashSet and TreeSet?
○ HashSet does not maintain order, while TreeSet sorts elements in natural
order.
3. Can a Set contain duplicate elements?
○ No, a Set automatically removes duplicates.
3. Map in Selenium
When to Use Map?
● To store key-value pairs, such as test data, configuration properties, or WebElement
references with descriptive names.
Key Methods:
● put(key, value): Adds a key-value pair to the map.
● get(key): Retrieves the value associated with a key.
● containsKey(key): Checks if a specific key exists.
● entrySet(): Returns a set view of the mappings.
Example:
java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MapExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
// Storing elements in a map with descriptive keys
Map<String, WebElement> elements = new HashMap<>();
[Link]("Username Field",
[Link]([Link]("username")));
[Link]("Password Field",
[Link]([Link]("password")));
[Link]("Login Button",
[Link]([Link]("login")));
// Performing actions
[Link]("Username Field").sendKeys("testuser");
[Link]("Password Field").sendKeys("password123");
[Link]("Login Button").click();
[Link]();
}
}
Interview Questions:
1. Why is a Map useful in Selenium?
○ To associate WebElements with their functional names for better readability and
manageability.
2. What is the difference between HashMap and LinkedHashMap?
○ HashMap does not maintain order, while LinkedHashMap preserves the
insertion order.
3. Can a Map have duplicate keys?
○ No, keys in a Map are unique, but values can be duplicated.
Advanced Use Cases in Selenium
Storing Dropdown Options:
java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class DropdownExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
WebElement dropdown = [Link]([Link]("dropdown"));
Select select = new Select(dropdown);
// Storing options in a Set to ensure uniqueness
List<WebElement> options = [Link]();
Set<String> uniqueOptions = new HashSet<>();
for (WebElement option : options) {
[Link]([Link]());
}
[Link]("Unique Dropdown Options: " +
uniqueOptions);
[Link]();
}
}
Handling Dynamic Tables with Maps:
java
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class TableExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
[Link]("[Link]
// Fetching table rows
List<WebElement> rows =
[Link]([Link]("//table/tbody/tr"));
Map<Integer, String> tableData = new HashMap<>();
// Storing data in a map
for (int i = 1; i <= [Link](); i++) {
String cellData =
[Link]([Link]("//table/tbody/tr[" + i +
"]/td[1]")).getText();
[Link](i, cellData);
}
// Printing table data
for ([Link]<Integer, String> entry : [Link]())
{
[Link]("Row " + [Link]() + ": " +
[Link]());
}
[Link]();
}
}
General Interview Questions
1. What is the difference between List, Set, and Map in Java?
2. How do you ensure uniqueness in dropdown values using Selenium?
3. How can you store dynamic WebElement locators in a Map?
4. What happens when you use findElements with a locator that returns no
elements?
○ It returns an empty List.