Java Course Basic Knowlwdge
Java Course Basic Knowlwdge
// Lesson 3: Operators
public class Lesson3 {
public static void main(String[] args) {
int x = 10;
int y = 5;
// Arithmetic Operators
System.out.println(x + y); // 15
System.out.println(x - y); // 5
System.out.println(x * y); // 50
System.out.println(x / y); // 2
System.out.println(x % y); // 0
// Assignment Operators
int a = 10;
a += 5; // a = a + 5;
a -= 3; // a = a - 3;
a *= 2; // a = a * 2;
a /= 4; // a = a / 4;
a %= 3; // a = a % 3;
// Comparison Operators
System.out.println(x == y); // false
System.out.println(x != y); // true
System.out.println(x > y); // true
System.out.println(x < y); // false
System.out.println(x >= y); // true
System.out.println(x <= y); // false
}
}
// if-else statement
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
// switch statement
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
// for loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// while loop
int j = 0;
while (j < 5) {
System.out.println(j);
j++;
}
}
}
// Lesson 5: Arrays
public class Lesson5 {
public static void main(String[] args) {
// One-dimensional array
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[2]); // 3
// Two-dimensional array
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println(matrix[1][2]); // 6
}
}
// Lesson 6: Methods
public class Lesson6 {
public static void main(String[] args) {
int result = add(3, 4);
System.out.println(result); // 7
class Person {
String name;
int age;
void greet() {
System.out.println("Hello, my name is " + name + " and I am " + age + "
years old.");
}
}
class Car {
String brand;
String model;
void start() {
System.out.println("The " + brand + " " + model + " is starting.");
}
void stop() {
System.out.println("The " + brand + " " + model + " is stopping.");
}
}
// Lesson 8: Inheritance
public class Lesson8 {
public static void main(String[] args) {
// Creating an object of the Student class
Student student = new Student();
student.name = "Alice";
student.age = 20;
student.studentId = "12345";
student.greet();
student.study();
}
}
void study() {
System.out.println("The student is studying.");
}
}
// Lesson 9: Polymorphism
public class Lesson9 {
public static void main(String[] args) {
Animal animal1 = new Animal();
Animal animal2 = new Dog();
Animal animal3 = new Cat();
animal1.makeSound();
animal2.makeSound();
animal3.makeSound();
}
}
class Animal {
void makeSound() {
System.out.println("The animal makes a sound.");
}
}