Wednesday, July 9, 2025

Java Programming Basics

 ✅ 1. Your First Java Program

1
2
3
4
5
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}

  • public class HelloWorld: Java code must be inside a class.

  • main(String[] args): Entry point of any Java program.

  • System.out.println(): Prints output to the console.

✅ 2. Variables and Data Types

1
2
3
4
5
int age = 25;
double price = 19.99;
char grade = 'A';
boolean isJavaFun = true;
String name = "Alice";

Type Description Example
int   Integer    5
double   Decimal number   3.14
char   Single character    'A'
boolean   True or false   true / false
String   Text (object) " Hello"

✅ 3. Operators

1
2
3
int x = 10 + 5;    // 15
int y = 10 * 2;    // 20
int z = x / 3;     // 5

  • +, -, *, /, %: Arithmetic

  • ==, !=, >, <, >=, <=: Comparison

  • &&, ||, !: Logical


✅ 4. Control Statements

if Statement

1
2
3
4
5
if (age > 18) {
    System.out.println("Adult");
} else {
    System.out.println("Minor");
}

switch Statement


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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");
}

✅ 5. Loops

for Loop

1
2
3
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}


while Loop

1
2
3
4
5
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

✅ 6. Arrays

1
2
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // 1

✅ 7. Methods (Functions)

1
2
3
4
5
6
public static int add(int a, int b) {
    return a + b;
}

// Usage:
int result = add(3, 4);  // 7

✅ 8. Classes and Objects

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Car {
    String color;

    public void drive() {
        System.out.println("Car is driving");
    }
}

// In another class or in main()
Car myCar = new Car();
myCar.color = "Red";
myCar.drive();

✅ 9. Comments

1
2
3
4
// This is a single-line comment

/* This is a
   multi-line comment */

✅ 10. Compile and Run Java

Assuming your file is HelloWorld.java:

javac HelloWorld.java   # Compiles the code

java HelloWorld         # Runs the program

No comments:

Post a Comment

Deploying a React Frontend to Railway: A Complete Guide (To-Do App)

 If you've already deployed your Java Spring Boot backend to Railway, congratulations — the hardest part is done! 🎉 Now it’s time to ...