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

oops using java (Unit-II)

This document provides an overview of operators in Java, categorizing them into arithmetic, bitwise, relational, boolean logical, assignment, and ternary operators. It explains the functionality of each operator with examples and discusses concepts like operator precedence and short-circuit evaluation. Additionally, it covers compound assignment operators and the two's complement representation for negative integers.

Uploaded by

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

oops using java (Unit-II)

This document provides an overview of operators in Java, categorizing them into arithmetic, bitwise, relational, boolean logical, assignment, and ternary operators. It explains the functionality of each operator with examples and discusses concepts like operator precedence and short-circuit evaluation. Additionally, it covers compound assignment operators and the two's complement representation for negative integers.

Uploaded by

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

1

Object Oriented Programming using JAVA


UNIT II
Operators

Java’s operators can be divided into following groups:


1. Arithmetic operators 4. Boolean Logical operators
2. The Bitwise operators 5. The assignment operator
3. Relational operators 6. The ? (Ternary) operator

1. Arithmetic Operators: Arithmetic operators are used in mathematical expressions


in the same way that they are used in algebra.

Operator Result

+ Addition (unary plus)


 The operands of the arithmetic
– Subtraction (also unary operators must be of a numeric type.
minus)  We cannot use them on boolean
types, but we can use them on char
* Multiplication types, since the char type in Java is,
essentially, a subset of int.
/ Division
 The unary minus operator negates its
% Modulus single operand.

++ Increment  The unary plus operator just returns


the operand value.
+= Addition assignment
 When the division operator is applied
–= Subtraction assignment to an integer type, there will be no
fractional component attached to the
*= Multiplication assignment result.

/= Division assignment

%= Modulus assignment

–– Decrement
2

// 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; Output:
int c = b / 4;
int d = c - a; Integer Arithmetic
int e = -d; a=2
System.out.println("a = " + a); b=6
System.out.println("b = " + b); c=1
System.out.println("c = " + c); d = -1
System.out.println("d = " + d); e=1
System.out.println("e = " + e);

// arithmetic using doubles Floating Point Arithmetic


System.out.println("\nFloating Point Arithmetic"); da = 2.0
double da = 1 + 1; db = 6.0
double db = da * 3; dc = 1.5
double dc = db / 4; dd = -0.5
double dd = dc - a; de = 0.5
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);
}
}

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[]) { Output:
int x = 42;
double y = 42.25; x mod 10 = 2
System.out.println("x mod 10 = " + x % 10); y mod 10 = 2.25
System.out.println("y mod 10 = " + y % 10);
}
}

Arithmetic Compound Assignment Operators (+=, – =, *=, /=, %=)


Any statement of the form var = var op expression; can be written as
var op= expression;
3

// Demonstrate several assignment operators. Output:

class OpEquals { a=6


public static void main(String args[]) { b=8
int a = 1; c=3
int b = 2;
int c = 3;
a += 5;
b *= 4; Benefits of compound assignment
c += a * b; operators
c %= 6;
System.out.println("a = " + a); 1. They save a bit of typing.
System.out.println("b = " + b);
System.out.println("c = " + c); 2. In some cases they are more
} efficient than are their equivalent
} long forms.

Increment and Decrement (++ and --)


The increment operator (++)

The increment operator increases its operand by one.

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

The decrement operator (--)

The decrement operator decreases its operand by one.

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

// Demonstrate ++.
class IncDec {  These operators can appear both in prefix or
public static void main(String args[]) { postfix form.
int a = 1;
int b = 2;
int c; Prefix form: The operand is incremented or
int d; decremented before the value is obtained for use in
c = ++b; the expression.
d = a++;
c++; x = 42; equal to x = x + 1;
y = x; Y = 43, X = 43
System.out.println("a = " + a); y = ++x;
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d); Postfix form: The previous value is obtained for use
} in the expression, and then the operand is modified.
}
x = 42; equal to Y=x;
Output: Y = 42 , X = 43
y = x++; X = x + 1;
a=2
b=3
c=4
d=1
4

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

Operator Result

~ Bitwise unary NOT

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

>> Shift right

>>> Shift right zero fill

<< Shift left

&= Bitwise AND assignment

|= Bitwise OR assignment

^= Bitwise exclusive OR assignment

>>= Shift right assignment

>>>= Shift right zero fill assignment

<<= Shift left assignment

2’s complement

1) Java uses an encoding known as two’s complement to represent negative


integers.
i. Write the binary number for +ve value
ii. Invert the bits (changing 1’s to 0’s and vice versa)
iii. Add 1 to the result obtained in step ii.

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.

2) Decoding
5

To decode a negative number, first invert all of the bits, then add 1.

For example, –42, or 11010110 inverted, yields 00101001,or 41,so when


you add 1, you get 42.

3) The leftmost bit (high-order bit) determines sign of an integer. If the bit is 1 then it is a
negative number. If the bit is 0 then it is a positive number.

The Bitwise Logical Operators


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

The Bitwise NOT

Also called the bitwise complement, the unary NOT operator, ~, inverts all of the
bits of its operand.

The Bitwise AND

The AND operator, &, produces a 1 bit if both operands are also 1.

A zero is produced in all other cases.

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.

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.

A B A|B A&B A^B ~A

0 0 0 0 0 1

1 0 1 0 1 0

0 1 1 0 1 1

1 1 1 1 0 0

// Demonstrate the bitwise logical operators.


class BitLogic
{
public static void main(String args[]) { Output
int a = 3; // 0011 in binary
int b = 6; // 0110 in binary a|b = 7

a&b=2

a^b=3
6

int c = a | b;
int d = a & b;
int e = a ^ b;

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


System.out.println(" a&b = " + a & b);
System.out.println(" a^b = " + a ^ b);
}

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

a) Here, num specifies the number of positions to left-shift the value in value.
b) For each shift left, the high-order bit is shifted out (and lost), and a zero is brought in on
the right.

// Left shifting a byte value.


class ByteShift
{ Output:
public static void main(String args[]) {
byte a = 64, b;
Original value of a: 64
int i;
i and b: 256 0
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}

The Right Shift

1) The right shift operator, >>, shifts all of the bits in a value to the right a specified number
of times. It has this general form:

value >> num

2) Here, num specifies the number of positions to right-shift the value in value.

3) Each time you shift a value to the right, it divides that value by two—and discards
any remainder.

int a = 35;
a = a >> 2; // a contains 8
7

00100011 35
>> 2
00001000 8

4) When we are shifting right, the top (leftmost) bits exposed by the right shift are filled in
with the previous contents of the top bit. This is called sign extension and serves to
preserve the sign of negative numbers.

11111000 –8
>> 1
11111100 –4

The Unsigned Right Shift (>>>)

Java’s unsigned, shift right operator, >>>, which always shifts zeros into the high-order bit.

int a = -1;

a = a >>> 24;

11111111 11111111 11111111 11111111 –1 in binary as an int

>>>24

00000000 00000000 00000000 11111111 255 in binary as an int

Bitwise Operator Compound Assignments

a = a >> 4; can be written as a >>= 4;

class OpBit {
public static void main(String args[]) {
int a = 1; Output
int b = 2;
int c = 3; a=3
a |= 4;
b >>= 1; b=1
c <<= 1;
a ^= c; c=6
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
8

3. Relational Operators
1) The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering.
2) The outcome of these operations is a boolean value.

Operator Result

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

3) The relational operators are most frequently used in the expressions that control the if
statement and the various loop statements.

int a = 4; Output:
int b = 1;
boolean c = a < b; false

4. Boolean Logical Operators


The Boolean logical operators shown here operate only on boolean operands.

Operator Result

& Logical AND

| Logical OR

^ Logical XOR (exclusive OR)

|| Short-circuit OR

&& Short-circuit AND

! Logical unary NOT


9

&= AND assignment

|= OR assignment

^= XOR assignment

== Equal to

!= Not equal to

?: Ternary if-then-else

Example

A B A|B A&B A^B !A

False False False False False True

True False True False True False

False True True False True True

True True True True False False

// Demonstrate the boolean logical operators.

class BoolLogic {

public static void main(String args[]) { Output:


boolean a = true;
boolean b = false; true
boolean c = a | b; false
boolean d = a & b; true
System.out.println( a); false
System.out.println(b);
System.out.println( c);
System.out.println(d);
}
}

Short-Circuit Logical Operators(&& , ||)


The secondary versions of the Boolean AND (&) and OR (|) operators are known as Short-
circuit operators.
10

If we use short-circuit operators || and &&, Java will not bother to evaluate the right hand
operand when the outcome of the expression can be determined by the left operand alone.

Short-circuit AND - && (Conditional-and)

class ShortCktAnd
{
public static void main(String args[])
{
Output:
int num = 20;
int denom = 0;
After if
if (denom != 0 && num / denom > 10)
{
System.out.println("Inside If");
}
System.out.println("After if");
}
}

Short-circuit OR - || (Conditional-or)

class ShortCktOr
{
public static void main(String args[])
{ Ouput:
int num = 20;
int denom = 0; Inside if

if (denom == 0 || num / denom > 10) After if


{
System.out.println("Inside If");
}
System.out.println("After if");
}
}

5. The Assignment Operator

The assignment operator is the single equal sign, =.

It’s general form is:

var = expression;

Here, the type of var must be compatible with the type of expression.

Example:

int x, y, z;
11

x = y = z = 100;

The ternary / three-way operator (?)

The ? has this general form:

expression1 ? expression2 : expression3

➢ expression1 can be any expression that evaluates to a boolean value.

➢ If expression1 is true, then expression2 is evaluated; otherwise, expression3 is


evaluated.

➢ Both expression2 and expression3 are required to return the same (or compatible) type,
which can’t be void.

➢ It will be used to replace certain types of if-then-else statements.

Example

// Demonstrate ?.

class Ternary {
public static void main(String args[]) Ouput:
{
int num = 20; 0
int denom = 0;

int ratio = denom == 0 ? 0 : num / denom;


System.out.println(ratio);
}
}

Operator Precedence

1) In the below table, Operators with higher precedence are evaluated before operators
with relatively lower precedence. Operators on the same line have equal precedence.
2) When operators of equal precedence appear in the same expression, All binary
operators except for the assignment operators are evaluated from left to right;
assignment operators are evaluated right to left.

Highest
postfix ++ postfix --
prefix ++ prefix -- ~ ! unary + unary - (type-cast)
12

* / %
+ -

>> >>> <<


> >= < <= instanceof
== !=
&
^
|
&&
||
?:
->
= op=
Lowest

Using Parentheses

1) Parentheses raise the precedence of the operations that are inside them.
2) Parentheses can sometimes be used to help clarify the meaning of an expression.

Example

a >> b + 3 → This expression first adds 3 to b and then shifts a right by that result.

If we want to first shift a right by b positions and then add 3 to that result, we will need to
parenthesize the expression like this:

(a >> b) + 3

Control Statements

Programming languages uses control statements to cause the flow of execution to advance and
branch based on changes to the state of a program.

Categories of Java’s Control statements


Java’s program control statements can be put into three categories:
13

1) selection,
2) iteration, and
3) jump.

1) Selection statements (if and switch)


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

Java supports two selection statements: if and switch.

if

➢ The if statement is Java’s


conditional branch statement.

➢ It can be used to route program


execution through two different
paths.

General form

if (condition) statement1;
else statement2;

➢ 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.
➢ else clause is optional.

Working of if

➢ If the condition is true, then statement1 is executed.


➢ Otherwise, statement2 (if it exists) is executed.
Example:
Explanation:
int a, b;
if(a < b) a = 0; If a is less than b, then a is set to zero. Otherwise, b is set to zero.
else b = 0;

Nested ifs
A nested if is an if statement that is the target of another if or else.

Example:

if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d;
14

else a = c;
}
else a = d;

The if-else-if Ladder

A sequence of nested ifs is the if-else-if ladder.

if(condition)
statement; Working of if-else-if ladder
else if(condition)
statement; 1) The if statements are executed from the top down.
else if(condition) 2) As soon as one of the conditions controlling the if
statement; is true, the statement associated with that if is
. executed, and the rest of the ladder is bypassed.
.
3) If none of the conditions is true, then the final else
.
else statement will be executed.
statement; 4) If there is no final else and all other conditions are
false, then no action will take place.

// Demonstration if-else-if statements.


class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season; Q: This program is to
if(month == 12 || month == 1 || month == 2) determine which season
season = "Winter"; a particular month is in.
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer"; Output:
else if(month == 9 || month == 10 || month == 11)
season = "Autumn"; April is in the Spring.
else
season = "Invalid Month";

System.out.println("April is in the " + season + ".");


}
} ➢ The switch statement is Java’s
multiway branch statement.
switch ➢ It provides an easy way to dispatch
execution to different parts of your
switch (expression) {
code based on the value of an
case value1:
// statement sequence expression.
break; ➢ It often provides a better alternative
case value2: than a large series of if-else-if
// statement sequence statements.
➢ expression must be of type
byte,short,int,char,enum,or String
➢ Duplicate case values are not allowed.
case constants must be unique.
15

break;
.
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}

Working of switch

• The value of the expression is compared with each of the values in the case
statements.
• If a match is found, the code sequence following that case statement is executed.
• If none of the constants matches the value of the expression, then the default statement
is executed.
• However, the default statement is optional.
• If no case matches and no default is present, then no further action is taken.
• The break statement is used inside the switch to terminate a statement sequence.
• When a break statement is encountered, execution branches to the first line of code that
follows the entire switch statement.
• break is also optional. If break is omitted, the program just keeps executing the
remaining case blocks until either a break is found or the switch statement ends.

//Demonstration of switch statement


class Switch {
public static void main(String args[]) {
int month = 4;
String season;

switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
Q: This program is to
season = "Spring";
break; determine which season
case 6: a particular month is in.
case 7:
case 8:
season = "Summer";
break; Output:
case 9:
April is in the Spring.
16

case 10:
case 11:
season = "Autumn";
break;
default:
season = "Invalid Month";
}
System.out.println("April is in the " + season + ".");
}
}

Switch Example without break:


Output:
int x = 1;
switch(x) {
x is one
case 1: System.out.println("x is one");
x is two
case 2: System.out.println("x is two");
x is three
case 3: System.out.println("x is three");
out of the switch
}
System.out.println("out of the switch");

Nested switch Statements

We can write 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.

switch(count) {
case 1: Here, outer switch and inner
switch(target) { // nested switch
switch contains the same case
case 1: // no conflicts with outer switch
System.out.println("target is one"); constant 1, but it is perfectly
break; valid.
}
break;
case 2: // ...

Difference between if and switch

➢ The switch differs from the if in that switch can only test for equality, whereas if can
evaluate any type of Boolean expression.
➢ A switch statement is usually more efficient than a set of nested ifs.
➢ If we need to select among a large group of values, a switch statement will run much
faster than the equivalent logic coded using a sequence of if-elses.
17

Iteration statements (while,do-while and for)

➢ Java’s iteration statements


are for, while, and do-while

➢ Iteration statements enable


program execution to repeat
one or more statements,
which are called as loops.

➢ A loop repeatedly executes


the same set of instructions
until a termination condition
is met.

while
It repeats a statement or block while its controlling expression is true.

syntax
Example
while(condition)
{ class While {
// body of loop public static void main(String args[]) {
} int n = 1;
while(n < 5) {
Working of while System.out.println(n);
n++;
➢ The condition can be any Boolean expression. }
}
➢ The body of the loop will be executed as long }
as the conditional expression is true.

➢ When condition becomes false, control Output


passes to the next line of code immediately
following the loop. 1
➢. 2
➢ The curly braces are unnecessary if only a 3
nullsingle
statement
statement is being repeated. 4

Null statement
null statement is a statement which consists only of a semicolon.
18

The body of the while can be empty, that is, it can be a null statement.

Example
Output:
int n = 1;
No output will be printed but the loop stops
while(n++ < 5);
execution after 4 iterations.

do-while
do {
// body of loop
} while (condition); Example

class While {
Working of do-while public static void main(String args[]) {
int n = 1;
➢ In do-while, conditional do{
expression is at the bottom of System.out.println(n);
the loop. n++;
}while(n < 5);
➢ Each iteration of the do-while }
loop first executes the body of }
the loop and then evaluates the
conditional expression.
Output
➢ If this expression is true, the
loop will repeat. Otherwise, the 1
loop terminates. 2
3
➢ The do-while loop always 4
executes its body at least once.

for

Beginning with JDK 5, there are two


forms of the for loop.

1. Basic for loop


2. For-each (Enhanced for loop)
19

Basic for loop Flow Diagram

for(initialization; condition;
iteration)
{
// body
}

Working of for loop

1. When the loop first starts, the


initialization portion of the
loop is executed.

2. Next, condition is evaluated.


This must be a Boolean
expression.

3. If this expression is true, then Example


the body of the loop is
executed. class For {
If it is false, the loop public static void main(String args[]) {
terminates. for(i=1; i<5;i++) {
System.out.println(n);
4. Next, the }
Enhanced foriteration portion of
loop (for-each) }
the loop is executed.
}
5. The loop then iterates, first
evaluating the conditional Output
expression, then executing the
body of the loop, and then 1
2
executing the iteration
3
expression with each pass.
4

1. Declaring Loop Control Variables Inside the for Loop


It is possible to declare the variable inside the initialization portion of the for.

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


for(int n=10; n>0; n--)
System.out.println(n);

2. Using the Comma


i. Using comma, we can include more than one statement in the
initialization and iteration portions of the for loop.
ii. We can not use more than one statement in increment section.
20

int a, b; Output:

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


System.out.println("a = " + a); b=4
System.out.println("b = " + b); a=2
} b=3

For loop variations

1. The condition can be any Boolean expression.


2. Either the initialization or the iteration expression or both may be absent.

public static void main(String args[]) {


int i;
boolean done = false; Output:

i = 0; 1
for( ; !done; ) { 2
System.out.println( i); 3
if(i == 4) done = true; 4
i++;
}
}

3. We can leave all three parts of the for empty.

for( ; ; ) {
// ... Output:
} Infinite loop

The For-Each Version of the for Loop

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

form of for-each

for(type itr-var : collection)


statement-block

Here,

➢ type specifies the type


21

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

Example 1:
Output:
int nums[] = { 1, 2, 3, 4, 5 };
Value is: 1
Value is: 2
// use for-each style for to display and sum the values
Value is: 3
for(int x : nums) {
System.out.println("Value is: " + x); Value is: 4
} Value is: 5

Example 2: Iterating over multidimensional arrays

int sum = 0;
int nums[][] = { {1,2},{3,4}}; Output:

// use for-each for to display and sum the values Value is: 1
for(int x[] : nums) { Value is: 2
for(int y : x) { Value is: 3
System.out.println("Value is: " + y); Value is: 4
sum += y; Sum: 10
}
}
System.out.println("Sum: " + sum);

Nested For Loops


Like all other programming languages, Java allows loops to be nested. That is, one loop may be
inside another.
Output:

// Loops may be nested. * ** * * * ****


class Nested { * ** * * * ***
public static void main(String args[]) { * ** * * * **
int i, j; * ** * * * *
for(i=0; i<10; i++) { * ** * * *
for(j=i; j<10; j++) { * ** * *
System.out.print("*"); * ** *
} * **
System.out.println(); * *
} *
}
}
22

Jump Statements (break, continue, return)


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

Java supports three jump statements: break, continue, and return.

break
In Java, the break statement has three uses.

Unlabeled break

1) It terminates a statement
sequence in a switch
statement.
2) It can be used to exit a
loop.
Labeled break:
3) It can be used as a
“civilized” form of goto.

Unlabeled break : break to Exit a loop

Example

➢ By using break, we can force


immediate termination of a loop, class BrkEx
bypassing the conditional public static void main(String args[]) {
expression and any remaining code for(int i=1; i<5;i++) {
if(i == 4)
in the body of the loop. break;
System.out.println(n);
➢ When a break statement is }
encountered inside a loop, the loop }
is terminated and program control }
resumes at the next statement
following the loop.
Output
➢ The break statement can be used
with any of Java’s loops, including 1
intentionally infinite loops. 2
3
23

Labeled break : Form of Goto

➢ In Java, break statement can also be Example:


used as form of Goto.
class Break {
➢ Java does not have a goto public static void main(String args[])
{
statement. break gives you the
boolean t = true;
benefits of a goto without its
problems. first:
{
General form second:
{
break label; third:
{
✓ label is the name of a label System.out.println("Before the break.");
that identifies a block of code. if(t) break second; // break second block
System.out.println("This won't execute");
➢ A label is any valid Java identifier }
System.out.println("This won't execute");
followed by a colon. }
System.out.println("This is after second block.");
➢ To name a block, put a label at the }
start of it. }
}
➢ Labeled break causes execution to
Output:
resume at the end of the labeled
Before the break.
block.
This is after second block.

continue

1) continue is used to force an early Example:


iteration of the loop.
class Continue
2) In any iteration, continue will stop public static void main(String args[]) {
processing the code that is for(int i=1; i<5;i++) {
present after the continue and if( i % 2 == 0) continue;
continues the execution from the System.out.print(i);
next iteration. }
}
3) In while and do-while loops, a }
continue statement causes
control to be transferred directly
to the conditional expression that Output
controls the loop.
1
4) In a for loop, control goes first to 3
the iteration portion of the for
statement and then to the
conditional expression.
24

return
Example
➢ The return statement is used
// Demonstrate return.
to explicitly return from a
class Return {
method.
public static void main(String args[]) {
boolean t = true;
➢ It causes program control to
transfer back to the caller of
System.out.println("Before the return.");
the method.
if(t) return; // return to caller
➢ The return statement
immediately terminates the
System.out.println("This won't execute.");
method in which it is executed.
}
}

class
The General Form of a Class
class
class classname {
➢ class is a logical construct type instance-variable1;
which defines shape and type instance-variable2;
nature of an object. // ...
type instance-variableN;
➢ class is a template which
defines data and code that type methodname1(parameter-list) {
acts on that data. // body of method
}
➢ class defines a new data type. type methodname2(parameter-list) {
// body of method
➢ A class is declared by use of }
the class keyword. // ...
type methodnameN(parameter-list) {
// body of method
}
}

Instance variables or member variables


Members of a class
➢ The data, or variables, defined within a class are
called instance variables.
➢ Instance variables are called so, because each The variables and methods
instance of the class (that is, each object of the class) defined within a class are
contains its own copy of these variables. called members of the class.
25

Methods / Instance methods / member methods

The code is contained within methods.

Class Example

class Box {
double width;
double height;
double depth;
}

Declaring Objects (new operator)

➢ Objects are created with new keyword.


➢ The new operator dynamically allocates (at runtime) memory for an object and
returns a reference to it. This reference is memory address of object. This reference
is stored in a variable.

Form

classname object_reference = new classname ( );

Statement Effect

Box mybox;

width

mybox = new Box(); height

depth
mybox

Box object
26

Class vs Object

class object
Class is a template. Object is an instance of a class

Class is declared with class keyword. Object is created with new keyword.

Class does not create an actual object. Object will create an actual object.

Ex: class Test { } Ex: Test t = new Test();

Methods
➢ type specifies the type of data returned
This is the general form of a method: by the method.
➢ If the method does not return a value,
type name(parameter-list) {
its return type must be void.
// body of method ➢ Methods that have a return type other
than void return a value to the calling
} method using the following form:
➢ return value;

Points about methods

➢ Method can return values (primitives and objects)


➢ Method can take parameters (primitives and objects)

class Box {
double width, height, depth;
// compute and return volume
double volume() {
return width * height * depth;
}
class BoxDemo
{
public static void main(String args[]) {
Box b1 = new Box();
Box b2 = new Box();
double vol;

// assign values to mybox1's instance variables


b1.width = 10;
b1.height = 20;
b1.depth = 15;
27

/* assign different values to mybox2's instance variables */


b2.width = 3;
b2.height = 6;
b2.depth = 9;

// get volume of first box


vol = b1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = b2.volume();
System.out.println("Volume is " + vol);
}
}

Constructors
1. Constructors are used to initialize objects.
2. A constructor initializes an object immediately upon creation.
3. Constructor has the same name as the class name.
4. Constructor is syntactically similar to a method but it does not contain any return type,
including void.
5. Constructor is called when the object is created, before the new operator completed.

Types of Constructors

1. Default or no-argument constructor


2. Parameterized constructor

1. Default or no-argument constructor

1. The constructor which does not take any parameters is called as default or no-arg
constructor.
2. When we do not explicitly define a constructor for a class, then Java creates a
default constructor for the class.
3. The default constructor automatically initializes all instance variables to their default
values, which are zero, null, and false, for numeric types, reference types, and
boolean, respectively.

/* Here, Box uses a constructor to initialize the dimensions of a box. */


class Box {
double width;
double height;
double depth;
28

// This is the constructor for Box.


Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10; }

// compute and return volume


double volume() {
return width * height * depth;
}
}

2. Parameterized constructor
1. The constructor which takes parameters is called as parameterized
constructor.
2. This is useful to initialize different objects with different values.

/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */


class Box {
double width;
double height;
double depth;

// This is the constructor for Box.


Box(double w, double h, double d)
{
System.out.println("Constructing Box");
width = w;
height = h;
depth = d;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}
class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);

double vol;

// get volume of first box


vol = mybox1.volume();
29

System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

this keyword

this always refers to the currently executing object.

There are two uses with the this keyword.

1. To resolve the name collisions between instance variables and local variables
2. To explicitly call a constructor from another constructor

1. Instance Variable Hiding


To resolve the name collisions between instance variables and local variables

a) when a local variable has the same name as an instance variable, the local
variable hides the instance variable.
b) To resolve this name conflicts, we use this.

// Use this to resolve name-space collisions.


Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}

2. To explicitly call a constructor from another constructor

a) We can use this to call a constructor from another constructor. This is called a
Explicit constructor invocation.
b) this() should be the first statement inside a constructor.

class Box {
double width;
double height;
double depth;
Box()
{
System.out.println("Defualt constructor");
}
// This is the constructor for Box.
Box(double w,double h, double d) {
30

// calling default constructor


this();
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
}

Garbage Collection

➢ In Java, objects are allocated memory dynamically using new operator. But memory
de-allocation happens automatically.

➢ In Java, Garbage collection is the technique through which the memory de-allocation
will happen automatically.

Working of Garbage Collection

a) The job of the Garbage collector is to identify the unused objects and delete them from
memory.

b) Garbage collector checks the objects which do not have any reference and deletes
them from memory.

c) Garbage collector runs periodically during the program execution. But there is no
guarantee when a Garbage collector runs.

d) The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects.

e) Garbage collector calls finalize( ) method just before it runs.

gc() method

1. The gc() method is used to invoke the garbage collector to perform cleanup
processing.
2. The gc() is found in System and Runtime classes.

public static void gc(){ }

Example

public class MemoryTest{


public static void main(String args[]) {
31

Runtime r=Runtime.getRuntime();
System.out.println("Total Memory: "+r.totalMemory());
System.out.println("Free Memory: "+r.freeMemory());

for(int i=0;i<100;i++){
new MemoryTest();
}
System.out.println("After creating 100 instance, Free Memory: "+r.freeMemory());

System.gc();
System.out.println("After gc(), Free Memory: "+r.freeMemory());
}
}

finalize( ) method / finalization

a) By using finalize() method or finalization, we can define specific actions that will
occur when an object is just about reclaimed by the Garbage collector.

b) To add a finalizer to a class, we simply define the finalize( ) method. The Java
run time calls that method whenever it is about to recycle an object of that class.

c) Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed.

The finalize( ) method has this general form:


protected void finalize( )
{
// finalization code here
}

Overloading Methods

1. Overloading is the process through which we can define two or more methods within
the same class that share the same name but with different parameters (type and/or
number).
2. The Overloaded methods must differ in the type and / or number of their parameters.
3. When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
32

4. In some cases, Java’s automatic type conversions can play a role in overload
resolution.

// Demonstrate method overloading.


class OverloadDemo {
void test() {
System.out.println("No parameters");
}

// Overload test for one integer parameter.


void test(int a) {
System.out.println("a: " + a);
}

// Overload test for two integer parameters.


void test(int a, int b) { Output:
System.out.println("a and b: " + a + " " + b);
} No parameters
a: 10
// Overload test for a double parameter a and b: 10 20
double test(double a) { double a: 123.25
System.out.println("double a: " + a); Result of ob.test(123.25):
return a*a; 15190.5625
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;

// call all versions of test()


ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Constructor Overloading
We can define two or more constructors with the same name but with different parameters. This
process is called Constructor overloading.

class Box {
double width;
double height;
double depth;

// This is the constructor for Box.


Box() {
33

width = -1;
height = -1;
depth = -1; }

// This is the constructor for Box.


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Argument Passing Techniques


There are two argument passing techniques

1. Call-by-value

Java uses call-by-value when we pass primitive types to a method

2. Call-by-reference

Java uses call-by-reference when we pass object references to a method.


34

1. Call-by-value
➢ This approach copies the value of an argument into the formal parameter of the method.
Therefore, changes made to the parameter of the method have no effect on the
argument.

// Primitive types are passed by value.


class Test {
void meth(int i, int j) { Output:
i *= 2;
j /= 2; a and b before call: 15 20
} a and b after call: 15 20
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();

int a = 15, b = 20;

System.out.println("a and b before call: " + a + " " + b);

ob.meth(a, b);

System.out.println("a and b after call: " + a + " " + b);


}
}

2. Call-by-reference
1. In this approach, a reference to an argument (not the value of the argument) is passed
to the parameter.
2. Inside the subroutine, this reference is used to access the actual argument specified in
the call. This means that changes made to the parameter will affect the argument used
to call the method.
3. Although Java uses call-by-value to pass all arguments, the precise effect differs
between whether a primitive type or a reference type is passed.

// Objects are passed through their references.


class Test {
int a, b;

Test(int i, int j) { Output:


a = i;
b = j; a and b before call: 15 20
} a and b after call: 30 10
// pass an object
void meth(Test o) {
*= 2;
35

/= 2;
}
}

class PassObjRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}

Recursion
➢ Java supports recursion.
➢ Recursion is the process of defining something in terms of itself.
➢ A method that calls itself is said to be recursive.
➢ When a method calls itself, new local variables and parameters are allocated storage
on the stack, and the method code is executed with these new variables from the start.
➢ As each recursive call returns, the old local variables and parameters are removed from
the stack.
➢ The main advantage to recursive methods is that they can be used to create clearer
and simpler versions of several algorithms than can their iterative relatives.

Ex: QuickSort and AI related problems

➢ When writing recursive methods, we must have an if statement somewhere to force the
method to return without the recursive call being executed.

➢ Recursive versions of many routines may execute a bit more slowly than the iterative
equivalent because of the added overhead of the additional method calls.

Example:

Factorial of a Number:

// A simple example of recursion.


class Factorial {
// this is a recursive method
int fact(int n) {
int result;

if(n==1) return 1;
else
{
result = fact(n-1) * n;
36

return result;
}
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}

Encapsulation (Access Control)


Encapsulation provides two features:
1. It links data with the code it manipulates.
2. Access control

Access Control (private, public, protected and default access)

➢ Through encapsulation, we can control what parts of a program can access the
members of a class.
➢ By controlling access, you can prevent misuse.
➢ Java uses access modifier to determine how a member can be accessed.
➢ Java provides three access modifiers – private, public and protected.
➢ Java also provides default access level.

private

When a member of a class is specified as private, then that member can only be accessed by
other members of its class.

public
When a member of a class is specified as public, then that member be accessed by any other
code.

Protected

protected applies only when inheritance is involved.

default access

When no access modifier is used, then by default the member of a class is public within its
own package, but cannot be accessed outside of its package.
37

/* This program demonstrates the difference between public and private. */


class Test {
int a; // default access
public int b; // public access
private int c; // private access

// methods to access c
void setc(int i) {
// set c's value
c = i;
}
int getc() {
// get c's value
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();

// These are OK, a and b may be accessed directly


ob.a = 10; ob.b = 20;

// This is not OK and will cause an error //


ob.c = 100; // Error!

// You must access c through its methods


ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}

Static
Static is used to access a member by itself, without reference to a specific instance.
When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object.

Things can be declared as static

1. Variables
2. Methods
3. Static blocks
4. Nested classes
38

Things can not be declared as static

1. Local variables
2. classes
3. constructor

static variables (class variables)

➢ Instance variables declared as static are, essentially, global variables.


➢ When objects of its class are declared, no copy of a static variable is made.
➢ Instead, all instances of the class share the same static variable.

static methods

Methods declared as static have several restrictions:

➢ They can only directly call other static methods.


➢ They can only directly access static data.
➢ They cannot refer to this or super in any way.

Static blocks (OR) static initialization block

➢ Static blocks are used to initialize the static variables.


➢ Static block gets executed exactly once, when the class is first loaded.

// Demonstrate static variables, methods, and blocks.


class UseStatic {
static int a = 3;
static int b; Order:

static void meth(int x) { Static variables


System.out.println("x = " + x); Static blocks
System.out.println("a = " + a); Static methods (first main() then other
System.out.println("b = " + b); methods)
}

static { Output:
System.out.println("Static block initialized.");
b = a * 4; Inside the same class, we can access
} static members directly

public static void main(String args[]) { Outside the class, we can access the
meth(42); static members,using the format:
}
} Classname.variable
Classname.method( )
39

Nested and Inner classes

Defining a class inside another class is known as nested class.

Nested classes are 4 types in Java :

1. Inner class (Non-static Nested class)


2. Method-Local Inner class
3. Static Nested class
4. Anonymous Inner class

1. Inner class

➢ An inner class is a non-static nested class.


➢ It has access to all of the variables and methods of its outer class, including private
members
➢ We can create an instance of an Inner class only through the object of the outer class.

// Demonstrate Inner class.


class Outer {
private int x = 7;

class Inner{
void meth() {
System.out.println("x = " + x);
}
}

public static void main(String args[]) {


Outer ou = new Outer();
Outer.Inner in = ou.new Inner();
in.meth();
}
}

2. Method-Local Inner class

➢ We can define a nested class inside a method or any block scope (loops).
➢ We must create the instance of the inner class somewhere inside the method but
after the inner class definition.

// Demonstrate method-local nested class.


class Outer {

void display()
{
class Nest{
void meth() {
40

System.out.println("Hello");
}
}
Nest in = new Nest();
in.meth();
}

public static void main(String args[]) {


Outer ou = new Outer();
ou.display();

}
}

3. Static Nested class

A static nested class is one that has the static modifier applied.

// Demonstrate Static Nested class.


class Outer {
private int x = 7;

static class Inner{


void meth() {
System.out.println("x = " + x);
}
}

public static void main(String args[]) {


Inner in = new Inner();
in.meth();
}
}

String class

Java API defines String as a class

Two important things about Strings

1. For every string, Java creates an object of type String. Even string constants are
actually String objects.
2. String objects are immutable.

Creation of Strings / Construction of Strings

String are created many ways, but the easiest are two ways :
41

1) Without new operator

String s = “Java”;

2) With new operator

String s = new String(“Java”);

Difference Between the above two ways (OR) Important facts about String and Memory

➢ When a String is created using without new operator, then the string object will be
created inside the separate memory called “String Constant pool”.

➢ When a String is created using new operator, then the string object will be created both
heap memory and inside “String Constant pool”. But the heap memory copy will be
referred by the reference variable.

➢ When creating a string in String constant pool, JVM first checks the pool to see if there
is a similar string exists or not. If exists, no new string will be created, existing one will be
reused. If string does not exist, then JVM will create a new one.

Immutability:
Once a string is created, its String constant pool Heap memory
contents cannot be altered.
Java Java
String s = “Java”;

String s1 = new String(“Java”);


Java
String s2 = “Java”;

String s3 = new String(“Java”);


S1
s S2 S3

String Methods

Important methods in the String class

1. charAt() Returns the character located at the specified index


2. concat() Appends one String to the end of another ( "+" also works)
3. equalsIgnoreCase() Determines the equality of two Strings, ignoring case
4. length() Returns the number of characters in a String
5. replace() Replaces occurrences of a character with a new character
6. substring() Returns a part of a String
42

7. toLowerCase() Returns a String with uppercase characters converted


8. toString() Returns the value of a String
9. toUpperCase() Returns a String with lowercase characters converted
10. trim() Removes whitespace from the ends of a String

1. public char charAt(int index)

String x = “CARGO";
System.out.println( x.charAt(2) ); Output is : R

2. public String concat(String s)

String x = "taxi";
System.out.println( x.concat(" cab") ); Output is : taxi cab

+ and += operators

String x = "library";
System.out.println( x + " card"); Output is : library card

String x = "Atlantic";
x+= " ocean";
System.out.println( x ); Output is : Atlantic ocean

3. public boolean equals(Object anObject)

Compares this string to the specified object. The result is true if and only if the argument
is not null and is a String object that represents the same sequence of characters as this object.

String x = "Exit";
System.out.println( x.equals("EXIT")); Output is: false

String x = "Exit";
System.out.println( x.equals("Exit")); Output is: true

4. public boolean equalsIgnoreCase(String s)

This is similar to equals() method and it will return true even when characters in the String
objects being compared have differing cases.

String x = "Exit";
System.out.println( x.equalsIgnoreCase("EXIT")); Output is: true
43

5. public int length()

String x = "01234567";
System.out.println( x.length() ); Output is: 8

6. public String replace(char old, char new)

String x = "oxoxoxox";
System.out.println( x.replace('x', 'X') ); Output is: oXoXoXoX

7. public String substring(int begin)

String x = "0123456789";
System.out.println( x.substring(5) ); Output is: 56789

8. public String substring(int begin, int end)

String x = "0123456789";

System.out.println( x.substring(5, 8)); Output is: 567

9. public String toLowerCase()

String x = "A New Moon";


System.out.println( x.toLowerCase() ); Output is: a new moon

10. public String toUpperCase()

String x = "A New Moon";


System.out.println( x.toUpperCase() ); Output is: A NEW MOON

11. public String trim()

String x = " hi ";


System.out.println( x.trim()); Output is: hi

12. public String toString()

All objects in Java must have a toString() method, which typically returns a String that in
some meaningful way describes the object in question.

String x = "big surprise";


System.out.println( x.toString() ); Output is: big surprise
44

Write a Java program to demonstrate String class and its methods

// Demonstrating some String methods.


class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;

System.out.println("Length of strOb1: " +strOb1.length());

System.out.println("Char at index 3 in strOb1: " +strOb1.charAt(3));

if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");

if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
}

String arrays

We can have arrays of strings, just like we can have arrays of any other type of object.

// Demonstrate String arrays.


class StringDemo { Output:
public static void main(String args[]) {
String str[] = { "one", "two", "three" }; one
two
for(int i=0; i<str.length; i++) three
System.out.println(str[i]);
}
}

Command-Line Arguments

1) By using, command-line arguments, we can pass information into a program when we


run it.

2) A command-line argument is the information that directly follows the program’s name on
the command line when it is executed.
45

3) A Java application can accept any number of arguments from the command line.

4) Command Line arguments are stored as strings in a String array passed to the args
parameter of main( ).

5) The first command-line argument is stored at args[0], the second at args[1], and so on.

Example:

// Display all command-line arguments.


class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}

javac CommandLine.java
java CommandLine this is a test 10 -20
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1

Varargs (OR) Variable-Length arguments

1) In Java, as of JDK 5.0, It is possible to create methods that can take a variable number
of arguments.
2) A method that takes a variable number of arguments is called a variable-arity method,
or simply a varargs method.
3) A variable-length argument is specified by three periods (...).

Example:
void display(int ... v) { }

This syntax tells the compiler that display( ) can be called with zero or more arguments.
As a result, v is implicitly declared as an array of type int[ ].

The declaration rules for var-args

a) We can write normal parameters in a method that uses a var-arg parameter, but the
var-arg parameter must come at the last in the list.
46

b) Var-args limits: There must be only one var-args in a method

Valid var-args Invalid var-args

void display(int... x) { } void display(int x...) { }


void display(char c, int... x) { } void display(int... x, char... y) { }
void display(Box... b) { } void display(String... s, byte b) { }

// Demonstrate variable-length arguments.


class VarArgs {

// vaTest() now uses a vararg.


static void vaTest(int ... v) {
System.out.print("Number of args: ");

for(int x : v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
// Notice how vaTest() can be called with a variable number of arguments.
vaTest(10); // 1 arg
vaTest(1, 2, 3); // 3 args
vaTest(); // no args
}
}

Overloading Vararg Methods

➢ We can overload a method that takes a variable-length argument.


➢ A varargs method can also be overloaded by a non-varargs method.

// Varargs and overloading.


class VarArgs {

static void vaTest(int ... v) {


System.out.print("Number of args: " + v.length);
}

static void vaTest(boolean ... v) {


47

System.out.print("Number of args: " + v.length);

}
static void vaTest(String msg, int ... v) {
System.out.print("Number of args: " + v.length);
}

public static void main(String args[]) {


vaTest(1, 2, 3);
vaTest("Testing: ", 10, 20);
vaTest(true, false, false);
}
}

Varargs and Ambiguity

➢ Somewhat unexpected errors can result when overloading a method that takes a
variable length argument.

➢ These errors involve ambiguity because it is possible to create an ambiguous call to an


overloaded var-args method.

Ambiguity Error 1

// Varargs, overloading, and ambiguity.


class VarArgs {

static void vaTest(int ... v) {


System.out.print("Number of args: " + v.length);
}

static void vaTest(boolean ... v) {


System.out.print("Number of args: " + v.length);
}

public static void main(String args[]) {


vaTest(1, 2, 3); // OK
vaTest(true, false, false); // OK

vaTest(); // Error: Ambiguous!


}
}
48

Ambiguity Error 2

// Varargs, overloading, and ambiguity.


class VarArgs {

static void vaTest(int ... v) {


System.out.print("Number of args: " + v.length);
}

static void vaTest(int n, int ... v1) {


System.out.print("Number of args: " + v1.length);
}

public static void main(String args[]) {

vaTest(10); // Error: Ambiguous!


}
}

final keyword

final has 3 uses in Java.

1. To define the constants


2. To prevent Inheritance
3. TO prevent Method overriding

To define constants:

Once a constant is defined, it’s value can not be modified.

Ex:

final int PI = 3.14;

You might also like