Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

2022 BCS306A OOC With Java Module 1 Notes

Uploaded by

KAVYA SHREE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

2022 BCS306A OOC With Java Module 1 Notes

Uploaded by

KAVYA SHREE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Department of Computer Science and Business Systems

OOP with Java (BCS306A)


Notes: Module 1

Prepared by,
Ramesh Babu N,
Associate Professor,
Dept. of CS & BS,
KSSEM
OOP with Java (BCS306A)

Module 1

Contents
Introduction .......................................................................................................................... 2
The Creation of Java .......................................................................................................... 2
How Java Changed the Internet ......................................................................................... 2
The Java Buzzwords ........................................................................................................... 3
Object-Oriented Programming .......................................................................................... 5
Two Paradigms .............................................................................................................. 5
The Three OOP Principles .............................................................................................. 5
Two Control Statements ................................................................................................ 7
Using Blocks of Code ......................................................................................................... 8
Lexical Issues ..................................................................................................................... 8
Data Types, Variables, and Arrays...................................................................................... 9
A Closer Look at Literals .................................................................................................. 12
Variables ......................................................................................................................... 13
Type Conversion and Casting ........................................................................................... 15
Automatic Type Promotion in Expressions ...................................................................... 17
Arrays .............................................................................................................................. 18
Introducing Type Inference with Local Variables ............................................................. 19
Operators ........................................................................................................................ 21
Control Statements ......................................................................................................... 30
Jump Statements............................................................................................................. 40

Syllabus
An Overview of Java: Object-Oriented Programming (Two Paradigms, Abstraction, The Three
OOP Principles), Using Blocks of Code, Lexical Issues (Whitespace, Identifiers, Literals,
Comments, Separators, The Java Keywords).
Data Types, Variables, and Arrays: The Primitive Types (Integers, Floating-Point Types,
Characters, Booleans), Variables, Type Conversion and Casting, Automatic Type Promotion in
Expressions, Arrays, Introducing Type Inference with Local Variables.
Operators: Arithmetic Operators, Relational Operators, Boolean Logical Operators, The
Assignment Operator, The ? Operator, Operator Precedence, Using Parentheses.
Control Statements: Java’s Selection Statements (if, The Traditional switch), Iteration
Statements (while, do-while, for, The For-Each Version of the for Loop, Local Variable Type
Inference in a for Loop, Nested Loops), Jump Statements (Using break, Using continue,
return).
Chapter 2, 3, 4, 5

Ramesh Babu N, Page 1 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Introduction
Computer language innovation and development occurs for two fundamental reasons:
• To adapt to changing environments and uses
• To implement refinements and improvements in the art of programming

Java’s Lineage
Java is related to C++, which is a direct descendant of C. Much of the character of Java
is inherited from these two languages. From C, Java derives its syntax. Many of Java’s
object-oriented features were influenced by C++.

The Creation of Java


Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working
version. This language was initially called “Oak,” but was renamed “Java” in 1995.

The original impetus for Java was not the Internet! Instead, the primary motivation was the
need for a platform-independent (that is, architecture-neutral) language that could be used
to create software to be embedded in various consumer electronic devices, such as
microwave ovens and remote controls.

The trouble with C and C++ (and most other languages) is that they are designed to be
compiled for a specific target. Gosling and others began work on a portable, platform-
independent language that could be used to produce code that would run on a variety of
CPUs under differing environments. This effort ultimately led to the creation of Java.

With the emergence of the World Wide Web, Java was propelled to the forefront of computer
language design, because the Web, too, demanded portable programs.

The environmental change that prompted Java was the need for platform-independent
programs destined for distribution on the Internet.

The C# Connection
The most important example of Java’s influence is C#. Created by Microsoft to support the
.NET Framework, C# is closely related to Java. For example, both share the same general
syntax, support distributed programming, and utilize the same object model.

How Java Changed the Internet


The Internet helped catapult Java to the forefront of programming, and Java, in turn, had a
profound effect on the Internet.

Java Applets
An applet is a special kind of Java program that is designed to be transmitted over the Internet
and automatically executed by a Java-compatible web browser.

Applets are intended to be small programs. They are typically used to display data provided
by the server, handle user input, or provide simple functions, such as a loan calculator, that
execute locally, rather than on the server. In essence, the applet allows some functionality to
be moved from the server to the client.
Ramesh Babu N, Page 2 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
The creation of the applet changed Internet programming because it expanded the universe
of objects that can move about freely in cyberspace.

Security
Every time you download a “normal” program, you are taking a risk, because the code you
are downloading might contain a virus, Trojan horse, or other harmful code.Java achieved this
protection by confining an applet to the Java execution environment and not allowing it
access to other parts of the computer.

Portability
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. Java achieves portability by bytecode.

Java’s Magic: The Bytecode


Bytecode is a highly optimized set of instructions designed to be executed by the Java run-
time system, which is called the Java Virtual Machine (JVM).

In essence, the original JVM was designed as an interpreter for bytecode. Translating a Java
program into bytecode makes it much easier to run a program in a wide variety of
environments because only the JVM needs to be implemented for each platform. Thus, the
execution of bytecode by the JVM is the easiest way to create truly portable programs.

Servlets: Java on the Server Side


A servlet is a small program that executes on the server. Servlets dynamically extend the
functionality of a web server.

Servlets are used to create dynamically generated content that is then served to the client.
For example, an online store might use a servlet to look up the price for an item in a database.
Because servlets (like all Java programs) are compiled into bytecode and executed by the JVM,
they are highly portable. Thus, the same servlet can be used in a variety of different server
environments.

The Java Buzzwords


The key considerations were summed up by the Java team in the following list of buzzwords.
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic

Ramesh Babu N, Page 3 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Simple
If you already understand the basic concepts of object-oriented programming, learning Java
will be even easier. Java inherits the C/C++ syntax and many of the object-oriented features
of C++, most programmers have little trouble learning Java.

Object-Oriented
The object model in Java is simple and easy to extend, while primitive types, such as integers,
are kept as high-performance non objects.

Robust
Java is a strictly typed language, it checks your code at compile time. However, it also checks
your code at run time.

Java virtually manages memory allocation and deallocation for you. (In fact, deallocation is
completely automatic, because Java provides garbage collection for unused objects.)

Exceptional conditions in traditional environments often arise in situations such as division by


zero or “file not found,” and they must be managed with clumsy and hard-to-read constructs.
Java helps in this area by providing object-oriented exception handling.

Multithreaded
Java supports multithreaded programming, which allows you to write programs that do many
things simultaneously.

Java run-time system comes with a solution for multiprocess synchronization that enables
you to construct smoothly running interactive systems.

Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. 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.”
Interpreted and High Performance
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. This code can be executed on any system that
implements the Java Virtual Machine.

The Java bytecode was carefully designed so that it would be easy to translate directly into
native machine code for very high performance by using a just-in-time compiler.

Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols. In fact, accessing a resource using a URL is not much different from accessing a file.
Java also supports Remote Method Invocation (RMI).

Ramesh Babu N, Page 4 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
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.

Object-Oriented Programming
Object-oriented programming (OOP) is at the core of Java.

Two Paradigms
All computer programs consist of two elements: code and data. A program can be
conceptually organized around its code or around its data.

The first way is called the process-oriented model. This approach characterizes a program as
a series of linear steps (that is, code). Procedural languages such as C employ this model.

The second approach, called object-oriented programming organizes a program around its
data (that is, objects) and a set of well-defined interfaces to that data.

The Three OOP Principles


All object-oriented programming languages provide mechanisms that help you implement the
object-oriented model. They are encapsulation, inheritance, and polymorphism.

Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse. In Java, the basis of encapsulation is
the class.

A class defines the structure and behavior (data and code) that will be shared by a set of
objects. Each object of a given class contains the structure and behavior defined by the class,
as if it were stamped out by a mold in the shape of the class. Objects are referred to as
instances of a class. Thus, a class is a logical construct; an object has physical reality.

When you create a class, you will specify the code and data that constitute that class.
Collectively, these elements are called members of the class. The data defined by the class
are referred to as member variables or instance variables. The code that operates on that
data is referred to as member methods or just methods. In properly written Java programs,
the methods define how the member variables can be used. This means that the behavior
and interface of a class are defined by the methods that operate on its instance data.

Each method or variable in a class may be marked private or public. The public interface of a
class represents everything that external users of the class need to know, or may know. The
private methods and data can only be accessed by code that is a member of the class.

Inheritance
Inheritance is the process by which one object acquires the properties of another object. It
supports the concept of hierarchical classification. For example, a Golden Retriever is part of
the classification dog, which in turn is part of the mammal class, which is under the larger
class animal.
Ramesh Babu N, Page 5 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Without the use of hierarchies, each object would need to define all of its characteristics
explicitly. By use of inheritance, an object need only define those qualities that make it unique
within its class. It can inherit its general attributes from its parent.

Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to
be used for a general class of actions.

Consider a stack (which is a last-in, first-out list). You might have a program that requires three
types of stacks. One stack is used for integer values, one for floating-point values, and one for
characters.

A First Simple Program


Let’s start by compiling and running the short sample program shown here.

/*
This is a simple Java program.
Call this file "Example.java".
*/

class Example {
// Your program begins with a call to main().
public static void main(String args[]) {

System.out.println("This is a simple Java program.");

}
}

Entering the Program


The name of the source file should be Example.java. In Java, a source file is officially called a
compilation unit. It is a text file that contains one or more class definitions and requires that
source file use the .java filename extension.

The name of the class defined by the program is also Example. In Java, all code must reside
inside a class. By convention, the name of that class should match the name of the file that
holds the program.

Compiling the Program


To compile the Example program, execute the compiler, javac, specifying the name of the
source file on the command line, as shown here:
C:\>javac Example.java

The javac compiler creates a file called Example.class that contains the bytecode version
of the program.

To actually run the program, you must use the Java application launcher, called java.
To do so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example

When the program is run, the following output is displayed:


Ramesh Babu N, Page 6 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
This is a simple Java program.

The next line of code in the program is shown here:


class Example {

This line uses the keyword class to declare a new class. The entire class definition, including
all of its members, will be between the opening curly brace ({) and the closing curly brace (}).

In this case, main( ) must be declared as public, since it must be called by code outside of
its class when the program is started. The keyword static allows main( ) to be called without
having to instantiate a particular instance of the class. This is necessary since main( ) is
called by the Java Virtual Machine before any objects are made. The keyword void simply
tells the compiler that main( ) does not return a value.

String args[ ] declares a parameter named args, which is an array of instances of the class
String. args receives any command-line arguments present when the program is executed.
System is a predefined class that provides access to the system, and out is the output stream
that is connected to the console. println( ) method displays the string which is passed to it.

Two Control Statements

The if Statement
It is syntactically identical to the if statements in C, C++,
if(condition) statement;

Here, condition is a Boolean expression. If condition is true, then the statement is executed.
If condition is false, then the statement is bypassed. Here is an example:

if(num < 100)


System.out.println("num is less than 100");

The for Loop


The simplest form of the for loop is shown here:

for(initialization; condition; iteration) statement;

the initialization portion of the loop sets a loop control variable to an initial value. The
condition is a Boolean expression that tests the loop control variable.

If the outcome of that test is true, the for loop continues to iterate. If it is false, the loop
terminates. The iteration expression determines how the loop control variable is changed
each time the loop iterates.

Example: /* Demonstrate the for loop. Call this file "ForTest.java". */


class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
}
}

Ramesh Babu N, Page 7 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Using Blocks of Code
Java allows two or more statements to be grouped into blocks of code, also called code blocks.
This is done by enclosing the statements between opening and closing curly braces.

if(x < y) { // begin a block


x = y;
y = 0;
} // end of block

The two statements inside the block form a logical unit, and one statement cannot execute
without the other also executing.

Lexical Issues
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.

Whitespace
In Java, whitespace is a space, tab, or newline. Java is a free-form language. You do not need
to follow any special indentation rules.

Identifiers
Identifiers are used for class names, method names, and variable names. An identifier may
be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore
and dollar-sign characters.
Some examples of valid identifiers are
Avg Temp count a4 $test this_is_ok

Invalid identifier names include these:


2count high-temp Not/ok
Literals
A constant value in Java is created by using a literal representation of it. For example, here
are some literals: 100 98.6 'X' "This is a test"

Comments
Java supports three styles of comments.
 single-line comment: begins with a // and ends at the end of the line.
 multiline comment: must begin with /* and end with */.
 documentation comment: /** and ends with a */ and is used to produce an HTMLfile
that documents your program.

Separators
In Java, there are a few characters that are used as separators.

Ramesh Babu N, Page 8 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)

The Java Keywords


There are 50 keywords currently defined in the Java language.

Data Types, Variables, and Arrays


Java is a strongly typed language. Every variable has a type, every expression has a type, and
every type is strictly defined. All assignments, whether explicit or via parameter passing in
method calls, are checked for type compatibility. There are no automatic coercions or
conversions of conflicting types.

The Primitive Types


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
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.

Ramesh Babu N, Page 9 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values.

byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127.
Variables of type byte are useful when you’re working with a stream of data from a network
or file.

Byte variables are declared by use of the byte keyword. For example, the following declares
two byte variables called b and c:
byte b, c;

short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-
used Java type. Here are some examples of short variable declarations:
short s;
short t;

int
The most commonly used integer type is int. It is a signed 32-bit type that has a range
from –2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are
commonly employed to control loops and to index arrays.

long
long is a signed 64-bit type and is useful for those occasions where an int type is not large
enough to hold the desired value.

Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions
that require fractional precision. Java implements the standard (IEEE–754) set of floating-
point types and operators.

Ramesh Babu N, Page 10 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision
is faster on some processors and takes half as much space as double precision,
Here are some example float variable declarations:
float hightemp, lowtemp;

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 that have been
optimized for high-speed mathematical calculations.

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;

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);


}
}

Characters
In Java, the data type used to store characters is char. Java uses Unicode to represent
characters. Unicode defines a fully international character set that can represent all of the
characters found in all human languages. It is a unification of dozens of character sets, such
as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose,
it requires 16 bits. Java char is a 16-bit type. The range of a char is 0 to 65,536.

Although char is designed to hold Unicode characters, it can also be thought of as an integer
type on which you can perform arithmetic operations. For example, you can add two
characters together, or increment the value of a character variable. Consider the following
program:

// char variables behave like integers.


class CharDemo2 {
public static void main(String args[]) {
char ch1;

ch1 = 'X';
System.out.println("ch1 contains " + ch1);

ch1++; // increment ch1


System.out.println("ch1 is now " + ch1);
}
}
The output generated by this program is shown here:
ch1 contains X
ch1 is now Y

Ramesh Babu N, Page 11 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)

Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two
possible values, true or false.

Here is a program that demonstrates the boolean type:


// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;

b = false;
System.out.println("b is " + b);

b = true;
System.out.println("b is " + b);

// a boolean value can control the if statement


if(b)
System.out.println("This is executed.");

b = false;
if(b)
System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value


System.out.println("10 > 9 is " + (10 > 9));
}
}

The output generated by this program is shown here:


b is false
b is true

This is executed.
10 > 9 is true

A Closer Look at Literals


Integer Literals
Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. These are all
decimal values, meaning they are describing a base 10 number.

To specify Octal values are denoted in Java by a leading zero. You signify a hexadecimal
constant with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so A
through F (or a through f ) are substituted for 10 through 15.

When a literal value is assigned to a byte or short variable, no error is generated if the literal
value is within the range of the target type.

To specify a long literal append an upper- or lowercase L to the literal.


For example, 0x7ffffffffffffffL or 9223372036854775807L is the largest long.
An integer can also be assigned to a char as long as it is within range.
Ramesh Babu N, Page 12 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component. They can be
expressed in either standard or scientific notation.

Examples:
standard notation: 2.0, 3.14159, 0.6667
scientific notation: 6.022E23, 314159E–05, and 2e+100.

Floating-point literals in Java default to double precision. To specify a float literal, you must
append an F or f to the constant. You can also explicitly specify a double literal by appending
a D or d.

Boolean Literals
There are only two logical values that a boolean value can have, true and false. The true
literal in Java does not equal 1, nor does the false literal equal 0.

Character Literals
They are 16-bit values that can be converted into integers and manipulated with the integer
operators, such as the addition and subtraction operators. A literal character is represented
inside a pair of single quotes.

For characters that are impossible to enter directly, there are several escape sequences that
allow you to enter the character you need.

String Literals
String literals in Java are specified by enclosing a sequence of characters between a pair of
double quotes. Examples of string literals are “Hello World” “two\nlines”

Variables
The variable is the basic unit of storage in a Java program.

Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:

Ramesh Babu N, Page 13 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)

type identifier [ = value][, identifier [= value] ...] ;

The type is one of Java’s atomic types, or the name of a class or interface.

Examples:
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
Example:
...
double a = 3.0, b = 4.0;

// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
...

The Scope and Lifetime of Variables


A block defines a scope. Thus, each time you start a new block, you are creating a new scope.
A scope determines what objects are visible to other parts of your program. It also determines
the lifetime of those objects.

In Java, the two major scopes are those defined by a class and those defined by a method.
Method scope defined begins with its opening curly brace. Method has parameters, they too
are included within the method’s scope. Variables declared inside a scope are not visible to
code that is defined outside that scope.

Scopes can be nested. the outer scope encloses the inner scope. This means that objects
declared in the outer scope will be visible to code within the inner scope. However, the
reverse is not true.

Example:
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main

x = 10;

if(x == 10) { // 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;
}

Ramesh Babu N, Page 14 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}

Variables are created when their scope is entered, and destroyed when their scope is left. 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.

Example:
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;

for(x = 0; x < 3; x++) {


// y is initialized each time block is entered
int y = -1;
System.out.println("y is: " + y); //always prints -1

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

Although blocks can be nested, you cannot declare a variable to have the same name as one
in an outer scope. For example, the following program is illegal:
// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;

{ // creates a new scope


int bar = 2; //Compile-time error – bar already defined!
}
}
}

Type Conversion and Casting


If the two types are compatible, then Java will perform the conversion automatically. For
example, it is always possible to assign an int value to a long variable. you must use a cast,
which performs an explicit conversion between incompatible types. (from double to byte)

Ramesh Babu N, Page 15 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Java’s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion
(a widening 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.

For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other. Java also performs an automatic type conversion when storing a
literal integer constant into variables of type byte, short, long, or char.

Casting Incompatible Types


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.
Example:
int a;
byte b;
// ...
b = (byte) a;

A different type of conversion will occur when a floating-point value is assigned to an integer
type: truncation. when a floating-point value is assigned to an integer type, the fractional
component is lost. if the size of the whole number component is too large to fit into the target
integer type, then that value will be reduced modulo the target type’s range.

Example:
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {

byte b;
int i = 257;
double d = 323.142;

System.out.println("\nConversion of int to byte.");


b = (byte) i;
System.out.println("i and b " + i + " " + b);

System.out.println("\nConversion of double to int.");


i = (int) d;
System.out.println("d and i " + d + " " + i);

System.out.println("\nConversion of double to byte.");


b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}

This program generates the following output:


Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Ramesh Babu N, Page 16 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Conversion of double to byte.
d and b 323.142 67

Automatic Type Promotion in Expressions


In an expression, the precision required of an intermediate value will sometimes exceed the
range of either operand. For example, examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;

The result of the intermediate term a * b easily exceeds the range of either of its byte
operands. To handle this kind of problem, Java automatically promotes each byte, short, or
char operand to int when evaluating an expression. They can cause confusing compile-time
errors.
For example, this seemingly correct code causes a problem:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
b = (byte)(b * 2); //correct

The Type Promotion Rules


Java defines several type promotion rules that apply to expressions.
All byte, short, and char values are promoted to int.
If one operand is a long, the whole expression is promoted to long.
If one operand is a float, the entire expression is promoted to float.
If any of the operands is double, the result is double.

Example:
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;

double result = (f * b) + (i / c) - (d * s);


System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}

In the first subexpression, f * b, b is promoted to a float and the result of the subexpression
is float. Next, in the subexpression i / c, c is promoted to int, and the result is of type int.
Then, in d * s, the value of s is promoted to double, and the type of the subexpression is
double. Finally, these three intermediate values, float, int, and double, are considered. The
outcome of float plus an int is a float. Then the resultant float minus the last double is
promoted to double, which is the type for the final result of the expression.

Ramesh Babu N, Page 17 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays of
any type can be created and may have one or more dimensions. A specific element in an array
is accessed by its index.

One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. The general form of a
one-dimensional array declaration is
type var-name[ ];
Here, type declares the base type of the array.

int month_days[ ]
the value of month_days is set to null. To link month_days with an actual, physical array of
integers, you must allocate one using new and assign it to month_days.

The general form of new as it applies to one-dimensional arrays appears as follows:


array-var = new type[size];

Further, all elements in the array will be initialized to zero. All array indexes start at zero.

Example:
int month_days[] = new int[12];
month_days[9] = 31;
System.out.println("October has " + month_days[9] + " days.");

An array initializer is a list of comma-separated expressions surrounded by curly braces. The


array will automatically be created large enough to hold the number of elements you specify
in the array initializer.

Example:
int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("October has " + month_days[9] + " days.");

Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays.

For example, the following declares a two dimensional array variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as
an array of arrays of int.

When you allocate memory for a multidimensional array, you need only specify the memory
for the first (leftmost) dimension. You can allocate the remaining dimensions separately.

Example:
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];

When you allocate dimensions manually, you do not need to allocate the same number of
elements for each dimension.
Ramesh Babu N, Page 18 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Example:
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];

Initialize multidimensional arrays


Enclose each dimension’s initializer within its own set of curly braces.
Example:
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};

Alternative Array Declaration Syntax


There is a second form that may be used to declare an array:
type[ ] var-name;

The following two declarations are equivalent:


int al[] = new int[3];
int[] a2 = new int[3];

The following declarations are also equivalent:


char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];

This alternative declaration form offers convenience when declaring several arrays at the
same time. For example,
int[] nums, nums2, nums3; // create three arrays

creates three array variables of type int. It is the same as writing

int nums[], nums2[], nums3[]; // create three arrays

Introducing Type Inference with Local Variables

Beginning with JDK 10, it is now possible to let the compiler infer the type of a local variable
based on the type of its initializer, thus avoiding the need to explicitly specify the type.

Advantages
Eliminating the need to redundantly specify a variable’s type when it can be inferred from its
initializer.

To support local variable type inference, the context-sensitive identifier var was added to Java
as a reserved type name.

Ramesh Babu N, Page 19 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
To use local variable type inference, the variable must be declared with var (context-sensitive
identifier) as the type name and it must include an initializer.

Example:
double avg = 10.0; //earlier

Using type inference, this declaration can now also be written like this:
var avg = 10.0;

In both cases, avg will be of type double. In the first case, its type is explicitly specified. In the
second, its type is inferred as double because the initializer 10.0 is of type double.

The use of var is illegal as classname.

Output:
Value of avg: 10.0
Value of var: 1
Value of k: -1

Creating Array:
var myArray = new int[10]; // This is valid.

Notice that neither var nor myArray has brackets. Instead, the type of myArray is inferred to
be int[ ].

You cannot use brackets on the left side of a var declaration.


var[] myArray = new int[10]; // Wrong
var myArray[] = new int[10]; // Wrong
Ramesh Babu N, Page 20 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
var can be used to declare a variable only when that variable is initialized.
var counter // Wrong! Initializer required.

Remember that var can be used only to declare local variables. It cannot be used when
declaring instance variables, parameters, or return types.

var Restrictions
 Only one variable can be declared at a time. Eg: var c = 10, d = 20; // error
 A variable cannot use null as an initializer. Eg: var e = null; //error
 var cannot be used as the name of a class, an interface, enumeration, or annotation,
or as the name of a generic type parameter.
 Cannot be used to declare the exception type caught by a catch statement.
 An array can be declared using var, but cannot use var with an array initializer.

Example:
var myArray = new int[10]; // This is valid.

but this is not:


var myArray = { 1, 2, 3 }; //Wrong

Operators
Java provides a rich operator environment. Most of its operators can be divided into the
following four groups: arithmetic, bitwise, relational, and logical.

Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are
used in algebra.

The operands of the arithmetic operators must be of a numeric type (char also).

Ramesh Babu N, Page 21 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
The Basic Arithmetic Operators
The basic arithmetic operations—addition, subtraction, multiplication, and division— all
behave as you would expect for all numeric types.

Example:
// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;

System.out.println("a = " + a);


System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);

// arithmetic using doubles


System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;

System.out.println("da = " + da);


System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
When you run this program, you will see the following output:
Integer Arithmetic
a = 2
b = 6
c = 1
d = -1
e = 1
Floating Point Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5

The Modulus Operator


The modulus operator, %, returns the remainder of a division operation. It can be applied to
floating-point types as well as integer types.

Ramesh Babu N, Page 22 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Example:
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;

System.out.println("x mod 10 = " + x % 10);


System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program, you will get the following output:
x mod 10 = 2
y mod 10 = 2.25

Arithmetic Compound Assignment Operators


There are compound assignment operators for all of the arithmetic, binary operators.
Thus, any statement of the form
var = var op expression;
can be rewritten as
var op= expression;

Java provides special operators that can be used to combine an arithmetic operation with an
assignment.
a = a + 4; can also be written as a += 4

// Demonstrate several assignment operators.


class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;

a += 5;
b *= 4;
c += a * b;
c %= 6;

System.out.println("a = " + a);


System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
The output of this program is shown here:
a = 6
b = 8
c = 3

Increment and Decrement


The ++ and the – – are Java’s increment and decrement operators. The increment operator
increases its operand by one. The decrement operator decreases its operand by one.
For example,
x = x + 1; can be rewritten like this by use of the increment operator x++;

x = x - 1; can be rewritten like this by use of the increment operator x--;

Ramesh Babu N, Page 23 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
In the prefix form, the operand is incremented or decremented before the value is obtained
for use in the expression.
In postfix form, the previous value is obtained for use in the expression, and then the operand
is modified.

The following program demonstrates the increment operator.


// Demonstrate ++.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;

c = ++b;
d = a++;
c++;

System.out.println("a = " + a);


System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
The output of this program follows:
a = 2
b = 3
c = 4
d = 1

The Bitwise Operators


Java defines several bitwise operators that can be applied to the integer types, long, int, short,
char, and byte.

All of the integer types (except char) are signed integers. This means that they can represent
negative values as well as positive ones. Java uses an encoding known as two’s complement.
For example, –42 is represented as 11010110.

Ramesh Babu N, Page 24 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
The Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of
each operation.

The Bitwise NOT


Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its
operand. For example, the number 42, which has the following bit pattern:
!00101010 = 11010101

The Bitwise AND


The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all
other cases. Here is an example:
00101010 42
& 00001111 15
00001010 10

The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then
the resultant bit is a 1, as shown here:
00101010 42
| 00001111 15
00101111 47

The Bitwise XOR


The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1.
Otherwise, the result is zero.
00101010 42
^ 00001111 15
00100101 37

The Left Shift


The left shift operator, <<, shifts all of the bits in a value to the left a specified number of
times. It has this general form:
value << num
Here, num specifies the number of positions to left-shift the value in value.

Java’s automatic type promotions produce unexpected results when you are shifting byte and
short values. As you know, byte and short values are promoted to int when an expression is
evaluated.
A negative byte or short value will be sign-extended when it is promoted to int. Thus, the
high-order bits will be filled with 1’s.

Ramesh Babu N, Page 25 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Example: // Left shifting a byte value.
class ByteShift {
public static void main(String args[]) {
byte a = 64, b;
int i;

i = a << 2;
b = (byte) (a << 2);

System.out.println("Original value of a: " + a);


System.out.println("i and b: " + i + " " + b);
}
}

The output generated by this program is shown here:


Original value of a: 64
i and b: 256 0

Since a is promoted to int for the purposes of evaluation, left-shifting the value 64 (0100 0000)
twice results in i containing the value 256 (1 0000 0000).

The Right Shift


The right shift operator, >>, shifts all of the bits in a value to the right a specified number of
times. Its general form is shown here:
value >> num
Here, num specifies the number of positions to right-shift the value in value.

Example:
int a = 32; // 35 in binary 00100011
a = a >> 2; // a now contains 8 (in binary 00001000)

When you are shifting right, the top (leftmost) bits exposed by the right shift are filled in with
the previous contents of the top bit. This is called sign extension and serves to preserve
the sign of negative numbers when you shift them right. For example, –8 >> 1 is –4, which,
in binary, is
11111000 –8
>>1
11111100 –4

The Unsigned Right Shift


Java’s unsigned, shift-right operator, >>>, always shifts zeros into the high-order bit.
Example:
int a = -1;
a = a >>> 24;
Here is the same operation in binary form to further illustrate what is happening:
11111111 11111111 11111111 11111111 –1 in binary as an int
>>>24
00000000 00000000 00000000 11111111 255 in binary as an int

Bitwise Operator Compound Assignments


All of the binary bitwise operators have a compound form similar to that of the algebraic
operators, which combines the assignment with the bitwise operation.
Examples: a = a >> 4; can also be written as a >>= 4;
a = a | b; can also be written as a |= b;

Ramesh Babu N, Page 26 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering.

The outcome of these operations is a boolean value. The relational operators are most
frequently used in the expressions that control the if statement and the various loop
statements.

Example:
int a = 4;
int b = 1;
boolean c = a < b; //false will be stored in c

Boolean Logical Operators


The Boolean logical operators shown here operate only on boolean operands. All of the binary
logical operators combine two boolean values to form a resultant boolean value.

The following table shows the effect of each logical operation:

Ramesh Babu N, Page 27 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Example: // Demonstrate the boolean logical operators.
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;

System.out.println(" a = " + a);


System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}

Output:
a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false

Short-Circuit Logical Operators


Java will not bother to evaluate the right-hand operand when the outcome of the expression
can be determined by the left operand alone.

This is very useful when the right-hand operand depends on the value of the left one in order
to function properly.

Example:
if (denom != 0 && num / denom > 10)

Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time
exception when denom is zero. If this line of code were written using the single & version of
AND, both sides would be evaluated, causing a run-time exception when denom is zero.

The Assignment Operator


The assignment operator is the single equal sign, = and works in Java much as it does in any
other computer language. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression.

It also allows you to create a chain of assignments.


Example: int x, y, z;
x = y = z = 100; // set x, y, and z to 100
This fragment sets the variables x, y, and z to 100 using a single statement.
Ramesh Babu N, Page 28 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else statements. This operator is the ?. The ? has this general form:

expression1 ? expression2 : expression3


Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise, expression3 is evaluated.

Example:
// Demonstrate ?.
class Ternary {
public static void main(String args[]) {
int i, k;

i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);

i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}

The output generated by the program is shown here:


Absolute value of 10 is 10
Absolute value of -10 is 10

Operator Precedence
The following Table shows the order of precedence for Java operators, from highest to lowest.

Ramesh Babu N, Page 29 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)

Control Statements
Java’s program control statements can be put into the following categories:
 selection,
 iteration, and
 jump

Selection statements allow your program to choose different paths of execution based upon
the outcome of an expression or the state of a variable.

Iteration statements enable program execution to repeat one or more statements (that is,
iteration statements form loops).

Jump statements allow your program to execute in a nonlinear fashion.

Java’s Selection Statements


Java supports two selection statements: if and switch.
if
The if statement is Java’s conditional branch statement. It can be used to route program
execution through two different paths. Here is the general form of the if statement:
if (condition)
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block). The condition is any expression that returns a boolean value. The else
clause is optional.

The if works like this: If the condition is true, then statement1 is executed. Otherwise,
statement2 (if it exists) is executed.
Example:
int a, b;
// ...
if(a < b)
a = 0;
else
b = 0;
Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero.

Nested ifs
A nested if is an if statement that is the target of another if or else.
Example:
if(i == 10) {
if(j < 20)
a = b;
if(k > 100)
c = d; // this if is
else
a = c; // associated with this else
}
else
a = d; // this else refers to if(i == 10)

Ramesh Babu N, Page 30 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the if-else-
if ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;

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.

Switch
The switch statement is Java’s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression
statements. Here is the general form of a switch statement:

switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}

The expression must be of type byte, short, int, or char; each of the values specified in the
case statements must be of a type compatible with the expression.

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.

Ramesh Babu N, Page 31 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
// 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;
default:
System.out.println("i is greater than 3.");
}
}
}

The output produced by this program is shown here:


i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.

The break statement is optional. If you omit the break, execution will continue on into the
next case. It is sometimes desirable to have multiple cases without break statements between
them.
Example:
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0: case 1: case 2: case 3:
case 4: System.out.println("i is less than 5");
break;
case 5: case 6: case 7: case 8:
case 9: System.out.println("i is less than 10");
break;
default: System.out.println("i is 10 or more");
}
}
}

This program generates the following output:


i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
Ramesh Babu N, Page 32 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more

Nested Switch
You can use a switch as part of the statement sequence of an outer switch.
Example:
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
.
.
.
}

Here, the case 1: statement in the inner switch does not conflict with the case 1: statement
in the outer switch. The count variable is only compared with the list of cases at the outer
level. If count is 1, then target is compared with the inner list cases.

Iteration Statements
Java’s iteration statements are for, while, and do-while. A loop repeatedly executes the same
set of instructions until a termination condition is met.

While
While construct repeats a statement or block while its controlling expression is true. Here is
its general form:
while(condition) {
// body of loop
}

The condition can be any Boolean expression. The body of the loop will be executed as long
as the conditional expression is true. When condition becomes false, control passes to the
next line of code immediately following the loop. The curly braces are unnecessary if only a
single statement is being repeated.

Ramesh Babu N, Page 33 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Example:
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 5;

while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}

When you run this program, it will “tick” five times:


tick 5
tick 4
tick 3
tick 2
tick 1

The body of the while (or any other of Java’s loops) can be empty. This is because a null
statement (one that consists only of a semicolon) is syntactically valid in Java.
Example:
// The target of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;

// find midpoint between i and j


while(++i < --j) ; // no body in this loop

System.out.println("Midpoint is " + i);


}
}

Output:
Midpoint is 150

In professionally written Java code, short loops are frequently coded without bodies when
the controlling expression can handle all of the details itself.

do-while
The do-while loop always executes its body at least once, because its conditional expression
is at the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);

If this condition is true, the loop will repeat. Otherwise, the loop terminates.

Ramesh Babu N, Page 34 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Example:
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;

do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}

When you run this program, it will “tick” five times:


tick 5
tick 4
tick 3
tick 2
tick 1

for
There are two forms of the for loop. The first is the traditional form that has been in use since
the original version of Java and working mechanism is same as for construct in C or C++.
Here is the general form of the traditional for statement:
for(initialization; condition; iteration) {
// body
}

It is possible to declare the variable inside the initialization portion of the for.
Example:
// Declare a loop control variable inside the for.
class ForTick {
public static void main(String args[]) {

// here, n is declared inside of the for loop


for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}

Using the Comma


There will be times when you will want to include more than one statement in the
initialization and iteration portions of the for loop. Java permits you to include multiple
statements in both the initialization and iteration portions of the for. Each statement is
separated from the next by a comma.

Example:
// Using the comma.
class Comma {
public static void main(String args[]) {
int a, b;

for(a=1, b=4; a<b; a++, b--) {


System.out.println("a = " + a);
System.out.println("b = " + b);
Ramesh Babu N, Page 35 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
}
}
}

Output:
a = 1
b = 4
a = 2
b = 3

Some for Loop Variations


Either the initialization or the iteration expression or both may be absent, as in this next
program:
// Parts of the for loop can be empty.
class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;

for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10)
done = true;

i++;
}
}
}

You can intentionally create an infinite loop (a loop that never terminates) if you leave all
three parts of the for empty.
For example:
for( ; ; ) {
// ...
}
This loop will run forever because there is no condition under which it will terminate.

The For-Each Version of the for Loop


Beginning with JDK 5, a second form of for was defined that implements a “for-each” style
loop. A foreach style loop is designed to cycle through a collection of objects, such as an array,
in strictly sequential fashion, from start to finish.

The general form of the for-each version of the for is shown here:
for(type itr-var : collection) statement-block

Here, type specifies the type and


itr-var specifies the name of an iteration variable that will receive the elements from a
collection, one at a time, from beginning to end.
The collection being cycled through is specified by collection.

Ramesh Babu N, Page 36 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Example:
// Use a for-each style for loop.
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;

// use for-each style for to display and sum the values


for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}

The output from the program is shown here.


Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55

Iterating Over Multidimensional Arrays


The enhanced version of the for also works on multidimensional arrays. In Java,
multidimensional arrays consist of arrays of arrays.

Example:
// Use for-each style for on a two-dimensional array.
class ForEach3 {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];

// give nums some values


for(int i = 0; i < 3; i++)
for(int j=0; j < 5; j++)
nums[i][j] = (i+1)*(j+1);

// use for-each for to display and sum the values


for(int x[] : nums) {
for(int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}

Ramesh Babu N, Page 37 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
The output from this program is shown here:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Summation: 90

Applying the Enhanced for


Types of applications that benefit from for-each style loops include searching, computing an
average, finding the minimum or maximum of a set, looking for duplicates, and so on.
Example:
// Search an array using for-each style for.
class Search {
public static void main(String args[]) {
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false;

// use for-each style for to search nums for val


for(int x : nums) {
if(x == val) {
found = true;
break;
}
}

if(found) System.out.println("Value found!");


}
}

Local Variable Type Inference in a for Loop


Local variable type inference can be used in a for loop when declaring and initializing the
loop control variable inside a traditional for loop, or when specifying the iteration variable in
a for-each for.

Example:

Ramesh Babu N, Page 38 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)

Output:
Values of x: 2.5 5.0 10.0 20.0 40.0 80.0 //var is double
Values in nums array: 1 2 3 4 5 6 //var is int

Nested Loops
Java allows loops to be nested. That is, one loop may be inside another.
Example: Loops may be nested.
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");

System.out.println();
}
}
}

The output produced by this program is shown here:


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

Ramesh Babu N, Page 39 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Jump Statements
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program.

Using break
In Java, the break statement has three uses.
 First, as you have seen, it terminates a statement sequence in a switch statement.
 Second, it can be used to exit a loop.
 Third, it can be used as a “civilized” form of goto.

By using break, you can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop. When a break statement is
encountered inside a loop, the loop is terminated and program control resumes at the next
statement following the loop. Here is a simple example:
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {

for(int i=0; i<100; i++) {


if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}

System.out.println("Loop complete.");
}
}

When used inside a set of nested loops, the break statement will only break out of the
innermost loop.

For example:
// Using break with nested loops.
class BreakLoop3 {
public static void main(String args[]) {
for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10)
break; // terminate loop if j is 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
}

This program generates the following output:


Pass 0: 0 1 2 3 4 5 6 7 8 9
Pass 1: 0 1 2 3 4 5 6 7 8 9
Pass 2: 0 1 2 3 4 5 6 7 8 9
Loops complete.

Ramesh Babu N, Page 40 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Java does not have a goto statement. Java defines an expanded form of the break statement
using which break out of one or more blocks of code. When this form of break executes,
control is transferred out of the named block.

The general form of the labeled break statement is shown here:


break label;
label is the name of a label that identifies a block of code.

To name a block, put a label at the start of it. A label is any valid Java identifier followed by a
colon.
Example 1:
// Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; //break outof second
block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}

Running this program generates the following output:


Before the break.
This is after second block.

One of the most common uses for a labeled break statement is to exit from nested loops.

Example 2:
// Using break to exit from nested loops
class BreakLoop4 {
public static void main(String args[]) {
outer: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");

for(int j=0; j<100; j++) {


if(j == 10) break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}

This program generates the following output:


Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

Ramesh Babu N, Page 41 of 43


Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
Using continue
A continue statement causes control to be transferred directly to the conditional expression
that controls the loop.

In a for loop, control goes first to the iteration portion of the for statement and then to the
conditional expression.

Example 1:
// Demonstrate continue.
class Continue {
public static void main(String args[]) {

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


System.out.print(i + " ");
if (i%2 == 0)
continue;
System.out.println("");
}
}
}

This code uses the % operator to check if i is even. If it is, the loop continues without printing
a newline. Here is the output from this program:
0 1
2 3
4 5
6 7
8 9

continue may specify a label to describe which enclosing loop to continue.


Example 2:
// Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}

The continue statement in this example terminates the loop counting j and continues with
the next iteration of the loop counting i. Here is the output of this program:
0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
Ramesh Babu N, Page 42 of 43
Dept. of CS & BS, KSSEM
OOP with Java (BCS306A)
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81

return
The return statement is used to explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method.
Example:
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;

System.out.println("Before the return.");


if(t)
return; // return to caller

System.out.println("This won't execute.");


}
}

The output from this program is shown here:


Before the return.

Textbook:
1. Java: The Complete Reference, Twelfth Edition, by Herbert Schildt, November 2021,
McGraw-Hill, ISBN: 9781260463422

Ramesh Babu N, Page 43 of 43


Dept. of CS & BS, KSSEM

You might also like