Fundamentals

Java Fundamentals

Variables & Data Types

1. Variables

A variable is a named memory location used to store data.

java
1int age = 25;
2String name = "Akash";
ConceptExampleMeaning
Declarationint age;Creates a variable
Initializationage = 25;Assigns a value
Declaration + Initializationint age = 25;Both together
Reassignmentage = 26;Changes the value

2. Primitive Data Types

Java has 8 primitive data types.

TypeSizeExampleDefault Value*
byte8-bitbyte x = 10;0
short16-bitshort x = 100;0
int32-bitint x = 1000;0
long64-bitlong x = 100000L;0L
float32-bitfloat x = 10.5f;0.0f
double64-bitdouble x = 10.5;0.0d
char16-bitchar c = 'A';'\u0000'
booleanJVM-dependentboolean flag = true;false

Note: Default values apply to instance/static variables, not local variables.

3. Reference Data Types

Reference variables store a reference to an object.

TypeExample
StringString name = "Akash";
Arrayint[] nums = {1, 2, 3};
ClassUser user = new User();
InterfaceList<Integer> list = new ArrayList<>();
EnumDay day = Day.MONDAY;

4. Primitive vs Reference

PrimitiveReference
Stores actual valueStores reference to an object
8 built-in typesClasses, arrays, interfaces, enums, etc.
Cannot be nullCan be null
Generally more lightweightObjects may require heap allocation
int x = 10String s = "Hello"

Operators

Operators are symbols used to perform operations on variables and values.

1. Types of Operators

CategoryOperatorsExample
Arithmetic+, -, *, /, %a + b
Relational==, !=, >, <, >=, <=a > b
Logical&&, ||, !a > 0 && b > 0
Assignment=, +=, -=, *=, /=, %=a += 5
Unary++, --, +, -, !++a
Bitwise&, |, ^, ~a & b
Shift<<, >>, >>>a << 2
Ternary?, :a > b ? a : b
instanceofinstanceofobj instanceof String

2. Arithmetic Operators

OperatorPurposeExample
+Addition5 + 2 → 7
-Subtraction5 - 2 → 3
*Multiplication5 * 2 → 10
/Division5 / 2 → 2
%Remainder5 % 2 → 1

Important: Integer division removes the decimal part.

java
1int x = 5 / 2; // 2
2double y = 5 / 2; // 2.0
3double z = 5 / 2.0; // 2.5

3. Logical Operators

OperatorMeaningExample
&&ANDa > 0 && b > 0
||ORa > 0 || b > 0
!NOT!(a > 0)

Key interview point: && and || use short-circuit evaluation.

4. Unary Operators

OperatorMeaningExample
++aIncrement, then usePre-increment
a++Use, then incrementPost-increment
--aDecrement, then usePre-decrement
a--Use, then decrementPost-decrement
!aReverses booleanLogical NOT
java
1int a = 5;
2int b = a++; // b = 5, a = 6

5. Ternary Operator

Short form of if-else.

java
1int max = a > b ? a : b;
Next TopicArrays & Strings