Java Programming: Features and Basics
Java Programming: Features and Basics
● Known for its Write Once, Run Anywhere capability, which means code written in Java
can run on any device that supports the Java Virtual Machine (JVM).
● Syntax and structure is similar to C-based languages like C++ and C#.
● Used to build Android apps, desktop and web apps, enterprise backend systems, and
cloud-based software.
● Has popular frameworks like Spring and Hibernate which makes it powerful for
enterprise applications.
● It runs on all platforms Windows, Mac, and Linux using the JVM.
Comments in Java
● The comments are the notes written inside the code to explain what we are
doing. The comment lines are not executed while we run the program.
● Single-line comment
● // This is a comment
● Multi-line comment
● /*
● This is a multi-line comment.
● This is useful for explaining larger sections of code.
● */
Variables in Java:
Variables are containers to store data in memory. Each variable has a
name, type and value. It is the basic unit of storage in a program. Java
has 4 types of variables.
● Local Variables: Declared inside a method, constructor, or block.
Accessible only within that block.
● Instance Variables: Declared inside a class but outside any method.
Each object of the class has its own copy.
● Static Variables: Declared with the static keyword inside a class.
Shared by all objects of the class.
● Final Variables: Declared with final keyword. Value cannot be
changed once assigned.
Keywords in Java:
Keywords are reserved words in Java that have a predefined meaning.
They cannot be used as variable names, class names or identifiers.
Examples: new, package, private, protected, public, return, short,
static, etc.
In Java, keywords are the reserved words that have some predefined
meanings and are used by the Java compiler for some internal process
or represent some predefined actions. These words cannot be used as
identifiers such as variable names, method names, class names, or
object names.
Java Keywords List
Java contains a list of keywords or reserved words which are also
highlighted with different colors be it an IDE or editor in order to
segregate the differences between flexible words and reserved words.
As of Java 21, there are 53 keywords defined in Java. They are listed
below in the table with the primary action associated with them.
Keywords Usage
values only
branches accordingly
Important Points:
● The keywords const and goto are reserved, even though they are not
currently used in Java.
● true, false, and null look like keywords, but in actuality they
are literals. However, they still can't be used as identifiers in a
program.
● In Java, keywords are case-sensitive, and writing Java keywords in
upper case (like IF instead of if) will throw an error.
Array
In Java, an array is an important linear data structure that allows us to
store multiple values of the same type.
● Arrays in Java are objects, like all other objects in Java, arrays implicitly
inherit from the [Link] class. This allows you to invoke
methods defined in Object (such as toString(), equals() and
hashCode()).
● Arrays have a built-in length property, which provides the number of
elements in the array
Example
public class Geeks {
public static void main(String[] args) {
// initializing array
int[] arr = { 40,55,63,17,22,68,89,97,89};
// size of array
int n = [Link];
// traversing array
for (int i = 0; i < n; i++)
[Link](arr[i] + " ");
}
}
Output
40 55 63 17 22 68 89 97 89
Key features of Arrays
● Store Primitives and Objects: Java arrays can hold both primitive
types (like int, char, boolean, etc.) and objects (like String, Integer,
etc.)
● Contiguous Memory Allocation When we use arrays of primitive
types, the elements are stored in contiguous locations. For non
primitive types, references of items are stored at contiguous locations.
● Zero-based Indexing: The first element of the array is at index 0.
● Fixed Length: After creating an array, its size is fixed; we can not
change it.
Basics Operation on Arrays in Java
1. Declaring an Array
The general form of array declaration is
// Method 1:
int arr[];
// Method 2:
int[] arr;
The element type determines the data type of each element that
comprises the array. Like an array of integers, we can also create an
array of other primitive data types like char, float, double, etc. or user-
defined data types (objects of a class).
2. Initialization an Array in Java
When an array is declared, only a reference of an array is created. We
use new to allocate an array of given size.
int arr[] = new int[size];
● Array Declaration is generally static, but if the size in not defined, the
Array is Dynamically sized.
● Memory for arrays is always dynamically allocated (on heap segment)
in Java. This is different from C/C++ where memory can either be
statically allocated or dynamically allocated.
● The elements in the array allocated by new will automatically be
initialized to zero
(for numeric types), false (for boolean) or null (for reference types).
●
● // Changing the first element to 90
arr[0] = 90;
● Change an Array Element
● To change an element, assign a new value to a specific index.
The index begins with 0 and ends at (total array size)-1.
●
● // Changing the first element to 90
arr[0] = 90;
3. Change an Array Element
● To change an element, assign a new value to a specific index.
4. Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int n = [Link];
Used to
Used to
develop Executes
run Java
Java Java
application
application bytecode
s
Purpose s
bytecode is
(OS (OS
platform-
specific) specific)
y independent
JRE +
ClassLoade
Developme JVM +
r, JIT
nt tools Libraries
Compiler,
(javac, (e.g.,
Garbage
debugger, [Link])
Collector
Includes etc.)
Running a Convert
Writing and Java bytecode
compiling application into native
Java code on a machine
Use Case system code
Note: The JVM is platform-independent in the sense that the bytecode can
run on any machine with a JVM, but the actual JVM implementation is
platform-dependent. Different operating systems (e.g., Windows, Linux,
macOS) require different JVM implementations that interact with the
specific OS and hardware
We have discussed the core differences, now let's take a closer look at
each component. Let, us discuss them in brief first and interrelate them
with the image below proposed.
JDK (Java Development Kit)
The JDK is a software development kit that provides tools to develop and
run Java applications. It includes two main components:
● Development Tools (to provide an environment to develop your java
programs)
● JRE (to execute your java program)
Note:
● JDK is only for development (it is not needed for running Java programs)
● JDK is platform-dependent (different version for windows, Linux, macOS)
Working of JDK
The JDK enables the development and execution of Java programs.
Consider the following process:
● Java Source File (e.g., [Link]): You write the Java program in a
source file.
● Compilation: The source file is compiled by the Java Compiler (part of
JDK) into bytecode, which is stored in a .class file (e.g., [Link]).
● Execution: The bytecode is executed by the JVM (Java Virtual Machine),
which interprets the bytecode and runs the Java program.
Working of JDK
Note: From above, media operation computing during the compile time can
be interpreted.
Java Identifiers
class Geeks {
public static void main(String[] args) {
// Declaring and initializing variables
// Integer variable
int age = 25;
// String variable
String name = "GeeksforGeeks";
// Double variable
double salary = 50000.50;
Output
Age: 25
Name: GeeksforGeeks
Salary: 50000.5
How to Declare Java Variables?
The image below demonstrates how we can declare a variable in Java:
Variable Declaration
From the image, it can be easily perceived that while declaring a variable,
we need to take care of two things that are:
1. data type: In Java, a data type define the type of data that a variable can
hold.
2. variable name: Must follow Java naming conventions (e.g., camelCase).
In this way, a name can only be given to a memory location. It can be
assigned values in two ways:
● Variable Initialization
● Assigning value by taking input
How to Initialize Java Variables?
It can be perceived with the help of 3 components explained above:
Variable Initialization
Example: Here, we are initalizing variables of different types like float, int
and char.
// Demonstrating how to intialize variables
// of different types in Java
class Geeks{
public static void main(String[] args) {
// Declaring and initializing variables
Output
Simple Interest: 5.5
Speed: 20
Time: 10
Character: h
Types of Java Variables
Now let us discuss different types of variables which are listed as follows:
● Local Variables
● Instance Variables
● Static Variables
Type of Variable
Let us discuss the traits of every type of variable listed here in detail.
1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
● The Local variable is created at the time of declaration and destroyed when
the function completed its execution.
● The scope of local variables exists only within the block in which they are
declared.
● We first need to initialize a local variable before using it within its scope.
Example: This example show how a local variable is declared and used
inside the main method and it can not be used outside of it.
// Java Program to show the use of local variables
import [Link].*;
class Geeks {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
Output
Local Variable: 10
Example: This example demonstrates that local variables are only
accessible within the block in which they are declared
// Java Program to show the use of
// Local Variables
import [Link].*;
if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5";
[Link](result);
}
Output
x = 10
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2
2. Instance Variables
Instance variables are known as non-static variables and are declared in a
class outside of any method, constructor, or block.
● Instance variables are created when an object of the class is created and
destroyed when the object is destroyed.
● Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier, then the default access specifier will
be used.
● Initialization of an instance variable is not mandatory. Its default value is
dependent on the data type of variable. For String it
is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it
is null, etc.
● Scope of instance variables are throughout the class except the static
contexts.
● Instance variables can be accessed only by creating objects.
● We initialize instance variables using constructors while creating an object.
We can also use instance blocks to initialize the instance variables.
Example: This example demonstrates the use of instance variables, which
are declared within a class and initialized via a constructor, with default
values for uninitialized primitive types.
// Java Program to show the use of
// Instance Variables
import [Link].*;
class Geeks {
// Main Method
public static void main(String[] args)
{
// Object Creation
Geeks name = new Geeks();
// Displaying O/P
[Link]("Geek name is: " + [Link]);
[Link]("Default value for int is "+ name.i);
Output
Geek name is: Sweta Dash
Default value for int is 0
Default value for Integer is: null
3. Static Variables
Static variables are also known as class variables.
● These variables are declared similarly to instance variables. The difference is
that static variables are declared using the static keyword within a class
outside of any method, constructor, or block.
● Unlike instance variables, we can only have one copy of a static variable per
class, irrespective of how many objects we create.
● Static variables are created at the start of program execution and destroyed
automatically when execution ends.
● Initialization of a static variable is not mandatory. Its default value is
dependent on the data type of variable. For String it is null, for float it
is 0.0f, for int it is 0, for Wrapper classes like Integer it is null, etc.
● If we access a static variable like an instance variable (through an object),
the compiler will show a warning message, which won't halt the program.
The compiler will replace the object name with the class name
automatically.
● If we access a static variable without the class name, the compiler will
automatically append the class name. But for accessing the static variable of
a different class, we must mention the class name as 2 different classes
might have a static variable with the same name.
● Static variables cannot be declared locally inside an instance method.
● Static blocks can be used to initialize static variables.
Example: This example demonstrates the use of static variables, which
belong to the class and can be accessed without creating an object of the
class.
// Java Program to show the use of
// Static variables
import [Link].*;
class Geeks {
// static int c = 0;
// above line, when uncommented,
// will throw an error as static variables cannot be
// declared locally.
}
}
Output
Geek Name is: Sweta Dash
Instance Variables vs Static Variables
Now let us discuss the differences between the Instance variables and the
Static variables:
● Each object will have its own copy of an instance variable, whereas we can
only have one copy of a static variable per class, irrespective of how many
objects we create. Thus, static variables are good
for memory management.
● Changes made in an instance variable using one object will not be reflected
in other objects as each object has its own copy of the instance variable. In
the case of a static variable, changes will be reflected in other objects as
static variables are common to all objects of a class.
● We can access instance variables through object references, and static
variables can be accessed directly using the class name.
● Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed. Static variables
are created when the program starts and destroyed when the program stops.
Syntax: Static and instance variables
class Geeks
{
// Static variable
static int a;
// Instance variable
int b;
}
Common Mistakes to Avoid
The common mistakes that can occur when working with variables in Java
are listed below:
● Using uninitialized local variables: Accessing a local variable without
initializing it leads to a compile-time error.
● Confusing == and .equals() for Strings: == is used to compare object
references, while .equals() is used to compare the content of the strings.
● Modifying static variables incorrectly: Changing static variables in a
multi-threaded environment can lead to thread safety issues
Operators in java
Java operators are special symbols that perform operations on variables or
values. These operators are essential in programming as they allow you to
manipulate data efficiently.
Example: Below code describes basic structure of operator. how to use operators
like the + and - operators are used to perform addition and subtraction on numeric
values."
// Java program to show the use of + and - operators
public class Geeks
{
public static void main(String[] args)
{
// Declare and initialize variables
int num1 = 500;
int num2 = 100;
}
}
Output
The Sum is: 600
The Difference is: 400
Explanation:
● A class named Geeks is created containing the main method.
● Two integer variables num1 and num2 are declared and initialized with
values.
● The + operator is used to add the two numbers and store the result in sum.
● The result of addition is printed to the console.
● The - operator is used to subtract the second number from the first and store
the result in diff.
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. An instance of an operator
Let's see all these operators one by one with their proper examples.
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive
and non-primitive data types.
● * : Multiplication
● / : Division
● % : Modulo
● + : Addition
● - : Subtraction
Note:
● Division (/) truncates decimal points for integers.
● Modulus (%) is useful for checking even/odd numbers.
Example: This example demonstrates the use of arithmetic operators on
integers and string-to-integer conversion for performing mathematical
operations.
// Java Program to show the use of
// Arithmetic Operators
import [Link].*;
class Geeks
{
public static void main (String[] args)
{
}
}
Output
a + b = 13
a-b=7
a * b = 30
a/b=3
a%b=1
a1 + b1 = 40
2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or
negate a value.
● - , Negates the value.
● + , Indicates a positive value (automatically converts byte, char,
or short to int).
● ++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
● -- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
● ! , Inverts a boolean value.
Example: This example demonstrates the use of unary operators for post-
increment, pre-increment, post-decrement, and pre-decrement operations.
// Java Program to show the use of
// Unary Operators
import [Link].*;
// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
3. Assignment Operator
'=' The assignment operator is used to assign a value to any variable. It has right-
to-left associativity, i.e. value given on the right-hand side of the operator is
assigned to the variable on the left, and therefore right-hand side value must be
declared before using it or should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with others to create
shorthand compound statements. For example, a += 5 replaces a = a + 5. Common
compound operators include:
● += , Add and assign.
● -= , Subtract and assign.
● *= , Multiply and assign.
● /= , Divide and assign.
● %= , Modulo and assign.
Example: This example demonstrates the use of various assignment operators,
including compound, bitwise, and shift operators, for modifying a variable.
// Java Program to show the use of
// Assignment Operators
import [Link].*;
// Driver Class
class Geeks {
// Main Function
public static void main(String[] args)
{
// Assignment operators
int f = 7;
[Link]("f += 3: " + (f += 3));
[Link]("f -= 2: " + (f -= 2));
[Link]("f *= 4: " + (f *= 4));
[Link]("f /= 3: " + (f /= 3));
[Link]("f %= 2: " + (f %= 2));
[Link]("f &= 0b1010: " + (f &= 0b1010));
[Link]("f |= 0b1100: " + (f |= 0b1100));
[Link]("f ^= 0b1010: " + (f ^= 0b1010));
[Link]("f <<= 2: " + (f <<= 2));
[Link]("f >>= 1: " + (f >>= 1));
[Link]("f >>>= 1: " + (f >>>= 1));
}
}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6
Note: Use compound assignments (+=, -=) for cleaner code.
4. Relational Operators
Relational Operators are used to check for relations like equality, greater than, and
less than. They return boolean results after the comparison and are extensively
used in looping statements as well as conditional if-else statements. The general
format is ,
variable relation_operator value
Relational operators compare values and return Boolean results:
● == , Equal to.
● != , Not equal to.
● < , Less than.
● <= , Less than or equal to.
● > , Greater than.
● >= , Greater than or equal to.
Example: This example demonstrates the use of relational operators to compare
values and return boolean results.
// Java Program to show the use of
// Relational Operators
import [Link].*;
// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true
5. Logical Operators
Logical Operators are used to perform "logical AND" and "logical OR" operations,
similar to AND gate and OR gate in digital electronics. They have a short-
circuiting effect, meaning the second condition is not evaluated if the first is false.
Conditional operators are:
● &&, Logical AND: returns true when both conditions are true.
● ||, Logical OR: returns true if at least one condition is true.
● !, Logical NOT: returns true when a condition is false and vice-versa
Example: This example demonstrates the use of logical operators (&&, ||, !) to
perform boolean operations.
// Java Program to show the use of
// Logical operators
import [Link].*;
class Geeks {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
Output
x && y: false
x || y: true
!x: false
6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three
operands and hence the name Ternary. The general format is,
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the '?' else execute the statements after the ':'.
Example: This example demonstrates the use of the ternary operator to find the
maximum of three numbers.
// Java program to illustrate
// max of three numbers using
// ternary operator.
public class Geeks {
Output
Max of three numbers = 30
7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual bits of a
number and with any of the integer types. They are used when performing update
and query operations of the Binary indexed trees.
● & (Bitwise AND): returns bit-by-bit AND of input values.
● | (Bitwise OR): returns bit-by-bit OR of input values.
● ^ (Bitwise XOR): returns bit-by-bit XOR of input values.
● ~ (Bitwise Complement): inverts all bits (one's complement).
Example: This example demonstrates the use of bitwise operators (&, |, ^, ~, <<,
>>, >>>) to perform bit-level operations.
// Java Program to show the use of
// bitwise operators
import [Link].*;
class Geeks
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
Output
d&e:8
d | e : 14
d^e:6
~d : -11
d << 2 : 40
e >> 1 : 6
e >>> 1 : 6
8. Shift Operators
Shift Operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number by two, respectively. They can be used when
we have to multiply or divide a number by two. The general format ,
number shift_op number_of_places_to_shift;
● << (Left shift): Shifts bits left, filling 0s (multiplies by a power of two).
● >> (Signed right shift): Shifts bits right, filling 0s (divides by a power of
two), with the leftmost bit depending on the sign.
● >>> (Unsigned right shift): Shifts bits right, filling 0s, with the leftmost bit
always 0.
Example: This example demonstrates the use of shift operators (<<, >>) to shift
the bits of a number left and right.
// Java Program to show the use of
// shift operators
import [Link].*;
class Geeks
{
public static void main(String[] args)
{
int a = 10;
// Using left shift
[Link]("a<<1 : " + (a << 1));
Output
a<<1 : 20
a>>1 : 5
9. instanceof Operator
The instanceof operator is used for type checking. It can be used to test if an object
is an instance of a class, a subclass, or an interface. The general format,
object instance of class/subclass/interface
Example: This example demonstrates the use of the instanceof operator to check
if an object is an instance of a specific class or interface
// Java program to show the use of
// Instance of operator
public class Geeks
{
public static void main(String[] args)
{
Person obj1 = new Person();
Person obj2 = new Boy();
interface MyInterface {
}
Output
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true
Common Mistakes to Avoid
The common mistakes that can occur when working with Java Operators are listed
below:
● Confusing == with =: Using == for assignment instead of = for equality
check leads to logical errors.
● Incorrect Use of Floating Point Comparison: Comparing floating point
numbers using == can lead to unexpected results due to precision issues.
● Integer Division Confusion: Dividing two integers will result in integer
division (truncating the result).
● Overusing + for String Concatenation in Loops: Using + for
concatenating strings in loops leads to performance issues because it creates
new string objects on each iteration.
Decision Making in Java (if-else, switch, break, continue, jump)
Decision-making in programming is similar to decision-making in real life.
In programming, we also face situations where we want a certain block of
code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of
execution of a program based on certain conditions.. Java provides several
control statements to manage program flow, including:
● Conditional Statements: if, if-else, nested-if, if-else-if
● Switch-Case: For multiple fixed-value checks
● Jump Statements: break, continue, return
Types of Decision-Making Statements
● if
● if-else
● nested-if
● if-else-if
● switch-case
● jump - break, continue, return
The table below demonstrates various control flow statements in
programming, their use cases, and examples of their syntax.
Statement Use Case Example
Single condition
if (age >= 18)
if check
Two-way
if (x > y) {...} else {...}
if-else decision
Multi-level
if (x > 10) { if (y > 5) {...} }
nested-if conditions
1. Java if Statement
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or
not i.e. if a certain condition is true then a block of statements is executed
otherwise not.
Syntax:
if(condition) {
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement
accepts boolean values - if the value is true then it will execute the block of
statements under it. If we don't use curly braces( {} ), only the next line after
the if is considered as part of the if block For example,
if (condition) // Assume condition is true
statement1; // Belongs to the if block
statement2; // Does NOT belong to the if block
Here's what happens:
● If the condition is True statement1 executes.
● statement2 runs no matter what because it's not a part of the if block
if Statement Execution Flow
The below diagram demonstrates the flow chart of an "if Statement
execution flow" in programming.
Java if
Example: The below Java program demonstrates without curly braces, only
the first line after the if statement is part of the if block and the rest code will
be execute independently.
import [Link].*;
class Geeks {
public static void main(String args[])
{
int i = 10;
if (i < 15)
Output
Inside If block
10 is less than 15
I am Not in if
2. Java if-else Statement
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won't. But what if we want
to do something else if the condition is false? Here, comes the "else"
statement. We can use the else statement with the if statement to execute a
block of code when the condition is false.
Syntax:
if(condition){
// Executes this block if
// condition is true
}else{
// Executes this block if
// condition is false
}
if-else Statement Execution flow
The below diagram demonstrates the flow chart of an "if-else Statement
execution flow" in programming
if-else
Example: The below Java program demonstrates the use of if-else statement
to execute different blocks of code based on the condition.
import [Link].*;
class Geeks {
public static void main(String args[])
{
int i = 10;
if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
}
Output
i is smaller than 15
3. Java nested-if Statement
A nested if is an if statement that is the target of another if or else. Nested if
statements mean an if statement inside an if statement. Yes, java allows us to
nest if statements within if statements. i.e, we can place an if statement
inside another if statement.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
nested-if Statement Execution Flow
The below diagram demonstrates the flow chart of an "nested-if Statement
execution flow" in programming.
Nested-if
// Outer if statement
if (i < 15) {
[Link]("i is smaller than 15");
// Nested if statement
if (i == 10) {
[Link]("i is exactly 10");
}
}
}
}
Output
i is smaller than 15
i is smaller than 12 too
4. Java if-else-if ladder
Here, a user can decide among multiple [Link] if statements are
executed from the top down. As soon as one of the conditions controlling the
if is true, the statement associated with that 'if' is executed, and the rest of
the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed. There can be as many as 'else if' blocks
associated with one 'if' block but only one 'else' block is allowed with one 'if'
block.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
if-else-if ladder Execution Flow
The below diagram demonstrates the flow chart of an "if-else-if ladder
execution flow" in programming
if-else-if ladder
Example: This example demonstrates an if-else-if ladder to check multiple
conditions and execute the corresponding block of code based on the value
of I.
import [Link].*;
class Geeks {
public static void main(String args[])
{
int i = 20;
if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
}
}
Output
i is 20
5. Java Switch Case
The switch statement is a multiway branch statement. It provides an easy
way to dispatch execution to different parts of code based on the value of the
expression.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases...
default:
// code to be executed if no cases match
}
switch Statements Execution Flow
The below diagram demonstrates the flow chart of a "switch Statements
execution flow" in programming.
switch statement
Example: The below Java program demonstrates the use of switch-case
statement to evaluate multiple fixed values.
import [Link].*;
class Geeks {
public static void main(String[] args)
{
int num = 20;
switch (num) {
case 5:
[Link]("It is 5");
break;
case 10:
[Link]("It is 10");
break;
case 15:
[Link]("It is 15");
break;
case 20:
[Link]("It is 20");
break;
default:
[Link]("Not present");
}
}
}
Output
It is 20
● The expression can be of type byte, short, int char, or an enumeration.
Beginning with JDK7, the expression can also be of type String.
● Duplicate case values are not allowed.
● The default statement is optional.
● The break statement is used inside the switch to terminate a statement
sequence.
● The break statements are necessary without the break keyword, statements in
switch blocks fall through.
● If the break keyword is omitted, execution will continue to the next case.
6. jump Statements
Java supports three jump statements: break, continue and return. These
three statements transfer control to another part of the program.
● Break: In Java, a break is majorly used for:
class Geeks {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
Output
13579
Return Statement
The return statement is used to explicitly return from a method. That is, it
causes program control to transfer back to the caller of the method.
Example: The below Java program demonstrates how the return statements
stop a method and skips the rest of the code.
import [Link].*;
if (t)
return;
class Geeks {
public static void main(String[] args)
{
for (int i = 0; i <= 10; i++) {
[Link](i + " ");
}
}
}
Output
0 1 2 3 4 5 6 7 8 9 10
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
● Initialization condition: Here, we initialize the variable in use. It marks the
start of a for loop. An already declared variable can be used or a variable can
be declared, local to loop only.
● Testing Condition: It is used for testing the exit condition for a loop. It
must return a boolean value. It is also an Entry Control Loop as the
condition is checked prior to the execution of the loop statements.
● Statement execution: Once the condition is evaluated to true, the statements
in the loop body are executed.
● Increment/ Decrement: It is used for updating the variable for next
iteration.
● Loop termination:When the condition becomes false, the loop terminates
marking the end of its life cycle.
Note: There is another form of the for loop known as Enhanced for loop or
(for each loop).
Enhanced for loop (for each)
This loop is used to iterate over arrays or collections.
Example: The below Java program demonstrates an Enhanced for loop (for
each loop) to iterate through an array and print names.
// Java program to demonstrate
// the working of for each loop
import [Link].*;
class Geeks {
public static void main(String[] args)
{
String[] names = { "Sweta", "Gudly", "Amiya" };
Output
Name: Sweta
Name: Gudly
Name: Amiya
Syntax:
for (dataType variable : arrayOrCollection) {
// code to be executed
}
2. while Loop
A while loop is used when we want to check the condition before executing
the loop body.
Example: The below Java program demonstrates a while loop that prints
numbers from 0 to 10 in a single line.
// Java program to demonstrates
// the working of while loop
import [Link].*;
class Geeks {
public static void main(String[] args)
{
int i = 0;
while (i <= 10) {
[Link](i + " ");
i++;
}
}
}
Output
0 1 2 3 4 5 6 7 8 9 10
Syntax:
while (condition) {
// code to be executed
}
class Geeks {
public static void main(String[] args)
{
int i = 0;
do {
[Link](i + " ");
i++;
} while (i <= 10);
}
}
Output
0 1 2 3 4 5 6 7 8 9 10
Syntax:
do {
// code to be executed
} while (condition);
● do while loop starts with the execution of the statement. There is no
checking of any condition for the first time.
● After the execution of the statements, and update of the variable value, the
condition is checked for true or false value. If it is evaluated to true, next
iteration of loop starts.
● When the condition becomes false, the loop terminates which marks the end
of its life cycle.
● It is important to note that the do-while loop will execute its statements a
tleast once before any condition is checked, and therefore is an example of
exit control loop.
Common Loop Mistakes and How to Avoid them
If loops are not used correctly, they can introduce pitfalls and bugs that
affect code performance, readability, and functionality. Below are some
common pitfalls of loops:
1. Infinite Loops
This is one of the most common mistakes while implementing any sort of
looping is that it may not ever exit, that is the loop runs for infinite time.
This happens when the condition fails for some reason.
Types of Infinite Loops:
● infinite for Loop
● infinite while Loop
Example: Here, both the examples demonstrates the infinite loops.
// Java program to demonstrate
// the infinite for loop
import [Link].*;
class Geeks {
public static void main(String[] args)
{
for (int i = 0; i < 5; i--) {
[Link](
"This loop will run forever");
}
}
}
Output: When you run both the above codes you will get TLE (Time Limit
Exceeded) error.
2. Off-by-One Errors
Off-by-One Errors are caused when the loop runs one more or one fewer
time than you wanted. It basically happens when the loop condition is not set
correctly.
Example: The below Java program demonstrates an Off-by-One Error,
where the loop runs 6 times and we expected it to run 5 times.
// Java Program to demonstrates Off-by-One Errors
import [Link].*;
class Geeks {
public static void main(String[] args)
{
for (int i = 0; i <= 5; i++) {
[Link](i + " ");
}
}
}
3. Modifying Loop Variables Inside the Loop
When we change the loop condition (like i) inside the loop, it can cause the
loop to skip certain iterations or behave in ways that we did not expected.
This might leads to errors or unexpected behavior.
Example: The below Java program demonstrates modifying the loop
variable inside the loop, which cause the loop to skip certain iterations and
behave unexpected.
// Java program demonstrates
// modification in i variable
import [Link].*;
class Geeks {
public static void main(String[] args)
{
for (int i = 0; i < 5; i++) {
if (i == 2) {
class Geeks {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
Executes
Loop Condition At Least
Type When to Use Checking Once?
Before loop
When you
body, It is
want exact no
for called Entry-
iterations
loop controlled.
Before loop
When you
body, It is
need condition no
while called Entry-
check first.
loop controlled.
After loop
When you
do- body, It is
need to run at yes
while called Exit-
least once
loop controlled.
When you
for- process all Internally
no
each collection handled
loop items