Question 1:
Write a Java program that greets the user with various messages based on their age. Implement
the ‘Main’ class with the following methods:
sayHello(): This method takes no parameters and returns a string containing the message "Hello".
sayHello(String name): This method takes a string name as input and returns a string containing
the message "Hello <name>".
greetBasedOnAge(int age): This method takes an integer age as input and returns a string
containing a custom greeting message based on the age as follows:
If the age is less than 0, return "Invalid age. Please provide a valid age."
If the age is less than 18, return "Hey, kiddo!"
If the age is less than 60, return "Hello, adult!"
Otherwise, return "Greetings, senior citizen!"
Input Format:
The program expects the following inputs from the user:
A single line containing a string representing the user's name.
A single line containing an integer representing the user's age.
Output Format:
The program will produce the following output:
A single line displaying the greeting message "Hello".
A single line displaying the personalized greeting message "Hello <name>".
A single line displaying the custom greeting message based on the user's age.
Title for Question 1: Greet based on age
Solution:
import java.util.*;
class Main {
public String sayHello(){
return "Hello";
}
public String sayHello(String s){
return "Hello " + s;
}
public String greetBasedOnAge(int age){
if (age < 0) {
return "Invalid age. Please provide a valid age.";
} else if (age < 18) {
return "Hey, kiddo!";
} else if (age < 60) {
return "Hello, adult!";
} else {
return "Greetings, senior citizen!";
}
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String name = in.nextLine();
Main s = new Main();
System.out.println(s.sayHello());
System.out.println(s.sayHello(name));
// System.out.print("Enter your age: ");
int age = in.nextInt();
System.out.println(s.greetBasedOnAge(age));
}
}
TestCases:
S.No Inputs Outputs
1 Emma 65 Hello Hello Emma Greetings, senior citizen!
2 Robert 35 Hello Hello Robert Hello, adult!
3 Sophia -5 Hello Hello Sophia Invalid age. Please provide a valid age.
4 Peter 68 Hello Hello Peter Greetings, senior citizen!
5 Alice 10 Hello Hello Alice Hey, kiddo!
6 John 20 Hello Hello John Hello, adult!
Question 2:
Develop a program that asks the user to enter their age. Implement exception handling to handle
cases where the user enters non-numeric data or negative numbers.
Input Format:
A single line containing a value that represents age. This value can be an integer or any other type
of input, as the program handles validation.
Output Format:
There can be multiple lines in the output based on the input validation.
If the user inputs a valid non-negative age:
Thank you! Your age is <AGE>
Where <AGE> is the valid age entered.
If the user inputs a negative number:
Age cannot be negative. Please enter a valid age.
If the user inputs a non-numeric value:
That's not a valid number. Please enter a numeric value for age.
In cases of invalid input (both negative or non-numeric), the program will continue to prompt the
user for valid input. The output will show the corresponding error message for each invalid input
attempt.
Title for Question 2: Input Validation
Solution:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int age = -1;
while (age < 0) {
// System.out.print("Please enter your age: ");
try {
age = scanner.nextInt();
if (age < 0) {
System.out.println("Age cannot be negative. Please enter
}
} catch (InputMismatchException e) {
System.out.println("That's not a valid number. Please enter
scanner.next(); // Clear the invalid input
}
}
System.out.println("Thank you! Your age is " + age);
}
}
TestCases:
S.No Inputs Outputs
That's not a valid number. Please enter a numeric value for age. Thank
1 @@ 45
you! Your age is 45
2 0 Thank you! Your age is 0
Age cannot be negative. Please enter a valid age. Age cannot be
-10 -5
3 negative. Please enter a valid age. That's not a valid number. Please
world 35
enter a numeric value for age. Thank you! Your age is 35
That's not a valid number. Please enter a numeric value for age. Thank
4 hello 23
you! Your age is 23
Age cannot be negative. Please enter a valid age. Thank you! Your age
5 -15 8
is 8
-5 twenty Age cannot be negative. Please enter a valid age. That's not a valid
6
30 number. Please enter a numeric value for age. Thank you! Your age is 30
Question 3:
Write a program that prompts the user to enter a password and then checks if it meets certain
criteria (e.g., length, presence of special characters). Implement exception handling to handle
cases where the password doesn't meet the required criteria.
Input Format:
The program will prompt the user to enter a password.
The user should input the password as a single line of text.
Output Format:
If the entered password meets all the specified criteria, the program will display the message
"Password is valid."
If the entered password does not meet the required criteria, the program will display an error
message indicating the reason for the invalid password.
Title for Question 3: Password Validation
Solution:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// System.out.println("Enter your password: ");
String password = scanner.nextLine();
validatePassword(password);
System.out.println("Password is valid.");
} catch (InvalidPasswordException e) {
System.out.println("Invalid password: " + e.getMessage());
}
scanner.close();
}
public static void validatePassword(String password) throws InvalidPassw
if (password.length() < 8) {
throw new InvalidPasswordException("Password must be at least 8
}
if (!password.matches(".*[a-z]+.*")) {
throw new InvalidPasswordException("Password must contain at lea
}
if (!password.matches(".*[A-Z]+.*")) {
throw new InvalidPasswordException("Password must contain at lea
}
if (!password.matches(".*\\d+.*")) {
throw new InvalidPasswordException("Password must contain at lea
}
if (!password.matches(".*[!@#$%^&*]+.*")) {
throw new InvalidPasswordException("Password must contain at lea
}
}
}
class InvalidPasswordException extends Exception {
public InvalidPasswordException(String message) {
super(message);
}
}
TestCases:
S.No Inputs Outputs
1 @#$%^&*() Invalid password: Password must contain at least one letter.
Invalid password: Password must contain at least one
2 Password123
special character.
3 StrongPassword123@ Password is valid.
Invalid password: Password must be at least 8 characters
4 weak1@
long.
Invalid password: Password must be at least 8 characters
5 123456*
long.
6 Herkfbv#ddg21245 Password is valid.
Question 4:
Write a program to read the Register Number and Mobile Number of a student. Create user defined
exception and handle the following:
If the Register Number does not contain exactly 9 characters in specified format(2 numbers
followed by 3 characters followed by 4 numbers) or if the Mobile Number does not contain exactly
10 characters, throw an IllegalArgumentException.
If the Mobile Number contains any character other than a digit, raise a NumberFormatException.
If the Register Number contains any character other than digits and alphabets, throw a
NoSuchElementException.
If they are valid, print the message ‘valid’ else ‘Invalid’.
Input Format :
Register number as a string in the first line
Mobile number as a string in the second line
Output Format :
Valid or Invalid with exception message
Refer sample outputs for format and exact text
Title for Question 4: Student Register
Solution:
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main{
static void validate(String r, String n){
if(r.length() != 9){
System.out.println("Invalid");
throw new IllegalArgumentException("Register Number does not contain exactly
}
if(n.length() != 10){
System.out.println("Invalid");
throw new IllegalArgumentException("Mobile Number does not contain exactly 1
}
// String pattern = "^[6|7|8|9]{1}\\d{9}";
String pattern = "^[1-9]([0-9]){9,9}$";
Pattern a = Pattern.compile(pattern);
Matcher m1 = a.matcher(n);
if(!m1.find()){
System.out.println("Invalid");
throw new NumberFormatException("Mobile Number cannot contain any character
}
String pattern2 = "^[1-9][0-9]([A-Z]){3,3}([0-9]){4,4}$";
Pattern b = Pattern.compile(pattern2);
Matcher m2 = b.matcher(r);
if(!m2.find()){
System.out.println("Invalid");
throw new NoSuchElementException("Registration Number cannot contain any cha
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String reg = sc.nextLine();
String no = sc.nextLine();
sc.close();
try {
validate(reg, no);
System.out.println("Valid");
}catch(Exception e)
{
System.out.println(e);
}
}
}
TestCases:
S.No Inputs Outputs
12X567 Invalid java.lang.IllegalArgumentException: Register Number does
1
1234567A90 not contain exactly 9 characters
12XYZ567 Invalid java.lang.IllegalArgumentException: Register Number does
2
1234567890 not contain exactly 9 characters
12XYZ5678 Invalid java.lang.IllegalArgumentException: Mobile Number does
3
123456789 not contain exactly 10 characters
Invalid java.util.NoSuchElementException: Registration Number
X12YZ5678
4 cannot contain any character other than digits and alphabets in
1234567890
format specified
12XYZ5678 Invalid java.lang.NumberFormatException: Mobile Number cannot
5
12345A7890 contain any character other than a digit
12XYZ5678
6 Valid
1234567890
Question 5:
Create an Employee class with attributes like name, age, and salary. Include a method
display_info() that prints out the general information of the employee. Then, create two subclasses
(Manager and Programmer) that inherit from the Employee class. Override the display_info()
method in each subclass to display additional information specific to managers and programmers,
such as the number of subordinates managed for managers and programming languages known
for programmers. Write a program to demonstrate method overriding by creating instances of both
employee types and calling their display_info() method.
Input format:
Employee Input:
The first line contains the name of the employee (a string).
The second line contains the age of the employee (an integer).
The third line contains the salary of the employee (a double).
Manager Input:
The first line contains the name of the manager (a string).
The second line contains the age of the manager (an integer).
The third line contains the salary of the manager (a double).
The fourth line contains the number of subordinates the manager has (an integer).
Programmer Input:
The first line contains the name of the programmer (a string).
The second line contains the age of the programmer (an integer).
The third line contains the salary of the programmer (a double).
The fourth line contains a space-separated list of programming languages known by the
programmer (multiple strings).
Output format :
Employee Output:
The name, age, and salary of the employee will be displayed.
Manager Output:
The name, age, and salary of the manager will be displayed.
The number of subordinates the manager has will also be displayed.
Programmer Output:
The name, age, and salary of the programmer will be displayed.
The list of programming languages known by the programmer will also be displayed, with each
language printed on a separate line preceded by a hyphen.
Title for Question 5: Employee inheritance
Solution:
import java.util.Scanner;
class Employee {
private String name;
private int age;
private double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age + ", Salary: "
}
}
class Manager extends Employee {
private int numSubordinates;
public Manager(String name, int age, double salary, int numSubordinates)
super(name, age, salary);
this.numSubordinates = numSubordinates;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Number of Subordinates: " + numSubordinates);
}
}
class Programmer extends Employee {
private String[] programmingLanguages;
public Programmer(String name, int age, double salary, String[] programm
super(name, age, salary);
this.programmingLanguages = programmingLanguages;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Programming Languages Known: ");
for (String language : programmingLanguages) {
System.out.println("- " + language);
}
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Input for Employee
String empName = input.nextLine();
int empAge = input.nextInt();
double empSalary = input.nextDouble();
input.nextLine(); // Consume the newline left by nextDouble()
Employee employee = new Employee(empName, empAge, empSalary);
// Input for Manager
String mgrName = input.nextLine();
int mgrAge = input.nextInt();
double mgrSalary = input.nextDouble();
int numSubordinates = input.nextInt();
input.nextLine();
Manager manager = new Manager(mgrName, mgrAge, mgrSalary, numSubordi
// Input for Programmer
String progName = input.nextLine();
int progAge = input.nextInt();
double progSalary = input.nextDouble();
input.nextLine();
String languagesInput = input.nextLine();
String[] programmingLanguages = languagesInput.split(" ");
Programmer programmer = new Programmer(progName, progAge, progSalary
input.close();
System.out.println("Employee Information:");
employee.displayInfo();
System.out.println("Manager Information:");
manager.displayInfo();
System.out.println("Programmer Information:");
programmer.displayInfo();
}
}
TestCases:
S.No Inputs Outputs
Employee Information: Name: Elizabeth Brown, Age: 35,
Elizabeth Brown 35
Salary: 75000.0 Manager Information: Name:
75000.0 Christopher
Christopher Wilson, Age: 38, Salary: 92000.0 Number of
1 Wilson 38 92000.0 3
Subordinates: 3 Programmer Information: Name: Daniel
Daniel Martin 26 59000.0
Martin, Age: 26, Salary: 59000.0 Programming
Java Python C# Go
Languages Known: - Java - Python - C# - Go
Employee Information: Name: Jennifer Lee, Age: 29,
Jennifer Lee 29 60000.0
Salary: 60000.0 Manager Information: Name: David
David Johnson 42
Johnson, Age: 42, Salary: 88000.0 Number of
2 88000.0 6 William Smith
Subordinates: 6 Programmer Information: Name: William
31 62000.0 C#
Smith, Age: 31, Salary: 62000.0 Programming
JavaScript TypeScript
Languages Known: - C# - JavaScript - TypeScript
Employee Information: Name: Robert Miller, Age: 33,
Robert Miller 33 65000.0 Salary: 65000.0 Manager Information: Name: Nancy
Nancy Williams 39 Williams, Age: 39, Salary: 95000.0 Number of
3
95000.0 4 Matthew Davis Subordinates: 4 Programmer Information: Name:
27 58000.0 Java C++ Matthew Davis, Age: 27, Salary: 58000.0 Programming
Languages Known: - Java - C++
S.No Inputs Outputs
Employee Information: Name: Michael Jackson, Age: 45,
Michael Jackson 45
Salary: 100000.0 Manager Information: Name: Maria
100000.0 Maria Garcia
Garcia, Age: 37, Salary: 85000.0 Number of
4 37 85000.0 2 Emily Clark
Subordinates: 2 Programmer Information: Name: Emily
29 60000.0 Java Python
Clark, Age: 29, Salary: 60000.0 Programming Languages
Ruby C++
Known: - Java - Python - Ruby - C++
Employee Information: Name: Sech Green, Age: 28,
Sech Green 28 55000.0 Salary: 55000.0 Manager Information: Name: Bob White,
Bob White 40 90000.0 3 Age: 40, Salary: 90000.0 Number of Subordinates: 3
5
Sam Brown 32 70000.0 Programmer Information: Name: Sam Brown, Age: 32,
C# JavaScript Salary: 70000.0 Programming Languages Known: - C# -
JavaScript
Employee Information: Name: Frank, Age: 30, Salary:
Frank 30 50000.0 Jane 50000.0 Manager Information: Name: Jane Smith, Age:
Smith 35 80000.0 5 Mark 35, Salary: 80000.0 Number of Subordinates: 5
6
Johnson 25 60000.0 Java Programmer Information: Name: Mark Johnson, Age: 25,
Python C++ Salary: 60000.0 Programming Languages Known: - Java
- Python - C++