Java UNIT 1 Notes-Kumar
Java UNIT 1 Notes-Kumar
UNIT-I
Introduction to OOP, procedural programming language and object oriented language,
principles of OOP, applications of OOP, history of java, java features, JVM, program
structure. Variables, primitive data types, identifiers, literals, operators, expressions,
precedence rules and associativity, primitive type conversion and casting, flow of control.
INTRODUCTION TO OOP
TS
Object-oriented programming System (OOPs) is a programming paradigm based on the
concept of “objects” that contain data and methods. The primary purpose of object-oriented
programming is to increase the flexibility and maintainability of programs. Object oriented
programming brings together data and its behavior (methods) in a single location(object) makes it
easier to understand how a program works.
OOP is a technique that helps in designing a program more effectively using classes and
objects.Classes and objects are the basics of objected oriented programming. In an objected
oriented model, the focus is on data (contained in objects) and not on the code that manipulates
the data. A class contains instance variables, constructors and methods. We instantiate (create)
objects from these classes by invoking (calling) the constructors. Each object created from a class
has a copy of the instance variables. Each object manipulates its instance variables independently
CI
using the methods of the class. While variables represent an object, the methods help in
modification of these variables and accomplishment of tasks.
Object oriented model of programming helps to simulate real world objects in a better
way. Let's discuss how this is done by considering a 'Car' class as an example. The class can have
instance variables such as current Speed, quantityOfPetrol, and so on. We can provide methods
such as startCar(), stopCar(), chageSpeed() and so on. Some of these methods do not require any
additional information while a few others do require. For instance, startCar() and stopCar() doesn't
require any additional information while changeSpeed() requires the speed to which the car is to
be raced. This information that is to be passed is known as an argument. In conclusion, we have
BV
designed the 'Car' class and we are now capable of building a number of Car objects from them
such as 'Car1', 'Car2' and so on. Each of these objects function independently from each other by
maintaining their own sets of variables. We can, of course, make different objects such as 'Car1'
and 'Car2' interact with each other. We have now a world of cars. We have been able to
successfully build a virtual world. That is what object oriented programming is all about-
simulating the real world using objects built from classes.
The first step in OOP is to identify all the objects the programmer wants to manipulate and
how they relate to each other, an exercise often known as data modeling. Once an object has
been identified, it is generalized as a class of objects which defines the kind of data it contains and
any logic sequences that can manipulate it. Each distinct logic sequence is known as a method.
Objects communicate with well-defined interfaces called messages.
Classes and Objects:A class is said to be a blueprint for an object or collection of objects. It is a
logical entity. And object is an instance of a class. It is a physical entity. For example: chair, pen,
table, keyboard, bike etc.
Example :
Object: House
State: Address, Color, Area
TS
Behavior: Open door, close door
So if I had to write a class based on states and behaviours of House. We can do it like this: States
can be represented as instance variables and behaviours as methods of the class.
class House {
String address;
String color;
double are;
void openDoor() {
//body of the method
}
}
CI
void closeDoor() {
}
...
// body of the method
TS
Pascal. C#.NET.
PRINCIPLES OF OOP
There are four main principles in the area of object-oriented programming:
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
ABSTRACTION:
One of the most fundamental concept of OOPs is Abstraction. Abstraction is a process
CI
where you show only “relevant” data and “hide” unnecessary details of an object from the user.
For example, when you login to your Amazon account online, you enter your user_id and
password and press login, what happens when you press login, how the input data sent to amazon
server, how it gets verified is all abstracted away from the you.
Another example of abstraction: A car in itself is a well-defined object, which is composed of
several other smaller objects like a gearing system, steering mechanism, engine, which are again
have their own subsystems. But for humans car is a one single object, which can be managed by
the help of its subsystems, even if their inner details are unknown.
Abstraction in Java is done by using an interface and abstract class in Java. In order to use
an interface or abstract class we need to explain the methods of an interface or abstract class in a
BV
sub-class.
Main advantage: the user gets data according to their needs but they don't need to use
unnecessary data.
ENCAPSULATION:
Encapsulation is binding the data with the code that manipulates it or Encapsulation means
binding all methods and classes in a single class It keeps the data and the code safe from external
interference.
Encapsulation is the technique of making the fields in a class private and providing access
to the fields via public methods. If a field is declared private then it cannot be accessed by anyone
outside the class, thereby hiding the fields within the class. The main benefit of encapsulation is
the ability to modify our implemented code without breaking the code of others who use our
code.
Encapsulation provides data hiding, maintainability, flexibility and extensibility of our code.
Advantages:
The following are a few advantages of using Encapsulation:
1. Provides the ability to change one part of code without affecting another part of code.
2. Controls the access of the user interface.
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
3. With new requirements it is easy to change encapsulated code.
4. Helps to write immutable classes in Java that are beneficial in multi-threading
environments.
5. Encapsulation in Java makes unit testing easy.
6. Reduces the coupling of modules since all pieces of the same type are encapsulated in one
place.
INHERITANCE:
The process by which one class acquires the properties and functionalities of another class
TS
is called inheritance. Inheritance provides the idea of reusability of code and each sub class
defines only those features that are unique to it, rest of the features can be inherited from the
parent class.
1. Inheritance is a process of defining a new class based on an existing class by extending its
common data members and methods.
2. Inheritance allows us to reuse of code, it improves reusability in your java application.
3. The parent class is called the base class or super class. The child class that extends the
base class is called the derived class or sub class or child class.
Note: The biggest advantage of Inheritance is that the code in base class need not be rewritten in
the child class.
The variables and methods of the base class can be used in the child class as well.
Syntax: Inheritance in Java:
}
CI
To inherit a class we use extends keyword. Here class B is child class and class A is parent class.
class B extends A
{
POLYMORPHISM:
In Core Java, Polymorphism is an easy concept to understand. Polymorphism in Greek is a
combination of poly, which means many and morphism which means forms. It refers to the
object's ability to be Polymorphic depending on its type.
There are two types of Polymorphism available in Java.
BV
1) Static Polymorphism
2) Dynamic Polymorphism
1. Static Polymorphism:
Overloading methods demonstrate the concept of polymorphism. For this reason Method
overloading is also known as Static Polymorphism.
Method Overloading: In Java method overloading we define two or more methods with the same
name but different parameters (type signatures). The methods are said to be overloaded, and the
process is referred to as method overloading.
Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding
where binding of method call to its definition happens at Compile time.
When java encounters a call to an overloaded method, it simply executes the version of
the method whose parameters match the arguments used in the call.
TS
n2 = 20;
}
void square()
{
System.out.println("The Square is " + n1 * n2);
}
void square(int p1)
{
n1 = p1;
System.out.println("The Square is " + n1 * n2);
}
void square(int p1, int p2)
CI {
{
n1 = p1;
n2 = p2;
System.out.println("The Square is " + n1 * n2);
Output :
The Square is 200
The Square is 80
The Square is 56
You can see that here we have 3 square methods with different argument. It is called method
overloading.
2. Dynamic Polymorphism: Dynamic polymorphism is also called as runtime polymorphism. We
can also call it as Method Overriding.
Method Overriding:
In a class hierarchy, when a method in a sub class has the same name and type signature as
a method in its superclass, then the method in the subclass is said to override the method in the
superclass. This feature is called method overriding.
TS
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
}
}CI
obj.eat();
TS
Real time Systems : - A real time system is a system that give output at given instant and its
parameters changes at every time. A real time system is nothing but a dynamic system. Dynamic
means the system that changes every moment based on input to the system. OOP approach is
very useful for Real time system because code changing is very easy in OOP system and it leads
toward dynamic behavior of OOP codes thus more suitable to real time system.
Simulation and Modeling: - System modeling is another area where criteria for OOP approach is
countable. Representing a system is very easy in OOP approach because OOP codes are very easy
to understand and thus is preferred to represent a system in simpler form.
Hypertext And Hypermedia : - Hypertext and hypermedia is another area where OOP approach is
spreading its legs. Its ease of using OOP codes that makes it suitable for various media
approaches.
Decision support system : - Decision support system is an example of Real time system that too
CI
very advance and complex system. More details is explained in real time system.
CAM/CAE/CAD System : - Computer has wide use of OOP approach. This is due to time saving in
writing OOP codes and
it
dynamic behavior
automated system.
AI and expert system : - It is mixed system having both hypermedia and real time system.
Advantages of Object Oriented Programming:
Object Oriented Programming (OOP) offers several advantages to both the program
designer and the user. The important advantages are given below:
Reusability: Elimination of redundant code and use of existing classes through inheritance. Thus
BV
provides economy of expression.
Modularity: Programs can be the built from standard working modules.
Security: Principle of information hiding helps programmers to build secure programs.
Easy Mapping: Object in the problem domain can be directly mapped to the objects in the
program.
Scalability: Can be easily upgraded from small programs to large programs. Object oriented
systems are also resilient to change and evolves over time in a better way.
Easy Management: Easy management of software complexity.
• OOP provides a clear modular structure for programs which makes it good for defining
abstract datatypes where implementation details are hidden and the unit has a clearly
defined interface.
• OOP makes it easy to maintain and modify existing code as new objects can be created
with small differences to existing ones.
• OOP provides a good framework for code libraries where supplied software components
can be easily adapted and modified by the programmer. This is particularly useful for
developing graphical user interfaces
TS
object-oriented programming language; it was originally designed for the development of
software for consumer electronic devices like TVs, VCRs, set-up boxes and other electronic
devices. Currently, Java is used in internet programming, mobile devices, games, e-business
solutions etc. The goal had a strong impact on the development team to make the language
simple, portable and high reliable. The java team which included Patrick Naughton discovered that
the existing languages like C and C++ had limitations in terms of both reliability and portability.
However, they modeled their new language Java on C and C++ but removed a number of features
of C and C++ that were considered as sources of problems and thus made Java a really simple,
reliable, portable, and powerful language.
➢ The following table shows some important milestones in the development of Java
CI
BV
1. Simple 7. Portable
2. Object-Oriented 8. Dynamic
3. Platform independent 9. Interpreted
TS
4. Secured 10. High Performance
5. Robust 11. Multithreaded
6. Architecture neutral 12. Distributed
Simple : Java was designed to be easy for the professional programmer to learn and use
effectively. If you already understand the basic concepts of object-oriented programming, learning
Java will be even easier. Best of all, if you are an experienced C/C++ programmer, moving to Java
will require very little effort. Because Java inherits the C/C++ syntax.
Object-Oriented: 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.
Platform independent: A platform is the hardware or software environment in which a program
CI
runs. There are two types of platforms software-based and hardware-based. Java provides
software-based platform. Java code can be run on multiple platforms e.g.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: A Java program is executed by the JVM also helps to make it secure. Because the JVM is
in control, it can contain the program and prevent it from generating side effects outside of the
system.
Robust : Robust simply means strong. Java uses strong memory management. There are lack of
BV
pointers that avoids security problem. There is automatic garbage collection in java. There is
exception handling and type checking mechanism in java. All these points makes java robust.
Architecture neutral: One of the main problems facing programmers is that no guarantee exists
that if you write a program today, it will run tomorrow—even on the same machine. Operating
system upgrades, processor upgrades, and changes in core system resources can all combine to
make a program malfunction. The Java designers made several hard decisions in the Java language
and the Java Virtual Machine in an attempt to alter this situation. Their goal was “write once; run
anywhere, anytime, forever.”
Portable: Portability is a major aspect of the Internet because there are many different types of
computers and operating systems connected to it. If a Java program were to be run on virtually
any computer connected to the Internet, there needed to be some way to enable that program to
execute on different systems. So we can carry the java byte code to any platform.
Dynamic: Java programs carry with them substantial amounts of run-time type information that is
used to verify and resolve accesses to objects at run time. This makes it possible to dynamically
link code in a safe and expedient manner.
TS
multi-threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.
Distributed: Java is designed as a distributed language for creating applications on networks. It
has the ability to share both data and programs. Java applications can open and access remote
objects on Internet as easily as they can do in a local system. This enables multiple programmers
at multiple remote locations to collaborate and work together on a single project. Java also
supports Remote Method Invocation (RMI). This feature enables a program to invoke methods
across a network.
JAVA VIRTUAL MACHINE
JVM is an abstract computing machine. It is a specification that provides runtime
environment in which java bytecode can be executed. The output of a Java compiler is not
executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed
CI
to be executed by the Java run-time system,which is called the Java Virtual Machine. In essence,
the original JVM was designed as an interpreter for bytecode.The JVM plays a central role in
making Java portable. It provides a layer of abstraction between the compiled Java program and
the underlying hardware platform and operating system. The JVM is central to Java's portability
because compiled Java programs run on the JVM. Java program execution uses a combination of
compilation and interpretation. Programs written in Java are compiled into machine language, but
it is a machine language for a computer that is, virtual and doesn't really exist. This so-called
"virtual" computer is known as the Java virtual machine (JVM). The machine language for the Java
virtual machine is called Java bytecode.
BV
Java Virtual Machine is a program that runs pre compiled Java programs, which mean JVM
executes .class files (byte-code) and produces output. The JVM is written for each platform
supported by Java included in the Java Runtime Environment (JRE). JDK is an acronym for Java
Development Kit. It physically exists. It contains JRE + development tools.
What is JVM?
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment) that
means Sun’s implementations of the Java virtual machine (JVM) is itself called as JRE
3. Runtime Instance Whenever you write java command on the command prompt to run the
java class, and instance of JVM is created.
What it does?
The JVM performs following operation:
• Loads code
• Verifies code
TS
3) JVM comes along with both JDK and JRE and created when you execute Java program by giving
“java” command.
TS
The javac compiler will create a class file called Welcome.class that contains only bytecodes. These
bytecodes have to be interpreted by a Java Virtual Machine(JVM) that will convert the bytecodes
into machine codes. Once we successfully compiled the program, we need to run the program in
order to get the output. So this can be done by the java interpreter called java. In the command
line type as shown here.
c:\>java Welcome
So the output will be displayed as
Welcome to Java
As we had seen above, when the source code has been compiled , it creates a class file with a
extension of .class. Since this class file contains the bytecodes that can be interpreted by the JVM
which can be resided at any platform. Remember that while running the program we are using
only .class file but not the .java file. So once you got the class file you can run the same java
CI
program at any platform instead of writing the program again and again. This is the very special
feature about java that 'Write once and Run anywhere'
Looking into the program line by line
Let us closely examine each part of the program.
/*
This is a sample java program
Save this file as Welcome.java
*/
This is called comment. This is for us to enter the comments about the program for our own
convenience. The contents of a comment will be ignored by the compiler. Actually java supports
BV
three styles of comments. The above one is called multi-line comment which may contain several
lines. This type of comment must begin with /* and end with */.
The next line of the code in a program is
class Welcome
{
The word class is a keyword to define a new class and Welcome is a name of the class. The class
definition must begins with opening curly brace ({) and ends with closing curly brace (}). The rest
of the things defined inside these braces are called member of the class. And note that all the
program activities are defined inside the class.
// A java program will start from here.
This is another type of comment. This is called single line comment starts with // and ends with
end of the line. Generally we use it for brief comments.
The next line of the code in a program is
public static void main(String args[])
This line begins with main method as like functions or subroutines in other languages. The
program will start execute by calling this main method. Let us see briefly about the other
attributes declared in main method. However we are going to discuss in detail about this in later
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
chapters. The keyword public is an access specifier. The keyword static is a kind of modifier. The
keyword void means that the method main() does not return any value. As we had seen before
the entire java program will start execute by calling the main method. If we want to pass any
information to a method will be received by the variables declared within the parenthesis is called
parameters. In a main() method there is only one parameter ,String args[] . args[] is a name of the
parameter that is an array of the objects of data type String. String store sequences of characters
and args will receive the command line arguments.
All the methods in java must be start with opening curly brace ({) and ends with closing curly brace
TS
(}).
The next line of the program is
System.out.println(" Welcome to Java");
System.out.println helps to display the output in the command line. As you have probably noticed,
the System.out.println statement ends with ;. All statements in java must end with semicolon. And
remember that java is case sensitive. So we should be very careful about cases while coding the
program. Otherwise it will lead to the serious problems.
In short, we can illustrate as follows:
public: It indicates that main() can be called outside the class.
static: It is an access specifier, which indicates that main() can be called directly without creating
an object to the class.
void: It indicates that the method main() doesn’t return a value.
CI
main(): It is a method which is an entry point into the java program. When you run a java
program, main() is called first.
String args [ ]: String is a class, which belongs to java.lang package. It can be used as a string data
type in java.
args[]: It is an array of string type. It is used to store command line args.
System: It is a class, which belongs to java.lang package.
out: It is an output stream object, which is a member of System class.
println(): It is a method supported by the output stream object “out”. It is used to display any kind
of output on the screen. It gives a new line after printing the output.
print(): It is similar to println(). But doesn’t give a new line after printing the output.
BV
VARIABLES
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime.
You must declare all variables before they can be used. The basic form of a variable declaration is
shown here:
datatype variable [ = value][, variable [= value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To declare more
than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java:
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
➢ The names of variables in the Java language are referred to as identifiers.
Rules for naming variables:
TS
names are case-sensitive.
➢ You cannot use a java keyword (reserved word) for a variable name.
➢ Variable name should be meaningful.
Examples:
String i=”Raj”; //valid but not meaningful
String name=”Raj”; //valid and meaningful
int abc=7; (valid)
int _abc=8; (valid)
int abc8=9; (valid)
int 8abc=10 (invalid)
int $_abc=12; (valid)
int $_abc*=15; (invalid)
CI
Note: Some programmers use underscore in variable names to separate parts of the name, such
as shipping_weight. Others prefer a "capital style" notation, such as shippingWeight to separate
parts of the name. NEVER use uppercase for every letter in a variable name, because uppercase
names are reserved for final (constant) variables.
Types of Variable: There are three types of variables in java
➢ local variable
➢ instance variable
➢ static variable
Local Variable: A variable that is declared inside the methods, constructors or blocks is called
BV
local variable.
Instance Variable: A variable that is declared inside the class but outside the method is called
instance variable. It is not declared as static.
Static variable: A variable that is declared using static keyword is called static variable. It
cannot be local.
Example program:
class A
{
int x=12; //instance variable
static int y=13; //static variable
public static void main(String args[])
{
int z=30; //local variable
System.out.println(x);
System.out.println(y);
System.out.println(z);
TS
scopes are those defined by a class and those defined by a method. variables declared inside a
scope are not visible (that is, accessible) to code that is defined outside that scope. Thus, when
you declare a variable within a scope, you are localizing that variable and protecting it from
unauthorized access and/or modification.
Example program:
// Demonstrate block scope.
class Scope {
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
CI
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
BV
}
}
As the comments indicate, the variable x is declared at the start of main( )’s scope
and is accessible to all subsequent code within main( ). Within the if block, y is declared. Since
a block defines a scope, y is only visible to other code within its block. This is why outside of its
block, the line y = 100; is commented out. If you remove the leading comment symbol, a
compile-time error will occur, because y is not visible outside of its block. Within the if block, x
can be used because code within a block (that is, a nested scope) has access to variables
declared by an enclosing scope.
Lifetime refers to the amount of time a variable exists. Variables are created when
their scope is entered, and destroyed when their scope is left. This means that a variable will
not hold its value once it has gone out of scope. Therefore, variables declared within a method
will not hold their values between calls to that method. Also, a variable declared within a block
will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.
If a variable declaration includes an initializer, then that variable will be reinitialized each time
the block in which it is declared is entered. For example, consider the next program.
// Demonstrate lifetime of a variable.
TS
y = 100;
System.out.println("y is now: " + y);
}}}
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
As you can see, y is reinitialized to –1 each time the inner for loop is entered. Even though it is
subsequently assigned the value 100, this value is lost.
CI DATATYPES
The term data type refers to the type of data that can be stored in a variable. Java is
called a “strongly typed language” because when you declare a variable, you must specify the
variable’s type. Then the compiler ensures that you don’t try to assign data of the wrong type
to the variable. Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
• Integers: This group includes byte, short, int, and long, which are for whole-valued signed
numbers.
• Floating-point numbers: This group includes float and double, which represent numbers
BV
with fractional precision.
• Characters: This group includes char, which represents symbols in a character set, like letters
and numbers.
• Boolean: This group includes boolean, which is a special type for representing true/false
values.
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
TS
in memory.
Why char uses 2 bytes in java and what is \u0000 ?
Because java uses unicode system rather than ASCII code system. \u0000 is the lowest range
of unicode system. In unicode, character holds 2 bytes, so java also uses 2 bytes for characters.
Eg. char b ='z';
Here is a program that demonstrates char variables:
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
}
CI
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
TS
double: Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Double
precision is actually faster than single precision on some modern processors. All math
functions, such
as sin( ), cos( ), and sqrt( ), return double values. Double data type should never be used for
precise values such as currency. The range of double is 4.9e–324 to 1.8e+308 approximately.
Example: double d1 = 123.4
Here is a short program that uses double variables to compute the area of a circle:
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r, a;
CI
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
LITERALS
Java literals are fixed or constant values in a program's source code. You can use any primitive
type value as a literal e.g. Boolean,int, char and float. However, string is not a primitive type in
BV
Java yet we can use strings as literals.
For example, Here are some literals :
integer literal value : 100
floating-point literal value : 98.6
character literal value : ‘X’
string literal value : “This is a test”
A literal can be used anywhere a value of its type is allowed.
Integer Literals :
Integer literals are the primary literals used in Java programming. They come in a few different
formats: decimal, hexadecimal, and octal. These formats correspond to the base of the
number system used by the literal. Decimal (base 10) literals appear as ordinary numbers with
no special notation. Hexadecimal numbers (base 16) appear with a leading 0x or 0X. Octal
(base 8) numbers appear with a leading 0 in front of the digits.
For example, an integer literal for the decimal number 12 is represented in Java as 12 in
decimal, 0xC in hexadecimal, and 014 in octal.
Integer literals default to being stored in the int type, which is a signed 32-bit value. If you are
working with very large numbers, you can force an integer literal to be stored in the long type
TS
float ff = 89.0f; //OK
double dou = 89.0D; //OK
double doub = 89.0d; //OK
double doubl = 89.0;
Boolean Literals :
Boolean literals are certainly welcome if you are coming from the world of C/C++. In C, there is
no boolean type, and therefore no boolean literals. The boolean values true and false are
represented by the integer values 1 and 0.
Java fixes this problem by providing a boolean type with two possible states: true and false.
Not surprisingly, these states are represented in the Java language by the keywords true and
false.
Boolean literals are used in Java programming about as often as integer literals because they
CI
are present in almost every type of control structure. Any time you need to represent a
condition or state with two possible values, a boolean is what you need. The two boolean
literal values: true and false.
Character Literals :
Character literals represent a single Unicode character and appear within a pair of single
quotation marks. Special characters (control characters and characters that cannot be printed)
are represented by a backslash (\) followed by the character code.
A good example of a special character is \n, which forces the output to a new line when
printed. Table shows the special characters supported by Java.
BV
Description Representation
Backslash \\
Continuation \
Backspace \b
Carriage return \r
Form feed \f
Horizontal tab \t
Newline \n
Single quote \'
Double quote \"
Unicode character \udddd
Octal character \ddd
An example of a Unicode character literal is \u0048, which is a hexadecimal representation of
the character H. This same character is represented in octal as \110.
TS
OPERATORS
JAVA supports a rich set of operators. An operator is a symbol that tells the computer to
perform certain mathematical operations or logical manipulations. Operators are used in
programs to manipulate data and variables. Operators act upon data items called as operands.
JAVA operators can be classified into a number of categories. They include
1. Arithmetic operators 5. Increment and decrement operators
2. Relational operators 6. Conditional operator
3. Logical operators 7. Bitwise operators
4. Assignment operator
1. Arithmetic Operators:
JAVA provides all the basic arithmetic operators. They are listed in below table. These can
operate on any built-in data type allowed in Java.
CI Operator
+
-
*
/
%
Table : Arithmetic Operators
Meaning
Addition or unary plus
Subtraction or unary minus
Multiplication
Division
Module Division
Integer division truncates any fractional part. The modulo division produces the remainder of
an integer division.
BV
Examples of arithmetic operators are:
a+b a-b a*b a/b a%b -a*b
Here a and b are variables and are known as operands. The module division operator % can
also be used on floating point datatype in Java, whereas in C, % can’t be applied on floating
point datatype.
Arithmetic operations are classified as:
1. Integer arithmetic 2. Real arithmetic 3. Mixed mode arithmetic
Integer arithmetic: When both the operands in a single arithmetic expression such as a+b are
integers, the expression is called an “integer expression”, and the operation is called integer
arithmetic. Integer arithmetic always yields an integer value. The largest integer value
depends on the machine. In the above examples, if a and b are integers, then for a=14 and b=4
we have the following results:
a-b=10 a+b=18
a*b=56 a/b=3 (decimal part truncated)
a%b=2 (remainder of division)
During integer division, if both the operands are of the same sign, the result is truncated
towards zero. If one of them is negative, the direction of truncation is implementation
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
dependent. That is,
6/7=0 and -6/-7=0
But-6/7 may be 0 or -1 (machine dependent)
Similarly, during module division, the sign of the result is always the sign of the first operand of
the dividend. This is,
-14 % 3= -2 -14 % -3 = -2 14 % -3 = 2
Real arithmetic: An arithmetic operation involving real operands is called as “real arithmetic”.
A real operand may assume values either in decimal or exponential notation. If x, y and z are
TS
floats, then we will have
X= 6.0/7.0 = 0.857143 Y= 1.0/3.0 = 0.333333 Z= -2.0/3.0= -0.666667
The operator % can also be used with real operands in java.
Example: float a= 20.0, b= 3.0:
a+b= 23.000000 a-b= 17.000000 a*b= 60.000000 a/b= 6.666666666666667 a%b
=2.0
iii. Mixed mode arithmetic: When one of the operand is real and the other is integer, the
expression is called a “mixed mode arithmetic” expression. If either operand is of the real
type, then only the real operation is performed and the result is always a real number.
Thus 15/10.0=1.5 whereas, 15/10=1
Example: int a=3;
float b=2.0;
CI
a+b=5.0 a-b=1.0 a*b=6.0 a/b=1.50
2. RELATIONAL OPERATORS(Comparative Operators):
a % b = 1.0
We often compare two quantities, and depending on their relation, take certain decisions. For
example, we may compare the age of two persons or the price of two items and so on. These
comparisons can be done with the help of relational operators.
An expression such as, a<b or 1<20 containing a relational operators is termed as a
“relational expression”. The value of a relational expression is either 0 or 1. It is 1 if the
specified relation is true and 0 if the relation is false. For example, 10 < 20 is true so it returns
1. But 20<10 is false so it returns 0.
BV
Java supports 6 relational operators. These operators & their meanings are shown in table
below:
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
Fig : Relational Operators
A simple relational expression contains expression contains only one relational operator and
takes the following form.
ae1 relational operator ae2
Ae1 and ae2 are arithmetic expressions, which may be simple constants variables or
combinations of them. Given below are some examples of simple relational expressions and
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
their values:
4.5 <=10 TRUE 4.5 < -10 FALSE
-3.5 > =0 FALSE 10 < 7+5 TRUE
a+b==c+d TRUE only if the sum of values of a and b is equal to the sum of values of c and d.
When arithmetic expressions are used on either side a relational operator, the arithmetic
expressions will be evaluated first and then the results compared. That is, arithmetic operators
have a higher priority over relational operators. Relational expressions are used in decision
statements such as, if and while to decide the course of action of a running program.
TS
3.LOGICAL OPERATORS:
In addition to the relational operators, Java has the following 3 logical operators.
Logical Operators Meaning
&& Logical AND
Logical OR
! Logical NOT
The logical operators && and are used when we want to test more than one condition and
make decisions.
An example is : a>b && x==10
An expression of this kind which combines two or more relational expressions is termed as a
logical expression or a compound relational expression.
Like simple relational expressions, logical expression also yields a value of 1 or 0, according to
CI
the truth table shown in below table. The logical expression given above is true only if a>b is
true and x==0 is true. If either (or both) of them are false, the expression is false.
Truth table:
op1 op2 op1&&op2 op1 op2
0
0
1
0
1
0
0
0
0
0
1
1
1 1 1 1
Logical AND: The result of the logical AND expression will be true only when both the
BV
relational expressions are true.
Syntax: op1 && op2
Eg: 1) if a=9, b=4, c=14
i = (a>b) && (b<c):
The value of i in this expression will be 1.
2) i=(a<b) && (b<c)
The value of i is 0.
Logical OR: The result of logical or expression will be false only when both relational
expressions are false.
Syntax: op1 op2
Ex: i=(a<b) (b<c)
Here the value of i is 1.
i=(a<b) (b>c) Here the value of i is 0
Logical Not: The result of the expression will be true, if the expression is false & viceversa.
Syntax: !0p1
Eg: x=20
i=!(x==20)
BVCITS –BATLAPALEM Prepared By,
A P V D L Kumar, M.Tech, MISTE
Training and Placement Officer
The value of i = 0. This is because x==20 is true (value 1), !true(!1=0) is false(i.e, 0)
4.ASSIGNMENT OPERATORS:
Assignment operators are used to assign the result of an expression to a variable. The
assignment operator is ‘=’. In addition ‘Java’ has a set of ‘shorthand’ assignment operators of
the form
v o p = e x p;
Where v is a variable, exp is an expression and op is a c binary arithmetic operator. The
operator op= is known as the shorthand assignment operator.
TS
Assignment statement,
vop= exp; is equivalent to v=vopexp;
With v evaluated only once. Consider an example, x+=y+1;
This is same as the statement x=x+(y+1);
The shorthand operator + = means ‘add y + 1 to x ‘ or ‘increment x by y+1’. For y=2, the above
statement becomes
x+=3;
And when this statement is executed, 3 is added to x. if the old value of d is, say 5, then the
new value of x is 8.
Eg: a+=5; or a=a+5;
Some of the commonly used shorthand assignment operators are illustrated in below table
Statement with simple assignment Statement with shorthand operator
CI
operator
a=a+1
a=a-1
a=a*(n+1)
a=a/(n+1)
a=a%b
The use of shorthand assignment operators has three advantages
a+=1
a-=1
a*=n+1
a/=n+1
a%=b
1. What appears on the left hand side need not be repeated and therefore it becomes
easier to write.
BV
2. The statement is more concise and easier to read.
3. The statement is more efficient.
5.INCREMENT AND DECREMENT OPERATORS :
C has two very useful operators , these are increment (++) and decrement (--) operators ++
add 1 o the operand while subtracts 1. These are unary operators and take the following
form.
Operator Action
a++ post – increment
++a pre-increment
a-- post decrement
--a pre decrement
Suppose, if we take a=5,
y= a++,
Then, the value of y would be 5 and a would be 6.
A prefix operator first adds 1 to the operand and then the result is assigned to the variable in
left. On the other hand, a postfix operator first assigns the value to the variable on left then
TS
y=++a;
The value of y will be 9, and a is also 9
2. int a=8;
y=a++;
The value of y will be 8, and a is also 9.
3. int a=5;
y=--a;
the value of y will be 4, and a is also 4.
4. int a=5;
y=a--;
The value of y will be 5, and the value of a is 4
6.Conditional Operator: It is also called as ternary operator (?:)
CI
Syntax: exp1?exp2:exp3;
Where exp1, exp2 and exp3 are expressions.
The operator ? : works as follows:
Exp1 is evaluated first. If it is non zero (True) , then the expression exp2 is evaluated and
becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes
the value of the expression. Note that only one of the expressions (either exp2 or exp3) is
evaluated. For example consider the following statements.
int a=10,b=15;
x=(a>b)?a:b;
BV
Here, x will be assigned the value of b. because the condition (a>b) is false. So, exp3 is
evaluated.
This can be achieved using the if…. else statements as follows..
if(a>b)
x=a;
else
x=b;
Example: int a=5, b=10, c=15;
y=(a>b)?b:c;
In the above statement, the expression a>b is evaluated since,, it is false, so value of c will be
assigned to y. so value of y will be 15.
y = (a<b) ? b:c; Here a<b is true, so value of b is assigned to y. so value of y will be 10.
7.BITWISE OPERATORS:
These operators are used for manipulation of data at bit level. When bitwise operators are
used with variables they are internally converted to binary numbers and then bitwise
operators are applied on individual bits. These operators work with char and int data types.
They can’t be used with float or double. These operators & their meanings are shown in
TS
>>> Right Shift filled with 0’s
Table: Bitwise Operators
Bitwise AND: If two bits are set to 1, then the result is 1 otherwise the result is 0.
Truth Table
A B a&b
0 0 0
0 1 0
1 0 0
1 1 1
Ex: If a=4 (0100), b=6 (0110) Then c=a&b (0100)
Bitwise OR: If either of the bit is 1, then the result is set to 1, otherwise the result is 0.
Ex:
CI A
0
0
1
1
If a=4 (0100) b=6 (0110) Then
A
B
0
1
0
1
B
c=a b = 0110
ab
0
1
1
1
Bitwise XOR: If one bit is 0 and other is 1, then the result is set to 1, otherwise 0.
a^b
0 0 0
BV
0 1 1
1 0 1
1 1 0
Ex: If a=4 (0100) b=6 (0110) then c=a^b = 0010
Left Shift Operator (<<) :
This operator is useful when we want to multiply an integer by a power of 2.
a<<b
The above expression returns the value of a multiplied by 2 to the power of b.
Ex.
5<<1=10 /*5*21=10*/
5<<2=20 /*5*22=20*/
5<<3=40 /*5*23=40*/
10<<2=40 /*10*22=40*/
4<<2=16 /*4*22=16*/
Consider the example 4<<2 by using binary values.
The equivalent binary value of 4 is 00000100. So 4<<2 means, it shifts the binary bits twice. So
we get 00010000. The decimal value of 00010000 is 16.
TS
5>>2 means we want to remove last two bits then the binary number is 0001, it is equivalent
to decimal number 1.
One’s Complement :
The operator is represents as ~ and operates on one operand. For a binary number if we take
one’s complement all zero’s become 1 and one’s become 0’s.
Example: x=0001
~x=1110
Right Shift filled with 0’s: Zero fill shift right is represented by the symbol >>>. This operator
fills the leftmost bits by zeros. So the result of applying the operator >>> is always positive. (In
two's complement representation the leftmost bit is the sign bit. If sign bit is zero, the number
is positive, negative otherwise.) The example below illustrates applying the operator >>> on a
number.
int
CI b = 13; // 00000000
11111111
b = b >>> 2; // b now becomes 00111111 11111111 11111111 1111 1101
00000000
11111111
0000
1111
So the result of applying zero fill right shift operator with operand two on -11 is 1073741821.
1101
So the result of doing a zero fill right shift by 2 on 13 is 3. The next example explains the effect
0101
Note: For positive numbers the signed right shift operator and the zero fill right shift operator
both give the same results. For negative numbers, their results are different.
BV
EXPRESSIONS
An expression is a combination of variables, constants and operators arranged as per the
syntax of the language. Java can handle any complex mathematical expressions. Some of the
examples of Java expressions are shown in the below table.
Algebraic Expressions Java Expressions
axb-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
a*b/c
3x2+2x+1 3*x*x+2*x+1
x/y+c
Table : Expressions
Evaluations of Expressions:
Expressions are evaluated using as assignment statement of the form
variable = expression;
variable is any valid Java variable name. When the statement is encountered, the expression is
TS
are used in the expressions.
Rules for evaluation of expression:
➢ First parenthesized sub expressions from left to right are evaluated.
➢ If parenthesis are nested, the evaluation begins with the innermost sub expression.
➢ The “precedence” rule is applied when two or more operators of the same precedence
level appear in a sub expression.
➢ Arithmetic expressions are evaluated from left to right using the rules of precedence.
➢ When the parenthesis are used, the expressions within the parenthesis assume highest
priority.
Precedence of Arithmetic operators:
An arithmetic expression without parenthesis will be evaluated from left to right using the
rules of precedence of operators. These are two distinct priority levels of arithmetic operators
CI
in Java.
High Priority *, /, % Low Priority +, -
The basic evaluation procedure includes two left – to – right passes through the expression.
During the first pass, the high priority operators (if any) are applied as they are encountered.
During the second pass, the low priority operators (if any) are applied as they are
encountered.
/* Program evaluation of expressions*/
class Example
{
BV
public static void main(String args[])
{
float a=9,b=12,c=3,x,y,z;
x=a-b/3+c*2-1;
y=a-b/(3+c)*(2-1);
z=a-(b/(3+c)*2)-1;
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
}
OUTPUT: x=10.000000
y=7.000000
z=4.000000
when a=9,b=12,c=3, the statement becomes
And is evaluated as follows
First pass : Step 1 :
Whenever parentheses are used, the expressions within the parenthesis assume highest
TS
priority. If two or more sets of parenthesis appear one after another as shown above, the
expression contained in the left most set is evaluated first and the right most in the in the last.
Given below are the new steps:
First Pass: Step 1 :
Step 2 :
Second Pass: Step 3 :
Step 4:
Third Pass: Step 5 :
This time the procedure consists of three left to right passes. However the number of
evaluation steps remain the same as 5. (i.e. equal to the number of arithmetic operators).
Parenthesis may be nested, and in such cases, evaluation of expression will proceed outward
CI
from the inner most set of parenthesis, just make sure that every opening parenthesis has a
matching closing one. For example
Whereas
While parenthesis allows us to change the order of priority, we may also use them to improve
understandability of the program.
TS
++ pre-increment
-- pre-decrement
+ unary plus
2 right to left
- unary minus
! logical NOT
~ bitwise NOT
() cast
3 right to left
new object creation
*
/ multiplicative 4 left to right
%
+
+
<<
CI
>>>
< <=
>>
- additive
string concatenation
shift
5
6
left to right
left to right
relational
> >= 7 left to right
type comparison
BV
instanceof
==
equality 8 left to right
!=
& bitwise AND 9 left to right
^ bitwise XOR 10 left to right
| bitwise OR 11 left to right
&& conditional AND 12 left to right
|| conditional OR 13 left to right
?: conditional 14 right to left
= += -=
*= /= assignment 15 right to left
%=
TS
then Java will perform the conversion automatically. For example, it is always possible to
assign an int value to a long variable. However, not all types are compatible, and thus, not all
type conversions are implicitly allowed. For instance, there is no automatic conversion defined
from double to byte. Fortunately, it is still possible to obtain a conversion between
incompatible types. To do so, you must use a cast, which performs an explicit conversion
between incompatible types. Let’s look at both automatic type conversions and casting.
Java’s Automatic Conversions:When one type of data is assigned to another type of variable,
an automatic type conversion will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. That means the data
type of smaller size is converted into higher size then implicit casting is done. It will done by
CI
compiler itself. This process is also called as widening. For example, the int type is always large
enough to hold all valid byte values, so no explicit cast statement is required.
Ex:
class Example {
public static void main(String[] args) {
byte b = 120;
int i ;
i = b;
System.out.println("b is " + b);
BV
System.out.println("i is " + i);
}
}
Output: b is 120
i is 120
Casting Incompatible Types:Although the automatic type conversions are helpful, they will
not fulfill all needs. For example, what if you want to assign an int value to a byte variable?
This conversion will not be performed automatically, because a byte is smaller than an int.
This kind of conversion is sometimes called a narrowing conversion, since you are explicitly
making the value narrower so that it will fit into the target type. To create a conversion
between two incompatible types, you must use a cast. A cast is simply an explicit type
conversion. It has this general form:
(target-type) value;
Here, target-type specifies the desired type to convert the specified value to. For example, the
following fragment casts an int to a byte. If the integer’s value is larger than the range of a
byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range.
int a;
TS
large to fit into the target integer type, then that value will be reduced modulo the target
type’s range.
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Example{
public static void main(String[] argc) {
byte b;
int i =257;
b = (byte)i;
System.out.println("b is " + b);
System.out.println("i is " + i);
}
}
CI
Output: b is 1
i is 257
When the value 257 is cast into a byte variable, the result is the remainder of the division of
257 by 256 (the range of a byte), which is 1 in this case. So the value of b is 1.
Some examples of casts and their actions are shown in below table :
Example
x=int(7.5)
Action
7.5 is converted to integer by truncation.
a=(int)21.3/(int)4.5 Evaluated as 21/4 & the result would be 5.
BV
b=(double)sum/n Division is done in floating point mode.
y=(int)(a+b) The result of a+b is converted to integer.
z=(int)a+b a is converted to integer and then added to b.
p=cos((double)x) Converts x to double before using it.
Explicit casting means when the higher type of data is converted into lower type data, then
some value may be truncated. This process is called narrowing.
TS
contained statement will be skipped and execution continues with the rest of the program.
The condition is an expression that returns a boolean value.
Syntax :
if (condition)
{
statement1;
}
When the condition is true the Statement within the if is executed. After that execution
continues with the next statement after the if statement.
If the condition is false then the statement within the if is not executed and the execution
continues with the statement after the if statement.
Ex: if(a>=0)
CI{
}
System.out.println(“ a is positive”);
System.out.println(“ a is negative”);
Here if we give a value is -5 then it will be executed the statement a is negative but when we
give a value is 5 then it will be executed both the print statements because there is no else in
simple if statements. That’s the reason simple if is also called as null else statement.
if-else statement:
If-else statement is used for test condition to check whether the statement is true or false.
BV
Depending upon the condition, the control statement exists. The syntax for if-else statement
is
Syntax :
if (condition)
{
statement1;
}
else
{
statement2;
}
The if else work like this: If the condition is true, then statement1 is executed. Otherwise,
statement2 is executed. In no case will both statements be executed.
Ex: if(a>=0)
{
System.out.println(“ a is positive”);
}
TS
if(condition)
{
if(condition)
statements....
else
statements....
}
else
{
if(condition)
statements....
else
}
Ex.
CI statements....
import java.util.Scanner;
class MaxValue
{
public static void main(String args[])
{
int a,b,c;
BV
int max=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter value for a : ");
a=s.nextInt();
System.out.println("Enter value for b : ");
b=s.nextInt();
System.out.println("Enter value for c : ");
c=s.nextInt();
if (a>b)
{
if(a>c)
max=a;
else //This else is associate with this if(a>c)
max=c;
}
else //This else is associate with this if(a>b)
{
TS
Output: max value=15
if-else-if Ladder :
Syntax :
if(condition)
statements;
else if(condition)
statements;
else if(condition)
statements;
...
...
else
CI
statements;
The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is executed, and the
rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed. The final else
acts as a default condition; that is, if all other conditional tests fail, then the last else
statement is performed.
If there is no final else and all other conditions are false, then no action will take place.
Ex:
BV
import java.util.Scanner;
class example
{
public static void main( String[] args )
{
int age;
Scanner s = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = s.nextInt();
if ( age >= 18 && age <=35 )
System.out.println( "between 18-35 " );
else if(age >35 && age <=60)
System.out.println("between 36-60");
else
System.out.println( "your age is above 60" );
}
}
TS
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
CI
The switch statement works like this: The value of the expression is compared with each of the
literal values in the case statements. If a match is found, the code sequence following that
case statement is executed. If none of the constants matches the value of the expression, then
the default statement is executed. However, the default statement is optional. If no case
matches and no default is present, then no further action is taken. The break statement is
used inside the switch to terminate a statement sequence. When a break statement is
encountered, execution branches to the first line of code that follows the entire switch
statement. This has the effect of “jumping out” of the switch.
Here is a simple example that uses a switch statement:
BV
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
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;
case 3:
System.out.println("i is three.");
break;
TS
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Iteration Statements: Repeating the same code fragment several times until a specified
condition is satisfied is called iteration. Iteration statements execute the same set of
instructions until a termination condition is met.
Java provides the following loop for iteration statements:
• The for loop
• The while loop
• The do-while loop
for loop :
CI • The for loop repeats a set of statements a certain number of times until a condition is
Syntax :
matched.
• It is commonly used for simple iteration. The for loop appears as shown below.
}
Set of statements;
class Example
{
public static void main(String args[])
{
int i;
for (i=1;i<=5;i++)
{
System.out.println(i);
}
}
}
Output: 1
2
TS
{
body(statements) of the loop
}
• Where <condition> is the condition to be tested. If the condition returns true then the
statements inside the <body of the loop> are executed.
• Else, the loop is not executed.
class Example
{
public static void main(String args[])
{
int i=1;
while(i<=5)
}
CI}
do-while:
{
}
System.out.println(i);
i++;
• The do while loop is similar to the while loop except that the condition to be evaluated
is given at the end.
BV
• Hence the loop is executed at least once even when the condition is false.
• The syntax for the do while loop is as follows:
Syntax :
do
{
body of the loop
} while (condition);
NOTE : for and while loops are entry control loop because here conditions are checked at
entry time of loop but do while loop is exit control loop because the condition is checked at
exit time.
class Example
{
public static void main(String args[])
TS
System.out.println("\n\n\tThe sum of 1 to 10 is .. " + sum);
}
}
Output :
The sum of 1 to 10 is .. 55
Jump statements: These are used to unconditionally transfer the program control to another
part of the program. Java provides the following jump statements:
• break statement
• continue statement
• return statement
break statement : The break statement immediately quits the current iteration and goes to
the first statement following the loop. Another form of break is used in the switch statement.
CI
The break statement has the following two forms:
• Labeled break Statement
• Unlabeled break Statement
Unlabeled break Statement: This is used to jump program control out of the specific loop on
the specific condition.
Ex: class Example
{
public static void main( String[] args )
{
BV
for ( int var = 0; var < 5; var++ )
{
System.out.println( "Var is : " + var );
if ( var == 3 )
break;
}
}
}
Output:
Var is 0
Var is 1
Var is 2
Var is 3
Labeled break Statement: This is used for when we want to jump the program control out of
nested loops or multiple loops.
Ex:
class Example
TS
if ( var1 == 3 )
break Outer;
}
} } }
Output:
CI
continue statement:
• This statement is used only within looping statements.
• When the continue statement is encountered, the next iteration starts.
• The remaining statements in the loop are skipped. The execution starts from the top
of loop again.
The program below shows the use of continue statement.
BV
class Example
{
public static void main(String args[])
{
for (int i=1; i<=10; i++)
{
if (i%2 == 0)
continue;
System.out.println( i);
}
}
}
Output :
1
3
TS
public static void main( String[] args )
{
ReturnDemo r = new ReturnDemo();
System.out.println( "No : " + r.returnCall() );
}
int returnCall()
{
return 5;
}
}
Output: No: 5
CI
BV