Program1,2,3,4
Program1,2,3,4
Program: GreetUser.java
public class GreetUser {
public static void main(String[] args) {
// Check if the user passed an argument
if (args.length > 0) {
System.out.println("Hello, " + args[0] + "!");
} else {
System.out.println("Hello, stranger!");
}
}
}
✅ How to Compile and Run (Using Command Line)
1. Open your terminal or command prompt.
2. Navigate to the directory where your file GreetUser.java is saved.
3. Compile the program:
javac GreetUser.java
Output:
Hello,Aman
Output:
Hello, stranger!
Program: 3
WAP to implement OOP concepts and basics of Java programming.
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Abstract method
abstract void displayInfo();
}
// Constructor
public Student(String name, int age, String studentId) {
super(name, age); // calling superclass constructor
this.studentId = studentId;
}
// Main class
public class OOPDemo {
public static void main(String[] args) {
// Creating object - Object Instantiation
Student s1 = new Student("Alice", 20, "S101");
Output:
Student Name: Alice
Age: 20
Student ID: S102
Concepts Used:
Concept Example Used
Class & Object Student, Person, OOPDemo
Inheritance Student extends Person
Encapsulation studentId with getters/setters
Abstraction Abstract class Person
Polymorphism displayInfo() overridden in Student
Program: 4
Create Java programs using inheritance and polymorphism.
// Main class
public class InheritancePolymorphismDemo {
public static void main(String[] args) {
// Inheritance + Polymorphism using superclass reference
Animal myAnimal; // reference of base class
myAnimal = new Dog(); // Dog object
myAnimal.makeSound(); // Outputs Dog sound
Output:
Dog says: Woof Woof!
Cat says: Meow Meow!
Cow says: Moo Moo!
Key Concepts:
Concept How It's Used
Inheritance Dog, Cat, Cow extend Animal class
Polymorphism makeSound() method is overridden in each class
Dynamic Binding Method called based on actual object type at runtime