✅ 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.
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
Loop1 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