1. OBJECT ORIENTED PROGRAMMING
WITH JAVA – BCS306A
MRS. RASHMI T V
ASSISTANT PROFESSOR
DEPT. OF CSE, EPCET
Department of Computer Science and Engineering
2. Syllabus
Module 1
An Overview of Java: Object-Oriented Programming (Two paradigms, Abstraction, The Three OOP Principles), Using Block
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 Interface 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 loop. Local variable Type Inference in a for loop, Nested Loops), Jump Statements (Using break,
Using continue, return).
Chapter 2,3,4,5
2
3. Syllabus contd…
Module 2
Introducing Classes: Classes fundamentals, Declaring objects, Assigning Object Reference Variables,
Introducing Methods, Constructors, The this keyword, Garbage Collection.
Methods and Classes: Overloading Methods, Objects as Parameters, Argument Passing, Returning Objects,
Access Control, Understanding static, Introducing final, Introducing Nested and Inner Classes.
Chapter 6, 7
Module 3
Inheritance: Inheritance basics, Using super, creating multi-level hierarchy, When Constructors are executed,
method overriding, Dynamic Method Dispatch, Using Abstract Classes, Using final with inheritance, Local
Variable Type and Inheritance, The Object Class.
Interfaces: Interfaces, Default Interface Methods, Use Static Methods in an Interface, Private Interface
Methods.
Chapter 8, 9
3
4. Syllabus contd…
Module 4
Packages: Packages, Packages and Member Access, Importing Packages.
Exceptions: Exception-Handling Fundamentals, Exception Types, Uncaught Exceptions, Using try and catch,
Multiple catch clauses, Nested try statements, throw, throws, finally, Java’s Built-in Exceptions, Creating your
own Exception Subclasses, Chained Exceptions.
Chapter: 9, 10
Module 5
Multi-Threaded Programming: The Java Thread Model, The Main Thread, Creating Multiple Threads, Using
isAlive() and join(), Thread Priorities, Synchronization, Interthread communications, Suspending, Resuming,
and Stopping Threads, Obtaining a Thread’s state.
Enumerations, Type Wrappers and Autoboxing: Enumerations (Enumeration Fundamentals, The values() and
valueof() Methods), Type Wrappers (Character, Boolean, The Numeric Type Wrappers), Autoboxing
(Autoboxing and Methods, Autoboxing/Unboxing occurs in Expressions, Autoboxing/Unboxing Boolean and
Character Values).
Chapter 11, 12.
4
5. Course Outcomes
CO1: Demonstrate proficiency in writing simple programs involving branching and looping
structures.
CO2: Design a class involving data members and methods for the given scenario.
CO3: Apply the concepts of inheritance and interfaces in solving real world problems.
CO4: Use the concept of packages and exception handling in solving complex problem.
CO5: Apply concepts of multithreading, autoboxing and enumerations in program development
5
6. Text Books
Sl. No. Book Name Author(s) Publisher Year, Edition
Text
Books 1.
Java: The Complete
Reference,
Herbert Schildt McGraw-Hill
12th Edition,
November 2021
Refere
nce
Books
1.
Programming with
Java
E. Balaguruswamy
McGraw Hill
Education
6th
Edition, March
2019
2. Thinking in Java Bruce Eckel Prentice Hall 4th
Edition, 2006
6
7. Arise of Programming Language
• computer languagesevolve for two reasons:
• to adapt to changes in environment and
• to implement advances in the art of programming.
• Java was the perfect response to the demands of the then newly emerging, highly
distributed computing universe.
7
10. JAVA
Java was conceived by James
Gosling, Patrick Naughton,
Chris Warth, Ed Frank, and
Mike Sheridan at Sun
Microsystems, Inc. in 1991.
This language was initially
called “Oak,” but was
renamed “Java” in 1995.
10
11. How Java Changed the Internet?
Java innovated a new type of networked program called the applet that changed the way the
online world thought about content.
Java also addressed some of the thorniest issues associated with the Internet: portability and
security.
Bytecode – is the key that makes the Java language more secure and portable
11
17. 17
JVM - To enable Java programs to be executed on multiple CPUs without modifications, java programs
are compiled into machine instructions that can be understood and executed by an idealized CPU. Such
a CPU is called Java Virtual Machine (JVM).
WORA - A Java program is first compiled into the machine code that is understood by JVM. Such a
code is called Byte Code.This Byte Code is a platform-independent code because it can be run on
multiple platforms i.e. Write Once and Run Anywhere(WORA).
JIT - The Just In Time (JIT) compiler compiles the byte code into executable machine code in real
time, on a piece-by- piece demand basis.
JDK - The JIT cannot compile the entire byte code of a Java program into executable machine code all
at once, because Java Runtime Environment carries out various run time checks that can be performed
only at run time.The collection of the three entities name the Java language, the Java language packages
and the set of Java development tools is called the Java Development Kit (JDK)
Tool in JDK –
javac : This tool is Java compiler. It compiles the Java source code into the bytecode, which can be
understood by JVM.
java :This tool is the Java interpreter. It interprets the byte code into machine code and then
executes it.
20. An Overview of Java
• Two Paradigms that governs how a program is constructed:
• What is happening?
• Who is being affected?
20
Procedure-Oriented Model Object-Oriented Programming
A program as a series of linear steps
[Code acting on Data]
Organizes a program around
data(objects) and a set of well-
defines interfaces to that data.
[Data Controlling access to code]
21. 21
OBJECT – ORIENTED
PROGRAMMING
Object-oriented programming (OOP)
is a programming paradigm based on
the concept of "objects", which can
contain data and code: data in the
form of fields (often known as
attributes or properties), and code, in
the form of procedures (often known
as methods).
22. Organization of data and functions in OOP
22
Features of OOPS:
1. Emphasis is on data rather than
procedure.
2. Program are divided into what are known
as objects.
3. Data structure are designed such that they
characterized the objects.
4. Functions that are operate on the data of
an object are tied together in the DS.
5. Data is hidden and cannot be accessed by
external functions only access by internal
functions.
6. Objects can communicate with each other
through functions
7. New functions and data can be easily
23. Basic concepts of Object Oriented
Programming
1. Objects 2. Classes
• A class is a collection of objects
of similar type.
• For example: grapes, orange
and apple and are members of
class fruit.
• The classes are user defined data
types and always behave like the
built in types of a programming.
23
32. Benefits of OOP
Through inheritance, we can eliminate reduce the code and extend the use of existing
classes.
We can build program from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving
of the development time and high productivity.
The principal of data hidden helps the programmer to build secure programs that
cannot be invaded by code in other parts of the program.
It is possible to have number of instances of an object to co exist without any
interference.
It is possible to map objects in the program domain to those in the program.
It is also easy to partition the work in a project based on objects.
The object oriented system can be easily upgraded from small to large systems.
Software complexity can be easily managed.
32
33. Applications of OOPS
1. Real Time system.
2. Object oriented database.
3. simulation and modeling.
4. Hypertext, hypermedia and expertext.
5. AI and expert systems.
6. Neural networks and parallel programming.
7. Decision support and office automation systems.
33
38. Arrays
An arrayis a groupof like-typed variablesthat arereferredto bya commonname. Arraysof any
type can be created and may have one or more dimensions.
One-Dimensional Arrays
Aone-dimensional arrayis, essentially, alist of like-typed variables.Tocreatean 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 base type of the array.The base type determines the data type of each
element that comprises the array.Thus, the base type for the array determines what type
of data the array will hold.
int month_days[ ];
Although this declaration establishes the fact that month_days is an array variable,
no
array actually exists.
In fact, the value of month_days is set to null, which represents an array with
no value.
39. / / For January
/ / For
February
/ / Demonstrate a one-dimensional
array. class Array
{
public static void main(String args[ ])
{
int month_days[ ];
month_days = new
int[12]; month_days[0] =
31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + "
days.");
}
40. 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 inApril 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];
This is the way that you will normally see it done in professionally written Java
programs
Arrays can be initialized when they are declared.The process is much the same as that used to
initialize the simple types. An arrayinitializer is a list of comma-separatedexpressionssurrounded
by curly braces.
The commas separate the values of the array elements.The array will automatically be
created large enough to hold the number of elements youspecify in the array initializer.
There is no need to use new.
41. Example
If you try to access elements outside the range of the array (negative numbers or
numbers
greater than the length of the array), you will cause a run-time error.
Ex: ifyou try to access month_days[13] ….You will get an error
/ / An improved version of the previous program.
class AutoArray
{
public static void main(String args[ ])
{
int month_days[ ] = { 31, 28, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] +
" days.");
}
}
42. Example on 1-D array
/ / Average an array of values. class Average
{
public static void main(String args[ ])
{
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i]; System.out.println("Average is " + result / 5);
}
}
43. Multidimensional Arrays
In Java, multidimensional arraysareactually arraysof arrays.
However, as you will see, there are a couple of subtle differences.
T
o
multidimensional array variable, specify each additional index using another set of square
brackets.
For example, the following declares a two dimensional array variable called twoD.
int twoD[ ][ ] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix
is implemented as an arrayof arraysof int.
The following program numbers each element in the array from left to right, top to
bottom, and then displays these values:
44. / / Demonstrate a two-dimensional array.
class TwoDArray
{
public static void main(String args[ ])
{
int twoD[ ][ ]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++)
{
twoD[i][j] = k; k+
+;
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
OUTPUT
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
45. Contd…
When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension.You can allocate the remaining dimensions
separately.
46. Contd…
For example, this following code allocates memory for the first dimension of twoD when it is declared. It
allocates the second dimension manually.
int twoD[ ][] = new int[4][ ];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
While there is no advantage to individually allocating the second dimension arrays in this situation, there
may be in others.
For example, when you allocate dimensions manually,you do not need to allocate the same number of
elements for each dimension.
As stated earlier, since multidimensional arrays are actuallyarrays of arrays, the length ofeach array is under
your control.
47. / / Manually allocate differing size second
dimensions.
class TwoDAgain
{
public static void main(String
args[ ])
{
int twoD[ ][] = new int[4]
[ ]; twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++)
{
twoD[i][j] = k;
k++;
}
for(i=0; i<4;
i++)
{
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println( );
}
output
: 0
1 2
3 4 5
6 7 8 9
48. The array created by this program lookslike
this:
It is possible to initialize multidimensional arrays.To do so, simply enclose each dimension’s
initializer within its own set of curly braces.
The following program creates a matrix where each element contains the product of the
row
and column indexes.
51. 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.
52. The Basic Arithmetic Operators
The basic arithmetic operations—addition, subtraction, multiplication, and division—
all behave as you would expect for all numeric types.
/ / Demonstrate the basic arithmetic
operators.
class BasicMath
{
public static void main(String args[])
{
/ / arithmetic using integers
System.out.println("Integer
Arithmetic"); int a = 1 + 1;
int b = a *
3; int c =
b / 4; int d
= c - a; int
e = -d;
System.out.println("a = " + a);
System.out.println("b = " +
b); System.out.println("c = "
+ c); System.out.println("d =
/ / arithmetic using doubles
System.out.println("nFloating Point
Arithmetic");
double da = 1 +
1; double db = da
* 3; double dc =
db / 4; double dd
= dc - a; double
de = -dd;
System.out.println("da = " + da);
System.out.println("db = " +
db); System.out.println("dc = "
+ dc); System.out.println("dd =
" + dd); System.out.println("de
= " + de);
}
}
53. The Modulus Operator: The modulus operator, %, returns the remainder of
a division operation.
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;
/ / Demonstrate the %
operator. class Modulus
{
public static void main(String
args[ ])
{
int x = 42;
double y =
42.25;
System.out.printl
n("x mod 10 = "
+ x % 10);
System.out.printl
n("y mod 10 = "
+ y% 10);
}
}
OUTPUT
x mod 10 = 2
y mod 10 = 2.25
54. This version uses the += compound assignment operator. Both statements perform
the same action: they increase the value of a by 4.
Here is another example,
a = a % 2;
which can be expressed as
a %= 2;
/ / 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);
}
}
55. 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++;
x = x -
1;
x--;
Similarly, this
statement:
is equivalent to
These operators are unique in that they can appear both in postfixform, wherethey follow the
operand as just shown, and prefix form
x = 42; y = ++x;
In this case, y is set to 43 because the increment occurs beforex 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++;
56. Contd
…
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;
/ / Demonstrate +
+. class IncDec
{
public static void
main(String args[ ])
{
int a = 1;
int b =
2; int c;
int d;
c = +
+b; d =
a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " +
Output
a = 2
b = 3
c = 4
d = 1
57. The Bitwise Operators
Java defines several bitwise operatorsthat canbeapplied tothe integer types, long, int, short,
char, and byte.These operators act upon the individual bits of their operands.
All of the integer types are represented by binary numbers of varying bit widths.
For example, the byte value for 42 in binary is 00101010
58. Contd
…
All of the integer types (except char) are signed integers.This means that they
can represent negative values as well as positive ones.
Java uses an encoding known as two’
scomplement, which means that negative numbers
are represented by inverting (changing 1’s to 0’s and vice versa) all of the bits in a
value, then adding 1 to the result.
For example, –42 is represented by inverting all of the bits in 42, or 00101010, which
yields 11010101, then adding 1, which results in 11010110, or –42.
The Bitwise Logical Operators
The bitwise logical operators are &, | , ^, and ~.
59. Contd
…
The Bitwise NOT Also called the bitwise complement, the unary NOToperator
,~, 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.
Azero is produced in all other cases. Here isan 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
60. Contd
…
The Bitwise XOR The XOR operator, ^, combines bits such that if exactly
one operand is 1, then the result is 1. Otherwise, the result is zero.
00101010 42
^ 00001111 15
00100101 37
Using the Bitwise Logical Operators
NEXTEXAMPLEGIVESYOU CLEAR
ILLUSTARTION
61. EXAMPLE
(BitLogic.java)
/ / Demonstrate the bitwise logical
operators. class BitLogic
{
public static void main(String args[ ])
{
String binary[ ] = {
"0000", "0001", "0010", "0011", "0100",
"0101",
"0110", "0111",
"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 &
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]);
}
}
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b =
0101
62. The Left Shift (<<)
The left shift operator, <<, shifts all of the bits in a value to the left a
specified number of times.
It has this general form: value <<num
Here, num specifiesthe numberof positions to left-shift the valuein value.That is, the << moves
all of the bits in the specified value to the left by the number of bit positions specified by
num.
For each shift left, the high-order bit is shifted out (and lost), and a zero is brought in on
the right.
Java’s automatic type promotions produce unexpected results when you are shifting byte
and short values. As you know, byte and short values are promoted to int
when an expression is evaluated. Furthermore, the result ofsuch an expression is also
an int.
63. 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 isshown here:
value >> num
Here, num specifies the numberof 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
int a = 35;
a = a >> 2; / / a still contains 8
Looking at the same operation in binary shows more clearly how this happens:
35
00100011
>> 2
00001000 8
Each time you shift a value to the right, it divides that value by two—and discards
any remainder.
64. The Unsigned Right Shift
Asyou 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, ifyou are shifting something that does not represent a numeric value, you may
not
want sign extension to take place.
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.
Toaccomplish 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 valueis 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:
–1 in binary as an
int
11111111 11111111 11111111 11111111
>>>24
00000000 00000000 00000000 11111111 255 in binary as an
int
65. Contd…
The >>> operator is often not as useful as you might like, since it is
only meaningful for 32- and 64-bit values.
Remember, smaller values are automatically promoted to int in expressions.This means
that sign-extension occurs and that the shift will take place on a 32-bit rather than on an 8-
or 16- bit value.
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 |
66. Relational Operators
The relational operatorsdetermine the relationship that oneoperandhasto the
other.
The outcome of these operations is a boolean value.
int a = 4;
int b =
1;
boolean
c = a <
b;
In this case, the result of a<b (which
is false) is stored in c.
67. 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 logical Boolean operators, &, | , and ^, operate on boolean values in the
same way that they operate on the bits of an integer.
!true == false and !false == true.
68. Contd
…
Short-Circuit Logical Operators (V.V.IMP)
Java provides two interesting Boolean operators not found in many other computer
languages. These are secondaryversions 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 Ais
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 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.
69. This is very useful when the right-hand operand depends on the value of the left one in
order to function properly.
For example, the following code fragment shows how you can take advantage of short-
circuit
logicalevaluation to be sure that a division operation will be valid before evaluating it:
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.
It is standard practice to use the short-circuit forms of AND and OR in cases involving
Boolean logic, leaving the single-character versions exclusively for bitwise operations.
However, there are exceptions to this rule.
For example, 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.
70. The Assignment Operator
The assignmentoperatoris 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 varmust becompatiblewith the type of expression.
The assignment operator does have one interesting attribute that you may not be
familiar with: it allowsyou 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. This
works
because the = is an operator that yields the value of the right-hand expression.
Thus, the value of z = 100 is 100, which is then assigned to y, which in turn is
assigned to x. Using a “chain of assignment” isan easy way to set a group of
71. The ? Operator
Java includes a special ternary (three-way) operatorthat canreplacecertain types of if-then-else
statements.
This operator is the ?. It can seem somewhat confusing at first, but the ? can be
used very effectively once mastered.The ?has this general form:
expression1?expression2 : expression3
Here, expression1canbeany expressionthat evaluates to aboolean 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 arerequiredto return the same type, which can’t be void.
Here isan 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 no equal zero, then the expression after the colon is evaluatedand used for
the value of the entire ? expression.
The result produced by the ?operator is then assigned to ratio.
72. Using Parentheses
Parenthesesraisethe precedenceof the operationsthat areinside them.This is often necessaryto
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
In addition to altering the normal precedence of an operator, parentheses can sometimes
be used to help clarify the meaningof an expression.
For anyone reading your code, a complicated expression can be difficult to understand.
a | 4 + c >> b &7
(a | (((4 + c) >> b) & 7))
73. class BoolLogic
{
public static void main(String args[ ])
{
boolean a = true;
boolean b = false;
boolean c = a |
b; boolean d = a
& b; boolean e =
a ^ b;
boolean f = (!a &b) | (a &!b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " +
d); System.out.println(" a^b = "
+ e);
System.out.println("!a&b|a&!b = " +
f); System.out.println(" !a = " + g);
}
}
OUTPUT
a =
true b
= false
a|b = true
a&b =
false a^b
= true
a&b|a&!b
= true
!a = false
75. 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
basedupon 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 : 1) if
2) Nested if
3)The if-else-if Ladder
4) switch
5) Nested switch Statements
76. Java supports two selection statements: if and switch.
If : The if statement is Java’sconditional branch statement. It can be used to route
program
execution through two different paths. Here is the general form of the if statement:
if (condition) statement1;
else statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly braces
(that
is, a block). The condition is any expression that returns a boolean value.The else clause is optional.
The if works like this: If the condition is true, then statement1 is executed.
Otherwise,
statement2 (if it exists) is executed.
int a, b;
/ / ...
if(a < b) a =
0; else b = 0;
77. 77
boolean dataAvailable;
/ / ...
if (dataAvailable)
ProcessData();
else
waitForMoreData(
);
int bytesAvailable;
/ / ...
if (bytesAvailable > 0)
{
ProcessData();
bytesAvailable -= n;
}
else
waitForMoreData();
78. Nested If
78
int bytesAvailable;
/ / ...
if (bytesAvailable > 0)
{
ProcessData();
bytesAvailable -= n;
}
else
waitForMoreData();
if(i == 10)
{
if(j < 20)
a = b;
if(k > 100)
c = d; // this if is
else
a = c;
}
else
a = d; // this else refers to if(i == 10)
80. 80
// Demonstrate if-else-if statements.
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 + ".");
}
}
81. 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 valueof an expression.
Here is the general form of a switch statement:
switch (expression)
{
case value1:
/ / statement sequence
break;
case value2:
/ / statement sequence
break;
...
case valueN:
/ / statement sequence
break;
default:
/ / default
statement sequence
}
82. 82
/ / Asimple example of the switch.
class SampleSwitch {
public static void main(String args[ ]) { for(int i=0;
i<6; i++)
switch(i)
{ case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is
greater than 3.");
}
83. 83
/ / In a switch, break statements are
optional.
class MissingBreak
{
public static void main(String args[ ])
{
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
84. 84
// Use a string to control a switch statement.
class StringSwitch {
public static void main(String[] args)
{
String str = "two";
switch(str)
{
case "one":
System.out.println("one");
break;
case "two":
System.out.println("two");
break;
case "three":
System.out.println("three");
break;
default:
System.out.println("no match");
break;
}
}}
85. Nested Switch
85
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: // ...
86. Iteration Statements
Java’s iteration statements are for, while, and do-while.These statements create
what we commonlycall loops.
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:
while(condition)
{
/ / body of loop
}
The condition canbeany Booleanexpression.Thebodyof the loop will beexecutedaslong as
the conditional expression is true.
When condition becomesfalse, control passestothe next line of code immediately
following the
loop.
87. Since the while loop evaluates its conditional expression at the top of the
loop, the body of the loop will not execute even once if the condition is false to begin
with.
/ / Demonstrate the while loop.
class While
{
public static void main(String
args[ ])
{
int n = 10;
while(n > 0)
{
System.out.println("t
ick " + n);
n--;
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
88. int a = 10, b =
20; while(a > b)
System.out.println("
This will not be
displayed");
The body of the while (or any other of Java’s
loops) can be empty.This is because a
null statement (one that consists only of a semicolon)is
syntactically valid in Java.
/ / The target of a loop can be empty.
class NoBody
{
public static void main(String args[ ])
{
int i, j;
i = 100;
j = 200;
/ / find midpoint between i and j
while(++i < --j) ; / / no body in this loop
System.out.println("Midpoint is " + i);
} }
Midpoint is 150
89. Do While
do
{
/ / body of loop
} while (condition);
Each iteration of the do-while loop first
executes the body of the loop and then
evaluates the conditional expression. If this
expression is true, the loop will repeat.
Otherwise, the loop terminates.
/ / Demonstrate the do-while loop.
class DoWhile
{
public static void main(String args[ ])
{
int n = 10;
do
{
System.out.println("tick " +
n);
n--;
} while(n > 0);
}
}
The loop in the preceding program, while
technically correct, can be written more
efficiently as follows:
do {
System.out.println("tick " + n);S
} while(--n > 0);
90. 90
for : there are two forms of the for loop. The first is the traditional form
that has been in use since the original version of Java.
The second is the new “for-each” form.
Here is the general form of the traditional for statement:
for(initialization; condition; iteration)
{
/ / body
}
If only one statement is being repeated, there is no need for the curly braces.
For Loop
91. 91
/ / Demonstrate the for loop.
class ForTick
{
public static void main(String
args[ ])
{
int n;
for(n=10; n>0; n--)
System.out.println("tick " +
n);
}
}
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);
}
92. 92
class Sample
{
public static void main(String args[ ])
{
int a, b;
b = 4;
for(a=1; a<b; a++)
{
System.out.println("a = " + a);
System.out.println("b = " + b);
b--;
}
}
}
/ / Using the comma.
class Comma
{
public static void
main(String args[ ])
{
int a, b;
for(a=1, b=4; a<b; a+
+, b--)
{
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}
Using the Comma
93. 93
Some for loop variations
/ / 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++;
}
}
}
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++)
{
// ...
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.
94. 94
for( ; ; ) {
// ...
}
This loop will run forever because there is no condition under which it will
terminate.
95. 95
The For-Each Version of the for Loop
Aforeach style loop is designed to cycle through a collection of objects, such as an array, in
strictly sequential fashion, from start to finish.
Unlike somelanguages, such as C#, that implement a for-each loop by using the keyword
foreach, 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 specifiesthe type and itr-var specifiesthe nameof 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, Ex: Arrays.
96. 96
/ / Use break with a for-each style for.
class ForEach2
{
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)
{
System.out.println("Value is: " + x);
sum += x;
if(x == 5) break; / / stop the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum);
}
Value is: 1
Value is: 2
Value is: 3
Value is: 4
V
alue is: 5
Summationof first 5 elements: 15
97. 97
/ / The for-each loop is essentially read-only.
class NoChange
{
public static void main(String args[ ]) {
int nums[ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int x : nums)
{
System.out.print(x + " ");
x = x * 10; / / no effect on
nums
} 1 2 3 4 5 6 7 8 9 10
System.out.println(); 1 2 3 4 5 6 7 8 9 10
for(int x : nums)
System.out.print(x + " ");
System.out.println();
}
}
98. Jump Statements
Java supports three jump statements: break , continue, and return.
Using break :In Java, the break statement has three uses.
1) It terminates a statement sequence in a switch statement.
2) It can be used to exit a loop.
3) It can be used asa “civilized” form of goto.
/ / a ) Using break to exit a loop.
class BreakLoop
{
public static void main(String args[ ])
{
for(int i=0; i<100; i++)
{
if(i == 10) break; / / terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete
99. 99
/ / Using break to exit a while loop.
class BreakLoop2 {
public static void main(String args[ ])
{
int i = 0;
while(i < 100)
{
if(i == 10) break; / / terminate loop if i is 10
System.out.println("i: " + i);
i++;
}
System.out.println("Loop complete.");
}
}
101. 101
b) Using break as a Form of Goto
class Break
{
public static void main(String args[ ])
{
boolean t = true;
first:
{
second:
{
third:
{
System.out.println("Befo
re the break.");
if(t)
break second;
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
Before the break.
This is after second block.
102. 102
/ / Using break to exit from nested loops
class BreakLoop4
{
public static void main(String args[ ])
{
outer: for(int i=0; i<3; i++)
{
System.out.print("Pass " + i + ":
"); for(int j=0; j<100; j++)
{
if(j == 10) break outer; / / exit both
loops System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops
complete.
103. Keep in mind that you cannot break to any label which is not defined for an enclosing
block
/ / This program contains an error. class
BreakErr
{
public static void main(String args[ ])
{
one: for(int i=0; i<3; i++)
{
System.out.print("Pass " + i + ": ");
}
for(int j=0; j<100; j++)
{
if(j == 10)
break one; / / WRONG
System.out.print(j + " ");
}
}
105. 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. As such, it is categorized as a jump
statement.
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.
/ / Demonstrate return.
class Return
{
public static void main(String args[ ])
{
boolean t = true;
System.out.println("Before the return.");
if(t)
return; / / return to caller
System.out.println("This won't execute.");
}
}
Before the return.