Java Basics Notes
Basic Syntax
Program: public class ClassName { public static void main(String[] args){ } }
Print: [Link](), println(), printf().
Input: import [Link]; Scanner sc=new Scanner([Link]);
Common input: nextInt(), nextDouble(), next(), nextLine(), next().charAt(0).
Arrays
An array stores multiple values of the same data type.
Syntax:
int[] arr;
int[] arr = new int[5];
int[] arr = {1,2,3};
Access: arr[index]
Update: arr[index]=value;
Length: [Link]
2D array: int[][] arr = new int[3][3];
Example:
int[] a={10,20,30};
[Link](a[1]); //20
Operators
Arithmetic: + - * / %
Assignment: = += -= *= /= %=
Relational: == != > < >= <= (returns true/false)
Logical: && || !
Increment/Decrement: ++ --
Ternary: condition ? value1 : value2
Bitwise: & | ^ ~ << >>
Example: 5 & 3 = 1, 5 | 3 = 7, 5 ^ 3 = 6, ~5 = -6, 5<<1 =10, 20>>2=5.
Conditional Statements
if: executes when condition is true.
if-else: chooses between two blocks.
else-if ladder: checks multiple conditions.
nested if: if inside another if.
switch: selects matching case.
Example:
if(age>=18){...} else {...}
switch(day){case 1: break; default: }
Looping Statements
for: for(initialization; condition; update){}
while: while(condition){}
do-while: do{}while(condition);
break exits loop; continue skips current iteration.
Example:
for(int i=1;i<=5;i++){[Link](i);}