Saturday, May 5, 2012

GIST NOTES 4 - Java Operators



GIST NOTES 4 - Java Operators

[DISCLAIMER: This is solely for non-commercial use. I don't claim ownership of this content. This is a crux of all my readings studies and analysis. Some of them are excerpts from famous books on  the subject. Some of them are my contemplation upon experiments with direct hand coded code samples using IDE or notepad.


I've created this mainly to reduce an entire book into few pages of critical content that we should never forget. Even after years, you don't need to read the entire book again to get back its philosophy. I hope these notes will help you to replay the entire book in your mind once again.]


[JDK 7]

operators produce new values from one or more operands.

operands are the things that are on the left or right side of the operator.

+ operator adds two primitive numbers together or concatenates string literals.

&, | and ^ operators can be used in two different ways; one for logic another for binary operations.

Assignment Operator
-------------------

When assigning value to a primitive, size matters.

Pointers in C/C++ are physical memory locations.

Object references in Java are logical IDs to an abstracted entity called object that lives in heap memory of the Virtual Machine. Nobody knows the physical memory locations the VM uses to store objects.

Java DOES NOT have pointers.

Compound Assignment Operators
-----------------------------

Like +=, -=, *= and /=.

Expression on the right hand side of the compound operator will be evaluated first before employing compound operator.

Relational Operators
---------------------

Relational operators always results in boolean value.

Hence the resulting value can be used for conditionals or can be assigned to a boolean primitive variable.

> >= < <= operators allow any combination of integers, floating point numbers or characters to be compared.

Comparison between characters and between character and a number are all LEGAL in java (w.r.to relational operators mentioned above).

Java uses unicode value of the character for comparison.

Equality Operators (== and !=)
------------------------------

These two return boolean value as a result of comparison.

One can't compare incompatible types.

== looks at the bit pattern of the variables being compared.

(5.0 == 5L) returns true.

Using = in the place of == will lead to erraneous behaviour (though this confusion will occur only with boolean variables).

== operator does not look inside the objects being compared.

However when comparing enum constants(in object form), == does indeed finds out whether they are actually equal or not(enum constants are static objects, that is why).

instanceof operator
-------------------

instanceof operator is used only for object reference variables.

Lefthand side object should pass IS-A test for the right hand side type. e.g. ("hi" instanceof String) returns true.

Usually instanceof check is done before doing a downcast to convert an object to one of its subtypes.

Testing instanceof on a null is LEGAL.

When two OBVIOUSLY unrelated types (even compiler knows you are STUPID) are compared with instanceof, compilation fails. e.g. ("hi" instanceof Thread) fails to compile. Basically types from two different class hierarchies are not allowed to be compared.

( (new int[]{1,2}) instanceof Object ) returns true.

Arithmetic Operators
---------------------

* / % operators have higher precedence than + or -.

Concatenation
-------------

+ is used to concatenate string literals. Mixing numbers with at least one string variable results in all numbers involved in the expression be treated as strings, and a string concatenation is performed.

e.g. ("hi" + 2 + score) results in a string

+= operator also can be used for string concatenation.

int b=3;
System.out.println(""+b+4); //prints 34
System.out.println("1"+ (b+4) ); //prints 17
System.out.println(b+4); //prints 7
System.out.println(b+4+"6"); //prints 76 (this is because the expression is always evaluated
                       //from left to right; so until a string variable is reached,it does numeric addition)

Increment/Decrement Operators
-----------------------------

a++ value of 'a' is used in the expression before incrementing.

++a value of 'a' is used in the expression after incrementing.

Using these operators on a final variable results in compiler error.

Conditional Operator
--------------------

It is called ternary operator. It has three operands.

It is used to evaluate boolean expressions.

Ternary operator decides which value to assign based on the condition.

x = (condition) ? a : b; //if success 'a' is assigned, otherwise 'b' is assigned.

Ternary operator can be nested.

x = (condition1) ? a : (condition2) ? b : c;

Logical Operators
------------------

They are [& | ^ ! && ||].

& | ^ operators are also used for bitwise operations.

& --> both bits should be 1
| --> any one of the bits should be 1
^ --> only one of the bits should be 1, but not both(XOR operation)

Short circuit logical operators
-------------------------------

Short circuit AND is &&.

Short circuit OR is ||.

These are named short-circuit operators because they don't waste time on evaluating all parts of the boolean expression. Once end result is known they skip the remaining expressions and return the result.

&& evaluates left side expression first and if it turns out to be 'false' it skips all right side expressions.

cond1 && cond2 && cond3 - skips evaluating cond2 and cond3 if cond1 is false.

|| evaluates left side expression first and if it is 'true' skips all right hand side expressions. Otherwise, it keeps evaluating till it gets 'true'.

These two operators work only with boolean operands.

if(5 && 1) {} will not compile.

Non short circuit logical operators
-----------------------------------

They are | and &. They are exactly same as || and && except that they are dumb. That is they evaluate all operands even though the final result is evident early.

NOT and XOR
------------

^ is exclusive OR and ! is boolean invert.

These two operate only on boolean values. (heh? ^ can do bit XOR also right?)

^ operator evaluates all operands and doesn't skip any expression. It returns true if only one operand is true out of the two.

! returns the opposite of the operand at hand.

Overloaded Operators
--------------------

+ can add numbers and concatenate strings; hence it is overloaded operator.

| & ^ are used for bitwise operation as well as logical expressions; hence they are overloaded.


Mathematical expressions are evaluated from left to right.


String[] args = new String[0]; // it is possible to create an array of 0 size; args is not null and tyring to access args[0] will result in ArrayIndexOutOfBoundsException. This is happens when no command line paramenters are passed to main method.


Reference: Kathy Sierra's SCJP Book

No comments:

Post a Comment