Download presentation
Presentation is loading. Please wait.
Published byReynard Butler Modified over 6 years ago
1
G. Pullaiah College of Engineering and Technology
Object Oriented Programming through Java Department of Computer Science & Engineering
2
Unit 2 1. Operators 2. Control Statements 3. Class Fundamentals, 4
Unit Operators 2. Control Statements 3. Class Fundamentals, 4. Objects 5. Methods 6. Constructors 7. The this Keyword 8. Garbage Collection 9. The Finalize() method 1
3
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
4
Kinds of Operators Computers need step-step instructions 2
5
Operator Precedence Usually things go left-to-right, but there are precedence rules Nutshell reading lists operators by precedence Override precedence with ()’s
6
Arithmetic Operators The usual suspects: plus, minus, blah, blah, blah
Modulo/remainder operator
7
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
8
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
9
Testing Out Short-Hand
Suppose we start with: X = 7; Y = 9; What’s the difference between: X++; ++X;
10
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
11
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;
12
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.”;
13
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…
14
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)
15
And, But and Or will get you pretty far..
Logical operators combine simple expressions to form complex ones Boolean logic
16
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 ??
17
Logical Operators in Java
Translating logic into Java AND && OR || XOR ^ NOT !
18
Boolean Expressions One OR Two == One AND Two
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
19
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?
20
Sideline on Side Effects
Side effects are results of expression evaluation other than the expression’s value Examples X++; Output: System.out.println(“Howdy!”);
21
Short-Circuiting Side Effects
Short-circuiting could prevent a side effect How do you force the compiler to evaluate a second expression?
22
No Short-Circuit Here Guarantee that the second expression is evaluated AND & OR | XOR ^ (Why is ^ listed here?)
23
Relational Operators Determine the relationship between values
Equality & inequality Less than, greater than
24
(In)Equality Equality is different from assignment == != =
== != = Most keyboards just have = Use == for equality And != for inequality
25
Bitwise Operators Computers are binary creatures: everything’s on or off For example, computers can’t store decimal numbers so
26
Binary Arithmetic Everything’s in powers of two Turn 78 into:
27
Accentuate the positive
Computers don’t know about negative numbers Use the first (leftmost) bit as a sign bit: 1 if negative: -5 is 0 if positive: +5 is
28
Bitwise is Binary Work with the bits inside the values
Only good for integral values (integer numbers, bytes and characters)
29
And Shift Your Bits ‘Round and ‘Round
Bitwise AND of 78 and 34
30
Control Statements if else switch while do while for break continue
return Labeled break, continue
31
if-else if(conditional_statement){ statement to be executed if conditions becomes true }else{ statements to be executed if the above condition becomes false }
32
switch switch(byte/short/int){ case expression: statements default: statement }
33
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++;
34
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);
35
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);
36
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);
37
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);
38
return return statement can be used to cause execution to branch back to the caller of the method.
39
Labeled break,continue
Labeled break and continue statements will break or continue from the loop that is mentioned. Used in nested loops.
40
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)
41
OO Programming Concepts
42
Class and Objects
43
Class Declaration class Circle { double radius = 1.0; double findArea(){ return radius * radius * ; }
44
Declaring Object Reference Variables
ClassName objectReference; Example: Circle myCircle;
45
Creating Objects objectReference = new ClassName(); Example:
myCircle = new Circle(); The object reference is assigned to the object reference variable.
46
Declaring/Creating Objects in a Single Step
ClassName objectReference = new ClassName(); Example: Circle myCircle = new Circle();
47
Differences between variables of primitive Data types and object types
48
Copying Variables of Primitive Data Types and Object Types
49
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.
50
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.
51
Accessing Objects Referencing the object’s data: objectReference.data
myCircle.radius Invoking the object’s method: objectReference.method myCircle.findArea()
52
Example : Using Objects
Objective: Demonstrate creating objects, accessing data, and using methods. TestCircle Run
53
Constructors Circle(double r) { radius = r; } Circle() { radius = 1.0; myCircle = new Circle(5.0); Constructors are a special kind of methods that are invoked to construct objects.
54
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.
55
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
56
Example : Using Constructors
Objective: Demonstrate the role of constructors and use them to create objects. TestCircleWithConstructors Run
57
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.
58
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
59
Passing Objects to Methods
Passing by value (the value is the reference to the object) Example Passing Objects as Arguments TestPassingObject Run
60
Passing Objects to Methods, cont.
61
Instance Variables, and Methods
Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class.
62
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.
63
Class Variables, Constants, and Methods, cont.
To declare class variables, constants, and methods, use the static modifier.
64
Class Variables, Constants, and Methods, cont.
65
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
66
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.
67
The Keyword this Use this to refer to the current object.
Use this to invoke other constructors of the object.
68
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.
69
Array of Objects, cont. Circle[] circleArray = new Circle[10];
70
Array of Objects, cont. Example : Summarizing the areas of the circles
TotalArea Run
71
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.
72
Example The Mortgage Class
TestMortgageClass Run
73
Example The Count Class
Run TestVoteCandidate
74
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.
75
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.
76
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.