100 likes | 142 Views
Operators and Expressions. Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in. Agenda. Your first programs in Java Arithmetic operators Expressions. Printing on monitor. /* Example of multiline comment; This is our first Program */ class printcoursename{
E N D
Operators and Expressions Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in
Agenda • Your first programs in Java • Arithmetic operators • Expressions
Printing on monitor /* Example of multiline comment; This is our first Program */ class printcoursename{ public static void main(String arg[]){ // This prints name of the course (single line comment) System.out.println("This course is ESc101N"); } }
Printing on monitor /* Example of multiline comment; This is our second Program. Will print the same thing in a different way. */ class printcoursename{ public static void main(String arg[]){ // This prints name of the course (single line comment) System.out.println("This ” + “course ” + “is ” + “ESc101N”); } }
Printing numbers class printnumber { public static void main (String args[]){ // Notice that I can use args also // because it is a variable name and can be // anything. int var1; // Declaration var1 = 124; // Operator and expression System.out.println("Value of var1 is: "+var1); } }
Operators • Arithmetic operators +, -, *, /, % • Addition: a+b • Subtraction: a-b • Multiplication: a*b • Division: a/b (what is this? Find out in lab) • Remainder: a%b • Assignment operator = • Comparison operators: > , < , >= , <=, == , !=
Expressions • An expression is a statement involving operators and variables or constants Example: x = a + b; // Add a and b and put the // result in x Example: int x = 6; // Declaration and // initialization int y = x; y = y + 1; // Same as y += 1; // Same as y++; • Two new operators: += , ++ • More operators: -= , *= , /= , --
Expressions • More examples class SomeThing { public static void main (String args[]) { int x, y; boolean z, w; x = 10; y = 12; z = (x > y); w = (y >= x); System.out.println(“z: ” + z + “,” + “w: ” +w); } }
Expressions • More examples class SomeThing { public static void main (String args[]) { int x, y; boolean z, w; x = 10; y = 10; z = (x == y); w = (y != x); System.out.println(“z: ” + z + “,” + “w: ” +w); } }
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 isLessThan100Perfect = ((x==6) || (x==28)); boolean isTwoDigit = (10 <= x < 100); [Wrong!]