Java Notes
Java Notes
3. Write a simple Java program to add two numbers using user input.
java
Copy code
import java.util.Scanner; // Importing Scanner class
Principles of OOP:
java
Copy code
class Person {
private String name; // Encapsulation
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
java
Copy code
class Animal {
void eat() { System.out.println("This animal eats food."); }
}
class Dog extends Animal {
void bark() { System.out.println("This dog barks."); }
}
java
Copy code
class Animal { void sound() { System.out.println("Animal makes a
sound."); } }
class Dog extends Animal { void sound() { System.out.println("Dog
barks."); } }
java
Copy code
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() { System.out.println("Drawing a circle."); }
}
5. What are the different control statements in Java? Give examples of each.
1. Conditional Statements:
o if-else: Executes code based on a condition.
java
Copy code
if (x > 0) { System.out.println("Positive"); } else {
System.out.println("Negative"); }
2. Switch Statement:
o Executes one block of code among many options.
java
Copy code
switch (day) { case 1: System.out.println("Monday"); break; }
3. Looping Statements:
o for: Iterates a block of code a fixed number of times.
java
Copy code
for (int i = 0; i < 5; i++) { System.out.println(i); }
java
Copy code
while (x > 0) { x--; }
java
Copy code
do { x--; } while (x > 0);
4. Jump Statements:
o break: Exits a loop or switch.
o continue: Skips the current iteration.
6. Explain the use of the “switch” statement in Java with a sample program.
Switch Statement: It evaluates an expression and executes the matching case block. If no
match is found, the default block is executed.
Example Program:
java
Copy code
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
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");
}
}
}
Output:
Wednesday