Java Notes
Java Notes
Module 1
Concepts of Object Oriented programming
In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a
paradigm that provides many concepts, such as
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the type of
response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc.
Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Benefits of OOP
Code Organization
One of the main benefits of OOP as it relates to Java is that it gives developers the
ability to encapsulate data and behavior within classes and objects, keeping a focus
on data integrity and preventing accidental access to information.
Code Reusability
There are several OOP mechanisms Java provides to promote code reusability. By
letting developers extend class functionality and inherit attributes and methods
from parent classes, code redundancy (or duplicate code) can be reduced, as we do
not need to recode the same functionality over and over again
Scalability
Using OOP principles, developers create code that is highly organized and
“placed” into self-contained modules that can be developed and tested
independently from other blocks of code and classes. This modularity makes code
maintenance, bug fixing, and adding features much more efficient, as any code
changes you make to a module are less likely to impact others. Additionally, using
modular code allows for easy integration of new modules, helping programmers to
scale up applications as their requirements grow.
Collaboration
Features of Java
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
High-performance
PGM College Kangazha 5
Java Programming Using Linux
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).
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.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
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.
1. Standalone applications
2. Web applets
1) Standalone Application
A standalone application, also known as a desktop application is a software program
designed in such a way that to run this software program, users don’t need an internet
connection or any server access. Web-based applications need an internet connection,
servers, and any additional resources to run but standalone applications do not require any
additional resources such as an internet connection, server, etc.
2) Web Applets
PGM College Kangazha 7
Java Programming Using Linux
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
For executing any Java program, the following software or application must be properly
installed.
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory.
o Create the Java program
o Compile and run the Java program
To write the simple program, you need to open notepad by start menu -> All Programs ->
Accessories -> Notepad and write a simple program as we have shownbelow:
In order to compile and run the program, you need to open the command prompt by start
menu -> All Programs -> Accessories -> command prompt.
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Output:
Hello Java
Java Tokens
In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation. These statements and
expressions are made up of tokens The tokens are the small building blocks of a Java
program that are meaningful to the Java compiler. Further, these two components contain
variables, constants, and operators.
Types of Tokens
Java token includes the following:
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the
following keywords:
06. case 07. catch 08. char 09. continue 10. default
46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier: Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user. It uses letters, underscores, or a dollar sign as the first character.
The label is also known as a special kind of identifier that is used in the goto statement.
Remember that the identifier name must be different from the reserved keywords. There are
some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid
Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is
defined by the programmer. Once it has been defined cannot be changed. Java provides five
types of literals are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type
23 int
9.86 double
"javatpoint" String
Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators that can be classified
according to the functionality they provide. There are eight types of operators in Java, are as
follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Logical && , ||
Bitwise &,|,^,~
Separators: The separators in Java is also known as punctuators. There are nine
separators in Java, are as follows:
1. separator <= ; | , | . | ( | ) | { | } | [ | ]
o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the
two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates
the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.
Comments: Comments allow us to specify information about the program inside our Java
code. Java compiler recognizes these comments as tokens but excludes it form further
processing. The Java compiler treats comments as whitespaces. Java provides the following
two types of comments:
What is constant?
Constant refers to fixed value that cannot be changed during the execution of the program.
Java does not directly support the constants. Java supports several types of constants.
Types of Constants
There are the following types if constants in Java:
1. Numeric Constants
o Integer Constants
o Real Constants
2. Non-numeric Constants
o Character Constants
o String Constants
Numeric Constants
Numeric constants are the constants that contains numerals. It may also have a leading sign
and decimal point.
Integer Constants
A constant that contains digits (0-9) and does not have decimal point is called integer
constants. By default, it is type of int. There are the following three types of integer
constants:
Decimal Constants: It contains digits between 0 to 9. Note that must not start with 0.
For example, 898, 67, 66.
Octal Constants: It contains digits between 0 to 7 and must begin with 0. For
example, 012, 032, 067.
Real Constants
Numeric constants that have a decimal point are called real or floating-point constants. By
default, the real constants are of double type. We can explicitly mention the type of a
floating-point constant as a float by appending the letter f or F at the end of the constant. For
example, 45f, -0.14f, 5.6F.
o Fractional Form
o Exponential Form
Fractional Form
Non-numeric Constants
A constant that does not contain digits is called non-numeric constants. There are the
following two types of non-numeric constants:
Character Constants
A Character constant is a single alphabet, digit or any special symbol enclosed using single
quotes. For example, 'Y', 'd', '6', '#', '&'.
The maximum length of a character constant is 1 character long. It means that we cannot put
more than one character inside single quotation marks.
String Constants
String constants consist of zero or more characters enclosed in double quotes (""). At the end
of the string, the null character i.e '\0' is automatically placed by the compiler. For
example, "hello", " " (denotes blank space), "111".
The following table denotes the backslash character constants used in Java.
\b Backspace
\f From feed
\n New line
\r Carriage return
\t Horizontal tab
\" Double quote
\' Single quote
\\ Backslash
\v Vertical tab
\a Alert
\? Question mark
\N Octal constant
\xN Hexadecimal constant
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type. A variable is the name of a reserved area allocated in
memory. In other words, it is a name of the memory location. It is a combination of "vary +
able" which means its value can be changed.
There are three types of variables in java: local, instance and static.
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
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.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
The int data type is generally used as a default data type for integral values unless if there is
no problem about memory.
Example:
Example:
1. float f1 = 234.5f
Example:
1. double d1 = 12.3
Example:
Variable Declaration
Java programming language requires variables to operate and handle data. Java creates
several variables as per data format and data types.
There are two ways to declare a variable in Java. The first method is to assign the initial value
to the variable. The second method declares variable without initial value.
1. Data_type variable_name;
o For example: String my_name;
o We do not need to initialize data with a given variable.
o Assign value in any method and display it as an output.
o The way of declaration works inside and outside of the default method.
o The variable data is displayed inside of the default method of the class.
int student_id;
o InputStreamReader
o Console
o Scanner
o DataInputStream etc.
InputStreamReader class
InputStreamReader class can be used to read data from keyboard. It performs two tasks:
BufferedReader class
BufferedReader class can be used to read data line by line by readLine() method.
import java.io.*;
class G5
{
public static void main (String args [])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
Syntax
Example:-
int m=50;
byte n= (byte)m;
long count= (long)m;
Automatic conversion
It is possible to assign a value of one type to a variable of a different type without a cast. Java
does the assigned value automatically.
Example:-
byte b=75;
int a=b;
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:
1. Arithmetic Operator
2. Relational Operator
3. Logical Operator
4. Assignment Operator
5. Increment and decrement Operator
6. Conditional Operator
7. Bitwise Operator
8. Special Operator
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Output:
15
5
50
2
0
Relational Operators
Java Relational Operators are a bunch of binary operators used to check for relations
between two operands, including equality, greater than, less than, etc. They return a
boolean result after the comparison and are extensively used in looping statements as well
as conditional if-else statements and so on. The general format of representing relational
operator is:
Syntax
== Equal to x == y
!= Not equal x != y
Example
int x = 5;
int y = 3;
Logical Operators
You can also test for true or false values with logical operators.
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)
Logical operators are used to determine the logic between variables or values:
Output:
false
false
t Exercises
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
Example
int x = 10;
Example
int x = 10;
x += 5;
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
We can apply these unary operators on all primitive types except Boolean.
Syntax:
++x : which increments the value by 1 of ‘x’ variable.
Example:
class PreIncrement
{
}
Output:
y value is: 11
On the above example, pre increment operator is applied on x operand, here first
the value of x will be incremented by 1 and then the incremented value will be
assigned to the variable y .
As per example, the initial value of ‘x’ is 10. After applying pre-increment
operator on ‘x’ the value of ‘x’ is incremented by 1 (i.e., 11) and that value is
assigned to the variable ‘y’. So that the final value of ‘y’ is 11.
Syntax:
class PostIncrement
{
}
Output:
y value is: 10
Post increment operator is applied on ‘x’, here the case is exact opposite of pre
increment, first the value of variable ‘x’ is assigned to the variable ‘y’ and then the
value of ‘x’ is incremented by 1 .
As per example, the initial value of ‘x’ is 10. After applying post-increment
operator the current values of ‘x’ (i.e, 10) is assigned to y, and then the value
of ‘x’ is incremented by 1. So when displaying variable ‘y’ it is showing as 10.
Syntax:
–x: which decrease the value by 1 of variable ‘x’.
Example:
class PreDecrement {
public static void main(String[] args) {
int x = 10;
int y = --x;
System.out.println("y value is: " + y);
}
}
Output:
y value is: 9
Pre decrement operator is applied on ‘x’, first, the value of ‘x’ will be decremented
by 1 and then the decremented value will be assigned to the variable ‘y’.
As per example, the initial value of ‘x’ is 10. After applying pre decrement
operator on ‘x’, the value of ‘x’ is decremented by 1 (i.e., 9) and that value is
assigned to the variable ‘y’. So, when we display the variable ‘y’ it is showing as 9.
class PostDecrement {
public static void main(String[] args) {
int x = 10;
int y = x--;
System.out.println("y value is: " + y);
}
}
Output:
y value is: 10
Post decrement operator is applied on ‘x’, here the case is the complete opposite of
pre decrement operator, first, the value of variable ‘x’ is assigned to the
variable ‘y’ and then the value of ‘x’ is decremented by 1.
Syntax:
As per example, the initial value of ‘x’ is 10. After applying post decrement
operator on variable ‘x’ the current values of ‘x’ (i.e, 10) is assigned to ‘y’, and
then the value of ‘x’ is decremented by 1. So when displaying the value of ‘y’ it is
showing as 10.
Syntax:
The above statement states that if the condition returns true, expression1 gets executed, else
the expression2 gets executed and the final result stored in a variable.
TernaryOperatorExample.java
Output
Value of y is: 90
Value of y is: 61
Bitwise Operators
Bitwise operators are used to performing the manipulation of individual bits of a
number. They can be used with any integral type (char, short, int, etc.). They are
used when performing update and query operations of the Binary indexed trees. .
o Bitwise AND
o Bitwise exclusive OR
o Bitwise inclusive OR
o Bitwise Compliment
o Bit Shift Operators
Bitwise Compliment ~ ~ op
Special Operators
Java supports some special operators of interest such as instanceof operator and member
selection operator (.).
instanceof operator
The java 'instanceof' operator is used to test whether an object is an instance of a specified
type (class or sub - class or visual interface).
'instanceof' in Java is also known as the type comparison operator because it compares the
instances with type. It returns true or false. If we apply the 'instanceof' operator with a
variable value, the value returned is false.
Example:-
Is true if the object person belongs to the class student; otherwise it is false.
Dot operator
The dot operator(.) is userd to access the instance variables and methods of class objects.
Example:-
Control Statements
Branching statements
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.
o if statements
o switch statement
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
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.
if(condition)
{
statement 1; //executes when condition is true
}
Example:-
Student.java
Student.java
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
}
Student.java
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.
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
}
Student.java
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.
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
}
}
Student.java
}
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.
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
Output:
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
Example:-
Calculation.java
}
}
Output:
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.
while(condition)
{
//looping statements
}
The flow chart for the while loop is given in the following image.
Calculation .java
Output:
0
2
4
6
8
10
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
Output:
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.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
Output:
0
1
2
3
4
5
6
Calculation.java
System.out.println(k);
if(k==5)
{
break a;
}
}
}
}
}
}
Output:
0
1
2
3
4
5
Consider the following example to understand the functioning of the continue statement in
Java.
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Labeled loops
A label is a valid variable name that denotes the name of the loop to where the control of
execution should jump. To label a loop, place the label before the loop with a colon at the
end. Therefore, a loop with the label is called a labeled loop.
Example:-
…………………..
…………………….
……………….
Block1: {
……….
…………
Block2: {
……….
……….
……..
……
Example:
LabeledForLoop.java
Output:
123456789
123456789
123456789
123456789
123456789