Java Type Casting
Type casting is when you assign a value of one primitive data type to another
type.
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger
type size
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) - converting a larger type to a smaller
size type
double -> float -> long -> int -> char -> short -> byte
Widening Casting
Widening casting is done automatically when passing a smaller size type to a
larger size type:
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
[Link](myInt); // Outputs 9
[Link](myDouble); // Outputs 9.0
Narrowing Casting
Narrowing casting must be done manually by placing the type in
parentheses () in front of the value:
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
[Link](myDouble); // Outputs 9.78
[Link](myInt); // Outputs 9
Java Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
int x = 100 + 50;
Java divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
int x = 10;
x += 5;
Comparison Operators
Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make
decisions.
int x = 5;
int y = 3;
[Link](x > y);
Logical Operators
You can also test for true or false values with logical operators.
x < 5 && x < 10