0% found this document useful (0 votes)
2 views83 pages

Java QP Descriptive

NA

Uploaded by

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

Java QP Descriptive

NA

Uploaded by

pspk90623
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Question Bank Core Java

Solve the following problems - OOP

Q. No. Question Detail Level

1 Take an object “Mobile Phone” and realize the following OOPs concept Easy
1: Identify the object and determine the essential attributes and behaviors for
the object.
2: Realize the concept of class as a blueprint of the mobile phone.
3: How is abstraction employed in the mobile phone to facilitate user
interaction? What is the abstraction for the following user levels: User,
Designer, Engineer, and Servicemen.
4: How is encapsulation applied in the mobile?
5: Realize the concept of inheritance and the types of inheritance.
6: How does the concept of polymorphism enable flexible handling of different
interactions?
7: Realize association and its types – aggregation and composition.

Solve the following problems – Arrays and Strings

1
Question Bank Core Java
Questio
Question Detail Level
n No.

ARRAYS

Number of Even and Odd Integers Easy

Problem Statement:

Write a Java program that reads an array of integers from the


user and calculates the number of even and odd elements in the
array. The program should then display the count of even
numbers and the count of odd numbers.

Input Format:

 The first line contains an integer N, the number of


elements in the array.

 The second line contains N space-separated integers


representing the array elements.

Output Format:

 Print the number of even elements as: Number of even


elements: X

 Print the number of odd elements as: Number of odd


elements: Y

Constraints:
1
 1 ≤ N ≤ 50

 -100 ≤ array element ≤ 100

Test Cases:

Input 1:

Enter value N: 6

Enter array elements: 1 2 3 4 5 6

Output 1:

Number of even elements: 3

Number of odd elements: 3

Input 2:

Enter value N: 5

Enter array elements: 7 9 11 13 15

Output 2:

Number of even elements: 0

2
Question Bank Core Java
Number of odd elements: 5

Input 3:

Enter value N: 0

Output 3:

Invalid Input: Array size must be between 1 and 50

Input 4:

Enter value N: 4

Enter array elements: 10 20 150 30

Output 4:

Invalid Input: Array elements must be between -100 and 100

Arrange Array with Negative Integers Before Positives Easy

Problem Statement:

Given an array of integers, rearrange the elements so that all


negative integers appear before all positive integers, while
maintaining the order of elements within each group.
The program should also validate the array size and input
correctness.

Input Format:

 The first line contains an integer N, the number of


elements in the array.

 The second line contains N space-separated integers


2 representing the array elements.

Output Format:

 If valid, print the updated array with all negative numbers


appearing before positive numbers.

 If invalid, print an appropriate error message.

Constraints:

 1 ≤ N ≤ 20

 Array elements are integers.

3
Question Bank Core Java
Test Cases:

Input 1:

Enter number of elements in the array: 6

Enter array elements: 5 -3 8 -1 4 -2

Output 1:

Rearranged array: -3 -1 -2 5 8 4

Input 2:

Enter number of elements in the array: 5

Enter array elements: -10 -5 -2 0 3

Output 2:

Rearranged array: -10 -5 -2 0 3

Input 3:

Enter number of elements in the array: 0

Output 3:

Invalid input. Number of elements must be between 1 and 20.

Input 4:

Enter number of elements in the array: 4

Enter array elements: 1 -2 3

Output 4:

Invalid input. Number of elements entered does not match N.

GCD of Array Easy

Problem Statement:

Given an array of positive integers, find the Greatest Common


Divisor (GCD) of all the elements in the array. The GCD of an
array is the largest integer that divides all the array elements
3 without leaving a remainder.

Input Format

 Enter the number of elements: N

 Enter N array elements separated by space.

Output Format

4
Question Bank Core Java
 Print the GCD of the array in the form of a sentence.

Constraints

 1 ≤ N ≤ 50

 1 ≤ array element ≤ 10⁴

Test Cases:

Input 1:

Enter the number of elements: 5


Enter array elements: 10 20 30 40 50

Output 1:
The GCD of the array is: 10

Explanation:
10 divides all numbers (10, 20, 30, 40, 50). No greater number
divides all.

Input 2:
Enter the number of elements: 4
Enter array elements: 7 14 21 28

Output 2:
The GCD of the array is: 7

Explanation:
7 is the largest number that divides all elements.

Input 3:
Enter the number of elements: 0
Enter array elements:

Output 3:
Invalid Input: The number of elements must be at least 1.

Input 4:
Enter the number of elements: 3
Enter array elements: 12 -6 18

Output 4:
Invalid Input: Array elements must be positive integers only.

4 Rearrange Array Alternately Easy

Problem Statement:

Write a program to rearrange a sorted array in an alternate


maximum and minimum form.

5
Question Bank Core Java
 The first element should be the maximum,

 the second should be the minimum,

 the third should be the second maximum,

 the fourth should be the second minimum, and so on.

Input Format

 Enter the number of elements: N

 Enter N array elements in sorted order separated by


space.

Output Format

 Print the rearranged array in a single line separated by


spaces.

Constraints

 1 ≤ N ≤ 50

 -100 ≤ array element ≤ 100

Test Cases:

Input 1:
Enter the number of elements: 6
Enter array elements: 1 2 3 4 5 6

Output 1:
Rearranged array: 6 1 5 2 4 3

Explanation:
Max = 6, Min = 1, 2nd Max = 5, 2nd Min = 2, 3rd Max = 4, 3rd
Min = 3.

Input 2:
Enter the number of elements: 5
Enter array elements: -3 -1 2 4 7

Output 2:
Rearranged array: 7 -3 4 -1 2

Explanation:
Max = 7, Min = -3, 2nd Max = 4, 2nd Min = -1, Middle = 2.

Input 3:
Enter the number of elements: 0

Output 3:
Invalid Input: The number of elements must be at least 1.

6
Question Bank Core Java

Input 4:
Enter the number of elements: 4
Enter array elements: 10 20 150 30

Output 4:
Invalid Input: Array elements must be between -100 and 100.

5 Sort an Array in Descending Order Mediu


m
Problem Statement:

Write a program to sort an array of integers in descending The


program should first validate the input constraints. If inputs are
valid, it should display the original array, sort it in descending
order, and print the sorted array.

Input Format

 Enter the number of elements: <N>

 Enter array elements: <a1> <a2> ... <aN>

Output Format

 Sorted array in descending order: <a1> <a2> ... <aN>

Constraints

 1 ≤ N ≤ 100

 -10⁶ ≤ array elements ≤ 10⁶

Test Cases:

Input 1:

Enter the number of elements: 5


Enter array elements: 3 1 4 2 5

Output 1:

Sorted array in descending order: 5 4 3 2 1


Explanation:
Original array: 3 1 4 2 5 → Sorted in descending order: 5 4 3 2 1

Input 2:

Enter the number of elements: 4


Enter array elements: 10 20 5 15

Output 2:

Sorted array in descending order: 20 15 10 5


Explanation:
Original array: 10 20 5 15 → Sorted in descending order: 20 15 10
5

7
Question Bank Core Java

Input 3:

Enter the number of elements: 0

Output 3:

Number of elements out of constraints

Input 4:

Enter the number of elements: 101

Output 4:

Number of elements out of constraints

Count Possible Triangles from an Unsorted Array Mediu


m
Problem Statement:
Write a Java program that reads an unsorted array of positive
integers and counts the number of possible triangles that can be
formed using three different elements of the array.
A triangle is valid if the sum of any two sides is greater than the
third side.

Input Format:

 The first line contains an integer N, the number of


elements in the array.

 The second line contains N space-separated positive


integers representing the array elements.

Output Format:

 Print the total number of possible triangles that can be


6 formed.

 If less than three elements are entered, print: Not enough


elements to form a triangle.

Constraints:

 3 ≤ N ≤ 50

 1 ≤ array element ≤ 100

Test Cases:

Input 1:
Enter number of elements: 5
Enter array elements: 4 6 3 7 5

Output 1:
Total number of possible triangles: 7

8
Question Bank Core Java
Explanation:
Valid triangles are formed by sides (3,4,5), (4,5,6), (3,6,7), etc.

Input 2:
Enter number of elements: 4
Enter array elements: 10 21 22 100

Output 2:
Total number of possible triangles: 2

Explanation:
Only (10,21,22) and (21,22,100) satisfy the triangle property.

Input 3:
Enter number of elements: 2
Enter array elements: 5 7

Output 3:
Not enough elements to form a triangle.

Search in a 2D Array Mediu


m
Problem Statement:

Given a 2D array of size MxN, and a number X, check if X is


present in the array. Print its position if found.

Input Format

 Enter number of rows: M

 Enter number of columns: N

 Enter matrix elements row-wise

 Enter the number to search: X

Output Format
7
 If found: X found at row R and column C

 Else: X not found in the array

Constraints

 1 ≤ M, N ≤ 50

 -1000 ≤ matrix element, X ≤ 1000

Test Cases:

Input 1:

Enter number of rows: 2


Enter number of columns: 3
Enter matrix elements:

9
Question Bank Core Java
123
456
Enter the number to search: 5

Output 1:

5 found at row 1 and column 1

Input 2:

Enter number of rows: 2


Enter number of columns: 2
Enter matrix elements:
78
9 10
Enter the number to search: 11

Output 2:

11 not found in the array

Input 3 :

Enter number of rows: 0

Output 3:

Invalid Input: Number of rows must be at least 1

Input 4:

Enter number of columns: 51

Output 4:

Invalid Input: Number of columns must be at most 50

Transpose of a Matrix Mediu


m
Problem Statement:

Write a program that reads a matrix of size MxN from the user
and prints its transpose. The program should first ask for the
number of rows and columns, then accept the matrix elements
row by row, and finally display the transposed matrix. If the
number of rows or columns is outside the allowed range, the
8 program should print an appropriate error message.

Input Format

 Enter number of rows: M

 Enter number of columns: N

 Enter MxN matrix elements row-wise

Output Format

10
Question Bank Core Java
 Print the transposed matrix

Constraints

 1 ≤ M, N ≤ 50

Test Cases:

Input 1:

Enter number of rows: 2


Enter number of columns: 3
Enter matrix elements:
123
456

Output 1:

Transpose of matrix:
14
25
36

Input 2:

Enter number of rows: 3


Enter number of columns: 2
Enter matrix elements:
78
9 10
11 12
Output 2:

Transpose of matrix:
7 9 11
8 10 12

Input 3:

Enter number of rows: 0

Output 3:

Invalid Input: Number of rows must be at least 1

Input 4:

Enter number of columns: 51

Output 4:

Invalid Input: Number of columns must be at most 50

9 Row-wise Sum Mediu

11
Question Bank Core Java
Problem Statement: m
Given a jagged matrix (rows may have different number of
columns), compute and display the sum of each row.

Input Format:

 First line: Enter number of rows: followed by an integer

 Next lines: For each row, enter space-separated integers


representing the elements of that row

Output Format:

 For each row, print: Sum of row <row_number>:


<sum_value>

 If any matrix element is out of the range 1 to 100, print:


Invalid matrix element

Constraints:

 1 ≤ number of rows ≤ 10

 1 ≤ number of elements in any row ≤ 10

 1 ≤ element ≤ 100

Test Cases:

Input 1:

Enter number of rows: 3

Enter number of elements in row 1: 2

Enter row 1 elements: 1 2

Enter number of elements in row 2: 3

Enter row 2 elements: 3 4 5

Enter number of elements in row 3: 1

Enter row 3 elements: 6

Output 1:

Sum of row 1: 3

Sum of row 2: 12

Sum of row 3: 6

Explanation:

 Row 1: 1 + 2 = 3

 Row 2: 3 + 4 + 5 = 12

 Row 3: 6 = 6

12
Question Bank Core Java

Input 2:

Enter number of rows: 2

Enter number of elements in row 1: 3

Enter row 1 elements: 10 20 30

Enter number of elements in row 2: 2

Enter row 2 elements: 5 15

Output 2:

Sum of row 1: 60
Sum of row 2: 20
Explanation:

 Row 1 sum: 10 + 20 + 30 = 60

 Row 2 sum: 5 + 15 = 20

Input 3:

Enter number of rows: 2


Enter number of elements in row 1: 2
Enter row 1 elements: 10 105
Output 3:

Invalid matrix element

Input 4 :

Enter number of rows: 1


Enter number of elements in row 1: 12

Output 4:

Invalid number of elements in row 1

STRINGS

String Operations – Menu Driven Mediu


m
Problem Statement:
Accept a string input from the user and provide a menu to
perform the following operations without using in-built functions.

10 1. Find Length – Calculate and display the total number of


characters in the string.

2. Trim Spaces – Remove any leading and trailing spaces from


the string and display it along with the original and
trimmed lengths.

3. Concatenate – Read a second string from the user and join

13
Question Bank Core Java
it with the main string.

4. Character at Index – Display the character at a specified


index. Handle invalid indices appropriately.

5. Find Substring / Contains Substring – Check if a substring


exists in the string and display its index if found.

6. Starts With / Ends With – Check if the string begins or ends


with a specified sequence.

7. Compare Strings – Compare the main string with another


string (exact and ignoring case).

8. Split into Words – Split the string into words separated by


spaces and display each word.

9. Convert to Characters – Display all characters of the string


individually.

[Link] Substring – Replace a portion of the string with


another sequence.

[Link] Number or Data – Append a number or other data


type to the string.

[Link] – Terminate the program.

Input Format:

 Prompt the user for the main string.

 For operations requiring extra input (concatenate,


compare, replace, etc.), prompt accordingly.

 Show a menu to the user to select an operation.

Output Format:

 Display the result of the selected operation clearly.

Test cases:
Sample Input/Output:

Enter the Main string: Java Programming

Menu:

1. Find Length

2. Trim Spaces

3. Concatenate

4. Character at Index

5. Find Substring / Contains

14
Question Bank Core Java
6. Starts With / Ends With

7. Compare Strings

8. Split into Words

9. Convert to Characters

10. Replace Substring

11. Append Number or Data

12. Exit

Enter your choice: 1

Length of the string: 16

Enter your choice: 2

Trimmed string: Java Programming

Original length: 16, Trimmed length: 16

Enter your choice: 3

Enter string to concatenate: Lab

Concatenated string: Java ProgrammingLab

Enter your choice: 4

Enter index: 5

Character at index 5: P

Enter your choice: 5

Enter substring/character to find: Programming

The index of 'Programming' is: 5

Enter your choice: 6

Enter starting sequence: Java

Enter ending sequence: Programming

Starts with 'Java': true

Ends with 'Programming': true

15
Question Bank Core Java

Enter your choice: 7

Enter string to compare: java programming

Strings are equal ignoring case

Enter your choice: 8

Words in the string:

Java

Programming

Enter your choice: 9

Characters in the string: [J, a, v, a, , P, r, o, g, r, a, m, m, i, n, g]

Enter your choice: 10

Enter substring to replace: Programming

Enter replacement string: Lab

After replacement: Java Lab

Enter your choice: 11

Enter number or data to append: 2025

After appending: Java Programming2025

Enter your choice: 12

Exiting program.

Reverse Vowels Mediu


m
Problem Statement:

Given a string, reverse only the vowels (a, e, i, o, u). Keep all
other characters in the same position.
11
Input Format

 Enter a string: S

Output Format

 Print the string after reversing the vowels

16
Question Bank Core Java
Constraints

 1 ≤ length(S) ≤ 50

 String can contain both uppercase and lowercase English


letters

Test Cases:

Input 1:

Enter a string: hello

Output 1:

String after reversing vowels: holle

Explanation:
Vowels: e, o → reversed → o, e

Input 2:

Enter a string: programming

Output 2:

String after reversing vowels: prigrammong

Explanation:
Vowels: o, a, i → reversed → i, a, o

Input 3 :

Enter a string: he!!o

Output 3:

Invalid Input: String must contain only letters

Input 4:

Enter a string:

Output 4:

Invalid Input: String must not be empty

12 Longest Substring Without Repeating Characters Mediu


m
Problem Statement:

Given a string, find the longest substring without repeating


characters and print its length.
If multiple substrings have the same maximum length, print any
one of them.

17
Question Bank Core Java
Input Format:

 A single line containing a string S.

Output Format:

 Print the longest substring without repeating characters.

 Print the length of this substring.

 If the string is empty, print an appropriate error message.

Constraints:

 1 ≤ Length of S ≤ 1000

 String contains only lowercase and uppercase English


letters.

Test Cases:

Input 1:

Enter a string: abcabcbb

Output 1:

Longest substring without repeating characters: abc

Length: 3

Input 2:

Enter a string: pwwkew

Output 2:

Longest substring without repeating characters: wke

Length: 3

Input 3:

Enter a string:

Output 3:

Invalid input. String cannot be empty.

Input 4:

Enter a string: ab12cd

Output 4:

18
Question Bank Core Java
Invalid input. String contains non-alphabetic characters.

FUNCTIONS

First and Last Position of Element in Sorted Array Mediu


m
Problem Statement:

You are given a non-decreasing array of n integers and an


integer x. Write a program using user-defined functions to find
the first and last position of x in the array.

Note:

1. The array follows 0-based indexing.

2. If x is not present, return -1 -1.

3. If x is present only once, the first and last position will be


the same.

Input Format:

 Enter the number of elements: N

 Enter N space-separated array elements

 Enter the element to find: X

Output Format:

 Print the first and last position of X as: <first_index>


13 <last_index>

 If X is not present, print -1 -1.

Constraints:

 1 ≤ N ≤ 10⁴

 -10⁹ ≤ arr[i], X ≤ 10⁹

Test Cases:
Input 1:

Enter the number of elements: 5


Enter array elements: -10 -5 -5 -5 2
Enter the element to find: -5
Output 1:

13
Explanation:
The first occurrence of -5 is at index 1 and the last occurrence is
at index 3.

Input 2:

19
Question Bank Core Java
Enter the number of elements: 4
Enter array elements: 1 2 3 4
Enter the element to find: -1

Output 2:

-1 –1

Explanation:
The element -1 is not present in the array.

Input 3:

Enter the number of elements: 0

Output 3:

Invalid Input: The number of elements must be at least 1.

Input 4:

Enter the number of elements: 3


Enter array elements: 1 10000000000 3
Enter the element to find: 1

Output 4:

Invalid Input: Array elements must be between -1000000000 and


1000000000.

14 Remove Consecutive Duplicates Mediu


m
Problem Statement:

You are given a string str of size N. Your task is to remove


consecutive duplicates from this string recursively using a user-
defined function.

Only adjacent duplicates should be removed; non-adjacent


duplicates should remain.

For example, if the input string is aazbbby, the output should be


azby.

If the input is invalid (e.g., string length does not match N, or


contains characters other than lowercase letters a–z), print an
appropriate error message.

Input Format:

1. Enter the number of test cases: T

2. For each test case:

a. Enter the size of the string: N

b. Enter the string: str

20
Question Bank Core Java
Output Format:

 For each test case, print the string after removing


consecutive duplicates.

 If input is invalid, print the corresponding error message.

Constraints:

 1 ≤ T ≤ 10

 1 ≤ N ≤ 1000

 String must contain only lowercase English alphabets (a–z)

Test Cases:

Input 1:

Enter the number of test cases: 2

Enter the size of the string: 7

Enter the string: aazbbby

Enter the size of the string: 6

Enter the string: aabbcb

Output 1:

The string after removing consecutive duplicates is: azby

The string after removing consecutive duplicates is: abcb


Explanation:

 aazbbby → remove adjacent duplicates → azby

 aabbcb → remove adjacent duplicates → abcb

Input 2:
Enter the number of test cases: 2

Enter the size of the string: 5

Enter the string: abcde

Enter the size of the string: 5

Enter the string: aaaaa

Output 2:

The string after removing consecutive duplicates is: abcde

The string after removing consecutive duplicates is: a

Explanation:

21
Question Bank Core Java
 abcde → no duplicates → abcde

 aaaaa → remove duplicates → a

Input 3:
Enter the number of test cases: 1

Enter the size of the string: 6

Enter the string: abCD12


Output 3:
Invalid input: String must contain only lowercase alphabets

Input 4:
Enter the number of test cases: 1

Enter the size of the string: 4

Enter the string: abc


Output 4:
Invalid input: Size of string does not match given N

Solve the following problems – Control Flow

Questio
Question Detail Level
n No.
LOOPING STATEMENTS
1 Perfect Squares in a Range Easy
Problem Statement:
Given two integers a and b (1 ≤ a ≤ b ≤ 10⁵), find the number of perfect
squares between a and b (inclusive).
Input Format:
Two space-separated integers representing the range:
ab
Output Format:
 Print the number of perfect squares between a and b.
 If the input is invalid (e.g., a < 1, b < 1, or a > b), print:
Invalid Input
Constraints:
 1 ≤ a ≤ b ≤ 10⁵

Test Cases:

22
Question Bank Core Java
Input 1:
Enter the Integer value: 3 8
Output 1:
1
Explanation: Perfect squares between 3 and 8 → 4

Input 2:
Enter the Integer value: 9 25
Output 2:
3
Explanation: Perfect squares between 9 and 25 → 9, 16, 25

Input 3:
Enter the Integer value: 30 20
Output 3:
Invalid Input

Input 4:
Enter the Integer value: 0 50
Output 4:
Invalid Input
All Prime Numbers Less Than or Equal to N Mediu
Problem Statement: m
Given a positive integer N, print all prime numbers less than or equal to N.
 A prime number is a number greater than 1 that has no positive
divisors other than 1 and itself.
 Use loops and conditional checks; do not use inbuilt prime functions.
Input Format
 Input consists of a single integer N.
2 Output Format
 Print all prime numbers ≤ N separated by space.
 Print "Invalid Input" if the input does not satisfy the constraints.
Constraints
 1 ≤ N ≤ 10⁴

Test Cases:
Input 1:
Enter the value of N: 10

23
Question Bank Core Java
Output 1:
Prime numbers: 2 3 5 7
Explanation:
 The program checks numbers from 2 to 10.
 Numbers with no divisors other than 1 and itself are prime.
 Prime numbers ≤ 10 are: 2, 3, 5, 7.

Input 2:
Enter the value of N: 20
Output 2:
Prime numbers: 2 3 5 7 11 13 17 19
Explanation:
 The program checks numbers from 2 to 20.
 Prime numbers ≤ 20 are: 2, 3, 5, 7, 11, 13, 17, 19.

Input 3:
Enter the value of N: -5
Output 3:
Prime numbers: Invalid Input

Input 4:
Enter the value of N: 20000
Output 4:
Prime numbers: Invalid Input
Sum of Fibonacci Series up to Nth Term Mediu
Problem Statement: m
Given a number positive number N, find value of f0 + f1 + f2 + . + fN where fi
indicates ith Fibonacci number.
Input Format:
 A single integer value representing the Nth term.
Output Format:
3
 If the input is valid (positive integer within the constraint), print the sum
of the Fibonacci series from f0 to fN.
 If the input is invalid (e.g., a negative number), print:
Invalid input. Enter a positive integer.
Constraints:
1 ≤ n ≤ 40

24
Question Bank Core Java
Test Cases:
Input 1:
Enter the value of N: 5
Output 1:
12
Explanation: Fibonacci: 0, 1, 1, 2, 3, 5 → sum = 0 + 1 + 1 + 2 + 3 + 5 =
12

Input 2:
Enter the value of N: 10
Output 2:
143
Explanation: Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 → sum = 143

Input 3:
Enter the value of N: 40
Output 3:
165580140

Input 4:
Enter the value of N: -5
Output 4:
Invalid input. Enter a positive integer.
PATTERN
Square Matrix with Repeated Row Numbers Easy
Problem Statement:
Write a program to print a square pattern of size N × N, where each row
contains the same number repeated N times. The number in each row
should start from 1 and increase by 1 in the next row.
For example, for N = 4, the pattern should be:
1111
4
2222
3333
4444
Input Format:
 A single integer N, where N represents the size of the square matrix.
Output Format:
 A square pattern of size N × N, where each row i contains the

25
Question Bank Core Java
number i repeated N times, separated by spaces.
Constraints:
 1 <= N <= 50

Test Cases:
Input 1: Enter the value N: 3
Output 1:
111
222
333

Input 2:
Enter the value N: 5
Output 2:
11111
22222
33333
44444
55555

Input 3:
Enter the value N: 0
Output 3:
Error: N must be between 1 and 50

Input 4:
Enter the value N: 101
Output 4:
Error: N must be between 1 and 50
Decreasing Rows with Increasing Numbers Easy
Problem Statement:
Print a number pattern in which:
 The first row starts from 1 and prints numbers up to n.
5  Each subsequent row starts from the next number and prints one
less value than the previous row.
 The pattern continues until only the last number is printed.
Input Format:
 A single integer n — the number of columns (or the maximum

26
Question Bank Core Java
number in the first row).
Output Format:
 The pattern starts from 1 to n in the first row.
 From the second row onward, the starting number increases by 1
and the number of elements decreases by 1 per row.
 The last row contains just the number n.
Constraints:
 1 ≤ n ≤ 50

Test Cases:
Input 1:
Enter the value N: 3
Output 1:
123
23
3

Input 1:
Enter the value N: 4
Output 1:
1234
234
34
4

Input 3: Enter the value N: 0


Output 3: Invalid input (less than minimum allowed)

Input 4: Enter the value N: 52


Output 4: Invalid input (exceeds maximum limit)
Right-Aligned Increasing Number Triangle Mediu
Problem Statement: m
Print a right-aligned triangle of numbers.
Each row starts from 1 and increases up to the row number.
6
 The pattern should be printed with increasing indentation from top to
bottom to create a right-aligned effect.
Input Format:
A single integer n — the number of rows in the triangle.

27
Question Bank Core Java
Output Format:
Each row contains numbers starting from 1 up to the row number, aligned to
form a right-angled triangle shape.
Constraints:
1 ≤ n ≤ 50

Test Cases:
Input 1:
Enter the value N: 3
Output 1:
1
12
123

Input 2:
Enter the value N: 5
Output 3:
1
12
123
1234
12345

Input 3: Enter the value N: 0


Output 3: Invalid input (less than minimum allowed)

Input 4: Enter the value N: 105


Output 4: Invalid input (exceeds maximum limit)
Left-Aligned Triangle with Repeated Row Numbers Mediu
Problem Statement: m
Write a program to print a left-aligned triangle pattern of numbers, where
each row i contains the number i, repeated i times.
Input Format:
7
 A single integer N which represents the number of rows in the
pattern.
Output Format:
 A triangle pattern where the ith row contains the number i, repeated i
times, separated by spaces.

28
Question Bank Core Java
Constraints:
 1 <= N <= 50

Test Cases:
Input 1: Enter the value N: 3
Output 1:
1
22
333

Input 2:
Enter the value N: 5
Output 2:
1
22
333
4444
55555

Input 3:
Enter the value N: 0
Output 3: Error: N must be between 1 and 50

Input 4:
Enter the value N: 51
Output 4: Error: N must be between 1 and 50
Pascal’s Triangle Generator Mediu
Problem Statement: Generate and print Pascal’s Triangle for a given m
integer N, where N specifies the number of rows in the triangle.
Pascal’s Triangle is a triangular array of numbers were:
 The first and last numbers of each row are always 1.
 Every interior number is the sum of the two numbers directly above
8
it from the previous row.
Input Format:
 Number: N (an integer representing the number of rows in Pascal’s
Triangle)
Output Format:
 A triangle of numbers with N rows where each number is computed

29
Question Bank Core Java
based on Pascal’s Triangle rules.
 If the input is below the minimum limit (i.e., N < 1), print:
Invalid input (below minimum limit)
 If the input exceeds the maximum limit (i.e., N > 25), print:
Invalid input (exceeds maximum limit)
Constraints:
1 ≤ N ≤ 25

Test Cases:
Input 1: Enter the value N: 5
Output 1:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Explanation:
Each number is the sum of the two numbers directly above it.
Row 1: 1
Row 2: 1 1
Row 3: 1 (1+1)=2 1
Row 4: 1 (1+2)=3 (2+1)=3 1
Row 5: 1 (1+3)=4 (3+3)=6 (3+1)=4 1

Input 2: Enter the value N: 3


Output 2:
1
1 1
1 2 1

Input 3: Enter the value N: 0


Output 3: Invalid input (below minimum limit)

Input 4: Enter the value N: 30


Output 4: Invalid input (exceeds maximum limit)

30
Question Bank Core Java

Solve the following problems : Classes and Object, Constructors, Static,


Encapsulation.

Q.
Question Detail Level
No.

CLASSES&OBJECTS

1 Average of Three Numbers Easy


Problem Statement
Create a class named Average. The class should have a method to calculate
the average of three numbers. Accept three numbers from the user, calculate
the average using the method, and print the result.
Sample Input/output:
Input 1: 5, 10, 15
Output 1: Average = 10.0
Input 2: 8, 12, 20

31
Question Bank Core Java
Output 2: Average = 13.33

2 Modeling Books and Authors Easy


Problem Statement:
a) Design a class Author as shown in the UML diagram.
b) Design a class Book as shown in the UML diagram, where each Book has
one Author (composition).
c) Write a driver class to:
 Create instances of Author and Book.
 Test all methods of both Author and Book classes.

Sample Input/output:
Author:
Name: J.K. Rowling
Email: jkrowling@[Link]
Gender: F

Book:
Title: Harry Potter and the Sorcerer's Stone
Price: 500
Quantity: 10
Author: J.K. Rowling

Author Details:
Name: J.K. Rowling
Email: jkrowling@[Link]

32
Question Bank Core Java
Gender: F

Book Details:
Title: Harry Potter and the Sorcerer's Stone
Price: 500
Quantity: 10
Author: J.K. Rowling

CONSTRUCTORS

3 Product Information Easy


Problem Statement:
You are developing a simple program to manage product information for an
online store. To represent each product, you need to create a Java class with
constructors that initialize the product details.

Specifications:

1. Define a Java class named Product with the following specifications:


Private instance variables to store the product ID, name, price, and
quantity.
2. Implement a default constructor that initializes the product details as
follows:

 Product ID: 0

 Product name: "Unknown"

 Price: 0.0

 Quantity: 0

3. Implement another constructor that takes parameters for product ID,


name, price, and quantity, and initializes the corresponding instance
variables with the provided values.

Write a Main class to demonstrate the usage of both constructors by creating


instances of the Product class and displaying their details.

Sample Input/output:

For default constructor:

33
Question Bank Core Java
No input required (uses default values)

For parameterized constructor:

Product ID: 101

Product Name: Laptop

Price: 55000.0

Quantity: 5

Default Product Details:

Product ID: 0

Product Name: Unknown

Price: 0.0

Quantity: 0

Parameterized Product Details:

Product ID: 101

Product Name: Laptop

Price: 55000.0

Quantity: 5

4 Farm Vegetables Using Constructor Overloading Easy


Problem Statement:
You are helping a farmer to manage the vegetables on his farm. The farm
contains different types of vegetables: Carrot (C), Potato (P), and Brinjal
(B). You need to create a Java class that can store the quantity of each
vegetable and display the information in a specific format.
Specifications:
o Define a Java class named Crop with private instance
variables for the quantity of each vegetable: carrot (int),potato
(int),brinjal (int)
2. Implement constructor overloading as follows:
o Default constructor: Initializes all vegetable quantities to 0.
o Parameterized constructor: Accepts the quantities of Carrot,

34
Question Bank Core Java
Potato, and Brinjal, and initializes the corresponding instance
variables.
3. Implement a method to display the vegetable quantities in the
following format:C <carrot_quantity> P <potato_quantity> B
<brinjal_quantity>
4. Demonstrate the usage of the class by creating objects using both
constructors and displaying the results.
Sample Input/output:
For parameterized constructor:
Carrot: 15
Potato: 25
Brinjal: 30
For default constructor:
No input required (all quantities default to 0)

Default Crop Quantities:


C0P0B0
Parameterized Crop Quantities:
C 15 P 25 B 30
5 Cash Register in a Vending Machine Mediu
Problem Statement: m
The machine has two main components:
1. A built-in cash register
2. Several dispensers to hold and release the products
In this task, you need to design the cashRegister class in Java with the
following specifications:
1. Private Member
o cashOnHand (int): stores the current balance in the register.
2. Constructors
o cashRegister() → Default constructor that sets cashOnHand =
100.
o cashRegister(int amount) → Initializes the register with the
given amount.
3. Public Methods
o getCurrentBalance() → Returns the value of cashOnHand.
o acceptAmount(int amount) → Adds the deposited amount to the
cashOnHand.
4. Write a driver class (Main) to create objects of cashRegister and

35
Question Bank Core Java
demonstrate all the methods.

Sample Input/output:
Using default constructor
Deposit: 50
Using parameterized constructor (cashOnHand = 200)
Deposit: 100

Default Register Balance: 100


After Deposit: 150
Parameterized Register Balance: 200
After Deposit: 300
6 Calculate Tax on Salary Mediu
Problem Statement: m
You need to design a Java class TaxOnSalary to calculate tax on salary based
on certain rules. The class should manage employee salary and PAN status,
and compute tax accordingly.
Requirements:
Attributes:
 salary (double) → salary to calculate tax
 isPANsubmitted (boolean) → PAN submission status
Specifications:
1. Constructors:
o TaxOnSalary() → Initializes salary = 0.0 and isPANsubmitted =
false.
o TaxOnSalary(boolean panStatus) → Initializes isPANsubmitted =
panStatus and salary = 1000.0.
2. Methods:
o getSalary() and isPANsubmitted() → Accessor methods.
o inputSalary() → Reads salary from the user (keyboard) and
assigns it.
o calculateTax() → Computes tax based on these rules:
 If salary < 180000 and isPANsubmitted = true → Tax = 0
 If salary < 180000 and isPANsubmitted = false → Tax =
5% of salary
 If 180000 < salary < 500000 → Tax = 10% of salary
 If 500000 < salary < 1000000 → Tax = 20% of salary

36
Question Bank Core Java
 If salary > 1000000 → Tax = 30% of salary
3. Test class (TestTax)
o Create two objects (tax1, tax2) with different constructors.
o Take salary input from the user for both objects.
o Display calculated tax for both.
Sample Input/output:
Enter salary for Tax1: 150000
Enter salary for Tax2: 600000
(PAN submitted true for Tax1, false for Tax2)

Tax for Tax1: 0.0


Tax for Tax2: 120000.0

STATIC METHODS/VARIABLES

7 Library Collection with Static and Final Variables Mediu


Problem Statement: m
You are developing a simple program to manage a library's collection of books.
Each book in the library has a unique identification number assigned to it.
Additionally, you want to define a constant variable to represent the maximum
number of books that the library can hold.
Define a Java class named Library with the following specifications:

1. Implement a static variable named totalBooks to keep track of the


total number of books in the library.

2. Define a constant variable named MAX_CAPACITY to represent the


maximum number of books that the library can hold. Set its value to
1000.

3. Implement a method named addBook() that increments the


totalBooks count each time a new book is added to the library.

4. Implement a method named getTotalBooks() that returns the current


count of total books in the library.

5. Ensure that the MAX_CAPACITY variable cannot be modified after


initialization.

Write the Java class Library with the given requirements and demonstrate its
usage in the Main class by adding books to the library and retrieving the total
count.

37
Question Bank Core Java

Sample Input/output:

Add 3 books

Add 2 more books

Output:

Total books in library: 3

Total books in library: 5

Maximum Capacity of Library: 1000

8 Compound Interest Calculation Using Static Methods Mediu


Problem Statement: m
You are developing a simple banking system that requires calculating the
compound interest earned on a savings account. To achieve this, define a Java
class with static methods that can perform compound interest calculations.
Specifications:
1. Create a class named InterestCalculator.
2. Inside this class, implement the following static methods:
o calculateCompoundInterest(principal, rate, years)
 Returns the total amount (principal + compound
interest).
 Formula: Total Amount = Principal * (1 + Rate/100) ^
Years
o calculateInterestOnly(principal, rate, years)
 Returns only the compound interest earned.
 Formula: Compound Interest = Principal * ((1 +
Rate/100) ^ Years - 1)
3. Demonstrate the use of these methods in a separate Main class by
calculating and displaying the results for different scenarios.

Sample Input/output:
Principal = 1000
Rate = 5
Years = 3

Total Amount (with CI): 1157.625

38
Question Bank Core Java
Compound Interest Only: 157.625

ENCAPSULATION

9 Employee Information Using Encapsulation Mediu


Problem Statement: m
You are tasked with developing a simple application to manage employee
information for a company. To maintain data integrity and ensure security, you
need to encapsulate the employee details within a Java class and provide
controlled access using getter and setter methods.
Specifications
1. Define a Java class named Employee with the following
specifications:Private instance variables to store the employee's ID,
name, age, and salary.
2. Public getter and setter methods for each instance variable to provide
controlled access to the employee details. Ensure that the setter
methods validate the input before assigning it to the instance variables:
 The employee ID must be a positive integer.
 The employee's name cannot be empty.
 The employee's age must be a positive integer.
 The employee's salary must be a non-negative value.
3. Implement a method named raiseSalary() that takes a percentage
increase as input and raises the employee's salary accordingly.
4. Implement a method named displayInfo() that displays all the
employee details.
Write the Java class Employee with the given requirements and demonstrate
its usage in the Main class by creating an employee, updating their details,
giving them a salary raise, and displaying their information.

Sample Input/output:
Employee ID: 101
Employee Name: John Doe
Employee Age: 30
Employee Salary: 50000
Raise Salary by: 10%

Employee Details:
ID: 101

39
Question Bank Core Java
Name: John Doe
Age: 30
Salary: 50000.0

After Salary Raise:


ID: 101
Name: John Doe
Age: 30
Salary: 55000.0

Solve the following problems : Inheritance, Polymorphism

Question
Question Detail Level
No.

40
Question Bank Core Java
INHERITANCE

1 Bank Account Hierarchy Medium

Problem Statement:

 Create a BankAccount class with accountNumber,


balance, interestRate, and method deposit().

 Create a subclass SavingsAccount with


minimumBalance and method withdraw().

 Create another subclass FixedDepositAccount with


term and method getInterest() to calculate interest.

Sample Input/Output:

Input:
Account Number: 101
Balance: 5000
Interest Rate: 5
Minimum Balance: 1000
Deposit: 2000
Withdraw: 1500
Term: 2 years

Output:
2000.0 deposited successfully.
1500.0 withdrawn successfully.
Interest Earned: 550.0

2 Student Information Medium

Problem Statement:

Create a base class Person with attributes:

 name

 age

Method: displayInfo() to show basic person details.

Create a subclass Student extending Person with attribute:

 studentId

Override displayInfo() to include student ID.

Create further subclasses:

 UndergraduateStudent with attribute major. Override


displayInfo() to include major.

 GraduateStudent with attribute researchTopic.


Override displayInfo() to include research topic.

Demonstrate polymorphism by creating objects of all classes


and invoking their displayInfo() methods.

41
Question Bank Core Java
Sample Input/Output:

Input:
Person: Name=John Doe, Age=30
Student: Name=Alice Smith, Age=20, Student ID=123456
Undergraduate Student: Name=Bob Johnson, Age=21,
Student ID=654321, Major=Computer Science
Graduate Student: Name=Emily Brown, Age=25, Student
ID=987654, Research Topic=Machine Learning

Output:
Displaying information for a Person:
Name: John Doe
Age: 30

Displaying information for a Student:


Name: Alice Smith
Age: 20
Student ID: 123456

Displaying information for an Undergraduate Student:


Name: Bob Johnson
Age: 21
Student ID: 654321
Major: Computer Science

Displaying information for a Graduate Student:


Name: Emily Brown
Age: 25
Student ID: 987654
Research Topic: Machine Learning

3 Current Account Maintenance Meidum

Problem Statement:

Write a Java program with the following specifications:

 Create a parent class Account with attributes:

o customerName (String)

o accountNumber (String)

o balance (float)

 Include a method calculateMaintenanceCharge(float


noOfYears) in Account (can be empty or default).

 Create a child class CurrentAccount that overrides


calculateMaintenanceCharge(float noOfYears) as:

Maintenance Charge = (m * n) + 200


Where:
m = 100 (base charge for Current Account)
n = number of years (input from user)

42
Question Bank Core Java

 Use a constructor to initialize customerName,


accountNumber, and balance.

 Demonstrate inheritance and polymorphism in the


main method.

Sample Output:

Customer Name: Aravindhan


Account Number: CA12345
Balance: 50000.0
Maintenance Charge for 3 years: 500.0

Customer Name: Ravi


Account Number: CA67890
Balance: 75000.0
Maintenance Charge for 5 years: 700.0

POLYMORPHISM

4 Perimeter Calculation Easy

Problem Statement:

Write a Java program that demonstrates method


overloading with a method named Calculate Perimeter. The
method should:

 Calculate the perimeter of a square (side)

 Calculate the perimeter of a rectangle (length, width)

 Calculate the circumference of a circle (radius,


"circle")

Sample Input/output:

Square: side=5
Rectangle: length=4, width=6
Circle: radius=7, shape="circle"
Perimeter of Square: 20.0
Perimeter of Rectangle: 20.0
Circumference of Circle: 43.982297150257104

5 Volume Calculation Easy

Problem Statement:

Write a Java program that demonstrates method


overloading with a method named CalculateVolume. The
method should:

 Calculate the volume of a cube (side)

 Calculate the volume of a cuboid (length, width,


height)

 Calculate the volume of a cylinder (radius, height,

43
Question Bank Core Java
"cylinder")

Sample Input/output:

Cube: side=3
Cuboid: length=4, width=5, height=6
Cylinder: radius=3, height=7, shape="cylinder"

Volume of Cube: 27.0


Volume of Cuboid: 120.0
Volume of Cylinder: 197.92033717615698

6 Library Book Search Easy

Problem Statement:

 Create a Library class to manage a collection of Book


objects.

 Implement overloaded methods in the library class to


search books by:

o Title – returns a list of matching books.

o Author – returns a list of matching books.

o ISBN – returns a single book or null if not found.

 Demonstrate the search methods in the main method


with sample books.

Sample Input/Output:

Input:
Library books:
1. Title: Java Programming, Author: John Smith, ISBN:
1234567890
2. Title: Python Programming, Author: Alice Johnson, ISBN:
0987654321
3. Title: Data Structures, Author: Bob Brown, ISBN:
9876543210
4. Title: Algorithms, Author: Alice Johnson, ISBN:
5432109876

Output:
Books with title 'Java Programming':
Java Programming by John Smith

Books by author 'Alice Johnson':


Python Programming by Alice Johnson
Algorithms by Alice Johnson

Book with ISBN '9876543210':


Data Structures by Bob Brown

44
Question Bank Core Java
7 Employee Salary Calculation Medium

Problem Statement:

 Create an Employee class with attributes: id, name,


salary.

 Implement method overloading for


calculateYearlySalary() in 3 ways:

o Using monthly salary.

o Using daily salary and days in year.

o Using hourly salary and hours worked per day.

 Implement toString() to display employee details.

Sample Input/Output:

Input:
Employee ID: 101
Name: John Doe
Salary: 3000
Monthly Salary: 3000
Daily Salary: 120
Hourly Salary: 15, Hours per day: 8

Output:
Employee ID: 101, Name: John Doe, Salary: 3000.0
Yearly Salary (Monthly): 36000.0
Yearly Salary (Daily): 43800.0
Yearly Salary (Hourly): 31200.0

Solve the following problems : Abstraction, Interface

Question
Question Detail Level
No.

ABSTRACTION

1 Online Payment System Easy

Problem Statement:
Design an online payment system using abstraction in Java.
Create an abstract class Payment with a property amount (double)

45
Question Bank Core Java
and an abstract method processPayment().

Derive two classes from it:

 CreditCardPayment – displays "Credit Card Payment


Approved: <amount>".

 UPIPayment – displays "UPI Payment Successful:


<amount>".

In the main program, create objects of both classes, accept the


amount from the user, and display the respective payment
messages.

Sample Input/Output:

Payment: 500 by Credit Card


Credit Card Payment Approved: 500.0

Payment: -200 by UPI


Error: Invalid amount entered.

2 Ticket Booking System Easy

Problem Statement:
Design a ticket booking system using abstraction in Java. Create
an abstract class Ticket with properties ticketNo and price, and an
abstract method bookTicket(). Derive two classes:

 MovieTicket – displays "Movie Ticket #<ticketNo> booked.


Price: <price>".

 TrainTicket – displays "Train Ticket #<ticketNo> booked.


Price: <price>".

In the main program, create objects of both classes, accept ticket


details from the user, and display the booking details.

Sample Input/Output:

Movie Ticket #101 booked. Price: 200.0


Train Ticket #102 booked. Price: 0

3 Electricity Bill Calculator Easy

Problem Statement:
Design an electricity bill calculator using abstraction in Java.
Create an abstract class Bill with a property units (int) and an
abstract method calculateBill(). Derive two classes:

 DomesticBill – calculates the bill as units × 5.

 CommercialBill – calculates the bill as units × 10.

In the main program, create objects of both classes.

46
Question Bank Core Java

Sample Input/Output:

Domestic Bill for 100 units: 500.0


Commercial Bill for -50 units: Error: Invalid unit entry

4 Student Grade System Medium

Problem Statement:
Design a student grade system using abstraction in Java. Create
an abstract class Student with properties name and an array
marks[], and an abstract method calculateGrade(). Derive two
classes:

 HighSchoolStudent – grade is Pass if average marks ≥ 50,


otherwise Fail.

 CollegeStudent – grade is First Class if average marks ≥ 60,


otherwise Second Class.

In the main program, create student objects. If the marks array is


empty, display as "Error: Marks cannot be empty."

Sample Input/Output:

John

60 70 80

Alice

Output:

Enter student name: John

Enter number of marks: 3

Student: John, Marks: {60, 70, 80}

Grade: Pass

Enter student name: Alice

Enter number of marks: 0

Student: Alice, Marks: {}

Error: Marks cannot be empty. y.

INTERFACE

5 Music Player System Easy

47
Question Bank Core Java
Problem Statement:
Design a music player system using interfaces in Java. Create an
interface MusicPlayer with two methods: play() and stop().
Implement two classes:

 MP3Player – displays play/stop messages for an MP3 player.

 CDPlayer – displays play/stop messages for a CD player.

In the main program, create objects of both classes and


demonstrate play and stop functionality.

Sample Input/Output:

MP3 Player playing music.


MP3 Player stopped.
CD Player playing music.
CD Player stopped.

6 Student Result Calculator Easy

Problem Statement:
Define an interface Result with a method calculateResult(int
marks). Create a class ExamResult that implements this interface.
If the marks are less than 0 or greater than 100 ,indicate as
invalid input.

Sample Input/Output:

Marks: 80 → Result: Pass


Marks: -10 → Error: Invalid marks

7 Shopping Cart System Medium

Problem Statement:
Define an interface CartOperations with two methods:
addItem(String item, double price) and checkout(). Implement a
class ShoppingCart that allows items to be added to the cart and
calculates the total at checkout. If the item name is null or the
price is less than or equal to zero display an error message.

Sample Input/Output:

Added Item: Laptop, Price: 50000.0


Added Item: null, Price: 2000
Error: Invalid item or price.
Checkout Total: 50000.0

48
Question Bank Core Java

Solve the following problems : Exception Handling

Questio
Question Detail Level
n No.

1 Easy
Bookstore Inventory
Problem Statement: You are developing a Java
application for a bookstore that manages book inventory.
As part of the application, you need to handle various
exceptions that may occur during the inventory
management process. Design and implement exception
handling for the following scenarios:
1. InputMismatchException Handling: When the
user inputs data for book quantity, there is a
possibility of encountering an
InputMismatchException if the input provided is

49
Question Bank Core Java
not a valid integer. Implement exception handling to
catch and handle this exception gracefully. Display
an error message informing the user about the
incorrect input format and prompt them to enter the
quantity again.
2. NumberFormatException Handling: When
processing book prices, there is a risk of
encountering a NumberFormatException if the
price entered by the user cannot be parsed as a
valid decimal number. Implement exception
handling to catch and handle this exception. Display
an error message indicating that the price format is
invalid and prompt the user to enter the price again.
3. ArrayIndexOutOfBoundsException Handling:
During the inventory update process, there is a
possibility of encountering an
ArrayIndexOutOfBoundsException if the user
attempts to access an array element with an invalid
index. Implement exception handling to catch and
handle this exception. Display an error message
indicating that the specified index is out of bounds
and prompt the user to enter a valid index.

Sample Input/Output:
Quantity: 5
Price: 250.50
Index: 2

Enter the quantity of books: 5


Enter the price of the book: $250.50
Enter the index of the book to update (0-4): 2
Updating inventory for book: Book3
2 Grocery Store Invoice Easy
Problme Statement: Create a class called Invoice that a
Grocery store might use to represent an invoice for an item
sold at the store. An Invoice should include four pieces of
information as instance variables—a part number (type
integer), a part description (type String), quantity of the

50
Question Bank Core Java
item being purchased (type integer) and a price per item
(double). Provide method constructor with four arguments.
Write a test application to create an instance and validate
the input obtained using Scanner object. Ensure that part
number is value greater than 0, part description is not null
string, quantity of the item and price per item is value
greater than 0.
Note : The InputMismatchException is thrown when
attempting to retrieve a value using the Scanner class that
doesn’t match the expected pattern or type.

Sample Input/output:
Part Number: 101
Part Description: Milk Pack
Quantity: 10
Price per Item: 55.50

Invoice Details:
Part Number: 101
Part Description: Milk Pack
Quantity: 10
Price Per Item: $55.5
3 Banking Application Medium
Problem Statement: You are developing a simple banking
application to manage customer accounts. One of the
requirements is to ensure that the withdrawal amount from
an account does not exceed the available balance.
Implement a custom exception called
InsufficientBalanceException to handle cases where the
withdrawal amount exceeds the available balance. Your
task is to modify the existing Account class to include
exception handling for withdrawals.
Your implementation should adhere to the following
specifications:
1. Define a custom exception class named
InsufficientBalanceException that extends the
Exception class. This class should have a
parameterized constructor that accepts a message

51
Question Bank Core Java
string.
2. Modify the Account class to include exception
handling for withdrawals:
 When a withdrawal is attempted, check if the
withdrawal amount is greater than the
available balance.
 If the withdrawal amount exceeds the
available balance, throw an
InsufficientBalanceException with an
appropriate error message.
 If the withdrawal amount is valid, deduct the
amount from the available balance.
3. In the main method or a separate testing class,
create an instance of the Account class with an
initial balance. Test the withdrawal functionality by
attempting to withdraw an amount that exceeds the
available balance. Handle the
InsufficientBalanceException appropriately by
displaying an error message.

Sample Input/Output:
Initial Balance: 1000
Withdrawal: 500

Withdrawal successful.
Updated balance: 500.0
4 Employee Management Medium
Problem Statement: Define an employee class with
properties Employee code, name, date of birth and date of
appointment. The Employee code must be a positive
integer number.
 Write a java program to read the above details and
validate the employee code. If the employee code is
not in the format specified , then raise an exception
called InvalidEmpNumberException.
 Verify if the date of birth is before the data of
appointment. If it is not so then raise an exception
called InvalidDateOfJoinException. If it is correct,

52
Question Bank Core Java
then create the Employee object and display the
details of employees and the number of years of
experience.

Sample Input/Output:
EmpCode: 1001
Name: John Doe
DOB: 1990-05-15
DOJ: 2015-08-20

Employee Code: 1001


Name: John Doe
Date of Birth: 1990-05-15
Date of Appointment: 2015-08-20
Years of Experience: 9
5 Account Management Medium
Problem Statement: Create a java class for handling an
Exception called ‘PayOutOfBoundsException’ and throw the
exception when the transaction amount exceeds the limit or
the amount is insufficient. (Maximum transaction limit is
30000).Create a class called ‘AccountManagement’ with
two methods named ‘checkForDebit’ and ‘withdrawAmount’
that uses PayOutOfBoundsException.(Keep Current balance
as 80000).

Sample Input/output:
Withdraw Amount: 20000
Transaction successful. Amount withdrawn: 20000.0

53
Question Bank Core Java

Solve the following problems

Questio
Question Detail Level
n No.

1 Sequential Thread Execution Easy

Problem Statement:
Write a Java program that creates two threads:

1. The first thread prints numbers from 1 to 10.

2. The second thread prints numbers from 11 to 20.

Ensure that the first thread completes its printing before the
second thread starts. Print the numbers along with the thread
name. Use synchronization if required.

Sample Output:

Thread-1: 1
Thread-1: 2
Thread-1: 3
Thread-1: 4
Thread-1: 5
Thread-1: 6
Thread-1: 7
Thread-1: 8
Thread-1: 9
Thread-1: 10
Thread-2: 11
Thread-2: 12
Thread-2: 13
Thread-2: 14
Thread-2: 15
Thread-2: 16
Thread-2: 17
Thread-2: 18
Thread-2: 19
Thread-2: 20

2 Using Runnable Interface Easy

54
Question Bank Core Java
Problem Statement:
Write a Java program that implements a custom thread using the
Runnable interface.

1. Create a class that implements Runnable.

2. Inside the run() method, print the thread name, then sleep
for 2 seconds, and print the thread name again.

3. Start this task with multiple threads.

Sample Output:

Thread-0 is running
Thread-1 is running
Thread-2 is running
Thread-0 finished after 2 seconds
Thread-1 finished after 2 seconds
Thread-2 finished after 2 seconds

3 Synchronization in Bank Account Easy

Problem Statement:
Write a Java program that simulates a bank account supporting
deposit and withdrawal operations.

1. Implement a BankAccount class with methods deposit(int


amount) and withdraw(int amount).

2. Ensure that multiple threads can perform deposits and


withdrawals concurrently, but synchronize the methods to
update the account balance correctly.

3. Create multiple threads performing deposits and


withdrawals on the same BankAccount object.

4. Print the operation performed, the amount, and the current


balance.

Sample Output:

Deposit 100 by Thread-1, Balance: 100


Deposit 200 by Thread-2, Balance: 300
Withdraw 50 by Thread-3, Balance: 250
Deposit 150 by Thread-1, Balance: 400
Withdraw 100 by Thread-2, Balance: 300

4 Producer-Consumer Using Threads Easy

Problem Statement:
Write a Java program to implement the Producer-Consumer
problem using threads.

55
Question Bank Core Java
1. Create a shared buffer (queue) for storing items (numbers).

2. Implement a Producer thread that generates numbers and


adds them to the buffer.

3. Implement a Consumer thread that removes numbers from


the buffer and processes them.

4. Use wait() and notify() methods to synchronize the producer


and consumer so that the producer waits if the buffer is full,
and the consumer waits if the buffer is empty.

5. Print messages whenever an item is produced or consumed


along with the current buffer size.

Sample Output:

Produced: 1
Consumed: 1
Produced: 2
Produced: 3
Consumed: 2
Produced: 4
Consumed: 3
Produced: 5
Consumed: 4
Consumed: 5

5 Thread Pool using Executor Service Mediu


m
Problem Statement:
Write a Java program that uses a thread pool to process a list of
tasks.

1. Create multiple tasks that simulate a time-consuming


operation (e.g., sleeping for a few seconds).

2. Use ExecutorService to manage a fixed number of threads


and execute the tasks efficiently.

3. Print messages indicating which thread is processing which


task.

4. Ensure that all tasks are completed before the program


terminates.

Sample Output:

Task 1 is being executed by pool-1-thread-1


Task 2 is being executed by pool-1-thread-2
Task 3 is being executed by pool-1-thread-3
Task 4 is being executed by pool-1-thread-1
Task 5 is being executed by pool-1-thread-2
All tasks completed.

6 Countdown Timer using a separate thread Mediu


m
Problem Statement:
Write a Java program that simulates a countdown timer using a

56
Question Bank Core Java
separate thread.

1. Create a thread that counts down from 10 to 0.

2. The thread should print the current count every second.

3. After the countdown finishes, the main thread should print


"Time's up!".

Sample Output:

Countdown: 10
Countdown: 9
Countdown: 8
Countdown: 7
Countdown: 6
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Countdown: 0
Time's up!

7 Printing Numbers in Sequence with Multiple Threads Mediu


m
Problem Statement:
Write a Java program where three threads print numbers in
sequence:

1. The first thread prints 1, the second thread prints 2, the


third thread prints 3, and then the sequence continues: 4, 5,
6….

2. The threads must execute in the correct order, so the


numbers appear in sequence without skipping or
overlapping.

3. Use synchronization or other thread coordination


mechanisms to ensure the correct order.

Sample Output:

Thread-1: 1
Thread-2: 2
Thread-3: 3
Thread-1: 4
Thread-2: 5
Thread-3: 6
Thread-1: 7
Thread-2: 8
Thread-3: 9
Thread-1: 10

57
Question Bank Core Java
8 Thread-Safe Counter using AtomicInteger Mediu
m
Problem Statement:
Write a Java program that implements a thread-safe counter using
AtomicInteger.

1. Create multiple threads that increment the counter


concurrently.

2. Use AtomicInteger to ensure thread-safe increments.

3. After all threads finish execution, print the final value of the
counter.

Sample Output:

Thread-0 incremented counter to 1


Thread-1 incremented counter to 2
Thread-2 incremented counter to 3
Thread-0 incremented counter to 4
Thread-1 incremented counter to 5
Thread-2 incremented counter to 6
Final Counter Value: 6

9 Synchronized Access to Shared List Mediu


m
Problem Statement:
Write a Java program where multiple threads read from and write
to a shared list of numbers.

1. Implement a shared ArrayList<Integer> as the resource.

2. Create writer threads that add numbers to the list.

3. Create reader threads that read and print the numbers in


the list.

4. Use synchronization to ensure that read and write


operations do not conflict and the list is updated correctly
when a thread writes to it.

Sample Output:

Writer-1 added 10
Writer-2 added 20
Reader-1 reads: [10]
Writer-1 added 30
Reader-2 reads: [10, 20, 30]
Writer-2 added 40
Reader-1 reads: [10, 20, 30, 40]

10 Simulation of Bank Account Mediu


m
Problem Statement:

Create a program to simulate a bank account. Implement a

58
Question Bank Core Java
BankAccount class with a synchronized method deposit (int
amount) to safely update the balance. Two threads deposit
different amounts concurrently. Ensure the final balance is correct.

Sample Input/Output:

Deposit Thread 1: 1000

Deposit Thread 2: 2000

Deposit Thread 1: 1000

Deposit Thread 2: 2000

Final Balance: 3000

Solve the following problems : Collections

59
Question Bank Core Java
Questio
Question Detail Level
n No.

1 Library Inventory Using ArrayList Mediu


Problem Statement: You are tasked with creating a m
program to manage a library's book inventory using
ArrayLists. Implement a Java class called LibraryInventory
with the following functionalities:

i. Adding Books:

a. Adds a new book title to the library


inventory.

ii. Removing Books:

a. Removes a specific book title from the


inventory. Returns true if the book was
successfully removed, false otherwise.

b. Removes books from the inventory based on


a specified condition.

iii. Searching and Checking:

a. Checks if a book with the given title exists in


the inventory. Returns true if found,
otherwise false.

b. Checks if the library inventory is empty.


Returns true if empty, otherwise false.

iv. Listing Books:

a. Lists all the books in the inventory, typically


alphabetically.

v. Sorting and Ordering:

a. Sorts the books in the inventory


alphabetically by title.

b. Sorts the books in the inventory


alphabetically by author.

vi. Size and Capacity:

a. Returns the number of books currently in the


inventory.

b. Increases the capacity of the inventory by


the specified amount.

vii. Iteration and Conversion:

a. Iterates over the inventory and prints each


book's title and author.

b. Converts the inventory ArrayList to a regular

60
Question Bank Core Java
array of book titles.

c. Returns a special iterator capable of


iterating over the inventory and performing
remove operations on the books.

viii. Additional Functionality:

a. Keeping track of the number of copies


available for each book.

b. Methods for lending and returning books,


which involve decrementing and
incrementing the available copies
respectively.

Sample Input/Output:
Books in library:

The Alchemist by Paulo Coelho

1984 by George Orwell

To Kill a Mockingbird by Harper Lee

Lending '1984'...

Returning '1984'...

Is 'The Alchemist' available? true

Is 'Moby Dick' available? false

Removing 'To Kill a Mockingbird'...

Books after removal:

The Alchemist by Paulo Coelho

1984 by George Orwell

Books sorted by title:

1984 by George Orwell

The Alchemist by Paulo Coelho

61
Question Bank Core Java
Books sorted by author:

The Alchemist by Paulo Coelho

1984 by George Orwell

Number of books: 2

Books as array:

1984

The Alchemist

2 Student List Management using LinkedList Mediu


Problem Statement: m
You are tasked with implementing a Java class called
LinkedList to manage a list of students using a linked list.
Include the following functionalities along with their
respective methods:

i. Adding Students:

a. Implement a method to add a new student to


the list.

ii. Removing Students:

a. Implement a method to remove a specific


student from the list by their name.

b. Implement a method to remove all students


with a specified age.

iii. Searching and Checking:

a. Implement a method to check if a student


with a given name exists in the list.

b. Implement a method to check if the list is


empty.

iv. Listing Students:

a. Implement a method to print the names of


all students in the list.

v. Size and Capacity:

a. Implement a method to get the total number


of students in the list.

b. Implement a method to increase the capacity


of the list by a specified amount.

vi. Iteration and Conversion:

a. Implement a method to iterate over the list

62
Question Bank Core Java
and print each student's name and age.

b. Implement a method to convert the linked


list to an array of student names.

c. Implement a method to return a special


iterator that iterates over the list and
performs remove operations on the
students.

d. Implement a method to return a descending


iterator that iterates over the list in reverse
order.

vii. Sorting and Ordering:

a. Implement a method to sort the students in


the list alphabetically by their names.

b. Implement a method to sort the students in


the list by their ages in ascending order.

viii. Additional Functionality:

a. Include functionality to keep track of each


student's age and grade.

b. Implement methods to update a student's


age or grade.

a. Implement a method to clear the entire list


of students.

Sample Input/Output:

Student Names:

Alice

Bob

Charlie

Diana

Contains Bob? true

Contains Eve? false

All Students:

Name: Alice, Age: 20, Grade: 85

63
Question Bank Core Java
Name: Bob, Age: 22, Grade: 90

Name: Charlie, Age: 20, Grade: 70

Name: Diana, Age: 23, Grade: 88

Sorting by Name:

Name: Alice, Age: 20, Grade: 85

Name: Bob, Age: 22, Grade: 90

Name: Charlie, Age: 20, Grade: 70

Name: Diana, Age: 23, Grade: 88

Sorting by Age:

Name: Alice, Age: 20, Grade: 85

Name: Charlie, Age: 20, Grade: 70

Name: Bob, Age: 22, Grade: 90

Name: Diana, Age: 23, Grade: 88

Updating Alice's age to 21 and grade to 92...

Name: Alice, Age: 21, Grade: 92

Name: Charlie, Age: 20, Grade: 70

Name: Bob, Age: 22, Grade: 90

Name: Diana, Age: 23, Grade: 88

Removing Bob...

Removing students with age 20...

Students after removals:

Name: Alice, Age: 21, Grade: 92

Name: Diana, Age: 23, Grade: 88

Total students: 2

Students as Array:

64
Question Bank Core Java
Alice

Diana

Descending Order Traversal:

Diana (23)

Alice (21)

Clearing the list...

Is list empty? true

3 Product list Management Using Vector Mediu


Problem Statement: m

You are tasked with implementing a Java class called


Vector to manage a list of products using a Vector.
Include the following functionalities along with their
respective methods:

i. Adding Products:

a. Implement a method to add a new product to


the vector.

ii. Removing Products:

a. Implement a method to remove a specific


product from the vector by its name.

b. Implement a method to remove all products


with a specified category.

iii. Searching and Checking:

a. Implement a method to check if a product


with a given name exists in the vector.

b. Implement a method to check if the vector is


empty.

iv. Listing Products:

a. Implement a method to print the details of


all products in the vector.

v. Size and Capacity:

a. Implement a method to get the total number


of products in the vector.

b. Implement a method to increase the capacity


of the vector by a specified amount.

c. Implement a method to trim the capacity of


the vector to its current size, removing any

65
Question Bank Core Java
unused capacity beyond the actual number
of elements stored.

vi. Iteration and Conversion:

a. Implement a method to iterate over the


vector and print each product's details.

b. Implement a method to convert the vector to


an array of product objects.

vii. Sorting and Ordering:

a. Implement a method to sort the products in


the vector alphabetically by their names.

b. Implement a method to sort the products in


the vector by their prices in ascending order.

viii. Additional Functionality:

a. Include functionality to keep track of each


product's category and price.

b. Implement methods to update a product's


category or price.

c. Implement a method to clear the entire


vector of products.

Sample Input/Output:
All Products:

Name: Laptop, Category: Electronics, Price: 75000.0

Name: Shirt, Category: Clothing, Price: 1500.0

Name: Phone, Category: Electronics, Price: 30000.0

Name: Shoes, Category: Footwear, Price: 3500.0

Contains 'Laptop'? true

Contains 'Tablet'? false

Removing 'Shirt'...

Removing all Electronics...

Products after removals:

Name: Shoes, Category: Footwear, Price: 3500.0

66
Question Bank Core Java
Sorting by Price:

Name: Bag, Category: Accessories, Price: 1200.0

Name: Watch, Category: Accessories, Price: 2000.0

Name: Shoes, Category: Footwear, Price: 3500.0

Sorting by Name:

Name: Bag, Category: Accessories, Price: 1200.0

Name: Shoes, Category: Footwear, Price: 3500.0

Name: Watch, Category: Accessories, Price: 2000.0

Updating 'Bag' category to 'Travel' and price to 1800...

Name: Bag, Category: Travel, Price: 1800.0

Name: Shoes, Category: Footwear, Price: 3500.0

Name: Watch, Category: Accessories, Price: 2000.0

Total Products: 3

Products via Array Conversion:

Bag - Travel - 1800.0

Shoes - Footwear - 3500.0

Watch - Accessories - 2000.0

Increasing capacity by 5...

Trimming capacity to size...

Clearing all products...

Is vector empty? true

4 Books Management Using stack Mediu


Problem Statement: m
You are tasked with managing a stack of books using a
Java class called Stack and a Stack. Given the following
initial books:

1. Title: "The Great Gatsby", Author: "F. Scott


Fitzgerald", Publication Year: 1925

67
Question Bank Core Java
2. Title: "To Kill a Mockingbird", Author: "Harper Lee",
Publication Year: 1960

3. Title: "1984", Author: "George Orwell", Publication


Year: 1949

i. Pushing Books:

a. Implement a method to push a new book


onto the stack.

ii. Popping Books:

a. Implement a method to pop the top book


from the stack.

b. Implement a method to remove and return


the top book from the stack using the poll()
method.

iii. Peeking:

a. Implement a method to peek at the top book


of the stack without removing it.

iv. Searching and Checking:

a. Implement a method to check if a book To


Kill a Mockingbird exists in the stack.

b. Implement a method to check if the stack is


empty.

v. Listing Books:

a. Implement a method to print the titles of all


books in the stack.

vi. Size and Capacity:

a. Implement a method to get the total number


of books in the stack.

b. Implement a method to increase the capacity


of the stack by a specified amount.

vii. Iteration and Conversion:

a. Implement a method to iterate over the


stack and print each book's title.

viii. Additional Functionality:

a. Include functionality to keep track of each


book's author and publication year.

b. Implement methods to update a book's


author or publication year.

c. Implement a method to clear the entire stack

68
Question Bank Core Java
of books.

Sample Input/Output:
Books in stack:

- The Great Gatsby

- To Kill a Mockingbird

- 1984

Total books: 3

Pushed: Moby Dick

Peek top: Moby Dick by Herman Melville (1851)

Popped: Moby Dick by Herman Melville (1851)

Contains 'To Kill a Mockingbird'? true

Updated author of 1984 to Orwell, George

Updated publication year of The Great Gatsby to 1926

Polled book: 1984 by Orwell, George (1949)

Iterating stack:

The Great Gatsby

To Kill a Mockingbird

Stack cleared.

Is stack empty? true

5 Priority Queue Mediu


Problem Statement: m
Create a new Java class named Queue. Import the
necessary Java Collection [Link] a Priority
Queue object named "integerQueue" where elements are
ordered specified by a custom Comparator and perform
the following operations:

a. Adding Elements:

i. Add the following integers to the


integerQueue: 10, 20, 30, 40.

b. Removing Elements:

i. Remove the head element from the


integerQueue.

c. Accessing Elements:

i. Peek at the head element of the


integerQueue without removing it.

69
Question Bank Core Java
b. Checking Queue Status:

i. Check whether the integerQueue is


empty.

ii. Determine and print the size of the


integerQueue.

e. Custom Comparator:

i. Implement a custom Comparator class


that orders integers in descending
order.

f. Clearing the Queue:

i. Clear all elements from the


integerQueue.

ii. Verify whether the integerQueue is


empty after clearing.

Sample Input/Output:

Iterating through the elements of the integerQueue:

30

10

20

Array representation of the integerQueue: [30, 10, 20]

6 Char PriorityQueue Mediu


Problem Statement: m
Create a new Java class named PriorityQueueChar. Import
the necessary Java Collection classes. Initialize a Priority
Queue object named "charQueue" where elements are
ordered based on their ASCII values, with the element
with the maximum ASCII value having the highest priority
and perform the following operations:

a. Adding Elements:

i. Add the following characters to the


charQueue: 'a', 'b', 'c', 'd'.

b. Removing Elements:

i. Remove the head element from the


charQueue.

c. Accessing Elements:

i. Peek at the head element of the


charQueue without removing it.

70
Question Bank Core Java
b. Checking Queue Status:

i. Check whether the charQueue is


empty.

ii. Determine and print the size of the


charQueue.

e. Custom Comparator:

i. Implement a custom Comparator class


that orders characters based on their
ASCII values, ensuring the element
with the maximum ASCII value has the
highest priority.

f. Iteration and Conversion:

i. Iterate through the elements of the


charQueue and print each element.

ii. Convert the charQueue into an array


and print the resulting array.

b. Clearing the Queue:

i. Clear all elements from the


charQueue.

Verify whether the charQueue is empty after clearing.

Sample Input/output:

Iterating through the elements of the charQueue:

Array representation of the charQueue: [c, a, b]

7 LinkedHashMap Mediu
Problem Statement: m
Create a new Java class named LinkedHashMap. Import
the necessary Java Collection classes. Initialize a
LinkedHashMap named "linkedHashMap" to store key-
value pairs and perform the following operations:

a. Adding Key-Value Pairs:

i. Add the following key-value pairs to


the linkedHashMap: {1:"Hello", 2:"hi",
3:"Morning", 4:"Good", 5:"day"}.

ii. Add a null key with the value


"NullValue1".

71
Question Bank Core Java
iii. Add multiple null values.

b. Copying Mappings:

i. Create a new LinkedHashMap named


"copyMap".

ii. Copy all mappings from the


linkedHashMap to the copyMap.

b. Retrieving Values:

i. Retrieve and print the value


associated with the key 3.

e. Removing a Mapping:

i. Remove the mapping for the key 4


from the linkedHashMap.

f. Checking for Key Presence:

i. Check if the linkedHashMap contains


the key 2.

ii. Check if the linkedHashMap contains


the value "Morning".

g. Checking LinkedHashMap Status:

i. Check if the linkedHashMap is empty.

ii. Determine and print the number of


key-value mappings in the
linkedHashMap.

b. Iterating Over Entries:

i. Iterate through the entries of the


linkedHashMap and print each key-
value pair.

i. Retrieving Keys and Values:

i. Retrieve and print the set of keys in


the linkedHashMap.

Retrieve and print the collection of values in the


linkedHashMap.

Sample Input/output:
Value associated with key 3: Morning

Contains key 2: true

Contains value 'Morning': true

Is linkedHashMap empty: false

72
Question Bank Core Java
Size of linkedHashMap: 7

Entries of linkedHashMap:

1:Hello

2:hi

3:Morning

5:day

null:NullValue1

6:null

7:null

Keys in linkedHashMap: [1, 2, 3, 5, null, 6, 7]

Values in linkedHashMap: [Hello, hi, Morning, day,


NullValue1, null,null]

8 Initialize a Character Using TreeSet Mediu


Problem Statement: m
Create a new Java class named TreeSetChar. Import the
necessary Java Collection classes. Initialize a TreeSet
named "charSet" to store characters. Add the characters
{'b', 'a', 'c', 'f', 'e', 'd'} to the charset Perform the
following operations and Sort the charset in natural
ordering.

a. Adding Elements:

i. Add an integer value g to the charSet.

b. Removing Elements:

i. Remove an integer value c from the


charSet.

c. Checking if Set Contains Elements:

i. Check if the charSet contains ‘e’ in


charset

b. Checking Set Status:

i. Check if the charSet is empty.

ii. Determine the size of the charSet

e. Iterating Over Set:

i. Iterate through the elements of the


charSet and print each element.

f. Retrieving First and Last Elements:

i. Retrieve and print the first (lowest)


element and last (highest) element.

73
Question Bank Core Java
g. Polling First and Last Elements:

i. Retrieve and remove the first (lowest)


element and the last (highest)
element.

b. Clearing the Stack:

i. Clear all elements from the


integerStack.

ii. Verify whether the integerStack is


empty after clearing.

Sample Input/Output:
Output:

Elements of charSet:

First element: a

Last element: g

Polled first element: a

Polled last element: g

CharSet after operations: [b, d, e, f]

9 TreeSet Mediu
Problem Statement: m
Create a new Java class named TreeSetCharacter. Import
the necessary Java Collection classes. Define a custom
Comparator for characters to reverse the order. Initialize
a TreeSet named "charSet" to store characters, sorted
according to the custom Comparator. Add the characters
{'z', 'a', 'b', 'c', 'x', 'y'} to the charset and perform the
following operations:

a. Adding Elements:

i. Add a character value 'd' to the


charSet.

b. Removing Elements:

i. Remove a character value 'x' from the


charSet.

74
Question Bank Core Java
c. Checking if Set Contains Elements:

i. Check if the charSet contains a


specific character 'b'.

b. Checking Set Status:

i. Check if the charSet is empty.

ii. Determine the size of the charSet.

e. Iterating Over Set:

i. Iterate through the elements of the


charSetand print each element.

f. Retrieving First and Last Elements:

i. Retrieve and print the first (lowest)


element and last (highest) element.

g. Polling First and Last Elements:

Retrieve and remove the first (lowest) element and last


(highest) element.

Sample Input/Output:
Elements of charSet:

First element: z

Last element: a

Polled first element: z

Polled last element: a

CharSet after operations: [y, d, c, b]

10 WordCount using HashMap Mediu


Problem Statement: m
Create a new Java class named HashMap. Import the
necessary Java Collection classes. Initialize a HashMap
named "wordCountMap" to store words (String) as keys
and their corresponding counts (Integer) as values. Add
the following entries to the wordCountMap and perform
the following operations:

75
Question Bank Core Java
i. Adding Key-Value Pairs:

a. Add the following key-value pairs to the


wordCountMap: - "apple" : 5 - "banana" : 8 -
"cherry" : 3 - "date" : 6 - "grape" : 4

ii. Copying Mappings:

a. Create a new HashMap named "copyMap". ii.


Copy all mappings from the wordCountMap
to the copyMap.

iii. Retrieving Values:

a. Retrieve and print the count associated with


the word "date".

iv. Removing a Mapping:

a. Remove the mapping for the word "cherry"


from the wordCountMap.

v. Checking for Key Presence:

a. Check if the wordCountMap contains the


word "banana". ii. Check if the
wordCountMap contains the count 4.

vi. Checking HashMap Status:

a. Check if the wordCountMap is empty. ii.


Determine and print the number of key-value
mappings in the wordCountMap.

vii. Iterating Over Entries:

a. Iterate through the entries of the


wordCountMap and print each word-count
pair.

viii. Retrieving Keys and Values:

a. Retrieve and print the set of words in the


wordCountMap. ii. Retrieve and print the
collection of counts in the wordCountMap.

Sample Input/Output:
Count associated with 'date': 6
Contains 'banana': true
Contains count 4: true
Is wordCountMap empty: false
Number of mappings in wordCountMap: 4
Entries of wordCountMap:
Word: apple, Count: 5
Word: banana, Count: 8
Word: date, Count: 6
Word: grape, Count: 4

76
Question Bank Core Java
Words in wordCountMap: [apple, banana, date, grape]
Counts in wordCountMap: [5, 8, 6, 4]

// Extra Questions

ArrayDeque
Problem Statement:

Create a new Java class named ArrayDeque. Import the


necessary Java Collection [Link] an ArrayDeque
object named "integerDeque" to store integers and
perform the following operations:

a. Adding Elements:

i. Add the following integers to the


integerDeque: 12, 24, 45, 67, 87, 43.

a. Adding Elements at Both Ends:

i. Add the integer 100 to the beginning


of the integerDeque.

ii. Add the integer 200 to the end of the


integerDeque.

i. Removing Elements:

i. Remove and retrieve the first element


from the integerDeque.

ii. Remove and retrieve the last element


from the integerDeque.

d. Accessing Elements:

i. Retrieve, but do not remove, the first


element of the integerDeque.

ii. Retrieve, but do not remove, the last


element of the integerDeque.

iii. Retrieve an element from the


integerDeque at a random index and
print it.

e. Checking Deque Status:

i. Check whether the integerDeque is


empty.

ii. Determine and print the size of the


integerDeque.

f. Dynamic Resizing:

i. Add the integers 300, 400, 500, 600,


700, 800, 900 to the integerDeque,
observing how it dynamically resizes
to accommodate the additional

77
Question Bank Core Java
elements.

ii. Remove several elements from the


integerDeque, ensuring it dynamically
shrinks when elements are removed.

h. Iteration and Conversion:

i. Iterate through the elements of the


integerDeque and print each element.

ii. Convert the integerDeque into an


array and print the resulting array.

j. Clearing the Deque:

iii. Clear all elements from the


integerDeque.

iv. Verify whether the integerDeque is


empty after clearing.

Sample Input/Output:
Deque after dynamic resizing: [12, 24, 45, 67, 87, 43,
300, 400, 500, 600, 700, 800, 900]

Deque after removing elements: [12, 24, 45, 67, 87, 43,
300, 400, 500, 600]

Iterating through the elements of the integerDeque:

12

24

45

67

87

43

300

400

500

600

Array representation of the integerDeque: [12, 24, 45,


67, 87, 43, 300, 400, 500, 600]

Vehicle Type Using LinkedHashMap


Problem Statement:
Create a new Java class named LinkedHashMap. Import
the necessary Java Collection classes. Initialize a
LinkedHashMap named "vehicleTypeMap" to store vehicle
types (String) as keys and their corresponding categories

78
Question Bank Core Java
(String) as values. Use the following key-value pairs:

{"car": "sedan", "truck": "pickup", "motorcycle":


"sportbike", "van": "minivan", "suv": "crossover"}

Perform the following operations:

i. Adding Key-Value Pairs:

a. Add the given key-value pairs to the


vehicleTypeMap.

ii. Copying Mappings:

a. Create a new LinkedHashMap named


"copyMap".

b. Copy all mappings from the vehicleTypeMap


to the copyMap.

iii. Retrieving Values:

a. Retrieve and print the category associated


with the vehicle type "motorcycle".

iv. Removing a Mapping:

a. Remove the mapping for the vehicle type


"van" from the vehicleTypeMap.

v. Checking for Key Presence:

a. Check if the vehicleTypeMap contains the


vehicle type "suv".

b. Check if the vehicleTypeMap contains the


category "pickup".

vi. Checking LinkedHashMap Status:

a. Check if the vehicleTypeMap is empty.

b. Determine and print the number of key-value


mappings in the vehicleTypeMap.

vii. Iterating Over Entries:

a. Iterate through the entries of the


vehicleTypeMap and print each vehicle type-
category pair.

viii. Retrieving Keys and Values:

a. Retrieve and print the set of vehicle types in


the vehicleTypeMap.

Retrieve and print the collection of categories in the


vehicleTypeMap.

79
Question Bank Core Java

Solve the following problems : Lambda Expression and Stream API

Q.
Question Detail
No.

1 Count Vowels in a String


Problem Statement:
Create a custom functional interface VowelCounter with a method int count(String str)
that returns the number of vowels in a given string. Use a lambda to implement it.
Functional Interface:
interface VowelCounter { int count(String str); }

Sample Input:
Enter a string: Lambda
Sample Output:
Number of vowels: 2
2 Number Divisibility Checker
Problem Statement:
Create a custom functional interface DivisibilityChecker with a method boolean
isDivisible(int n, int divisor) that checks if a number is divisible by another number. Use a
lambda to implement it.
Functional Interface:
interface DivisibilityChecker { boolean isDivisible(int n, int divisor); }

Sample Input:
Enter number: 24
Enter divisor: 6
Sample Output:
24 is divisible by 6: true
3 Java Stream API Operations on E-Commerce Product Inventory
You are tasked with developing a Java application to manage and analyze product
information for an e-commerce system. The product data is stored as an
ArrayList<Product>, where You are working as a Java developer for a retail inventory
management system. Your task is to model product data using object-oriented principles

80
Question Bank Core Java
and perform various data processing operations using Java's Stream API.
The system maintains a list of products, each with details such as name, category, brand,
price, stock quantity, units sold, and creation date. You are required to:
1. Model the product using a Product class with appropriate fields and methods.
2. Store a list of products in memory using an ArrayList<Product>, where each
Product object contains the following fields:
3. id: Product ID (integer)
4. name: Product name (string)
5. category: Product category (e.g., Laptop, Mobile, Headphones)
6. brand: Manufacturer brand (string)
7. price: Product price (double)
8. quantity: Units available in stock (integer)
9. unitsSold: Total units sold so far (integer)
[Link]: Date the product was added (LocalDate)

Consider the sample data below for the processing,


new Product(1, "iPhone 13", "Mobile", "Apple", 69999.00, 20, 150, [Link](2024, 5,
1)),
new Product(2, "Galaxy S22", "Mobile", "Samsung", 64999.00, 15, 120, [Link](2024,
6, 15)),
new Product(3, "Dell Inspiron 15", "Laptop", "Dell", 55999.00, 10, 70, [Link](2024,
4, 10)),
new Product(4, "MacBook Air M2", "Laptop", "Apple", 99999.00, 5, 90, [Link](2024,
7, 1)),
new Product(5, "Sony WH-1000XM4", "Headphones", "Sony", 19999.00, 30, 200,
[Link](2024, 3, 20)),
new Product(6, "HP Pavilion x360", "Laptop", "HP", 49999.00, 12, 40, [Link](2024,
5, 10)),
new Product(7, "OnePlus Nord CE", "Mobile", "OnePlus", 24999.00, 25, 100,
[Link](2024, 4, 5)),
new Product(8, "Lenovo Tab M10", "Tablet", "Lenovo", 17999.00, 18, 60,
[Link](2024, 6, 1)),
new Product(9, "Samsung Galaxy Tab A7", "Tablet", "Samsung", 20999.00, 20, 80,
[Link](2024, 6, 20)),
new Product(10, "Realme Buds Air 3", "Headphones", "Realme", 3999.00, 50, 250,
[Link](2024, 2, 28))

Execute the operations below using stream API

81
Question Bank Core Java

1. Group Products by Category


Organize products into groups based on their category and display the number of
products in each group.
2. Map Brand to Product Names
Create a mapping where each brand is associated with a list of its product names.
3. Fetch Recently Added Products
List all products added in the last 60 days, based on their creation date.
4. Find Products by Category and Price Range
Retrieve all products that belong to the "Laptop" category and are priced between
₹40,000 and ₹80,000.
5. Find Products with Zero Sales
List all products that have unitsSold equal to 0.
6. Count Products per Brand
Count how many products each brand offers and display the result as a map.
7. Find the Product with the Highest Stock Value
Determine which product has the highest stock value (i.e., price × quantity).
8. Generate Summary Statistics for Product Prices
Use DoubleSummaryStatistics to display the count, min, max, average, and sum of
product prices.
9. Group Products by Brand and Count Units Sold
Group products by brand and calculate the total units sold for each brand.
[Link] the Most Recently Added Product
Identify and display the product with the most recent createdDate.

Solve the following problems : JDBC

Questio
Question Detail Level
n No.

1 Student Management System with MySQL Mediu


m
Problem Statement:

Design and implement a Java Swing application that simulates a

82
Question Bank Core Java
Student Management System connected to a MySQL database.

Requirements:

1) Authentication

 On launching the application, display a Sign-In Page.

 The application must connect to MySQL and create the


database and users table if not already existing.

 Authentication must be done using username and


password stored in the database.

 If login is successful, navigate to the Dashboard.


Otherwise, display an error message ("Invalid username
or password").

2) Dashboard

 Displays a welcome message with the logged-in


username.

 Provides buttons to perform Student Operations.

 A Sign-Out button must return to the login page and clear


session data.

3) Student Operations (All data stored in MySQL)

From the Dashboard, allow the user to perform the following via
Swing forms:

 Add Student → Enter ID, Name, Course, and Email →


Insert into the students table.

 View Students → Display all students in a JTable


(retrieved from the database).

 Update Student → Select a student and update their


details.

 Delete Student → Remove a student from the table.

4) Database Handling

 The program must create the database and required


tables (users, students) automatically if they don’t exist.

 Insert a default user (e.g., username: admin, password:


12345) when the database is first created.

83

You might also like