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

JAVA PRACTICAL FILE

The document contains a series of Java programming lab experiments focusing on Object-Oriented Programming concepts. It includes various coding exercises such as calculating the product of digits, checking for multiples, manipulating arrays, and implementing classes with methods. Each experiment demonstrates practical applications of Java syntax and object-oriented principles through multiple coding examples.

Uploaded by

Ashita Pahwa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

JAVA PRACTICAL FILE

The document contains a series of Java programming lab experiments focusing on Object-Oriented Programming concepts. It includes various coding exercises such as calculating the product of digits, checking for multiples, manipulating arrays, and implementing classes with methods. Each experiment demonstrates practical applications of Java syntax and object-oriented principles through multiple coding examples.

Uploaded by

Ashita Pahwa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

OBJECT ORIENTED PROGRAMMING USING JAVA ( CSPC-205 )

LAB EXPERIMENTS

Submitted to: Submitted by:


Paras Garg sir Ashita Pahwa
123102181
CS-11
EXPERIMENT 1
Q1)
import java.util.Scanner;
public class main{
public static void main(String[] args){

Scanner sc=new Scanner(System.in);


System.out.println("enter a number between 0 and 1000");
int z=sc.nextInt();
int p=1;

while(z!=0){
int num=z%10;
p=p*num;
z=z/10;
}
System.out.println(p);
}
}

Q2)
import java.util.Scanner;

public class firstq2lab {


public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("enter first number");
int z=sc.nextInt();

System.out.println("enter second number");


int k=sc.nextInt();

if(z%k==0){
System.out.println("first number is multiple of second");
}
else{
System.out.println("first number is not a multiple of
second");
}
}
}

Q3)
import java.util.Scanner;
public class firstq3lab {

static public void main(String args[]){


int n;
System.out.println("enter size of array");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();

int[] arr=new int[n];

System.out.println("enter array elements");


for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int cnt=0;
for(int i=0;i<n;i++){
if(arr[i]==0)
cnt++;
}
int[] ans=new int[cnt];
int k=0;
for(int i=n-cnt;i<n;i++){
if(arr[i]!=0){
ans[k]=arr[i];
k++;
arr[i]=0;
}

}
k=0;
for(int i=0;i<n-cnt;i++){
if(arr[i]==0){
arr[i]=ans[k];
k++;
}
}
for(int i=0;i<n;i++){
System.out.println(arr[i]);
}

}
}

Q4)
import java.util.Scanner;
public class first4lab {
static public void main(String args[]){
int[] arr=new int[101];

Scanner sc=new Scanner(System.in);


int z=sc.nextInt();
arr[z]++;
while(z!=-1){
z=sc.nextInt();
if(z!=-1)
arr[z]++;
}
for(int i=0;i<101;i++){
if(arr[i]!=0){
System.out.print(i+" "+arr[i]);

}
}

}
}

Q5)import java.util.Scanner;
public class first5lab {
static public void main(String args[]){
int n;
System.out.println("enter size of array");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();

int[] arr=new int[n];

System.out.println("enter array elements");


for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int l=0,r=0;
int summ=0,curr=0,maxi=-100000;
while(r<n){

summ+=arr[r];
if(summ<=0){
summ=0;

r++;
l=r;
summ+=arr[r];
}

if(summ>maxi)
maxi=summ;

r++;
}
System.out.println(maxi);
}
}

EXPERIMENT 2
Q1)
import java.util.*;
public class second1lab {
public static boolean compare(String str1,String str2){
boolean ans=true;
int n=str1.length();
int m=str2.length();
if(n!=m){
ans=false;
}
else{
for(int i=0;i<n;i++){
if(str1.charAt(i)!=str2.charAt(i)){
ans=false;
break;
}
}
}
return ans;
}

static public void main(String args[]){

Scanner sc=new Scanner(System.in);


System.out.println("enter first string");

String str1=sc.next();
System.out.println("enter second string");
String str2=sc.next();

boolean ans=compare(str1,str2);
if(ans==true)
System.out.println("strings are equal");
else{
System.out.println("Strings are not equal");
}
}
}

Q2)
public class second2lab {
public static void main(String[] args)
{
// Create two Dog objects
Dog spot = new Dog("spot", "Ruff!");
Dog scruffy = new Dog("scruffy", "Wurf!");

// Display their names and what they say


spot.display();
scruffy.display();

// Create a new Dog reference and assign it to spot's object


Dog anotherDog = spot;

// Compare references using ==


System.out.println("\nComparing references using ==:");
System.out.println("spot == scruffy: " + (spot == scruffy));
System.out.println("spot == anotherDog: " + (spot == anotherDog));
System.out.println("anotherDog == scruffy: " + (anotherDog ==
scruffy));

// Compare references using equals()


System.out.println("\nComparing references using equals():");
System.out.println("spot.equals(scruffy): " +
spot.equals(scruffy));
System.out.println("spot.equals(anotherDog): " +
spot.equals(anotherDog));
System.out.println("anotherDog.equals(scruffy): " +
anotherDog.equals(scruffy));

// After Changing the content of scruffy object


scruffy.name = "spot";
scruffy.says = "Ruff!";
System.out.println("\n Content of scruffy object : ");
System.out.println("scruffy.name = " + scruffy.name);
System.out.println("scruffy.says = " + scruffy.says);
System.out.println("spot == scruffy : " + (spot == scruffy));
System.out.println("spot.equals(scruffy) : " +
(spot.equals(scruffy)));

}
}
class Dog
{
String name;
String says;

// Constructor to initialize the Dog object


public Dog(String name, String says)
{
this.name = name;
this.says = says;
}

// Method to display the dog's name and what it says


public void display()
{
System.out.println(name + " says: " + says);
}

@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Dog otherDog = (Dog) obj;
return name.equals(otherDog.name) && says.equals(otherDog.says);
}

@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + says.hashCode();
return result;
}

}
Q3)

public class second3lab {


public static void main(String[] args)
{
// Creating a StringBuilder object with an initial string
StringBuilder sb = new StringBuilder("Hello");

// 1. append(): Adds text at the end of the current sequence


sb.append(" World");
System.out.println("After append: " + sb);

// 2. insert(): Inserts text at a specified index


sb.insert(5, " Beautiful");
System.out.println("After insert: " + sb);

// 3. replace(): Replaces a portion of the sequence with another


string
sb.replace(6, 15, "Wonderful");
System.out.println("After replace: " + sb);

// 4. delete(): Removes a portion of the sequence


sb.delete(5, 15);
System.out.println("After delete: " + sb);

// 5. deleteCharAt(): Removes a single character at a specified


index
sb.deleteCharAt(5);
System.out.println("After deleteCharAt: " + sb);

// 6. reverse(): Reverses the entire sequence


sb.reverse();
System.out.println("After reverse: " + sb);

// 7. setCharAt(): Changes a character at a specified index


sb.setCharAt(0, 'h');
System.out.println("After setCharAt: " + sb);
// 8. capacity(): Returns the current capacity of the
StringBuilder
System.out.println("Capacity: " + sb.capacity());

// 9. ensureCapacity(): Ensures that the capacity is at least


equal to the specified minimum
sb.ensureCapacity(50);
System.out.println("Capacity after ensureCapacity(50): " +
sb.capacity());

// 10. length(): Returns the number of characters in the


StringBuilder
System.out.println("Length: " + sb.length());

// 11. substring(): Extracts a portion of the sequence as a String


(similar to String class)
String sub = sb.substring(0, 5);
System.out.println("Substring (0, 5): " + sub);

// 12. toString(): Converts the StringBuilder object to a String


String finalString = sb.toString();
System.out.println("Final string: " + finalString);
}
}

EXPERIMENT 3
Q1)
import java.util.*;
class MyInteger
{
private int value;

MyInteger(int value)
{
this.value = value;
}
int getValue()
{
return value;
}

boolean isEven()
{
return this.value % 2 == 0;
}

static boolean isEven(MyInteger obj)


{
return obj.getValue() % 2 == 0;
}

static boolean isEven(int val)


{
return val % 2 == 0;
}

public boolean equals(int val)


{
return this.value == val;
}

public boolean equals(MyInteger obj)


{
return obj.getValue() == this.value;
}
}
public class thirdlab {
public static void main(String args[]){

MyInteger myInt = new MyInteger(4);

System.out.println("Value: " + myInt.getValue());


System.out.println("Is Even: " + myInt.isEven());
System.out.println("Is Even (static): " + MyInteger.isEven(3));
System.out.println("Is Even (MyInteger object): " +
MyInteger.isEven(myInt));
System.out.println("Equals (int): " + myInt.equals(4));
System.out.println("Equals (MyInteger object): " +
myInt.equals(new MyInteger(4)));

}
}

Q2)import java.util.*;
class Dog
{
void bark()
{
System.out.println("The dog is barking!");
}

void bark(int volume)


{
if (volume < 5)
{
System.out.println("Soft bark");
}
else if (volume < 10)
{
System.out.println("Loud bark");
}
else
{
System.out.println("Very loud bark");
}
}

void bark(String sound)


{
if (sound.equals("woof"))
{
System.out.println("Dog says woof!");
}
else if (sound.equals("howl"))
{
System.out.println("Dog is howling!");
}
else
{
System.out.println("Dog is making a different sound: " +
sound);
}
}

class WithoutConstructor
{

class WithConstructors
{
WithConstructors()
{
this(0);
System.out.println("First constructor called");
}

WithConstructors(int value)
{
System.out.println("Second constructor called with value: " +
value);
}
}
public class thirdlab1 {
public static void main(String args[]){

// Create an instance of Dog class and call different overloaded


bark methods
Dog dog = new Dog();
dog.bark(); // Calls the no-argument version
dog.bark(7); // Calls the int version
dog.bark("howl"); // Calls the String version
// Create an instance of a class without a constructor
WithoutConstructor obj1 = new WithoutConstructor(); // Verifies
default constructor

// Create instances of the class with overloaded constructors


WithConstructors obj2 = new WithConstructors(); // Calls the
first constructor
WithConstructors obj3 = new WithConstructors(10); // Calls the
second constructor with a value
}
}

EXPERIMENT 4:
Q1)
import java.util.*;
class phone{
private
String make;
int model;
int year;
phone(String maker,int model1,int year1){
make=maker;
model=model1;
year=year1;
}
int get_year(){
return this.year;
}
String get_make(){
return this.make;
}
int get_model(){
return this.model;
}
void set_year(int year1){
this.year=year1;
}
void set_model(int model1){
this.model=model1;
}
void set_year(String maker){
this.make=maker;
}
String tostring(){
return this.make+" model no: "+this.model+"year of manufacture
"+this.year;
}
Boolean isObsolete(){
System.out.println("enter current year");
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();

if(num-this.year>10)
return true;
else
return false;
}

}
public class fourthlab1{
public static void main(String args[]){
phone p1=new phone("abs",3678,2020);
System.out.println(p1.tostring());
}
}

Q2)
import java.util.*;

public class fourthlab2 {

private static final boolean[] firstClass = new boolean[5];


private static final boolean[] economyClass = new boolean[5];
private static int bookFirstClassTicket()
{
int firstClassVacantSeats = getFirstClassVacantSeats();
if(firstClassVacantSeats > 0)
{
firstClass[firstClass.length - firstClassVacantSeats] = true;
return firstClass.length - firstClassVacantSeats + 1;
}
else
{
return -1;
}

private static int bookEconomyClassTicket()


{
int ecoClassVacantSeats = getEconomyClassVacantSeats();
if(ecoClassVacantSeats > 0)
{
economyClass[economyClass.length - ecoClassVacantSeats] =
true;
return economyClass.length - ecoClassVacantSeats + 6;
}
else
{
return -1;
}

private static int getFirstClassVacantSeats()


{
int vacantSeats = 0;
for(boolean isVacant : firstClass)
{
if (!isVacant)
vacantSeats++;
}
return vacantSeats;
}

private static int getEconomyClassVacantSeats()


{
int vacantSeats = 0;
for(boolean isVacant : economyClass)
{
if (!isVacant)
vacantSeats++;
}
return vacantSeats;
}

private static void generateBoardingPass(int seatAllocated, String


classOpted)
{
System.out.println("|| BOARDING PASS ||");
System.out.println("|| SEAT NO. : " + seatAllocated + " ||");
System.out.println("|| CLASS : " + classOpted + " Class ||");
}

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
System.out.println("|| Welcome to Automated Airline Reservation
Application || \n");
System.out.println("Booking Choices Available : ");
System.out.println("1) First Class : " +
(getFirstClassVacantSeats() > 0 ? getFirstClassVacantSeats() + " Vacant
Seats" : "No Vacant Seat"));
System.out.println("2) Economy Class : " +
(getEconomyClassVacantSeats() > 0 ? getEconomyClassVacantSeats() + "
Vacant Seats" : "No Vacant Seat"));

while(true)
{
System.out.print("Enter your choice ( 1 for First Class, 2 for
Economy Class, 3 for exiting menu ) : ");
int choice = sc.nextInt();
switch (choice)
{
case 1 :
{
int seatAllocated = bookFirstClassTicket();
if(seatAllocated == -1)
{
System.out.println("All seats are already reserved
in First Class. Reservation not successful!!");
}
else
{
generateBoardingPass(seatAllocated, "First");
}
break;
}
case 2 :
{
int seatAllocated = bookEconomyClassTicket();
if(seatAllocated == -1)
{
System.out.println("All seats are already reserved
in Economy Class. Reservation not successful!!");
}
else
{
generateBoardingPass(seatAllocated, "Economy");
}
break;
}
case 3 :
{
System.exit(0);
}
default:
{
System.out.println("Wrong Choice!!!");
System.out.println("Please enter again!!!");
break;
}
}

}
}

EXPERIMENT 5 :
Q1)
public class Program1
{
static String str1 = "Lab5Program1";
static String str2;

static
{
str2 = "staticBlockString";
}

public static void printString()


{
System.out.println("Normal Static String : " + str1);
System.out.println("Static Block String : " + str2);
}

public static void main(String[] args)


{
printString();
}
}
Q2)
public class Program2 {
public static void main(String... args)
{
for(String arg : args)
{
System.out.println(arg);
}
}
}

EXPERIMENT 6
Q1)

import java.util.Calendar;

class MyDate
{
private int year;
private int month;
private int day;

public MyDate()
{
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
}

// Constructor with elapsed time since January 1, 1970


public MyDate(long elapsedTime)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(elapsedTime);
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
}

// Constructor with specified year, month, and day


public MyDate(int year, int month, int day)
{
this.year = year;
this.month = month;
this.day = day;
}

public int getYear()


{
return year;
}

public int getMonth()


{
return month;
}

public int getDay()


{
return day;
}

// Method to set a new date using elapsed time


public void setDate(long elapsedTime)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(elapsedTime);
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
}
}

public class sixlab1 {


public static void main(String[] args)
{
MyDate date1 = new MyDate();
MyDate date2 = new MyDate(34355555133101L);

System.out.println("Date 1:");
System.out.println("Year: " + date1.getYear());
System.out.println("Month: " + (date1.getMonth() + 1)); // 0-based
to 1-based
System.out.println("Day: " + date1.getDay());

System.out.println("\nDate 2:");
System.out.println("Year: " + date2.getYear());
System.out.println("Month: " + (date2.getMonth() + 1)); // 0-based
to 1-based
System.out.println("Day: " + date2.getDay());
}
}

Q2)
import java.util.*;

public class sixlab2 {


public static void main(String[] args)
{
// ArrayList demonstration
System.out.println("ArrayList Demo:");
ArrayList<String> indianTeamPlayers = new ArrayList<>();
indianTeamPlayers.add("MS Dhoni");
indianTeamPlayers.add("Ravindra Jadeja");
indianTeamPlayers.add("Shardul Thakur");
indianTeamPlayers.add("Ruturaj Gaikwad");

// Traversing using Iterator


Iterator<String> arrayListIterator = indianTeamPlayers.iterator();
System.out.println("ArrayList elements using Iterator:");
while (arrayListIterator.hasNext())
{
System.out.println(arrayListIterator.next());
}

// LinkedList demonstration
System.out.println("\nLinkedList Demo:");
LinkedList<String> carsBrand = new LinkedList<>();
carsBrand.add("Range Rover");
carsBrand.add("M.G.");
carsBrand.add("Jeep");
carsBrand.add("Ford");

// Traversing using ListIterator (forwards)


ListIterator<String> linkedListIterator =
carsBrand.listIterator();
System.out.println("LinkedList elements using ListIterator
(forwards):");
while (linkedListIterator.hasNext())
{
System.out.println(linkedListIterator.next());
}

// Traversing using ListIterator (backwards)


System.out.println("LinkedList elements using ListIterator
(backwards):");
while (linkedListIterator.hasPrevious())
{
System.out.println(linkedListIterator.previous());
}

// Set demonstration (HashSet)


System.out.println("\nHashSet Demo:");
Set<String> colours = new HashSet<>();
colours.add("Yellow");
colours.add("Blue");
colours.add("Pink");
colours.add("Green");

// Traversing using Iterator


Iterator<String> hashSetIterator = colours.iterator();
System.out.println("HashSet elements using Iterator:");
while (hashSetIterator.hasNext())
{
System.out.println(hashSetIterator.next());
}

// Demonstrating Collections class methods


System.out.println("\nCollections Class Demo:");
// Sorting the ArrayList
Collections.sort(indianTeamPlayers);
System.out.println("Sorted ArrayList: " + indianTeamPlayers);

// Reversing the LinkedList


Collections.reverse(carsBrand);
System.out.println("Reversed LinkedList: " + carsBrand);

// Shuffling the ArrayList


Collections.shuffle(indianTeamPlayers);
System.out.println("Shuffled ArrayList: " + indianTeamPlayers);

// Finding max and min in a List


System.out.println("Max in ArrayList: " +
Collections.max(indianTeamPlayers));
System.out.println("Min in ArrayList: " +
Collections.min(indianTeamPlayers));

// Frequency of an element
indianTeamPlayers.add("Apple"); // Adding "Apple" to demonstrate
frequency
System.out.println("Frequency of 'Apple' in ArrayList: " +
Collections.frequency(indianTeamPlayers, "Apple"));
}
}

EXPERIMENT 8
Q1)
class A {
// Default constructor for class A
public A() {
System.out.println("Constructor of Class A");
}
}

class B {
// Default constructor for class B
public B() {
System.out.println("Constructor of Class B");
}
}

class C extends A {
// Class C inherits from A and has a member of class B
B b = new B(); // Composition: an object of class B is created inside
class C

// No constructor for class C is defined, so the default constructor


is used
}
public class sevenlab1 {
public static void main(String[] args) {
// Create an object of class C
C cObject = new C();
}
}

Q2)
class Base {
// Non-default constructor in Base class
public Base(String message) {
System.out.println("Base class constructor called with message: "
+ message);
}
}

// Derived class
class Derived extends Base {
// Default (no-arg) constructor for Derived class
public Derived() {
super("Default call from Derived"); // Calling the base class
constructor
System.out.println("Derived class no-arg constructor called");
}

// Non-default constructor for Derived class


public Derived(String message) {
super(message); // Calling the base class constructor with the
passed message
System.out.println("Derived class constructor called with message:
" + message);
}
}

public class sevenlab2 {


public static void main(String[] args) {
// Create an object using the default constructor of Derived class
System.out.println("Creating object using default constructor:");
Derived obj1 = new Derived();

// Create an object using the non-default constructor of Derived


class
System.out.println("\nCreating object using non-default
constructor:");
Derived obj2 = new Derived("Custom message from Derived");
}
}

Q3)
class BaseClass {
// First overloaded method
public void display(int a) {
System.out.println("BaseClass display method with int argument: "
+ a);
}

// Second overloaded method


public void display(double a) {
System.out.println("BaseClass display method with double argument:
" + a);
}

// Third overloaded method


public void display(String message) {
System.out.println("BaseClass display method with String argument:
" + message);
}
}

// Derived class that inherits BaseClass


class DerivedClass extends BaseClass {
// New overloaded method in the derived class
public void display(boolean flag) {
System.out.println("DerivedClass display method with boolean
argument: " + flag);
}
}

public class sevenlab3 {


public static void main(String[] args) {
// Create an object of DerivedClass
DerivedClass derivedObj = new DerivedClass();

// Call all four versions of the display() method


derivedObj.display(10); // Calls the method with int
argument
derivedObj.display(3.14); // Calls the method with double
argument
derivedObj.display("Hello World"); // Calls the method with String
argument
derivedObj.display(true); // Calls the method with
boolean argument
}
}

Q4)
class FinalMethodClass {
// Final method that cannot be overridden
public final void display() {
System.out.println("This is a final method in FinalMethodClass.");
}
}
// Derived class that attempts to override the final method
class ChildClass extends FinalMethodClass {
// Uncommenting the following method will cause a compile-time error
/*
@Override
public void display() {
System.out.println("Trying to override the final method.");
}
*/
}

// Final class that cannot be inherited


final class FinalClass {
public void show() {
System.out.println("This is a method in a final class.");
}
}

// Attempting to inherit from a final class will cause a compile-time


error
/*
class SubClass extends FinalClass {
// Inheriting from FinalClass is not allowed
}
*/

public class sevenlab4 {


public static void main(String[] args) {
// Create an object of the DerivedClass
ChildClass derivedObj = new ChildClass();
derivedObj.display(); // Call the final method

// Create an object of the FinalClass


FinalClass finalClassObj = new FinalClass();
finalClassObj.show(); // Call the method in final class
}
}
EXPERIMENT 8
Q1)package Exp8.Program1.Child;

import Exp8.Program1.Parent.NotificationDriver;

public class EmailNotification extends NotificationDriver


{
private String message = "Deloitte: NLA | Congratulations on coming
one step closer to discovering your impact with Deloitte!";

public void send()


{
System.out.println("Gmail : ");
System.out.println(message);
}
}

package Exp8.Program1.Child;

import Exp8.Program1.Parent.NotificationDriver;

public class SmsNotification extends NotificationDriver


{
private String message = "From AD-FLPKRT, Your order is shipped
successfully.";

public void send()


{
System.out.println("SMS Notification : ");
System.out.println(message);
}
}

package Exp8.Program1.Parent;
import Exp8.Program1.Child.SmsNotification;

public class NotificationDriver


{
public static void main(String[] args)
{
SmsNotification sms = new SmsNotification();
sms.send();
}
}
Q2)
package Exp8.Program2.Appliances;

public interface ApplianceControl


{
void turnOn();
void turnOff();
}

EXPERIMENT 9
Q1)
class OuterClass {

// Private field in the outer class


private String outerField = "Initial Value";

// Private method in the outer class


private void privateMethod() {
System.out.println("Private method in OuterClass called.");
}

// Public method in the outer class to demonstrate the inner class


modifying the private field and method
public void modifyUsingInnerClass() {
// Create an instance of the inner class
program_1 inner = new program_1();
// Call the inner class method that modifies the outer class
inner.modifyOuter();
// Show the result
System.out.println("Outer field after modification: " +
outerField);
}
public class program_1{
public void modifyOuter() {
// Modify the outer class's private field
outerField = "Modified Value";
// Call the outer class's private method
privateMethod();
}
}

// Main method to test the code


public static void main(String[] args) {
OuterClass outer = new OuterClass();
System.out.println("Outer field before modification: " +
outer.outerField);
outer.modifyUsingInnerClass();
}
}
Q2)
class OuterClass {
// An inner class
class InnerClass {
// Private member of InnerClass
private int secretValue = 42;

// Public method in InnerClass to provide controlled access


public int getSecretValue() {
return secretValue;
}
}

// Method in OuterClass attempting to access InnerClass's private


member
public void showSecret() {
InnerClass inner = new InnerClass();

// Uncommenting the line below will cause a compilation error


// because secretValue is private in InnerClass
// System.out.println("Secret Value: " + inner.secretValue);

// Accessing the value via a public method of InnerClass


System.out.println("Accessing via public method: " +
inner.getSecretValue());
}
}

public class Main {


public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.showSecret();
}
}

EXPERIMENT 10
Q1)

public class Program1 {


public static void main(String[] args) {
try {
// Throwing an exception with a message
throw new CustomException("This is a custom exception
message.");
} catch (CustomException e) {
// Catching the exception and printing its message
System.out.println("Caught Exception: " + e.getMessage());
} finally {
// Finally block to prove it executes
System.out.println("Inside finally block: Cleanup can be done
here.");
}
}
}
class CustomException extends Exception {
// Constructor accepting a string message
public CustomException(String message) {
super(message); // Pass the message to the superclass (Exception)
}
}

Q2)
class CustomException extends Exception {
// Private field to store the message
private String message;

// Constructor that takes a string argument


public CustomException(String message) {
this.message = message; // Store the message in the object
}

// Method to display the stored string


public void displayMessage() {
System.out.println("Exception Message: " + message);
}
}

public class Program2 {


public static void main(String[] args) {
try {
// Throwing an instance of CustomException with a custom
message
throw new CustomException("This is a custom exception
message.");
} catch (CustomException e) {
// Catching the exception and displaying the stored message
e.displayMessage();
}
}
}

You might also like