G.
Pullaiah College of Engineering and Technology
Object Oriented Programming through Java
Department of Computer Science &
Engineering
UNIT 2
1. OPERATORS
2. CONTROL STATEMENTS
3. CLASS FUNDAMENTALS,
4. OBJECTS
5. METHODS
6. CONSTRUCTORS
7. THE THIS KEYWORD
8. GARBAGE COLLECTION
9. THE FINALIZE() METHOD
Operating with Java
Most programming languages have operators
Operators are short-hand symbols for actions
= Assign right to left
+ Add two numbers (or concatenate two strings)
Operators in Java have fixed meaning
No operator overloading
Can’t say:
List = List + Item; // Add item to list
Kinds of Operators
Category What it does… Examples
Arithmetic Addition, subtraction +, -, /
Assignment Set a value to an expression =, +=, &=
Conditional Choose one of two values ?:
Logical Logical comparisons &&, ||
Relational Compare values ==, >=
Bitwise Move bits within a number <<, >>
Operator Precedence
Usually things go left-to-right, but there are
precedence rules
Nutshell reading lists operators by precedence
Override precedence with ()’s
Arithmetic Operators
The usual suspects: plus, minus, blah, blah, blah
Modulo/remainder operator
Modulo Operator
Modulo (or remainder) operator: what’s left over
after division
7%3 = 1
198%3 = ??
6.0%4.0 = 2
Is it odd or even?
Looping with clock arithmetic
Appointment at 5pm everyday
Baking 217 cakes: step 3 of 7 same as 24 of 28
Short-Hand Operators
Increment and decrement: ++ and --
Often need to add or subtract 1
Pre: Add (subtract) first
Post: Add (subtract) afterwards
Compiler can sometimes optimize
Testing Out Short-Hand
Suppose we start with:
X = 7;
Y = 9;
After X Y Whole thing
X++ * Y
++X + Y
++X / Y++
What’s the difference between:
X++;
++X;
Are You My Type?
What’s the type of a result?
Expression Result type
int * int int
float * float ??
int * float ??
int / int ??
Conversion & promotion
Assignment Operators
Change the value on the left to the value of the
expression on the right
If you want to: Try:
Assign 8 to Y Y = 8;
Add 1 to Y Y++;
Assign Y+10 to Y X += 10;
Works for Strings Too
Strings are “added” (concatenated) with +
What is Name after the third line?
Name = “Simpson”;
First = “Lisa”;
Name += First;
What’s the result here?
Age = 11;
Message = “He’s “ + Age + “ years old.”;
Conditional Operator
Instead of If..Then..Else, use ?:
Takes three arguments in the form:
Boolean condition ? If-true : If-false
If (Simpson == “Lisa”) {
Message = “She’s our favorite!”;
} else {
Message= “Doh!”;
}
System.out.println(Message);
is the same as…
Using the Conditional Operator
System.out.println(Simpson==“Lisa”
? ”She’s our favorite” :“Doh!”);
(The above should be on one line in a real program)
And, But and Or will get you pretty
far..
Logical operators combine simple expressions to
form complex ones
Boolean logic
Expression One Expression Two One AND Two One OR Two One XOR Two
False False False False False
False True False True True
True False False True True
True True True True False
Boolean Types
True or false are real values in Java
Some languages just use 0 and not 0
if (y = 7) then …
In Java result of a comparison is Boolean
8 != 9 ??
8 != 8 ??
Logical Operators in Java
Translating logic into Java
AND &&
OR ||
XOR ^
NOT !
Boolean Expressions
De Morgan’s Laws with Expressions One & Two
One OR Two == One AND Two
One AND Two == One OR Two
Some handy relations
One XOR One == False
One OR One == True
Short-Circuit
Remember:
False AND Anything == False
True OR Anything == True
Sometimes compiler can short-circuit and skip
evaluation of second expression
What if there are side effects?
Sideline on Side Effects
Side effects are results of expression evaluation
other than the expression’s value
Examples
X++;
Output:
System.out.println(“Howdy!”);
Short-Circuiting Side Effects
Short-circuiting could prevent a side effect
How do you force the compiler to evaluate a
second expression?
No Short-Circuit Here
Guarantee that the second expression is evaluated
AND &
OR |
XOR ^
(Why is ^ listed here?)
Relational Operators
Determine the relationship between values
Equality & inequality
Less than, greater than
(In)Equality
Equality is different from assignment
== != =
Most keyboards just have =
Use == for equality
And != for inequality
Bitwise Operators
Computers are binary creatures: everything’s on or
off
For example, computers can’t store decimal
numbers so
Binary Arithmetic
Everything’s in powers of two
Turn 78 into:
128 64 32 16 8 4 2 1
0 1 0 0 1 1 1 0
64 8 4 2
Accentuate the positive
Computers don’t know about negative numbers
Use the first (leftmost) bit as a sign bit:
1 if negative: -5 is 11111101
0 if positive: +5 is 00000011
Bitwise is Binary
Work with the bits inside the values
Only good for integral values (integer numbers,
bytes and characters)
Operator Name Description
& AND AND the corresponding bits in the two
operands
| OR OR the corresponding bits in the two
operands
^ XOR XOR the corresponding bits in the two
operands
<< Left shift Shift the bits from right to left
>> Right shift with sign Shift the bits right and preserve the sign
extension
>>> Right shift with zero Shift the bits right and always fill in 0’s
extension
~ Complement Switch 0’s and 1’s
And Shift Your Bits ‘Round and
‘Round
Bitwise AND of 78 and 34
128 64 32 16 8 4 2 1
78 0 1 0 0 1 1 1 0
34 0 0 1 0 0 0 1 0
2 0 0 0 0 0 0 1 0
Control Statements
• if else
• switch
• while
• do while
• for
• break
• continue
• return
• Labeled break, continue
if-else
if(conditional_statement){
statement to be executed if conditions becomes
true
}else{
statements to be executed if the above condition
becomes false
}
switch
switch(byte/short/int){
case expression:
statements
case expression:
statements
default:
statement
}
while - loop
while(condition_statementtrue){
Statements to be executed when the condition becomes
true and execute them repeatedly until condition
becomes false.
}
E.g.
int x =2;
while(x>5){
system.out.println(“value of x:”+x);
x++;
}
do while - loop
do{
statements to be executed at least once without
looking at the condition.
The statements will be exeucted until the condition
becomes true.
}while(condition_statement);
for - loop
for(initialization; condition; increment/decrement){
statements to be executed until the condition
becomes false
}
E.g:
for(int x=0; x<10;x++){
System.out.println(“value of x:”+x);
}
break
Break is used in the loops and when executed,
the control of the execution will come out of the
loop.
for(int i=0;i<50;i++){
if(i%13==0){
break;
}
System.out.println(“Value of i:”+i);
}
continue
Continue makes the loop to skip the current
execution and continues with the next iteration.
for(int i=0;i<50;i++){
if(i%13==0){
continue;
}
System.out.println(“Value of i:”+i);
}
return
return statement can be used to cause execution
to branch back to the caller of the method.
Labeled break,continue
Labeled break and continue statements will
break or continue from the loop that is
mentioned.
Used in nested loops.
Objects and Classes
OO Programming Concepts
Creating Objects and Object Reference Variables
Differences between primitive data type and object type
Automatic garbage collection
Constructors
Modifiers (public, private and static)
Instance and Class Variables and Methods
Scope of Variables
Use the this Keyword
Case Studies (Mortgage class and Count class)
OO Programming Concepts
An object A Circle object
Data Field
data field 1
radius = 5
... State
Method
data field n findArea
method 1
... Behavior
method n
Class and Objects
Circle UML Graphical notation for classes
radius: double UML Graphical notation for fields
UML Graphical notation for methods
findArea(): double
new Circle() new Circle()
circle1: Circle circlen: Circle UML Graphical notation
for objects
radius = 2 ... radius = 5
Class Declaration
class Circle {
double radius = 1.0;
double findArea(){
return radius * radius * 3.14159;
}
}
Declaring Object Reference Variables
ClassName objectReference;
Example:
Circle myCircle;
Creating Objects
objectReference = new ClassName();
Example:
myCircle = new Circle();
The object reference is assigned to the object
reference variable.
Declaring/Creating Objects in a Single Step
ClassName objectReference = new
ClassName();
Example:
Circle myCircle = new Circle();
Differences between variables of
primitive Data types and object types
Primitive type int i = 1 i 1
Object type Circle c c reference
c: Circle
Created using
new Circle() radius = 1
Copying Variables of Primitive Data
Types and Object Types
Primitive type assignment Object type assignment
i=j c1 = c2
Before: After: Before: After:
i 1 i 2 c1 c1
j 2 j 2 c2 c2
c1: Circle c2: Circle
radius = 5 radius = 9
Garbage Collection
As shown in the previous figure, after
the assignment statement c1 = c2, c1
points to the same object referenced by
c2. The object previously referenced by
c1 is no longer useful. This object is
known as garbage. Garbage is
automatically collected by JVM.
Garbage Collection, cont
TIP: If you know that an object is no
longer needed, you can explicitly assign
null to a reference variable for the
object. The Java VM will automatically
collect the space if the object is not
referenced by any variable.
Accessing Objects
Referencing the object’s data:
objectReference.data
myCircle.radius
Invoking the object’s method:
objectReference.method
myCircle.findArea()
Example : Using Objects
Objective: Demonstrate creating objects,
accessing data, and using methods.
TestCircle Run
Constructors
Circle(double r) {
radius = r;
} Constructors are a
special kind of
Circle() { methods that are
radius = 1.0; invoked to construct
} objects.
myCircle = new Circle(5.0);
Constructors, cont.
A constructor with no parameters is referred to as
a default constructor.
Constructors must have the same name as the
class itself.
Constructors do not have a return type—not
even void.
Constructors are invoked using the new
operator when an object is created. Constructors
play the role of initializing objects.
Example : Using Classes from the
Java Library
Objective: Demonstrate using classes from the
Java library. Use the JFrame class in the
javax.swing package to create two frames; use
the methods in the JFrame class to set the title,
size and location of the frames and to display
the frames.
TestFrame Run
Example : Using Constructors
Objective: Demonstrate the role of
constructors and use them to create
objects.
TestCircleWithConstructors Run
Visibility Modifiers and
Accessor Methods
By default, the class, variable, or data can be
accessed by any class in the same package.
public
The class, data, or method is visible to any class in any
package.
private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.
Example :
Using the private Modifier and
Accessor Methods
In this example, private data are used for the radius
and the accessor methods getRadius and setRadius
are provided for the clients to retrieve and modify
the radius.
TestCircleWithAccessors Run
Passing Objects to Methods
Passing by value (the value is the reference to the
object)
Example Passing Objects as Arguments
TestPassingObject Run
Passing Objects to Methods, cont.
main printAreas
method method
times
n 5 5 Pass by value (here the value is 5)
myCircle Reference Reference Pass by value (here the value is the
reference for the object)
myCircle: Circle
radius = 1
Instance
Variables, and Methods
Instance variables belong to a specific instance.
Instance methods are invoked by an instance of
the class.
Class Variables, Constants,
and Methods
Class variables are shared by all the instances of the
class.
Class methods are not tied to a specific object.
Class constants are final variables shared by all the
instances of the class.
Class Variables, Constants,
and Methods, cont.
To declare class variables, constants, and methods,
use the static modifier.
Class Variables, Constants,
and Methods, cont.
UML Notation: Memory
+: public variables or methods
-: private variables or methods
underline: static variables or metods
circle1:Circle 1 radius
instantiate -radius = 1
radius is an instance CircleWithStaticVariable -numOfObjects = 2
variable, and
numOfObjects is a -radius
class variable -numOfObjects
2 numOfObjects
+getRadius(): double instantiate
+setRadius(radius: double): void circle2:Circle
+getNumOfObjects(): int
+findArea(): double
-radius = 5 5 radius
-numOfObjects = 2
Example
Using Instance and Class Variables and
Method
Objective: Demonstrate the roles of
instance and class variables and their
uses. This example adds a class variable
numOfObjects to track the number of
Circle objects created.
TestCircleWithStaticVariable Run
Scope of Variables
The scope of instance and class variables is the
entire class. They can be declared anywhere inside
a class.
The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must be
declared before it can be used.
The Keyword this
Use this to refer to the current object.
Use this to invoke other constructors of the
object.
Array of Objects
Circle[] circleArray = new Circle[10];
An array of objects is actually an array of
reference variables. So invoking
circleArray[1].findArea() involves two
levels of referencing as shown in the next
figure. circleArray references to the entire
array. circleArray[1] references to a
Circle object.
Array of Objects, cont.
Circle[] circleArray = new Circle[10];
circleArray reference circleArray[0] Circle object 0
circleArray[1]
… Circle object 1
circleArray[9] Circle object 9
Array of Objects, cont.
Example : Summarizing the areas of
the circles
TotalArea Run
Class Abstraction
Class abstraction means to separate class
implementation from the use of the class. The creator
of the class provides a description of the class and let
the user know how the class can be used. The user of
the class does not need to know how the class is
implemented. The detail of implementation is
encapsulated and hidden from the user.
Example The Mortgage Class
Mortgage
-annualInterestRate: double
-numOfYears: int
-loanAmount: double
Mortgage
+Mortgage()
+Mortgage(annualInterestRate: double,
numOfYears: int, loanAmount: double)
+getAnnualInterestRate(): double TestMortgageClass
+getNumOfYears(): int
+getLoanAmount(): double
+setAnnualInterestRate(annualInteresteRate: double): void
+setNumOfYears(numOfYears: int): void
+setLoanAmount(loanAmount: double): void
Run
+monthlyPayment(): double
+totalPayment(): double
Example The Count Class
TestVoteCandidate Run
Java API and Core Java classes
java.lang
Contains core Java classes, such as numeric classes,
strings, and objects. This package is implicitly
imported to every Java program.
java.awt
Contains classes for graphics.
java.applet
Contains classes for supporting applets.
Java API and Core Java classes,
cont.
java.io
Contains classes for input and output
streams and files.
java.util
Contains many utilities, such as date.
java.net
Contains classes for supporting
network communications.
Java API and Core Java classes,
cont.
java.awt.image
Contains classes for managing bitmap images.
java.awt.peer
Platform-specific GUI implementation.
Others:
java.sql
java.rmi