0% found this document useful (0 votes)
21 views53 pages

OOM Chap-2 Introduction To Java

This document provides an introduction to the Java programming language. It discusses the principles of object-oriented programming and covers key Java concepts like objects, classes, inheritance, polymorphism, packages, exception handling, and files/input-output. It also compares Java to other languages like C/C++, outlines the types of applications that can be developed in Java, and describes features of Java like being platform independent, secure, robust, high performance, and distributed.

Uploaded by

kirantamanna63
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
21 views53 pages

OOM Chap-2 Introduction To Java

This document provides an introduction to the Java programming language. It discusses the principles of object-oriented programming and covers key Java concepts like objects, classes, inheritance, polymorphism, packages, exception handling, and files/input-output. It also compares Java to other languages like C/C++, outlines the types of applications that can be developed in Java, and describes features of Java like being platform independent, secure, robust, high performance, and distributed.

Uploaded by

kirantamanna63
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 53

Chapter-2 INTRODUCTION TO JAVA

ü PRINCIPLES OF OBJECT ORIENTED PROGRAMMING

ü INTRODUCTION TO JAVA

ü OBJECTS AND CLASSES

ü USING JAVA OBJECTS

ü INHERITANCE

ü POLYMORPHISM

ü PACKAGES: PUTTING CLASSES TOGETHER

ü JAVA FILES AND I/O

ü EXCEPTION HANDLING

PREPARED BY
Nishita Kindo (Lecturer, CSE)
BOSE, Cuttack
OOP with JAVA : INTRODUCTION TO JAVA
INTRODUCTION TO JAVA : What is Java?
What is Java ?

Ø Java is a programming language and a platform. Java is a high level, robust,


object-oriented and secure programming language.
Ø Java was developed by Sun Microsystems (which is now the subsidiary of
Oracle) in the year 1995. James Gosling is known as the father of Java. Before
Java, its name was Oak. Since Oak was already a registered company, so Ja
mes Gosling and his team changed the Oak name to Java.

Application of Java

According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are asfollows:
Ø Desktop Applications such as acrobat reader, media player, antivirus, etc.
Ø Web Applications such as irctc.co.in, javatpoint.com, etc.
Ø Enterprise Applications such as banking applications.
Ø Mobile
Ø Embedded System
Ø Smart Card
Ø Robotics
Ø Games, etc.

Types of Java Applications

There are mainly 4 types of applications that can be created using Java
programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window -
based applications. These are traditional software that we need to install on every
machine. Examples of standalone application are Media player, antivirus, etc. AWT and
Swing are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is
called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc.
is called enterprise application. It has advantages of the high -level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile
application. Currently, Android and Java ME are used for creating mobile applications.
Java Platforms / Editions

There are 4 platforms or editions of Java:


1) Java SE (Java Standard Edition) : It is a Java programming platform.
It includes Java programming APIs such as java.lang, java.io, java.net, java.util,
java.sql, java.math etc. It includes core topics like OOPs, String, Regex,
Exception, Inner classes, Multithreading, I/ O Stream, Networking, AWT,
Swing, Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition) : It is an enterprise platform
which is mainly used to develop web and enterprise applications. It is built on
the top of the Java SE platform. It includes topics like Servlet, JSP, Web
Services, EJB, JPA, etc.
3) Java ME (Java Micro Edit ion): It is a micro platform which is
mainly used to develop mobile applications.
4) Java FX: It is used to develop rich internet applications. It uses
a light -weight user interface API.
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.
The most important features of Java language are as follows:
Ø Simple
Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun, Java language is a simple programming language
because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely -used features, for example,
explicit pointers, operator overloading, etc.
• 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 incorporates both data and behavior.
Ø Object-oriented programming (OOPs) is a methodology that simplifies
software development and maintenance by providing some rules.
Ø Basic concepts of OOPs are:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Ø 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 the top of other hardware -based
platforms. It has two components:
• Runtime Environment
• API (Application Programming Interface)
Ø Java code can be run 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:
Ø No explicit pointer
Ø Java Programs run inside a virtual machine sandbox
Ø HOW JAVA IS SECURED
• Classloader: Class loader in Java is a part of the Java Runtime
Environment (JRE) which is used to load Java classes into the Java Virtual
Machine dynamically. It adds security by separating the package for the
classes of the local file system from those that are imported from network
sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can
violate access right to objects.
• Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.
Ø Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS,
Cryptograph y, etc.
Ø Robust
Ø Robust simply means strong. Java is robust because:
Ø It uses strong memory management.
Ø There is a lack of pointers that avoids security problems.
Ø There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
Ø There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
Ø 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
Ø 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 comm on memory area. Threads are important for multi -
media, Web applications, etc.
Ø Dynamic
Ø Java is a dynamic language. It supports 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).

C vs Java

C Java
C is a Procedural Programming
Java is an Object -Oriented language.
Language.

C was developed by Dennis M. Ritchie in Java language was developed by James


1972. Gosling in 1995.

It is a high -level language because the


It is a middle -level language as it is
translation of code is taken place into
binding the gaps between machine level
machine language, which uses compil er
and high-level languages.
or interpreter.

In the C declaration variable are declared In Java, you can declare a variable
at the beginning of theblock. anywhere.

Free is a variable used for freeing the A compiler will free up the memory by
memory in C. calling the garbage collector.

C does not support threading. Java has a feature of threading.

C support pointers. Java does not support pointers.

Memory allocation can be done by Memory allocation can be done by a new


malloc. keyword.

Garbage collector needs to manage In Java, it is automatically managed by a


manually. garbage collector

C does not have a feature of overloading


Java supports method overloading.
functionality.

C offers support for call by value and call


Java only supports a call by value.
by reference.
C++ vs Java

C++ Java
C++ is platform -dependent. Java is platform-independent.

Java is mainly used for application


C++ is mainly used for system programming. It is widely used in
programming. window, web -based, enterprise and
mobile applications.

Java was designed and created as an


interpreter for printing systems but later
C++ was designed for systems and
extended as a support network
applications programming. It was an
computing. It was designed with a goal
extension of C programming language.
of being easy to use and accessible to a
broader audience.

C++ supports the goto statement. Java doesn't support the goto statement.

Java doesn't support multiple inheritance


C++ supports multiple inheritance. through class. It can be achieved by
interfaces in java.

Java doesn't support operator


C++ supports operator overloading.
overloading.

Java supports pointer internally.


C++ supports pointers. You can write However, you can't writ e the pointer
pointer program in C++. program in java. It means java has
restricted pointer support in java.

Java uses compiler and interpreter both.


Java source code is converted into
C++ uses compiler only. C++ is compiled
bytecode at compilation time. The
and run using the compiler which
interpreter executes this bytecode at
converts source code into machine code runtime and produces output. Java is
so, C++ is platform dependent. interpreted that is why it is platform
independent.

C++ supports both call by value and call Java supports call by value only. There is
by reference. no call by reference in java.

Java doesn't support structures and


C++ supports structures and unions.
unions.

C++ doesn't have built -in support for Java has built -in thread support.
threads. It relies on third -party libraries
for thread support.

Java supports documentation comment


C++ doesn't support documentation
(/ ** ... */ ) to create documentation for
comment.
java source code.

Java has no virtual keyword. We can


C++ supports virtual keyword so that we
override all non -static methods by
can decide whether or not override a
default. In other words, non -static
function.
methods are virtual by default.

Java supports unsigned right shift >>>


operator that fills zero at the top for the
C++ doesn't support >>> operator.
negative numbers. For positive numbers,
it works same like >> operator.

Java uses a single inheritance tree always


C++ creates a new inheritance tree because all classes are the child of Object
always. class in java. The object class is the root of
the inheritance tree in java.

C++ is nearer to hardware. Java is not so interactive with hardware.

Java is also an object-oriented language.


C++ is an object-oriented language. However, everything (except
However, in C language, single root fundamental types) is an object in Java. It
hierarchy is not possible. is a single root hierarchy as everything
gets derived fromjava.lang.Object.

INTRODUCTION TO JAVA : Execution Model of Java


Execution Model of Java
Ø Five phases in Java Programs
Ø In the figure below, 5 phases of the Java Program are described clearly with edit,
compile, load, verify and execute.
Ø Phase 1: Edit
Ø We create the program on editor, after that it stored in the disk with the
name's ending .java
Ø Phase 2: Compile javac (java compiler)
Ø Compiler translate from high -level language program to byte codes and store
it in disk with the ending name .class.
Ø Phase 3: Load
Ø Class loader compile read and put those byte codes from disk to Primary
Memory.
Ø Phase 4: Verify
Ø Verify byte codes to confirm that all byte codes are valid and do not risk for
the Java's security restrictions.
Ø Phase 5: Execute
Ø Java Virtual Machine (JVM) read and translates those byte codes to language
that computer can understand (Machine Language). Then execute the
program, store it values in primary memory.
INTRODUCTION TO JAVA : The Java Virtual Machine
What is JVM?
Ø Java Virtual Machine (JVM) is a engine that provides runtime environment to drive
the Java Code or applications.
Ø It converts Java bytecode into machines language.
Ø JVM is a part of Java Run Environment (JRE).
Ø In other programming languages, the compiler produces machine code for a
particular system.
Ø However, Java compiler produces code for a Virtual Machine known as Java Virtual
Machine.
Ø Here is how JVM works
Ø First, Java code is complied into bytecode. This bytecode gets interpreted on different
machines
Ø Between host system and Java source, Bytecode is an intermediary language.
Ø JVM is responsible for allocating memory space.

JVM Architecture
Ø Let's understand the Architecture of JVM. It contains classloader, memory area,
execution engine etc.
Ø Working of Java Virtual Machine (JVM) & its Architecture

1) Class Loader

The class loader is a subsystem used for loading class files. It performs
three major functions viz. Loading, Linking, and Initialization.

2) Method Area

JVM Method Area stores class structures like metadata, the constant
runtime pool, and the code for methods.

3) Heap

All the Objects, their related instance variables, and arrays are stored in
the heap. This memory is common and shared across multiple threads.

4) JVM language Stacks

Java language Stacks store local variables, and it’s partial results. Each
thread has its own JVM stack, created simultaneously as the thread is
created. A new frame is created whenever a method is invoked, and it is
deleted when method invocation process is complete.

5) PC Registers

PC register store the address of the Java virtual machine instruction


which is currently executing. In Java, each thread has its separate PC
register.

6) Native Method Stacks

Native method stacks hold the instruction of native code depends on


the native library. It is written in another language instead of Java.

7) Execution Engine

It is a type of software used to test hardware, software, or complete


systems. The test execution engine never carries any information about the
tested product.

8) Native Method interface


The Native Method Interface is a programming framework. It allows
Java code which is running in a JVM to call by libraries and native
applications.

9) Native Method Libraries

Native Libraries is a collection of the Native Libraries(C, C++) which


are needed by the Execution Engine.

INTRODUCTION TO JAVA : A First Java Program


A First Java Program

class Simple{

public static void main(String args[]){

System.out.println("Hello Java");

Output:Hello Java
Parameters used in First Java Program

Ø Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
• class keyword is used to declare a class in java.
• public keyword is an access modifier which represents visibility. It means it is
visible to all.
• 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 requir e to create an object to invoke the main method. So
it saves memory.
• void is the return type of the method. It means it doesn't return any value.
• main represents the starting point of the program.
• String[] args is used for command line argument. We will le arn it later.
• 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.
INTRODUCTION TO JAVA : Variables and Data types
Variables in Java

A variable is a name which is associated with a value that can be changed. For
example when I write int i=10; here variable name is i which is associated with value 10,
int is a data type that represents that this variable can hold integer values.
How to Declare a variable in Java
Ø To declare a variable follow this syntax:
data_type variable_name = value;
here value is optional because in java, you can declare the variable first and then
later assign the value to it.
Ø For example: Here num is a variable and int is a data type.
int num;
Ø Similarly we can assign the values to the variables while declaring them, like this:
char ch = 'A';
int number = 100;
or we can do it like this:
char ch;
int number;
...
ch = 'A';
number = 100;
Variables naming convention in java
1) Variables naming cannot contain white spaces, for example: int number = 100; is
invalid because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower case
letter, for example int number; For lengthy variables names that has more than one
words do it like this: int smallNumber; int bigNumber; (start the second word with
capital letter).
4) Variable names are case sensitive in Java.
Types of Variables in Java
There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable

Static (or class) Variable

Static variables are also known as class variable because they are
associated with the class and common for all the instances of class. For example, If I
create three objects of a class and access this static variable, it would be common for
all, the changes made to the variable using one of the object would reflect when you
access it through other objects.

Example of static variable

public class StaticVarExample {


public static String myClassVar="class or static variable";
public static void main(String args[]){
StaticVarExample obj = new StaticVarExample();
StaticVarExample obj2 = new StaticVarExample();
StaticVarE xample obj3 = new StaticVarExample();
//All three will display "class or static variable"
System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);
//changing the valu e of static variable using obj2
obj2.myClassVar = "ChangedText";
//All three will display "Changed Text"
System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);
}
}
Output:
class or static variable
class or static variable
class or static variable
Changed Text
Changed Text
Changed Text
Ø As you can see all three statements displayed the same output irrespective of the
instance through which it is being accessed. That’s is why we can access the static
variables without using the objects like this:
System.out.println(myClassVar);
Ø Do note that only static variables can be accessed like this. This doesn’t apply for
instance and local variables.

Instance variable

Each instance(objects) of class has its own copy of instance variable. Unlike static
variable, instance variables have their own separate copy of instance variable. We
have changed the instance variable value using object obj2 in the following program
and when we disp layed the variable using all three objects, only the obj2 value got
changed, others remain unchanged. This shows that they have their own copy of
instance variable.

Example of Instance variable

public class InstanceVarExample {


String myInstanceVar="ins tance variable";
public static void main(String args[]){
InstanceVarExample obj = new InstanceVarExample();
InstanceVarExample obj2 = new InstanceVarExample();
InstanceVarExample obj3 = new InstanceVarExample();
System.out.println(obj.myInstanceVar) ;
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);
obj2.myInstanceVar = "Changed Text";
System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);
}
}
Output:
instance variable
instance variable
instance variable
instance variable
Changed Text
instance variable

Local Variable

These variables are declared inside method of the class. Their scope is limited to the
method which means that You can’t change th eir values and access them outside of
the method.

In this example, I have declared the instance variable with the same name as local
variable, this is to demonstrate the scope of local variables.

Example of Local variable

public class VariableExample {


/ / instance variable
public String myVar="instance variable";
public void myMethod(){
/ / local variable
String myVar ="Inside Method";
System.out.println(myVar);
}
public static void main(String args[]){
/ / Creating ob ject
VariableExample obj = new VariableExample();
/ * We are calling the method, that changes the
* value of myVar. We are displaying myVar again after
* the method call, to demonstrate that the local
* variable scope is limited to the method itself.
*/
System.out.println("Calling Method");
obj.myMethod();
System.out.println(obj.myVar);
}
}
Output:
Calling Method
Inside Method
instance variable
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:
Ø Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
Ø Non-primitive data types: The non-primitive data types include
Classes, Interfaces, and Arrays.
INTRODUCTION TO JAVA : Primitive Datatypes &
Declarations
Java Primitive Data Types
Ø In Java language, primitive data types are the buildi ng blocks of data manipulation.
Ø Java is a statically -typed programming language. It means, all
variables must be declared before its use. That is why we need to declare
variable's type and name.
Ø There are 8 types of primitive data types:
• boolean data type
• byte data type
• char data type
• short data t ype
• int data type
• long data type
• float data type
• double data type

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 isan 8 -bit signed
two's complement integer. Its value -range lies between -128 to 127 (inclusive).
Its minimum value is -128 and maximum value i s 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,808 and
maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long
data type is used when you need a range of values more than those provided
by int.
• Example: long a = 100000L, long b = -200000L

Float Data Type

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

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

Char Data Type

• The char data type is a s ingle 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'

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

• It is because java uses Unicode system not ASCII code system. The \ u0000 is
the lowest range of Unicode system. To get detail explanation about Unicode
visit next page.

INTRODUCTION TO JAVA: Arrays, Non -Primitive Datatypes


Non-primitive Data Types in Java

Ø These are the datatypes which have instances like objects. Hence, they are called
reference variables. They are primarily classes, arrays, strings or interfaces.

a. Classes in Java

• These are the special user defined data type. It has member variables and
class methods. T hey are blueprinted by objects.
• Java program to illustrate classes:

class Java { int a,


b,
c;
void teach() {
System.out.println(“Hi I am teaching at Java”);
}
void learn() {
System.out.println(“Hi I am learning at Java”);
}}
b. Interfaces in Java

• These are similar to classes. However there is one prime difference, i.e. the
methods are abstract by default. i.e., they have no body.
• Similarly, like objects, interfaces are also the blueprints of a class.
• If the class implements an interface, then it is supposed to add detail to every
function of the interface. If not, then we must declare the class as abstract.
• Example program to illustrate interfaces in Java:

interface Java{ void


teach();
void learn();
}
class JavaCls implements Java { public void
teach() {
System.out.println("I teach at Java");
}
public void learn() {
System.out.println("I learn at Java");
}
publicstatic void main(String[] args) throws IOException{
JavaCls ob = new JavaCls();
ob.teach();
ob.learn();
}
}

c. Strings in Java

• You may be knowing string as a collection of characters but in Java String is a


completely different class altogether. It’s located in java.lang.String. However,
strings end with a ‘ \ 0’ character.
• Java has a lot of methods for manipulating strings such as substring, length
and many more.
• Example:

String s=”Java is a fun place to learn”;


String sub=s.substring(0,4);
System.out.println(sub);
Output:

Java

d. Arrays in Java

• Arrays are special memory locations that can store a collection of


homogeneous data. They are indexed. Arrays always start indexing from 0.
• Dynamic allocation of arrays is there in Java.
• Arrays in Java can be passed as method parameters, local variables and static
fields.
• Example- int arr[] = new int[100];
• This creates a storage space for 100 integers.
• Java program to explain the concept of arrays:

import java.io. * ;
import java.util. * ;
class JavaArray {
public static void main(String[] args) throws IOException{
int i;
Scanner sc = new Scanner(System. in );
int arr[] = new int[] {
1,
2,
3,
4,
5
};
int arr1[] = new int[5];
for (i = 0; i < 5; i++) {
System.out.println("Enter your number");
arr1[i] = sc.nextInt();
}
System.out.println(“The array which was previously assigned”);
for (i = 0; i < 5; i++) {
System.out.println(arr[i]);
}
System.out.println(""); System.out.println("The
array you entered is:");for (i = 0; i < 5; i++) {
System.out.println(arr1[i]);
}}}
Output:
Enter yournumber
4
Enter yournumber
1
Enter yournumber
2
Enter yournumber
3
Enter your number
4The array which was previously assigned:
1
2
3
4
5
The array you entered is:
4
1
2
3
4

INTRODUCTION TO JAVA : Numeric, Character Literals and


String Literals
Literals in Java – Integral, Floating -Point, Char, String, Boolean
• Literals are number, text, or anything that represent a value. In other words,
Literals in Java are the constant values assigned to the variable. It is also called a
constant.
• For example,
int x = 100;
So, 100 is literal.
• There are 5 types of Literals can be seen in Java. But before we start the discussion,
you should revise the concept of Variables in Java.

Types of Literals in Java

1. Integral Literals in Java


We can specify the integer literals in 4 different ways –

Decimal (Base 10)

Digits from 0 -9 are allowed in this form.

int x =101;

Octal (Base 8)

Digits from 0 – 7 are allowed. It should always have a prefix 0.

int x = 0146;

Hexa-Decimal (Base 16)

Digits 0 -9 are allowed and also characters from a -f are allowed in this form.
Furthermore, both uppercase and lowercase characters can be used, Java
provides an exception here.

int x = 0X123Face;

Binary

A literal in this type should have a prefix 0b and 0B, from 1.7 one can also
specify in binary literals, i.e. 0 and 1.

int x = 0b1111;

Example-

public class IntegralLiteral {


public static void main(String[] args)
{
int decimalValue = 123; // decimal -form literal
int octalValue = 01200; / / octal -form literal
int hexaDecimalValue = 0xAce; // Hexa -decimal form literal
int binaryValue = 0b00101; / / Binary literal
System.out.println("Decimal form literal is "+decimalValue);
System.out.println("Octal form literal is "+b);
System.out.println("Hexa -decimal form literal is "+hexaDecimalValue);
System.out.println("Binary literal is "+binaryValue);
}
}

Output-
Integral -Literal -in-java

We can specify explicitly as long type by suffixed with l or L but there


is no way to specify byte and short, but if it’s in the range the compiler
automatically treats it as a byte.

2. Floating-Point Literals in Java

Here, datatypes can only be specified in decimal forms and not in octal or
hexadecimal form.

Decimal (Base 10)

public class FloatingPointLiteral


{
public static void main(String args[])
{
double decimalValue = 101.230; / / decimal -form literal
double decimalValue1 = 0123.222; / / It also acts as decimal literal
double hexaDecimalValue = 1.234e2; / / Hexa -decimal form
System.out.println("Decimal form literal is "+decimalValue);
System.out.println("Second Decimal form literal is "+decimalValue1);
System.out.println("Hexa decimal form literal is "+hexaDecimalValue);
}
}
Output-
Decimal form literal is 101.23
Second Decimal form literal is 123.222
Hexa decimal form literal is 123.4
Every floating type is a double type and this the reason why we canno t assign it
directly to float variable, to escape this situation we use f or F as suffix, and for
double we use d or D.

3. Char Literals in Java

These are the four types of char -

• Single Quote

Java Literal can be specified to a char data type as a single character


within a single quote.

char ch = 'a';

• Char as Integral
A char literal in Java can specify as integral literal which also
represents the Unicode value of a character.

Furthermore, an integer can specify in decimal, octal and even


hexadecimal type, but the range is 0 -65535.

char ch = 062;

• Unicode Representation

Char literals can specify in Unicode representation ‘ \ uxxxx’. Here


XXXX represents 4 hexadecimal numbers.

char ch = '\ u0061';// Here / u0061 represent a.

• Escape Sequence

Escape sequences can also specify as char literal.

char ch = '\ n';

Example-

public class CharacterLiteral {


public static void main(String[] args)
{
char character = 'd';
/ /char number = 0789; error: Integer number too large
char unicodeCharacter = ' \ u0064';
System.out.println(character);
System.out.println(unicodeCharacter);
System.out.println(" \ " is a symbol");
}
}
Output-
d
d
“ isa symbol
4. String Literals in Java

Java String literals are any sequence of characters with a double quote.

String s = "Hello";

They may not contain unescaped newline or linefeed characters. However, the Java
compiler will evaluate compile -time expressions.
Example-

public class StringLiteral {


public static void main(String[] args)
{
String myString = "Hello! Welcome to Java";
/ / If we assign without "" then it treats as a variable
/ / and causes compiler error
/ / String myString1 = Hello;
System.out.println(myString );
}
}
Output-

Hello! Welcome to Java

5. Boolean Literals in Java

They allow only two values i.e. true and false.

boolean b = true;

Example-

public class BooleanLiteral {


public static void main(String[] args)
{
boolean boolVar1 = true;
boolean boolVar2 = false;
/ / boolean boolVar3 = 0; error: incompatible types: int cannot be converted to
boolean
/ / boolean boolVar1 = 1; error: incompatible types: int cannot be converted to
boolean
System.out.println(boolVar1);
System.out.println(boolVar2);
}
}
Output-
true
false
INTRODUCTION TO JAVA : Casting and Type Casting
Java Type Casting
Type casting is when you assign a value of one primitive data type to another
type. In Java, there are two types of casting:

• Widening Casting (automatically) - converting a smaller type to a larger type


size
byte -> short -> char -> int -> long -> float -> double
• Narrowing Casting (manually) - converting a larger type to a smaller size
type
double -> float -> long -> int -> char -> short -> byte

INTRODUCTION TO JAVA : Widening and Narrowing


Conversions
Widening Casting

Widening casting is done automatically when passing a smaller size type to a larger
size type:

Example

public class MyClass {


public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); / / Outputs 9
System.out.println(myDouble); / / Outputs9.0
}
}
Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses in


front of the value:

Example

public class MyClass {


public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; / / Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); / / Outputs 9
}
}

INTRODUCTION TO JAVA : Operators and Expressions


Operators in Java
Operators are the constructs which can manipulate the values of the operands.
Consider the expression 2 + 3 = 5, here 2 and 3 are operands and + is called operator.
In this article on Java operators, the goal is to get you the expertise required to get
started and work with operators in Java.

Java supports the following typesof operators:

Arithmetic Operators
Assignment Operators
Logical Operators
Relational Operators
Unary Operators
Bitwise Operators
Ternary Operators
Shift Operators

Let’s focus on each of these operators one by one.

Arithmetic Operators in Java

Arithmetic Operators are used to perform mathematical operations like additio n,


subtraction, etc. Assume that A = 10 and B = 20 for the below table.

Operator Description Example

+ Addition Adds values on either side A+B=30


of the operator

– Subtraction Subtracts the right -hand A-B=-10


operator with left -hand
Operator

* Multiplication Multiplies values on either A*B=200


side of the operator

/ Division Divides left hand operand A/ B=0


with right hand operator

% Modulus Divides left hand operand A%B=0


by right hand operand
and returns remainder

Consider the below example:

public class ArithmeticOperators {


public static void main(String[] args) {
int A = 10;
int B = 20;
System.out.println(A + B);
System.out.println(A - B);
System.out.println(A * B);
System.out.println(A / B);
System.out.println(A % B);
}
}
Output:
30
-10
200
0
10

Assignment Operators in Java

An Assignment Operator is an operator used to assign a new value to a variable.


Assume A = 10 and B = 20 for the below table.

Operator Description Example

= Assigns values from right c=a+b


side operands to left side
operand

+= It adds right operand to c += a


the left operand and
assigns the result to left
operand

-= It subtracts right operand c -= a


from the left operand and
assigns the result to left
operand

*= It multiplies right operand c *= a


with the left operand and
assigns the result to left
operand

/= It divides left operand c/=a


with the right operand
and assigns the result to
left operand

%= It takes modulus using c %= a


two operands and assigns
the result to left operand

^= Performs exponential c ^= a
(power) calculation on
operators and assign value
to the left operand
Consider the below example:

public class JavaOperators {


public static void main(String[] args) {
int a = 10;
int b=20;
int c;
System.out.println(c = a); // Output =10
System.out.println(b += a);// Output=30
System.out.println(b -= a);// Out put=20
System.out.println(b *= a);/ / Output=200
System.out.println(b /= a);/ / Output=2
System.out.println(b %= a);// Output=0
System.out.println(b ^= a);// Output=0
}
}
Relational Operators in Java

These operators compare the values on either side of them and decide the relation
among them. Assume A = 10 and B = 20.

Operator Description Example

== If the values of two (A == B) is not true


operands are equal, then
the condition becomes
true.

!= If the values of two (A != B) is true


operands are not equal,
then condition becomes
true.

> If the value of the left (a > b) is not true


operand is greater than the
value of right operand,
then condition becomes
true.

< If the value of the left (a < b) is true


operand is less than the
value of right operand,
then condition becomes
true.

>= If the value of the left (a >= b) is not true


operand is greater than or
equal to the value of the
right operand, then
condition becomes true.

<= If the value of the left (a <= b) is true


operand is less than or
equal to the value of right
operand, then condition
becomes true.
Consider the below example:

public class JavaOperators {


public static void main(String[] args) {
int a = 10;
int b=20;
System.out.println(a == b); // returns false because 10 is not equal to 20
System.out.println(a != b); // returns true because 10 is not equal to 20
System.out.println(a > b); / / returns false
System.out.println(a < b); / / returns true
System.out.println(a>=b); // returnsfalse
System.out.println(a <= b); / / returns true
}
}
Logical Operators in Java

The following are the Logical operators present in Java:

Operator Description Example

&& (and) True if both the operands a<10 && a<20


is true

| | (or) True if either of the a<10 | | a<20


operands is true

! (not) True if an operand is false !(x<10 && a<20)


(complements the
operand)
Consider the below example:

public class JavaOperators {


public static void main(String[] args) {
int a = 10;
System.out.println(a<10 & a<20); // returns false
System.out.println(a<10 || a<20); / / returns true
System.out.println(!(a< 10 & a<20)); //returns true
}
}
Unary Operator in Java

Unary operators are the one that needs a single operand and are used to
increment a value, decrement or negate a value.

Operator Description Example

++/-- Increments/decrements a++ and ++a/


the value by 1. There is a-- and --a
post -increment/
decrement and pre
increment/ decrement
operators

— decrements the value by 1. a– or –a


There is post decrement
and pre decrement
operators

! invert a boolean value !a


Consider the following example:

public class JavaOperators {


public static void main(String[] args) {
int a = 10;
boolean b=true;
System.out.println(a++); / / returns 11
System.out.println(++a);
System.out.println(a --);
System.out.println( --a);
System.out.println(!b); // returns false
}
}
Bitwise Operator in Java

Bitwise operations directly manipulate bits. In all computers, numbers are


represented with bits, a series of zeros and ones. In fact, pretty much everything in a
computer is represented by bits. Assume that A = 10 and B = 20 for the below table.

Operator Description Example

& (AND) returns bit by bit AND of a&b


input

| (OR) returns OR of input values a| b

^ (XOR) returns XOR of input a^b


values

~ (Complement) returns the one’s ~a


complement. (all bits
reversed)

Consider the example shown below:

public class JavaOperators {


public static void main(String[] args) {
int a = 58; / / 111010
int b=13; / / 1101
System.out.println(a&b); //returns 8 = 1000
System.out.println(a|b); / / 63=111111
System.out.println(a^b); / / 55=11011
System.out.println(~a); / / -59
}
}
Ternary Operators in Java

The ternary operator is a conditional operator that decreases the length of


code while performing comparisons and conditionals. This method is an alternative
for using if -else and nested if -else statements. The order of execution for this
operator is from left to right.

Syntax:

(Condition) ? (Statement1) : (Statement2);

Condition: It is the expression to be evaluated which returns a boolean value.

Statement 1: It is the statement to be executed if the condition results in a true state.

Statement 2: It is the statement to be executed if the condition results in a false state.

Consider the below example:

public class JavaOperators {


public static void main(String[] args) {
int a = 20, b = 10, c = 30, res;
res = ((a > b) ? (a > c)? a: c: (b > c)? b: c);
System.out.println("Max of three numbers = "+ res);
}
}
Output– Max of three numbers = 30

Shift Operators in Java

Shift operators are used to shift the bits of a number left or right, thereby multiplying
or dividing the number. There are three different types of shift operators, namely left
shift operator()<<, signed right operator(>>) and unsigned right shift operator(>>>).

Syntax:

number shift_op number_of_places_to_shift;

Consider the following example:

public class JavaOperators {


public static void main(String[] args) {
int a=58;
System.out.println(a<< 2); //232=11101000
System.out.println(a>>2); / / returns 14=1110
System.out.println(a>>>2); / / returns 14
}
}
Output–
11101000
1110
14

Instance of operator in Java

Instance of operator is used for type checking. It can be used to test if an


object is an instance of a class, a subclass or an interface.

Consider the below example:

/ / Java program to illustrate


// instance of operator
class operators{
public static void main(String[] args)
{
Person obj1 = new Person();
Person obj2 = new Boy();
/ / As obj is of type person, it is not an
/ / instance of Boy or interface
System.out.println("obj1 instanceof Person: "
+ (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy: "
+ (obj1 instanceof Boy));
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));
/ / Since obj2 is of type boy,
/ / whose parent class is person
/ / and it implements the interface Myinterface
/ / it is instance of all of these classes
System.out.println("obj2 instanceof Person: "
+ (obj2 instanceof Person) );
System.out.println("obj2 instanceof Boy: "
+ (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));
}
}
class Person {
}
class Boy extends Person implements MyInterface {
}
interface MyInterface {
}
Output:
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true

Precedence and Associativity of Operators


Precedence and associative rules are used when dealing with hybrid
equations involving more than one type of operator. In such cases, these rules
determine which part of the equation to consider first as there can be many different
valuations for the same equation. The below table depicts the precedence of
operators in decreasing order as magnitude with the top representing the highest
precedence and bottom shows the lowestprecedence.
Java Expressions
• A Java expression consists of variables, operators, literals, and method calls.
To know more about method calls, visit Java methods. For example,
int score;
score = 90;
• Here, score = 90 is an expression that returns an int. Consider another
example,
double a = 2.2, b = 3.4, result;
result = a + b - 3.4;
• Here, a + b - 3.4 is an expression.
if (number1 == number2)
System.out.println("Number 1 is larger than number 2");
• Here, number1 == number2 is an expression that returns a boolean value.
Similarly, "Number 1 is larger than number 2" is a string expression.

Java Statements
• In Java, each statement is a complete unit of execution. For example,
int score = 9*5;
• Here, we have a statement. The complete execution of this statement involves
multiplying integers 9 and 5 and then assigning the result to the variable
score.
• In the above statement, we have an expression 9 * 5. In Java, expressions are
part of statements.

Expression statements
We can convert an expression into a statement by terminating the expression
with a ;. These are known as expression statements. For example,

// expression

number = 10

/ / statement

number = 10;

In the above example, we have an expression number = 10. Here, by adding a


semicolon (;), we have converted the expression into a statement (number = 10;).

Consider another example,


/ / expression

++number

/ / statement

++number;
Similarly, ++number is an expression whereas ++number; is a statement.

Declaration Statements
In Java, declaration statements are used for declaring variables. For example,

Double tax = 9.5;

The statement above declares a variable tax which is initialized to 9.5.

INTRODUCTION TO JAVA : Control Flow Statements


Java if, if...else Statement
In computer programming, it's often desirable to execute a certain section of
code based upon whether the specified condition is true or false (which is known
only during the run time). For such cases, control flow statements are used.

Java if (if-then) Statement


Ø In Java, the syntax of the if -then statement is:
if (expression) {
/ / statements
}
Ø Here expression is a boolean expression. A boolean expression returns either
true or false.
• if the expression is evaluated to true, statement(s) inside the body of
if (statements inside parenthesis) are executed
• if the expression is evaluated to false, statement(s) inside the body
of if are skipped from execution

How if statement works?

Working of Java if statement


Example 1: Java if Statement
class IfStatement {
public static void main(String[] args) {

int number = 10;

/ / checks if number is greater than 0


if (number > 0) {
System.out.println("The number ispositive.");
}
System.out.println( "This statement is always executed.");
}
}
Output:
The number is positive.
This statement is always executed.
Ø In the above example, we have a variable named number. Here, the test
expression checks if the number is greater than 0 (number > 0).
Ø Since the number is greater than 0. So the test expression evaluates to true.
Hence code inside the body of if is executed.
Ø Now, change the value of the number to a negative integer. Let's say -5.
int number = -5;
Ø If we run the above program with the new value of the number, the output
will be:
This statement is always executed.
Ø Here, the value of number is less than 0. So, the test expression number > 0
evaluates to false. Hence, the body of if is executed.

Java if...else (if -then-else) Statement


Ø The if statement executes a certain section of code if the test expression is
evaluated to true. However, if the test expression is evaluated to false, it
does nothing.
Ø In this case, we can use an optional else block. Statements inside the body
of else block are executed if the test expression is evaluated to false. This is
known as the if -then-else statement in Java.

The syntax of the if -then-else statement is:


if (expression) {
/ / codes
}
else {
// some other code
}
Here, our program will do one task (task inside if block) if the test expression is
true and another task (task inside else block) if the test expression is false.
How if...else statement works?

Working of Java if -else statements


Example 2: Java if else Statement

class IfElse {
public static void main(String[] args) {
int number = 10;

/ / checks if number is greater than 0


if (number > 0) {
System.out.println("The number ispositive.");
}
else {
System.out.println(" The number is not positive.");
}

System.out.println("This statement is always executed.");


}
}
Output:
The number is positive.
This statement is always executed.
Ø In the above example, we have a variable named number. Here, the test
expression checks if the number is greater than 0 (number > 0).
Ø Since the value of the number is 10, the test expression evaluates to true.
Hence code inside the body of if is executed.
Ø Now, change the value of the number to a negative integer. Let's say -5.
int number = -5;
Ø If we run the program with the new value of the number, the output will be:
The number isnot positive.
This statement is always executed.
Ø Here, the value of number is -5. So the test expression evaluates to false.
Hence code inside the body of else is executed.

Java if..else..if Statement


Ø In Java, we have an if...else...if ladder, that can be used to execute one block of
code among multiple other blocks.

if (expression1) {
/ / codes
}
else if(expression2) {
/ / codes
}
else if (expression3) {
/ / codes
}
.
.
else {
/ / codes
}
Ø Here, if statements are executed from the top towards the bottom. As soon as
the test expression is true, codes inside the body of that the if statement is
executed. Then, the control of the program jumps outside the if -else-if ladder.
Ø If all test expressions are false, codes inside the body of else is executed.

Example 3: Java if..else..if Statement


class Ladder {
public static void main(String[] args) {

int number = 0;

/ / checks if number is greater than 0


if (number > 0) {
System.out.println("The number ispositive.");
}

/ / checks if number is less than 0


else if (number < 0) {
System.out.println("The number isnegative.");
}
else {
System.out.println("The number is 0.");
}
}
}
Output:

The number is 0.

Ø In the above example, we are checking whether the number is positive,


negative or zero. Here, we have two test expressions:

• number > 0 - checks if the number is greater than 0

• number < 0 - checks if the number is less than 0

Ø Here, the value of number is 0. So both the test expression evaluates to


false. Hence the statement inside the body of else is executed.

Java Nested if..else Statement


Ø In Java, it is also possible to if..else statements inside a if..else statement. It's
called nested if...else statement.
Ø Here's a program to find largest of 3 number s:

Example 4: Nested if...else Statement


class Number {
public static void main(String[] args) {
/ / declaring double type variables
Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber;
/ / checks if n1 is greater than or equal to n2
if (n1 >=n2) {
/ / if...else statement inside the if block
/ / checks if n1 is greater than or equal to n3
if (n1 >=n3) {
largestNumber = n1;
}
else {
largestNumber = n3;
}
}
else {
/ / if..else statement inside else block
/ / checks if n2 is greater than or equal to n3
if (n2 >=n3) {
largestNumber = n2;
}
else {
largestNumber = n3;
}
}
System.out.println("The largest number is " + largestNumber);
}
}
Output:

The largest number is 4.5

Java switch Statement


Ø In Java, we have used the if..else..if ladder to execute a block of code among
multiple blocks. However, the syntax of if...else...if ladders are too long.
Ø Hence, we can use the switch statement as a substitute for long if...else...if
ladders. The use of s witch statements makes our code more readable.

The syntax of the switch statement is:

switch (variable/expression) {
case value1:
// statements of case1
break;

case value2:
// statements of case2
break;

.. .. ...
.. .. ...

default:
/ / default statements
}
Ø The switch statement evaluates the expression (mostly variable) and
compares it with values (can be expressions) of each case label.
Ø Now, if the value matches a certain case label, then all the statements of the
matching case label are executed.
Ø For example, if the variable/ expression is equal to value2. In this case, all
statements of that matching case (statements of case2) are executed.
Ø Notice, the use of break statements in each case. The break statement is
used to terminate t he execution of the switch statement.
Ø It is important because if break is not used all the statements after the
matching case are executed in sequence until the end of the switch
statement.

Flowchart of switch Statement

Example 1: Java switchstatement


class Main {
public static void main(String[] args) {

int week = 4;
String day;

// switch statement to check day


switch (week) {
case 1:
day="Sunday";
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;

/ / match the value of week


case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
break;
default:
day = "Invalid day";
break;
}
System.out.println("The day is " + day);
}
}

Output:
The day is Wednesday

Ø In the above example, we have used the switch statement to find out the
day of a week. Here, we have a variable week that holds an integer value.
The value is compared to each case inside the switch block.
Ø Here the value of week is 4. Hence it matches the case 4. So the statement
inside case 4 is executed.

Java for Loop


Ø In computer programming, loops are used to repeat a specific block of code
until a certain condition is met (test expression is false). For example,
Ø Imagine we need to print a sentence 50 times on your screen. Well, we can
do it by using the print statement 50 times (without using loops). H ow
about you need to print a sentence one million times? You need to use
loops. With loops, we can simply write the print statement one time and
run it for any number of times.
Ø It's just a simple example showing the importance of loop in computer
programmi ng.
Java for Loop
The syntax of for Loop in Java is:

for (initialization; testExpression; update)


{
/ / codes inside for loop's body
}

for Loop Flowchart

Example 1: for Loop


// Program to print a sentence 10 times
class Loop {
public static void main(String[] args) {

for (int i = 1; i <= 10; ++i) {


System.out.println("Line " + i);
}
}
}
Output:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

Ø In the above example, we have


• initialization expression: int i = 1.e
• test expression: i <=10
• update expression: ++i
Ø Here, initially, the value of i is 1. So the test expression evaluates to true for
the first time. Hence, the print statement is executed. Now the update
expression is evaluated.
Ø Each time the update expression is evaluated, the value of i is increased by
1. Again, the test expression is evaluated. And, the same process is
repeated.
Ø This process goes on until i is 11. When i is 11, the test expression (i <= 10)
is false and the for loop terminates.

Java while and do...while Loop


Ø In computer programming, loops are used to repeat a specific block of code
until a certain condition is met (test expression is false). For example,
Ø Imagine we need to print a sentence 50 times on your screen. Well, we can
do it by using the print statement 50 times (without using loops). How
about you need to print a sentence one million times? You need to use
loops. With loops, we can simply write the print statement one time and
run it for any number of times.
Ø It's just a simple example showing the importance of loop in computer
programming. There are 3 types of loops in Java: for loop, while loop, and
do-while loop.

Java while Loop


The syntax of while loop in Java is:

while (testExpression) {
/ / codes inside the body of while loop
}
How while loop works?
In the above syntax, the test expression inside parenthesis is a boolean expression.
If the test expression is evaluated to true,

• statements inside the while loop are executed.

• then, the test expression isevaluated again.


This process goes on until the test expression is evaluated to false. If the test
expression is evaluated to false,

• the while loop is terminated.

Flowchart of while Loop

Working of while Loop

Example 1: while Loop


/ / Program to print line 10 times
class Loop {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
System.out.println("Line " + i);
++i;
}
}
}
Output:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Ø In the above example, we have a test expression (i <= 10). It checks whether
the value of i is less than or equal to 10.
Ø Here initially, the value of i is 1. So the test expression evaluates to true for
the first time. Hence, the print statement inside while loop is executed.
Ø Inside while loop notice the statement
++i;
Ø This statement increases the value of i by 1 in each iteration. After 10
iterations, the value of i will be 11. Then, the test expression (i <= 10)
evaluates to false and while loop terminates.

Java do...while Loop


Ø The do...while loop is similar to while loop with one key difference. The
body of do...while loop is executed for once before the test expression is
checked.
Ø Here is the syntax of the do...while loop.

do {
/ / codes inside body of do while loop
} while (testExpression);

How do...while loop works?


Ø The body of do...while loop is executed once (before checking the test
expression). Only then, the test expression is checked.
Ø If the test expression is evaluated to true, codes inside the body of the loop
are executed, and the test expression is evaluated again. This process goes
on until the test expression is evaluated to false.
Ø When the test expression is false, the do..while loop terminates.

Flowchart of do...while Loop


Working of do...while Loop
• The program below calculates the sum of numbers entered by the user
until user enters 0.
• To take input from the user, we have used the Scanner object. To learn
more about Scanner, visit Java Scanner.

Example 3: do...while Loop

import java.util.Scanner;
class Sum {
public static void main(String[] args) {
Double number, sum = 0.0;
/ / creates an object of Scanner class
Scanner input = new Scanner(System.in);
do {
/ / takes input from the user
System.out.print("Enter a number: ");
number = input.nextDouble();
sum += number;
} while (number != 0.0); / / test expression
System.out.println("Sum=" + sum);
}
}
Output:
Enter a number: 2.5
Enter a number: 23.3
Enter a number: -4.2
Enter a number: 3.4
Enter a number: 0
Sum = 25.0

Java break Statement


Ø While working with loops, it is sometimes desirable to skip some
statements inside the loop or terminate the loop immediately without
checking the test expression.
Ø In such cases, break and continue statements are used.
Ø The break statement in Java terminates the loop immediately, and the
control of the program moves to the next statement following the loop.
Ø It is almost always used with decision -making statements (Java if...else
Statement).
Ø Here is the syntax of the break statement in Java:

break;

How break statement works?


Working of Java break Statement
Example 1: Java break statement

class Test {
public static void main(String[] args) {
/ / for loop
for (int i = 1; i <= 10; ++i) {
/ / if the value of i is 5 the loop terminates
if (i == 5){
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Ø In the above program, we are using the for loop to print the value of i in
each iteration. To know how for loop works, visit the Java for loop. Here,
notice the statement,
if (i == 5) {
break;
}
Ø This means when the value of i is equal to 5, the loop terminates. Hence,
we get the output with values less than 5 only.
Java continue Statement
Ø While working with loops, it is sometimes desirable to skip some
statements inside the loop or terminate the loop immediately without
checking the test expression.
Ø In such cases, break and continue statements are used. To learn about the
break statement, visit Java break.
Ø The continue statement in Java skips the current iteration of a loop (for,
while, do...while, etc) and the control of the program moves to the end of
the loop. And, the test expression of a loop is evaluated.
Ø In the case of for loop, the update statement is executed before the test
expression.
Ø The continue statement is almost always used in decision -making
statements (if...else Statement). It's syntax is:

continue;

How continue statement works?

Workingof Java continue statement

Example 1: Java continue statement


class Test {
public static void main(String[] args) {

/ / for loop
for (int i = 1; i <= 10; ++i) {
/ / if value of i is between 4 and 9, continue is executed
if (i > 4 && i < 9) {
continue;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
9
10
Ø In the above program, we are using for loop to print the value of i in each
iteration. To know how for loop works, visit Java for loop. Here, notice the
statement,
if (i > 5 && i < 9) {
continue;
}
Ø This means when the value of i becomes more than 4 and less then 9, the print
statement inside the loop is skipped. Hence, we get the output with values 5,
6, 7, and 8 skipped.

You might also like