0% found this document useful (0 votes)
12 views65 pages

Chapter 1-jpr Full

This document provides an overview of basic syntactical concepts in Java, focusing on Object-Oriented Programming (OOP) principles such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It discusses the history and features of Java, highlighting its platform independence, robustness, and security. Additionally, it outlines the advantages of using Java for application development and its environment, including the Java Development Kit (JDK).

Uploaded by

karpevaishnavi08
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)
12 views65 pages

Chapter 1-jpr Full

This document provides an overview of basic syntactical concepts in Java, focusing on Object-Oriented Programming (OOP) principles such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It discusses the history and features of Java, highlighting its platform independence, robustness, and security. Additionally, it outlines the advantages of using Java for application development and its environment, including the Java Development Kit (JDK).

Uploaded by

karpevaishnavi08
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
You are on page 1/ 65

Unit-1 Basic Syntactical Concepts in Java

CO 1 Develop programs using Object Oriented Methodology in Java.

Introduction to object-oriented paradigm


The major objective of object-oriented approach is to eliminate some of the flaws encountered in the
procedural approach. 00P treats data as a critical element in the program development and does not allow it to
flow freely around the system. It ties data more closely to the functions that operate on it and protects it from
unintentional modification by other functions.

OOP allows us to decompose a problem into a number of entities called Objects and then build data and
functions (known as methods in Java) around these entities. The combination of data and methods make up an
object (see Fig.). The data of an object can be accessed only by the methods associated with that object.
However, methods of one object can access the methods of other objects.
Some of the features of object-oriented paradigm are:

 Emphasis is on data rather than procedure.


 Programs are divided into what are known as Objects.
 Data structures are designed such that they characterize the objects.
 Methods that operate on the data of an object are tied together in the data structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through methods.
 New data and methods can be easily added whenever necessary.
 Follows bottom-up approach in program design.

Basic Concepts of Object Oriented Programming


There are some basic concepts of object oriented programming as follows:
1. Object
2. Class
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism

Classes and Objects

Class: A class in java is the building block, that leads to Object-Oriented programming. It is a user-defined data
type, which holds its own data members and member functions, which can be accessed and used by creating an
instance of that class. A java class is like a blueprint for an object.

For Example:
Consider the Class of Cars. There may be many cars with different names and brand but all of them will share
some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is
the class and wheels, speed limits, mileage are their properties.

 A Class is a user defined data-type which has data members and member functions.
 Data members are the data variables and member functions are the functions used to manipulate these
variables and together these data members and member functions defines the properties and behavior of
the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage etc and member functions
can be apply brakes, increase speed etc.

An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated
(i.e. an object is created) memory is allocated.

Class is also can be used to achieve user defined data types.


In real world many examples of object and class like dog, cat, and cow are belong to animal's class. Each
object has state and behaviors. For example a dog has state:- color, name, height, age as well as behaviors:-
barking, eating, and sleeping.

Abstraction in Java
Data abstraction refers to providing only essential information to the outside world and hiding their
background details, i.e., to represent the needed information in program without presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation of interface and
implementation.
Hiding of data is known as data abstraction. In object oriented programming language this is implemented
automatically while writing the code in the form of class and object.
Real Life Example of Abstraction in Java
Abstraction shows only important things to the user and hides the internal details, for example, when we ride
a bike, we only know about how to ride bikes but can not know about how it work? And also we do not
know the internal functionality of a bike.
Another real life example of Abstraction is ATM Machine; All are performing operations on the ATM
machine like cash withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal
details about ATM.

Encapsulation in Java

Encapsulation is a process of wrapping of data and methods in a single unit is called encapsulation.
Encapsulation is achieved in java language by class concept.
Combining of state and behavior in a single container is known as encapsulation. In java language
encapsulation can be achieve using class keyword, state represents declaration of variables on attributes and
behavior represents operations in terms of method.
Advantage of Encapsulation
The main advantage of using of encapsulation is to secure the data from other methods, when we make a data
private then these data only use within the class, but these data not accessible outside the class.
Real life example of Encapsulation in Java
The common example of encapsulation is capsule. In capsule all medicine are encapsulated in side capsule.

Benefits of encapsulation
 Provides abstraction between an object and its clients.
 Protects an object from unwanted access by clients.
 Example: A bank application forbids (restrict) a client to change an Account's balance.

Polymorphism in Java
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take
more than on form..
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
Polymorphism is not a programming concept but it is one of the principal of OOPs. For many objects
oriented programming language polymorphism principle is common but whose implementations are varying
from one objects oriented programming language to another object oriented programming language.
Real life example of polymorphism in Java
Suppose if you are in class room that time you behave like a student, when you are in market at that time you
behave like a customer, when you at your home at that time you behave like a son or daughter, Here one
person present in different-different behaviors.

Real life example of polymorphism in Java


You can see in the below Images, you can see, Man is only one, but he takes multiple roles like - he is a dad
to his child, he is an employee, a salesperson and many more. This is known as Polymorphism.
Inheritance in Object Oriented Programming

The process of obtaining the data members and methods from one class to another class is known
as inheritance. It is one of the fundamental features of object-oriented programming.

Important points

 In the inheritance the class which is give data members and methods is known as base or super or parent
class.

 The class which is taking the data members and methods is known as sub or derived or child class.

Real Life Example of Inheritance in C++

The real life example of inheritance is child and parents, all the properties of father are inherited by his son.

Diagram
In the above diagram data members and methods are represented in broken line are inherited from faculty
class and they are visible in student class logically.

Advantage of inheritance

If we develop any application using this concept than that application have following advantages,

 Application development time is less.

 Application take less memory.

 Application execution time is less.

 Application performance is enhance (improved).

 Redundancy (repetition) of the code is reduced or minimized so that we get consistence results and
less storage cost.
Differences between C, C++ and Java

History of Java
Java language developed by company Sun Microsystems and the creator is James Gosling.
Story behind development of Java

Sun Microsystems Started by a group of the students who are studing in Standard University. These people
found the problem in their room with electronic consumable remote. That means one electronic consumable
control doesn't work on another electronics consumable. These people want to develop a common remote
control which is controlling all the electronic consumables so they contact James Gosling and requested for
the projects. Sun Microsystems started by a group of students out of them one person also Indian whose
name Vinode Khosla.
James Gosling and his team members given the project name as Green started in the year 1990 and common
remote control completed in the year 1992.
The James Gosling team develops a new language called as OAK But this name is already selected by any
other company renamed as Java, but Java has no meaning representation of Island in Indonesia. The
unofficial abbreviation of Java is Just Another Virtual Analyzer (JAVA).
Java Version History
Now a day 8 versions of java are released, which is listed below with realizing date.
 JDK Alpha and Beta (1995)
 JDK 1.0 (23rd Jan, 1996)
 JDK 1.1 (19th Feb, 1997)
 J2SE 1.2 (8th Dec, 1998)
 J2SE 1.3 (8th May, 2000)
 J2SE 1.4 (6th Feb, 2002)
 J2SE 5.0 (30th Sep, 2004)
 Java SE 6 (11th Dec, 2006)
 Java SE 7 (28th July, 2011)
 Java SE 8 (18th March, 2014)
Overview of Java
Java is one of the programming language or technology used for developing web applications. Java language
developed at SUN Micro Systems in the year 1995 under the guidance of James Gosling and there team.
Originally SUN Micro Systems is one of the Academic university (Standford University Network)
Whatever the software developed in the year 1990, SUN Micro Systems has released on the name of oak,
which is original name of java (scientifically oak is one of the tree name). The OAK has taken 18 months to
develop.
The oak is unable to fulfill all requirements of the industry. So James Gosling again reviews this oak and
released with the name of java in the year 1995. Scientifically java is one of the coffee seed name.
JAVA FEATURES
As we know that the Java is an object oriented programming language developed by Sun Microsystems of USA in
1991. Java is first programming language which is not attached with any particular hardware or operating system.
Program developed in Java can be executed anywhere and on any system.
Features of Java are as follows:
1. Compiled and Interpreted
2. Platform Independent and portable
3. Object- oriented
4. Robust and secure
5. Distributed
6. Familiar, simple and small
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible

Compiled and interpreted

1. Simple, small and Familiar

It is simple because of the following factors:


 Java is Simple because Java doesn’t support a complex concept like a pointer so that Java
program execution time will be less as well as less development time.
 Java is Simple because Java added concept call garbage collation to destroy the useless
object which free memory.
 Java is Simple because Java provides user-friendly syntax.
 It is free from Operator overloading.
 It has Rich set of API (application programming interface).
 It removes multiple inheritances with the classes.
It is Small because
Java can be considered both a compiled and an interpreted language because its source code is first compiled
into a byte-code (or Intermediate code). This byte-code runs on the Java Virtual Machine (JVM), which is
usually a software-based interpreter. The use of compiled byte-code allows the interpreter (the virtual
machine) to be small and efficient (and nearly as fast as the CPU running native, compiled code).

Java is familiar because: It has a base of Native languages like C and C++ and contains many features of
these languages. It removes the drawbacks, complexities and confusing elements of C/C++. So if you
have good knowledge of C/C++, you will find Java familiar and easy to understand.

2. Object Oriented
Java is truly object-oriented language. Java supports major Object-Oriented programming features like
Encapsulation, Abstraction, and Inheritance. In Java, almost everything is an Object. All program code and
data exist in objects and classes. Java comes with an extensive set of classes; organize in packages that can be
used in program by Inheritance.

For example, we cannot develop an executable program in Java without making use of the class. This indicates
that Java very strictly applies the principle of Encapsulation.

3. Compiled and interpreted


Basically a computer language is either compiled or interpreted. Java comes together both these approach thus
making Java a two-stage system.

Java compiler translates Java code to Bytecode instructions and

Java Interpreter generate machine code that can be directly executed by machine that is running the Java
program..

4. Platform Independent
A programming language or technology is said to be platform independent if and only if which can run on all
available operating systems with respect to its development and compilation(Platform represents O.S)..

Java is a platform independent programming language, because when you install jdk software on your system
then automatically JVM are installed on your system. For every operating system separate JVM is available
which is capable to read the .class file or byte code. When we compile your Java code then .class file is
generated by compiler(Javac) these codes are readable by JVM and every operating system have its own JVM
so JVM is platform dependent but due to JVM java language is become platform independent.
Java Virtual Machine (JVM), which is usually a software-based interpreter.

5. Portable
Portability means java programs can be easily moved from one computer system to another and anywhere.
That is WORE means “Write once run anywhere”.
If any language supports platform independent feature known as portable.
Changes and upgrades in operating systems, processors and system resources will not force any alteration in
Java programs and make the language portable.
This is reason why Java has become a trendy language for programming on Internet which interconnects
different kind of systems worldwide.

The languages like C, CPP, Pascal are treated as non-portable language. It is a portable language.
According to SUN microsystem. Java supports the feature portability..

6. Robust and secure


Java is a most strong language which provides many securities to make certain reliable code.
 It provides certain safeguards such as check data type at the time of compilation and interpretation.
 It is design as garbage –collected language, which helps the programmers virtually to handle
all memory management problems.
 Java also includes the concept of exception handling, which detain serious errors and reduces all
kind of threat of crashing the system.
Security is an important feature of Java and this is the strong reason that programmer use this language for
programming on Internet. The absence of pointers in Java ensures that programs cannot get right of entry
to memory location without proper approval.
7. Distributed
Java is called as Distributed language for construct applications on networks which can contribute both data and
programs. Java is distributed because it encourages users to create distributed applications.

In Java, we can split a program into many parts and store these parts on different computers. A Java
programmer sitting on a machine can access another program running on the other machine.

This feature in Java gives the advantage of distributed programming, which is very helpful when we develop
large projects. Java helps us to achieve this by providing the concept of RMI (Remote Method
Invocation) and EJB (Enterprise JavaBeans).

Note: In this architecture same application is distributed in multiple server system.

8. Multithreaded and Interactive


Multithreaded means managing multiple tasks simultaneously. Java maintains multithreaded programs. That
means we need not wait for the application to complete one task before starting next task. This feature is
helpful for graphic applications.
Java is interactive because its code supports effective CUI (Character User Interface) and GUI (Graphical
User Interface) programs. It greatly improves the interactive performance of graphical applications.

9. Dynamic and Extensible

Java is dynamic and extensible means with the help of OOPs, we can add classes and add new methods to
classes, creating new classes through subclasses. This makes it easier for us to expand our own classes and
even modify them.
Java gives the facility of dynamically linking new class libraries, methods, and objects. It is highly dynamic
as it can adapt to its evolving environment.

Java even supports functions written in other languages such as C and C++ to be written in Java
programs. These functions are called “native methods”. These methods are dynamically linked at runtime.
10. High performance
It have high performance because of following reasons;
 This language uses Bytecode which is faster than ordinary pointer code so Performance of this language
is high.
 Garbage collector, collect the unused memory space and improve the performance of the application.
 It has no pointers so that using this language we can develop an application very easily.
 It support multithreading, because of this time consuming process can be reduced to executing
the program.
Java Environment:
Java environment includes a number of development tools, classes and methods. The development tools
are p art of the system known as Java Development Kit (JDK) and the classes and methods are part of
the Java Standard Library (JSL), also known as the Application Programming Interface (API). Java
Development kit (JDK) –
The JDK comes with a set of tools that are used for developing and running Java program. It includes:
1. Appletviewer( It is used for viewing the applet)
2. Javac(It is a Java Compiler)
3. Java(It is a java interpreter)
4. Javap(Java diassembler,which convert byte code into program description)
5. Javah(It is for java C header files)
6. Javadoc(It is for creating HTML document)
7. Jdb(It is Java debugger)
Create First program
Step 1:-Open the Notepad and write the code

Example
class First
{
public static void main(String[] args)
{
System.out.println("Hello Java");
System.out.println("My First Java Program");
}
}

. Parameters used in First Java Program


Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
o class keyword is used to declare a class in java.
o public keyword is an access modifier which represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main method is executed by the JVM, so it doesn't require to create an object to invoke
the main method. So it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args is used for command line argument. We will learn it later.
o System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class. We will learn about the internal working
of System.out.println statement later.
o Save Java Program

o oSyntax:
o o o o o
o Filename.java
Path where u save u r file[Different for everyone]

Path: C:\Program Files\Java\jdk1.8.0_162\bin Example:

First.java

o Compile Java Program


Syntax:
Javac Filename.java
Example:
Javac First.java

o Compile and Execute Java Code


To compile: javac First.java
To execute: java First

o Note: Here Javac and Java are called tools or application programs or exe files developed by sun
micro system and supply as a part of jdk 1.5/1.6/1.7 in bin folder. Javac is used for compile the java
program and java is used for run the java program.

Step 2:Open the command prompt and set the path as

Step 3:
If the path is set u will get the following

Step 4:
Compile the code with javac

Step 5:
Interpret the code with java

JDK: Java Development Kit


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.

Components of JDK

Following is a list of primary components of JDK:


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

java: 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 and deployment. The old deployment
launcher, jre, no longer
comes with Sun JDK, and instead it has been replaced by this new
java loader.

javac: It specifies the Java compiler, which converts source code


into Java bytecode.

javadoc: The documentation generator, which automatically generates


documentation
from source code comments

javah: the C header and stub generator, used to write native methods.

jdb: the debugger.

Object and class in Java

Class: Class is a blue print which is containing only list of variables and method
and no memory is allocated for them. A class is a group of objects that has
common properties.
A class in java contains:
 Data Member
 Method
 Constructor
 Block
 Class and Interface

Object: Object is a instance of class, object has state and behaviors. Object is the
physical as well as logical entity where as class is the only logical entity.

An Object in java has three characteristics:


 State
 Behavior
 Identity
State: Represents data (value) of an object.
Behavior: Represents the behavior (functionality) of an object such as deposit,
withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. But,it is used internally by the JVM to
identify each object uniquely.
Class is also can be used to achieve user defined data types.
Real life example of object and class
In real world many examples of object and class like dog, cat, and cow are belong
to animal's class. Each object has state and behaviors. For example a dog has
state:- color, name, height, age as well as behaviors:- barking, eating, and

sleeping.
Vehicle class

Car, bike, truck these all are belongs to vehicle class. These Objects have also
different different states and behaviors. For Example car has state - color, name,
model, speed, Mileage. as well as behaviors - distance travel
Difference between Class and Object in Java
Class Object

Class is a container which


1 collection of variables object is a instance of class
and methods.
Sufficient memory space will
No memory is allocated at the be allocated for all the
2
time of declaration variables of class at the time
of declaration.
One class definition should
For one class multiple objects
3 exist only once in the
can be created.
program.

Syntax to declare a Class


class Class_Name
{
data member; method;
}
Object Declaration Syntax:
Class_Name object_name=new Class_Name();//new keyword which is used to
//allocate a memory for object in java

Syntax for Declaration of Object


class Student
{
}

Objcet for class Student

Syntax Declaration of Object


Student s;
Define object
s=new Student();

OR

Student s-=new Student();

Simple Example of Object and Class


In this example, we have created a Employee class that have two data members
eid and ename. We are creating the object of the Employee class by new keyword
and printing the objects value.
Example
class Employee
{
int eid; // data member (or instance variable)
String ename; // data member (or instance variable)
eid=101;
ename="Hitesh";
public static void main(String args[])
{
Employee e=new Employee(); // Creating an object of class Employee
System.out.println("Employee ID: "+e.eid);
System.out.println("Name: "+e.ename);
}
}

Output
Employee ID: 101
Name: Hitesh

Note: A new keyword is used to allocate memory at runtime, new keyword is


used for create an object of class, later we discuss all the way for create an object
of class.

Java Tokens
Java Tokens are the smallest individual building block or smallest unit of a Java program. The
Java compiler uses it for constructing expressions and statements. Java program is a
collection of different types of tokens, comments, and white spaces.
When we write a program, we need different important things. We require language tokens,
white spaces, and formats
There are various tokens used in Java:

 Reserved Keywords
 Identifiers
 Literals
 Operators
 Separators
 White space is also considered as a token.

Java Keywords

Keywords are words that have already been defined for Java compiler. They have special
meaning for the compiler. Java Keywords must be in your information because you can not use
them as a variable, class or a method name.

Java Reserved Keywords List

You can't use keyword as identifier in your Java programs, its reserved words in Java library
and used to perform an internal operation.
Note:
true, falseand nu are not reserved words but cannot be used as identifiers, because it is literals
of built-in types.
Java operators

Java operators are symbols that are used to perform mathematical or logical manipulations.
Java is rich with built-in operators.
Operators are tokens that perform some calculations when they are applied to variables.
There are many types of operators available in Java such as:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Conditional Operator
 Increment and decrement operator
 instanceof Operator
 Member Selection or Dot Operator

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.
For example: _hi123,$a,I etc
o The whitespace cannot be included in the identifier.
For example :

o Identifiers are case sensitive.


Some valid identifiers are:
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

false, true Boolean

'K', '7', '-' Char


"javatpoint" String

Null any reference type

Separator in java:
Let's discuss what is a separator in java and what are all the types of separators available in
java. let's get started. A separator is a symbol that is used to separate a group of code from one
another is called as separators in java. In java, there are few characters that are used as a
separator. The most commonly used separator is a semicolon. As we have seen it is used to
terminate the statement.

For example, items in the list are separated by commas in a sentence like lists of items in a
sentence. In Java language, it has six types of separators. They are:

S.NO MEANING SYMBOL PURPOSE


1 Parentheses () Used to enclose an argument in the method definition.
Also used for defining the expression in control
statements.
2 Braces {} Used to define a block of code for classes and methods.
Also used to contain the values of arrays.
3 Brackets [] Used to declare an array type. Also used when
dereferencing array values.
4 Semicolon ; Used to separate or terminate the statement.
5 Comma , Used to separate identifiers (or) Variable declarations.
Also used to chain statements together inside a for a
statement.
6 Period . Used to separate package names from sub-packages and
classes. Also used to separate a variable or method from a
reference variable.
Data Types in Java
Data type specifies the size and type of values that can be stored in an identifier. The Java
language is rich in its data types. Different data types allow you to select the type appropriate to
the needs of the application.

Data types in Java are classified into two types:

1. Primitive—which include Integer, Character, Boolean, and Floating Point.


2. Non-primitive—which include Classes, Interfaces, and Arrays.

Primitive Data Types

1. Integer

Integer types can hold whole numbers such as 123 and −96. The size of the values that can be
stored depends on the integer type that we choose.

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.
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 one = false
Byte Data Type

The byte data type is an example of primitive data type. It is an 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.
Example: byte a = 10, byte b = -20

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,808and 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

Type Size Range of values that can be stored

byte 1 byte −128 to 127

short 2 bytes −32768 to 32767

int 4 bytes −2,147,483,648 to 2,147,483,647

9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,755,807

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
Type Size Range of values that can be stored

float 4 bytes 3.4e−038 to 3.4e+038

double 8 bytes 1.7e−308 to 1.7e+038

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 letterA = 'A'

Java Variables

A variable is a container which holds the value while the Java program is executed. A variable
is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
There are two types of data types in Java: primitive and non-primitive.

Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.

1. int data=50;//Here data is variable


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.
A local variable cannot be defined with "static" keyword.
Example:
int a;
void add(int b)(here variable b is a local variable)
{
a=b;
}

2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. It is not
declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
Example:
int c=20;
[Here c is an instance variable]

3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of
static variable and share among all the instances of the class. Memory allocation for static variable happens
only once when the class is loaded in the memory.

Example to understand the types of variables in java


1. class A{
2. int data=50;//instance variable
3. static int m=100;//static variable
4. void method(){
5. int n=90;//local
variable 6. }
7. }//end of class
Type Casting in Java
In Java, type casting is a method or process that converts a data type into another data type in both ways
manually and automatically. The automatic conversion is done by the compiler and manual conversion
performed by the programmer. In this section, we will discuss type casting and its types with proper examples.

Type casting
Convert a value from one data type to another data type is known as type casting.
Types of Type Casting
There are two types of type casting:
o Widening Type Casting
o Narrowing Type
Casting Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known as implicit
conversion or casting down. It is done automatically. It is safe because there is no chance to lose data. It takes
place when:
o Both data types must be compatible with each other.
o The target type must be larger than the source type.

1. byte -> short -> char -> int -> long -> float -> double

For example, the conversion between numeric data type to char or Boolean is not done automatically. Also, the
char and Boolean data types are not compatible with each other. Let's see an example.

WideningTypeCastingExample.java
1. public class WideningTypeCastingExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 7;
6. //automatically converts the integer type into long type
7. long y = x;
8. //automatically converts the long type into float type
9. float z = y;
10. System.out.println("Before conversion, int value "+x);
11. System.out.println("After conversion, long value "+y);
12. System.out.println("After conversion, float value "+z);
13. }
14. }
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is:
7.0
In the above example, we have taken a variable x and converted it into a long type. After that, the long type is
converted into the float type.

Narrowing Type Casting

Converting a higher data type into a lower one is called narrowing type casting. It is also known as explicit
conversion or casting up. It is done manually by the programmer. If we do not perform casting then the
compiler reports a compile-time error. There is loss of data in this type.
Syntax
dataType variableName = (dataType) variableToConvert;
Example
double calculatedMark = 87.6;
int finalGrade = (int)calculatedMark; //will return 87

1. double -> float -> long -> int -> char -> short -> byte

Let's see an example of narrowing type casting.


In the following example, we have performed the narrowing type casting two times. First, we have converted
the double type into long data type after that long data type is converted into int type.
NarrowingTypeCastingExample.java

1. public class NarrowingTypeCastingExample


2. {
3. public static void main(String args[])
4. {
5. double d = 166.66;
6. //converting double data type into long data type
7. long l = (long)d;
8. //converting long data type into int data type
9. int i = (int)l;
10. System.out.println("Before conversion: "+d);
11. //fractional part lost
12. System.out.println("After conversion into long type: "+l);
13. //fractional part lost
14. System.out.println("After conversion into int type: "+i);
15. }
16. }
Operators in Java

Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation.
Java supports following lists of operators.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Ternary or Conditional Operators

Arithmetic Operators
Given table shows all the Arithmetic operator supported by Java Language. Lets suppose variable A hold 8
and B hold 3.
Java arithmetic operator takes numerical values as operands, operates on them, and returns a single numerical
value. Java Arithmetic operators are used for simple mathematic operations, they are
 Addition (+)
 Subtraction (-)
 Multiplication (*)
 Division (/)
 Modulus (%)
Operator Example (int A=8, B=3) Result

+ A+B 11

- A-B 5

* A*B 24

/ A/B 2

% A%4 0
Relational Operators
Which can be used to check the Condition, it always return true or false. Lets suppose variable A hold 8
and B hold 3.
Operators Example (int A=8, B=3) Result
< A<B False

<= A<=10 True

> A>B True

>= A<=B False

== A== B False

!= A!=(-4) True
Logical Operator
Which can be used to combine more than one Condition?. Suppose you want to combined two
conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is
Logical Operator.
Example (int A=8, B=3, C=-
Operator Result
10)

&& (A<B) && (B>C) False

|| (B!=-C) || (A==B) True

! !(B<=-A) True
Truth table of Logical Operator
C1 C2 C1 && C2 C1 || C2 !C1 !C2

T T T T F F

T F F T F T

F T F T T F

F F F F T T
Assignment operators
Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result

+= A+=B or A=A+B 11

-= A-=3 or A=A+3 5

*= A*=7 or A=A*7 56

/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3

=a=b Value of b will be assigned to a

Ternary operator

If any operator is used on three operands or variable is known as ternary operator. It can be represented with "
?: "
Ternary Operator in java
If any operator is used on three operands or variable is known as Ternary Operator. It can be represented
with ? : . It is also called as conditional operator
The ternary operator is an operator that takes three arguments. The first argument is a comparison argument,
the second is the result upon a true comparison, and the third is the result upon a false comparison. Ternary
operator is shortened way of writing an if-else statement.
Ternary operator is a?b:c it say that the condition a is true b will be executed else c will be executed.

Advantage of Ternary Operator


Using ?: reduce the number of line codes and improve the performance of application.
Syntax
expression-1 ? expression-2 : expression-3

In the above symbol expression-1 is condition and expression-2 and expression-3 will be either value or
variable or statement or any mathematical expression. If condition will be true expression-2 will be execute
otherwise expression-3 will be executed.
Bitwise Operator in Java
In Java, an operator is a symbol that performs the specified operations. In this section, we will discuss only
the bitwise operator and its types with proper examples.
Types of Bitwise Operator
There are six types of the bitwise operator in Java:
o Bitwise AND
o Bitwise exclusive OR
o Bitwise inclusive OR
o Bitwise Compliment
o Bit Shift Operators

Operators Symbol Uses


Bitwise AND & op1 & op2

Bitwise exclusive OR ^ op1 ^ op2

Bitwise inclusive OR | op1 | op2

Bitwise Compliment ~ ~ op

Bitwise left shift << op1 << op2

Bitwise right shift >> op1 >> op2

Unsigned Right Shift >>> op >>> number of places to


Operator shift
Let's explain the bitwise operator in detail.
Bitwise AND (&)
It is a binary operator denoted by the symbol &. It returns 1 if and only if both bits are 1, else returns 0.

Let's use the bitwise AND operator in a Java program.


BitwiseAndExample.java
1. public class BitwiseAndExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 9, y = 8;
6. // bitwise and
7. // 1001 & 1000 = 1000 = 8
8. System.out.println("x & y = " + (x & y));
9. }
10. }
Output
x&y=8
Bitwise exclusive OR/XOR (^)
It is a binary operator denoted by the symbol ^ (pronounced as caret). It returns 0 if both bits are the same, else
returns 1.
Let's use the bitwise exclusive OR operator in a Java program.
BitwiseXorExample.java
1. public class BitwiseXorExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 9, y = 8;
6. // bitwise XOR
7. // 1001 ^ 1000 = 0001 = 1
8. System.out.println("x ^ y = " + (x ^ y));
9. }
10. }
Output
x^y=1
Bitwise inclusive OR (|)
It is a binary operator denoted by the symbol | (pronounced as a pipe). It returns 1 if either of the bit is 1, else
returns 0.

Let's use the bitwise inclusive OR operator in a Java program.


BitwiseInclusiveOrExample.java
1. public class BitwiseInclusiveOrExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 9, y = 8;
6. // bitwise inclusive OR
7. // 1001 | 1000 = 1001 = 9
8. System.out.println("x | y = " + (x | y));
9. }
10. }
Output
x|y=9
Bitwise Complement (~)
It is a unary operator denoted by the symbol ~ (pronounced as the tilde). It returns the inverse or complement of
the bit. It makes every 0 a 1 and every 1 a 0.
Let's use the bitwise complement operator in a Java program.
BitwiseComplimentExample.java
1. public class BitwiseComplimentExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 2;
6. // bitwise compliment
7. // ~0010= 1101 = -3
8. System.out.println("~x = " + (~x));
9. }
10. }
Output
~x = -3
Bit Shift Operators
Shift operator is used in shifting the bits either right or left. We can use shift operators if we divide or multiply
any number by 2. The general format to shift the bit is as follows:
1. variable << or >> number of places to shift;
For example, if a=10
1. a>>2; //shifts two bits
2. a>>4; //shifts 4 bits
Java provides the following types of shift operators:
o Signed Right Shift Operator or Bitwise Right Shift Operator
o Unsigned Right Shift Operator
o Signed Left Shift Operator or Bitwise Left Shift Operator
Note: Java does not support the unsigned left shift operator (<<<).
Signed Right Shift Operator (>>)
The signed right shift operator shifts a bit pattern of a number towards the right with a specified number of
positions and fills 0. The operator is denoted by the symbol >>. It also preserves the leftmost bit (sign bit).
If 0 is presented at the leftmost bit, it means the number is positive. If 1 is presented at the leftmost bit, it means
the number is negative.
In general, if we write a>>n, it means to shift the bits of a number toward the right with a specified position (n).
In the terms of mathematics, we can represent the signed right shift operator as follows:

Note: When we apply right shift operator on a positive number, we get the positive number in the result also.
Similarly, when we apply right shift operator on a negative number, we get the negative number in the result
also.
Example: Apply the signed right shift operator with specified positions 4 if x = 256 and x = -256.
If x = 256
256 >> 4
256/24 = 16
If x = -256
-256 >> 4
-256/24 = -16
In the above example, we have observed that after shifting the operator 256 converted into 16 and -256
converted into -16.
Let's create a Java program and implement the left shift operator.
SignedRightShiftOperatorExample.java
1. public class SignedRightShiftOperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x = 50;
6. System.out.println("x>>2 = " + (x >>2));
7. }
8. }
Output
x>>2 = 12
Signed Left Shift Operator (<<)
The signed left shift operator (<<) shifts a bit pattern to the left. It is represented by the symbol <<. It also
preserves the leftmost bit (sign bit). It does not preserve the sign bit.
In general, if we write a<<n, it means to shift the bits of a number toward the left with specified position (n). In
the terms of mathematics, we can represent the signed right shift operator as follows:

Example 1: What will be the result after shifting a<<3. The value of a is 20.
Representation of 20 in binary is = 00010100
After performing the left shift operator, we get:
a << 3 = 10100000 (last three bits are the filled bits)
a << 3 = 160
Let's check the result by using the formula.
20 << 3
20*23 = 20*8 = 160
Example 2: What will be the result after shifting a<<2. The value of a is -10.
Representation of -10 in binary is = 11110110
a<<2 = 11011000 = -40
Let's check the result by using the formula.
-10 << 3
-10*22 = -10*4 = -40
Let's create a Java program and implement the signed left shift operator.
SignedLeftShiftOperatorExample.java
1. public class SignedLeftShiftOperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x = 12;
6. System.out.println("x<<1 = " + (x << 1));
7. }
8. }
Output
x<<1 = 24
Unsigned Right Shift Operator (>>>)
It shifts a zero at the leftmost position and fills 0. It is denoted by the symbol >>>. Note that the leftmost
position after >> depends on the sign bit. It does not preserve the sign bit.
Example: If a=11110000 and b=2, find a>>>b?
a >>> b = 11110000 >>> 2 = 00111100
The left operand value is moved right by the number of bits specified by the right operand and the shifted bits
are filled up with zeros. Excess bits shifted off to the right are discarded.
Therefore, before shifting the bits the decimal value of a is 240, and after shifting the bits the decimal value of a
is 60.
Let's create a Java program and use the unsigned right shift operator.
UnsignedRightShiftOperatorExample.java
1. public class UnsignedRightShiftOperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x = 20;
6. System.out.println("x>>>2 = " + (x >>>2));
7. }
8. }
Output
x>>>2 = 5
Java Operator Precedence
Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=
Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

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


>>>=

Java instanceof
The java instanceof operator is used to test whether the object is an instance of the specified type (class or
subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the instance with type. It
returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns
false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple1);//true
5. }
6. }

Output:true

DOT Operator in JAVA


The (.) operator is also known as member operator it is used to access the variable, methods, package , classes
etc
Example
System.out.println(“Hello”); { dot operator used to access method println() }

Java Math Methods


The java.lang.Math class contains various methods for performing basic numeric operations such as
the logarithm, cube root, and trigonometric functions etc. The various java math methods are as follows:
Basic Math methods

Method Description

Math.abs() It will return the Absolute value of the given value.


Math.max() It returns the Largest of two values.

Math.min() It is used to return the Smallest of two values.

Math.round() It is used to round of the decimal numbers to the nearest value.

Math.sqrt() It is used to return the square root of a number.

Math.pow() It returns the value of first argument raised to the power to


second argument.

Example 1
1. public class JavaMathExample1
2. {
3. public static void main(String[] args)
4. {
5. double x = 28;
6. double y = 4;
long y = -1876487618764l;
7. // return the maximum of two numbers
8. System.out.println("Maximum number of x and y is: " +Math.max(x, y));
9. System.out.println(“Minimum number of x and y is:” +Math.min(x,y));
10. // return the square root of y
11. System.out.println("Square root of y is: " + Math.sqrt(y));
12. //returns 28 power of 4 i.e. 28*28*28*28
13. System.out.println("Power of x and y is: " + Math.pow(x, y));
14.
15. // return the logarithm of given
value 16.
17.
18. // return a power of 2
19. System.out.println("exp of a is: " +Math.exp(x));
System.out.println("Math.abs(" + y + ")=" + Math.abs(y));

20.20.
21. }
22. }

Output:
Maximum number of x and y is: 28.0 Minimum number of x and y is: 4.0 Square root of y is: 2.0
Power of x and y is: 614656.0
exp of a is: 1.446257064291475E12

Math.abs(-1876487618764)=1876487618764
Decision Making Statement in Java
Decision making statement statements is also called selection statement. That is depending on the condition
block need to be executed or not which is decided by condition. If the condition is "true" statement block
will be executed, if condition is "false" then statement block will not be executed. In java there are three
types of decision making statement.
 if
 if-else
 switch
if-then Statement
if-then is most basic statement of Decision making statement. It tells to program to execute a certain part of
code only if particular condition is true.

Syntax
if(condition)
{
Statement(s)
}

Example if statement

class Hello
{
int a=10;
public static void main(String[] args)
{
if(a<15)
{
System.out.println("Hello good morning!");
}
}
}

Output
Hello good morning

if-else statement
In general it can be used to execute one block of statement among two blocks, in java language if and else are
the keyword in java.

Syntax

if(condition)
{
Statement(s)
}
else
{
Statement(s)
}
........
In the above syntax whenever condition is true all the if block statement are executed, remaining statement
of the program by neglecting. If the condition is false else block statement executed and neglecting if block
statements.
Example if else

import java.util.Scanner;
class Oddeven
{
public static void main(String[] args)
{
int no;
Scanner s=new Scanner(System.in);
System.out.println("Enter any number :");
no=s.nextInt();
if(no%2==0)
{
System.out.println("Even number");
}
else
{
System.out.println("Odd number");
}
}
}

Output
Enter any number :
10
Even number

Java if-else-if ladder Statement


The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
Example:
1. //Java Program to demonstrate the use of If else-if ladder.
2. //It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
3. public class IfElseIfExample {
4. public static void main(String[] args) {
5. int marks=65;
6.
7. if(marks<50){
8. System.out.println("fail"); 9.
}
10. else if(marks>=50 && marks<60){
11. System.out.println("D grade");
12. }
13. else if(marks>=60 && marks<70){
14. System.out.println("C grade");
15. }
16. else if(marks>=70 && marks<80){
17. System.out.println("B grade");
18. }
19. else if(marks>=80 && marks<90){
20. System.out.println("A grade");
21. }else if(marks>=90 && marks<100){
22. System.out.println("A+ grade");
23. }else{
24. System.out.println("Invalid!");
25. }
26. }
27. }
Output:
C grade
Program to check POSITIVE, NEGATIVE or ZERO:
1. public class PositiveNegativeExample {
2. public static void main(String[] args) {
3. int number=-13;
4. if(number>0){
5. System.out.println("POSITIVE");
6. }else if(number<0){
7. System.out.println("NEGATIVE");
8. }else{
9. System.out.println("ZERO");
10. }
11. }
12. }
Output:
NEGATIVE
Java Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if block condition
executes only when outer if block condition is true.
Syntax:
1. if(condition){
2. //code to be executed
3. if(condition){
4. //code to be executed 5.
}
6. }
Example:
1. //Java Program to demonstrate the use of Nested If Statement.
2. public class JavaNestedIfExample {
3. public static void main(String[] args) {
4. //Creating two variables for age and weight
5. int age=20;
6. int weight=80;
7. //applying condition on age and weight
8. if(age>=18){
9. if(weight>50){
10. System.out.println("You are eligible to donate blood");
11. }
12. }
13. }}

Switch Statement
The switch statement in java language is used to execute the code from multiple conditions or case. It is same
like if else-if ladder statement.
A switch statement work with byte, short, char and int primitive data type, it also works with enumerated
types and string.

Syntax
switch(expression/variable)
{
case value:
//statements
// any number of case
statements break; //optional
default: //optional
//statements
}

Rules for apply switch statement


With switch statement use only byte, short, int, char data type (float data type is not allowed). You can use any
number of case statements within a switch. Value for a case must be same as the variable in switch.
Limitations of switch statement
Logical operators cannot be used with switch statement. For instance
Example

case k>=20: // not allowed

Example of switch case

import java.util.*;

class switchCase
{
public static void main(String arg[])
{
int ch;
System.out.println("Enter any number (1 to 7) :");
Scanner s=new Scanner(System.in);
ch=s.nextInt();
switch(ch)
{
case 1:
System.out.println("Today is Monday");
break;
case 2:
System.out.println("Today is Tuesday");
break;
case 3:
System.out.println("Today is Wednesday");
break;
case 4:
System.out.println("Today is Thursday");
break;
case 5:
System.out.println("Today is Friday");
break;
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
default:
System.out.println("Only enter value 1 to 7");
}
}
}

Output
Enter any number (1 to 7) :
5
Today is Friday

Looping Statement in Java


Looping statement are the statements execute one or more statement repeatedly several number of times. In
java programming language there are three types of loops; while, for and do-while.
Why use loop ?
When you need to execute a block of code several number of times then you need to use looping concept in
Java language.
Advantage with looping statement
 Reduce length of Code
 Take less memory space.
 Burden on the developer is reducing.
 Time consuming process to execute the program is reduced.
Difference between conditional and looping statement
Conditional statement executes only once in the program where as looping statements executes repeatedly
several number of time.
While Loop in Java
In while loop in Java first check the condition if condition is true then control goes inside the loop body
otherwise goes outside of the body. while loop will be repeats in clock wise direction.
Syntax
while(condition)
{
Statement(s)
Increment / decrements (++ or --);
}

Example while loop

class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<5)
{
System.out.println(+i); i++;
}

Output
0
2
3
4

For Loop in Java


For Loop in Java is a statement which allows code to be repeatedly executed. For loop contains 3 parts
Initialization, Condition and Increment or Decrements
Syntax
for ( initialization; condition; increment )
{
statement(s);
}

 Initialization: This step is execute first and this is execute only once when we are entering into the
loop first time. This step is allow to declare and initialize any loop control variables.
 Condition: This is next step after initialization step, if it is true, the body of the loop is executed, if it
is false then the body of the loop does not execute and flow of control goes outside of the for loop.
 Increment or Decrements: After completion of Initialization and Condition steps loop body code
is executed and then Increment or Decrements steps is execute. This statement allows to update any
loop control variables.
Flow Diagram
Control flow of for loop

 First initialize the variable


 In second step check condition
 In third step control goes inside loop body and execute.
 At last increase the value of variable
 Same process is repeat until condition not
false. Improve your looping conceptFor Loop
Display any message exactly 5 times.
Example of for loop

class Hello
{
public static void main(String args[])
{
int i;
for (i=0: i<5; i++)
{
System.out.println("Hello Friends !");
}
}
}

Output
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !

do-while Loop in Java


A do-while loop in Java is similar to a while loop, except that a do-while loop is execute at least one time.
A do while loop is a control flow statement that executes a block of code at least once, and then repeatedly
executes the block, or not, depending on a given condition at the end of the block (in while).
When use do..while loop
when we need to repeat the statement block at least one time then use do-while loop. In do-while loop post-
checking process will be occur, that is after execution of the statement block condition part will be executed.
Syntax
do
{
Statement(s)

increment/decrement (++ or --)


}while();

n below example you can see in this program i=20 and we check condition i is less than 10, that means
condition is false but do..while loop execute onec and print Hello world ! at one time.
Example do..while loop

class dowhileDemo
{
public static void main(String args[])
{
int i=20;
do
{
System.out.println("Hello world !");
i++;
}
while(i<10);
}
}

Output
Hello world !

Example do..while loop

class dowhileDemo
{
public static void main(String args[])
{
int i=0;
do
{
System.out.println(+i);
i++;
}
while(i<5);
}
}

Output
1
2
3
4
5

For-each loop in Java


For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5.
 It starts with the keyword for like a normal for-loop.
 Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as
the base type of the array, followed by a colon, which is then followed by the array name.
 In the loop body, you can use the loop variable you created rather than using an indexed array element.
 It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)
 Syntax:
 for (type var : array)
 {
 statements using var;
 }
 is equivalent to:
 for (int i=0; i<arr.length; i++)
 {
 type var = arr[i];
 statements using var;
 }
Break and Continue statement in Java
 Last Updated : 26 Feb, 2021
The break and continue statements are the jump statements that are used to skip some statements inside the loop
or terminate the loop immediately without checking the test expression. These statements can be used inside
any loops such as for, while, do-while loop.
Break: The break statement in java is used to terminate from the loop immediately. When a break statement is
encountered inside a loop, the loop iteration stops there, and control returns from the loop immediately to the
first statement after the loop. Basically, break statements are used in situations when we are not sure about the
actual number of iteration for the loop, or we want to terminate the loop based on some condition.
Syntax :
break;
In Java, a break statement is majorly used for:
 To exit a loop.
 Used as a “civilized” form of goto.
 Terminate a sequence in a switch statement.
Using break to exit a loop

Using break, we can force immediate termination of a loop, bypassing the conditional expression and any
remaining code in the body of the loop. When we use break inside the nested loops, it will only break out of the
innermost loop.
Example:
Java

// Java program to demonstrate using


// break to exit a
loop class GFG {
public static void main(String[] args)
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++) {
// Terminate the loop when i is 5
if (i == 5)
break;
System.out.println("i: " +
i);
}
System.out.println("Out of Loop");
}
}

Output
i: 0
i: 1
i: 2
i: 3
i: 4
Out of Loop
Using break as a Form of Goto
Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured
manner. Java uses a label. A Label is used to identify a block of code.
Syntax:
label:
{
statement1;
statement2;
statement3;
.
.
}
Now, the break statements can be used to jump out of the target block. We cannot break to any label which is
not defined for an enclosing block.
Syntax:

break label;
Example:
Java

// Java program to demonstrates using break with goto


class GFG {
public static void main(String args[])
{
// First label
first:
for (int i = 0; i < 3; i++) {
// Second
label second:
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {

// Using break statement with label


break first;
}
System.out.println(i + " " + j);
}
}
}
}

Output
00
01
02
10
Using break to terminate a sequence in a switch statement.
The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different
parts of code based on the value of the expression. The break statement is used inside the switch to terminate a
statement sequence. The break statement is optional. If omitted, execution will continue on into the next case.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example:
Java

// Java program to demonstrate using break to terminate a


// sequence in a switch statement.
class GFG {
public static void main(String args[])
{
int i = 2;
switch (i) {
case 0:
System.out.println("i is
zero."); break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("Invalid number");
}
}
}

Output
i is two.
Continue:
The continue statement in Java is used to skip the current iteration of a loop. We can use continue statement
inside any types of loops such as for, while, and do-while loop. Basically continue statements are used in the
situations when we want to continue the loop but do not want the remaining statement after the continue
statement.
Syntax:
continue;
Using continue to continue a loop
Using continue, we can skip the current iteration of a loop and jumps to the next iteration of the loop
immediately.
Example:
Java

// Java program to demonstrates the continue


// statement to continue a
loop class GFG {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is 2
// skip and
continue if (i == 2)
continue;

System.out.print(i + " ");


}
}
}

Output
013456789
Using continue as a labelled continue statement
The unlabeled continue statement is used to continue the innermost loop. However, since JDK 1.5 java
introduces another feature known as labelled continue statement. We can use a labelled continue statement to
continue the outermost loop.
Example:
Java

// Java program to demonstrates labeled continue statement


class GFG {
public static void main(String args[])
{
// First label
first:
for (int i = 0; i < 3; i++) {
// Second
label second:
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {

// Using continue statement with label


continue first;
}
System.out.println(i + " " + j);
}
}
}
}

Output
00
01
02
10
20
21
22
Difference between break and continue:

Break Continue

The break statement is used to terminate the loop The continue statement is used to skip the current
immediately. iteration of the loop.

break keyword is used to indicate break statements continue keyword is used to indicate continue
in java programming. statement in java programming.

We can use a break with the switch statement. We can not use a continue with the switch statement.

The break statement terminates the whole loop


early. The continue statement brings the next iteration early.
Break Continue

It stops the execution of the loop. It does not stop the execution of the loop.

You might also like