0% found this document useful (0 votes)
17 views41 pages

OOPSJAVA 1 4 Notes OKD

Uploaded by

gg620785
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views41 pages

OOPSJAVA 1 4 Notes OKD

Uploaded by

gg620785
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Java Lecture Notes-1

JDK (Java Development Kit),

JRE(Java Runtime Environment), and

JVM(Java Virtual Machine)


We must understand the differences between JDK, JRE, and JVM before proceeding
further to Java.

JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
because it doesn't physically exist. It is a specification that provides a runtime
environment in which Java bytecode can be executed. It can also run those
programs which are written in other languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK
are platform dependent because the configuration of each OS is different from
each other. However, Java is platform independent. There are three notions of the
JVM specification, implementation, and instance.
1. A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created
The JVM performs following operation:
• Loads code

• Verifies code

• Executes code

• Provides runtime environment

1
JVM provides definitions for the:

• Memory area

• Class file format

• Register set

• Garbage-collected heap

• Fatal error reporting etc.

JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory
area, execution engine etc.

2
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we
run the java program, it is loaded first by the classloader. There are three built-in
classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the super


class of Extension classloader. It loads the rt.jar file which contains all class
files of Java Standard Edition like java.lang package classes, java.net
package classes, java.util package classes, java.io package classes, java.sql
package classes etc.

2. Extension ClassLoader: This is the child classloader of Bootstrap and


parent classloader of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.

3. System/Application ClassLoader: This is the child classloader of


Extension classloader. It loads the classfiles from classpath. By default,
classpath is set to current directory. You can change the classpath using "-
cp" or "-classpath" switch. It is also known as Application classloader.

These are the internal classloaders provided by Java. If you want to create your own
classloader, you need to extend the ClassLoader class.

2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool,
field and method data, the code for methods.

3) Heap
It is the runtime data area in which objects are allocated.

4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a
part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when
its method invocation completes.

3
5) Program Counter Register
PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.

6) Native Method Stack


It contains all the native methods used in the application.

7) Execution Engine
It contains:
1. A virtual processor

2. Interpreter: Read bytecode stream then execute the instructions.

3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT


compiles parts of the byte code that have similar functionality at the same
time, and hence reduces the amount of time needed for compilation. Here,
the term "compiler" refers to a translator from the instruction set of a Java
virtual machine (JVM) to the instruction set of a specific CPU.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to
communicate with another application written in another language like C, C++,
Assembly etc. Java uses JNI framework to send output to the Console or interact
with OS libraries.

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The
Java Runtime Environment is a set of software tools which are used for developing
Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other
files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides
Sun Micro Systems.

4
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:

• Standard Edition Java Platform

• Enterprise Edition Java Platform

• Micro Edition Java Platform


The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java
Application.

5
Components of JDK
Following is a list of primary components of JDK:

This tool is used to run and debug Java applets without a web
appletviewer:
browser.

apt: It is an annotation-processing tool.

extcheck: it is a utility that detects JAR file conflicts.

An IDL-to-Java compiler. This utility generates Java bindings


idlj:
from a given Java IDL file.

It is a Java Access Bridge. Exposes assistive technologies on


jabswitch:
Microsoft Windows systems.

The loader for Java applications. This tool is an interpreter


and can interpret the class files generated by the javac
compiler. Now a single launcher is used for both development
java:
and deployment. The old deployment launcher, jre, no longer
comes with Sun JDK, and instead it has been replaced by this
new java loader.

6
It specifies the Java compiler, which converts source code
javac:
into Java bytecode.

The documentation generator, which automatically generates


javadoc:
documentation from source code comments

The specifies the archiver, which packages related class


jar: libraries into a single JAR file. This tool also helps manage JAR
files.

javafxpackage
It is a tool to package and sign JavaFX applications.
r:

jarsigner: the jar signing and verification tool.

the C header and stub generator, used to write native


javah:
methods.

javap: the class file disassembler.

javaws: the Java Web Start launcher for JNLP applications.

JConsole: Java Monitoring and Management Console.

jdb: the debugger.

jhat: Java Heap Analysis Tool (experimental).

This utility gets configuration information from a running Java


jinfo:
process or crash dump.

Oracle jmap - Memory Map- This utility outputs the memory


jmap: map for Java and can print shared object memory maps or
heap memory details of a given process or core dump.

jmc: Java Mission Control

Java Virtual Machine Process Status Tool lists the


jps: instrumented HotSpot Java Virtual Machines (JVMs) on the
target system.

jrunscript: Java command-line script shell.

It is a utility that prints Java stack traces of Java threads


jstack:
(experimental).

7
jstat: Java Virtual Machine statistics monitoring tool (experimental).

jstatd: jstat daemon (experimental).

keytool: It is a tool for manipulating the keystore.

pack200: JAR compression tool.

It specifies the policy creation and management tool, which


Policytool: can determine policy for a Java runtime, specifying which
permissions are available for code from various sources.

It is a visual tool integrating several command-line JDK tools


VisualVM: and lightweight [clarification needed] performance and
memory profiling capabilities

It generates portable JAX-WS artifacts for invoking a web


wsimport:
service.

It is the part of the Java API for XML Binding (JAXB) API. It
xjc:
accepts an XML schema and generates Java classes.

8
Java Lecture Notes-2

Data Types in Java


Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

1.Primitive data types:The primitive data types include boolean, char,


byte, short, int, long, float and double.

2.Non-primitive data types: The non-primitive data types include Classes,


Interfaces, and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java language.
There are 8 types of primitive data types:
boolean data type
• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type

9
Data Type Default Value Default size
boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data
type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
Boolean flag=false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory
savings is most required. It saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data type.
Byte a=10, byte b=-20

10
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range
lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and
maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A
short data type is 2 times smaller than an integer.
Example:

short s=10000, short r=-5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its
minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its
default value is 0.
The int data type is generally used as a default data type for integral values
unless if there is no problem about memory.
Example:

int a=100000,int b=-200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807 (2 63 -1)(inclusive). Its
minimum value is –9,223,372,036,854,775,808 and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need
a range of values more than those provided by int.

Example:
long a=100000L, long b=-200000L

11
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value
range is unlimited. It is recommended to use a float (instead of double) if you
need to save memory in large arrays of floating point numbers. The float data
type should never be used for precise values, such as currency. Its default value is
0.0F.
Example:

float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just
like float. The double data type also should never be used for precise values, such
as currency. Its default value is 0.0d.
Example:

double d1=12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used
to store characters.
Example:

char letter A='A'

Why char uses 2 byte in java and what is \u0000 ?


It is because java uses Unicode system not ASCII code system. The \u0000 is the
lowest range of Unicode system.

12
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +,
-, *, / etc.
There are many types of operators in Java which are given below:

• Unary Operator,
• Arithmetic Operator,

• Shift Operator,

• Relational Operator,

• Bitwise Operator,

• Logical Operator,

• Ternary Operator and

• Assignment Operator.

Java Operator Precedence


Operator Type Category Precedence
postfix Expr++ expr--
Unary
prefix ++expr –expr +expr -expr ~ !

multiplicative */%
Arithmetic
additive +-

Shift shift <<, >>, >>>

comparison < > <= >= instanceof


Relational
equality == !=

bitwise AND &

bitwise exclusive
^
Bitwise OR

bitwise inclusive
|
OR
logical AND &&
Logical
logical OR ||

Ternary ternary ?:

= += -= *= /= %= &= ^= |= <<= >>=


Assignment assignment
>>>=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:

• incrementing/decrementing a value by one


• negating an expression

• inverting the value of a boolean

Java Unary Operator Example: ++ and --


Public class OperatorExample{
1. public static void main(String args[]){
2. int x=10;
3. System.out.println(x++);//10(11)
4. System.out.println(++x);//12
5. System.out.println(x--);//12(11)
6. System.out.println(--x);//10
7. }}
Output:

10

12

12

10

Java Unary Operator Example 2: ++ and --


1. Public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b+++ b++);//10+11=21
7.
8. }}
Output:

22

21

Java Unary Operator Example: ~ and !


1. Public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10.System.out.println(!d);//true
11.}}
Output:

-11

false

true

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They
act as basic mathematical operations.

Java Arithmetic Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10.}}
Output:

15

50

Java Arithmetic Operator Example: Expression


1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/ 2);
4. }}
Output:

21

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left
side of a specified number of times.

Java Left Shift Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}
Output:
40
80
80
240

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left operand to
right by the number of bits specified by the right operand.

Java Right Shift Operator Example


1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}
Output:

2
5
2

Java Shift Operator Example: >> vs >>>


1. public class OperatorExample{
2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}
Output:

5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &


The logical && operator doesn't check the second condition if the first condition is
false. It checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is
true or false.

public class OperatorExample{

1. public static void main(String args[]){


2. int a=10;
3. int b=5;
4. int c=20;
5. System.out.println(a<b&&a<c);//false && true = false
6. System.out.println(a<b&a<c);//false & true = false
7. }}
Output:

false
false

Java AND Operator Example: Logical && vs Bitwise &


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10.}}
Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is
true. It checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is
true or false.

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10.System.out.println(a);//10 because second condition is not checked
11.System.out.println(a>b|a++<c);//true | true = true
12.System.out.println(a);//11 because second condition is checked
13.}}
Output:

true
true
true
10
true
11

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else statement
and used a lot in Java programming. It is the only conditional operator which takes
three operands.
Java Ternary Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:

2
Another Example:

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:

Java Assignment Operator


Java assignment operator is one of the most common operators. It is used to
assign the value on its right to the operand on its left.

Java Assignment Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}
Output:

14
16

Java Assignment Operator Example


1. public class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10.a/=2;//18/2
11.System.out.println(a);
12.}}

Output:

13
9
18
9

Java Assignment Operator Example: Adding short


1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}
Output:

Compile time error


After type cast:

1. public class OperatorExample{


2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}
Output:

20

Java Keywords

Java keywords are also known as reserved words. Keywords are particular words
that act as a key to a code. These are predefined words by Java so they cannot be
used as a variable or object name or class name.

List of Java Keywords


A list of Java keywords or reserved words are given below:

1.abstract: Java abstract keyword is used to declare an abstract class. An


abstract class can provide the implementation of the interface. It can have
abstract and non-abstract methods.
2.Boolean: Java boolean keyword is used to declare a variable as a boolean
type. It can hold True and False values only.

3.Break: Java break keyword is used to break the loop or switch statement.
It breaks the current flow of the program at specified conditions.

4.Byte: Java byte keyword is used to declare a variable that can hold 8-bit
data values.

5.case:Java case keyword is used with the switch statements to mark blocks
of text.

6.catch:Java catch keyword is used to catch the exceptions generated by try


statements. It must be used after the try block only.

7.char:Java char keyword is used to declare a variable that can hold


unsigned 16-bit Unicode characters

8.class:Java class keyword is used to declare a class.

9.continue:Java continue keyword is used to continue the loop. It continues


the current flow of the program and skips the remaining code at the
specified condition.

10.default:Java default keyword is used to specify the default block of code


in a switch statement.

11.do:Java do keyword is used in the control statement to declare a loop. It


can iterate a part of the program several times.

12.double:Java double keyword is used to declare a variable that can hold


64-bit floating-point number.

13.else:Java else keyword is used to indicate the alternative branches in an


if statement.

14.enum:Java enum keyword is used to define a fixed set of constants.


Enum constructors are always private or default.

15.extends:Java extends keyword is used to indicate that a class is derived


from another class or interface.
16.final:Java final keyword is used to indicate that a variable holds a
constant value. It is used with a variable. It is used to restrict the user from
updating the value of the variable.

17.finally:Java finally keyword indicates a block of code in a try-catch


structure. This block is always executed whether an exception is handled or
not.

18.float:Java float keyword is used to declare a variable that can hold a 32-
bit floating-point number.

19.for:Java for keyword is used to start a for loop. It is used to execute a set
of instructions/functions repeatedly when some condition becomes true. If
the number of iteration is fixed, it is recommended to use for loop.

20.if:Java if keyword tests the condition. It executes the if block if the


condition is true.

21.implements:Java implements keyword is used to implement an


interface.

22.import:Java import keyword makes classes and interfaces available and


accessible to the current source code.

23.instanceof:Java instanceof keyword is used to test whether the object is


an instance of the specified class or implements an interface.

24.int:Java int keyword is used to declare a variable that can hold a 32-bit
signed integer.

25.interface:Java interface keyword is used to declare an interface. It can


have only abstract methods.

26.long:Java long keyword is used to declare a variable that can hold a 64-
bit integer.

27.native:Java native keyword is used to specify that a method is


implemented in native code using JNI (Java Native Interface).

28.new:Java new keyword is used to create new objects.


29.null:Java null keyword is used to indicate that a reference does not refer
to anything. It removes the garbage value.

30.package:Java package keyword is used to declare a Java package that


includes the classes.

31.private:Java private keyword is an access modifier. It is used to indicate


that a method or variable may be accessed only in the class in which it is
declared.

32.protected:Java protected keyword is an access modifier. It can be


accessible within the package and outside the package but through
inheritance only. It can't be applied with the class.

33.public:Java public keyword is an access modifier. It is used to indicate


that an item is accessible anywhere. It has the widest scope among all other
modifiers.

34.return:Java return keyword is used to return from a method when its


execution is complete.

35.short:Java short keyword is used to declare a variable that can hold a 16-
bit integer.

36.static:Java static keyword is used to indicate that a variable or method is


a class method. The static keyword in Java is mainly used for memory
management.

37.strictfp:Java strictfp is used to restrict the floating-point calculations to


ensure portability.

38.super:Java super keyword is a reference variable that is used to refer to


parent class objects. It can be used to invoke the immediate parent class
method.

39.switch:The Java switch keyword contains a switch statement that


executes code based on test value. The switch statement tests the equality
of a variable against multiple values.

40.synchronized:Java synchronized keyword is used to specify the critical


sections or methods in multithreaded code.
41.this:Java this keyword can be used to refer the current object in a
method or constructor.

42.throw:The Java throw keyword is used to explicitly throw an exception.


The throw keyword is mainly used to throw custom exceptions. It is followed
by an instance.

43.throws:The Java throws keyword is used to declare an exception.


Checked exceptions can be propagated with throws.

44.transient:Java transient keyword is used in serialization. If you define


any data member as transient, it will not be serialized.

45.try:Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.

46.void:Java void keyword is used to specify that a method does not have a
return value.

47.volatile:Java volatile keyword is used to indicate that a variable may


change asynchronously.

48.while:Java while keyword is used to start a while loop. This loop iterates a
part of the program several times. If the number of iteration is not fixed, it is
recommended to use the while loop.
Java Lecture Notes-3
Java Control Statements (Control Flow in Java)
Java compiler executes the code from top to bottom. The statements in the code
are executed according to the order in which they appear. However, Java provides
statements that can be used to control the flow of Java code. Such statements are
called control flow statements. It is one of the fundamental features of Java, which
provides a smooth flow of program.
Java provides three types of control flow statements.

• Decision Making statements

◦ if statements

◦ switch statement

• Loop statements

◦ do while loop

◦ while loop

◦ for loop

◦ for-each loop

• Jump statements

◦ break statement

◦ continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which statement to
execute and when. Decision-making statements evaluate the Boolean expression
and control the program flow depending upon the result of the condition provided.
There are two types of decision-making statements in Java, i.e., If statement and
switch statement.

1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the
program is diverted depending upon the specific condition. The condition of the If
statement gives a Boolean value, either true or false. In Java, there are four types
of if-statements given below.
Simple if statement

1. if-else statement

2. if-else-if ladder

3. Nested if-statement
Let's understand the if-statements one by one.

1. Simple if statement:
It is the most basic statement among all control flow statements in Java. It
evaluates a Boolean expression and enables the program to enter a block of code
if the expression evaluates to true.
Syntax of if statement is given below.

if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java
code.
Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:

x + y is greater than 20
2. if-else statement
The if-else statement is an extension to the if-statement, which uses another block
of code, i.e., else block. The else block is executed if the condition of the if-block is
evaluated as false.
Syntax:

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.
Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
}
else {
System.out.println("x + y is greater than 20");
}
}
}
Output:

x + y is greater than 20
3. if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if
statements. In other words, we can say that it is the chain of if-else statements
that create a decision tree where the program may enter in the block of code
where the condition is true. We can also define an else statement at the end of
the chain.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.
Student.java
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}
else if (city == "Noida") {
System.out.println("city is noida");
}
else if(city == "Agra") {
System.out.println("city is agra");
}
else {
System.out.println(city);
}
}
}
Output:

Delhi
4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement


inside another if or else-if statement.
Syntax of Nested if-statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
Student.java

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";

if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}
else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:

Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch
statement contains multiple blocks of code called cases and a single case is
executed based on the variable which is being switched. The switch statement is
easier to use instead of if-else-if statements. It also enhances the readability of
the program.
Points to be noted about switch statement:

• The case variables can be int, short, byte, char, or enumeration. String type
is also supported since version 7 of Java
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the
value of expression. It is optional.

• Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
• While using switch statements, we must notice that the case expression will
be of the same type as the variable. However, it will also be a constant
value.
The syntax to use the switch statement is given below.

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Student.java
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:

2
While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value. The
switch permits only int, string, and Enum type variables to be used.

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly
while some condition evaluates to true. However, loop statements are used to
execute the set of instructions in a repeated order. The execution of the set of
instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.

1.for loop

2.while loop

3.do-while loop
Let's understand the loop statements one by one.
Java for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop
variable, check the condition, and increment/decrement in a single line of code.
We use the for loop only when we exactly know the number of times, we want to
execute the block of code.

for(initialization, condition, increment/decrement) {


//block of statements
}
The flow chart for the for-loop is given below.

Consider the following example to understand the proper functioning of the for
loop in java.

Calculation.java

public class Calculattion {

public static void main(String[] args) {


// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:

The sum of first 10 natural numbers is 55

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable. The
syntax to use the for-each loop in java is given below.

for(data_type var : array_name/collection_name){


//statements
}

Consider the following example to understand the functioning of the for-each loop
in Java.
Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}
Output:

Printing the content of the array names:


Java
C
C++
Python
JavaScript
Java while loop
The while loop is also used to iterate over the number of statements multiple
times. However, if we don't know the number of iterations in advance, it is
recommended to use a while loop. Unlike for loop, the initialization and
increment/decrement doesn't take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the
start of the loop. If the condition is true, then the loop body will be executed;
otherwise, the statements after the loop will be executed.
The syntax of the while loop is given below.

while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.

Consider the following example.


Calculation .java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the
loop statements. When the number of iteration is not known and we have to
execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.

do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop
in Java.
Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the
other part of the program. There are two types of jump statements in Java, i.e.,
break and continue.

Java break statement


As the name suggests, the break statement is used to break the current flow of
the program and transfer the control to the next statement outside a loop or
switch statement. However, it breaks only the inner loop in the case of the nested
loop.
The break statement cannot be used independently in the Java program,
i.e., it can only be written inside the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with
the for loop.
BreakExample.java

public class BreakExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Output:

0
1
2
3
4
5
6
break statement example with labeled for loop
Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
} // end of for loop index by k
} // end of for loop index by j

} // end of for loop index by i


} // end of main
} // end of class
Output:

0
1
2
3
4
5
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas,
it skips the specific part of the loop and jumps to the next iteration of the loop
immediately.
Consider the following example to understand the functioning of the continue
statement in Java.

public class ContinueExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
} //end of if
System.out.println(j);
} // end of for index by j
} // end of for index by i
} // end of main
} // end of class
Output:

0
1
2
3
5
1
2
3
5
2
3
5

You might also like