90 likes | 98 Views
Printing characters : Revisited. class printcharacter{ public static void main(String arg[]){ char grade=‘A’; System.out.println(grade); // prints A System.out.println((int)grade); // prints 65 System.out.println(grade+’B’); // prints 131
E N D
Printing characters : Revisited class printcharacter{ public static void main(String arg[]){ char grade=‘A’; System.out.println(grade); // prints A System.out.println((int)grade); // prints 65 System.out.println(grade+’B’); // prints 131 System.out.println(grade+1); // prints 66 System.out.println(grade+"1"); // prints A1 System.out.println(grade+'1'); // prints 114 System.out.println((char)(grade+1)); // prints B } } • Notice the difference between 1, ‘1’ and “1” • Notice the automatic type conversion with + operator
Logical operators • Not: ! • AND: && • OR: || Examples: int x = 12; boolean isTwoDigit = ((x >= 10) && (x < 100)); boolean isMultipleOfSix = ((x%6)==0); boolean isOdd = !((x%2)==0); boolean isTwoDigit = (10 <= x < 100); [Wrong!]
Checking case class upperCaseCharacter{ public static void main(String arg[]){ char c=‘0’; boolean isuppercase, islowercase; isuppercase = ((c >= ‘A’) && (c <= ‘Z’)); islowercase = ((c >= ‘a’) && (c <= ‘z’)); System.out.ptintln(“The character is ” + c + “. Uppercase: ” + isuppercase); } }
Divisibility by 4 class divisibleByFour{ public static void main(String arg[]){ int x = 121; int lastTwoDigits; boolean isdivBy4; lastTwoDigits = x%100; isdivBy4 = ((lastTwoDigits % 4) == 0); System.out.println(“The number is: ” + x + “. Divisible by 4? ” + isdivBy4); } }
Exchanging numbers class swapBad{ public static void main(String arg[]){ int x = 121; int y = 200; System.out.println(“x: ” + x + “, y: ” + y); x = x + y; // Could overflow y = x – y; x = x – y; System.out.println(“x: ” + x + “, y: ” + y); } }
Exchanging numbers class swapGood{ public static void main(String arg[]){ int x = 121; int y = 200; int temp; System.out.println(“x: ” + x + “, y: ” + y); temp = x; x = y; y = temp; System.out.println(“x: ” + x + “, y: ” + y); } }
Operator precedence • Higher to lower precedence ++, -- (both post and pre) ! (logical NOT) *, /, % (multiply, divide, mod) +, - (add, subtract) <, <=, >, >= (LT, LE, GT, GE) ==, != (equality and non-equality) && (logical AND) || (logical OR) = (assignment)
Operator precedence • What is the answer? (assume x=1) x*x+x%2 2*x/2%4 (need to know associativity) • Almost all operators are left associative • This indicates in which direction the operators of the same precedence will evaluate • Assignment has right associativity x=y=2; // assigns y=2 first and then x=y • The above expression would lead to wrong answer if assignment was left associative