Lab Manual
Lab Manual
29 1. Save the above Java code in a file named68 System.out.println("Height: " + height);
30 HelloWorld.java.
69 System.out.println("Is student? " + isStudent);
31 2. Open a command prompt or terminal
70 System.out.println("Gender: " + gender);
32 window.
71 }
33 3. Navigate to the directory where
34 HelloWorld.java is saved. 72 }
35 4. Compile the program by running the 73 public class VariableInitializationExample {
36 command: javac HelloWorld.java. This will
37 generate a HelloWorld.class file. 74 public static void main(String[] args) {
38 5. Run the compiled program using the 75 // Declaring and initializing variables
39 command: java HelloWorld. You should
76 int apples = 10;
40 see the output "Hello, World!" printed to
41 the console. 77 double pricePerApple = 1.5;
1 String productName = "Apple"; 35 char grade = 'A';
2 36
3 // Displaying the values of variables 37 // Displaying the values of variables
4 System.out.println("Number of " + 38 System.out.println("Population: " +
5 productName + "s: " + apples); 39 population);
6 System.out.println("Price per " + 40 System.out.println("Temperature: " +
7 productName + ": $" + pricePerApple); 41 temperature);
8 } 42 System.out.println("Is it sunny? " + isSunny);
9 } 43 System.out.println("Grade: " + grade);
10 B. Primitive data types (int, double, boolean, char): 44 }
11 public class PrimitiveDataTypes { 45 }
12 public static void main(String[] args) { 46 C. Reference data types (String):
13 int number = 10; 47 public class ReferenceDataTypes {
14 double pi = 3.14; 48 public static void main(String[] args) {
15 boolean isJavaFun = true; 49 // String declaration and initialization
16 char grade = 'A'; 50 String greeting = "Hello, World!";
17 System.out.println("Integer: " + number); 51 System.out.println(greeting);
18 System.out.println("Double: " + pi); 52 }
19 System.out.println("Boolean: " + isJavaFun);53 }
20 System.out.println("Char: " + grade); 54 public class StringExample {
21 } 55 public static void main(String[] args) {
22 } 56 // String declaration and initialization
23 public class PrimitiveDataTypesExample { 57 String city = "New York";
24 public static void main(String[] args) { 58
25 // Integer data type 59 // Concatenating strings
26 int population = 1000000; 60 String welcomeMessage = "Welcome to ";
27 61 String fullMessage = welcomeMessage + city;
28 // Double data type 62
29 double temperature = 25.5; 63 // Displaying the strings
30 64 System.out.println("City: " + city);
31 // Boolean data type 65 System.out.println("Welcome message: " +
66 fullMessage);
32 boolean isSunny = true;
67 }
33
68 }
34 // Character data type
1 D. Type conversion and casting: 37 }
2 public class TypeConversionAndCasting { 38 }
3 public static void main(String[] args) { 39 3. Operators and Expressions:
4 // Implicit type conversion (widening 40 Arithmetic operators (+, -, *, /, %).
5 conversion)
41 public class ArithmeticOperatorsExample {
6 int numInt = 100;
42 public static void main(String[] args) {
7 long numLong = numInt;
43 int num1 = 10;
8
44 int num2 = 4;
9 // Explicit type conversion (narrowing
10 conversion) 45 // Addition
13 48 // Subtraction
20 55 // Division
27 62 }
14 49
16 boolean isGreaterOrEqual = num1 >= num2;51 boolean resultAnd = isTrue && isFalse;
19 54
24 } 59
25 } 60 // Logical NOT
36 71
1 // Complex logical expression 36 } else if (num < 0) {
2 boolean result = (num1 > num2) && (num2 37> System.out.println(num + " is negative.");
3 num3);
38 } else {
4 System.out.println("Is num1 greater than
5 num2 and num2 greater than num3? " + result);39 System.out.println(num + " is zero.");
6 40 }
15 break; 49 }
16 default: 50 }
24 } 58 do {
28 int num = 1; 62 }
29 63 }
12 scanner.close(); 45 System.out.println();
13 } 46 }
14 } 47 }
15 For loops. 48 }
18 51
// Printing numbers from 1 to 5 using for loop public static void main(String[] args) {
21 } 54 if (i == j) {
22 } 55 System.out.print("* ");
23 } 56 } else {
26 int n = 5; 59 }
28 61 }
62 }
29 for (int i = 1; i <= n; ++i) {
30 factorial *= i; 63 }
31 } 64 5. Arrays:
65 Declaring and initializing arrays.
32
33 System.out.println("Factorial of " + n + " = "66
+ public class ArrayDeclaration {
34 factorial); 67 public static void main(String[] args) {
1 // Declaring and initializing an array of 37 }
2 integers
38 }
3 int[] numbers = {1, 2, 3, 4, 5};
39
4
40 Multi-dimensional arrays.
5 // Declaring and initializing an array of
6 strings 41 public class MultiDimensionalArray {
7 String[] names = {"Alice", "Bob", "Charlie", 42 public static void main(String[] args) {
8 "David", "Emma"};
43 // Declaring and initializing a 2D array
9 }
44 int[][] matrix = {
10 }
45 {1, 2, 3},
11 46 {4, 5, 6},
12 Accessing array elements. 47 {7, 8, 9}
13 public class AccessingArrayElements { 48 };
14 public static void main(String[] args) { 49
15 int[] numbers = {10, 20, 30, 40, 50}; 50 // Accessing and printing individual elements
16 51 of the 2D array
36 } 70 }
1 35 public static int calculateSum(int a, int b, int c) {
2 public static void main(String[] args) { 36 return a + b + c;
3 // Calling the calculateSum method 37 }
4 int sum = calculateSum(5, 3); 38
5 System.out.println("Sum: " + sum); 39 public static void main(String[] args) {
6 40 // Calling the overloaded methods
7 // Calling the printGreeting method 41 int sum1 = calculateSum(5, 3);
8 printGreeting(); 42 int sum2 = calculateSum(2, 4, 6);
9 } 43
10 } 44 System.out.println("Sum 1: " + sum1);
25 59
28 62
// Method to calculate the sum of two integers int result = factorial(5);
30 return a + b; 64 }
31 } 65 }
24 60 }
29 } 63
33 class Rectangle { 67 }
30 account.deposit(1000); 66 Both Dog and Cat classes override the eat() and
67 sleep() methods from the Animal class to provide
31 account.withdraw(500); 68 specialized behavior for each type of animal.
32 System.out.println("Current balance: " + 69
33 account.getBalance());
70 // Base class
34 }
1 class Animal { 34 }
2 String name; 35
3 36 // Another derived class inheriting from Animal
4 Animal(String name) { 37 class Cat extends Animal {
5 this.name = name; 38 String color;
6 } 39
7 40 Cat(String name, String color) {
8 void eat() { 41 super(name);
9 System.out.println(name + " is eating."); 42 this.color = color;
10 } 43 }
11 44
12 void sleep() { 45 void meow() {
13 System.out.println(name + " is sleeping."); 46 System.out.println(name + " is meowing.");
14 } 47 }
15 } 48
16 49 @Override
17 // Derived class inheriting from Animal 50 void sleep() {
18 class Dog extends Animal { 51 System.out.println(name + " is sleeping quietly.");
19 String breed; 52 }
20 53 }
21 Dog(String name, String breed) { 54
22 super(name); 55 public class InheritanceExample {
23 this.breed = breed; 56 public static void main(String[] args) {
24 } 57 Dog dog = new Dog("Buddy", "Golden Retriever");
25 58 dog.eat(); // Output: Buddy is eating dog food.
26 void bark() { 59 dog.sleep(); // Output: Buddy is sleeping.
27 System.out.println(name + " is barking."); 60 dog.bark(); // Output: Buddy is barking.
28 } 61
29 62 Cat cat = new Cat("Whiskers", "White");
30 @Override 63 cat.eat(); // Output: Whiskers is eating.
31 void eat() { 64 cat.sleep(); // Output: Whiskers is sleeping quietly.
32 System.out.println(name + " is eating dog food."); 65 cat.meow(); // Output: Whiskers is meowing.
33 } 66 }
1 } 39 }
37 return salary * 0.1; // Default bonus calculation for 72 Employee partTimeEmployee = new
38 all employees 73 PartTimeEmployee("Jane Smith", 2001, 25000);
1 37 static {
2 System.out.println("Full-time employee details:"); 38 System.out.println("This is a static block.");
3 fullTimeEmployee.displayDetails(); 39 staticVar = 10;
4 System.out.println("Bonus: $" + 40 }
5 fullTimeEmployee.calculateBonus());
41
6
42 // Static nested class
7 System.out.println("\nPart-time employee details:");
43 static class StaticNestedClass {
8 partTimeEmployee.displayDetails();
44 public void display() {
9 System.out.println("Bonus: $" +
10 partTimeEmployee.calculateBonus()); 45 System.out.println("This is a method inside a static
46 nested class.");
11 }
47 }
12 }
48 }
13
49
14 Static keyword
50 public static void main(String[] args) {
15 In this example below:
51 // Calling static method directly
16 staticVar is a static variable shared among all
52 StaticExample.staticMethod();
17 instances of the class.
53
18 staticMethod() is a static method that can be
19 called without creating an instance of the class. 54 // Creating an instance of the static nested class
20 The static block initializes the static variable 55 StaticNestedClass nestedObj = new
21 staticVar. 56 StaticNestedClass();
22 StaticNestedClass is a static nested class, meaning
57 nestedObj.display();
23 it can be accessed without instantiating the outer
24 class 58 }
25 59 }
30 // Static method 64
22 55
25 } 58
26 59 car.printDetails();
28 return name; 61 }
4
41
The Rectangle, Circle, and Triangle classes extend private double radius;
5 Shape and provide their implementations of 42
6 calculateArea().
43 public Circle(double radius) {
7 We create an array of Shape objects containing
8 instances of different shapes. 44 this.radius = radius;
10 } 46 }
11 } 47
16 51 }
30 66 // Base class
34 70
new FullTimeEmployee("John Doe", "FT001", 5000), }
71 }
1 36 We then demonstrate creating objects of each
37 type and calling their respective methods.
2 // Derived class inheriting from Animal
38 // Base class Employee
3 class Dog extends Animal {
39 class Employee {
4 void bark() {
40 protected String name;
5 System.out.println("Dog is barking");
41 protected int id;
6 }
42 protected double salary;
7 }
43
8
44 public Employee(String name, int id, double salary) {
9 // Derived class inheriting from Dog
45 this.name = name;
10 class Labrador extends Dog {
46 this.id = id;
11 void color() {
47 this.salary = salary;
12 System.out.println("Labrador is golden in color");
48 }
13 }
49
14 }
50 public void displayInfo() {
15
51 System.out.println("Name: " + name);
16 public class AnimalHierarchy {
52 System.out.println("ID: " + id);
17 public static void main(String[] args) {
53 System.out.println("Salary: $" + salary);
18 Labrador labrador = new Labrador();
54 }
19 labrador.eat(); // Inherited from Animal class
55 }
20 labrador.bark(); // Inherited from Dog class
56
21 labrador.color(); // Specific to Labrador class
57 // Derived class Developer
22 }
58 class Developer extends Employee {
23 }
59 private String programmingLanguage;
24 In this example:
60
25 We have an Employee base class with common
26 attributes like name, ID, and salary. 61 public Developer(String name, int id, double salary,
62 String programmingLanguage) {
27 The Developer class extends Employee and adds a
28 specific attribute programmingLanguage and 63 super(name, id, salary);
29 behavior writeCode(). 64 this.programmingLanguage =
30 The Manager class also extends Employee and 65 programmingLanguage;
31 adds a specific attribute department and behavior
66 }
32 assignTasks().
67
33 The Executive class further extends Manager and
34 adds a specific attribute companyCar and 68 public void writeCode() {
35 behavior travelInCompanyCar().
69 System.out.println(name + " is writing code in " +
70 programmingLanguage);
1 } 36 public class CompanyHierarchy {
2 } 37 public static void main(String[] args) {
3 38 Developer developer = new Developer("John Doe",
39 1001, 80000, "Java");
4 // Derived class Manager
40 developer.displayInfo();
5 class Manager extends Employee {
41 developer.writeCode();
6 private String department;
42 System.out.println();
7
43
8 public Manager(String name, int id, double salary,
9 String department) { 44 Manager manager = new Manager("Alice Smith",
45 2001, 100000, "Software Development");
10 super(name, id, salary);
46 manager.displayInfo();
11 this.department = department;
47 manager.assignTasks();
12 }
48 System.out.println();
13
49
14 public void assignTasks() {
50 Executive executive = new Executive("Bob Johnson",
15 System.out.println(name + " is assigning tasks in " +51 3001, 150000, "Management", "Tesla Model S");
16 department);
52 executive.displayInfo();
17 }
53 executive.assignTasks();
18 }
54 executive.travelInCompanyCar();
19
55 }
20 // Derived class Executive
56 }
21 class Executive extends Manager {
22 private String companyCar; 57
23 58 Multiple inheritance
24 public Executive(String name, int id, double salary, 59 In this example, we have three interfaces: Flyable,
25 String department, String companyCar) { 60 Swimmable, and two classes: Bird and Fish that
61 implement Flyable and Swimmable respectively. The Duck
26 super(name, id, salary, department); 62 class implements both Flyable and Swimmable, allowing
63 instances of Duck to have both flying and swimming
27 this.companyCar = companyCar;
64 behavior.
28 }
65 // Interface for flying behavior
29
66 interface Flyable {
30 public void travelInCompanyCar() {
67 void fly();
31 System.out.println(name + " is traveling in the
68 }
32 company car");
69
33 }
70 // Interface for swimming behavior
34 }
71 interface Swimmable {
35
1 void swim(); 34 public static void main(String[] args) {
2 } 35 Bird bird = new Bird();
3 36 bird.fly(); // Output: Bird is flying
4 // Class representing a bird that can fly 37
5 class Bird implements Flyable { 38 Fish fish = new Fish();
6 @Override 39 fish.swim(); // Output: Fish is swimming
7 public void fly() { 40
8 System.out.println("Bird is flying"); 41 Duck duck = new Duck();
9 } 42 duck.fly(); // Output: Duck is flying
10 } 43 duck.swim(); // Output: Duck is swimming
11 44 }
12 // Class representing a fish that can swim 45 }
13 class Fish implements Swimmable { 46 In this example, we have interfaces representing different
14 @Override 47 roles within a school system such as Student, Teacher,
48 Administrator, and Parent. Each interface extends the
15 public void swim() { 49 Person interface, which defines the common behavior of
50 having a name. The classes SchoolStudent, SchoolTeacher,
16 System.out.println("Fish is swimming");
51 SchoolAdministrator, and SchoolParent then implement
17 } 52 the respective interfaces, showcasing the multiple
53 inheritance aspect in the context of a school system.
18 }
54 // Interface for a person with a name
19
55 interface Person {
20 // Class representing a duck that can both fly and swim
56 String getName();
21 class Duck implements Flyable, Swimmable {
57 }
22 @Override
58
23 public void fly() {
59 // Interface for a person who is a student
24 System.out.println("Duck is flying");
60 interface Student extends Person {
25 }
61 void enroll();
26
62 void study();
27 @Override
63 }
28 public void swim() {
64
29 System.out.println("Duck is swimming");
65 // Interface for a person who is a teacher
30 }
66 interface Teacher extends Person {
31 }
67 void teach();
32
68 }
33 public class Main {
69
1 // Interface for a person who is an administrator 35
2 interface Administrator extends Person { 36 // Class representing a teacher
3 void manage(); 37 class SchoolTeacher implements Teacher {
4 } 38 private String name;
5 39
6 // Interface for a person who is a parent 40 public SchoolTeacher(String name) {
7 interface Parent extends Person { 41 this.name = name;
8 void attendMeeting(); 42 }
9 } 43
10 44 @Override
11 // Class representing a student 45 public String getName() {
12 class SchoolStudent implements Student { 46 return name;
13 private String name; 47 }
14 48
15 public SchoolStudent(String name) { 49 @Override
16 this.name = name; 50 public void teach() {
17 } 51 System.out.println(name + " is teaching.");
18 52 }
19 @Override 53 }
20 public String getName() { 54
21 return name; 55 // Class representing a school administrator
22 } 56 class SchoolAdministrator implements Administrator {
23 57 private String name;
24 @Override 58
25 public void enroll() { 59 public SchoolAdministrator(String name) {
26 System.out.println(name + " has been enrolled as a60 this.name = name;
27 student.");
61 }
28 }
62
29
63 @Override
30 @Override
64 public String getName() {
31 public void study() {
65 return name;
32 System.out.println(name + " is studying.");
66 }
33 }
67
34 }
1 @Override 36
2 public void manage() { 37 student.enroll();
3 System.out.println(name + " is managing."); 38 student.study();
4 } 39
5 } 40 teacher.teach();
6 41
7 // Class representing a parent 42 administrator.manage();
8 class SchoolParent implements Parent { 43
9 private String name; 44 parent.attendMeeting();
10 45 }
11 public SchoolParent(String name) { 46 }
12 this.name = name; 47
13 } 48
14 49 In this example, we have three interfaces: Chargeable,
15 @Override 50 Connectable, and Playable, and a class Smartphone that
51 implements all three interfaces. This allows the
16 public String getName() { 52 Smartphone class to exhibit behavior related to charging,
53 connecting to the internet, and playing media, similar to
17 return name;
54 multiple inheritance.
18 }
55 // Interface for electronic devices that can be charged
19
56 interface Chargeable {
20 @Override
57 void charge();
21 public void attendMeeting() {
58 }
22 System.out.println(name + " is attending a parent-
23 teacher meeting."); 59
14 } 49
5 43 interface Shippable {
electronicProduct.leaveReview(); // Output: Review
6 for electronic product left 44 void ship();
7 electronicProduct.ship(); // Output: Electronic 45 }
8 product shipped
46
9
47 // Interface for clothing products that can be tried on
10 // Example with clothing product
48 interface TryOnable {
11 ClothingProduct clothingProduct = new
12 ClothingProduct(); 49 void tryOn();
10 } 45
5 43