Java Sem Ans
Java Sem Ans
PART – A ( 2 Marks)
UNIT - I (Minimum 8 Questions)
1. Outline any 3 benefits and applications of JAVA CO1-U
2. Outline the purpose of JIT compiler CO1-U
3. Summarize the Buzzwords in Java. CO1-U
Platform Independence: Java’s "Write Once, Run Anywhere" capability allows programs
to run on different OS without modification.
Security: Java provides built-in security features like bytecode verification and the
Security Manager.
Memory Management: Automatic garbage collection helps manage memory efficiently.
Applications:
Web Applications
Mobile Applications
Enterprise Software
1. The Just-In-Time (JIT) Compiler is a component of the Java Virtual Machine (JVM) that
dynamically translates Java bytecode into native machine code at runtime, improving
execution performance.
Purpose
Dynamic Translation
Performance Optimization
Adaptive Optimization
Code Caching
Platform Independence
Integration with JVM
3. Buzzwords in Java
i)Simple
ii)Object-Oriented
iii)Platform-Independent
iv)Distributed
v)Multithreaded
vi)Secure
vii)Robust
viii)Architecture-Neutral
ix)Portable
x)High-Performance
xi)Interpreted
xii)Dynamic
xiii)Scalable
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
System.out.println("Factorial: " + fact);
}
}
5. Purpose of new Operator
The new operator in Java is used to allocate memory for objects dynamically.
Example:
class Example {
int value;
Example(int v) {
value = v;
}
void show() {
System.out.println("Value: " + value);
}
Expression:
5 + 4 * 9 % (3 + 1) / 6 - 1
Step-by-step evaluation:
1. Parentheses: (3 + 1) = 4
2. Multiplication and Modulus: 4 * 9 = 36, then 36 % 4 = 0
3. Division: 0 / 6 = 0
4. Addition and Subtraction: 5 + 0 - 1 = 4
Final Result: 4
import java.util.Scanner;
public class CircleArea {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter radius: ");
double radius = sc.nextDouble();
double area = Math.PI * radius * radius;
System.out.println("Area: " + area);
}
}
8. Java Program: Conditional Sum Calculation
import java.util.Scanner;
public class SumCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
Example:
public class ExplicitConversion {
public static void main(String[] args) {
double d = 9.78;
int num = (int) d; // Explicit conversion from double to int
System.out.println("Converted value: " + num);
}
}
Output:
1
2
4
1. while Loop
Checks the condition before executing the loop body.
If the condition is false initially, the loop body won’t execute.
Used when the number of iterations is not known beforehand.
2. do-while Loop
Executes the loop body at least once before checking the condition.
Ensures execution even if the condition is false initially.
Used when at least one iteration must occur.
3. for Loop
Combines initialization, condition, and iteration in a single statement.
Best suited for loops with a fixed number of iterations.
UNIT - II(Minimum 8 Questions)
1. Outline the purpose of this keyword with example code CO1-U
2. Outline on Abstraction CO1-U
3. List out the Access Specifier in Java. CO1-U
4. Explain the purpose of static keyword in main() method? CO1-U
5. Develop a user defined method in java that checks the number is even or odd. CO2-Apply
6. Develop a Java program to interchange the values without using temporary variable. CO2-Apply
7. Make use of the concept you have learnt and identify which OOP’s concept is used what
will be the output of the following code with explanation: CO2-Apply
class Bank{
String bankName,area,phoneNo;
public static void main(String[] args){
Bank bank=new Bank();
System.out.println(bank.bankName);
Bank bank2=new Bank("abc","xyz","pqr");
System.out.println(bank2.bankName);
}
Bank(){
System.out.println("inside constructor");
}
Bank(String x,Stringy,String z){
bankName=x;
area=y;
phoneNo=z;
}
}
(A) Null abc
(B) print “abc” but with Runtime exception
(C) inside constructor null abc
(D) Runtime exception as none of the variables are initialized
8. Explain about the 2 Primary Sections in memory Management CO1-U
9. Infer the concept of Encapsulation CO1-U
10. Outline on Array with syntax and example CO1-U
11. List the OOPS concept CO1-U
12. Explain on Method with syntax and example CO1-U
ANSWER:
The this keyword in Java refers to the current object within an instance method or constructor. It is used to
differentiate instance variables from parameters, call another constructor, or return the current object.
Example:
class Example {
int a;
Example(int a) {
this.a = a; // Using 'this' to refer to the instance variable
}
void display() {
System.out.println("Value of a: " + this.a);
}
public static void main(String[] args) {
Example obj = new Example(10);
obj.display();
}
}
2. Outline on Abstraction
Abstraction is an OOP principle that hides implementation details and exposes only the essential
functionalities. In Java, it is achieved using abstract classes and interfaces.
Example:
Example:
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
a = a + b;
b = a - b;
a = a - b;
Stack Memory: Stores method calls, local variables, and function calls.
Heap Memory: Stores objects and instance variables, managed by the Garbage Collector.
9. Encapsulation Concept
Encapsulation is the bundling of data and methods that manipulate it, restricting direct access to some of
an object's components using private variables and public getter/setter methods.
Example:
class Student {
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
Syntax:
datatype[] arrayName = new datatype[size];
Example:
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers[1]); // Output: 20
Encapsulation
Abstraction
Inheritance
Polymorphism
Syntax:
returnType methodName(parameters) {
// method body
}
Example:
public class Example {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(5, 10)); // Output: 15
}
}
class Person1 {
String name;
Person1() {
System.out.println("In Person class"); CO2-Apply
void Print() {
System.out.println("person name" + name);
}
}
Student() {
System.out.println("In Student class");
}
int id;
10. Outline on Blank Final Variable with a simple example code CO1-U
11. Develop a Java program using interface to find the area of rectangle. CO2-Apply
ANSWER:
1. Definition & Advantages of Inheritance
Definition: Inheritance is an OOP concept where one class (child/subclass) acquires the properties and
behaviors of another class (parent/superclass).
Advantages:
Code Reusability
Method Overriding for customization
Enhances maintainability and scalability
Output: 6 (Option D)
Explanation:
x is static, shared across all instances.
Setting a.x = 2 changes x to 2, which also reflects in b.x and Question.x.
System.out.println(2 + 2 + 2) → 6.
Example:
class Parent {
Parent() { System.out.println("Parent Constructor"); }
}
class Child extends Parent {
Child() { super(); System.out.println("Child Constructor"); }
}
Method Overloading
Method Overriding
Explanation:
class Person1 {
String name;
Person1() { System.out.println("In Person class"); }
void Print() { System.out.println("person name" + name); }
}
Explanation:
First, Person1 constructor runs, printing "In Person class".
Example:
class Parent {
void show() { System.out.println("Parent method"); }
}
class Child extends Parent {
void show() {
super.show(); // Calls Parent's method
System.out.println("Child method");
}
}
Example:
class Example {
final int x; // Blank final variable
Example() { x = 10; } // Must be initialized in constructor
}
interface Shape {
double area();
}
class Rectangle implements Shape {
double length, breadth;
Rectangle(double l, double b) {
length = l;
breadth = b;
}
import java.util.List;
import java.util.ArrayList; CO2-Apply
class Employee {
private intempId;
public Employee(intempId) {
this.empId = empId;
}
}
public class ListTester {
public static void main(String[] args) {
CO2-Apply
LinkedList<Employee>firstList = new LinkedList<>();
LinkedList<Employee>secondList = new LinkedList<>();
firstList.addFirst(new Employee(2034));
secondList.addFirst(new Employee(2034));
if(firstList.contains(secondList.getFirst())){
System.out.println("Values are Same");
}else{
System.out.println("Values are Not Same");
}
}
}
8. Consider the following code snippet given below. What will be the output? Explain it.
import java.util.List;
import java.util.ArrayList;
nameList.add(1,"One");
nameList.add(2,"Two");
for(String no:nameList){
System.out.println(no);
}
}
}
ANSWER:
A Java package is a namespace that groups related classes and interfaces to avoid naming conflicts and
enhance code organization. It helps in maintaining modularity and access control.
Usage:
Example:
package mypackage;
public class MyClass {
public void show() {
System.out.println("Hello from MyClass");
}
}
Exception Handling in Java is a mechanism to handle runtime errors, ensuring smooth program execution.
It uses try, catch, finally, and throw/throws.
Syntax:
try {
int a = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Execution completed");
}
import java.util.List;
import java.util.ArrayList;
Output:
Output: NullPointerException
Explanation: totalValue is null, and calling intValue() on a null object causes NullPointerException.
import java.util.LinkedList;
class Employee {
private int empId;
public Employee(int empId) {
this.empId = empId;
}
}
public class ListTester {
public static void main(String[] args) {
LinkedList<Employee> firstList = new LinkedList<>();
LinkedList<Employee> secondList = new LinkedList<>();
firstList.addFirst(new Employee(2034));
secondList.addFirst(new Employee(2034));
if(firstList.contains(secondList.getFirst())){
System.out.println("Values are Same");
}else{
System.out.println("Values are Not Same");
}
}
}
Output:
Explanation:
Even though firstList and secondList contain Employee objects with the same empId, they are different
objects in memory.
Output: IndexOutOfBoundsException
Explanation:
ANSWER:
1. Syntax and Example for Creating a String from a Character Array (CO1-U)
Syntax:String str = new String(charArray);
Example:
public class StringExample {
public static void main(String[] args) {
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str = new String(chars);
System.out.println(str); // Output: Hello
CO2-Apply
}
}
2. Java Program Using String Constructor with ASCII Values (CO2-Apply)
Output:
ABCDEF
CDE
class xx {
public static void main(String args[]) {
String s = "four:" + 2 + 2;
System.out.println(s);
}
}
Output:
(A) four:22
Explanation:
"four:2" + 2 → "four:22"
Output:
YGOLONHCET NOITAMROFNI
Output:
Explanation:
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such as
addition, subtraction, multiplication, division, and modulus.
+: Addition
-: Subtraction
*: Multiplication
/: Division
%: Modulus (remainder)
Example:
int a = 10, b = 3;
System.out.println("Addition: " + (a + b)); // 13
System.out.println("Subtraction: " + (a - b)); // 7
System.out.println("Multiplication: " + (a * b)); // 30
CO1-U (16)
System.out.println("Division: " + (a / b)); // 3
System.out.println("Modulus: " + (a % b)); // 1
==: Equal to
!=: Not equal to
>: Greater than
<: Less than
>=: Greater than or equal to
<=: Less than or equal to
Example:
int a = 10, b = 5;
System.out.println("Equal: " + (a == b)); // false
System.out.println("Not Equal: " + (a != b)); // true
System.out.println("Greater Than: " + (a > b)); // true
System.out.println("Less Than: " + (a < b)); // false
System.out.println("Greater or Equal: " + (a >= b)); // true
System.out.println("Less or Equal: " + (a <= b)); // false
3. Logical Operators
Logical operators are used to combine multiple boolean expressions.
Example:
boolean x = true, y = false;
System.out.println("Logical AND: " + (x && y)); // false
System.out.println("Logical OR: " + (x || y)); // true
System.out.println("Logical NOT (x): " + !x); // false
System.out.println("Logical NOT (y): " + !y); // true
4. Assignment Operators
Assignment operators are used to assign values to variables.
=: Simple assignment
+=: Add and assign
-=: Subtract and assign
*=: Multiply and assign
/=: Divide and assign
%=: Modulus and assign
Example:
int a = 10;
a += 5; // a = a + 5 -> a = 15
a -= 3; // a = a - 3 -> a = 12
a *= 2; // a = a * 2 -> a = 24
a /= 4; // a = a / 4 -> a = 6
a %= 3; // a = a % 3 -> a = 0
System.out.println("Final value of a: " + a); // 0
5. Unary Operators
Unary operators are used to perform operations on a single operand.
Example:
int a = 5;
System.out.println("Unary Plus: " + (+a)); // 5
System.out.println("Unary Minus: " + (-a)); // -5
System.out.println("Post Increment: " + (a++)); // 5 (then a becomes 6)
System.out.println("Pre Increment: " + (++a)); // 7
System.out.println("Post Decrement: " + (a--)); // 7 (then a becomes 6)
System.out.println("Pre Decrement: " + (--a)); // 5
6. Bitwise Operators
Bitwise operators perform operations on the individual bits of a number.
Example:
int a = 5, b = 3; // 5 = 0101, 3 = 0011
System.out.println("Bitwise AND: " + (a & b)); // 1
System.out.println("Bitwise OR: " + (a | b)); // 7
System.out.println("Bitwise XOR: " + (a ^ b)); // 6
System.out.println("Bitwise NOT: " + (~a)); // -6
System.out.println("Left Shift: " + (a << 1)); // 10
System.out.println("Right Shift: " + (a >> 1)); // 2
7. Ternary Operator
The ternary operator is a shorthand for an if-else statement. It evaluates a condition
and returns one of two values based on the result.
Syntax:
condition ? expression1 : expression2;
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b; // Returns a if true, b if false
System.out.println("Maximum value: " + max); // 20
8. Instanceof Operator
The instanceof operator is used to test whether an object is an instance of a
particular class or subclass.
Syntax:
object instanceof ClassName
Example:
String str = "Hello";
System.out.println(str instanceof String); // true
Conclusion:
Java provides a wide range of operators to perform various operations on variables
and values. Understanding these operators is crucial for writing efficient and
functional code. The major categories include Arithmetic, Relational, Logical,
Assignment, Unary, Bitwise, Ternary, and Instanceof operators. Each serves a
specific purpose and is used in different scenarios based on the requirement of the
program.
• If the discriminant is 0, the values of both the roots will be same. Display
the value of the root.
• If the discriminant is greater than 0, the roots will be unequal real roots.
Display the values of both the roots.
• If the discriminant is less than 0, there will be no real roots. Display the
message "The equation has no real root"
Use the formula given below to find the roots of a quadratic equation.
x = (-b ± discriminant)/2a.
CO2-Apply (08)
ANSWER:
import java.util.Scanner;
public class QuadraticEquation {
public static void solveQuadratic(double a, double b, double c) {
// Calculate the discriminant
double discriminant = b * b - 4 * a * c;
scanner.close();
}
}
ANSWER:
import java.util.Scanner;
public class ProductWithSeven {
public static int calculateProduct(int a, int b, int c) {
// Check if 7 is present and determine the product accordingly
if (a == 7) {
return b * c;
} else if (b == 7) {
return c;
} else if (c == 7) {
return -1;
} else {
return a * b * c;
}
}
// Count occurrences of 7
int sevenCount = 0;
if (a == 7) sevenCount++;
if (b == 7) sevenCount++;
if (c == 7) sevenCount++;
scanner.close();
}
}
3. Implement a program to find the number of rabbits and chickens in a farm.
Given the number of heads and legs of the chickens and rabbits in a farm,
identify and display the number of chickens and rabbits in the farm.
If the given input cannot make a valid number of rabbits and chickens, then
display an appropriate message.
CO2-Apply (16)
ANSWER:
import java.util.Scanner;
scanner.close();
}
}
Output:1
Enter the total number of heads: 150
Enter the total number of legs: 500
Output:2
Enter the total number of heads: 3
Enter the total number of legs: 11
The number of chickens and rabbits cannot be determined.
While ordering food in "SwiftFood", when a customer orders food items, you
need to calculate the total cost that the customer should pay for the order. The
"Regular Customers" are provided with a 5% discount for their orders. Here,
we are assuming that each food item costs Rs.150. In the condition, we are
checking if the customer type is "Regular". When a customer places an order,
the total cost varies according to the customer type. The customer type must
be either Regular or Guest. For other values, the program should display an
error message.
CO2-Apply (08)
1)
2) ANSWER:
3) import java.util.Scanner;
4)
5) public class SwiftFood {
6) public static void main(String[] args) {
7) Scanner sc = new Scanner(System.in);
8)
System.out.print("Enter customer type (Regular/Guest): ");
9) String type = sc.next();
10)
11) System.out.print("Enter number of food items: ");
12) int items = sc.nextInt();
13)
14) int cost = items * 150;
15)
16) if (type.equalsIgnoreCase("Regular")) {
17) cost -= cost * 0.05;
18) System.out.println("Total cost after discount: Rs." + cost);
19) } else if (type.equalsIgnoreCase("Guest")) {
20) System.out.println("Total cost: Rs." + cost);
21) } else {
22) System.out.println("Error: Invalid customer type!");
23) }
24) sc.close();
25) }
}
OUTPUT:
ANSWER:
import java.util.Scanner;
OUTPUT:
if (customerType.equalsIgnoreCase("Regular")) {
double discount = totalCost * 0.05; // 5% discount
totalCost -= discount;
sc.close();
}
}
1)
2) ANSWER:
3) public class PyramidPattern {
4) public static void main(String[] args) {
5) int rows = 5; // Number of rows for the pyramid
6)
7) for (int i = 1; i <= rows; i++) {
8) // Print spaces
9) for (int j = rows - i; j > 0; j--) {
10) System.out.print(" ");
11) }
12) // Print stars
13) for (int k = 1; k <= (2 * i - 1); k++) {
14) System.out.print("*");
15) }
16) System.out.println(); // Move to the next line
17) }
18) }
19) }
Output
Part (i):
Number of food items: 3
Customer type: Regular
*
***
*****
*******
*********
6.20) Explain about the selection and iteration control structure in java with example
program
21) ANSWER:
Selection Control Structure in Java
Selection control structures allow the program to choose between different paths
based on conditions. The main types of selection control structures in Java are: CO1-U (16)
1. if statement:
Syntax:
if (condition) {
// Code to execute if condition is true
}
2. if-else statement:
It executes one block of code if the condition is true, and another block if the
condition is false.
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
3. else-if ladder:
Syntax:
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if none of the conditions are true
}
4. switch statement:
Syntax:
switch (variable) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no match
}
Example:
This example checks if the number is positive, negative, or zero using the if-else
structure.
Iteration control structures are used to repeat a block of code multiple times. There
are three primary types of iteration control structures in Java:
1. for loop:
Syntax:
2. while loop:
Syntax:
while (condition) {
// Code to execute
}
3. do-while loop:
Executes the block of code at least once, and then continues as long as the
condition is true.
Syntax:
do {
// Code to execute
} while (condition);
Example:
This for loop prints "Iteration 1" to "Iteration 5". It runs for a fixed number of times
because the condition i <= 5 is checked before every iteration.
Summary:
Selection structures allow branching based on conditions. if, if-else, and switch
are used for decision-making.
Iteration structures allow repeated execution of a code block. for, while, and do-
while are used for looping.
Both are essential for controlling program flow, making them key concepts in any
programming language.
7. (i)Implement a program to display the geometric sequence as given below for a (08)
// Validate input
CO2-
if (n <= 0) { Apply
System.out.println("Please enter a positive number");
return;
}
OUTPUT:
ANSWER:
public class NumberPattern {
public static void main(String[] args) {
// Number of rows needed is 7
int rows = 7;
OutpuT:
12
123
1234
12345
123456
1234567
8. Implement a program to find out whether a number is a seed of another
CO2- (16)
number. Apply
A number X is said to be a seed of number Y if multiplying X by its every digit
equates to Y.
E.g.: 123 is a seed of 738 as 123*1*2*3 = 738
ANSWER:
import java.util.Scanner;
if (isSeed(x, y)) {
System.out.println(x + " is a seed of " + y);
} else {
System.out.println(x + " is NOT a seed of " + y);
}
}
output
Test Case 1: 123 is a seed of 738
24 is a seed of 192
Explanation:
24 × 2 × 4 = 24 × 8 = 192 → So, 24 is a seed of 192.
9. (i) Write a Java program to print the Pascal’s triangle. CO2- (08)
Apply
ANSWER:
import java.util.Scanner; (08)
CO2-
Apply
public class PascalTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
printPascalTriangle(rows);
}
int number = 1;
for (int j = 0; j <= i; j++) {
System.out.print(number + " ");
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
OUTPUT:
Enter the number of rows for Pascal's Triangle: 5
1
11
121
1331
14641
(ii) Write a Java program to calculate the sum of first 'n' odd integer numbers
skipping 1 number. For example, n=1, sum=1. n=3, sum=1+5=6
ANSWER:
import java.util.Scanner;
OUTPUT:
Enter the value of n: 1
Sum of first 1 odd numbers (skipping 1 number): 1
printFloydTriangle(rows);
}
OUTPUT:
1
23
456
7 8 9 10
(ii) Write a Java program to find and print the duplicate element in an array.
ANSWER:
import java.util.Scanner;
findDuplicates(arr);
}
if (!foundDuplicate) {
System.out.print("No duplicates found");
}
}
}
OUTPUT:1
Enter the size of the array: 5
Enter the array elements:
12324
Duplicate elements: 2
OUTPUT:2
Enter the size of the array: 4
Enter the array elements:
1234
Duplicate elements: No duplicates found
1. Create a new class Restaurant in the Java project SwiftFood with the instance
variables and methods mentioned below.
CO2- (16)
Apply
Method Description
displayRestaurantDetails()
• Display the details of the restaurant (the values of the member variables)
• Create an object of the Restaurant class, initialize the instance variables,
and invoke the displayRestaurantDetails() method in the main() method
of the Tester class
ANSWER:
Class: Restaurant
package SwiftFood;
Class: Tester
package SwiftFood;
restaurant.displayRestaurantDetails();
}
}
Output:
ANSWER:
class Chocolate {
int barCode;
String name;
double weight;
double cost;
// Default constructor
public Chocolate() {
this.barCode = 101;
this.name = "Cadbury";
this.weight = 12;
this.cost = 10;
}
// Parameterized constructor
public Chocolate(int barCode, String name, double weight, double cost) {
this.barCode = barCode;
this.name = name;
this.weight = weight;
this.cost = cost;
}
System.out.println();
OUTPUT:
Chocolate Details:
Barcode: 101
Name: Cadbury
Weight: 12.0g
Cost: $10.0
Chocolate Details:
Barcode: 102
Name: Dairy Milk
Weight: 15.0g
Cost: $12.5
3. A book shop maintains the inventory of books that are being sold at the shop.
The list includes the details such as author, title, price, publisher and stock
position. Whenever a customer wants a book, the sales person inputs the title
and author and the system searches the list and displays whether it is available CO2- (16)
Apply
or not. If it is not, an appropriate message is displayed. If it is, then the system
displays the book details, and requests for the number of copies required. If the
requested copies are available, the total cost of the requested copies is displayed.
Otherwise, the message “Required copies not in stock” is displayed. Design a
system using a class called books with suitable methods and constructors.
ANSWER:
Class: Book
import java.util.Scanner;
public class Book {
// Instance variables
private String author;
private String title;
private double price;
private String publisher;
private int stock;
---
Class: BookShop
// Process purchase
book.purchaseBook(copiesRequested);
break;
}
}
if (!found) {
System.out.println("\nBook not available");
}
sc.close();
}
}
OUTPUT:
Book Found:
Book Title: Harry Potter
Author: J.K. Rowling
Price: Rs.500.0
Publisher: Bloomsbury
Stock: 10
Book Found:
Book Title: 1984
Author: George Orwell
Price: Rs.350.0
Publisher: Secker & Warburg
Stock: 5
ANSWER:
(08)
// Parameterized constructor
public Customer(String customerId, String customerName, long contactNumber,
String address) {
this.customerId = customerId;
this.customerName = customerName;
this.contactNumber = contactNumber;
this.address = address;
}
System.out.println("\nCustomer 2 Details:");
customer2.displayDetails();
}
}
OUTPUT:
Customer 1 Details:
Customer ID: C001
Customer Name: Alice
Contact Number: 9876543210
Address: 123 Main Street
Customer 2 Details:
Customer ID: C002
Customer Name: Bob
Contact Number: 8765432109
Address: 456 Elm Street
ANSWER:
public class Calculator {
// Method to calculate the average of three numbers
public double findAverage(double num1, double num2, double num3) {
double average = (num1 + num2 + num3) / 3;
return Math.round(average * 100.0) / 100.0; // Rounding to 2 decimal places
}
// Example input
double num1 = 25.5, num2 = 30.2, num3 = 45.8;
OUTPUT:
The average of 25.5, 30.2, and 45.8 is: 33.83
5. Develop a java program using Encapsulation and Abstraction for the following
scenario:
ANSWER:
// InfyTV.java
class InfyTV {
private String photographer;
private String newsReporter;
private String correspondent;
// Tester class
public class InfyTVTester {
public static void main(String[] args) {
// Create an object of InfyTV
InfyTV documentary = new InfyTV();
OUTPUT:
A hundred years ago there were 100,000 tigers in the world.
Today there are as few as 3,200. Why are tigers disappearing?...
by Correspondent: Kimberely
Photographer: Joshua
newsReporter: Hudson
6. (i)Given an array of integers, compute the maximum value for each integer in
the index, either by summing all the digits or by multiplying all the digits.
Choose which operation gives the maximum value. Write the Java program for
the given problem statement.
ANSWER:
import java.util.*;
CO2-
Apply (08)
public class MaxDigitOperation {
// Method to calculate sum of digits
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
CO2- (08)
sum += num % 10; Apply
num /= 10;
}
return sum;
}
(ii)Create a class Complex with two data members real, imag and a
parameterized constructor with two arguments to initialize the object. Include
appropriate methods to perform addition of two complex numbers and to
display the resultant complex number. Write a Java program for the given
scenario.
ANSWER:
class Complex {
private double real, imag;
// Parameterized constructor
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
OUTPUT:
➢ If the validations pass, determine whether the bank would provide theloan
or not.
• Display the account number, eligible and requested loan amount and the
number of EMIs, if the bank provides the loan.
• Display an appropriate message if the bank does not provide the loan.
ANSWER:
import java.util.Scanner;
System.out.println("Enter salary:");
double salary = scanner.nextDouble();
// Validate inputs
if (!validateAccountNumber(accountNumber)) {
System.out.println("Error: Account number should be 4 digits and start with
1");
return;
}
switch (loanType.toLowerCase()) {
case "car":
if (salary > 25000) {
eligibleLoanAmount = 500000;
eligibleEMIs = 36;
eligible = true;
}
break;
case "house":
if (salary > 50000) {
eligibleLoanAmount = 6000000;
eligibleEMIs = 60;
eligible = true;
}
break;
case "business":
if (salary > 75000) {
eligibleLoanAmount = 7500000;
eligibleEMIs = 84;
eligible = true;
}
break;
default:
System.out.println("Error: Invalid loan type");
return;
}
Loan Approved!
Account Number: 1234
Eligible Loan Amount: $6000000.0
Requested Loan Amount: $5000000.0
Eligible EMIs: 60
Requested EMIs: 48
NOT ELIGIBLE:
Enter account number:
1234
Enter account balance:
5000
Enter salary:
30000
Enter loan type (Car/House/Business):
Business
Sorry, you are not eligible for the Business loan based on your salary.
8. Write a Java program to perform Matrix Addition and subtraction
ANSWER:
import java.util.Scanner;
System.out.println("Sum of matrices:");
printMatrix(sum);
System.out.println("Difference of matrices:");
printMatrix(difference);
scanner.close();
}
}
OUTPUT:
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of first matrix:
12
34
Enter elements of second matrix:
56
78
Sum of matrices:
68
10 12
Difference of matrices:
-4 -4
-4 -4
9. 1. A project unit in a company wants to keep track of five employees in the
project and their salaries, and also find out the average of their salaries. They
also want to find the number of employees who get a salary greater than the
average salary and those who get lesser.
2. Consider that the salaries are stored in an array of double variables as given CO2- (16)
below: Apply
ANSWER:
OUTPUT:
The average salary of the employee is: 23914.0
The number of employees having salary greater than the average is: 2
The number of employees having salary lesser than the average is: 3
10. i)Develop a java program using encapsulation to display the age of a person by CO2- (06)
Apply
considering the instance variable age under private visibility lable, use two
methods setage(int age) and getage()
ANSWER:
class Person {
private int age;
OUTPUT:
Person's Age: 25
ANSWER:
class Account {
private long acc_no;
private String name, email;
private float amount;
OUTPUT:
UNIT-III(Minimum 10 Questions)
1. Create a class Student that has a data member rollno and getter and setter
methods to get and set rollno. Derive a class Test from Student that has data
members marks1, marks2 and getter and setter methods to get and set the
marks. Create a class Result derived from class Test that has a datamember
total and a method display() to display the members of all the classes. From
main() method, display the members of all the classes.
ANSWER:
// Base class Student
class Student {
private int rollno;
CO2-
(16)
// Getter for rollno Apply
// Main class
public class Main {
public static void main(String[] args) {
// Create an object of Result
Result result = new Result();
// Set data
result.setRollno(101);
result.setMarks1(85);
result.setMarks2(90);
Output:
ANSWER:
// Base class Train
class Train {
int noOfSeatsFirstTier;
int noOfSeatsSecondTier;
int noOfSeatsThirdTier;
reservation.displaySeats();
reservation.displayBookingStatus();
}
}
OUTPUT:
First Tier Seats: 50
Second Tier Seats: 100
Third Tier Seats: 150
Booking Successful!
Seats Booked - First Tier: 10
Seats Booked - Second Tier: 20
Seats Booked - Third Tier: 30
Cancellation Successful!
Seats Booked - First Tier: 5
Seats Booked - Second Tier: 10
Seats Booked - Third Tier: 15
3. Mysore United is a player's club which maintains the average rating of the
players and sets their category based on the average rating obtained from the
critics every month. The number of critics for the club varies from two to three.
The PlayerRating class stores the details of the player and the class diagram is
as shown below:
CO2-
(16)
Apply
ANSWER:
public class PlayerRating {
private int playerPosition;
private String playerName;
private float criticOneRating;
private float criticTwoRating;
private float criticThreeRating;
private float averageRating;
private char category;
// Constructor
public PlayerRating(int playerPosition, String playerName) {
this.playerPosition = playerPosition;
this.playerName = playerName;
this.criticThreeRating = 0; // Initialize to 0 for cases with only 2 critics
}
OUTPUT:
Player Position: 1
Player Name: John Doe
Critic 1 Rating: 8.5
Critic 2 Rating: 7.5
Average Rating: 8.0
Category: B
Player Position: 2
Player Name: Jane Smith
Critic 1 Rating: 9.0
Critic 2 Rating: 8.5
Critic 3 Rating: 9.5
Average Rating: 9.0
Category: A
Player Position: 3
Player Name: Mike Johnson
Critic 1 Rating: 4.5
Critic 2 Rating: 5.5
Average Rating: 5.0
Category: C
4. Enigma has recently opened its internet services in India. The company wants
users to register for their internet services. But for the authentication of the
user, the company has set criteria as below:
• The customer name and two phone numbers (one alternate phone
number) are compulsory fields.
• The user should have a passport. If the user is not having a passport,
he/she can provide anyone of the following combinations:
• License number and pan card number.
• Voter id and license number.
• Pan card and voter id.
The class diagram is as shown below:
CO2-
(16)
Apply
There are different users who want to register for this service and they satisfy
one of the above criteria.
Write a tester class to implement your code.
ANSWER:
import java.util.Arrays;
class Registration {
private String customerName;
private String panCardNo;
private int voterId;
private String passportNo;
private int licensenNo;
private long[] telephoneNo;
// Getters
public String getCustomerName() {
return customerName;
}
@Override
public String toString() {
return "Registration Details:\n" +
"Customer Name: " + customerName + "\n" +
(passportNo != null ? "Passport No: " + passportNo + "\n" : "") +
(panCardNo != null ? "PAN Card No: " + panCardNo + "\n" : "") +
(voterId != 0 ? "Voter ID: " + voterId + "\n" : "") +
(licensenNo != 0 ? "License No: " + licensenNo + "\n" : "") +
"Phone Numbers: " + Arrays.toString(telephoneNo);
}
}
OUTPUT:
Registration Details:
Customer Name: John Doe
Passport No: A12345678
Phone Numbers: [9876543210, 9123456780]
---------------------
Registration Details:
Customer Name: Jane Smith
PAN Card No: ABCDE1234F
License No: 123456
Phone Numbers: [8765432109, 8987654321]
---------------------
Registration Details:
Customer Name: Robert Johnson
Voter ID: 987654
License No: 567890
Phone Numbers: [7654321098, 8123456789]
---------------------
Registration Details:
Customer Name: Alice Brown
PAN Card No: FGHIJ5678K
Voter ID: 123456789
Phone Numbers: [6543210987, 7890123456]
5. Let's assume you work in a software company. And your manager told you
about a project to find out the volume of a box. You, the competent employee,
completed this task by creating a simple Box class(as shown in the below given
example).
CO2- (16)
• The next day, he told you to rewrite the program, adding weight as well. Apply
But, you had clear inheritance concepts, so you have created a child
class, BoxWeight, and inherited the Box class.
• But, the manager was not impressed and told you again to rewrite the
code and add Shipment details. This made you a little disturbed, but then
you recalled your multilevel inheritance concept. You created another
class, Shipment, and inherited the BoxWeight class.
Develop a java code for the above scenario
ANSWER:
// Base class: Box
class Box {
double length, width, height;
// Main class
public class BoxShipmentTest {
public static void main(String[] args) {
// Create a Shipment object
Shipment shipment = new Shipment(10, 5, 4, 15, 50);
OUTPUT:
Box Dimensions: 10.0 x 5.0 x 4.0
Weight: 15.0 kg
Shipping Cost: $50.0
Volume of the box: 200.0 cubic units
6. Class Media has title and price as data members. Provide constructor and
method display() to print the data members. Class Book is derived from class CO2- (16)
Media andhas an integer member pages.ClassTape is inherited from Media Apply
and has a float member time. Provide constructor to initialize the respective
data members. Provide display() to print the respective data members. From
main() method, display the members of all the classes.
ANSWER:
class Media {
private String title;
private double price;
// Main class
public class Main {
public static void main(String[] args) {
// Create a Book object
Book book = new Book("Java Programming", 29.99, 450);
Book Details:
Title: Java Programming
Price: $29.99
Pages: 450
Tape Details:
Title: Learning Java
Price: $19.99
Time: 90.5 minutes
7. Create a class Bike that has data members gear, speed and methods
applyBrake() to decrease the speed to the given value and speedup() to increase
the speed to the given value. Derive a class MountainBike from class Bike that
has a data member seatHeight and a method setHeight() to set the seatHeight to
new value. Provide constructors to initialize the respective data members.
Provide toString() to print the respective data members. From main() method,
display the members of all the classes.
PROGRAM:
// Bike class
class Bike {
int gear;
int speed;
// Overridden
public String toString() {
return super.toString() + ", Seat Height: " + seatHeight;
}
}
mountainBike.speedUp(10);
mountainBike.applyBrake(5);
mountainBike.setHeight(20);
OUTPUT:
Bike details: Gear: 5, Speed: 25
MountainBike details: Gear: 6, Speed: 30, Seat Height: 15
Updated MountainBike details: Gear: 6, Speed: 35, Seat Height: 20
8. A class Shape is defined with two data members length and breadth and two
CO2- (16)
overloading constructors in it and a method calculate() to find the area of the Apply
rectangle. Derive a class Box with a data member height and define the
constructors using super class constructors chaining in it. Also, override a
method calculate() to find the volume of a box. From main() method, Call the
appropriate constructors and methods.
ANSWER:
class Shape {
double length;
double breadth;
// Default constructor
Shape() {
this.length = 0;
this.breadth = 0;
}
// Parameterized constructor
Shape(double length, double breadth) {
this.length = length;
this.breadth = breadth;
}
double calculate() {
return length * breadth;
}
}
@Override
double calculate() {
return length * breadth * height; // Volume = length * breadth * height
}
}
// Main class
public class Main {
public static void main(String[] args) {
Shape rectangle = new Shape(5, 10);
System.out.println("Area of Rectangle: " + rectangle.calculate());
Box box = new Box(5, 10, 15);
System.out.println("Volume of Box: " + box.calculate());
}
}
OUTPUT:
Area of Rectangle: 50.0
Volume of Box: 750.0
9. Peter wants to start a payment service portal for making payments for the
credit card bill and online shopping. He will need a base class
(RRPaymentServices) to store balance and customer ID information. He will
use two classes- CreditCardPayment and ShoppingPayment for paying Credit
card bills and shopping bills respectively. The bill payment and id generation is
different for both payment modes.
Class Description:
Create a Java Project named AbstractClassesAndMethods
RRPaymentServices:
This is the base class for CreditCardPayment and ShoppingPayment classes. CO2- (16)
Apply
• It will store the amount to be paid by the user in the instance
variable balance of the class.
Method Description:
• payBill(double amount): This is an abstract method that has to be
implemented by the child classes of RRPaymentServices.
ShoppingPayment:
This class is a child class of RRPaymentServices. It has a static
variable counter, to set the paymentID. The class diagram is shown below:
Method Description:
• payBill(double amount): For a shopping bill payment, the payment id
should start with 'S' followed by a four digit integer number. If the user
enters an amount not equal to the balance which is due, an appropriate
error message should be displayed and the id should get generated only
for valid payments.
CreditCardPayment:
This class is another child class of RRPaymentServices. It has a static
variable counter, to generate the paymentID. The class diagram is shown below:
Method Description:
• payBill(double amount): For credit card bill payment, if a user enters an
amount more than the amount to be paid, the excess amount should be
stored as cashBack. The payBill method is used to pay the bill and
generate the transaction id. The id should start with 'C' followed by a
four-digit integer number. In case the user enters an amount less than
the amount to be paid, then the remaining amount should be stored in
the instance variable balanceDue of class CreditCardPayment.
• Use a Tester class to test your code and display the payment information.
ANSWER:
// Tester class
public class PaymentTester {
public static void main(String[] args) {
// Test ShoppingPayment
ShoppingPayment shopping = new ShoppingPayment(500.0, 1001);
System.out.println("Shopping Payment Test:");
shopping.payBill(500.0); // Valid payment
System.out.println("Payment ID: " + shopping.getPaymentID());
System.out.println();
// Test CreditCardPayment
CreditCardPayment creditCard = new CreditCardPayment(1000.0, 2001);
System.out.println("Credit Card Payment Test:");
creditCard.payBill(1200.0); // Payment with cashback
System.out.println("Payment ID: " + creditCard.getPaymentID());
System.out.println("Cashback: " + creditCard.getCashBack());
// ShoppingPayment class
class ShoppingPayment extends RRPaymentServices {
private static int counter = 1000;
private String paymentID;
@Override
public void payBill(double amount) {
if (amount == balance) {
counter++;
paymentID = "S" + String.format("%04d", counter);
System.out.println("Shopping payment successful for customer " +
customerID);
balance = 0;
} else {
System.out.println("Error: Amount entered is not equal to the balance
due.");
}
}
}
// CreditCardPayment class
class CreditCardPayment extends RRPaymentServices {
private static int counter = 1000;
private String paymentID;
private double cashBack;
private double balanceDue;
@Override
public void payBill(double amount) {
if (amount >= balance) {
counter++;
paymentID = "C" + String.format("%04d", counter);
cashBack = amount - balance;
balanceDue = 0;
balance = 0;
System.out.println("Credit card payment successful for customer " +
customerID);
} else {
balanceDue = balance - amount;
balance = 0;
System.out.println("Partial payment received. Balance due: " + balanceDue);
}
}
}
OUTPUT:
Intern:
This class for interns who completed their course in Institute A.
Method Description:
• calcPercentage(): This method will calculate the total marks of the intern
which is the sum of grace marks and the marks secured by the intern,
and hence calculate the percentage on the totalMaximumMarks.
Trainee:
This class is for trainees who completed their course in Institute B.
Method Description:
calcPercentage(): calculates the overall percentage of the marks of the trainee.
PROGRAM:
interface DataProvider {
double calcPercentage();
}
class Intern implements DataProvider {
private int courseMarks;
private static final int GRACE_MARKS = 100;
private static final int TOTAL_MAXIMUM_MARKS = 8000;
// Constructor
Intern(int courseMarks) {
this.courseMarks = courseMarks;
}
// Method to calculate percentage
@Override
public double calcPercentage() {
int totalMarks = courseMarks + GRACE_MARKS; // Add grace marks
return (totalMarks / (double) TOTAL_MAXIMUM_MARKS) * 100; // Calculate
percentage
}
}
OUTPUT:
Method Description
ValidateName(String name)
Validate that the name is not null or empty. If the name is null or empty, return
false, else returntrue.
ValidateJobProfile(String jobProfile)
CO2- (16)
Validate that the jobProfile is either 'Associate' or 'Clerk' or 'Executive' or Apply
'Officer'. If the jobProfile is valid, return true, else return false. Perform case-
insensitive comparison
ValidateAge(int age)
Validate that the age is between 18 and 30 (both inclusive). If the age is valid,
return true, elsereturn false
validate(Applicant applicant)
Validate the details of the applicant by calling the appropriate methods. If any
validation fails,throw user defined exceptions based on the below description.
Test the functionalities using the main method of the provided Tester class
based on the below description.
• Create an object of Applicant class and set the values of all the instance
variables
• Validate the details of the applicant by invoking the validate() method of
the Validator class
• If all the details are valid, display 'Application submitted
successfully!', else, display appropriate error message
PROGRAM:
class NameException extends Exception {
NameException(String msg) { super(msg); }
}
class JobException extends Exception {
JobException(String msg) { super(msg); }
}
class AgeException extends Exception {
AgeException(String msg) { super(msg); }
}
// Applicant Class
class Person {
String name;
String job;
int age;
Person(String name, String job, int age) {
}
this.name = name;
this.job = job;
this.age = age;
}
// Validator Class
class Check {
static boolean checkName(String name) {
return name != null && !name.trim().isEmpty();
}
static boolean checkJob(String job) {
String[] jobs = {"Associate", "Clerk", "Executive", "Officer"};
for (String j : jobs) {
if (j.equalsIgnoreCase(job)) return true;
}
return false;
}
static boolean checkAge(int age) {
return age >= 18 && age <= 30;
}
static void validate(Person p) throws NameException, JobException,
AgeException {
if (!checkName(p.name)) throw new NameException("Invalid Name: Name
cannot be empty.");
if (!checkJob(p.job)) throw new JobException("Invalid Job: Job must be
Associate, Clerk, Executive, or Officer.");
if (!checkAge(p.age)) throw new AgeException("Invalid Age: Age must be
between 18 and 30.");
}
}
// Tester Class
public class Main {
public static void main(String[] args) {
Person p = new Person("John Doe", "Clerk", 25);
try {
Check.validate(p);
System.out.println("Application submitted successfully!");
} catch (NameException | JobException | AgeException e) {
System.out.println(e.getMessage());
}
}
}
OUTPUT
Application submitted successfully!
2 Write a Java Code with its output for the following scenario:
Create a class GFG and create an array list with integer datatype .Add the
values 0,1 &1,2 by creating an object “L1”.Now,create another arraylist with
object “L2” and add the values 1,2,3. implement the following operations:
CO2- (16)
• Display the values of object L1 & l2
Apply
• Add L2 with L1 from index 1
• Remove the element of L1 at an index 1
• Print the element at index 3 from L1
• Replace the index 0 with the value 5
• Display L1
ANSWER:
import java.util.ArrayList;
// Display L1 and L2
System.out.println("L1: " + L1);
System.out.println("L2: " + L2);
// Display final L1
System.out.println("Final L1: " + L1);
}
}
OUTPUT:
L1: [0, 1, 1, 2]
L2: [1, 2, 3]
L1 after adding L2 at index 1: [0, 1, 1, 2, 1, 2, 3]
L1 after removing element at index 1: [0, 1, 2, 1, 2, 3]
Element at index 3 of L1: 1
L1 after replacing index 0 with 5: [5, 1, 2, 1, 2, 3]
Final L1: [5, 1, 2, 1, 2, 3]
3 Write a Java Code with its output as follows:
Create an array list and add the strings such as “C++,Java, C, python” and
implement the following operations:
• Retrieve the string at index 2 CO2- (16)
Apply
• Change the string at index position 2 as “programming”
• Remove the string at index position 0
PROGRAM:
import java.util.ArrayList;
OUTPUT:
String at index 2: C
Updated list: [C++, Java, Programming, Python]
List after removing element at index 0: [Java, Programming, Python]
4 What are Packages? How to create a Package in Java. Give examples
ANSWER:
Definition of Packages
1. Declare the package at the beginning of the Java file using package
package_name;
2. Save the file inside a folder matching the package name
3. Compile the file using javac -d . filename.java
4. Use the package in another program using import
javac -d . MyClass.java
javac TestPackage.java
java TestPackage
Output:
ANSWER:
Access modifiers determine the visibility of classes, methods, and variables. The four
types are:
1. Public Modifier
Accessible everywhere, even from different packages.
package myPackage;
import myPackage.PublicExample;
Output:
2. Protected Modifier
package myPackage;
package anotherPackage;
import myPackage.ProtectedExample;
Output:
package myPackage;
class DefaultExample {
void message() {
System.out.println("Default method - Accessible only in the same package");
}
}
package anotherPackage;
import myPackage.DefaultExample;
Error:
4. Private Modifier
package myPackage;
package anotherPackage;
import myPackage.PrivateExample;
Error:
secret() has private access in myPackage.PrivateExample
Conclusion
CO2-
(16)
Apply
The Student class contains a parametrized constructor to initialize its instance
variables. It also contains getters and setters for its non-public attributes.
Expected output:
1. Student Details:
2. Student ID: 101
3. Student Name: Alan
4. Student Marks: 400.0
5. Total Marks: 500.0
6. Student Percentage: 80.0%
PROGRAM:
package com.infy.package1;
public class Student {
// Private instance variables
private int studentId;
private String studentName;
private double totalMarks;
private double totalMarksObtained;
// Parameterized constructor
public Student(int studentId, String studentName, double totalMarks, double
totalMarksObtained) {
this.studentId = studentId;
this.studentName = studentName;
this.totalMarks = totalMarks;
this.totalMarksObtained = totalMarksObtained;
}
// Getters and Setters
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public double getTotalMarks() {
return totalMarks;
}
public void setTotalMarks(double totalMarks) {
this.totalMarks = totalMarks;
}
public double getTotalMarksObtained() {
return totalMarksObtained;
}
public void setTotalMarksObtained(double totalMarksObtained) {
this.totalMarksObtained = totalMarksObtained;
}
}
2)
package com.infy.package2;
import com.infy.package1.Student;
public class StudentDetails {
// Method to calculate and print the percentage
public void calculatePercentage(Student student) {
double percentage = (student.getTotalMarksObtained() / student.getTotalMarks())
* 100;
System.out.println("Student Percentage: " + percentage + "%");
}
// Method to display student details
public void displayStudentDetails(Student student) {
System.out.println("Student Details:");
System.out.println("Student ID: " + student.getStudentId());
System.out.println("Student Name: " + student.getStudentName());
System.out.println("Student Marks: " + student.getTotalMarksObtained());
System.out.println("Total Marks: " + student.getTotalMarks());
}
}
3)
import com.infy.package1. Student;
import com.infy.package2.StudentDetails;
public class Main {
public static void main(String[] args) {
// Create a Student object
Student student = new Student(101, "Alan", 500.0, 400.0);
// Create a StudentDetails object
StudentDetails studentDetails = new StudentDetails();
}
}
// Display student details
studentDetails.displayStudentDetails(student);
// Calculate and display the percentage
studentDetails.calculatePercentage(student);
OUTPUT:
Student Details:
Student ID: 101
Student Name: Alan
Student Marks: 400.0
Total Marks: 500.0
Student Percentage: 80.0%
7 Develop a java program with package and interface to calculate the area and CO2-
perimeter of Circle, Rectangle and Ellipse with the following input : Apply (16)
PROGRAM:
1)
package MyInterface;
public interface GeoAnalyzer {
double pi = 3.14159; // Constant for pi
double area();
double perimeter();
}
2)
package MyInterface;
public class Circle implements GeoAnalyzer {
private double radius;
// Constructor
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return pi * radius * radius;
}
@Override
public double perimeter() {
return 2 * pi * radius;
}
}
3)
package MyInterface;
public class Rectangle implements GeoAnalyzer{
private double length;
private double width;
// Constructor
public Rectangle(double length, double width){
this.length = length;
this.width = width;
}
public double area(){
return length * width;
}
4)
package MyInterface;
public class Ellipse implements GeoAnalyzer
{
private double semiMajorAxis;
private double semiMinorAxis;
5)
import MyInterface.*;
public class Main {
public static void main(String[] args)
{
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);
Ellipse ellipse = new Ellipse(5, 3);
System.out.println("Circle:");
System.out.println("Area: " + circle.area());
System.out.println("Perimeter: " + circle.perimeter());
System.out.println("\nRectangle:");
System.out.println("Area: " + rectangle.area());
System.out.println("Perimeter: " + rectangle.perimeter());
System.out.println("\nEllipse:");
System.out.println("Area: " + ellipse.area());
System.out.println("Perimeter: " + ellipse.perimeter());
}
}
OUTPUT:
Circle:
Area: 78.53975
Perimeter: 31.4159
Rectangle:
Area: 24.0
Perimeter: 20.0
Ellipse:
Area: 47.12385
Perimeter: 25.132741228718345
8.
Write java Code as follows.
• Create a class "Employee" with data members
“empName",“empAge",“empSalary".
• Add appropriate get/set methods for the data members.
• Create an Exception class “EmpSalaryException" with an appropriate
constructor.
• Create a class EmployeeService with the main() method.
• Write a method checkEmployeeSalary(Employee emp) in
EmployeeService, which checks if empSalary<1000 then throws
EmpSalaryException.
CO2-
• In the EmployeeService class main() method Apply
(16)
PROGRAM:
class Employee {
private String empName;
private int empAge;
private double empSalary;
// Constructor
public Employee(String empName, int empAge, double empSalary) {
this.empName = empName;
this.empAge = empAge;
this.empSalary = empSalary;
}
// Getter and Setter methods
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpAge() {
return empAge;
}
public void setEmpAge(int empAge) {
this.empAge = empAge;
}
public double getEmpSalary() {
return empSalary;
}
public void setEmpSalary(double empSalary) {
this.empSalary = empSalary;
}
}
// Custom exception class
class EmpSalaryException extends Exception {
public EmpSalaryException(String message) {
super(message);
}
}
// EmployeeService class
class EmployeeService {
OUTPUT:
ANSWER:
Exception Handling in Java
In Java, exceptions are objects derived from the Throwable class, which has two
subclasses:
Error and Exception. Error represents severe issues (e.g., OutOfMemoryError) that
are typically beyond a programmer’s control, while Exception covers recoverable
conditions (e.g., IOException, ArithmeticException). Exception handling ensures that
these issues are caught and managed effectively.
Here, dividing by zero triggers an ArithmeticException. The try block contains the
risky code, and the catch block handles the exception by displaying an error
message. Without exception handling, the program would crash.
10. Explain the Try, Throw, Catch , Finally blocks in Exception handling
mechanism
ANSWER:
1. *Try Block*: The try block encloses code that might throw an exception. It’s the
section where the program monitors for potential errors. For example:
java
try {
int[] numbers = new int[5];
numbers[10] = 50; // ArrayIndexOutOfBoundsException
}
CO1-U (16)
If an exception occurs, the control immediately transfers to the corresponding
catch block.
2. *Throw Keyword*: The throw keyword explicitly throws an exception. It’s used to
signal an error condition manually. For instance:
java
public void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Age must be 18 or older.");
} else {
System.out.println("Age is valid.");
}
}
Here, if the condition fails, an exception is thrown, which must be caught
elsewhere.
3. *Catch Block*: The catch block follows a try block and specifies the type of
exception it can handle. It executes only if an exception of the matching type
occurs. Multiple catch blocks can handle different exceptions:
java
try {
String text = null;
System.out.println(text.length()); // NullPointerException
} catch (NullPointerException e) {
System.out.println("Error: Null value encountered.");
}
4. *Finally Block*: The finally block contains code that executes regardless of
whether an exception occurs or is caught. It’s typically used for cleanup operations,
like closing files or releasing resources:
java
try {
int result = 10 / 2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error occurred.");
} finally {
System.out.println("Execution completed.");
}
Combined Example
java
public class ExceptionDemo {
public static void main(String[] args) {
try {
int[] arr = new int[3];
arr[5] = 10; // Throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught: " + e);
throw new RuntimeException("Rethrowing exception"); // Manually
throwing
} finally {
System.out.println("Finally block executed.");
}
}
}
This demonstrates how try monitors risky code, catch handles the exception, throw
rethrows it if needed, and finally ensures cleanup. Together, these blocks provide a
structured way to manage errors in Java.
Test the functionalities using the main() method of the Tester class.
class Tester
{
public static String reverseEachWord(String str)
{
//Implement your code here and change the return value accordingly
return null;
}
public static void main(String args[])
{
String str = "all cows eat grass";
System.out.println(reverseEachWord(str));
} CO2- (16)
} Apply
PROGRAM:
class Tester {
public static String reverseEachWord(String str) {
// Split the input string into words
String[] words = str.split(" ");
StringBuilder reversedString = new StringBuilder();
// Iterate through each word
for (String word : words) {
// Reverse the current word
StringBuilder reversedWord = new StringBuilder(word).reverse();
// Append the reversed word to the result
reversedString.append(reversedWord).append(" ");
}
// Remove the trailing space and return the result
return reversedString.toString().trim();
}
public static void main(String args[]) {
String str1= "all cows eat grass";
System.out.println(reverseEachWord(str1));
String str2 = "I love programming";
System.out.println(reverseEachWord(str2));
}
}
OUTPUT:
lla swoc tae ssarg
i evol gnimmargorp
ANSWER:
String Constructor and Character Extraction in Java
Introduction
String Constructors
Syntax:
Syntax:
Syntax:
Syntax:
Syntax:
1. charAt(int index)
Syntax:
char ch = str.charAt(2);
Syntax:
3. toCharArray()
Syntax:
// charAt()
char ch = str.charAt(3);
System.out.println("Character at index 3: " + ch);
// getChars()
char[] dest = new char[5];
str.getChars(0, 5, dest, 0);
System.out.println("Extracted characters: " + new String(dest));
// toCharArray()
char[] charArray = str.toCharArray();
System.out.println("Converted to char array: " + new String(charArray));
}
}
Output
Character at index 3: g
Extracted characters: Progr
Converted to char array: Programming
Conclusion
The String class provides various constructors for initialization and methods for
extracting characters. Understanding these concepts helps in effective string
manipulation in Java.
Move all the special characters present in the string passed to the method to the
end of the string and return the modified string.
Note: Assume that the input string does not have any space.
Test the functionalities using the main() method of the Tester class.
CO2-
class Tester (16)
Apply
{
public static String moveSpecialCharacters(String str)
{
//Implement your code here and change the return value accordingly
return null;
}
public static void main(String args[])
{
String str = "He@#$llo!*&";
System.out.println(moveSpecialCharacters(str));
}
}
PROGRAM:
class Tester {
public static String moveSpecialCharacters(String str) {
if (Character.isLetterOrDigit(ch)) {
alphanumeric.append(ch); // Append to alphanumeric characters
} else {
specialChars.append(ch); // Append to special characters
}}
}
}
return alphanumeric.toString() + specialChars.toString();
public static void main(String args[]) {
String str1 = "He@#$llo!*&";
System.out.println(moveSpecialCharacters(str1));
String str2 = "%$Wel*come!";
System.out.println(moveSpecialCharacters(str2));
OUTPUT:
Hello@#$!*&
Welcome%$*!
4. Write a java program to find the count of the highest occurring character in the
string passed to the method and return the count.
Test the functionalities using the main() method of the Tester class. CO2- (16)
Apply
PROGRAM:
import
import
java.util.
java.util.
HashMap;
Map;
class Tester {
public static int HighOccuredCharCount(String str) {
Map<Character, Integer> charFrequencyMap = new HashMap<>();
}
}
OUTPUT:
Count of the highest occurring character: 3
Count of the highest occurring character: 2
5. Write a java program to remove all the duplicate characters and white spaces
from the string passed to the method and return the modified string.
Test the functionalities using the main() method of the Tester class.
CO2- (16)
Apply
PROGRAM:
OUTPUT:
Original: "hello world" | Modified: "helowrd"
Original: "java programming" | Modified: "javprogmin
CO2-
(16)
Apply
PROGRAM:
public class PalindromeChecker {
public static boolean checkPalindrome(String str)
{ str = str.toLowerCase();
int left = 0, right = str.length() - 1;
OUTPUT:
True
False
True
False
7.
Outline on string Buffer constructors with necessary syntax and example
program
ANSWER:
StringBuffer Constructors in Java
Example:
Syntax:
Example:
Syntax:
Example:
Syntax:
Example:
Conclusion
The StringBuffer class is useful for handling mutable strings efficiently. The choice of
constructor depends on the specific use case, whether initializing an empty buffer,
using a predefined string, setting a custom capacity, or utilizing a CharSequence.
Understanding these constructors helps in optimizing string operations in Java
programs.
8. Develop the java code to find the following using string methods for the String
input s= “ GeeksforGeeks ” ,s1=”Geeks”,s2=”forGeeks”,
CO2-
s4 = "Learn Share Learn": (16)
Apply
• Length
• Find the character at thirds position
• Substring(3)
• Substring(2,5)
• Concatenate s1 & s2
• Compare s1 & s2
• Change the string “forgeeks” to upper case and then to lower case
• Replace the word ‘ f ’ to ‘ g ‘ in string “s”
PROGRAM:
public class StringOperations {
public static void main(String[] args) {
// Given strings
String s = " GeeksforGeeks ";
String s1 = "Geeks";
String s2 = "forGeeks";
String s4 = "Learn Share Learn";
// 1. Length of the string s
System.out.println("Length of string s: " + s.length());
// 2. Find the character at the third position in s
System.out.println("Character at third position in s: " + s.charAt(2));
// 3. Substring starting from index 3 in s
System.out.println("Substring from index 3 in s: " + s.substring(3));
// 4. Substring from index 2 to 5 in s
System.out.println("Substring from index 2 to 5 in s: " + s.substring(2, 5));
// 5. Concatenate s1 and s2
String concatenatedString = s1.concat(s2);
System.out.println("Concatenated string of s1 and s2: " +
concatenatedString);
// 6. Compare s1 and s2
int comparisonResult = s1.compareTo(s2);
System.out.println("Comparison of s1 and s2: " + comparisonResult);
// 7. Change the string "forgeeks" to upper case and then to lower case
String forgeeks = "forgeeks";
System.out.println("Uppercase of 'forgeeks': " + forgeeks.toUpperCase());
System.out.println("Lowercase of 'forgeeks': " + forgeeks.toLowerCase());
// 8. Replace the word 'f' with 'g' in string s
String replacedString = s.replace('f', 'g');
System.out.println("String s after replacing 'f' with 'g': " + replacedString);
}
}
OUTPUT
Length of string s: 15
Character at third position in s: e
Substring from index 3 in s: eksforGeeks
Substring from index 2 to 5 in s: eks
Concatenated string of s1 and s2: GeeksforGeeks
Comparison of s1 and s2: -4
Uppercase of 'forgeeks': FORGEEKS
Lowercase of 'forgeeks': forgeeks
String s after replacing 'f' with 'g': GeeksgorGeeks
9. (i) Develop a java program to find the duplicate word in the string CO2- (06)
Apply
“This sentence contains two words, one and two”
PROGRAM:
public class DuplicateWordFinder { (10)
public static void main(String[] args) { CO2-
String input = "This sentence contains two words, one and two and one"; Apply
String[] words = input.split(" "); // Split the string into words
}
}
System.out.println("Duplicate words:");
for (int i = 0; i < words.length; i++) {
for (int j = i + 1; j < words.length; j++) {
if (words[i].equals(words[j])) {
System.out.println(words[i]); // Print duplicate word
}
}
}
OUTPUT:
Duplicate words:
two
one
and
PROGRAM:
public class RemoveDuplicates {
public static void main(String[] args) {
int[][] array = {
{1, 1, 2, 2, 3, 4, 5},
{1, 1, 1, 1, 1, 1, 1},
{1, 2, 3, 4, 5, 6, 7},
{1, 2, 1, 1, 1, 1, 1}
};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
for (int k = 0; k < j; k++) {
if (array[i][j] == array[i][k]) {
array[i][j] = 0;
break;
}
}
}
}
}
System.out.println("Modified array:");
for (int[] row : array) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
OUTPUT:
Modified array:
1020345
1000000
1234567
1200000
10.
(i) Develop a java program to check if String is an anagram
PROGRAM:
import java.util.Arrays;
CO2-
public class AnagramChecker { Apply (08)
public static boolean isAnagram(String str1, String str2) {
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
CO2- (10)
if (str1.length() != str2.length()) { Apply
return false;
}
OUTPUT:
True
False
PROGRAM: