Skip to main content

Types & Operators

Types

In Built Types

int, long, float, double, char, boolean

  • Decimal point number is double by default. To force creation of float, use the f sign

float a = 10.3f

  • Whole numbers are int by default. To force creation of long, use the L or l sign

long d = 100000L (or) long d = 100000l

Custom Types

To create our own data type, we need to create Class & Object

Arithmetic Operators

Plus (+) Operator

  • Can perform append & mathematical addition based on the input
String a = "Mr.";
String b = "Vicky";
a+b -> returns String -> "Mr.Vicky"
String a = "Mr.";
int b = 10;
a+b -> returns String -> "Mr.10"
String a = "Mr.";
float b = 10.4f;
a+b -> returns String -> "Mr.10.4"
int a = 10;
int b = 20;
a+b -> returns int -> 30
float a = 10.4f;
float b = 3.14f;
a+b -> returns float -> 13.54
int a = 10;
float b = 10.4;
a+b -> returns float -> 20.4

Multiplication (*) Operator

Does mathematical multiplication operation.

If both operands are int, whole number multiplication is done.

If one or more operands is float/double/long, the other operand will be upcasted & then multiplication will happen

Division (/) Operator

If both operands are int, operator will perform whole number division & return the Quotient part

E.g. 10/3 will return 3

If either of the operands are float/double, the other operand will be upcasted & then division will happen

E.g. 10.0/3 will return 3.3333333333333335

Remainder (%) Operator

If both operands are int, operator will perform whole number division & return the Remainder part

E.g. 10%3 will return 1

If either of the operands are float/double, the other operand will be upcasted & then division will happen

E.g. 10.0%3 will return 1.0

Assignment Operator

  • Least precedence operator
  • Assign value from right to left

Ternary Operator

Conditional operator (?:) is also called the ternary operator in Java. Since its accepting three operands, it’s called ternary.

Its the shorthand for if-else statement.

If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result.

Ternary Operator
String state = "Tamilnadu";
String data = state.contains("A") ? "state contains A" : "state not contain A";

In the above statement, state.contains("A") before ? is the condition.

If the condition is true, then String data will be stored with "state contains A" message (first value). If the condition is false, String data will contain "state doesn’t contains A message (second value)​.

Operator Precendence

() -> Brackets will take highest precendence

/ * % -> Equal Precedence

+ - -> Equal Precedence