0% found this document useful (0 votes)
4 views482 pages

Java 2

The document discusses various types of errors in Java programming, including compile-time errors (lexical, syntax, semantic), runtime errors (linkage, stack overflow, out of memory), and default exception handling. It provides examples of each error type, demonstrating how they occur and the corresponding output messages. Additionally, it covers predefined exceptions such as checked exceptions, including end-of-file and file not found exceptions.
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)
4 views482 pages

Java 2

The document discusses various types of errors in Java programming, including compile-time errors (lexical, syntax, semantic), runtime errors (linkage, stack overflow, out of memory), and default exception handling. It provides examples of each error type, demonstrating how they occur and the corresponding output messages. Additionally, it covers predefined exceptions such as checked exceptions, including end-of-file and file not found exceptions.
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

1 / 482

2 / 482
3 / 482
4 / 482
5 / 482
6 / 482
7 / 482
8 / 482
9 / 482
10 / 482
11 / 482
12 / 482
13 / 482
14 / 482
15 / 482
16 / 482
17 / 482
18 / 482
19 / 482
20 / 482
21 / 482
22 / 482
23 / 482
24 / 482
25 / 482
26 / 482
27 / 482
28 / 482
29 / 482
30 / 482
31 / 482
32 / 482
33 / 482
34 / 482
35 / 482
36 / 482
37 / 482
38 / 482
39 / 482
40 / 482
41 / 482
42 / 482
43 / 482
44 / 482
45 / 482
46 / 482
47 / 482
48 / 482
49 / 482
50 / 482
51 / 482
52 / 482
53 / 482
54 / 482
55 / 482
56 / 482
57 / 482
58 / 482
59 / 482
60 / 482
61 / 482
62 / 482
63 / 482
64 / 482
65 / 482
66 / 482
67 / 482
68 / 482
69 / 482
70 / 482
71 / 482
72 / 482
73 / 482

0'<'
74 / 482

0'<'
75 / 482
76 / 482
77 / 482
78 / 482
79 / 482
80 / 482
81 / 482
82 / 482
83 / 482
84 / 482
85 / 482
86 / 482
87 / 482
88 / 482
89 / 482
90 / 482
91 / 482
92 / 482
93 / 482
94 / 482
95 / 482
96 / 482
97 / 482
98 / 482
99 / 482
100 / 482
101 / 482
102 / 482
103 / 482
104 / 482
105 / 482
106 / 482
107 / 482
108 / 482
109 / 482
110 / 482
111 / 482
112 / 482
113 / 482
114 / 482
115 / 482
116 / 482
117 / 482
118 / 482
119 / 482
120 / 482
121 / 482
122 / 482
123 / 482
124 / 482
125 / 482
126 / 482
127 / 482
128 / 482
129 / 482
130 / 482
131 / 482
132 / 482
133 / 482
134 / 482
135 / 482
136 / 482
137 / 482
138 / 482
139 / 482
140 / 482
141 / 482
142 / 482
143 / 482
144 / 482
145 / 482
146 / 482
147 / 482
148 / 482
149 / 482
150 / 482
151 / 482
152 / 482
153 / 482
154 / 482
155 / 482
156 / 482
157 / 482
158 / 482
159 / 482
160 / 482
161 / 482
162 / 482
163 / 482
164 / 482
165 / 482
166 / 482
167 / 482
168 / 482
169 / 482
170 / 482
171 / 482
172 / 482
173 / 482
174 / 482
175 / 482
176 / 482
177 / 482
178 / 482
179 / 482
180 / 482
181 / 482
182 / 482
183 / 482
184 / 482
185 / 482
186 / 482
187 / 482
188 / 482
189 / 482
190 / 482
191 / 482
192 / 482
193 / 482
194 / 482
195 / 482
196 / 482
197 / 482
198 / 482
199 / 482
200 / 482
201 / 482
202 / 482
203 / 482
204 / 482
205 / 482
206 / 482
207 / 482
208 / 482
209 / 482
210 / 482
211 / 482
212 / 482
213 / 482
214 / 482
215 / 482
216 / 482
217 / 482
218 / 482
219 / 482
220 / 482
221 / 482
222 / 482
223 / 482
224 / 482
225 / 482
226 / 482
227 / 482
228 / 482
229 / 482
230 / 482
231 / 482
232 / 482
233 / 482
234 / 482
235 / 482
236 / 482
237 / 482
238 / 482
239 / 482
240 / 482
241 / 482
242 / 482
243 / 482
244 / 482
245 / 482
246 / 482
247 / 482
248 / 482
249 / 482
250 / 482
251 / 482
252 / 482
253 / 482
254 / 482
255 / 482
256 / 482
257 / 482
258 / 482
259 / 482
260 / 482
261 / 482
262 / 482
263 / 482
264 / 482
265 / 482
266 / 482
267 / 482
268 / 482
269 / 482
270 / 482
271 / 482
272 / 482
273 / 482
274 / 482
275 / 482
276 / 482
277 / 482
278 / 482
279 / 482
280 / 482
281 / 482
282 / 482
283 / 482
284 / 482
285 / 482
286 / 482
287 / 482
288 / 482
289 / 482
290 / 482
291 / 482
292 / 482
293 / 482
294 / 482
295 / 482
296 / 482
297 / 482
298 / 482
299 / 482
300 / 482
301 / 482
302 / 482
303 / 482
304 / 482
305 / 482
306 / 482
307 / 482
308 / 482
309 / 482
310 / 482
311 / 482
312 / 482
313 / 482
314 / 482
315 / 482
316 / 482
317 / 482
318 / 482
319 / 482
320 / 482
321 / 482
322 / 482
323 / 482
324 / 482
325 / 482
326 / 482
327 / 482
328 / 482
329 / 482

EXCEPTION HANDLING

ERROR:
Compile Time Error:
1) Lexical Error:

class LE
{
public static void main(String[] args)
{
int i=10;
nit j=20;
[Link](+i,+j);
}
}

Output:
>javac [Link]
[Link]: error: cannot find symbol
nit j=20;
^
symbol: class nit
location: class LE
1 error

2) Syntax Error:

class SE
{
public static void main(String[] args)
{
int i=10;
j int =20;
[Link](+i,+j);
}
}
330 / 482

Output:

javac [Link]
[Link]: error: not a statement
j int =20;
^
[Link]: error: ';' expected
j int =20;
^

3) Semantic Error:

class SEE
{
public static void main(String[] args)
{
int i=10;
boolean b = true;
char c= i+b;
[Link](+c);
}
}

>javac [Link]
[Link]: error: bad operand types for binary operator '+'
char c= i+b;
^
first type: int
second type: Boolean

4)Variable might not have been initialization

public class UninitializedVariable


{

public static void main(String[] args) {


331 / 482

int x;
int y;

[Link](x);

y = 5;
[Link](y);
}
}

Output:

>javac [Link]
[Link]: error: variable x might not have been
initialized
[Link](x);
^

5)Possible Loss of Precision

public class LossOfPrecisions


{

public static void main(String[] args) {


int intValue = 1000;

// Explicit casting to byte, acknowledging the possible loss of


precision
byte byteValue = (byte) intValue;

[Link](byteValue);
}
}

Output:

-24
332 / 482

RunTime Error:

6) Linkage Error

class LE
{
public static void main(String[] args)
{
[Link]("hello csmb");
}
}

Output:

java LE
Error: LinkageError occurred while loading main class LE
[Link]: Incompatible magic value 71528292 in
class file LE

7) StackOverFlow Error

class SOE
{
public static void m1()
{
m2();
}
333 / 482

public static void m2()


{
m1();
}
public static void main(String[] args)
{
m1();
}
}

Output:

java SOE
Exception in thread "main" [Link]
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
334 / 482

at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
at SOE.m2([Link])
at SOE.m1([Link])
continues

8) Out Of Memory Error

public class OOM


{

public static void main(String[] args)


{
try {
// Intentionally allocate more memory than the JVM can handle
int arraySize = Integer.MAX_VALUE;
335 / 482

int[] largeArray = new int[arraySize];


}
catch (OutOfMemoryError e)
{
[Link]("OutOfMemoryError: " + [Link]());
[Link]();
}
}
}

Output:

java OOM
OutOfMemoryError: Requested array size exceeds VM limit
[Link]: Requested array size exceeds VM limit
at [Link]([Link])

9) Default Exception Handling:

class DEH
{
public static void main(String[] args)
{
doStuff();
}
336 / 482

public static void doStuff()


{
domoreStuff();
}
public static void domoreStuff()
{
[Link](10/0);
}
}

Output:
java DEH
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
at [Link]([Link])
at [Link]([Link])

Exception Handling:

1) Pre-Defined / Built – in Exceptions :

A)Checked Exception:

10)End Of File Exception:

import [Link];
import [Link];
337 / 482

import [Link];
import [Link];

public class EOF1 {


public static void main(String[] args)
{

String filePath = "C://Users//Shanti//Desktop//csmb java


lab//ExceptionHandling//CheckedExceptions//[Link]";

ObjectInputStream objectInputStream = new ObjectInputStream(new


FileInputStream(filePath));

Object obj = [Link](); // This line may throw


EOFException
[Link]("Read object: " + obj);
}

}
Output:
javac [Link]
[Link]: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown. ^
[Link]: error: unreported exception IOException; must be caught or
declared to be thrown

11) File Not Found Exception


338 / 482

import [Link];
import [Link];
import [Link];
import [Link];

public class FNF1 {


public static void main(String[] args)
{

String filePath = "C://Users//Shanti//Desktop//csmb java


lab//ExceptionHandling//CheckedExceptions//[Link]";

ObjectInputStream objectInputStream = new ObjectInputStream(new


FileInputStream(filePath));

Object obj = [Link]();


[Link]("Read object: " + obj);
}
}

Output:
javac [Link]
[Link]: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown. ^
[Link]: error: unreported exception IOException; must be caught or
declared to be thrown.

12) SQL Exception


339 / 482

import [Link].*;

public class SQL


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

String mysqlUrl = "jdbc:mysql://localhost:3306/yourmysqldatabase";


String mysqlUsername = "yourmysqlusername";
String mysqlPassword = "yourmysqlpassword";
Connection mysqlConnection =
[Link](mysqlUrl, mysqlUsername, mysqlPassword);
String mysqlQuery = "SELECT * FROM yourmysqltable";
PreparedStatement mysqlStatement =
[Link](mysqlQuery);
ResultSet mysqlResultSet = [Link]();
while ([Link]())
{
[Link]("MySQL Data: " +
[Link]("column_name"));
}
}
}

Output:

javac [Link]
340 / 482

[Link]: error: unreported exception SQLException; must be caught or


declared to be thrown. ^
[Link]: error: unreported exception SQLException; must be caught or
declared to be thrown ^
[Link]: error: unreported exception SQLException; must be caught or
declared to be thrown ^
[Link]: error: unreported exception SQLException; must be caught or
declared to be thrown ^
[Link]: error: unreported exception SQLException; must be caught or
declared to be thrown

13) Parse Exception

import [Link];
import [Link];

public class PE1


{

public static void main(String[] args)


{
String dateString = "-12-05";

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-


dd");
Date parsedDate = [Link](dateString);
[Link]("Parsed Date: " + parsedDate);
}
341 / 482

}
Output:
javac [Link]
[Link]: error: unreported exception ParseException; must be caught or
declared to be thrown

14) Interrupted Exception

class IE
{
public static void main(String[] args)
{
[Link](1000);
}
}
Output:
javac [Link]
[Link]: error: unreported exception InterruptedException; must be caught or
declared to be thrown
[Link](1000);

B) UnChecked Exception:

15)Arithmetic Exception
class DEH
{
public static void main(String[] args)
342 / 482

{
doStuff();
}
public static void doStuff()
{
domoreStuff();
}
public static void domoreStuff()
{
[Link](10/0);
}
}

Output:
java AE
Exception in thread "main" [Link]: / by zero
at [Link]([Link])

16)Null Pointer Exception

public class NPE {


public static void main(String[] args) {
String str = null;
int length = [Link]();
[Link]("Length of the string: " + length);
}
}
343 / 482

Output:
>java NPE
Exception in thread "main" [Link]: Cannot invoke
"[Link]()" because "<local1>" is null
at [Link]([Link])

17) Class Cast Exception

class A
{
}
class B extends A
{
}
class CCE
{
public static void main(String[] args)
{
A a = new A();
B b =(B)a;
}
}

Output:
java CCE
Exception in thread "main" [Link]: class A cannot be
cast to class B (A and B are in unnamed module of loader 'app')
344 / 482

at [Link]([Link])

18) String Out Of Bound Exception

public class SIOBE1{


public static void main(String[] args) {

String str = "Hello";


char character = [Link](10);
[Link]("Character at index 10: " + character);
}
}

Output:
java SIOBE
StringIndexOutOfBoundsException caught: String index out of range: 10

19)Array Index Out Of Bounds Exception

public class AIOBE1 {


public static void main(String[] args) {

int[] array = {1, 2, 3};


int element = array[5];
[Link]("Element at index 5: " + element);
}
}
345 / 482

Output:
java AIOBE1
Exception in thread "main" [Link]: Index
5 out of bounds for length 3
at [Link]([Link])

Try-Catch for Checked Exceptions:

20)File Not Found Exception Handling

import [Link];
import [Link];
import [Link];

public class FNF {


public static void main(String[] args) {
// Provide a file path that doesn't exist to simulate FileNotFoundException
String filePath = "C://Users//Shanti//Desktop//csmb java
lab//ExceptionHandling//CheckedExceptions//[Link]";

try (FileInputStream fileInputStream = new FileInputStream(filePath)) {


// Additional code for reading from the file can go here
[Link]("File opened successfully.");
} catch (FileNotFoundException e) {
[Link]("FileNotFoundException caught: " + [Link]());
} catch (IOException e) {
[Link]("IOException caught: " + [Link]());
346 / 482

[Link]("Program continues after handling


FileNotFoundException.");
}
}

Output:
javac [Link]

C:\Users\Shanti\Desktop\csmb java
lab\throwable\ExceptionHandling\CheckedExceptions>java FNF
FileNotFoundException caught: C:\Users\Shanti\Desktop\csmb java
lab\ExceptionHandling\CheckedExceptions\[Link] (The system cannot
find the path specified)
Program continues after handling FileNotFoundException.

21) SQL Exceptin Handling:

import [Link].*;

public class MultiDatabaseExceptionHandling {


public static void main(String[] args) {
try {
// Attempt to connect to MySQL database
String mysqlUrl = "jdbc:mysql://localhost:3306/yourmysqldatabase";
String mysqlUsername = "yourmysqlusername";
String mysqlPassword = "yourmysqlpassword";
347 / 482

Connection mysqlConnection =
[Link](mysqlUrl, mysqlUsername, mysqlPassword);

// Attempt to execute a SQL query on MySQL database


String mysqlQuery = "SELECT * FROM yourmysqltable";
try (PreparedStatement mysqlStatement =
[Link](mysqlQuery);
ResultSet mysqlResultSet = [Link]()) {

// Process MySQL ResultSet (replace this with your actual processing


logic)
while ([Link]()) {
[Link]("MySQL Data: " +
[Link]("column_name"));
}

// Close MySQL connection


[Link]();
}
} catch (SQLException mysqlException) {
// Handle MySQL exception
[Link]("MySQL Exception caught: " +
[Link]());

// Attempt to read data from Oracle database in the catch block


try {
// Connect to Oracle database
String oracleUrl =
"jdbc:oracle:thin:@youroracledb:1521:youroracledbsid";
348 / 482

String oracleUsername = "youroracleusername";


String oraclePassword = "youroraclepassword";
Connection oracleConnection =
[Link](oracleUrl, oracleUsername, oraclePassword);

// Execute a SQL query on Oracle database


String oracleQuery = "SELECT * FROM youroracletable";
try (PreparedStatement oracleStatement =
[Link](oracleQuery);
ResultSet oracleResultSet = [Link]()) {

// Process Oracle ResultSet (replace this with your actual


processing logic)
while ([Link]()) {
[Link]("Oracle Data: " +
[Link]("column_name"));
}

// Close Oracle connection


[Link]();
}
} catch (SQLException oracleException) {
// Handle Oracle exception
[Link]("Oracle Exception caught: " +
[Link]());
}
}
}
}
349 / 482

Try-Catch For Unchecked Exception:

22) Arithmetic Exception Handling:


public class AEH
{
public static void main(String[] args)
{

try
{

[Link](10/0);
}
catch (ArithmeticException e)
{
[Link](10/2);

}
}

Output:
java AEH
5
contiued after handling exception
350 / 482

23)String Index Out Of Bounds Exception:

public class SIOBE{


public static void main(String[] args) {
try {
// Attempting to access a character at an index that is out of bounds
String str = "Hello";
char character = [Link](10); // This line will throw
StringIndexOutOfBoundsException
[Link]("Character at index 10: " + character);
} catch (StringIndexOutOfBoundsException e) {
[Link]("StringIndexOutOfBoundsException caught: " +
[Link]());
}

[Link]("Program continues after handling


StringIndexOutOfBoundsException.");
}
}

Output:
java SIOBE
StringIndexOutOfBoundsException caught: String index out of range: 10
Program continues after handling StringIndexOutOfBoundsException.

Try With Multiple Catch :


351 / 482

24) Arithmetic Exception Handling:

import [Link];
import [Link];

public class TryWithMultipleCatch {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

try {
[Link]("Enter a number: ");
int numerator = [Link]();

[Link]("Enter another number: ");


int denominator = [Link]();

int result = divide(numerator, denominator);


[Link]("Result of division: " + result);
} catch (InputMismatchException e) {
[Link]("Error: Please enter valid integers for numerator and
denominator.");
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero. Please enter a non-
zero denominator.");
} catch (Exception e) {
[Link]("An unexpected error occurred: " + [Link]());
}
352 / 482

[Link]();
}

private static int divide(int numerator, int denominator) {


return numerator / denominator;
}
}

Output:
>java TryWithMultipleCatch
Enter a number: 4
Enter another number: 7
Result of division: 0

>java TryWithMultipleCatch
Enter a number: 2
Enter another number: g
Error: Please enter valid integers for numerator and denominator.

>java TryWithMultipleCatch
Enter a number: 6
Enter another number: 0
Error: Cannot divide by zero. Please enter a non-zero denominator.

Finally:
25) finally block to close FILE:
353 / 482

import [Link];
import [Link];
import [Link];

public class Finally1 {


public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;

try {

String inputFilePath = "[Link]";

String outputFilePath = "[Link]";

fis = new FileInputStream(inputFilePath);


fos = new FileOutputStream(outputFilePath);

int byteData;
while ((byteData = [Link]()) != -1) {
[Link](byteData);
}
354 / 482

[Link]("File copied successfully!");


} catch (IOException e) {
[Link]("Error: " + [Link]());
} finally {

try {
if (fis != null) {
[Link]();
}
if (fos != null) {
[Link]();
}
} catch (IOException e) {
[Link]("Error closing streams: " + [Link]());
}
}
}
}

Throw:

25) throw – UserDefined Exception:

class InsufficientBalanceException extends Exception


{
public InsufficientBalanceException(String message)
355 / 482

{
super(message);
}
}
class ATM {
private double balance = 1000;
public void withdraw(double amount)
{
try {
if (amount > balance)
{
throw new InsufficientBalanceException("Insufficient balance to
withdraw " + amount);
}
balance -= amount;
[Link]("Withdrawal successful! Remaining balance: " +
balance);
} catch (InsufficientBalanceException e) {
[Link]("Error: " + [Link]());
}
}
}
public class throw1
{
public static void main(String[] args)
{
ATM atm = new ATM();
[Link](1500);
356 / 482

}
}

Output:
java throw1
Error: Insufficient balance to withdraw 1500.0

Throws:

25)throws with checked methods:


import [Link];
import [Link];

public class FileOutput2


{

public static void main(String[] args)throws IOException


{
String filePath = "C:/Users/Shanti/Desktop/csmb java lab/[Link]";

FileOutputStream file = new FileOutputStream(filePath,true);

String data = "Hello,csmd.";


byte[] byteData = [Link]();
[Link](byteData);
357 / 482

[Link]("Data has been written to the file.");


[Link]();

}
}
Output:
java FileOutput2
Data has been written to the file.

26) throws with throw (UserDefined Exception):

public class MobileNumberValidator {


public static void main(String[] args) {
try {
validateMobileNumber("9885089465");
validateMobileNumber("98567890121");
validateMobileNumber("88664433");
validateMobileNumber("98ab@123");
} catch (InvalidArrayIndexException e) {
[Link]("InvalidArrayIndexOutofBounds Exception: " +
[Link]());
} catch (LengthNotSufficientException e) {
[Link]("Invalid LengthNotSufficientException: " +
[Link]());
} catch (NumberFormatException e) {
358 / 482

[Link]("InvalidNumberFormatException: " +
[Link]());
}
}

static void validateMobileNumber(String mobileNumber)


throws InvalidArrayIndexException, LengthNotSufficientException,
NumberFormatException {
if ([Link]() > 10) {
throw new InvalidArrayIndexException("Exceeds length of 10");
} else if ([Link]() < 10) {
throw new LengthNotSufficientException("Less than length of 10");
}

if (![Link]("\\d+")) {
throw new NumberFormatException("Contains non-digit characters");
}

[Link]("Valid number");
}
}

class InvalidArrayIndexException extends Exception {


public InvalidArrayIndexException(String message) {
super(message);
}
}
359 / 482

class LengthNotSufficientException extends Exception {


public LengthNotSufficientException(String message) {
super(message);
}
}

Output:
Valid number
InvalidArrayIndexOutofBounds Exception: Exceeds length of 10

Try_With_Resources

27) import [Link];


import [Link];
import [Link];
import [Link];
import [Link];

public class TryWithResources


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

String inputFile = "[Link]";


String outputFile = "[Link]";
360 / 482

try {

copyFile(inputFile, outputFile);
[Link]("File copied successfully!");
} catch (IOException e)
{
[Link]("Error: " + [Link]());
}
}

private static void copyFile(String inputFile, String outputFile) throws


IOException {

try (BufferedReader reader = new BufferedReader(new


FileReader(inputFile));
PrintWriter writer = new PrintWriter(new FileWriter(outputFile)))
{

String line;
while ((line = [Link]()) != null)
{
[Link](line);
}

}
361 / 482

}
}

Multi Catch Block

27)Multi catch block

public class MultiCatch


{
public static void main(String[] args)
{
try {
int[] numbers = {1, 2, 3};
int result = numbers[4] / 0;
[Link]("Result: " + result);
}
catch (ArrayIndexOutOfBoundsException | ArithmeticException e)
{
[Link]("Caught exception: " + [Link]().getSimpleName() + " - "
+ [Link]());
}
}
}
362 / 482
363 / 482
364 / 482
365 / 482
366 / 482
367 / 482
368 / 482
369 / 482
370 / 482
371 / 482
372 / 482
373 / 482
374 / 482
375 / 482
376 / 482
377 / 482
378 / 482
379 / 482
380 / 482
381 / 482
382 / 482
383 / 482
384 / 482
385 / 482
386 / 482
387 / 482
388 / 482
389 / 482
390 / 482
391 / 482

1) Synchronized Block with <this=

class SharedResource

int counter = 0;

synchronized void increment()

for (int i = 0; i < 5; i++)

[Link]([Link]().getName() + " incremented counter to: " +


(++counter));

class IncrementThread extends Thread

SharedResource sharedResource;

public IncrementThread(SharedResource sharedResource)

[Link] = sharedResource;

public void run()

[Link]();

public class SyncBlockThis


392 / 482

public static void main(String[] args)

SharedResource sharedResource = new SharedResource();

// Creating multiple threads to increment the counter

Thread t1 = new IncrementThread(sharedResource);

Thread t2 = new IncrementThread(sharedResource);

// Starting threads

[Link]();

[Link]();

Output:

Thread-0 incremented counter to: 1

Thread-0 incremented counter to: 2

Thread-0 incremented counter to: 3

Thread-0 incremented counter to: 4

Thread-0 incremented counter to: 5

Thread-1 incremented counter to: 6

Thread-1 incremented counter to: 7

Thread-1 incremented counter to: 8

Thread-1 incremented counter to: 9

Thread-1 incremented counter to: 10


393 / 482

2) Synchronized Block with Particular Object

class SharedResource

int counter = 0;

final Object lock = new Object();

void increment()

// Non-critical section

synchronized (lock)

for (int i = 0; i < 5; i++)

[Link]([Link]().getName() + " incremented counter to: " +


(++counter));

// Non-critical section

class IncrementThread extends Thread

SharedResource sharedResource;

public IncrementThread(SharedResource sharedResource)

[Link] = sharedResource;
394 / 482

public void run()

[Link]();

public class SyncBlockObject

public static void main(String[] args)

SharedResource sharedResource = new SharedResource();

// Creating multiple threads to increment the counter

Thread t1 = new IncrementThread(sharedResource);

Thread t2 = new IncrementThread(sharedResource);

// Starting threads

[Link]();

[Link]();

Output:

Thread-0 incremented counter to: 1

Thread-0 incremented counter to: 2

Thread-0 incremented counter to: 3

Thread-0 incremented counter to: 4

Thread-0 incremented counter to: 5


395 / 482

Thread-1 incremented counter to: 6

Thread-1 incremented counter to: 7

Thread-1 incremented counter to: 8

Thread-1 incremented counter to: 9

Thread-1 incremented counter to: 10

3) Synchronized Block with Class

class SharedResource

static int counter = 0;

public static void increment()

synchronized ([Link])

for (int i = 0; i < 5; i++)

[Link]([Link]().getName() + " incremented counter to: " +


(++counter));

class IncrementThread extends Thread

public void run()

[Link]();

}
396 / 482

public class SyncBlockClass

public static void main(String[] args)

// Creating multiple threads to increment the counter

Thread t1 = new IncrementThread();

Thread t2 = new IncrementThread();

// Starting threads

[Link]();

[Link]();

Output:

Thread-0 incremented counter to: 1

Thread-0 incremented counter to: 2

Thread-0 incremented counter to: 3

Thread-0 incremented counter to: 4

Thread-0 incremented counter to: 5

Thread-1 incremented counter to: 6

Thread-1 incremented counter to: 7

Thread-1 incremented counter to: 8

Thread-1 incremented counter to: 9

Thread-1 incremented counter to: 10


397 / 482

4) With Out Synchronization

class SharedResource

int counter = 0;

public void increment()

for (int i = 0; i < 5; i++)

int currentValue = counter;

// Simulating some processing time

try

[Link](1000);

catch (InterruptedException e)

[Link]();

counter = currentValue + 1;

[Link]([Link]().getName() + " incremented counter to: " +


counter);

class IncrementThread extends Thread

private SharedResource sharedResource;

public IncrementThread(SharedResource sharedResource)


398 / 482

[Link] = sharedResource;

public void run()

[Link]();

public class WithOutSync

public static void main(String[] args)

SharedResource sharedResource = new SharedResource();

// Creating multiple threads to increment the counter

Thread t1 = new IncrementThread(sharedResource);

Thread t2 = new IncrementThread(sharedResource);

// Starting threads

[Link]();

[Link]();

Output:

Thread-0 incremented counter to: 1

Thread-0 incremented counter to: 2

Thread-0 incremented counter to: 3


399 / 482

Thread-0 incremented counter to: 4

Thread-0 incremented counter to: 5

Thread-1 incremented counter to: 6

Thread-1 incremented counter to: 7

Thread-1 incremented counter to: 8

Thread-1 incremented counter to: 9

Thread-1 incremented counter to: 10

5) Creating Multiple Threads

class SharedResource

public synchronized void printMessage(String message)

for (int i = 0; i < 5; i++)

// Simulating some processing time

try

[Link](1000);

catch (InterruptedException e)

[Link]();

[Link]([Link]().getName() + ": " + message);

}
400 / 482

class WorkerThread extends Thread

private SharedResource sharedResource;

private String message;

public WorkerThread(SharedResource sharedResource, String message)

[Link] = sharedResource;

[Link] = message;

public void run()

[Link](message);

public class MultipleThreads

public static void main(String[] args)

SharedResource sharedResource = new SharedResource();

// Creating multiple threads to perform work

Thread t1 = new WorkerThread(sharedResource, "Working on Task A");

Thread t2 = new WorkerThread(sharedResource, "Working on Task B");

Thread t3 = new WorkerThread(sharedResource, "Working on Task C");

// Starting threads

[Link]();
401 / 482

[Link]();

[Link]();

// Waiting for all threads to complete

try {

[Link]();

[Link]();

[Link]();

catch (InterruptedException e)

[Link]();

class SharedResource

public synchronized void printMessage(String message)

for (int i = 0; i < 5; i++)

// Simulating some processing time

try

[Link](1000);

catch (InterruptedException e)

[Link]();

[Link]([Link]().getName() + ": " + message);


402 / 482

class WorkerThread extends Thread

private SharedResource sharedResource;

private String message;

public WorkerThread(SharedResource sharedResource, String message)

[Link] = sharedResource;

[Link] = message;

public void run()

[Link](message);

public class MultipleThreads

public static void main(String[] args)

SharedResource sharedResource = new SharedResource();

// Creating multiple threads to perform work

Thread t1 = new WorkerThread(sharedResource, "Working on Task A");

Thread t2 = new WorkerThread(sharedResource, "Working on Task B");

Thread t3 = new WorkerThread(sharedResource, "Working on Task C");


403 / 482

// Starting threads

[Link]();

[Link]();

[Link]();

// Waiting for all threads to complete

try {

[Link]();

[Link]();

[Link]();

catch (InterruptedException e)

[Link]();

Output:

Thread-0: Working on Task A

Thread-0: Working on Task A

Thread-0: Working on Task A

Thread-0: Working on Task A

Thread-0: Working on Task A

Thread-1: Working on Task B

Thread-1: Working on Task B

Thread-1: Working on Task B

Thread-1: Working on Task B


404 / 482

Thread-1: Working on Task B

Thread-2: Working on Task C

Thread-2: Working on Task C

Thread-2: Working on Task C

Thread-2: Working on Task C

Thread-2: Working on Task C

6) isAlive()

public class Alive1 extends Thread

public void run()

for (int i = 0; i < 5; i++)

[Link](" child Working...");

public static void main(String[] args)throws InterruptedException

Alive1 t = new Alive1();

// Check if the thread is alive

[Link]("Is the thread alive? " + [Link]());

// Start the thread

[Link]();
405 / 482

for (int i = 0; i < 5; i++)

[Link]("main Working...");

// Check again after the thread has finished

[Link]("Is the thread alive? " + [Link]());

Output:

Is the thread alive? false

main Working...

main Working...

main Working...

main Working...

child Working...

child Working...

main Working...

child Working...

child Working...

Is the thread alive? true

child Working...
406 / 482
407 / 482
408 / 482
409 / 482
410 / 482
411 / 482
412 / 482
413 / 482
414 / 482
415 / 482
416 / 482
417 / 482
418 / 482
419 / 482
420 / 482
421 / 482
422 / 482
423 / 482
424 / 482
425 / 482
426 / 482

Collections Framework:

Collection:
List:
1) ArrayList:

import [Link].*;
public class ArrayList1
{
public static void main(String args[]){
ArrayList<Integer> a=new ArrayList<Integer>();
[Link](a);
[Link](34);
[Link](0,78);
[Link](a);
[Link](5);
[Link]("Size:"+[Link]());
[Link](19);
[Link](24);
[Link](36);
[Link](48);
[Link](57);
[Link](63);
[Link](72);
[Link](86);
[Link](94);
[Link]("Size:"+[Link]());
// we cant get "capacity" for ArrayList
[Link](a);
[Link]([Link](7));
[Link]([Link](48));
[Link]([Link](1,10));
[Link](a);
[Link]([Link](5));
[Link](a);
[Link]([Link](a));
[Link](a);
}
427 / 482

Output:

[]
[78, 34]
Size:3
Size:12
[78, 34, 5, 19, 24, 36, 48, 57, 63, 72, 86, 94]
57
true
34
[78, 10, 5, 19, 24, 36, 48, 57, 63, 72, 86, 94]
36
[78, 10, 5, 19, 24, 48, 57, 63, 72, 86, 94]
true
[]

2) Vector

import [Link].*;
public class Vector1
{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
[Link](v);
[Link]("Ayush");
[Link](0,"Ashish");
[Link](v);
[Link]("a");
[Link]("Size:"+[Link]());
[Link]("Capacity:"+[Link]());
428 / 482

[Link]("b");
[Link]("c");
[Link]("d");
[Link]("e");
[Link]("g");
[Link]("g");
[Link]("h");
[Link]("x");
[Link]("y");
[Link]("Size:"+[Link]());
[Link]("Capacity:"+[Link]());
[Link](v);
[Link]([Link](5));
[Link]([Link]("t"));
[Link]([Link](1,"y"));
[Link](v);
[Link]([Link](5));
[Link](v);
[Link]([Link]("g"));
[Link](v);
[Link]([Link](v));
[Link](v);
}
}
429 / 482

Output:

[]
[Ashish, Ayush]
Size:3
Capacity:10
Size:12
Capacity:20
[Ashish, Ayush, a, b, c, d, e, g, g, h, x, y]
d
false
Ayush
[Ashish, y, a, b, c, d, e, g, g, h, x, y]
d
[Ashish, y, a, b, c, e, g, g, h, x, y]
true
[Ashish, y, a, b, c, e, g, h, x, y]
true
[]

3) Stack

import [Link].*;
public class Stack1
{
public static void main(String args[]){
430 / 482

Stack<Integer> a=new Stack<Integer>();


[Link](a);
[Link](34);
[Link](0,78);
[Link](a);
[Link](5);
[Link]("Size:"+[Link]());
[Link]("Capacity:"+[Link]());
[Link](19);
[Link](24);
[Link](36);
[Link](48);
[Link](57);
[Link](63);
[Link](72);
[Link](86);
[Link](94);
[Link]("Size:"+[Link]());
[Link]("Capacity:"+[Link]());
[Link](a);
[Link]([Link](7));
[Link]([Link](48));
[Link]([Link](1,10));
[Link](a);
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
431 / 482

// we cant place certain value in pop method because top element only removed.
[Link](a);
[Link]([Link](5));
[Link]([Link](78));
[Link]([Link](a));
[Link](a);
}
}

Output:

[]
[78, 34]
Size:3
Capacity:10
Size:12
Capacity:20
[78, 34, 5, 19, 24, 36, 48, 57, 63, 72, 86, 94]
57
true
34
[78, 10, 5, 19, 24, 36, 48, 57, 63, 72, 86, 94]
94
86
72
[78, 10, 5, 19, 24, 36, 48, 57, 63, 72]
8
432 / 482

0
true
[]

4) LinkedList

import [Link].*;
public class LinkedList1
{
public static void main(String args[]){
LinkedList<String> v=new LinkedList<String>();
[Link](v);
[Link]("r");
[Link](0,"e");
[Link](v);
[Link]("a");
[Link]("Size:"+[Link]());
[Link]("b");
[Link]("c");
[Link]("d");
[Link]("e");
[Link]("g");
[Link]("g");
[Link]("h");
[Link]("x");
[Link]("y");
433 / 482

[Link]("Size:"+[Link]());
[Link](v);
[Link]([Link](5));
[Link]([Link]("t"));
[Link]([Link](1,"y"));
[Link](v);
[Link]([Link](5));
[Link](v);
[Link]([Link]("g"));
[Link](v);
[Link]([Link](v));
[Link](v);
}
}

Output:

[]
[e, r]
Size:3
Size:12
[e, r, a, b, c, d, e, g, g, h, x, y]
d
false
r
[e, y, a, b, c, d, e, g, g, h, x, y]
d
434 / 482

[e, y, a, b, c, e, g, g, h, x, y]
true
[e, y, a, b, c, e, g, h, x, y]
true
[]

Map:

5)HashMap

import [Link].*;
public class HashMap1
{
public static void main(String args[]){
HashMap<Integer,String> h=new HashMap<Integer,String>();
[Link](h);
[Link](1,"r");
[Link](2,"e");
[Link](h);
[Link](3,"a");
[Link]("Size:"+[Link]());
[Link](5,"b");
[Link](7,"c");
[Link](8,"d");
[Link](23,"e");
[Link](23,"e");
[Link](23,"z");
435 / 482

[Link](56,"g");
[Link](34,"g");
[Link](32,"h");
[Link](18,"x");
[Link](29,"y");
[Link]("Size:"+[Link]());
[Link](h);
[Link]([Link](23));// 23 is key to get regarding value
[Link]([Link](56));
[Link]([Link]("e"));
[Link](h);
[Link]();
[Link](h);

//The clear method in HashMap does not return a value


//(it has a return type of void),
//so you cannot directly use it as an argument to [Link]().
}
}

Output:

{}
{1=r, 2=e}
Size:3
Size:12
{32=h, 1=r, 2=e, 34=g, 18=x, 3=a, 5=b, 7=c, 23=z, 8=d, 56=g, 29=y}
436 / 482

z
true
true
{32=h, 1=r, 2=e, 34=g, 18=x, 3=a, 5=b, 7=c, 23=z, 8=d, 56=g, 29=y}
{}

6)LinkedHashMap

import [Link].*;
public class LinkedHashMap1
{
public static void main(String args[]){
LinkedHashMap<Integer,String> a=new LinkedHashMap<Integer,String>();
[Link](a);
[Link](34,"a");
[Link](5,"b");
[Link]("Size:"+[Link]());
[Link](19,"c");
[Link](24,"d");
[Link](36,"e");
[Link](48,"f");
[Link](57,"g");
[Link](63,"h");
[Link](72,"i");
[Link](a);
[Link]("Size:"+[Link]());
[Link](a);
437 / 482

[Link]([Link](57));
[Link](a);
}
}

Output:

{}
Size:2
{34=a, 5=b, 19=c, 24=d, 36=e, 48=f, 57=g, 63=h, 72=i}
Size:9
{34=a, 5=b, 19=c, 24=d, 36=e, 48=f, 57=g, 63=h, 72=i}
g
{34=a, 5=b, 19=c, 24=d, 36=e, 48=f, 63=h, 72=i}

7) TreeMap

import [Link].*;
public class TreeMap1
{
public static void main(String args[]){
TreeMap<Integer,String> a=new TreeMap<Integer,String>();
[Link](a);
[Link](34,"a");
[Link](5,"b");
[Link]("Size:"+[Link]());
[Link](78,"c");
438 / 482

[Link](3,"g");
[Link](8,"e");
[Link](7,"v");
[Link](12,"r");
[Link](1,"q");
[Link](72,"m");
[Link](a);
[Link](86,"p");
[Link](94,"z");
//values are displayed as sorted order . not in a specified way
[Link]("Size:"+[Link]());
[Link](a);
[Link]([Link](12));
[Link](a);
}
}

Output:

{}
Size:2
{1=q, 3=g, 5=b, 7=v, 8=e, 12=r, 34=a, 72=m, 78=c}
Size:11
{1=q, 3=g, 5=b, 7=v, 8=e, 12=r, 34=a, 72=m, 78=c, 86=p, 94=z}
r
{1=q, 3=g, 5=b, 7=v, 8=e, 34=a, 72=m, 78=c, 86=p, 94=z}
439 / 482

Set

8) HashSet

import [Link].*;
public class HashSet1
{
public static void main(String args[]){
HashSet<Integer> a=new HashSet<Integer>();
[Link](a);
[Link](34);
[Link](5);
[Link]("Size:"+[Link]());
[Link](19);
[Link](24);
[Link](36);
[Link](48);
[Link](57);
[Link](63);
[Link](72);
[Link](a);
[Link](72);
// try to duplicate.
[Link](a);// 72 is not stored again.
[Link](86);
[Link](94);
//values are displayed as random order . not in a specified way
440 / 482

[Link]("Size:"+[Link]());
[Link]([Link](48));
[Link](a);
[Link]([Link](57));
[Link](a);
}
}

Output:

[]
Size:2
[48, 34, 19, 36, 5, 24, 72, 57, 63]
[48, 34, 19, 36, 5, 24, 72, 57, 63]
Size:11
true
[48, 34, 19, 36, 5, 86, 24, 72, 57, 94, 63]
true
[48, 34, 19, 36, 5, 86, 24, 72, 94, 63]

9) LinkedHashSet

import [Link].*;
public class LinkedHashSet1
{
public static void main(String args[]){
LinkedHashSet<Integer> a=new LinkedHashSet<Integer>();
441 / 482

[Link](a);
[Link](34);
[Link](5);
[Link]("Size:"+[Link]());
[Link](19);
[Link](24);
[Link](36);
[Link](48);
[Link](57);
[Link](63);
[Link](72);
[Link](a);
//It follows the insertion order .
[Link]("Size:"+[Link]());
[Link]([Link](48));
[Link](a);
[Link]([Link](57));
[Link](a);
}
}

Output:
[]
Size:2
[34, 5, 19, 24, 36, 48, 57, 63, 72]
Size:9
true
442 / 482

[34, 5, 19, 24, 36, 48, 57, 63, 72]


true
[34, 5, 19, 24, 36, 48, 63, 72]

10) TreeSet

import [Link].*;
public class TreeSet1
{
public static void main(String args[]){
TreeSet<Integer> a=new TreeSet<Integer>();
[Link](a);
[Link](34);
[Link](5);
[Link]("Size:"+[Link]());
[Link](5);
[Link](3);
[Link](8);
[Link](7);
[Link](12);
[Link](1);
[Link](72);
[Link](a);
[Link](72);
// try to duplicate.
[Link](a);// 72 is not stored again.
[Link](86);
443 / 482

[Link](94);
//values are displayed as sorted order . not in a specified way
[Link]("Size:"+[Link]());
[Link]([Link](48));
[Link](a);
[Link]([Link](57));
[Link](a);
}
}

Output:

[]
Size:2
[1, 3, 5, 7, 8, 12, 34, 72]
[1, 3, 5, 7, 8, 12, 34, 72]
Size:10
false
[1, 3, 5, 7, 8, 12, 34, 72, 86, 94]
false
[1, 3, 5, 7, 8, 12, 34, 72, 86, 94]

Queue:

11)Priority Queue
444 / 482

import [Link].*;
public class PriorityQueue1
{
public static void main(String args[]){
PriorityQueue<Integer> a=new PriorityQueue<Integer>();
[Link](a);
[Link](34);
[Link](a);
[Link](5);
[Link]("Size:"+[Link]());
[Link](19);
[Link](24);
[Link](36);
[Link](48);
[Link](57);
[Link](63);
[Link](72);
[Link](86);
[Link](94);
[Link]("Size:"+[Link]());
//the interger which is small that has highest
//priority that is stored in "head/front".
//remaining all stored in random order.
[Link](a);
[Link]([Link](48));
[Link]([Link](5));
//5 is least element deleted.
445 / 482

//then searching performed the small integer now is 19


//so 19 placed at "head"
[Link](a);
[Link]([Link]());
// displayed the "front " element then deleted.
[Link](a);
[Link]([Link](a));
[Link](a);
}
}

Output:

[]
[34]
Size:2
Size:11
[5, 24, 19, 34, 36, 48, 57, 63, 72, 86, 94]
true
true
[19, 24, 48, 34, 36, 94, 57, 63, 72, 86]
19
[24, 34, 48, 63, 36, 94, 57, 86, 72]
true
[]
446 / 482

12) Array Deque

import [Link].*;
public class ArrayDeque1
{
public static void main(String args[]){
ArrayDeque<Integer> a=new ArrayDeque<Integer>();
[Link](a);
[Link](34);
[Link](5);
[Link]("Size:"+[Link]());
[Link](19);
[Link](24);
[Link](36);
[Link](48);
[Link](57);
[Link](63);
[Link](72);
[Link](32);
[Link](86);
[Link](59);
[Link](64);
[Link](19);
[Link](94);
[Link]("Size:"+[Link]());
[Link](a);
[Link]([Link](48));
447 / 482

[Link]([Link](59));
[Link](a);
[Link]([Link]());
[Link]([Link]());
[Link](a);
[Link]([Link]());
// displayed the "front " element then deleted.
[Link]([Link]());
[Link]([Link]());
[Link](a);
[Link]([Link]());
// displayed the first element
[Link]([Link]());
[Link]([Link]());
//displayed the last element
[Link](a);
[Link]([Link](a));
[Link](a);
}
}

Output:

[]
Size:2
Size:15
448 / 482

[59, 86, 63, 57, 34, 5, 19, 24, 36, 48, 72, 32, 64, 19, 94]
true
true
[86, 63, 57, 34, 5, 19, 24, 36, 48, 72, 32, 64, 19, 94]
86
94
[63, 57, 34, 5, 19, 24, 36, 48, 72, 32, 64, 19]
63
57
19
[34, 5, 19, 24, 36, 48, 72, 32, 64]
34
34
64
[34, 5, 19, 24, 36, 48, 72, 32, 64]
true
[]

13)LinkedList

import [Link].*;
public class LinkedList2
{
public static void main(String args[]){
LinkedList<String> a=new LinkedList<String>();
[Link](a);
[Link]("a");
449 / 482

[Link]("b");
[Link]("Size:"+[Link]());
[Link]("c");
[Link]("d");
[Link]("f");
[Link]("g");
[Link]("h");
[Link]("i");
[Link]("j");
[Link]("k");
[Link]("l");
[Link]("m");
[Link]("n");
[Link]("o");
[Link]("p");
[Link]("Size:"+[Link]());
//stored in a specified order.
[Link](a);
[Link]([Link]("k"));
[Link]([Link]("i"));
[Link](a);
[Link]([Link]());
[Link]([Link]());
[Link](a);
[Link]([Link]());
// displayed the "front " element then deleted.
[Link]([Link]());
450 / 482

[Link]([Link]());
[Link](a);
[Link]([Link]());
// displayed the first element
[Link]([Link]());
[Link]([Link]());
//displayed the last element
[Link](a);
[Link]([Link](a));
[Link](a);
}
}

Output:
[]
Size:2
Size:15
[m, l, i, h, a, b, c, d, f, g, j, k, n, o, p]
true
true
[m, l, h, a, b, c, d, f, g, j, k, n, o, p]
m
p
[l, h, a, b, c, d, f, g, j, k, n, o]
l
h
o
451 / 482

[a, b, c, d, f, g, j, k, n]
a
a
n
[a, b, c, d, f, g, j, k, n]
true
[]
452 / 482

1. Sample Case study on class & objects CO1


Bank Account Management System:
Problem Statement: Design a system to manage bank accounts.
Classes: Account, Savings-Account, Current-Account.
Attributes: Account number, balance, account type, interest rate (for savings account),
overdraft limit (for current account), etc.
Methods: Deposit, Withdraw, Calculate Interest, Transfer, etc.
Object Usage: Create objects for each customer's account and perform transactions like
deposits, withdrawals, and transfers.

import [Link];

// Base class: Account


class Account {
protected String accountNumber;
protected double balance;

public Account(String accountNumber, double balance) {


[Link] = accountNumber;
[Link] = balance;
}

public void displayBalance() {


[Link]("Account Number: " + accountNumber);
[Link]("Balance: " + balance);
}

public void deposit(double amount) {


balance += amount;
[Link]("Deposited: " + amount);
}

public void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
[Link]("Withdrawn: " + amount);
} else {
[Link]("Insufficient balance!");
}
}

public void transfer(Account targetAccount, double amount) {


if (balance >= amount) {
[Link](amount);
[Link](amount);
453 / 482

[Link]("Transferred: " + amount + " to Account: " +


[Link]);
} else {
[Link]("Transfer failed due to insufficient balance.");
}
}
}

// Derived class: SavingsAccount


class SavingsAccount extends Account {
private double interestRate;

public SavingsAccount(String accountNumber, double balance, double interestRate) {


super(accountNumber, balance);
[Link] = interestRate;
}

public void calculateInterest() {


double interest = balance * (interestRate / 100);
balance += interest;
[Link]("Interest added: " + interest);
}
}

// Derived class: CurrentAccount


class CurrentAccount extends Account {
private double overdraftLimit;

public CurrentAccount(String accountNumber, double balance, double overdraftLimit) {


super(accountNumber, balance);
[Link] = overdraftLimit;
}

@Override
public void withdraw(double amount) {
if (balance + overdraftLimit >= amount) {
balance -= amount;
[Link]("Withdrawn: " + amount);
} else {
[Link]("Overdraft limit exceeded!");
}
}
}

// Main class to test the implementation


public class BankAccountManagement {
454 / 482

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Creating Savings Account


SavingsAccount savings = new SavingsAccount("S123", 5000, 5);
[Link]();

// Deposit amount dynamically


[Link]("Enter deposit amount for Savings Account: ");
double depositAmount = [Link]();
[Link](depositAmount);

[Link]();

// Withdraw amount dynamically


[Link]("Enter withdrawal amount for Savings Account: ");
double withdrawAmount = [Link]();
[Link](withdrawAmount);

[Link]();

[Link]();

// Creating Current Account


CurrentAccount current = new CurrentAccount("C456", 3000, 1000);
[Link]();

// Deposit amount dynamically


[Link]("Enter deposit amount for Current Account: ");
depositAmount = [Link]();
[Link](depositAmount);

// Withdraw amount dynamically


[Link]("Enter withdrawal amount for Current Account: ");
withdrawAmount = [Link]();
[Link](withdrawAmount);

[Link]();

[Link]();

// Transfer from Savings to Current Account dynamically


[Link]("Enter transfer amount from Savings to Current Account: ");
double transferAmount = [Link]();
[Link](current, transferAmount);
455 / 482

[Link]();
[Link]();

[Link]();
}
}

output:
---------
Account Number: S123
Balance: 5000.0
Enter deposit amount for Savings Account: 5000
Deposited: 5000.0
Interest added: 500.0
Enter withdrawal amount for Savings Account: 6700
Withdrawn: 6700.0
Account Number: S123
Balance: 3800.0

Account Number: C456


Balance: 3000.0
Enter deposit amount for Current Account: 6000
Deposited: 6000.0
Enter withdrawal amount for Current Account: 5600
Withdrawn: 5600.0
Account Number: C456
Balance: 3400.0

Enter transfer amount from Savings to Current Account: 5000


Transfer failed due to insufficient balance.
Account Number: S123
Balance: 3800.0
Account Number: C456
Balance: 3400.0
----------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------

1. Sample Java program to check whether the given number is prime palindrome or
not.

import [Link];

public class PrimePalindrome {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
456 / 482

[Link]("Enter a number: ");


int number = [Link]();

if (isPrime(number) && isPalindrome(number)) {


[Link](number + " is a prime palindrome.");
} else {
[Link](number + " is not a prime palindrome.");
}
}

public static boolean isPrime(int num) {


if (num <= 1) return false;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) return false;
}
return true;
}

public static boolean isPalindrome(int num) {


int original = num;
int reverse = 0;

while (num != 0) {
int digit = num % 10;
reverse = reverse * 10 + digit;
num /= 10;
}

return original == reverse;


}
}
output:
---------
Enter a number: 12121
12121 is not a prime palindrome.

C:\Users\Shanti\Desktop>java PrimePalindrome
Enter a number: 7
7 is a prime palindrome.

-------------------------------------------------------------------------------------------
457 / 482

2. Write a java program which reads marks of five subjects through command line and
print the total and average.

public class MarksCalculator {


public static void main(String[] args) {
if ([Link] != 5) {
[Link]("Please enter marks for five subjects.");
return;
}

int total = 0;
for (String arg : args) {
total += [Link](arg);
}

double average = total / 5.0;

[Link]("Total Marks: " + total);


[Link]("Average Marks: " + average);
}
}

output:
-----------
java MarksCalculator
Please enter marks for five subjects.

java MarksCalculator 34 56 78 97 65
Total Marks: 330
Average Marks: 66.0
--------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------

3. Classes and Objects

Design a “farm animals” java application with the details of animals like cow, pig,
horse.
Consider the following details like where they stay, what they eat, the sound they make
by using classes and objects

// Base class Animal


class Animal {
String name;
String habitat;
String food;
458 / 482

String sound;

// Constructor
Animal(String name, String habitat, String food, String sound) {
[Link] = name;
[Link] = habitat;
[Link] = food;
[Link] = sound;
}

// Method to display animal details


void displayDetails() {
[Link]("Animal: " + name);
[Link]("Habitat: " + habitat);
[Link]("Food: " + food);
[Link]("Sound: " + sound);
[Link]();
}
}

// Cow class extending Animal


class Cow extends Animal {
Cow() {
super("Cow", "Barn", "Grass", "Moo");
}
}

// Pig class extending Animal


class Pig extends Animal {
Pig() {
super("Pig", "Sty", "Vegetables", "Oink");
}
}

// Horse class extending Animal


class Horse extends Animal {
Horse() {
super("Horse", "Stable", "Hay", "Neigh");
}
}

public class FarmAnimals {


public static void main(String[] args) {
// Create objects of each animal
Cow cow = new Cow();
Pig pig = new Pig();
459 / 482

Horse horse = new Horse();

// Display details of each animal


[Link]();
[Link]();
[Link]();
}
}
output:
----------
Animal: Cow
Habitat: Barn
Food: Grass
Sound: Moo

Animal: Pig
Habitat: Sty
Food: Vegetables
Sound: Oink

Animal: Horse
Habitat: Stable
Food: Hay
Sound: Neigh
----------------------------------------------------------------------------------------

// Base class: Order


460 / 482

class Order {
String date;
int number;

// Constructor for Order


Order(String date, int number) {
[Link] = date;
[Link] = number;
}

// Method to confirm the order


void confirm() {
[Link]("Order " + number + " confirmed on " + date);
}

// Method to close the order


void close() {
[Link]("Order " + number + " is closed.");
}
}

// Subclass: SpecialOrder linked to Order


class SpecialOrder extends Order {

// Constructor for SpecialOrder


SpecialOrder(String date, int number) {
super(date, number);
}

// Method to dispatch the order


void dispatch() {
[Link]("Special Order " + number + " dispatched on " + date);
}

@Override
void confirm() {
[Link]("Special Order " + number + " confirmed on " + date);
}

@Override
void close() {
[Link]("Special Order " + number + " is closed.");
}
}

// Subclass: NormalOrder linked to Order


461 / 482

class NormalOrder extends Order {


String status;

// Constructor for NormalOrder


NormalOrder(String date, int number, String status) {
super(date, number);
[Link] = status;
}

// Method to dispatch the order


void dispatch() {
[Link]("Normal Order " + number + " dispatched with status: " + status);
}

// Method to receive the order


void receive() {
[Link]("Normal Order " + number + " received.");
}

@Override
void confirm() {
[Link]("Normal Order " + number + " confirmed on " + date);
}

@Override
void close() {
[Link]("Normal Order " + number + " is closed.");
}
}

// Class: Customer
class Customer {
String name;
String location;

// Constructor for Customer


Customer(String name, String location) {
[Link] = name;
[Link] = location;
}

// Method to send an order


void sendOrder() {
[Link](name + " from " + location + " has sent an order.");
}
462 / 482

// Method to receive an order


void receiveOrder() {
[Link](name + " from " + location + " has received the order.");
}
}

// Main class to test the implementation


public class classdiagram {
public static void main(String[] args) {
// Create a customer
Customer customer = new Customer("Alice", "New York");

// Customer sends an order


[Link]();

// Create a special order


SpecialOrder specialOrder = new SpecialOrder("2024-09-08", 101);
[Link]();
[Link]();
[Link]();

// Create a normal order


NormalOrder normalOrder = new NormalOrder("2024-09-08", 102, "In Progress");
[Link]();
[Link]();
[Link]();
[Link]();

// Customer receives the order


[Link]();
}
}

Output
Alice from New York has sent an order.
Special Order 101 confirmed on 2024-09-08
Special Order 101 dispatched on 2024-09-08
Special Order 101 is closed.
Normal Order 102 confirmed on 2024-09-08
Normal Order 102 dispatched with status: In Progress
Normal Order 102 received.
Normal Order 102 is closed.
Alice from New York has received the order.
463 / 482

5. Constructor overloading

An organization is maintaining the data of employee according to cadre of employee


with following parameters: name, id, designation, salary, promotion status. Apply the
constructor overloading to implement it.

public class Employee {


private String name;
private int id;
private String designation;
private double salary;
private boolean promotionStatus;

// Constructor for regular employees


public Employee(String name, int id, double salary) {
[Link] = name;
[Link] = id;
[Link] = "Employee";
[Link] = salary;
[Link] = false;
}

// Constructor for managers


public Employee(String name, int id, double salary, boolean promotionStatus) {
[Link] = name;
[Link] = id;
[Link] = "Manager";
[Link] = salary;
[Link] = promotionStatus;
}

// Constructor for executives


public Employee(String name, int id, double salary, boolean promotionStatus, String
designation) {
[Link] = name;
[Link] = id;
[Link] = designation;
[Link] = salary;
[Link] = promotionStatus;
}

public static void main(String[] args) {


// Example usage of the Employee class with different constructors
Employee regularEmployee = new Employee("John Doe", 1001, 50000.0);
Employee manager = new Employee("Jane Smith", 2001, 80000.0, true);
464 / 482

Employee executive = new Employee("Robert Johnson", 3001, 120000.0, true,


"Executive");

// Displaying employee information


displayEmployeeInformation(regularEmployee);
displayEmployeeInformation(manager);
displayEmployeeInformation(executive);
}

// Method to display employee information


private static void displayEmployeeInformation(Employee employee) {
[Link]("Employee Information:");
[Link]("Name: " + [Link]);
[Link]("ID: " + [Link]);
[Link]("Designation: " + [Link]);
[Link]("Salary: " + [Link]);
[Link]("Promotion Status: " + [Link]);
[Link]();
}
}

Output:
Employee Information:
Name: John Doe
ID: 1001
Designation: Employee
Salary: 50000.0
Promotion Status: false

Employee Information:
Name: Jane Smith
ID: 2001
Designation: Manager
Salary: 80000.0
Promotion Status: true

Employee Information:
Name: Robert Johnson
ID: 3001
Designation: Executive
Salary: 120000.0
Promotion Status: true
465 / 482

6. Strings
Write a program to find the longest Substring without Repeating Characters
Input: abcabcbb
output:3 string: abc
Input: pwwkew
output:3 string: wke
Note: pwke is not a substring , it is a subsequence

public class LongestSubstring


{
public static void findLongestSubstring(String s)
{
int maxLength = 0;
int start = 0;
int startIndex = 0;

for (int end = 0; end < [Link](); end++)


{
char currentChar = [Link](end);

for (int i = start; i < end; i++)


{
if ([Link](i) == currentChar)
{
start = i + 1;
break;
}
}

if (end - start + 1 > maxLength)


{
maxLength = end - start + 1;
startIndex = start;
}
}

String longestSubstring = [Link](startIndex, startIndex + maxLength);


[Link]("Longest Substring: " + longestSubstring);
[Link]("Length of Longest Substring: " + maxLength);
}

public static void main(String[] args) {


String input1 = "abcabcbb";
[Link]("Input: " + input1);
findLongestSubstring(input1);
466 / 482

String input2 = "pwwkew";


[Link]("\nInput: " + input2);
findLongestSubstring(input2);
}
}

Output:
Input: abcabcbb
Longest Substring: abc
Length of Longest Substring: 3

Input: pwwkew
Longest Substring: wke
Length of Longest Substring: 3

7. Method overriding

All the banks operating in India are controlled by RBI. (e.g. minimum interest rate,
minimum balance allowed, maximum withdrawal limit etc) which all banks must
follow. For example, suppose RBI has set minimum interest rate applicable to a saving
bank account to be 4% annually. however, banks are free to use 4% interest rate or to
set any rates above it. Write a JAVA program to implement bank functionality in the
above scenario and demonstrate the dynamic polymorphism concept. Note: Create few
classes namely Customer, Account, RBI (Base Class) and few derived classes (SBI,
ICICI, PNB etc). Assume and implement required member variables and functions in
each class.
Testcase1: Enter the Bank name to find the rate of Interest : RBI
RBI rate of interest is : 4%
Testcase2: Enter the Bank name to find the rate of Interest : SBI
RBI rate of interest is : 7%

import [Link];

// Base class RBI


class RBI {
// Default interest rate set by RBI
protected double interestRate = 4.0;

public double getInterestRate() {


return interestRate;
}
}

// Derived classes with specific interest rates


class SBI extends RBI {
@Override
467 / 482

public double getInterestRate() {


return 5.0;
}
}

class ICICI extends RBI {


@Override
public double getInterestRate() {
return 6.0;
}
}

class PNB extends RBI {


@Override
public double getInterestRate() {
return 4.5;
}
}

// Class to represent a customer


class Customer {
private String name;

public Customer(String name) {


[Link] = name;
}

public String getName() {


return name;
}
}

// Class to represent an account


class Account {
private Customer customer;
private RBI bank;

public Account(Customer customer, RBI bank) {


[Link] = customer;
[Link] = bank;
}

public void displayInterestRate() {


[Link]([Link]() + "'s Bank: " +
[Link]().getSimpleName());
[Link]("Interest Rate: " + [Link]() + "%\n");
468 / 482

}
}

public class BankDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Create instances of customers


Customer customer = new Customer("John");

// Create instances of different banks


RBI rbi = new RBI();
RBI sbi = new SBI();
RBI icici = new ICICI();
RBI pnb = new PNB();

// Create and display accounts for different banks


new Account(customer, rbi).displayInterestRate();
new Account(customer, sbi).displayInterestRate();

[Link]("Enter the Bank name to find the rate of Interest (RBI, SBI, ICICI,
PNB): ");
String bankName = [Link]().toUpperCase();

// Demonstrate dynamic polymorphism


switch (bankName) {
case "RBI":
new Account(customer, rbi).displayInterestRate();
break;
case "SBI":
new Account(customer, sbi).displayInterestRate();
break;
case "ICICI":
new Account(customer, icici).displayInterestRate();
break;
case "PNB":
new Account(customer, pnb).displayInterestRate();
break;
default:
[Link]("Invalid bank name.");
}

[Link]();
}
}
469 / 482

Output:
C:\Users\Shanti\Desktop>java BankDemo
John's Bank: RBI
Interest Rate: 4.0%

John's Bank: SBI


Interest Rate: 5.0%

Enter the Bank name to find the rate of Interest (RBI, SBI, ICICI, PNB): icici
John's Bank: ICICI
Interest Rate: 6.0%

8. Interfaces:

Different categories of employees are working in a software company like Regular


Employees, Contract Employees and Vendors. And their pay roll is different for regular
and contract employees. For the regular employees Basic pay is 25000, HRA is 15000rs
and TA is 5000. For the Contract employees Basic pay is 12000 TA is 3000rs and there
is no HRA. Find the monthly salary details of Employee. If input is Regular Employee
display the Regular employee salary details. If input is Contract based display the
Contract salary details.
TestCase1:
Input: Enter Employee Id: R101
Output: Salary Details: Basic Pay: 25000 HRA: 15000 T.A: 5000 Total Amount: 45000

import [Link];

// Define the interface for Salary


interface Salary {
void calculateSalary();
void displaySalary();
}

// Regular Employee class implementing Salary interface


class RegularEmployee implements Salary {
private static final int BASIC_PAY = 25000;
private static final int HRA = 15000;
private static final int TA = 5000;
private int totalAmount;

@Override
public void calculateSalary() {
totalAmount = BASIC_PAY + HRA + TA;
}

@Override
470 / 482

public void displaySalary() {


[Link]("Salary Details:");
[Link]("Basic Pay: " + BASIC_PAY);
[Link]("HRA: " + HRA);
[Link]("T.A: " + TA);
[Link]("Total Amount: " + totalAmount);
}
}

// Contract Employee class implementing Salary interface


class ContractEmployee implements Salary {
private static final int BASIC_PAY = 12000;
private static final int TA = 3000;
private int totalAmount;

@Override
public void calculateSalary() {
totalAmount = BASIC_PAY + TA;
}

@Override
public void displaySalary() {
[Link]("Salary Details:");
[Link]("Basic Pay: " + BASIC_PAY);
[Link]("T.A: " + TA);
[Link]("Total Amount: " + totalAmount);
}
}

public class EmployeeSalaryDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter Employee Id: ");


String employeeId = [Link]();

[Link]("Enter Employee Type (Regular/Contract): ");


String employeeType = [Link]().toLowerCase();

Salary employee;

if ([Link]("regular")) {
employee = new RegularEmployee();
} else if ([Link]("contract")) {
employee = new ContractEmployee();
} else {
471 / 482

[Link]("Invalid Employee Type.");


[Link]();
return;
}

[Link]();
[Link]();

[Link]();
}
}
Output:
Enter Employee Id: 678
Enter Employee Type (Regular/Contract): regular
Salary Details:
Basic Pay: 25000
HRA: 15000
T.A: 5000
Total Amount: 45000
Test Case-2:
Enter Employee Id: 897
Enter Employee Type (Regular/Contract): contract
Salary Details:
Basic Pay: 12000
T.A: 3000
Total Amount: 15000

9. Packages

Define a package number and in that define Roman class and implement
romanToInteger() and import the method in another class.
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

// File: number/[Link]
package number;

public class Roman {


// Method to convert Roman numeral to integer
public static int romanToInteger(String s) {
// Map Roman numerals to their integer values
int[] values = new int[256];
values['I'] = 1;
values['V'] = 5;
472 / 482

values['X'] = 10;
values['L'] = 50;
values['C'] = 100;
values['D'] = 500;
values['M'] = 1000;

int total = 0;
int prevValue = 0;

// Process each character from right to left


for (int i = [Link]() - 1; i >= 0; i--) {
char ch = [Link](i);
int value = values[ch];

if (value < prevValue) {


total -= value;
} else {
total += value;
}
prevValue = value;
}
return total;
}
}

// File: [Link] (default package or another package)


import [Link];

public class RomanConverter {


public static void main(String[] args) {
// Test the romanToInteger method
String romanNumeral = "LVIII";
int result = [Link](romanNumeral);

[Link]("Input: " + romanNumeral);


[Link]("Output: " + result);
}
}

Output:
javac number/[Link]
>javac [Link]
>java RomanConverter
Input: LVIII
Output: 58
473 / 482

10. File Handling

Write the below text in the file called [Link] and then find the frequency count of
the patterns ‘pe’, and ‘pi’ Peter Piper picked a peck of pickled peppers A peck of
pickled peppers Peter Piper picked If Peter Piper picked a peck of pickled peppers
Where’s the peck of pickled peppers Peter Piper picked?
Expected Output: ‘pe’ – no of occurrences - 20 ‘pi’ – no of occurrences – 12

import [Link];
import [Link];
import [Link];
import [Link];

public class PatternFrequencyCounter {

public static void main(String[] args) {


String fileName = "[Link]";
String content = "Peter Piper picked a peck of pickled peppers\n"
+ "A peck of pickled peppers Peter Piper picked\n"
+ "If Peter Piper picked a peck of pickled peppers\n"
+ "Where’s the peck of pickled peppers Peter Piper picked?";

// Create and write to the file


writeToFile(fileName, content);

// Read from the file and count occurrences


countOccurrences(fileName, "pe", "pi");
}

// Method to write content to a file


private static void writeToFile(String fileName, String content) {
try (FileWriter writer = new FileWriter(fileName)) {
[Link](content);
[Link]("Content written to file successfully.");
} catch (IOException e) {
[Link]();
}
}

// Method to count occurrences of patterns in the file


private static void countOccurrences(String fileName, String... patterns) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
int[] counts = new int[[Link]];

while ((line = [Link]()) != null) {


474 / 482

for (int i = 0; i < [Link]; i++) {


counts[i] += countOccurrencesInLine(line, patterns[i]);
}
}

// Print results
for (int i = 0; i < [Link]; i++) {
[Link]("'" + patterns[i] + "' – no of occurrences - " + counts[i]);
}

} catch (IOException e) {
[Link]();
}
}

// Helper method to count occurrences of a substring in a line


private static int countOccurrencesInLine(String line, String subStr) {
int count = 0;
int index = 0;

while ((index = [Link](subStr, index)) != -1) {


count++;
index += [Link](); // Move past the last occurrence
}

return count;
}
}
Output:
Content written to file successfully.
'pe' â?? no of occurrences - 16
'pi' â?? no of occurrences – 8

11. Exception Handling

Input a mobile number and check the given number is valid mobile number or not.
● A valid mobile number is a combination of (0-9) digits of length exactly 10.
● If the given Number Exceeds length of 10 raise Invalid Mobile
NumberArrayIndexOutofBounds Exception
● If the given Number less than the length of 10 raise Invalid Mobile Number –
LengthNotSufficientException
● If the given Number contain any character other than digit raise Invalid Mobile
Number –NumberFormatException
Sample Input
Expected Output – 1 9885089465 Valid number
98567890121 Invalid Mobile Number-ArrayIndexOutofBounds Exception
475 / 482

88664433 Invalid Mobile Number – LengthNotSufficientException


98ab@123 Invalid Mobile Number –NumberFormatException

public class MobileNumberValidator


{
public static void main(String[] args)
{
try {

validateMobileNumber("9885089465");
validateMobileNumber("98567890121");
validateMobileNumber("88664433");
validateMobileNumber("98ab@123");

}
catch (InvalidArrayIndexException e)
{
[Link]("InvalidArrayIndexOutofBounds Exception: " + [Link]());
}
catch (LengthNotSufficientException e)
{
[Link]("Invalid LengthNotSufficientException: " + [Link]());
}
catch (NumberFormatException e)
{
[Link]("InvalidNumberFormatException: " + [Link]());
}
}

static void validateMobileNumber(String mobileNumber)


throws InvalidArrayIndexException, LengthNotSufficientException,
NumberFormatException {
if ([Link]() > 10)
{
throw new InvalidArrayIndexException("Exceeds length of 10");
}
else if ([Link]() < 10)
{
throw new LengthNotSufficientException("Less than length of 10");
}

if (![Link]("\\d+"))
{
throw new NumberFormatException("Contains non-digit characters");
}
476 / 482

[Link]("Valid number");
}
}

class InvalidArrayIndexException extends Exception


{
public InvalidArrayIndexException(String message)
{
super(message);
}
}

class LengthNotSufficientException extends Exception


{
public LengthNotSufficientException(String message)
{
super(message);
}
}
//super(message), it calls the constructor of the Exception class (its superclass)
//and passes the specified message to it.
//The Exception class has a constructor that takes a message as an argument,
//and this message is typically used to provide
//additional information about the exception when it is thrown.

Output:
Valid number
InvalidArrayIndexOutofBounds Exception: Exceeds length of 10

12. Multi-Threading

Implement a Reservation system which allows the persons to book seats. Define reserve
method initially with 100 seats. Now create one or more person threads to book seats. At
any time it should allow only one person thread to access the reserve method.
Expected Output: Person-1 entered. Available seats: 10 Requested seats: 5 Seat
Available. Reserve now :-) 5 seats reserved. Person-1 leaving.
----------------------------------------------
Person-2 entered. Available seats: 5 Requested seats: 2 Seat Available. Reserve now :-) 2
seats reserved. Person-2 leaving.
----------------------------------------------
Person-3 entered. Available seats: 3 Requested seats: 4 Requested seats not available :-)
Person-3 leaving.
---------------------------------------------
477 / 482

class ReservationSystem
{
private static int availableSeats = 100;

public synchronized void reserve(String personName, int requestedSeats)


{
[Link](personName + " entered.");
[Link]("Available seats: " + availableSeats + " Requested seats: " +
requestedSeats);

if (availableSeats >= requestedSeats)


{
[Link]("Seat Available. Reserve now :-)");
availableSeats -= requestedSeats;
[Link](requestedSeats + " seats reserved.");
}
else
{
[Link]("Not enough seats available. Reservation failed.");
}

[Link](personName + " leaving.");


}
}

class PersonThread extends Thread


{
private ReservationSystem reservationSystem;
private String personName;
private int requestedSeats;

public PersonThread(ReservationSystem reservationSystem, String personName, int


requestedSeats) {
[Link] = reservationSystem;
[Link] = personName;
[Link] = requestedSeats;
}

@Override
public void run()
{
[Link](personName, requestedSeats);
}
}

public class ReservationSystemDemo


478 / 482

{
public static void main(String[] args)
{
ReservationSystem reservationSystem = new ReservationSystem();

// Create multiple PersonThread instances to simulate multiple persons trying to reserve


seats
PersonThread person1 = new PersonThread(reservationSystem, "Person-1", 5);
PersonThread person2 = new PersonThread(reservationSystem, "Person-2", 20);
PersonThread person3 = new PersonThread(reservationSystem, "Person-3", 10);
PersonThread person4 = new PersonThread(reservationSystem, "Person-4",
90);

// Start the threads


[Link]();
[Link]();
[Link]();
[Link]();
}
}

Output:
-----------
Person-1 entered.
Available seats: 100 Requested seats: 5
Seat Available. Reserve now :-)
5 seats reserved.
Person-1 leaving.
Person-4 entered.
Available seats: 95 Requested seats: 90
Seat Available. Reserve now :-)
90 seats reserved.
Person-4 leaving.
Person-3 entered.
Available seats: 5 Requested seats: 10
Not enough seats available. Reservation failed.
Person-3 leaving.
Person-2 entered.
Available seats: 5 Requested seats: 20
Not enough seats available. Reservation failed.
Person-2 leaving.
479 / 482

13. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter
combinations that the number could represent. A mapping of digit to letters (just like
on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example: Input: "23"


Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf”]

import [Link];
//It is used to store the resulting letter combinations.
import [Link];
//It is used to create a mapping between digits and their corresponding letters.
import [Link];
//It is used to represent a list of letter combinations.
import [Link];
//It is used to create a mapping between digits and their corresponding letters.

public class LetterCombinations


{
public static void main(String[] args)
{
List<String> result = letterCombinations("23");
[Link](result);
}

public static List<String> letterCombinations(String digits)


//takes a string of digits as input and returns a list of strings.

{
List<String> result = new ArrayList<>();
//Create a new ArrayList named result to store the resulting letter
combinations.

if (digits == null || [Link]() == 0)


{
//Check if the input string digits is either null or has a length of 0.
//If true, return an empty result list, as there are no digits to form
combinations.
return result;
}
480 / 482

// Create a mapping of digits to letters

Map<Character, String> digitToLetters = new HashMap<>();

//Create a HashMap named digitToLetters to map each digit to its


//corresponding set of letters.

//Populate the digitToLetters map with mappings for digits 2 through 9,


//representing the letters on a telephone keypad.

[Link]('2', "abc");
[Link]('3', "def");
[Link]('4', "ghi");
[Link]('5', "jkl");
[Link]('6', "mno");
[Link]('7', "pqrs");
[Link]('8', "tuv");
[Link]('9', "wxyz");

generateCombinations("", digits, 0, digitToLetters, result);

//generateCombinations method to start the recursive process of generating


//letter combinations.
//The initial state has an empty current combination, the input digits,
//starting index 0, the digit-to-letter mapping, and the result list.

return result; //Return the final list of letter combinations.


}

private static void generateCombinations(String current, String digits, int index,


Map<Character, String> digitToLetters, List<String> result)

//This method is responsible for recursively generating letter combinations.


{
if (index == [Link]())
{
[Link](current);
return;
}
// Get the letters associated with the current digit
char digit = [Link](index);
//Get the current digit at the specified index from the input string.
String letters = [Link](digit);
// Retrieve the corresponding set of letters
//for the current digit from the digit-to-letter mapping.
481 / 482

// Recursively generate combinations for the next digit


for (int i = 0; i < [Link](); i++)
{
// Iterate through each letter in the set of letters associated
//with the current digit.

generateCombinations(current + [Link](i), digits, index + 1, digitToLetters,


result);
//Recursively call generateCombinations with an updated current combination,
//the same input digits, an increased index, the digit-to-letter mapping,
//and the result list
}
}
}

Output:
[ad, ae, af, bd, be, bf, cd, ce, cf]

14. Arrays

Write a program to find the Valid Parentheses Given a string containing just the
characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string
is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open
brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Input: ( )
Output: valid
Input: ( { ) }
Output: Not valid

import [Link];

public class ValidParentheses


{
public static void main(String[] args)
{
[Link](isValid("()"));
[Link](isValid("({)}"));
}

public static boolean isValid(String s) {


// Create a stack to store open parentheses
Stack<Character> stack = new Stack<>();
482 / 482

// Iterate through each character in the string


for (char c : [Link]()) {
if (c == '(' || c == '{' || c == '[')
{
// If an open parenthesis is encountered, push it onto the stack
[Link](c);
}
else if (c == ')' && ![Link]() && [Link]() == '(')
{
// If a closing parenthesis is encountered and it matches with the top
//of the stack, pop it
[Link]();
}
else if (c == '}' && ![Link]() && [Link]() == '{')
{
// If a closing curly brace is encountered and it matches with the top
//of the stack, pop it
[Link]();
}
else if (c == ']' && ![Link]() && [Link]() == '[')
{
// If a closing square bracket is encountered and it matches with the top
//of the stack, pop it
[Link]();
}
else
{
// If none of the valid cases is met, the parentheses are not valid
return false;
}
}

// The parentheses are valid if the stack is empty at the end


return [Link]();

}
}

Output:
true
false

You might also like