40 likes | 50 Views
Understand operator precedence, associativity, and default initial values in Java to write effective programs. Learn about unary and binary operators and why relying on default values is risky.
E N D
Operators and Expressions: Wrap up Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in
Operator precedence • Higher to lower precedence ++, -- (both post and pre) unary !, +, - (logical NOT, unary +, unary -) unary *, /, % (multiply, divide, mod) binary +, - (add, subtract) binary <, <=, >, >= (LT, LE, GT, GE) binary ==, != (equality and non-equality) binary && (logical AND) binary || (logical OR) binary = (assignment) binary
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
Default initial values • Every declared variable gets a pre-defined default initial value in Java • Not true for many other languages • All primitive types get a zero value (boolean gets false) • You should not rely on this in your programs even if the compiler allows you to do so • Never use uninitialized variables in a program