Java - Operator Assignment Operator =

What is Assignment Operator?

An assignment operator = assigns a value to a variable.

It takes two operands. The value of the right-hand operand is assigned to the left-hand operand.

The left-hand operand must be a variable.

For example,

  
int num; 
num = 2; 

Demo

public class Main {
  public static void main(String[] args) {
    int num; /*from  w  w w .j a  v  a2 s. co  m*/
    num = 2; 

    System.out.println(num);
  }
}

Result

Auto cast assignment

The value of type byte, short, and char are assignment compatible to int data type.

  
byte b = 5; 
char c = 'a'; 
short s = -2; 
int i = 10; 
i = b; // Ok. byte b is assignment compatible to int i 
i = c; // Ok. char c is assignment compatible to int i 
i = s; // Ok. short s is assignment compatible to int i 

Demo

public class Main {
  public static void main(String[] args) {
    byte b = 5; /*  w  w  w  .ja v a 2 s.  c  o  m*/
    char c = 'a'; 
    short s = -2; 
    int i = 10; 
    i = b; // Ok. byte b is assignment compatible to int i 
    System.out.println(i);
    i = c; // Ok. char c is assignment compatible to int i
    System.out.println(i);
    i = s; // Ok. short s is assignment compatible to int i 
    System.out.println(i);
  }
}

Result

Cast Assignment

long to int and float to int assignments are not compatible and need casting.

long big = 555L; 
float f = 1.19F; 
int i = 15; 
i = big; // A compile-time error. long to int, assignment incompatible 
i = f;   // A compile-time error. float to int, assignment incompatible 
i = (int)big; // Ok 
i = (int)f;   // Ok 

Demo

public class Main {
  public static void main(String[] args) {
    long big = 555L; 
    float f = 1.19F; 
    int i = 15; /*from   w  w w. j a  va  2  s . c  o  m*/
    //i = big; // A compile-time error. long to int, assignment incompatible 
    //i = f;   // A compile-time error. float to int, assignment incompatible 
    i = (int)big; // Ok
    System.out.println(i);
    i = (int)f;   // Ok 
    System.out.println(i);
  }
}

Result