📚 Java Basics – Full Notes with Explanation and Code
1. Hello World Program
This is the most basic program in Java. It prints a line of text on the console.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
- public class HelloWorld
: Declares a class named HelloWorld.
- public static void main(String[] args)
: Main method – the entry point of any Java application.
- System.out.println(...)
: Prints output to the console.
2. Data Types in Java
Java is a statically-typed language, meaning variables must be declared with a data type.
int num = 10;
float price = 5.99f;
char grade = 'A';
boolean isJavaFun = true;
String name = "Gaurav";
3. Variables and Constants
- Variable: A container to store data.
- Constant: A variable whose value cannot be changed (declared with final
keyword).
int age = 25;
final double PI = 3.14159;
4. Operators
Java supports arithmetic, relational, logical, and assignment operators.
int a = 10, b = 5;
System.out.println(a + b); // 15
System.out.println(a * b); // 50
System.out.println(a > b); // true
System.out.println(a == 10 && b == 5); // true
5. Conditional Statements
if-else
Checks a condition and executes code blocks based on whether it's true or false.
int age = 18;
if (age >= 18) {
System.out.println("Adult");
}else if (age >= 1){
System.out.println("Minor");
}else {
System.out.println("Not Valid");
}
switch
Used instead of multiple if-else
when checking for fixed values.
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Other Day");
}
6. Loops
for loop
Use when number of iterations is known.
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
while loop
Use when number of iterations is unknown.
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
do-while loop
Use when you want the loop to run at least once.
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
7. Arrays
Used to store multiple values in a single variable. Arrays are zero-indexed.
int[] marks = {90, 80, 70};
System.out.println(marks[0]); // Output: 90
8. Methods (Functions)
A method is a block of code that performs a specific task.
public class MyClass {
public static void greet() {
System.out.println("Hello from method!");
}
public static void main(String[] args) {
greet(); // Call the method
}
}
Comments
Post a Comment