0% found this document useful (0 votes)
22 views

Two Paradigms: Process-Oriented Model

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Two Paradigms: Process-Oriented Model

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Object Oriented Programming with JAVA(BCS306A) Module 1

Module 1
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

TWO PARADIGMS
All computer programs consist of two elements: code and data.
Process-oriented model: This approach characterizes a program as a series of linear steps
(that is, code). The process-oriented model can be thought of as code acting on data.
Procedural languages such as C employ this model
To manage increasing complexity, the second approach, called object-oriented programming,
was conceived. Object-oriented programming organizes a program around its data (that is,
objects) and a set of well-defined interfaces to that data. An object-oriented program can be
characterized as data controlling access to code.

ABSTRACTION
An essential element of object-oriented programming is abstraction. Humans manage
complexity through abstraction. For example, people do not think of a car as a set of tens of
thousands of individual parts. They think of it as a well-defined object with its own unique
behavior. This abstraction allows people to use a car to drive to the grocery store without
being overwhelmed by the complexity of the parts that form the car. They can ignore the
details of how the engine, transmission, and braking systems work. Instead, they are free to
utilize the object as a whole. A powerful way to manage abstraction is through the use of
hierarchical classifications

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. One way to think about encapsulation
is as a protective wrapper that prevents the code and data from being arbitrarily accessed by
other code defined outside the wrapper.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 1


Object Oriented Programming with JAVA(BCS306A) Module 1

In Java, the basis of encapsulation is the class. 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. Specifically, 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.
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. 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.
If you wanted to describe a more specific class of animals, such as mammals, they would
have more specific attributes, such as type of teeth and mammary glands. This is known as a
subclass of animals, where animals are referred to as mammals’ superclass. Since mammals
are simply more precisely specified animals, they inherit all of the attributes from animals. A
deeply inherited subclass inherits all of the attributes from each of its ancestors in the class
hierarchy

 Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to
be used for a general class of actions. The specific action is determined by the exact nature of
the situation. 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 floatingpoint
values, and one for characters. The algorithm that implements each stack is the same, even
though the data being stored differs.
A First Simple Program

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

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 2


Object Oriented Programming with JAVA(BCS306A) Module 1

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.");
}
}
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:
This is a simple Java program
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
LEXICAL ISSUES
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
 Whitespace
Java is a free-form language. This means that you do not need to follow any special
indentation rules. In Java, whitespace is a space, tab, or newline
 Identifiers
Identifiers are used to name things, such as classes, variables, and methods. An identifier may
be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore
and dollar-sign characters. (The dollar-sign character is not intended for general use.) They
must not begin with a number, lest they be confused with a numeric literal. Again, Java is
case-sensitive, so VALUE is a different identifier than Value.
 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”

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 3


Object Oriented Programming with JAVA(BCS306A) Module 1

 Comments
There are three types of comments namely Single-line and multiline and documentation
comment. This type of comment is used to produce an HTML file that documents your
program. The documentation comment begins with a /** and ends with a */.
 Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon. As you have seen, it is used to terminate statements. The
separators are shown in the following table:

THE JAVA KEYWORDS


There are 50 keywords currently defined in the Java language. These keywords cannot be
used as identifiers. Thus, they cannot be used as names for a variable, class, or method. The
keywords const and goto are reserved but not used. In addition to the keywords, Java reserves
the following: true, false, and null. These are values defined by Java. You may not use these
words for the names of variables, classes, and so on

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 4


Object Oriented Programming with JAVA(BCS306A) Module 1

Java Is a Strongly Typed Language


This means every variable has a type, every expression has a type, and every type is strictly
defined. Second, 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 as in some languages. The Java compiler checks all expressions and
parameters to ensure that the types are compatible. Any type mismatches are errors that must
be corrected before the compiler will finish compiling the class.

THE PRIMITIVE TYPES


Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. The primitive types are also commonly referred to as simple types.
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.
INTEGERS
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers.

 Byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to
127.
Byte variables are declared by use of the byte keyword. For example, the following declares
two byte variables called b and c:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 5


Object Oriented Programming with JAVA(BCS306A) Module 1

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
leastused 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. 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. The range of a long is quite large. This makes it useful
when big, whole numbers are needed.
FLOATING-POINT TYPES
Floating-point numbers, also known as real numbers, are used when evaluating expressions
that require fractional precision. There are two kinds of floating-point types, float and double,
which represent single- and double-precision numbers, respectively. Their width and ranges

are shown here:


 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,
but will become imprecise when the values are either very large or very small. Variables
of type float are useful when you need a fractional component, but don’t require a large
degree of precision.
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. All transcendental math
functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to
maintain accuracy over many iterative calculations, or are manipulating large-valued
numbers, double is the best choice
CHARACTERS

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 6


Object Oriented Programming with JAVA(BCS306A) Module 1

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. . Thus, in Java
char is a 16-bit type.

BOOLEANS
Java has a primitive type, called boolean, for logical values. It can have only one of two
possible values, true or false. This is the type returned by all relational operators, as in the
case of a < b. boolean is also the type required by the conditional expressions that govern the
control statements such as if and for

VARIABLES

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 7


Object Oriented Programming with JAVA(BCS306A) Module 1

The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have
a scope, which defines their visibility, and a lifetime.
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:
type identifier [ = value ][, identifier [= value ] …]
Here, type is one of Java’s atomic types, or the name of a class or interface. (Class and
interface types are discussed later in Part I of this book.) The identifier is the name of the
variable.

Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows
variables to be initialized dynamically, using any expression valid at the time the variable is
declared.

The Scope and Lifetime of Variables


So far, all of the variables used have been declared at the start of the main( ) method.
However, Java allows variables to be declared within any block. a block is begun with an
opening curly brace and ended by a closing curly brace. 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.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 8


Object Oriented Programming with JAVA(BCS306A) Module 1

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. However, not all types
are compatible, and thus, not all type conversions are implicitly allowed.
Java’s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion
will take place if the following two conditions are met
• The two types are compatible.
• The destination type is larger than the source type
When these two conditions are met, a widening conversion takes place. For example, the int
type is always large enough to hold all valid byte values, so no explicit cast statement is
required.
Casting Incompatible Types
Although the automatic type conversions are helpful, they will not fulfill all needs. For
example, what if you want to assign an int value to a byte variable? This conversion will not
be performed automatically, because a byte is smaller than an int. This kind of conversion is
sometimes called a narrowing conversion, since you are explicitly making the value narrower
so that it will fit into the target type. To create a conversion between two incompatible types,
you must use a cast. A cast is simply an explicit type conversion. It has this general form:
(target-type) value;
Here, target-type specifies the desired type to convert the specified value to. For example, the
following fragment casts an int to a byte.
int a;
byte b;
// …
b = (byte) a;

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 9


Object Oriented Programming with JAVA(BCS306A) Module 1

AUTOMATIC TYPE PROMOTION IN EXPRESSIONS

In addition to assignments, there is another place where certain type conversions may occur:
in expressions. To see why, consider the following. In an expression, the precision required
of an intermediate value will sometimes exceed the range of either operand. For example,
examine the following expression:

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. This means that the subexpression a*b is
performed using integers—not bytes. Thus, 2,000, the result of the intermediate expression,
50 * 40, is legal even though a and b are both specified as type byte.

The Type Promotion Rules


Java defines several type promotion rules that apply to expressions. They are as follows:
First, all byte, short, and char values are promoted to int, as just described. Then, 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 are double, the result is double.
The following program demonstrates how each value in the expression gets promoted to
match the second argument to each binary operator:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 10


Object Oriented Programming with JAVA(BCS306A) Module 1

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. Arrays offer a convenient means of grouping related information

One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you
first must create an array variable of the desired type. The general form of a one-dimensional
array declaration is
type var-name[ ];
Here, type declares the element type (also called the base type) of the array. The element type
determines the data type of each element that comprises the array. Thus, the element type for
the array determines what type of data the array will hold. For example, the following
declares an array named month_days with the type “array of int”:
int month_days[];
The general form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type [size];
Here, type specifies the type of data being allocated, size specifies the number of elements in
the array, and array-var is the array variable that is linked to the array. That is, to use new to
allocate an array, you must specify the type and number of elements to allocate.
month_days = new int[12];

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 11


Object Oriented Programming with JAVA(BCS306A) Module 1

When you run this program, it prints the number of days in April. As mentioned, Java array
indexes start with zero, so the number of days in April is month_days[3] or 30. It is possible
to combine the declaration of the array variable with the allocation of the array itself, as
shown here:
int month_days[] = new int[12];

Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. To declare a multidimensional
array variable, specify each additional index using another set of square brackets. For
example, the following declares a twodimensional 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

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 12


Object Oriented Programming with JAVA(BCS306A) Module 1

Alternative Array Declaration Syntax


There is a second form that may be used to declare an array:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable.
For example, the following two declarations are equivalent:

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 following table lists the arithmetic operators:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 13


Object Oriented Programming with JAVA(BCS306A) Module 1

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. The following example program demonstrates
the %:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 14


Object Oriented Programming with JAVA(BCS306A) Module 1

Arithmetic Compound Assignment Operators

can be rewritten as
var op= expression;

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.
x = 42;
y = ++x;
In this case, y is set to 43 as you would expect, because the increment occurs before x is
assigned to y.

The Bitwise Operators


Java defines several bitwise operators that can be applied to the integer types: long, int, short,
char, and byte. These operators act upon the individual bits of their operands. They are
summarized in the following table:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 15


Object Oriented Programming with JAVA(BCS306A) Module 1

The Bitwise Logical Operators


The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of
each operation. In the discussion that follows, keep in mind that the bitwise operators are
applied to each individual bit within each operand.

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. That is, the >>
moves all of the bits in the specified value to the right the number of bit positions specified
by num
The following code fragment shifts the value 32 to the right by two positions, resulting in a
being set to 8:
int a = 32;
a = a >> 2; // a now contains 8
When a value has bits that are “shifted off,” those bits are lost.

The Unsigned Right Shift


As you have just seen, the >> operator automatically fills the high-order bit with its previous
contents each time a shift occurs. This preserves the sign of the value. However, sometimes
this is undesirable. For example, if you are shifting something that does not represent a
numeric value, you may not want sign extension to take place. This situation is common
when you are working with pixel-based values and graphics. In these cases, you will
generally want to shift a zero into the high-order bit no matter what its initial value was. This
is known as an unsigned shift. To accomplish this, you will use Java’s unsigned, shiftright
operator, >>>, which always shifts zeros into the high-order bit.

The following code fragment demonstrates the >>>. Here, a is set to –1, which sets all 32 bits
to 1 in binary. This value is then shifted right 24 bits, filling the top 24 bits with zeros,
ignoring normal sign extension. This sets a to 255.
int a = -1;
a = a >>> 24;

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 16


Object Oriented Programming with JAVA(BCS306A) Module 1

Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:

The outcome of these operations is a boolean value.

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 Assignment Operator


The assignment operator is the single equal sign, =. The assignment operator 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

The ? Operator
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. The result of the ?
operation is that of the expression evaluated. Both expression2 and expression3 are required
to return the same (or compatible) type, which can’t be void.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 17


Object Oriented Programming with JAVA(BCS306A) Module 1

OPERATOR PRECEDENCE
The below table shows the order of precedence for Java operators, from highest to lowest.
Operators in the same row are equal in precedence. In binary operations, the order of
evaluation is left to right (except for assignment, which evaluates right to left). Although they
are technically separators, the [ ], ( ), and . can also act like operators.

USING PARENTHESES
Parentheses raise the precedence of the operations that are inside them. For example,
consider the following expression:
a >> b + 3
This expression first adds 3 to b and then shifts a right by that result. That is, this
expression can be rewritten using redundant parentheses like this:
a >> (b + 3)
However, if you want to first shift a right by b positions and then add 3 to that result, you will
need to parenthesize the expression like this:
(a >> b) + 3
In addition to altering the normal precedence of an operator, parentheses can sometimes be
used to help clarify the meaning of an expression. For anyone reading your code, a
complicated expression can be difficult to understand. Adding redundant but clarifying
parentheses to complex expressions can help prevent confusion later.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 18


Object Oriented Programming with JAVA(BCS306A) Module 1

CONTROL STATEMENTS
A programming language uses control statements to cause the flow of execution to advance
and branch based on changes to the state of a program. 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. These statements allow you to control
the flow of your program’s execution based upon conditions known only during run time.

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

 NESTED IFS
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the else
and that is not already associated with an else.

 THE IF-ELSE-IF LADDER

A common programming construct that is based upon a sequence of nested ifs is the if-elseif
ladder. It looks like this:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 19


Object Oriented Programming with JAVA(BCS306A) Module 1

The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed. If none of the conditions is true, then the final else statement will be
executed. The final else acts as a default condition; that is, if all other conditional tests fail,
then the last else statement is performed. If there is no final else and all other conditions are
false, then no action will take place.
 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.

 NESTED SWITCH STATEMENTS


You can use a switch as part of the statement sequence of an outer switch. This is called a
nested switch. Since a switch statement defines its own block, no conflicts arise between the
case constants in the inner switch and those in the outer switch.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 20


Object Oriented Programming with JAVA(BCS306A) Module 1

ITERATION STATEMENTS
Java’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met.
 WHILE
The while loop is Java’s most fundamental loop statement. It repeats a statement or block
while its controlling expression is true. Here is its general form:

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

 FOR
Beginning with JDK 5, 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. The second is the newer “for-each”
form.
Here is the general form of the traditional for statement:

The for loop operates as follows. When the loop first starts, the initialization portion of the
loop is executed. Generally, this is an expression that sets the value of the loop control
variable, which acts as a counter that controls the loop. It is important to understand that the
initialization expression is executed only once. Next, condition is evaluated. This must be a
Boolean expression. It usually tests the loop control variable against a target value. If this
expression is true, then the body of the loop is executed. If it is false, the loop terminates.
Next, the iteration portion of the loop is executed. This is usually an expression that
increments or decrements the loop control variable. The loop then iterates, first evaluating the
conditional expression, then executing the body of the loop, and then executing the iteration
expression with each pass. This process repeats until the controlling expression is false.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 21


Object Oriented Programming with JAVA(BCS306A) Module 1

 THE FOR-EACH VERSION OF THE FOR LOOP


Java adds the for-each capability by enhancing the for statement. The advantage of this
approach is that no new keyword is required, and no preexisting code is broken. The for-each
style of for is also referred to as the enhanced for loop. 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

JUMP STATEMENTS
Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.
 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.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 22


Object Oriented Programming with JAVA(BCS306A) Module 1

Using break to Exit a Loop :


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 lo
op is terminated and program control resumes at the next statement following the loop.

Using break as a Form of Goto


Java does not have a goto statement because it provides a way to branch in an arbitrary and
unstructured manner.
Java defines an expanded form of the break statement. By using this form of break, you can,
for example, break out of one or more blocks of code. These blocks need not be part of a loop
or a switch. They can be any block. Further, you can specify precisely where execution will
resume, because this form of break works with a label. As you will see, break gives you the
benefits of a goto without its problems.

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 23


Object Oriented Programming with JAVA(BCS306A) Module 1

 Using continue
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for this
particular iteration.
Here is an example program that uses continue to cause two numbers to be printed on each
line:

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 24


Object Oriented Programming with JAVA(BCS306A) Module 1

 Return
The last control statement is 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.
At any time in a method, the return statement can be used to cause execution to branch back
to the caller of the method. Thus, the return statement immediately terminates the method in
which it is executed.

Questions:
1. List out the 2 paradigms of programming
2. What is type casting illustrate with examples
3. Explain initialization of 1D, 2D arrays in java
4. Explain the OOP concepts
5. Illustrate for each with example
6. Demonstrate the usage of Jump statements
7. Exaplin javas selection commands
8. Bring out the difference between >>, >>>, <<

Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 25

You might also like