OOP With Java/ course1 Sundus Abid-Almuttalib
Lecture1_Java Operators
Operators in Java Classified into four groups: Arithmetic Operator Bitwise Operator Relational Operator Logical Operator
Arithmetic Operators Addition + Subtraction - Multiplication * Division / Remainder % Increment ++ Addition Assignment += Subtraction Assignment -= Multiplication Assignment *= Division Assignment /= Modulus Assignment %= Decrement --
Arithmetic Operators If either or both operands associated with an arithmetic operator are floating point, the result is a floating point. % operator applies both to floating-point type and integer types. Example: class modulus { public static void main (String args []) int x = 42; double y = 42.3; System.out.println(“x mod 10 =“ + x%10); System.out.println(“y mod 10 = “ + y%10); } Output: x mod 10 =2 y mod 10 = 2.3
Increment and Decrement The increment and decrement operators are arithmetic and operate on one operand The increment operator (++) adds one to its operand The decrement operator (--) subtracts one from its operand The statement count++; is functionally equivalent to count = count + 1;
Increment and Decrement The increment and decrement operators can be applied in prefix form (before the operand) or postfix form (after the operand) When used alone in a statement, the prefix and postfix forms are functionally equivalent. That is, count++; is equivalent to ++count;
Increment and Decrement When used in a larger expression, the prefix and postfix forms have different effects In both cases the variable is incremented (decremented) But the value used in the larger expression depends on the form used. If count currently contains 45, then the statement total = count++; assigns 45 to total and 46 to count If count currently contains 45, then the statement total = ++count; assigns the value 46 to both total and count
Assignment Operators The right hand side of an assignment operator can be a complex expression The entire right-hand expression is evaluated first, then the result is combined with the original variable
Assignment Operators There are many assignment operators, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y
Bitwise Operator ~ Bitwise unary NOT & Bitwise AND | Bitwise OR ^ Bitwise XOR >> Shift Right >>> Shift Right zero fill << Shift left & = Bitwise AND Assignment |= Bitwise OR Assignment ^= Bitwise XOR Assignment >>= Shift Right Assignment >>>= Shift Right zero fill Assignment <<= Shift Left Assignment
Bitwise Operator A B A | B A & B A^ B ~A 1 Applied to integer type – long, int, short, byte and char. A B A | B A & B A^ B ~A 1
The Left Shift byte a=8, b=24; int c; c=a<<2; 00001000 << 2 = 00100000=32 Java’s automatic type conversion produces unexpected result when shifting byte and short values. Example: byte a = 64, b; int i; i = a<<2; b= (byte) (a<<2); i 00000000 00000000 00000001 00000000 = 256 b 00000000 = 0 Each left shift double the value which is equivalent to multiplying by 2.
The Right Shift byte a=8, b=24; int c ; c=a>>2; 00001000 >> 2= 00000010=2 Use sign extension. Each time we shift a value to the right, it divides that value by two and discards any remainder. The Unsigned Right Shift int c; c=a>>>1 00001000 >>> 1= 00000100=4
Relational operators > greater than >= greater than or equal to < less than <= less than or equal to = = equal to != not equal to The outcome of these operations is a boolean value. = = , != can be applied to any type in java. Only numeric types are compared using ordering operator.
Relational Operator int done; …… if(!done) …. // Valid in C /C++ but not in java if(done)…. if (done == 0)…. if(done!=0) …….. //Valid in Java
Boolean Logical Operator & Logical AND | Logical OR ^ Logical XOR || Short-circuit OR && Short-circuit AND ! Logical unary NOT &= AND Assignment |= OR Assignment ^ = XOR Assignment = = Equal to != Not equal to ?: Ternary if-then-else
Boolean Logical Operator The logical boolean operators &, | and ^ operates in the same way that they operate on the bits of integer. A b a & b a | b a ^ b !a true True false ture
Short Circuit Logical Operators || Short circuit logical OR && Short circuit logical AND If the left operand is sufficient to determine the result, the right operand is not evaluated if (demon !=0 && num / demon >10) This type of processing must be used carefully
The Conditional Operator The conditional operator is similar to an if-else statement, except that it forms an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater that num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands
Operator Precedence Highest ( ) [] . ++ -- ~ ! * / % + - ( ) [] . ++ -- ~ ! * / % + - >> >>> << > >= < <= = = != & ^ | && || ?: = op= Lowest
Lecture2-Arrays
One-Dimensional Arrays The general form of a one dimensional array declaration is : type var-name[ ]; array-var = new type[size]; e.g. int month_days[]; month_days = new int[12]; 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];
One-Dimensional Arrays month_days[1] = 28; System.out.println(month_days[3]); There is a second form that may be used to declare an array: type[ ] var-name; e.g. int a1[] = new int[3]; int[] a2 = new int[3];
One-Dimensional Arrays 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.");
One-Dimensional Arrays 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."); }
One-Dimensional Arrays // 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); }
Multidimensional Arrays int twoD[][] = new int[4][5];
Multidimensional Arrays // 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();}}}
Multidimensional Arrays int twoD[][] = new int[4][]; twoD[0] = new int[5]; twoD[1] = new int[4]; twoD[2] = new int[3]; twoD[3] = new int[2]; char twod1[][] = new char[3][4]; char[][] twod2 = new char[3][4];
Lecture3-For Loop & Jump Statements
For Loop for(initialization ; condition ; iteration) { // body } e.g. int n; for(n=10; n>0; n--) System.out.println("tick " + n); or for(int n=10; n>0; n—)
For Loop : Using the Comma int a, b; b = 4; for(a=1; a<b; a++) { System.out.println("a = " + a); System.out.println("b = " + b); b—; } int a, b; for(a=1, b=4; a<b; a++, b—) { System.out.println("a = " + a); System.out.println("b = " + b); } Output: a = 1 b = 4 a = 2 b = 3
Some for Loop Variations boolean done = false; for(int i=1; !done; i++) { // ... if(interrupted()) done = true;} ********************************* int i; boolean done = false; i = 0; for( ; !done; ) { System.out.println("i is " + i ); if(i == 10) done = true; i++; } *********************************** for( ; ; ) System.out.println(“hello“ );
Nested for Loops int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) System.out.print("."); System.out.println(); } Output .......... ......... ........ ....... ...... ..... …. … .. .
Jump Statements Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program.
break In Java, the break statement has three uses: in a switch statement . to exit a loop . as a "civilized" form of goto. i: 0 i: 1 i: 2 i: 3 i: 4 i: 5 i: 6 i: 7 i: 8 i: 9 Loop complete. for(int i=0; i<100; i++) { if(i == 10) break; // terminate loop if i is10 System.out.println("i: " + i); } System.out.println("Loop complete.");
break 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.");
Break inside a set of nested loops break statement will only break out of the innermost loop for(int i=0; i<3; i++) { System.out.print("Pass " + i + ": "); for(int j=0; j<100; j++) { if(j == 10) break; // terminate loop if j is 10 System.out.print(j + " "); } System.out.println(); System.out.println("Loops complete."); Output Pass 0: 0 1 2 3 4 5 6 7 8 9 Pass 1: 0 1 2 3 4 5 6 7 8 9 Pass 2: 0 1 2 3 4 5 6 7 8 9 Loops complete.
Using break as a Form of Goto the goto can be useful when you are exiting from a deeply nested set of loops. The general form of the labeled break statement is shown here: break label; Here, label is the name of a label that identifies a block of code
Output: Before the break. This is after second block.
Outer: for(int i=0; i<3; i++) { System. out 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."); Output: Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.
one: for(int i=0; i<3; i++) { System. out 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 + " ");
Using continue output
output
Lecture4-Introducing Classes
Introducing Classes a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. Thus, a class is a template for an object, and an object is an instance of a class. Because an object is an instance of a class, you will often see the two words object and instance used interchangeably.
The General Form of a Class When we define a class, we declare its exact form and nature. We do this by specifying the data that it contains and the code that operates on that data. While very simple classes may contain only code or only data, most real-world classes contain both. As we will see, a class’ code defines the interface to its data. A class is declared by use of the class keyword.
The General Form of a Class A simplified general form of a class definition is shown here: class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) // ... type methodnameN(parameter-list) { // body of method } }
class Box { double width; double height; double depth; } A Simple Class class Box { double width; double height; double depth; }
A Simple Class /* A program that uses the Box class. Call this file BoxDemo.java */ class Box { double width; double height; double depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; // assign values to mybox's instance variables mybox.width = 10; mybox.height = 20; mybox.depth = 15; // compute volume of box vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } }
A Closer Look at new the new operator dynamically allocates memory for an object. It has this general form: class-var = new classname ( );
Assigning Object ReferenceVariables what do you think the following fragment does? Box b1 = new Box(); Box b2 = b1; Box b1 = new Box(); Box b2 = b1; // ... b1 = null; Here, b1 has been set to null, but b2 still points to the original object.
Lecture5-Introducing Methods
Introducing Methods classes usually consist of two things: instance variables and methods.
Introducing Methods
Introducing Methods
Introducing Methods
Lecture6-Overloading Methods
Overloading Methods
Overloading Methods
Overloading Methods
Overloading Methods
Overloading Methods
Overloading Constructors
Overloading Constructors
Overloading Constructors
Overloading Constructors
Using Objects as Parameters
Using Objects as Parameters
Using Objects as Parameters
Using Objects as Parameters
Using Objects as Parameters
Lecture 7
Lecture8: String Handling Character Extraction
Character Extraction charAt( ) getChars( ) getBytes( ) toCharArray( )
Character Extraction
Character Extraction
Character Extraction
Lecture9: String Handling String Comparison
String Comparison equals( ) and equalsIgnoreCase( ) regionMatches( ) startsWith( ) and endsWith( ) compareTo( )
String Comparison
String Comparison
String Comparison
String Comparison
String Comparison
String Comparison
Lecture10: String Handling Searching And Modifying string
Searching Strings The String class provides two methods that allow you to search a string for a specified character or substring : indexOf( ) Searches for the first occurrence of a character or substring. lastIndexOf( ) Searches for the last occurrence of a character or substring. the methods return the index at which the character or substring was found, or –1 on failure.
Modifying a String substring( ) concat( ) replace( ) trim( )
Modifying a String
Modifying a String
Modifying a String
Modifying a String