Core Java

OCA Java 8 Preparation : Operators

Java Operators is one of the topic in which Java OCA aspirants score comparatively a lot lower than the other sections of the test. In this post, we’ll cover all the must-know points about Java Operators for your OCA exam.

Now pass your Java OCA Exam with flying colours!

Operator Precedence & Associativity :

Precedence rules are important when trying to evaluate an expression. It helps to determine which operator to be applied first if we have two operators with different precedences.

Associativity rule comes into picture when we need to determine which operator to apply first when having two operators with same precedence.

DescriptionExample
Method invocation,Array Element access. , [index]
Unary postfix operatorselement++ , element--
Unary prefix operators~ , ! , + , - , ++element, --element
new operator and type castingnew , (type)
Multiplicative group* , /, %
Additive Group+ , -
Shift operators<< , >> , >>>
Relational group< , <= , > , >= , instanceof
Equality Operators == , !=
Bitwise AND&
Bitwise XOR^
Bitwise OR|
Conditional AND&&
Conditional OR||
Ternary operator ? :
Assignment group = , += , -= , *= , /= , %=
Table : Java Operator Precedence

In the above table we have listed the operator precedences in decreasing order(top to bottom).

We can also choose to use parentheses to change the default evaluation order of the operands.

Increment & Decrement Operators :

Unary operators ++ and — can be used in both prefix and postfix notation. They are used to increment and decrement the value of the operand by 1 respectively.

When used within an expression, using prefix/postfix notations of these unary operators can result in producing different results.

Prefix ( ++a , –a ) : First increment/decrement the value and then return the computed value.

Postfix( a++ , a– ) : First return the value of ‘a’ as an output and then increment/decrement its value.

int a = 5;
int result = a++ + --a + ++a; // 5 + (6-1) + 6 = 16
System.out.println(result + ":" + a); // result = 16, a = 6

a = 5; // re-initialized
result = ++a + a-- + a++; //  6 + 6 + 5 = 17
System.out.println(result + ":" + a); // result = 17, a = 6

Be wary of this while trying to answer a question in your OCA exam. There are few more important points to remember :

  1. Any attempt to use ++ or — operators on final variables will fail to compile.
  2. We are not allowed to use ++ or — operators with literals values i.e. ++3 or – -3 will fail to compile.

Relational Operators :

Relational Operators : < , > ,<=  , >=

These are binary operators and they can operate only on numeric operands. Their evaluation result in a boolean output. So you can’t assign the result produced to any type of variable other than boolean. Please look out for such cases in the exam.

Logical Operators :

Logical AND ( && ) : returns true if and only if both the operands evaluate to true.

Logical OR ( || ) : returns true if any one of the operands evaluate to true.

Logical NOT ( ! ) : Negates the boolean value. Returns true if the value was false and vice-versa.

&& and || are known as short-circuit operators due to the below behaviour.

Short Circuit && : If the first operand returns false, the second operand is never evaluated and false is returned as an output.

Short Circuit || : If the first operand evaluates to true, the second operand is not evaluated and true is returned as an output.

int a = 5;
System.out.println(a < 10 || a++ > 2); //true
System.out.println(a); //5

System.out.println(a > 10 && ++a > 1); // false
System.out.println(a); // 5

Assignment Operators and Type Conversion :

When using assignment operators on operands of different types, the rules of implicit and explicit type conversion are the ones to live-by.

  • Implicit widening conversion is applied whenever permissible. A widening primitive conversion can also result in loss of precision. For example, loss of precision might occur when trying to assign a long value(a really large value) to a float variable.Java Primitives Widening ConversionsWith reference of the above diagram, we now know that an int value can be automatically widened to fit into a float variable and likewise.
    //Widening Primitives
    long a = 10; //int -> long widening
    double d = a; // long -> float widening
    double d2 = 12f; // float -> double widening
    byte b = (byte)4; 
    short s = b;// byte-> short widening
    

    However, please note that in context of arithmetic operators, all byte, short and char values are automatically widened to int type.

  • Implicit narrowing of primitives is also possible when performing assignments, considering all the below mentioned conditions are fulfilled :
    1. The source is a constant expression of either byte, short, char or int type.
    2. The target type is either byte, short or char type.
    3. The value of the source is in the range of target type(Remember, the value of source is available at compile time as it is a constant expression).
      short var1 = 10; //implicit narrowing int ->char
      final char var2 = 'a'; //constant expression
      final char var3; //not a constant expression
      var3 = 'a'; 
      byte var4 = 5; //implicit narrowing int -> byte
      byte var5 = 6;//implicit narrowing int -> byte
      byte var6 = var4 + var5; //fails to compile as var4 and var5 are type casted to int
      
      final byte var7 = 5;// constant expression
      final byte var8 = 6; //constant expression
      byte var9 = var7 + var8; // compiles fine, type casted to byte this time

      A constant expression can be thought of as any expression the value of which is known at compile-time.

  • Explicit type-casting can be done to perform explicit narrowing wherever the rules of implicit narrowing doesn’t holds true, provided the data types are compatible.
     byte var6 = (byte)(var4 + var5); //explicit narrowing to byte
    // the below code will fail to compile
    var6 = (byte) var4 + (byte) var5;

Conclusion :

In this post, we covered the usage of different Java Operators which are important from OCA Exam perspective. We looked at increment and decrement operators and how their prefix and postfix notation usage within an expression might lead to different results.

We learnt the concept of short-circuit operators and their usage in expression evaluation.

We also covered the narrowing and widening concepts for Java Primitives. We now know that when used in the context of an arithmetic expression, byte, short and char types are all implicitly widened to an int type.

If you wish to learn more about Java Operators, refer the Oracle documentation here.

If you feel the need, do check out our blog post on Java Data Types Refresher for OCA Preparation here.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *