760 likes | 769 Views
Understand the fundamentals of operators, their precedence, and control statements in Java. Learn about arithmetic, short-hand, conditional operators, logical expressions, bitwise operations, and control statements like if-else and loops.
E N D
G. Pullaiah College of Engineering and Technology Object Oriented Programming through Java Department of Computer Science & Engineering
Unit 21. Operators2. Control Statements3. Class Fundamentals,4. Objects5. Methods6. Constructors7. The this Keyword8. Garbage Collection9. 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
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; 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
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:
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)
And Shift Your Bits ‘Round and ‘Round • Bitwise AND of 78 and 34
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)
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
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.