== operator java code example

Example 1: java == vs equals

In general both equals() and == operator in Java are used to compare 
objects to check equality but here are some of the differences between the two:

1) .equals() and == is that one is a method and other is operator.
2) We can use == operator for reference comparison (address comparison) 
and .equals() method for content comparison. 
 -> == checks if both objects point to the same memory location 
 -> .equals() evaluates to the comparison of values in the objects.
3) If a class does not override the equals method, then by default it 
uses equals(Object o) method of the closest parent class 
that has overridden this method.

// Java program to understand  
// the concept of == operator 
public class Test { 
    public static void main(String[] args) 
    { 
        String s1 = new String("HELLO"); 
        String s2 = new String("HELLO"); 
        System.out.println(s1 == s2); 
        System.out.println(s1.equals(s2)); 
    } 
} 
Output:
false
true
  
Explanation: Here we are creating two (String) objects namely s1 and s2.
Both s1 and s2 refers to different objects.
 -> When we use == operator for s1 and s2 comparison then the result is false 
 as both have different addresses in memory.
 -> Using equals, the result is true because its only comparing the 
 values given in s1 and s2.

Example 2: Operators in java

// example on ternary operator in java
public class TernaryOperatorDemo
{
   public static void main(String[] args)
   {
      int a = 50, b = 500, bigger;
      System.out.println("First number: " + a);
      System.out.println("Second number: " + b);
      bigger = (a > b) ? a : b;
      System.out.println("Bigger number is = " + bigger);
   }
}

Example 3: >> and >>> operators in java

>> is a right shift operator shifts all of the bits in a value to the 
right to a specified number of times.
int a =15;
a= a >> 3;
The above line of code moves 15 three characters right.

>>> is an unsigned shift operator used to shift right. The places which 
were vacated by shift are filled with zeroes

Example 4: Operators in java

// java unary (~) operator
public class JavaUnaryOperator
{
   public static void main(String[] args)
   {
      int a = 8, b = -4;
      System.out.println("a = " + a);
      System.out.println("b = " + b);
      System.out.println(a + " java bitwise complement is = " + ~a);
      System.out.println(b + " java bitwise complement ia = " + ~b);
   }
}

Example 5: Operators in java

// java unary decrement (–) operator
public class JavaUnaryOperator
{
   public static void main(String[] args)
   {
      int a = 23;
      // 23 gets printed and decremented to 22
      System.out.println("Java post-decrement = " + a--);
      System.out.println("a = " + a);
      // a value was 22, decremented to 21
      System.out.println("Java pre-decrement = " + --a);
   }
}