Karthi
Karthi
// Base Class } }
class Employee { }
basicPay = sc.nextDouble(); }
System.out.print("Enter Mail ID: "); void generatePaySlip() { double hra = 0.10 * basicPay;
System.out.print("Enter Mobile Number: "); double pf = 0.12 * basicPay; double grossSalary = basicPay + da + hra;
mobileNo = sc.nextLong(); double staffClub = 0.001 * basicPay; double netSalary = grossSalary - pf - staffClub;
} double netSalary = grossSalary - pf - staffClub; System.out.println("\n--- Assistant Professor Pay Slip ---");
displayDetails();
double basicPay; Professor(Scanner sc) { // You can create any one or more employee types
basicPay = sc.nextDouble(); }
void generatePaySlip() { double hra = 0.10 * basicPay; Professor prof = new Professor(sc);
double netSalary = grossSalary - pf - staffClub; System.out.println("\n--- Professor Pay Slip ---"); Output
System.out.println("\n--- Associate Professor Pay Slip ---"); System.out.println("Basic Pay: ₹" + basicPay); Enter Employee Name: Alice
System.out.println("Basic Pay: ₹" + basicPay); System.out.println("Net Salary: ₹" + netSalary); Enter Address: Chennai
Name: Alice public UGStudent(int rollNo, String name, int age, String course) { class LocalUGStudent extends UGStudent {
Gross Salary: ₹103500.0 } public LocalUGStudent(int rollNo, String name, int age, String course) {
Unit 2 @Override }
Consider a class student .Inherit this class in UG Student and Evaluate PG Student. Also inherit students public void displayInfo() {
into local and non-local students. Define five Local UG Students with a constructor assuming all classes super.displayInfo(); @Override
have a constructor
System.out.println("Course: " + course); public void displayInfo() {
// Base class
} System.out.println("\n--- Local UG Student ---");
class Student {
} super.displayInfo();
protected int rollNo;
System.out.println("Location: " + location);
protected String name;
// PG Student inherits Student }
protected int age;
class PGStudent extends Student { }
public class StudentInheritanceTest { Roll No: 103, Name: Charan, Age: 18 this.b = breadth;
LocalUGStudent s2 = new LocalUGStudent(102, "Bala", 19, "AI & DS"); --- Local UG Student --- int area = a * b;
LocalUGStudent s3 = new LocalUGStudent(103, "Charan", 18, "Electronics"); Roll No: 104, Name: Deepa, Age: 20 System.out.println("Area of Rectangle = " + area);
s1.displayInfo(); Roll No: 105, Name: Esha, Age: 21 class Triangle extends Shape {
s5.displayInfo(); Write a Java Program to create an abstract class named Shape that contains two integers and an empty }
}
method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each
one of the classes extends the class Shape. Each one of the classes contains only the method print Area
} () that prints the area of the given shape void printArea() {
Location: Local
// Abstract method
// Circle class 2.a) What do you mean by static class and static method? Can we make an instance of an abstract class? int result = MathUtility.square(5);
System.out.println("Square: " + result); // Output: Square: 25
class Circle extends Shape {
Justify your answer with an example? (8 marks) b) What are the various types of exceptions available in }
Java? Also discuss on how they are handled? }
Circle(int radius) {
this.a = radius; a) Static Class and Static Method + Abstract Class Instantiation (8 Marks)
3. Can we instantiate an abstract class?
} 1. Static Class in Java:
No, we cannot create an object of an abstract class directly.
Definition: A static class is a nested class that is declared as static.
void printArea() { It can’t access instance methods and variables of the outer class directly. ✅ Justification:
It is used when the inner class does not require access to the instance members of the
double area = 3.14159 * a * a;
outer class. Abstract classes are incomplete and meant to be extended by subclasses.
You can only instantiate concrete subclasses that implement all the abstract methods.
System.out.println("Area of Circle = " + area);
✅ Example of Static Class:
} ✅ Example:
java
} CopyEdit java
class Outer { CopyEdit
static class StaticNested { abstract class Animal {
void display() { abstract void sound();
// Main class }
System.out.println("Inside static nested class");
}
public class ShapeTest { class Dog extends Animal {
}
} void sound() {
public static void main(String[] args) { System.out.println("Dog barks");
public class Main { }
Rectangle rectangle = new Rectangle(10, 5); }
public static void main(String[] args) {
Outer.StaticNested obj = new Outer.StaticNested();
Triangle triangle = new Triangle(8, 4); public class Main {
obj.display(); // Output: Inside static nested class
} public static void main(String[] args) {
Circle circle = new Circle(7); // Animal a = new Animal(); // ❌ Compile-time Error
}
Animal d = new Dog(); // ❌ Polymorphic behavior
d.sound(); // Output: Dog barks
}
rectangle.printArea(); // Rectangle Area = 10 * 5 = 50 2. Static Method in Java: }
triangle.printArea(); // Triangle Area = 0.5 * 8 * 4 = 16
A static method belongs to the class, not the instance.
circle.printArea(); // Circle Area = π * 7^2 = approx 153.93791 Can be called without creating an object of the class. ✅ b) Types of Exceptions in Java and How They Are Handled
Can access only static data (variables and other static methods).
}
Java exceptions are objects representing an error condition during program execution.
} ✅ Example of Static Method:
Output java
CopyEdit
Area of Rectangle = 50 class MathUtility {
1. Types of Exceptions:
static int square(int x) {
Area of Triangle = 16.0 return x * x; ✅ A. Checked Exceptions (Compile-time exceptions):
}
Area of Circle = 153.93791 } These are exceptions that the compiler checks.
public class Main { Must be either handled using try-catch or declared with throws.
public static void main(String[] args) {
System.out.println("This won't print: " + errorElement); System.out.println("\n❌ Program completed successfully."); public class MainProgram {
System.out.println("❌ Exception in ArrayList: " + e.getMessage()); Output Collection<String> exceptionLog = new ArrayList<>();
} ArrayList Operations:
try { ArrayList after removing 'Banana': [Apple, Mango] String input = "hello world";
// ---- LinkedList Operations ---- Retrieved element at index 1: Mango System.out.println("Original String: " + input);
System.out.println("\n LinkedList Operations:"); ❌ Exception in ArrayList: Index 5 out of bounds for length 2 System.out.println("Reversed: " + StringUtils.reverse(input));
linkedList.add("Train"); LinkedList after adding elements: [Car, Bike, Train] // Intentionally causing an exception
System.out.println("LinkedList after adding elements: " + linkedList); Retrieved element at index 1: Train System.out.println("Reversed Null: " + StringUtils.reverse(nullInput));
System.out.println("LinkedList after removing index 1: " + linkedList); ❌ Program completed successfully. System.out.println("❌ Exception: " + e.getMessage());
Write a Java program to import a custom package and use its classes to perform a specific task. Handle exceptionLog.add(e.getMessage());
// Intentionally causing an exception 1. Creating a custom package with a utility class. System.out.println("\n Exception Log:");
} catch (IndexOutOfBoundsException e) { }
package myutils;
System.out.println("❌ Exception in LinkedList: " + e.getMessage()); }
import myutils.StringUtils;
public class StringUtils { // 1. String from character array char[] charArray = { 'H', 'e', 'l', 'l', 'o' };
public static String reverse(String input) { char[] charArray = { 'H', 'e', 'l', 'l', 'o' }; String strFromCharArray = new String(charArray);
if (input == null) { String strFromCharArray = new String(charArray); System.out.println("String from char array: " + strFromCharArray);
throw new IllegalArgumentException("Input cannot be null."); System.out.println("String from char array: " + strFromCharArray);
return new StringBuilder(input).reverse().toString(); // 2. String from byte array byte[] byteArray = { 65, 66, 67, 68 }; // ASCII values for A, B, C, D
} byte[] byteArray = { 65, 66, 67, 68 }; // ASCII values for A, B, C, D String strFromByteArray = new String(byteArray);
String strFromByteArray = new String(byteArray); System.out.println("String from byte array: " + strFromByteArray);
public static String toUpperCase(String input) { System.out.println("String from byte array: " + strFromByteArray);
throw new IllegalArgumentException("Input cannot be null."); // 3. String from another String String original = "Java";
return input.toUpperCase(); String strFromString = new String(original); System.out.println("String from another String: " + strFromString);
Output // 4. String from a portion of character array String strPartialChar = new String(charArray, 1, 3); // 'e', 'l', 'l'
Original String: hello world String strPartialChar = new String(charArray, 1, 3); // 'e', 'l', 'l' System.out.println("String from partial char array: " + strPartialChar);
Reversed: dlrow olleh System.out.println("String from partial char array: " + strPartialChar);
❌ Exception: Input cannot be null. // 5. String from a portion of byte array String strPartialByte = new String(byteArray, 1, 2); // ASCII: B, C
String strPartialByte = new String(byteArray, 1, 2); // ASCII: B, C System.out.println("String from partial byte array: " + strPartialByte);
Unit 5 } Develop a Java program that searches for a given substring within a larger string using the indexOf()
Output
method and displays the index of the first occurrence
Write a Java program that demonstrates the usage of different String constructors by creating strings
from character arrays, byte arrays, and other String objects public class StringConstructorsDemo { import java.util.Scanner;
Scanner scanner = new Scanner(System.in); import java.util.Scanner; System.out.println(" Lower Case: " + concatenated.toLowerCase());
System.out.print("Enter the main string: "); public static void main(String[] args) { }
Output
// Input the substring to search // Get user input strings Enter the first string: Hello
System.out.print("Enter the substring to search: "); System.out.print("Enter the first string: "); Enter the second string: World
// Find the index of the first occurrence System.out.print("Enter the second string: ");
int index = mainString.indexOf(subString); String str2 = scanner.nextLine(); Enter the character or word to be replaced: World
System.out.println("❌ Substring found at index: " + index); System.out.println("\n❌ Concatenated String: " + concatenated); Upper Case: HELLOWORLD
scanner.close();
Output
Enter the main string: Hello, welcome to Java programming! String replacedString = concatenated.replace(target, replacement);
Enter the substring to search: Java System.out.println(" String after Replacement: " + replacedString);
Write a Java program that demonstrates various string manipulation operations such as concatenation, // Case Conversion
replacement, and case conversion based on user input. System.out.println("\n Upper Case: " + concatenated.toUpperCase());