0% found this document useful (0 votes)
33 views72 pages

Java Programming: Features and Basics

Java is a high-level, object-oriented programming language known for its Write Once, Run Anywhere capability, allowing code to run on any device with a Java Virtual Machine. It is widely used for developing web applications, mobile apps, and enterprise software, with a strong job market and popular frameworks like Spring and Hibernate. Key features include platform independence, simplicity, security, and support for multithreading, making it a versatile choice for developers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views72 pages

Java Programming: Features and Basics

Java is a high-level, object-oriented programming language known for its Write Once, Run Anywhere capability, allowing code to run on any device with a Java Virtual Machine. It is widely used for developing web applications, mobile apps, and enterprise software, with a strong job market and popular frameworks like Spring and Hibernate. Key features include platform independence, simplicity, security, and support for multithreading, making it a versatile choice for developers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java is a high-level, object-oriented programming language used to build web apps, mobile

applications, and enterprise software systems.

● 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#.

Why Learn Java?

● Used to build Android apps, desktop and web apps, enterprise backend systems, and
cloud-based software.

● In high demand with many job opportunities in software development.

● Has popular frameworks like Spring and Hibernate which makes it powerful for
enterprise applications.

● Supports object-oriented programming for clean and reusable code.

● It runs on all platforms Windows, Mac, and Linux using the JVM.

● Top companies like Amazon, Netflix, and LinkedIn use Java.

● Java Hello World Program


● Here is a simple Java program that prints "Hello World".
public class Geeks {
public static void main(String args[])
{
[Link]("Hello World");
}
}
How does this work:
● // starts a single-line comment. The comments does not executed by
Java.
● public class HelloWorld defines a class named HelloWorld. In Java,
every program must be inside a class.
● public static void main(String[] args) is the entry point of any Java
application. It tells the JVM where to start executing the program.
● [Link]("Hello, World!"); prints the message to the
console.
Java is a high-level, object-oriented programming language developed
by Sun Microsystems in 1995. It is mostly used for building desktop
applications, web applications, Android apps, and enterprise systems.
Key Features of Java
● Platform Independent: Java is famous for its Write Once, Run
Anywhere (WORA) feature. This means we can write our Java code
once, and it will run on any device or operating system if Java Virtual
Machine is installed.
● Simple: No complex features like pointers and multiple inheritance,
which makes it a good choice for beginners.
● Object-Oriented: This makes code clean and reusable.
● Secured: Since there are no pointers, it has built-in protections to
keep our programs secure from common problems like memory
leakage and segment fault.
● Multithreading: Programs can do many things at the same time using
multiple threads. This is useful for handling complex tasks like
processing transactions.
● Just-In-Time (JIT) Compiler: Java uses a JIT compiler. It improves
performance by converting the bytecode into machine readable code
at the time of execution.

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.
● */

Famous Applications Built Using Java


● Android Apps: Most of the Android mobile apps are built using Java.
● Netflix: This uses Java for content delivery and backend services.
● Amazon: Java language is used for its backend systems.
● LinkedIn: This uses Java for handling high traffic and scalability.
● Minecraft: This is one of the world’s most popular games that is built in Java.
● Spotify: This uses Java in parts of its server-side infrastructure.
● Uber: Java is used for backend services like trip management.
● NASA WorldWind: This is a virtual globe software built using Java.

Java is a class-based, object-oriented programming language that is designed to be secure


and portable. Its core principle is “Write Once, Run Anywhere” (WORA), meaning Java
code can run on any device or operating system that has a Java Virtual Machine (JVM).

The development environment of Java consists of three components mainly:


1. JVM (Java Virtual Machine): JVM is the engine that runs Java programs. It converts
Java bytecode (compiled code) into machine code (understandable by the OS).
2. JRE (Java Runtime Environment): JRE = JVM + Libraries + Other components
needed to run Java applications.
3. JDK (Java Development Kit): JDK = JRE + Development Tools. It is required for
developing Java applications.

Data Types in Java:


In Java, data types specify the type of values a variable can hold. They
define the size, range and nature of data stored in memory. Java has
two main categories of data types:
1. Primitive: byte, short, int, long, float, double, char, boolean
2. Non-Primitive: String, Arrays, Classes, Interfaces, Objects

public class DataTypesDemo {


public static void main(String[] args) {

// -------- Primitive Data Types --------


byte b = 100; // 1 byte
short s = 30000; // 2 bytes
int i = 100000; // 4 bytes
long l = 10000000000L; // 8 bytes

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

Specifies that a class or method will be


abstract
implemented later, in a subclass

Assert describes a predicate placed in a


Java program to indicate that the
assert
developer thinks that the predicate is
always true at that place.

boolean A data type that can hold True and False


Keywords Usage

values only

A control statement for breaking out of


break
loops.

A data type that can hold 8-bit data


byte
values

Used in switch statements to mark


case
blocks of text

Catches exceptions generated by try


catch
statements

A data type that can hold unsigned 16-


char
bit Unicode characters

class Declares a new class

const Reserved but not used

continue Sends control back outside a loop

Specifies the default block of code in a


default
switch statement

do Starts a do-while loop


Keywords Usage

A data type that can hold 64-bit floating-


double
point numbers

Indicates alternative branches in an if


else
statement

A Java keyword is used to declare an


enum enumerated type. Enumerations extend
the base class.

Indicates that a class is derived from


extends
another class or interface

Indicates that a variable holds a


final constant value or that a method will not
be overridden

Indicates a block of code in a try-catch


finally
structure that will always be executed

A data type that holds a 32-bit floating-


float
point number

for Used to start a for loop

goto Reserved but not used

if Tests a true/false expression and


Keywords Usage

branches accordingly

Specifies that a class implements an


implements
interface

import References other classes

Indicates whether an object is an


instanceof instance of a specific class or
implements an interface

A data type that can hold a 32-bit signed


int
integer

interface Declares an interface

long A data type that holds a 64-bit integer

Specifies that a method is implemented


native
with native (platform-specific) code

new Creates new objects

This indicates that a reference does not


null
refer to anything

package Declares a Java package


Keywords Usage

An access specifier indicating that a


private method or variable may be accessed
only in the class it's declared in

An access specifier indicating that a


method or variable may only be
protected accessed in the class it's declared in (or
a subclass of the class it's declared in or
other classes in the same package)

An access specifier used for classes,


interfaces, methods, and variables
public indicating that an item is accessible
throughout the application (or where the
class that defines it is accessible)

Sends control and possibly a return


return
value back from a called method

A data type that can hold a 16-bit


short
integer

Indicates that a variable or method is a


static class method (rather than being limited
to one particular object)

A Java keyword is used to restrict the


strictfp precision and rounding of floating-point
calculations to ensure portability.
Keywords Usage

Refers to a class's base class (used in a


super
method or class constructor)

A statement that executes code based


switch
on a test value

Specifies critical sections or methods in


synchronized
multithreaded code

Refers to the current object in a method


this
or constructor

throw Creates an exception

Indicates what exceptions may be


throws
thrown by a method

Specifies that a variable is not part of an


transient
object's persistent state

Starts a block of code that will be tested


try
for exceptions

Specifies that a method does not have a


void
return value

This indicates that a variable may


volatile
change asynchronously
Keywords Usage

while Starts a while loop

The sealed keyword is used to declare a


sealed class as "sealed," meaning it restricts
which classes can extend it.

The permits keyword is used within a


sealed class declaration to specify the
permits
subclasses that are permitted to extend
it.

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).

Array Literal in Java


In a situation where the size of the array and variables of the array are
already known, array literals can be used.
// Declaring array literal
int[] arr = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
● The length of this array determines the length of the created array.
● There is no need to write the new int[] part in the latest versions of
Java.
● 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;
● 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.

The index begins with 0 and ends at (total array size)-1.


● // Changing the first element to 90
arr[0] = 90;

4. Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int n = [Link];

5. Accessing and Updating All Array Elements


● All the elements of array can be accessed using Java for Loop.
● Each element in the array is accessed via its index.

Java program to illustrate creating an array of integers, puts some values in


the array and prints each value to standard output
class Geeks {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the elements of the array, first to last(fifth) element


arr[0] = 2;
arr[1] = 4;
arr[2] = 8;
arr[3] = 12;
arr[4] = 16;
// accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i + " : " + arr[i]);
}
}
Output
Element at index 0 : 2
Element at index 1 : 4
Element at index 2 : 8
Element at index 3 : 12
Element at index 4 : 16

JDK vs JRE vs JVM

Aspect JDK JRE JVM

Used to
Used to
develop Executes
run Java
Java Java
application
application bytecode
s
Purpose s

Platform Platform- Platform- JVM is OS-


Dependenc dependent dependent specific, but
Aspect JDK JRE JVM

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.

The following actions occur at runtime as listed below:


● Class Loader
● Byte Code Verifier
● Interpreter
o Execute the Byte Code
o Make appropriate calls to the underlying hardware
JRE ((Java Runtime Environment)
The JRE is an installation package that provides an environment to only
run(not develop) the Java program (or application) onto your machine.
JRE is only used by those who only want to run Java programs that are end-
users of your system.
Note:
● JRE is only for end-users (not for developers).
● JRE is platform-dependent (different versions for different OS)
Working of JRE
When you run a Java program, the following steps occur:
● Class Loader: The JRE’s class loader loads the .class file containing the
bytecode into memory.
● Bytecode Verifier: JRE includes a bytecode verifier to ensure security
before execution
● Interpreter: JVM uses an interpreter + JIT compiler to execute bytecode for
optimal performance
● Execution: The program executes, making calls to the underlying hardware
and system resources as needed.
JVM (Java Virtual Machine)
The JVM is a very important part of both JDK and JRE because it is
contained or inbuilt in both. Whatever Java program you run using JRE or
JDK goes into JVM and JVM is responsible for executing the java program
line by line, hence it is also known as an interpreter.
Note:
● JVM is platform -dependent (different JVMs for window, linux, macOS).
● Bytecode (.class files) is platform-independent (same file runs in any JVM).
● While JVM includes an interpreter, modern implementations primarily use
JIT compilation for faster execution

Java Identifiers

An identifier in Java is the name given to Variables, Classes, Methods,


Packages, Interfaces, etc. These are the unique names used to identify
programming elements. Every Java Variable must be identified with a
unique name.
Example:
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
In the above Java code, we have 5 identifiers as follows:
● Test: Class Name
● main: Method Name
● String: Predefined Class Name
● args: Variable Name
● a: Variable Name
Rules For Naming Java Identifiers
There are certain rules for defining a valid Java identifier. These rules must
be followed, otherwise, we get a compile-time error. These rules are also
valid for other languages like C and C++.
● The only allowed characters for identifiers are all alphanumeric
characters([A-Z],[a-z],[0-9]), '$'(dollar sign) and '_' (underscore). For
example, "geek@" is not a valid Java identifier as it contains a '@', a special
character.
● Identifiers should not start with digits([0-9]). For example, "123geeks" is
not a valid Java identifier.
● Java identifiers are case-sensitive.
● There is no limit on the length of the identifier, but it is advisable to use an
optimum length of 4 - 15 letters only.
● Reserved Words can't be used as an identifier. For example, "int while =
20;" is an invalid statement as a while is a reserved word.
Note: Java has 53 reserved words (including 50 keywords and 3 literals),
that are not allowed to be used as identifiers.

Examples of Invalid Identifiers


My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character
Reserved Words in Java
Any programming language reserves some words to represent functionalities
defined by that language. These words are called reserved words. They can
be briefly categorized into two parts:
● Keywords (50): Keywords define functionalities. The below table shows list
of 50 keywords.
● literals (3): Literals define value. The three literals are, true, false and null.
Identifiers are stored by symbol tables and used during the lexical,
syntax, and semantic analysis phase of compilation.
Java Variables
In Java, variables are containers that store data in memory. Understanding
variables plays a very important role as it defines how data is stored,
accessed, and manipulated.
Key Components of Variables in Java:
A variable in Java has three components, which are listed below:
● Data Type: Defines the kind of data stored (e.g., int, String, float).
● Variable Name: A unique identifier following Java naming rules.
● Value: The actual data assigned to the variable.
Note: There are three types of variables in Java: Local, Instance and Static.
Example: The below example demonstrates the variable declaration in
Java
// Demonstarting how to declare and use a variable in Java

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;

// Displaying the values of variables


[Link]("Age: " + age);
[Link]("Name: " + name);
[Link]("Salary: " + salary);
}
}

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

// Initializing float variable


float si = 5.5f;

// Initializing integer variables


int t = 10;
int s = 20;

// Initializing character variable


char var = 'h';

// Displaying the values of the variables


[Link]("Simple Interest: " + si);
[Link]("Speed: " + s);
[Link]("Time: " + t);
[Link]("Character: " + var);
}
}

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;

// This variable is local to this main method only


[Link]("Local Variable: " + var);
}
}

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].*;

public class Geeks {

public static void main(String[] args)


{
// x is a local variable
int x = 10;

// message is also a local


// variable
String message = "Hello, world!";

[Link]("x = " + x);


[Link]("message = " + message);

if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5";
[Link](result);
}

// Uncommenting the line below will result in a


// compile-time error [Link](result);
for (int i = 0; i < 3; i++) {
String loopMessage
= "Iteration "
+ i; // loopMessage is a local variable
[Link](loopMessage);
}

// Uncommenting the line below will result in a


// compile-time error
// [Link](loopMessage);
}
}

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 {

// Declared Instance Variable


public String geek;
public int i;
public Integer I;
public Geeks()
{
// Default Constructor
// initializing Instance Variable
[Link] = "Sweta Dash";
}

// 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);

// toString() called internally


[Link]("Default value for Integer 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 {

// Declared static variable


public static String geek = "Sweta Dash";

public static void main(String[] args)


{

// geek variable can be accessed without object


// creation Displaying O/P [Link] --> using the
// static variable
[Link]("Geek Name is: " + [Link]);

// 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;

// Using the + (addition) operator


int sum = num1 + num2;
[Link]("The Sum is: "+sum);

// Using the - (subtraction) operator


int diff = num1 - num2;
[Link]("The Difference is: "+diff);

}
}

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)
{

// Arithmetic operators on integers


int a = 10;
int b = 3;

// Arithmetic operators on Strings


String n1 = "15";
String n2 = "25";

// Convert Strings to integers


int a1 = [Link](n1);
int b1 = [Link](n2);

[Link]("a + b = " + (a + b));


[Link]("a - b = " + (a - b));
[Link]("a * b = " + (a * b));
[Link]("a / b = " + (a / b));
[Link]("a % b = " + (a % b));
[Link]("a1 + b1 = " + (a1 + b1));

}
}

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;

// Using unary operators


[Link]("Postincrement : " + (a++));
[Link]("Preincrement : " + (++a));

[Link]("Postdecrement : " + (b--));


[Link]("Predecrement : " + (--b));
}
}

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;

[Link]("a > b: " + (a > b));


[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));
[Link]("a == c: " + (a == c));
[Link]("a != c: " + (a != c));
}
}

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;

[Link]("x && y: " + (x && y));


[Link]("x || y: " + (x || y));
[Link]("!x: " + (!x));
}
}

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 {

public static void main(String[] args)


{
int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
[Link]("Max of three numbers = "+ result);
}
}

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;

[Link]("d & e : " + (d & e));


[Link]("d | e : " + (d | e));
[Link]("d ^ e : " + (d ^ e));
[Link]("~d : " + (~d));
[Link]("d << 2 : " + (d << 2));
[Link]("e >> 1 : " + (e >> 1));
[Link]("e >>> 1 : " + (e >>> 1));
}
}

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));

// Using right 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();

// As obj is of type person, it is not an


// instance of Boy or interface
[Link]("obj1 instanceof Person: "
+ (obj1 instanceof Person));
[Link]("obj1 instanceof Boy: "
+ (obj1 instanceof Boy));
[Link]("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));

// Since obj2 is of type boy,


// whose parent class is person
// and it implements the interface Myinterface
// it is instance of all of these classes
[Link]("obj2 instanceof Person: "
+ (obj2 instanceof Person));
[Link]("obj2 instanceof Boy: "
+ (obj2 instanceof Boy));
[Link]("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}
// Classes and Interfaces used
// are declared here
class Person {
}

class Boy extends Person implements MyInterface {


}

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

Multiple if (marks >= 90) {...} else if


if-else-if conditions (marks >= 80) {...}

switch- Exact value


switch (day) { case 1: ... }
case matching

break Exit loop/switch break;

continue Skip iteration continue;

return Exit method return result;

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)

// part of if block(immediate one statement after if condition)


[Link]("Inside If block");

// always executes as it is outside of if block


[Link]("10 is less than 15");

// This statement will be executed as if considers one statement by


default again below statement is outside of if block
[Link]("I am Not in if");
}
}

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

Example: The below Java program demonstrates the use of nested if


statements to check multiple conditions.
class Geeks {
public static void main(String args[]) {
int i = 10;

// 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:

o Terminate a sequence in a switch statement (discussed above).


o To exit a loop.
o Used as a "civilized" form of goto.
● Continue: Sometimes it is useful to force an early iteration of a loop. That
is, you might want to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration. This is, in
effect, a goto just past the body of the loop, to the loop's end. The continue
statement performs such an action.
Jump Statements Execution Flow
The below diagram demonstrates the flow chart of a "jump Statements
execution flow" in programming.
jump statement
Example: The below Java Program demonstrates how the continue
statement skip the current iteration when a condition is true.
import [Link].*;

class Geeks {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {

// If the number is even, skip and continue


if (i % 2 == 0)
continue;

// If number is odd, print it


[Link](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].*;

public class Geeks {


public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");

if (t)
return;

// Compiler will bypass every statement return


[Link]("This won't execute.");
}
}
Output
Before the return.
Comparison of Decision-Making Statements
if-else vs switch-case
The table below demonstrates the difference between if-else and switch-
case.

Features if-else switch-case

Suitable for condition- Best for exact value


Use Case based checks matching

More readable and


More readable for a
efficient for many
few conditions
Readability cases

Slower for many Faster and optimized


Performanc checks due to multiple for handling many
e conditions cases

Supports ranges and Only supports exact


Flexibility complex conditions matches of values

Best Practices for Decision-Making in Java


● Use switch for multiple exact matches, it improves readability.
● Try avoiding deep nesting.
● Always include default in switch for unexpected cases.
● Prefer if-else for range checks.
Java Loops
Loops in programming allow a set of instructions to run multiple times
based on a condition. In Java, there are three types of Loops, which are
explained below:
1. for loop
The for loop is used when we know the number of iterations (we know how
many times we want to repeat a task). The for statement includes the
initialization, condition, and increment/decrement in one line.
Example: The below Java program demonstrates a for loop that prints
numbers from 0 to 10 in a single line.
// Java program to demonstrates the working of for loop
import [Link].*;

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" };

for (String name : names) {


[Link]("Name: " + name);
}
}
}

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
}

● While loop starts with the checking of Boolean condition. If it evaluated to


true, then the loop body statements are executed otherwise first statement
following the loop is executed. For this reason it is also called Entry control
loop
● Once the condition is evaluated to true, the statements in the loop body are
executed. Normally the statements contain an update value for the variable
being processed for the next iteration.
● When the condition becomes false, the loop terminates which marks the end
of its life cycle.
3. do-while Loop
The do-while loop ensures that the code block executes at least once before
checking the condition.
Example: The below Java program demonstrates a do-while loop that prints
numbers from 0 to 10 in a single line.
// Java program to demonstrates
// the working of do-while loop
import [Link].*;

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) {

// Modifies the loop variable and skips


// the next iteration
i++;
}
[Link](i);
}
}
}
4. Empty Loop Body
An empty loop body occurs when a loop is written to iterate but does not
perform any operations inside the loop. Running a loop without any useful
operations inside it can be confusing.
Example: The below Java program demonstrate Empty loop body.
// Java program to demonstrates Empty loop body
import [Link].*;

class Geeks {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {

// Empty body no operations


}
}
}
No output will be generated for this, because the body of the loop is empty.
Summary Table

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

You might also like