0% found this document useful (0 votes)
2 views

Lab Manual

The document serves as an OOP Lab Manual introducing Java programming, covering topics such as setting up the development environment, writing and running a basic 'Hello, World!' program, and understanding data types and variables. It includes examples of primitive and reference data types, type conversion, operators, expressions, and control flow statements like if-else. The content is structured to guide beginners through fundamental Java concepts and syntax.

Uploaded by

semagn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab Manual

The document serves as an OOP Lab Manual introducing Java programming, covering topics such as setting up the development environment, writing and running a basic 'Hello, World!' program, and understanding data types and variables. It includes examples of primitive and reference data types, type conversion, operators, expressions, and control flow statements like if-else. The content is structured to guide beginners through fundamental Java concepts and syntax.

Uploaded by

semagn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

1 OOP Lab Manual 42 C.

Introduction to Java syntax and basic concepts:


2 1. Introduction to Java Programming: 43 The provided "Hello, World!" program demonstrates some
44 basic Java syntax and concepts:
3  Setting up the development environment (IDE
4 installation). 45 1. public class HelloWorld: Declares a class
46 named HelloWorld.
5  Writing and running the first "Hello, World!"
6 program. 47 2. public static void main(String[] args):
48 Declares the main method, which is the
7  Introduction to Java syntax and basic concepts.
49 entry point of the Java program.
8 A. Setting up the development environment (IDE
50 3. System.out.println("Hello, World!");:
9 installation):
51 Prints "Hello, World!" to the console using
10 This task typically involves installing an Integrated 52 the println method of the System.out
11 Development Environment (IDE) such as IntelliJ IDEA, 53 object.
12 Eclipse, or NetBeans. Here's a simple Java program that
54
13 demonstrates how to output "Hello, World!" to the
14 console: 55 2. Data Types and Variables:
15 public class HelloWorld { 56 A. Declaring and initializing variables:
16 public static void main(String[] args) { 57 public class DataTypesAndVariables {
17 System.out.println("Hello, World!"); 58 public static void main(String[] args) {
18 } 59 // Declaring and initializing variables
19 } 60 int age = 25;
20 Save to grepper 61 double height = 5.8;
21 B. Writing and running the first "Hello, World!" 62 boolean isStudent = true;
22 program:
63 char gender = 'M';
23 You can write the above Java code in any text editor and
24 save it with the ".java" extension. Then, compile and run 64 String name = "John Doe";
25 the program using the Java Development Kit (JDK) 65 // Displaying the values of variables
26 command-line tools.
66 System.out.println("Name: " + name);
27 Here are the steps to compile and run the program using
28 command-line tools: 67 System.out.println("Age: " + age);

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

11 double numDouble = 3.14; 46 int sum = num1 + num2;

12 int numIntAgain = (int) numDouble; 47 System.out.println("Sum: " + sum);

13 48 // Subtraction

14 System.out.println("Long value: " + 49 int difference = num1 - num2;


15 numLong); 50 System.out.println("Difference: " +
16 System.out.println("Int value: " + 51 difference);
17 numIntAgain); 52 // Multiplication
18 } 53 int product = num1 * num2;
19 } 54 System.out.println("Product: " + product);

20 55 // Division

21 public class TypeConversionExample { 56 int quotient = num1 / num2;


22 public static void main(String[] args) { 57 System.out.println("Quotient: " + quotient);

23 // Implicit type conversion (widening 58 // Modulus


24 conversion)
59 int remainder = num1 % num2;
25 int numberOfStudents = 30;
60 System.out.println("Remainder: " +
26 long totalStudents = numberOfStudents; 61 remainder);

27 62 }

28 // Explicit type conversion (narrowing 63 }


29 conversion)
64 public class ArithmeticOperatorsExample {
30 double pi = 3.14159;
65 public static void main(String[] args) {
31 int approxPi = (int) pi;
66 double num1 = 15.5;
32
67 double num2 = 4.3;
33 System.out.println("Total students: " +
34 totalStudents); 68 // Division with double operands

35 System.out.println("Approximation of Pi: " +69 double quotient = num1 / num2;


36 approxPi); 70 System.out.println("Quotient: " + quotient);
1 // Modulus with double operands 37 System.out.println("Result after /= operation:
38 " + result);
2 double remainder = num1 % num2;
39 }
3 System.out.println("Remainder: " +
4 remainder); 40 }
5 // Using Math.pow() for exponentiation 41 public class AssignmentOperatorsExample {
6 double power = Math.pow(num1, 2); 42 public static void main(String[] args) {
7 System.out.println("Power of num1: " + 43 int num = 10;
8 power);
44
9 }
45 // Compound assignment with post-
10 } 46 increment
11  Assignment operators (=, +=, -=, *=, /=). 47 int result = num++;
12 public class AssignmentOperatorsExample { 48 System.out.println("Result after post-
13 public static void main(String[] args) { 49 increment: " + result);

14 int num = 10; 50 System.out.println("Value of num after post-


51 increment: " + num);
15
52
16 // Simple assignment
53 // Compound assignment with pre-decrement
17 int result = num;
54 result = --num;
18 System.out.println("Result: " + result);
55 System.out.println("Result after pre-
19 56 decrement: " + result);
20 // Compound assignment 57 System.out.println("Value of num after pre-
58 decrement: " + num);
21 result += 5; // Equivalent to: result = result +
22 5; 59 }
23 System.out.println("Result after += operation:
60 }
24 " + result);
61  Comparison operators (==, !=, >, <, >=, <=).
25
62 public class ComparisonOperatorsExample {
26 result -= 3; // Equivalent to: result = result - 3;
63 public static void main(String[] args) {
27 System.out.println("Result after -= operation:
28 " + result); 64 int num1 = 10;

29 65 int num2 = 20;

30 result *= 2; // Equivalent to: result = result *66


31 2; 67 // Equal to
32 System.out.println("Result after *= operation:
68 boolean isEqual = num1 == num2;
33 " + result);
69 System.out.println("Is num1 equal to num2? "
34 70 + isEqual);
35 result /= 4; // Equivalent to: result = result /71
36 4;
72 // Not equal to
1 boolean isNotEqual = num1 != num2; 37 // Comparing string values
2 System.out.println("Is num1 not equal to 38 boolean isEqualValue = str1.equals(str3);
3 num2? " + isNotEqual);
39 System.out.println("Are str1 and str3 values
4 40 equal? " + isEqualValue);
5 // Greater than 41 }
6 boolean isGreater = num1 > num2; 42 }
7 System.out.println("Is num1 greater than 43
8 num2? " + isGreater);
44  Logical operators (&&, ||, !).
9
45 public class LogicalOperatorsExample {
10 // Less than
46 public static void main(String[] args) {
11 boolean isLess = num1 < num2;
47 boolean isTrue = true;
12 System.out.println("Is num1 less than num2?
13 " + isLess); 48 boolean isFalse = false;

14 49

15 // Greater than or equal to 50 // Logical AND

16 boolean isGreaterOrEqual = num1 >= num2;51 boolean resultAnd = isTrue && isFalse;

17 System.out.println("Is num1 greater than or52 System.out.println("Result of logical AND: " +


18 equal to num2? " + isGreaterOrEqual); 53 resultAnd);

19 54

20 // Less than or equal to 55 // Logical OR

21 boolean isLessOrEqual = num1 <= num2; 56 boolean resultOr = isTrue || isFalse;

22 System.out.println("Is num1 less than or 57 System.out.println("Result of logical OR: " +


23 equal to num2? " + isLessOrEqual); 58 resultOr);

24 } 59

25 } 60 // Logical NOT

26 public class ComparisonOperatorsExample { 61 boolean resultNot = !isTrue;

27 public static void main(String[] args) { 62 System.out.println("Result of logical NOT: " +


63 resultNot);
28 String str1 = "Hello";
64 }
29 String str2 = "Hello";
65 }
30 String str3 = new String("Hello");
66 public class LogicalOperatorsExample {
31
67 public static void main(String[] args) {
32 // Comparing string references
68 int num1 = 10;
33 boolean isEqualRef = str1 == str2;
69 int num2 = 20;
34 System.out.println("Are str1 and str2
35 references equal? " + isEqualRef); 70 int num3 = 5;

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 }

7 // Using logical operators in control flow 41 }

8 if ((num1 > num2) || (num3 > num2)) { 42 }

9 System.out.println("At least one condition43 import java.util.Scanner;


10 is true.");
44
11 } else {
45 public class IfElseExample {
12 System.out.println("Both conditions are
46 public static void main(String[] args) {
13 false.");
47 Scanner scanner = new Scanner(System.in);
14 }
48
15 }
49 System.out.print("Enter your age: ");
16 }
50 int age = scanner.nextInt();
17
51
18
52 if (age >= 18) {
19 4. Control Flow Statements:
53 System.out.println("You are eligible to
20  If-else statements. 54 vote.");
21 public class IfElseExample { 55 } else {
22 public static void main(String[] args) { 56 System.out.println("You are not eligible to
23 int num = 10; 57 vote.");

24 58 int yearsToVote = 18 - age;

25 // Checking if the number is even or odd 59 System.out.println("You can vote in " +


60 yearsToVote + " year(s).");
26 if (num % 2 == 0) {
61 }
27 System.out.println(num + " is even.");
62
28 } else {
63 scanner.close();
29 System.out.println(num + " is odd.");
64 }
30 }
65 }
31
66  Switch statements.
32 // Checking if the number is positive,
33 negative, or zero 67 public class SwitchExample {

34 if (num > 0) { 68 public static void main(String[] args) {

35 System.out.println(num + " is positive."); 69 int dayOfWeek = 3;


1 String dayName; 35 break;
2 36 case '-':
3 switch (dayOfWeek) { 37 result = num1 - num2;
4 case 1: 38 break;
5 dayName = "Monday"; 39 case '*':
6 break; 40 result = num1 * num2;
7 case 2: 41 break;
8 dayName = "Tuesday"; 42 case '/':
9 break; 43 result = num1 / num2;
10 case 3: 44 break;
11 dayName = "Wednesday"; 45 default:
12 break; 46 System.out.println("Invalid operator!");
13 case 4: 47 return;
14 dayName = "Thursday"; 48 }
15 break; 49
16 case 5: 50 System.out.println("Result: " + result);
17 dayName = "Friday"; 51 }
18 break; 52 }
19 default: 53 import java.util.Scanner;
20 dayName = "Invalid day"; 54
21 } 55 public class SwitchExample {
22 56 public static void main(String[] args) {
23 System.out.println("Day of the week: " + 57 Scanner scanner = new Scanner(System.in);
24 dayName);
58 System.out.print("Enter a month number (1-
25 } 59 12): ");
26 } 60 int month = scanner.nextInt();
27 public class SwitchExample { 61
28 public static void main(String[] args) { 62 String season;
29 char operator = '*'; 63 switch (month) {
30 double num1 = 10, num2 = 5, result; 64 case 12:
31 65 case 1:
32 switch (operator) { 66 case 2:
33 case '+': 67 season = "Winter";
34 result = num1 + num2; 68 break;
1 case 3: 35 }
2 case 4: 36 }
3 case 5: 37 }
4 season = "Spring"; 38 public class WhileLoopExample {
5 break; 39 public static void main(String[] args) {
6 case 6: 40 int num = 1, sum = 0;
7 case 7: 41
8 case 8: 42 while (num <= 10) {
9 season = "Summer"; 43 sum += num;
10 break; 44 num++;
11 case 9: 45 }
12 case 10: 46
13 case 11: 47 System.out.println("Sum of numbers from 1
14 season = "Autumn"; 48 to 10: " + sum);

15 break; 49 }

16 default: 50 }

17 season = "Invalid month"; 51  Do-while loops.

18 } 52 public class DoWhileLoopExample {

19 53 public static void main(String[] args) {

20 System.out.println("The season for month "54


+ int num = 1;
21 month + " is " + season); 55
22 scanner.close(); 56 // Printing numbers from 1 to 5 using do-
23 } 57 while loop

24 } 58 do {

25  While loops. 59 System.out.println(num);

26 public class WhileLoopExample { 60 num++;

27 public static void main(String[] args) { 61 } while (num <= 5);

28 int num = 1; 62 }

29 63 }

30 // Printing numbers from 1 to 5 using while64 import java.util.Scanner;


31 loop
65
32 while (num <= 5) {
66 public class DoWhileLoopExample {
33 System.out.println(num);
67 public static void main(String[] args) {
34 num++;
68 Scanner scanner = new Scanner(System.in);
1 int num, sum = 0; 35 }
2 36 }
3 do { 37  Nested loops and conditional statements.
4 System.out.print("Enter a number (enter 038
5 to exit): ");
39 public class NestedLoopExample {
6 num = scanner.nextInt();
40 public static void main(String[] args) {
7 sum += num;
41 for (int i = 1; i <= 5; i++) {
8 } while (num != 0);
42 for (int j = 1; j <= i; j++) {
9
43 System.out.print(j + " ");
10 System.out.println("Sum of entered numbers:
11 " + sum); 44 }

12 scanner.close(); 45 System.out.println();

13 } 46 }

14 } 47 }

15  For loops. 48 }

16 public class ForLoopExample { 49

17 public static void main(String[] args) { 50 public class NestedLoopExample {

18 51
// Printing numbers from 1 to 5 using for loop public static void main(String[] args) {

19 for (int i = 1; i <= 5; i++) { 52 for (int i = 1; i <= 3; i++) {

20 System.out.println(i); 53 for (int j = 1; j <= 3; j++) {

21 } 54 if (i == j) {

22 } 55 System.out.print("* ");

23 } 56 } else {

24 public class ForLoopExample { 57 System.out.print("- ");

25 public static void main(String[] args) { 58 }

26 int n = 5; 59 }

27 long factorial = 1; 60 System.out.println();

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

17 // Accessing and printing individual array 52 System.out.println("Element at row 1, column


18 elements 53 2: " + matrix[0][1]);
54 System.out.println("Element at row 2, column
19 System.out.println("Element at index 0: " +
20 numbers[0]); 55 3: " + matrix[1][2]);

21 System.out.println("Element at index 3: " +56 }


22 numbers[3]); 57 }
23 }
58
24 }
59 6. Methods:
25 60  Declaring and defining methods.
26  Iterating through arrays. 61 public class ExampleMethods {
27 public class IteratingThroughArrays { 62 // Method to calculate the sum of two integers
28 public static void main(String[] args) { 63 public static int calculateSum(int a, int b) {
29 int[] numbers = {10, 20, 30, 40, 50}; 64 return a + b;
30 65 }
31 // Iterating through the array and printing 66
32 each element
67 // Method to print a greeting message
33 for (int i = 0; i < numbers.length; i++) {
68 public static void printGreeting() {
34 System.out.println("Element at index " + i +
35 ": " + numbers[i]); 69 System.out.println("Hello, World!");

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);

11 45 System.out.println("Sum 2: " + sum2);

12  Method parameters and return types. 46 }

13 public class MethodParametersAndReturnTypes47


{ }

14 // Method with parameters and return type 48


15 public static int calculateProduct(int a, int b) {49  Recursion.
16 return a * b; 50 public class RecursionExample {
17 } 51 // Method to calculate factorial using recursion
18 52 public static int factorial(int n) {
19 public static void main(String[] args) { 53 if (n == 0) {
20 // Calling the calculateProduct method 54 return 1;
21 int product = calculateProduct(4, 6); 55 } else {
22 System.out.println("Product: " + product); 56 return n * factorial(n - 1);
23 } 57 }
24 } 58 }

25 59

26  Method overloading. 60 public static void main(String[] args) {

27 public class MethodOverloading { 61 // Calling the factorial method

28 62
// Method to calculate the sum of two integers int result = factorial(5);

29 public static int calculateSum(int a, int b) { 63 System.out.println("Factorial of 5: " + result);

30 return a + b; 64 }

31 } 65 }

32 66 public class RecursionExample {


33 // Method overloading to calculate the sum of67 // Method to calculate the factorial of a
34 three integers 68 number using recursion
1 public static int factorial(int n) { 36 private int num1;
2 if (n == 0 || n == 1) { 37 private int num2;
3 return 1; 38
4 } else { 39 // Constructor with no parameters
5 return n * factorial(n - 1); 40 public ConstructorOverloading() {
6 } 41 System.out.println("Default constructor
42 called.");
7 }
43 }
8
44
9 // Method to calculate the Fibonacci series
10 using recursion 45 // Constructor with one parameter
11 public static int fibonacci(int n) { 46 public ConstructorOverloading(int num1) {
12 if (n <= 1) { 47 this.num1 = num1;
13 return n; 48 System.out.println("Constructor with one
49 parameter called. num1 = " + num1);
14 } else {
50 }
15 return fibonacci(n - 1) + fibonacci(n - 2);
51
16 }
52 // Constructor with two parameters
17 }
53 public ConstructorOverloading(int num1, int
18 54 num2) {
19 public static void main(String[] args) { 55 this.num1 = num1;
20 // Example of factorial calculation 56 this.num2 = num2;
21 int factorialResult = factorial(5); 57 System.out.println("Constructor with two
22 System.out.println("Factorial of 5: " + 58 parameters called. num1 = " + num1 + ", num2 = "
23 factorialResult); 59 + num2);

24 60 }

25 // Example of Fibonacci series calculation 61


26 int fibonacciResult = fibonacci(6); 62 public static void main(String[] args) {

27 System.out.println("6th number in Fibonacci63 // Creating objects using different


28 series: " + fibonacciResult); 64 constructors

29 } 65 ConstructorOverloading obj1 = new


66 ConstructorOverloading();
30 }
67 ConstructorOverloading obj2 = new
31 68 ConstructorOverloading(5);
32 69 ConstructorOverloading obj3 = new
33  Constructor overloading. 70 ConstructorOverloading(3, 7);

34 Constructor overloading with different parameters: 71 }

35 public class ConstructorOverloading { 72 }


1 37 public Rectangle(int length, int width) {
2 Constructor overloading with the same number of 38 this.length = length;
3 parameters but different types:
39 this.width = width;
4 public class ConstructorOverloading {
40 }
5 private int num1;
41
6 private double num2;
42 public int calculateArea() {
7
43 return length * width;
8 // Constructor with an integer parameter
44 }
9 public ConstructorOverloading(int num1) {
45 }
10 this.num1 = num1;
46
11 System.out.println("Constructor with int
12 parameter called. num1 = " + num1); 47 public class Main {

13 } 48 public static void main(String[] args) {

14 49 Rectangle rectangle = new Rectangle(5, 10);


50 System.out.println("Area of rectangle: " +
15 // Constructor with a double parameter
51 rectangle.calculateArea());
16 public ConstructorOverloading(double num2) {
52 }
17 this.num2 = num2;
53 }
18 System.out.println("Constructor with double
54  Constructors.
19 parameter called. num2 = " + num2);
20 } 55 class Employee {

21 56 private String name;

22 public static void main(String[] args) { 57 private int age;

23 // Creating objects using different 58


24 constructors 59 public Employee(String name, int age) {
25 ConstructorOverloading obj1 = new 60 this.name = name;
26 ConstructorOverloading(5);
61 this.age = age;
27 ConstructorOverloading obj2 = new
28 ConstructorOverloading(3.5); 62 }

29 } 63

30 } 64 public void displayInfo() {

31 7. Object-Oriented Programming Concepts: 65 System.out.println("Name: " + name);

32  Classes and objects. 66 System.out.println("Age: " + age);

33 class Rectangle { 67 }

34 private int length; 68 }

35 private int width; 69

36 70 public class Main {


1 public static void main(String[] args) { 35 }
2 Employee employee = new Employee("John", 30); 36  Inheritance.
3 employee.displayInfo(); 37 class Animal {
4 } 38 public void eat() {
5 } 39 System.out.println("Animal is eating.");
6  Encapsulation. 40 }
7 class BankAccount { 41 }
8 private double balance; 42
9 43 class Dog extends Animal {
10 public void deposit(double amount) { 44 public void bark() {
11 balance += amount; 45 System.out.println("Dog is barking.");
12 } 46 }
13 47 }
14 public void withdraw(double amount) { 48
15 if (amount <= balance) { 49 public class Main {
16 balance -= amount; 50 public static void main(String[] args) {
17 } else { 51 Dog dog = new Dog();
18 System.out.println("Insufficient funds."); 52 dog.eat(); // Inherited method
19 } 53 dog.bark(); // Subclass method
20 } 54 }
21 55 }
22 public double getBalance() { 56 In this example below:
23 return balance; 57  The Animal class is the base class, containing
24 } 58 common attributes and methods shared by all
59 animals.
25 }
60  The Dog class is derived from Animal, inheriting
26 61 its attributes and methods. It also has its own
62 unique attributes and methods (breed and bark()).
27 public class Main {
63  The Cat class is also derived from Animal, with its
28 public static void main(String[] args) {
64 own unique attributes and methods (color and
29 BankAccount account = new BankAccount(); 65 meow()).

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 }

2 In this example below: 40 }

3  The Employee class is the base class representing 41


4 common attributes and behaviors of all 42 // Derived class for full-time employees
5 employees.
43 class FullTimeEmployee extends Employee {
6  The FullTimeEmployee and PartTimeEmployee
7 classes are derived classes representing full-time44 FullTimeEmployee(String name, int id, double salary) {
8 and part-time employees, respectively.
45 super(name, id, salary);
9  Each derived class overrides the calculateBonus()
46 }
10 method to provide a different implementation of
11 bonus calculation based on the type of employee. 47
12  Polymorphism is demonstrated when calling the48 @Override
13 calculateBonus() method on objects of different
14 types (Employee, FullTimeEmployee, 49 double calculateBonus() {
15 PartTimeEmployee), resulting in different 50 return salary * 0.15; // Full-time employees get a
16 behaviors based on the actual type of the object51 higher bonus
17 at runtime.
52 }
18 // Base class
53 }
19 class Employee {
54
20 protected String name;
55 // Derived class for part-time employees
21 protected int id;
56 class PartTimeEmployee extends Employee {
22 protected double salary;
57 PartTimeEmployee(String name, int id, double salary) {
23
58 super(name, id, salary);
24 Employee(String name, int id, double salary) {
59 }
25 this.name = name;
60
26 this.id = id;
61 @Override
27 this.salary = salary;
62 double calculateBonus() {
28 }
63 return salary * 0.05; // Part-time employees get a
29 64 lower bonus
30 void displayDetails() { 65 }
31 System.out.println("Name: " + name); 66 }
32 System.out.println("ID: " + id); 67
33 System.out.println("Salary: $" + salary); 68 public class EmployeeManagementSystem {
34 } 69 public static void main(String[] args) {
35 70 Employee fullTimeEmployee = new
36 double calculateBonus() { 71 FullTimeEmployee("John Doe", 1001, 50000);

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 }

26 public class StaticExample { 60  this, super, final keyword

27 // Static variable 61 class Student {

28 private static int staticVar = 0; 62 private String name;

29 63 private int age;

30 // Static method 64

31 public static void staticMethod() { 65 public Student(String name, int age) {

32 System.out.println("This is a static method. Static 66 this.name = name;


33 variable value: " + staticVar); 67 this.age = age;
34 } 68 }
35 69
36 // Static block 70 public void display() {
1 System.out.println("Name: " + this.name); 34 public Car(String name, String model) {
2 System.out.println("Age: " + this.age); 35 super(name);
3 } 36 this.model = model;
4 37 }
5 public void updateInfo(String name, int age) { 38
6 this.name = name; 39 public String getModel() {
7 this.age = age; 40 return model;
8 } 41 }
9 } 42
10 43 public void printDetails() {
11 public class Main { 44 String vehicleName = super.getName();
12 public static void main(String[] args) { 45 String carModel = this.getModel();
13 Student student1 = new Student("John", 20); 46
14 student1.display(); // Output: Name: John, Age: 20 47 System.out.println("Vehicle Name: " + vehicleName);
15 48 System.out.println("Car Model: " + carModel);
16 student1.updateInfo("Alice", 22); 49 }
17 student1.display(); // Output: Name: Alice, Age: 22 50 }
18 } 51
19 } 52 public class Main {

20 class Vehicle { 53 public static void main(String[] args) {

21 private final String name; 54 Car car = new Car("Toyota", "Camry");

22 55

23 public Vehicle(String name) { 56 final String message = "Details of the car:";

24 this.name = name; 57 System.out.println(message);

25 } 58

26 59 car.printDetails();

27 public String getName() { 60 }

28 return name; 61 }

29 } 62 public class FinalExample {


30 } 63 // Final variable
31 64 private final int FINAL_NUMBER = 10;
32 class Car extends Vehicle { 65
33 private final String model; 66 // Final method
1 public final void finalMethod() { 36
2 System.out.println("This is a final method."); 37
3 } 38  Polymorphism (method overriding, dynamic
39 method dispatch).
4
40 class Animal {
5 // Final class
41 public void sound() {
6 final class FinalClass {
42 System.out.println("Animal makes a sound.");
7 public void display() {
43 }
8 System.out.println("This is a method inside a final
9 class."); 44 }
10 } 45
11 } 46 class Dog extends Animal {
12 47 @Override
13 // Method with final parameter 48 public void sound() {
14 public void displayFinalParameter(final int number) { 49 System.out.println("Dog barks.");
15 // Trying to modify a final parameter will result in a50 }
16 compilation error
51 }
17 // number = 20; // This line will cause a compilation
18 error 52

19 System.out.println("Final parameter value: " + 53 class Cat extends Animal {


20 number); 54 @Override
21 } 55 public void sound() {
22 56 System.out.println("Cat meows.");
23 public static void main(String[] args) { 57 }
24 FinalExample example = new FinalExample(); 58 }
25 System.out.println("Final variable value: " + 59
26 example.FINAL_NUMBER);
60 public class Main {
27 example.finalMethod();
61 public static void main(String[] args) {
28 // Creating an instance of the final class
62 Animal animal1 = new Dog();
29 FinalClass finalObj = example.new FinalClass();
63 Animal animal2 = new Cat();
30 finalObj.display();
64
31 // Using a final parameter
65 animal1.sound(); // Dynamic method dispatch
32 int parameterValue = 100;
66 animal2.sound(); // Dynamic method dispatch
33 example.displayFinalParameter(parameterValue);
67 }
34 }
68 }
35 }
69 In this example:
1  We have a base class Shape with a method 39 // Derived class Circle
2 calculateArea() which is overridden by derived
3 classes. 40 class Circle extends Shape {

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;

9  Using dynamic polymorphism, we iterate through 45 }


10 the array and call the calculateArea() method for
46
11 each shape. At runtime, the appropriate
12 overridden method based on the actual object 47 @Override
13 type is invoked, demonstrating dynamic
48 public double calculateArea() {
14 polymorphism.
49 return Math.PI * radius * radius;
15 // Base class Shape
50 }
16 class Shape {
51 }
17 public double calculateArea() {
52
18 return 0; // Default implementation, overridden by
19 derived classes 53 // Derived class Triangle
20 } 54 class Triangle extends Shape {
21 } 55 private double base;
22 56 private double height;
23 // Derived class Rectangle 57
24 class Rectangle extends Shape { 58 public Triangle(double base, double height) {
25 private double length; 59 this.base = base;
26 private double width; 60 this.height = height;
27 61 }
28 public Rectangle(double length, double width) { 62
29 this.length = length; 63 @Override
30 this.width = width; 64 public double calculateArea() {
31 } 65 return 0.5 * base * height;
32 66 }
33 @Override 67 }
34 public double calculateArea() { 68
35 return length * width; 69 public class AreaCalculator {
36 } 70 public static void main(String[] args) {
37 } 71 Shape[] shapes = {
38
1 new Rectangle(5, 10), 38 }
2 new Circle(7), 39
3 new Triangle(6, 4) 40 public String getEmployeeId() {
4 }; 41 return employeeId;
5 42 }
6 for (Shape shape : shapes) { 43
7 System.out.println("Area of " + 44 // Abstract method to calculate monthly salary
8 shape.getClass().getSimpleName() + ": " +
9 shape.calculateArea()); 45 public abstract double calculateMonthlySalary();

10 } 46 }

11 } 47

12 } 48 // Full-time employee class


49 class FullTimeEmployee extends Employee {
13 In this example:
50 private double monthlySalary;
14  We have a base class Employee with attributes
15 such as name and employee ID, along with an 51
16 abstract method calculateMonthlySalary() to
52 public FullTimeEmployee(String name, String
17 calculate the monthly salary.
53 employeeId, double monthlySalary) {
18  Derived classes FullTimeEmployee,
54 super(name, employeeId);
19 PartTimeEmployee, and Contractor implement the
20 calculateMonthlySalary() method differently 55 this.monthlySalary = monthlySalary;
21 based on their specific payroll rules.
56 }
22  The PayrollSystem class demonstrates the payroll
23 calculations for different types of employees by 57
24 creating an array of Employee objects and 58 @Override
25 iterating through them to display their details.
59 public double calculateMonthlySalary() {
26 // Base class Employee
60 return monthlySalary;
27 abstract class Employee {
61 }
28 private String name;
62 }
29 private String employeeId;
63
30
64 // Part-time employee class
31 public Employee(String name, String employeeId) {
65 class PartTimeEmployee extends Employee {
32 this.name = name;
66 private double hourlyRate;
33 this.employeeId = employeeId;
67 private double hoursWorked;
34 }
68
35
69 public PartTimeEmployee(String name, String
36 public String getName() { 70 employeeId, double hourlyRate, double hoursWorked) {
37 return name; 71 super(name, employeeId);
1 this.hourlyRate = hourlyRate; 35 new PartTimeEmployee("Alice Smith", "PT001", 20,
36 80),
2 this.hoursWorked = hoursWorked;
37 new Contractor("Bob Johnson", "C001", 30, 100)
3 }
38 };
4
39
5 @Override
40 System.out.println("Payroll Details:");
6 public double calculateMonthlySalary() {
41 System.out.println("-----------------");
7 return hourlyRate * hoursWorked * 4; // Assuming 4
8 weeks in a month 42
9 } 43 for (Employee emp : employees) {
10 } 44 System.out.println("Employee: " +
45 emp.getName());
11
46 System.out.println("Employee ID: " +
12 // Contractor class 47 emp.getEmployeeId());
13 class Contractor extends Employee { 48 System.out.println("Monthly Salary: $" +
14 private double hourlyRate; 49 emp.calculateMonthlySalary());

15 private double hoursWorked; 50 System.out.println();

16 51 }

17 public Contractor(String name, String employeeId, 52 }


18 double hourlyRate, double hoursWorked) { 53 }
19 super(name, employeeId);
54  Multilevel I heritance
20 this.hourlyRate = hourlyRate;
55
21 this.hoursWorked = hoursWorked;
56 In this example:
22 }
57  The Animal class is the base class with a method
23 58 eat().

24 @Override 59  The Dog class is derived from Animal and adds a


60 method bark().
25 public double calculateMonthlySalary() {
61  The Labrador class is derived from Dog and adds a
26 return hourlyRate * hoursWorked * 4; // Assuming 62
4 method color().
27 weeks in a month
63  When an object of Labrador is created and
28 } 64 methods are called, it can access methods from all
29 } 65 three classes due to multilevel inheritance.

30 66 // Base class

31 public class PayrollSystem { 67 class Animal {

32 public static void main(String[] args) { 68 void eat() {

33 Employee[] employees = { 69 System.out.println("Animal is eating");

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

24 } 60 // Interface for electronic devices that can connect to the


61 internet
25 }
62 interface Connectable {
26
63 void connectToInternet();
27 public class SchoolSystem {
64 }
28 public static void main(String[] args) {
65
29 SchoolStudent student = new SchoolStudent("John");
66 // Interface for electronic devices that can play media
30 SchoolTeacher teacher = new SchoolTeacher("Mr.
31 Smith"); 67 interface Playable {

32 SchoolAdministrator administrator = new 68 void playMedia();


33 SchoolAdministrator("Ms. Johnson"); 69 }
34 SchoolParent parent = new SchoolParent("Mrs. 70
35 Davis");
1 // Class representing a smartphone that can be charged,
37 public class ExceptionHandlingExample {
2 connect to the internet, and play media
38 public static void main(String[] args) {
3 class Smartphone implements Chargeable, Connectable,
4 Playable { 39 try {

5 @Override 40 // Code that may throw an exception

6 public void charge() { 41 int result = divide(10, 0);

7 System.out.println("Smartphone is charging"); 42 System.out.println("Result of division: " + result);


43 // This line will not execute
8 }
44 } catch (ArithmeticException e) {
9
45 // Handling the ArithmeticException
10 @Override
46 System.out.println("Error: Division by zero");
11 public void connectToInternet() {
47 }
12 System.out.println("Smartphone is connected to the
13 internet"); 48 }

14 } 49

15 50 // Method to perform division

16 @Override 51 public static int divide(int dividend, int divisor) {

17 public void playMedia() { 52 return dividend / divisor; // This may throw an


53 ArithmeticException if divisor is 0
18 System.out.println("Smartphone is playing media");
54 }
19 }
55 }
20 }
56 In this example, we have several interfaces representing
21 57 different aspects of products, such as Purchasable,
22 public class Main { 58 Reviewable, Shippable, TryOnable, and Customizable. We
59 then have classes ElectronicProduct and ClothingProduct
23 public static void main(String[] args) { 60 that implement various combinations of these interfaces,
61 showcasing the versatility and complexity of the e-
24 Smartphone smartphone = new Smartphone();
62 commerce domain.
25 smartphone.charge(); // Output: Smartphone is
63 // Interface for products that can be purchased
26 charging
64 interface Purchasable {
27 smartphone.connectToInternet(); // Output:
28 Smartphone is connected to the internet 65 void purchase();
29 smartphone.playMedia(); // Output: Smartphone
66 }
30 is playing media
67
31 }
68 // Interface for products that can be reviewed
32 }
69 interface Reviewable {
33  sf
70 void leaveReview();
34 8. Exception Handling:
71 }
35  Handling exceptions with try-catch blocks.
72
36
1 // Interface for electronic products that can be shipped 35
2 interface Shippable { 36 // Class representing a clothing product
3 void ship(); 37 class ClothingProduct implements Purchasable,
38 Reviewable, TryOnable, Shippable, Customizable {
4 }
39 @Override
5
40 public void purchase() {
6 // Interface for clothing products that can be tried on
41 System.out.println("Clothing product purchased");
7 interface TryOnable {
42 }
8 void tryOn();
43
9 }
44 @Override
10
45 public void leaveReview() {
11 // Interface for products that can be customized
46 System.out.println("Review for clothing product
12 interface Customizable { 47 left");
13 void customize(); 48 }
14 }
49
15 50 @Override
16 // Class representing an electronic product 51 public void tryOn() {
17 class ElectronicProduct implements Purchasable, 52 System.out.println("Clothing product tried on");
18 Reviewable, Shippable {
53 }
19 @Override
54
20 public void purchase() {
55 @Override
21 System.out.println("Electronic product purchased");
56 public void ship() {
22 }
57 System.out.println("Clothing product shipped");
23
58 }
24 @Override
59
25 public void leaveReview() {
60 @Override
26 System.out.println("Review for electronic product
27 left"); 61 public void customize() {
28 } 62 System.out.println("Clothing product customized");
29 63 }
30 @Override 64 }
31 public void ship() { 65
32 System.out.println("Electronic product shipped"); 66 public class Main {
33 } 67 public static void main(String[] args) {
34 } 68 // Example with electronic product
1 ElectronicProduct electronicProduct = new 40 }
2 ElectronicProduct();
41
3 electronicProduct.purchase(); // Output: Electronic
4 product purchased 42 // Interface for electronic products that can be shipped

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();

13 clothingProduct.purchase(); // Output: Clothing 50 }


14 product purchased 51
15 clothingProduct.leaveReview(); // Output: Review52 // Interface for products that can be customized
16 for clothing product left
53 interface Customizable {
17 clothingProduct.tryOn(); // Output: Clothing
18 product tried on 54 void customize();
19 clothingProduct.ship(); // Output: Clothing 55 }
20 product shipped
56
21 clothingProduct.customize(); // Output: Clothing
57 // Class representing an electronic product
22 product customized
58 class ElectronicProduct implements Purchasable,
23 }
59 Reviewable, Shippable {
24 }
60 @Override
25 In this example, we have several interfaces representing61 public void purchase() {
26 different aspects of products, such as Purchasable,
27 Reviewable, Shippable, TryOnable, and Customizable. We 62 System.out.println("Electronic product purchased");
28 then have classes ElectronicProduct and ClothingProduct
63 }
29 that implement various combinations of these interfaces,
30 showcasing the versatility and complexity of the e- 64
31 commerce domain.
65 @Override
32 // Interface for products that can be purchased
66 public void leaveReview() {
33 interface Purchasable {
67 System.out.println("Review for electronic product
34 void purchase(); 68 left");
35 } 69 }
36 70
37 // Interface for products that can be reviewed 71 @Override
38 interface Reviewable { 72 public void ship() {
39 void leaveReview(); 73 System.out.println("Electronic product shipped");
1 } 35 public static void main(String[] args) {
2 } 36 // Example with electronic product
3 37 ElectronicProduct electronicProduct = new
38 ElectronicProduct();
4 // Class representing a clothing product
39 electronicProduct.purchase(); // Output: Electronic
5 class ClothingProduct implements Purchasable, 40 product purchased
6 Reviewable, TryOnable, Shippable, Customizable {
41 electronicProduct.leaveReview(); // Output: Review
7 @Override 42 for electronic product left
8 public void purchase() { 43 electronicProduct.ship(); // Output: Electronic
9 System.out.println("Clothing product purchased"); 44 product shipped

10 } 45

11 46 // Example with clothing product

12 @Override 47 ClothingProduct clothingProduct = new


48 ClothingProduct();
13 public void leaveReview() {
49 clothingProduct.purchase(); // Output: Clothing
14 System.out.println("Review for clothing product 50 product purchased
15 left");
51 clothingProduct.leaveReview(); // Output: Review
16 } 52 for clothing product left
17 53 clothingProduct.tryOn(); // Output: Clothing
18 @Override 54 product tried on

19 public void tryOn() { 55 clothingProduct.ship(); // Output: Clothing


56 product shipped
20 System.out.println("Clothing product tried on");
57 clothingProduct.customize(); // Output: Clothing
21 } 58 product customized
22 59 }
23 @Override 60 }
24 public void ship() { 61  Throwing exceptions.
25 System.out.println("Clothing product shipped"); 62
26 } 63 public class ExceptionThrowingExample {
27 64 public static void main(String[] args) {
28 @Override 65 try {
29 public void customize() { 66 int result = divide(10, 0);
30 System.out.println("Clothing product customized");67 System.out.println("Result of division: " + result); //
68 This line will not execute
31 }
69 } catch (ArithmeticException e) {
32 }
70 System.out.println("Error: " + e.getMessage());
33
71 }
34 public class Main {
72 }
1 37 private String accountNumber;
2 public static int divide(int dividend, int divisor) { 38 private double balance;
3 if (divisor == 0) { 39
4 throw new ArithmeticException("Division by zero");
40 public BankAccount(String accountNumber, double
5 // Throwing ArithmeticException 41 balance) {
6 } 42 this.accountNumber = accountNumber;
7 return dividend / divisor; 43 this.balance = balance;
8 } 44 }
9 } 45
10  Checked vs. unchecked exceptions. 46 public void deposit(double amount) {
11 // Checked Exception Example 47 balance += amount;
12 public void readFile() throws IOException { 48 System.out.println("Deposited $" + amount + " into
49 account " + accountNumber);
13 FileInputStream file = new
14 FileInputStream("example.txt"); // Checked IOException50 }
15 must be declared
51
16 }
52 // Method to withdraw amount with exception
17 53 handling
18 // Unchecked Exception Example 54 public void withdraw(double amount) {
19 public void divide(int a, int b) { 55 try {
20 if (b == 0) { 56 if (amount > balance) {
21 throw new ArithmeticException("Cannot divide by 57 throw new Exception("Insufficient balance in
22 zero"); // Unchecked ArithmeticException 58 account " + accountNumber);
23 } 59 }
24 int result = a / b; 60 balance -= amount;
25 } 61 System.out.println("Withdrawn $" + amount + "
62 from account " + accountNumber);
26
63 } catch (Exception e) {
27 In this example:
64 System.out.println("Error: " + e.getMessage());
28  throw a standard Exception within the withdraw()
29 method if the withdrawal amount exceeds the 65 }
30 balance.
66 }
31  The withdraw() method now handles the
32 exception internally using a try-catch block, 67 }
33 printing an error message if an exception occurs.68
34 69 // Main class to demonstrate exception handling
35 // Bank account class 70 public class BankApplication {
36 class BankAccount { 71 public static void main(String[] args) {
1 BankAccount account1 = new 40 import java.io.IOException;
2 BankAccount("ACC001", 1000);
41
3 account1.withdraw(1500); // This will print an error
4 message 42 public class ExceptionExample {

5 43

6 BankAccount account2 = new 44 // Checked exception: FileReader constructor throws


7 BankAccount("ACC002", 2000); 45 FileNotFoundException

8 account2.withdraw(500); // This will not print an 46 public void readFile(String filePath) {


9 error message 47 try {
10 48 FileReader reader = new FileReader(filePath); //
11 // Example of unchecked exception 49 Checked exception must be handled
12 (ArithmeticException) 50 // Read file content
13 int dividend = 10; 51 // ...
14 int divisor = 0; 52 } catch (FileNotFoundException e) {
15 try { 53 System.err.println("File not found: " +
16 54
int result = dividend / divisor; // This will throw an e.getMessage());
17 ArithmeticException 55 }
18 } catch (ArithmeticException e) { 56 }
19 System.out.println("Error: Division by zero"); 57
20 } 58 // Unchecked exception: Division by zero
21 } 59 public double divide(int numerator, int denominator) {
22 } 60 if (denominator == 0) {
23 61 throw new ArithmeticException("Cannot divide by
62 zero"); // Unchecked exception
24 In this example:
63 }
25 1. The readFile method reads from a file specified by
26 64
the filePath. Since the FileReader constructor may return (double) numerator / denominator;
27 throw a FileNotFoundException, a checked
65 }
28 exception, it must be handled using a try-catch
29 block. 66
30 2. The divide method performs division between two 67 public static void main(String[] args) {
31 integers. If the denominator is zero, it throws an
32 ArithmeticException, an unchecked exception. 68 ExceptionExample example = new
33 This exception does not need to be declared or 69 ExceptionExample();
34 caught explicitly, but it's good practice to handle70
35 it for better error reporting and program stability.
71 // Example of handling checked exception
36
72 example.readFile("nonexistent-file.txt");
37 import java.io.File;
73
38 import java.io.FileReader;
74 // Example of throwing and handling unchecked
39 import java.io.FileNotFoundException; 75 exception
1 try {
2 double result = example.divide(10, 0);
3 System.out.println("Result: " + result);
4 } catch (ArithmeticException e) {
5 System.err.println("Error: " + e.getMessage());
6 }
7 }
8 }
9
10 9. abc
11  abc
12  abc
13

You might also like