Thursday 18 October 2012

Difference between C++ and Java

This is the 3rd post in "Difference between C++ and Java" series.Here we are going to continue with our discussion on differences between C++ and Java.
1. Unsigned Right Shift Operator
Statement 
There is an additional shift operator in Java called Unsigned Shift Operator. 
We all know that there are shift operators available in almost every language to shift the bits of integer operands. In C++, we have got two Shift operators namely Right Shift Operator(>>) and Left Shift Operator(<<). These two operators are also present in Java but there is an additional shift operator called Unsigned Right Shift operator. This fills '0's on the left of the argument irrespective of its sign. The no. of '0's filled are specified by second operand.
We will make it more clear with the help of an example.
  • Java
int i=-1;
System.out.println(Integer.toBinaryString(i));
System.out.println("applying unsigned right shift by 31");
i=i>>>31;
System.out.println(Integer.toBinaryString(i)); 
Output is 
11111111111111111111111111111111
applying unsigned right shift by 31
1
Here in above code snippet we have illustrated the use of Unsigned Shift Operator in Java. Initially, the value of  'i' variable is -1 which is represented by a sequence of 32 1's in binary. Then we apply the 'Unsigned Right Shift Operator(>>>)' and specify the no. of bits to be shifted as 31. As a result, 31 '0's are inserted at the left of the operand 'i' and we get 1 as our output.
  2. Operators 
There are a lot of common operators in C++ and Java. These operators have same comparative precedence in both the languages. These operators include increment/decrement operators, arithmetic operators, shift operators, relational operators, equality operators, bit-wise operators, logical operators, conditional operator(ternary operator), assignment operators.
In C++, there are scope resolution operator(::), pointer operator(->), sizeof operator, pointer to member operator(.* and ->*), comma operator(,) which are not present in Java.
In Java, there is a instanceof operator which is not there in C++. This operator returns a boolean value signifying whether the second argument is reference variable to first operand.
Since there is no use of pointers in Java, sizeof operator has no significance and is not used.
Thanks all for your time. We will continue with 'Difference between C++ and Java' series in next post. Any queries and suggestions are invited in comments.

No comments:

Post a Comment

Java vs C++

THis is a basic blog that differentiates features of two of the widely used languages C++ and Java.