2022 BCS306A OOC With Java Module 1 Notes
2022 BCS306A OOC With Java Module 1 Notes
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
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 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.
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.
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 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.
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.)
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).
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.
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.
/*
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[]) {
}
}
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.
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
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.
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:
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.
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
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.
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.
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:
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:
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two
possible values, true or false.
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
b = false;
if(b)
System.out.println("This is not executed.");
This is executed.
10 > 9 is true
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.
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:
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);
...
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;
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;
y = 100;
System.out.println("y is now: " + y);
}
}
}
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;
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.
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;
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
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;
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.
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.
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.");
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];
This alternative declaration form offers convenience when declaring several arrays at the
same time. For example,
int[] nums, nums2, nums3; // create three arrays
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.
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.
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[ ].
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.
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).
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;
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
a += 5;
b *= 4;
c += a * b;
c %= 6;
c = ++b;
d = a++;
c++;
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.
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
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.
i = a << 2;
b = (byte) (a << 2);
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).
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 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
Output:
a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false
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.
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);
}
}
Operator Precedence
The following Table shows the order of precedence for Java operators, from highest to lowest.
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).
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)
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.
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");
}
}
}
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.
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
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;
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.
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
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[]) {
Example:
// Using the comma.
class Comma {
public static void main(String args[]) {
int a, b;
Output:
a = 1
b = 4
a = 2
b = 3
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 general form of the for-each version of the for is shown here:
for(type itr-var : collection) statement-block
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];
Example:
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();
}
}
}
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[]) {
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.");
}
}
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.");
}
}
}
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 + ": ");
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[]) {
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
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;
Textbook:
1. Java: The Complete Reference, Twelfth Edition, by Herbert Schildt, November 2021,
McGraw-Hill, ISBN: 9781260463422