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

JAVA Module 1

1. The document discusses object-oriented programming concepts in Java including classes, objects, encapsulation, inheritance, and polymorphism. 2. It provides examples of procedural and object-oriented programming, explaining that object-oriented programs organize code around data. 3. The key aspects of object-oriented programming - encapsulation, inheritance, and polymorphism - are explained along with examples in Java.

Uploaded by

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

JAVA Module 1

1. The document discusses object-oriented programming concepts in Java including classes, objects, encapsulation, inheritance, and polymorphism. 2. It provides examples of procedural and object-oriented programming, explaining that object-oriented programs organize code around data. 3. The key aspects of object-oriented programming - encapsulation, inheritance, and polymorphism - are explained along with examples in Java.

Uploaded by

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

Object Oriented Programming with Java BCS306A

An Overview of Java

Object Oriented Programming:


 Object oriented programming (OOP) is the core of Java programming.
 Java is a general purpose, object- oriented programming language developed by Sun
Microsystems. It was invented by James Gosling and his team and was initially called
as Oak.
 The most important feature that made Java very popular was the ―Platform-
Independent‖ approach.
 It was the first programming language that did not tie-up with any particular operating
system (or hardware) rather Java programs can be executed anywhere and on any
system.
 Java was designed for the development of the software for consumer electronic
devices like TVs, VCRs, etc.
Two Paradigms:
 Every program contains 2 components code and data.
 Two approaches are there to solve the problem and in program writing:
Procedureoriented and object oriented.
Procedure Oriented:
 Procedure oriented programs are written based on ―what‘s happening‖ around,
where the code acts on data. Ex: C etc
 Problems increases in procedure oriented as the program grows larger and more
complex.
Object Oriented:
 Object oriented programs are written based on ―Who is being affected‖ around,
which manages the increasing complexity.
 It organizes program around data and well defined interfaces of that data.
 Characterized as data controlling access to code. Ex: C++, JAVA, Small Talk etc

The Three OOP:


The three important features of OOP are:
 Encapsulation
 Inheritance
 Polymorphism
Dept. of ISE, GSSSIETW, Mysuru.
Object Oriented Programming with Java BCS306A

Encapsulation:
 Encapsulation is the mechanism that binds together code and 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 state and behavior
(data & code) that will be shared by set of objects.
 Each object contains the structure and behavior defined by the class. The data
defined by the class are called instance variables (member variables), the code that
operates on that data are called methods (member functions).

Inheritance:
 Inheritance is the process by which one object acquires the properties of another
object. This is important as it supports the concept of hierarchical classification.
 By the use of inheritance, a class has to define only those qualities that make it
unique. The general qualities can be derived from the parent class or base class.
 Ex: A child inheriting properties from parents.

Polymorphism
 Polymorphism (meaning many forms) is a feature that allows one interface to be
used for a general class of actions. The specific action determined by the exact
nature of the situation. This concept is often expressed as ― one interface, multiple
methods‖.
 Ex: + can be used for addition of 2 numbers and also concatenation of 2 strings.
System.out.println(2+4); // outputs 6 as answer
System.out.println(Hello + Gautham); // outputs Hello Gautham as answer Apart
from this the additional features include:

Object:
 An object can be any real world entity.
 Ex: an animal, bank, human, box, fan etc
 An object is a software bundle of related state and behavior.
 An object is an instance of class.

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Class:
 A class is a blueprint or prototype from which objects are created.
 Its just a template for an object, which describes an object.
 Ex: a class describes how an animal looks like.
 A class is a user defined data type.

Abstraction:
 Data abstraction refers to providing only essential information to the outside world
and hiding their background details i.e., to represent the needed informatin in
program without presenting the details.
 Ex: a database system hides certain details of how data is stored and created and
maintained.

Polymorphism, Encapsulation and Inheritance work Together


 The 3 principles of OOP Polymorphism, Encapsulation and Inheritance combines
together to make the programming robust and scalable.
 Encapsulation allows migrating the implementation without disturbing the code that
depends on class.
 Polymorphism allows creating clean, sensible, readable, resilient code.
 Inheritance mainly deals with the code reusability.

A First Simple Program


class Example
{
public static void main(String args[])
{
System.out.println(―Welcome to Programming in Java‖);
}
}

1. Open the notepad and type the above program

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

2. Save the above program with .java extension, here file name and class name
should be same,
ex: Example.java
3. Open the command prompt and Compile the above program
javac Example.java
From the above compilation the java compiler produces a bytecode (.class file)
4. Finally run the program through the
interpreter java Example.java

Output of the program:


Welcome to Programming in Java

Note:
 In Java all code must reside inside a class and name of that class should match the
name of the file that holds the program.
 Java is case-sensitive

Compiling the program


 To compile the program, execute the compiler ―javac, specifying the name of the
source file on the command line as shown below
C:\> javac Example.java
 The ―javac: compiler creates a file called ―Example.class that contains the bytecode
version of the program.
 To run the program, we must use the java interpreter called ―java‖. To do so we pass
the class name ―Example as a command-line argument as shown below
C:\> java Example
 When you run the program we get the output:
Welcome to Programming in Java

Description:

(1) Class declaration: ―class Example‖ declares a class, which is an object- oriented
construct. Sampleone is a Java identifier that specifies the name of the class to be
defined.
(2) Opening braces: Every class definition of Java starts with opening braces and ends

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

with matching one.


(3) The main line: the line ― public static void main (String args[]) ― defines a method
name main. Java application program must include this main. This is the starting point
of the interpreter from where it starts executing. A Java program can have any number
of classes but only one class will have the main method.
(4) Public: This key word is an access specifier that declares the main method as
unprotected and therefore making it accessible to the all other classes.
(5) Static: Static keyword defines the method as one that belongs to the entire class and
not for a particular object of the class. The main must always be declared as static.
(6) Void: the type modifier void specifies that the method main does not return any value.
(7) The println: It is a method of the object out of system class. It is similar to the printf
or cout of c or c++. This always appends a newline character to the end of the string
i.e, any subsequent output will start on a new line.

A Second Short Program

/* This is a short example


Name of file : Example2.java */
class Example2{
public static void main(String args[])
{
int n=3;
System.out.println(― the value of n is ―+n);
n=n+5;
System.out.print(― the new value is‖);
System.out.println(n);
}
}
Output:
the value of n is 3
the new value of n is 8

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

The statement System.out.println(― the value of n is ―+n), the sign + causes the value of
―n‖ to be appended to the string that precedes it, and the resulting string is output. (Actually
n is first converted from an integer into its string equivalent and the concatenated with the
string that precedes it).
The System.out.print( ) method is just like println( ) except that it does not output a newline
character after each call.

Two Control Statements


Here in this chapter initially we focus on two control statements if and for loop , the
detailed control statements will be discussed in module 2.

if statement
 The if- statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluates
to true.
 Here is the general form of the if statement:
if (condition) statement;
 Here the condition is Boolean expression.
 If the condition is true then the statement is executed, if false then statement will be
skipped.

Example:
class Example
{
public static void main(String args[])
{
int a=10;
if(a>0)
System.out.println(―a is positive number‖);
System.out.println(― End of program‖);
}

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

In the above program since a is greater than 0 it prints the output asa is positive number.
If incase a is -1 or negative value the condition fails and it prints onlyEnd of program

The for loop


 The for loop is similar to that of C/C++
 Here is the general form of the traditional for statement:
for(initialization; condition; iteration)
{
//body
}
 Initialization sets the loop control variable to initial value.
 Condition is a Boolean expression which tests the loop
 Iteration expression tells hoe the control variable has to change at each iteration.
Generally the increment or decrement operator is used to perform iteration.
Example:
class Example
{
public static void main(String args[])
{
int a; for(a=0;a<5;a++)
System.out.println(a); System.out.println(― End of program‖);
}
}

Output:
0
1
2
3
4
End of program

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Using blocks of code


 Java supports code blocks - which means that two or more statements are grouped
into blocks of code.
 Opening and closing braces is used to achieve this.
 Each block is treated as logical unit.
 Whenever two or more statements has to be linked blocks can be used.
Example:
class Example
{
public static void main(String args[])
{
int a=10;
if(a>0)
{ // begin of block
System.out.println(―a is positive number‖);
System.out.println(― inside block‖);
}// end of block
}
}

Lexical issues:
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
Whitespace:
 Java is a free from language- means no need to follow any indentation rules.
 Whitespace is a space, tab, or newline.
Java character set:
 The smallest unit of Java language is its character set used to write Java tokens. This
character is defined by unicode character set that tries to create character for a large
number of characters worldwide.
 The Unicode is a 16-bit character coding system and currently supports 34,000
defined characters derived from 24 languages of worldwide.

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Key Words:
Java program is basically a collection of classes. A class is defined by a set of declaration
statements and methods containing executable statements. Most statement contains an
expression that contains the action carried out on data. The compiler recognizes the tokens
for building up the expression and statements. Smallest individual units of programs are
known as tokens. Java language includes five types of tokens. They are
(a) Reserved Keyword
(b) Identifiers
(c) Literals.
(d) Operators
(e) Separators.
Reserved keyword:
Java language has 61 words as reserved keywords. They implement specific feature of the
language. The keywords combined with operators and separators according to syntax build
the Java language.

Identifiers:
Identifiers are programmer-designed token used for naming classes methods variable,
objects, labels etc. The rules for identifiers are
1. They can have alphabets, digits, dollar sign and underscores.
2. They must not begin with digit.
3. Uppercase and lower case letters are distinct.
4. They can be any lengths.

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

5. Name of all public method starts with lowercase.


6. In case of more than one word starts with uppercase in next word.
7. All private and local variables use only lowercase and underscore.
8. All classes and interfaces start with leading uppercases.
9. Constant identifier uses uppercase letters only.

Example for valid identifiers:


Var_1, count, $value etc

Example for invalid identifiers:


6name, var@value, my/name etc

Literals:
Literals in Java are sequence of characters that represents constant values to be stored in
variables. Java language specifies five major types of Literals. They are:
1. Integer Literals. Ex: 100
2. Floating-point Literals. Ex: 98.6
3. Character Literals. Ex: ‗X‘
4. String Literals. Ex: ―This is a Test‖
5. Boolean Literals. Ex: true or false
Operators:
An operator is a symbol that takes one or more arguments and operates on them to produce
an result.

Separators:
Separators are the symbols that indicate where group of code are divided and arranged.
Some of the operators are:

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Comments:
 Java supports 3 styles of comments
 Multiline comment: this type of comment begins with /* and ends with */
Ex: /* Welcome to
Java Programming */
 Single line comments: this type of comment begins with // and ends at the end of
current line
Ex: // Welcome to java Programming
 Documentation Comment: this type of comment is used to produce an HTML file
that documents your program. The documentation comment begins with /** and
ends with */

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Data types, variables and arrays

Java is a strongly typed language:


 The strongly typed nature of Java gives it the robustness and safety for it.
 Every variable and expression has strictly defined type.
 Assignments, parameter passing or explicit value passing are checked for type
compatibility.
 Java compiler checks all expressions and parameters to ensure type compatibility.

Data types
The various data types supported in java is as follows:

Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. As shown in above figure.
 The primitive types represent single values—not complex objects. Although Java is
otherwise completely object-oriented, the primitive types are not.

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

 They are analogous to the simple types found in most other non–object-oriented
languages.
 The reason for this is efficiency. Making the primitive types into objects would have
degraded performance too much. The primitive types are defined to have an explicit
range and mathematical behavior.
 Because of Java‗s portability requirement, all data types have a strictly defined range.
For example, an int is always 32 bits, regardless of the particular platform.

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.
 Many other computer languages support both signed and unsigned integers.
 However, Java‗s designers felt that unsigned integers were unnecessary. Specifically,
they felt that the concept of unsigned was used mostly to specify the behavior of
the high-order bit, which defines the sign of an integer value.

byte
 The smallest integer type is byte.
 This is a signed 8-bit type that has a range from –128 to127.
 Variables of type byte are especially 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.

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

 Here are some examples of short variable declarations:


short s;
short t;
Floating-Point Types

 Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision.
 For example, calculations such as square root, or transcendental such as sine and
cosine, result in a value whose precision requires a floating-point type.
 There are two kinds of floating-point types, float and double, which represent
single- and double-precision numbers, respectively.
float
 The type float specifies a single-precision value that uses 32 bits of storage.
Ex: float hightemp;
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.

Characters
 In Java, the data type used to store characters is char.
 However, C/C++ programmers beware: char in Java is not the same as char in C or
C++.
 In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode
Dept. of ISE, GSSSIETW, Mysuru.
Object Oriented Programming with Java BCS306A

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.

 Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no
negative.

Booleans:
Java has a simple type called boolean for logical values. It can have only one of two possible
values. They are true or false.

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Literals:
A constant value in Java is created by using a literal representation of it. There are 5 types of
literals.
 Integer Literals.
 Floating-point Literals.
 Character Literals.
 String Literals.
 Boolean Literals.
Integer literals:
 Any whole number value is an integer literal.
 These are all decimal values describing a base 10 number.
 There are two other bases which can be used in integer literal, octal( base 8) where 0
is prefixed with the value, hexadecimal (base 16) where 0X or 0x is prefixed with the
integer value.
Example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;

Floating point literals:


 The default type when you write a floating-point literal is double, but you can
designate it explicitly by appending the D (or d) suffix
 However, the suffix F (or f) is appended to designate the data type of a floating-point
literal as float.
 We can also specify a floating-point literal in scientific notation using Exponent (short
E ore), for instance: the double literal 0.0314E2 is interpreted as:

Example:
0.0314 *10² (i.e 3.14).
6.5E+32 (or 6.5E32) Double-precision floating-point literal
7D Double-precision floating-point literal
.01f Floating-point literal

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Character literals:
 char data type is a single 16-bit Unicode character.
 We can specify a character literal as a single printable character in a pair of single
quote characters such as 'a', '#', and '3'.
 You must know about the ASCII character set. The ASCII character set includes 128
characters including letters, numerals, punctuation etc.
 Below table shows a set of these special characters.

Boolean Literals:
 The values true and false are treated as literals in Java programming.
 When we assign a value to a boolean variable, we can only use these two values.
 Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is equivalent
to false in Java.
 We have to use the values true and false to represent a Boolean value.
Example
boolean chosen = true;

String Literal
 The set of characters in represented as String literals in Java.
 Always use "double quotes" for String literals.
 There are few methods provided in Java to combine strings, modify strings and to
know whether to strings have the same values.
Example:
―hello world‖
―Java‖

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Variables:
A variable is an identifier that denotes a storage location used to store a data value. A
variable may have different value in the different phase of the program. To declare one
identifier as a variable there are certain rules. They are:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.

Declaring Variable: One variable should be declared before using.


The syntax is
type identifier [ = value][, identifier [= value] ...] ;
Example:
int a,b,c;
float quot, div;

Initializing a variable: A variable can be initialized in two ways. They are


(a) Initializing by Assignment statements.
(b) Dynamic Initialization
Initializing by assignment statements:
 One variable can be initialize using assignment statements. The syntax is :
Variable-name = Value;
Example: int a=10,b,c=16;
Double pi=3.147;

Dynamic initialization:
 Java allows variables to be initialized dynamically, using expression valid at the time
variable is declared.
Example:
class Example
{
public static void main(String args[])
{
double a=10, b=2.6;
double c=a/b;

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

System.out.println(―value of c is‖+c);
}
}

The Scope and Lifetime of Variables


 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.
 A scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
 Many other computer languages define two general categories of scopes: global
and local. However, these traditional scopes do not fit well with Java‗s strict,
object-oriented model.
 As a general rule, variables declared inside a scope are not visible (that is, accessible)
to code that is defined outside that scope. Thus, when you declare a variable within a

scope, you are localizing that variable and protecting it from unauthorized access
and/or modification.
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;
}
// y = 100; // Error! y not known here
// x is still known here. System.out.println("x is " + x);
}
}

Note:
 There should not be two variables with the same name in different scope.
 The variable at outer scope can be accessed in inner scope but vice versa is not
Dept. of ISE, GSSSIETW, Mysuru.
Object Oriented Programming with Java BCS306A

possible.

Type Conversion and casting


It is often necessary to store a value of one type into the variable of another type. In these
situations the value that to be stored should be casted to destination type. Assigning a value
of one type to a variable of another type is known as Type Casting .Type casting can be
done in two ways.
In Java, type casting is classified into two types,

Widening or Automatic type converion


Automatic Type casting take place when,
the two types are compatible
the target type is larger than the source type

Example :

public class Test


{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

System.out.println("Int value "+i);


System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Output :
Int value 100
Long value 100
Float value 100.0

Narrowing or Explicit type conversion


When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.
Example :
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);

}
}
Output :
Double value 100.04
Long value 100
Int value 100

Automatic type promotion in expressions:


 Type conversions also occur in expressions.
 Java automatically promotes each byte, short, or char operand to int when evaluating

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

an expression.
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
The operands were automatically promoted to int when the expression was evaluated,
theresult has also been promoted to int. Thus, the result of the expression is now of type
int,which cannot be assigned to a byte without the use of a cast.

byte b = 50;
b = (byte)(b * 2); which yields the correct value of 100.

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 is double, the result is double.

Arrays in Java
Array, which stores a fixed-size sequential collection of elements of the same
type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.

Declaring Array Variables:


To use an array in a program, you must declare a variable to reference the array, and
you must specify the type of array the variable can reference. Here is the syntax for
declaring an array variable:

dataType[] arrayRefVar; or dataType arrayRefVar[];

Example:

The following code snippets are examples of this syntax:

int[] myList; or int myList[];

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Creating Arrays:

You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:

It creates an array using new dataType[arraySize];


It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to
the variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];


Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};


The array elements are accessed through the index. Array indices are 0-based; that is,
they start from 0 to arrayRefVar.length-1.

Example:

Following statement declares an array variable, myList, creates an array of 10 elements of


double type and assigns its reference to myList:

double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and
the indices are from 0 to 9.

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all
of the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < 4; i++)
{
System.out.println(myList[i] + " ");
}
}

Multidimensional Arrays
Java does not support multidimensional arrays. However, you can declare and create an array
of arrays (and those arrays can contain arrays, and so on, for however many dimensions you
need), and access them as you would C-style multidimensional arrays:
int coords[] [] = new int[12] [12];
coords[0] [0] = 1; coords[0] [1] = 2;

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

A few words about strings:


 Java supports string type which is an object. It is used to declare string variables
 Array of strings can also be declared.
 A string variable can be assigned to another string variable.
 String variable can also be used as argument.
Example:
String name1=‖gautham‖, name2;
Name2=name1; // sets name2 withvalue gautham
System.out.println(name2); // string variable passed as parameter.

Type Inference with Local Variables

 It is possible to let the compiler infer the type of a local variable based on the type of its
initialize. Thus avoiding the need to explicitly specify the type.
 To support local variable type inference the context sensitive identifier var was added to
java as a reserved type name.
 To use local variable type inference, the variable must be declared with var as the type
name and it must include an initialize. Ex: double avg=10.0;
 Using type inference this declaration can be written as var avg=10.0;
 In both the cases, avg will be of type. In the first case, its type is explicitly specified. In
the second, its type is inferred as double because the initialize 10.0 is of type double.
 var is simply a user defined identifier with no special meaning. Ex: int var = 1; is still
valid.
 var cannot be used as the name of a class, other reference types like interface,
enumeration or annotation or as the name of a generic type parameter.
 Some var Restrictions:
o Only one variable can be declared at a time.
o A variable cannot use null as an initialize.
o The variable being declared cannot be used by the initialize expression.
o Var cannot be used with array initialize.
o For Ex: var myArray = new int[10]; // This is valid.
o Var myArray = {1,2,3}; // This is not valid.

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Programs:
// Compute distance light travels using long variables.
class Light
{
public static void main(String args[])
{
int lightspeed;
long days;
long seconds;
long distance; // approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.

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

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

// Demonstrate char data type.


class CharDemo
{
public static void main(String args[])
{
char ch1, ch2; ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
This program displays the following output:
ch1 and ch2: X Y

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

// Demonstrate boolean values.


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

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

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

Scope of variable
class LifeTime
{
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown here:
y is: -1

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100

Type conversion
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
Conversion of double to byte.
d and b 323.142 67

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Operators
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:

The operands of the arithmetic operators must be of a numeric type. You cannot use them on
boolean types, but you can use them on char types, since the char type in Java is, essentially,
a subset of int. The following simple example program demonstrates the arithmetic operators:

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
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.
// 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


Java provides special operators that can be used to combine an arithmetic operation with an
assignment.
a = a + 4;
In Java, you can rewrite this statement as shown here:
a += 4;
This version uses the += compound assignment operator. Both statements perform the same
action: they increase the value of a by 4.
var = var op expression;

can be rewritten as var op= expression;

The compound assignment operators provide two benefits. First, they save you a bit of typing,
because they are ―shorthand‖ for their equivalent long forms. Second, they are implemented
more efficiently by the Java run-time system than are their equivalent long forms.
// 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);
Dept. of ISE, GSSSIETW, Mysuru.
Object Oriented Programming with Java BCS306A
}
}
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, this statement:
x = x + 1;
can be rewritten like this by use of the increment operator:
x++;
Similarly, this statement:
x = x - 1;
is equivalent to
x - -;
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. For example:
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. Thus, the line y = ++x; is the equivalent of these two statements:
x = x + 1;
y = x;
However, when written like this,
x = 42;
y = x++;
the value of x is obtained before the increment operator is executed, so the value of y is 42. Of
course, in both cases x is set to 43. Here, the line y = x++; is the equivalent of these two
statements:
y = x;
x = x + 1;
The following program demonstrates the increment operator.
// Demonstrate ++.
Dept. of ISE, GSSSIETW, Mysuru.
Object Oriented Programming with Java BCS306A
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. These operators act upon the individual bits of their operands. They are
summarized in the following table:

The Bitwise Logical Operators


The bitwise logical operators are &, |, ^, and ~.

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

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 becomes 11010101 after the NOT operator is applied.

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. The following example shows the effect of the ^.
00101010 42
^ 00001111 15
00100101 37

Using the Bitwise Logical Operators


The following program demonstrates the bitwise logical operators:
// Demonstrate the bitwise logical operators.
class BitLogic {
public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}
In this example, a and b have bit patterns that present all four possibilities for two binary digits:
0-0, 0-1, 1-0, and 1-1. You can see how the | and & operate on each bit by the results in c and d.
The values assigned to e and f are the same and illustrate how the ^ works.
Here is the
output from this program:
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100

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

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
Here, num specifies the number of positions to left-shift the value in value.
The following program demonstrates this concept:
// 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

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;

The Unsigned Right Shift


The >> operator automatically fills the high-order bit with its previous contents each time a
shift occurs. This preserves the sign of the value. When you are working with pixel-based
values and graphics, 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, shift-right 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;
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

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
00000000 00000000 00000000 11111111 255 in binary as an int
The >>> operator is often not as useful as you might like, since it is only meaningful for 32-
and 64-bit values.

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. For example, the
following two statements, which shift the value in a right by four bits, are equivalent:
a = a >> 4;
a >>= 4;
Likewise, the following two statements, which result in a being assigned the bitwise expression
a OR b, are equivalent:
a = a | b;
a |= b;

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.

The following code fragment is perfectly valid:


int a = 4;
int b = 1;
boolean c = a < b;
int done;
// ...
if(!done) ... // Valid in C/C++
if(done) ... // but not in Java.
In Java, these statements must be written like this:
if(done == 0) // This is Java-style.
if(done != 0)

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

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:

Here is a program that is almost the same as the BitLogic example shown earlier, but it operates
on boolean logical values instead of binary bits:

Output:

Short-Circuit Logical Operators


These are secondary versions of the Boolean AND and OR operators, and are known as short-
circuit logical operators. As you can see from the preceding table, the OR operator results in
true when A is true, no matter what B is. Similarly, the AND operator results in false when A
is false, no matter what B is. If you use the || and && forms, rather than the | and & forms of

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
these 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.
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.
consider the following statement:
if(c==1 & e++ < 100) d = 100;
Here, using a single & ensures that the increment operation will be applied to e whether c is
equal to 1 or not.

The Assignment Operator


It has this general form: var = expression;
Here, the type of var must be compatible with the type of expression. The assignment operator
allows you to create a chain of assignments. For example, consider this fragment:
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. Using a ―chain of
assignment‖ is an easy way to set a group of variables to a common value.

The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else statements. 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 type, which can‘t be void.
Here is an example of the way that the ? is employed:
ratio = denom == 0 ? 0 : num / denom;
When Java evaluates this assignment expression, it first looks at the expression to the left of the
question mark. If denom equals zero, then the expression between the question mark and the
colon is evaluated and used as the value of the entire ? expression. If denom does not equal
zero, then the expression after the colon is evaluated and used for the value of the entire ?
expression. The result produced by the ? operator is then assigned to ratio.

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Here is a program that demonstrates the ? operator. It uses it to obtain the absolute value of a
variable.
// 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

Using Parentheses
Parentheses raise the precedence of the operations that are inside them. This is often necessary
to obtain the result you desire. 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

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Operator Precedence

Dept. of ISE, GSSSIETW, Mysuru.


Object Oriented Programming 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.

The if statement
 The if statement executes a block of code only if the specified expression is true.
 If the value is false, then the if block is skipped and execution continues with the rest
of the program.
 You can either have a single statement or a block of code within an if statement.
 Note that the conditional expression must be a Boolean expression.

Syntax:
if (<conditional expression>) {
<statements>
}

Example:
public class Example {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

System.out.println("b > a");


}
}

The if else statement


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

Syntax:
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:
public class Example {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
else
System.out.println("b > a");
}
}

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Nested ifs
 A nested if is an if statement that is the target of another if or else.
 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.
Here is an 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-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 bypassed.
 If none of the conditions is true, then the final else statement will be executed.

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

Example:
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}

The switch statement


 The switch case statement is a multi-way branch with several choices. A switch is
easier to implement than a series of if/else statements.
Structure of Switch:
 The switch statement begins with a keyword, followed by an expression that equates
to a no long integral value.
 Following the controlling expression is a code block that contains zero or more
labeled cases.
 Each label must equate to an integer constant and each must be unique.

Working of switch case:


 When the switch statement executes, it compares the value of the controlling
expression to the values of each case label.

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

 The program will select the value of the case label that equals the value of the
controlling expression and branch down that path to the end of the code block.
 If none of the case label values match, then none of the codes within the switch
statement code block will be executed. Java includes a default label to use in cases
where there are no matches.
 We can have a nested switch within a case block of an outer switch.

Syntax:
switch (<non-long integral expression>) {
case label1: <statement1> ; break;
case label2: <statement2> ; break;

case labeln: <statementn> ; break;
default: <statement>
}

Example:
public class Example {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
int status = -1;
if (a > b && a > c) {
status = 1;
} else if (b > c) {
status = 2;
} else {
status = 3;
}
switch (status) {
case 1:
System.out.println("a is the greatest");
break;
case 2:

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

System.out.println("b is the greatest");


break;
case 3:
System.out.println("c is the greatest");
break;
default:
System.out.println("Cannot be determined");
}
}
}

 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.
 For example, consider the following program:
// 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:

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

System.out.println("i is less than 10");


break;
default:
System.out.println("i is 10 or more");
}
}
}

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.
 For example, the following fragment is perfectly valid:
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: // ...

In summary, there are three important features of the switch statement to note:
 The switch differs from the if in that switch can only test for equality, whereas if can
evaluate any type of Boolean expression. That is, the switch looks only for a match
between the value of the expression and one of its case constants.
 No two case constants in the same switch can have identical values. Of course, a
switch statement and an enclosing outer switch can have case constants in common.
 A switch statement is usually more efficient than a set of nested ifs.

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
Iteration Statements

The while loop


 The while statement is a looping construct control statement that executes a block of
code while a condition is true.
 You can either have a single statement or a block of code within the while loop.
 The loop will never be executed if the testing expression evaluates to false.
 The loop condition must be a boolean expression.

Syntax:
while (<loop condition>) {
<statements>
}

Example:
public class Example {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++);
}
}
}

The do-while loop


 The do-while loop is similar to the while loop, except that the test is performed at the
end of the loop instead of at the beginning.
 This ensures that the loop will be executed at least once.

Syntax:
do {
<loop body>
} while (<loop condition>);

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
Example:
public class Example {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
do {
System.out.println(count++);
} while (count <= 10);
}
}

The for loop


 The for loop is a looping construct which can execute a set of instructions a specified
number of times. It’s a counter controlled loop.

Syntax:
for (<initialization>; <loop condition>; <increment expression>) {
<loop body>
}

Example:
public class Example {
public static void main(String[] args) {
System.out.println("Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++) {
System.out.println(count);
}
}
}

Declaring Loop Control Variables Inside the for Loop


 Often the variable that controls a for loop is only needed for the purposes of the loop
and is not used elsewhere.
 When this is the case, it is possible to declare the variable inside the initialization
portion of the for.

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
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);
}
}
 When you declare a variable inside a for loop, there is one important point to
remember: the scope of that variable ends when the for statement does

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

Some for Loop Variations


 The for loop supports a number of variations that increase its power and applicability.
The reason it is so flexible is that its three parts—the initialization, the conditional
test, and the iteration—do not need to be used for only those purposes can be used for
any purpose you desire.

 One of the most common variations involves the conditional expression.


 Specifically, this expression does not need to test the loop control variable against
some target value. In fact, the condition controlling the for can be any Boolean
expression. For example, consider the following fragment:
boolean done = false;
for(int i=1; !done; i++) {
// ...
Dept. Of ISE, GSSSIETW, Mysuru.
Object Oriented Programming with Java BCS306A
if(interrupted()) done = true;
}
In this example, the for loop continues to run until the boolean variable done is set to true.
It does not test the value of i.

 Here is another interesting for loop variation. 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++;
}
}
}
Here, the initialization and iteration expressions have been moved out of the for. Thus, parts
of the for are empty

 Here is one more for loop variation. 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.

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
 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.
 There are various types of collections that can be used with the for, but the only type
used in this chapter is the array.
Working:
 With each iteration of the loop, the next element in the collection is retrieved and
stored in itr-var.
 The loop repeats until all elements in the collection have been obtained.
 Because the iteration variable receives values from the collection, type must be the
same as (or compatible with) the elements stored in the collection.
 Thus, when iterating over arrays, type must be compatible with the base type of the
array.
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x : nums) {
sum += x;
}
System.out.println("Summation: " + sum);
}
}
 With each pass through the loop, x is automatically given a value equal to the next
element in nums. Thus, on the first iteration, x contains 1; on the second iteration, x
contains 2; and so on.
 Not only is the syntax streamlined, but it also prevents boundary errors.

For example, this program sums only the first five elements of nums:
class ForEach2 {

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
public static void main(String args[]) {
int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// use for to display and sum the values
for(int x : nums) {
sum += x;
if(x == 5) break; // stop the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum);
}
}

Iterating Over Multidimensional Arrays


 The enhanced version of the for also works on multidimensional arrays.
 Remember, however, that in Java, multidimensional arrays consist of arrays of
arrays. (For example, a two-dimensional array is an array of one-dimensional arrays.)
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) {
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
 In the program, pay special attention to this line:
for(int x[] : nums) {

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
 Notice how x is declared. It is a reference to a one-dimensional array of integers.
 This is necessary because each iteration of the for obtains the next array in nums,
beginning with the array specified by nums[0].
 The inner for loop then cycles through each of these arrays, displaying the values of
each element.

Java program to search given key element using for each loop.
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!");
}
}

Nested Loops
 Like all other programming languages, Java allows loops to be nested.
 That is, one loop may be inside another. For example, here is a program that nests for
loops:
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();

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
}
}
}

Jump Statements
 Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program.

The break statement


 The break statement transfers control out of the enclosing loop (for, while, do or
switch statement).
 You use a break statement when you want to jump immediately to the statement
following the enclosing control structure.
 You can also provide a loop with a label, and then use the label in your break
statement.
 The label name is optional, and is usually only used when you wish to terminate the
outermost loop in a series of nested loops.

Syntax:
break; // the unlabeled form
break <label>; // the labeled form

Example for break:


public class Example {
public static void main(String[] args) {
System.out.println("Numbers 1 - 10");
for (int i = 1;; ++i) {
if (i == 11)
break;
System.out.println(i + "\t");
}
}
}

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
Example for labeled break:
class Break {
public static void main(String args[]) {
boolean t = true;
first: {

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A

second: {
third: {

}
System.out.println("This is after second block.");
System.out.println("Before the break.");

if(t) break second; // break out of 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.

The continue statement


 A continue statement stops the iteration of a loop (while, do or for) and causes
execution to resume at the top of the nearest enclosing loop.
 You use a continue statement when you do not want to execute the remaining
statements in the loop, but you do not want to exit the loop itself.
 You can also provide a loop with a label and then use the label in your continue
statement.
 The label name is optional, and is usually only used when you wish to return to the
outermost loop in a series of nested loops.

Syntax:
continue; // the unlabeled form
continue <label>; // the labeled form

Example for continue:


public class Example {
public static void main(String[] args) {
System.out.println("Odd Numbers");

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0)
continue;
System.out.println(i + "\t");
}
}
}
Example for labelled continue:
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 return statement


 The return statement exits from the current method, and control flow returns to
where the method was invoked.

Syntax:
The return statement has two forms:
One that returns a value
return val;
One that doesn't returns a value
return;

Dept. Of ISE, GSSSIETW, Mysuru.


Object Oriented Programming with Java BCS306A
Example:
public class Example {
public static void main(String[] args) {
int res = sum(10, 20);
System.out.println(res);
}
private static int sum(int a, int b) {
return (a + b);
}
}

Dept. Of ISE, GSSSIETW, Mysuru.

You might also like