90 likes | 98 Views
Learn about unary and binary operators in computer science, their examples, and how they operate on variables or expressions. Get insights into type casting, automatic type conversion, and practical examples. Join the tutorial today at 11:00-12:00 in CS103.
E N D
Announcements • B7 tutorial today 1100-1200 in CS103 • In CSE department • Ask at entry desk for direction to CS103
Unary and binary operators • Operators acting on a single variable or an expression are called unary operators • Example: logical NOT, unary plus, unary minus boolean x = true; boolean y = !x; // unary logical NOT int z = 23; int w = +z; // unary plus int k = -z; // unary minus or negation int j = -z-20; // what is j: -43 or -3? int r = -(z-20); // what is r?
Unary and binary operators • Operators acting on two variables or expressions are called binary operators • Example: add (+), subtract (-), multiply (*), … • Example of boolean operators (unary and binary) boolean x = true; boolean y = !x && x; boolean z = !(y || x); boolean w = !y && !x; boolean k = !(y && x); boolean p = !y || !x;
Examples Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in
Printing characters 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((char)(grade+1)); // prints B } } • Notice the type cast • Notice the automatic type conversion
Printing characters class printcharacter{ public static void main(String arg[]){ char grade=‘A’; System.out.println(grade++);// prints A System.out.println(grade); // prints B } } • Post-increment
Printing characters class printcharacter{ public static void main(String arg[]){ char grade=‘A’; System.out.println(++grade);// prints B System.out.println(grade); // prints B } } • Pre-increment
More type cast class castExample{ public static void main(String arg[]){ double x=Math.PI; // Call to Math class double y=-Math.PI; System.out.println(“Value of PI is: ” + x); System.out.println((int)x); // prints 3 System.out.println((int)y); // prints -3 } }
Celsius to Fahrenheit class CToF{ public static void main(String arg[]){ double C = 40; double F; F = (C/5.0)*9.0 + 32; System.out.println(C + “Celsius is same as ” + F + “ Fahrenheit”); } }