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

Java Sem Ans

The document is a question bank for a Java Programming course at Sethu Institute of Technology, covering various topics including Java benefits, JIT compiler, buzzwords, and OOP concepts. It includes questions for both theoretical understanding and practical programming tasks, with a structured format for assessments. The content is designed for students in Information Technology and related fields, focusing on essential Java programming skills and concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Java Sem Ans

The document is a question bank for a Java Programming course at Sethu Institute of Technology, covering various topics including Java benefits, JIT compiler, buzzwords, and OOP concepts. It includes questions for both theoretical understanding and practical programming tasks, with a structured format for assessments. The content is designed for students in Information Technology and related fields, focusing on essential Java programming skills and concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 124

SETHU INSTITUTE OF TECHNOLOGY, KARIAPATTI

(An Autonomous Institution Affiliated to Anna University, Chennai)


Regulation – R2021
(Question Bank)
Department:Information Technology Subject name : Java Programming
(Integrated Course)
(Common to CSE, IT,CSD,AIML IoT & Cyber
Security)
Subject code :R21UIT404 Question Pattern : 10*2 =20
5*16 =80
Course Coordinator : Dr.G.Susan shiny,ASP/IT Time Duration : 3 Hours

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

4. Develop a Java Program to find the factorial of a given number CO2-Apply


5. Explain the purpose of new operator with example code CO1-U
6. 5+4*9%(3+1)/6-1.
CO2-Apply
Solve the expression using operator precedence
7. Develop a Java program to find the area of a circle and display the calculated area. CO2-Apply
8. Implement a program to display the sum of two given numbers if the numbers are
CO2-Apply
same. If the numbers are not same, display the double of the sum.
9. Infer the concept of Implicit type conversion with an example code CO1-U
10. Infer the concept of Explicit type conversion with an example code CO1-U
11. Compare and Contrast Break and Continue CO1-U
12. Compare and Contrast While, do..While & for CO1-U
ANSWER:
1. Three Benefits and Applications of Java
Benefits:

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

2. Purpose of JIT Compiler

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

4. Java Program: Factorial of a Number

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);
}

public static void main(String[] args) {


Example obj = new Example(10); // Using new to create an object
obj.show();
}
}

6. Solve the Expression Using Operator Precedence

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

7. Java Program: Area of a Circle

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();

int result = (num1 == num2) ? (num1 + num2) : 2 * (num1 + num2);


System.out.println("Result: " + result);
}
}

9. Implicit Type Conversion (Widening)


Implicit conversion occurs when a smaller data type is automatically converted into a
larger type.
Example:

public class ImplicitConversion {


public static void main(String[] args) {
int num = 10;
double d = num; // Implicit conversion from int to double
System.out.println("Converted value: " + d);
}
}

10. Explicit Type Conversion (Narrowing)


Explicit conversion requires casting to convert a larger type to a smaller type.

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);
}
}

11. Comparison: break vs. continue


break: Exits the loop entirely.
continue: Skips the current iteration and moves to the next.
Example:
public class BreakContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3)
continue; // Skips when i = 3
if (i == 5)
break; // Stops when i = 5
System.out.println(i);
}
}
}

Output:

1
2
4

12. Comparison: while vs. do-while vs. for

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:

1. Purpose of this keyword in Java

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:

abstract class Animal {


abstract void sound(); // Abstract method
}
class Dog extends Animal {
void sound() {
System.out.println("Barks");
}
}
public class Main {
public static void main(String[] args) {
Animal obj = new Dog();
obj.sound(); // Output: Barks
}
}

3. Access Specifiers in Java


Java has four access specifiers:
public – Accessible everywhere
private – Accessible only within the same class
protected – Accessible within the same package and subclasses
default (no modifier) – Accessible within the same package

4. Purpose of static keyword in main() method


The static keyword in the main() method allows the JVM to call it without creating an instance of the class.
This ensures that the program's execution starts directly, making the main() method globally accessible and
memory efficient.

Example:
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

5. Java Method to Check Even or Odd


public class EvenOdd {
static void checkNumber(int num) {
if (num % 2 == 0)
System.out.println(num + " is Even");
else
System.out.println(num + " is Odd");
}

public static void main(String[] args) {


checkNumber(5);
checkNumber(8);
}
}

6. Swap Two Variables Without Using a Temporary Variable


public class Swap {
public static void main(String[] args) {
int a = 5, b = 10;
System.out.println("Before Swap: a=" + a + " b=" + b);

a = a + b;
b = a - b;
a = a - b;

System.out.println("After Swap: a=" + a + " b=" + b);


}
}

7. Identify OOP Concept & Output of Code


Concept: Constructor Overloading
Output:
inside constructor
null
Answer: (C) inside constructor null abc
The first constructor prints "inside constructor" and does not initialize variables, so bankName is null. The
second constructor initializes variables, and bank2.bankName prints "abc".

8. Primary Sections in Memory Management

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;
}
}

10. Array in Java


An array is a collection of elements of the same data type stored in contiguous memory locations.

Syntax:
datatype[] arrayName = new datatype[size];

Example:
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers[1]); // Output: 20

11. OOPS Concepts

Encapsulation
Abstraction
Inheritance
Polymorphism

12. Methods in Java


A method is a block of code that performs a specific task.

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
}
}

UNIT - III(Minimum 8 Questions)


1. Define Inheritance. Mention the advantage of using it. CO1-U
2. Differentiate Method Overloading and Method Overriding with necessary syntax CO1-U
3. What will be the output of the program Give Explanation in detail
public class Question CO2-Apply
{
public static int x=7;
public static void main(String args[])
{
Question a=new Question();
Question b=new Question();
a.x=2;
b.x=2;
System.out.println(a.x+b.x+Question.x);
}
}
(a)11 b. 16 c. 21 d. 6
4. Why do we need super constructors? CO1-U
5. Define Polymorphism. How it can be achieved in Java? CO1-U
6. What will be the output of the program and give your explanation
class A
{
final public intgetResult(int a, int b) { return 0; }
}
class B extends A
{
public intgetResult(int a, int b) {return 1; }
}
CO2-Apply
public class Test
{
public static void main(String args[])
{
B b = new B();
System.out.println("x = " + b.getResult(0, 1));
}
}
(A)1 (B)Compiler Error (C)0 (D)Runtime Error
7. Outline on single inheritance with neat diagram and syntax. CO2-Apply
8. What is the output of the following code snippet? Give Explanation in detail

class Person1 {
String name;

Person1() {
System.out.println("In Person class"); CO2-Apply

void Print() {
System.out.println("person name" + name);
}
}

public class Student extends Person1 {


void Print() {
System.out.println("student name" + name);
}

Student() {
System.out.println("In Student class");
}

int id;

public static void main(String[] args) {


Person1 person = null;
person = new Student();
person.name = "abc";
person.Print();
}
}

(A)In Person class In Student class student nameabc

(B) In Student class In Person class student nameabc

(C) Compilation error at person=new Student() line of code snippet

(D) Runtime exception at person=new Student() line of code snippet

9. Summarize on Super keyword CO1-U

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

12. Compare Method Overloading and Constructor Overloading CO1-U

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

2. Method Overloading vs. Method Overriding


3. Output & Explanation of Given Program

public class Question {


public static int x = 7;
public static void main(String args[]) {
Question a = new Question();
Question b = new Question();
a.x = 2;
b.x = 2;
System.out.println(a.x + b.x + Question.x);
}
}

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.

4. Why Use Super Constructors?

• The super keyword in constructors is used to:


• Call a parent class constructor
• Avoid code duplication
• Ensure proper object initialization

Example:

class Parent {
Parent() { System.out.println("Parent Constructor"); }
}
class Child extends Parent {
Child() { super(); System.out.println("Child Constructor"); }
}

5. Definition & Achieving Polymorphism


Definition: Polymorphism allows the same method to behave differently based on the object that calls it.
Achieved by:

Method Overloading
Method Overriding

6. Output & Explanation of Given Program


class A {
final public int getResult(int a, int b) { return 0; }
}
class B extends A {
public int getResult(int a, int b) { return 1; } // ERROR: Cannot override final method
}

Output: (B) Compiler Error

Explanation:

getResult() in A is final, so it cannot be overridden in B.


Compiler throws an error.

7. Single Inheritance with Diagram & Syntax


Single inheritance refers to the inheritance where a class (subclass or child class) inherits properties and
behaviors (methods) from a single superclass (parent class).
class Parent {
void display() {
System.out.println("This is the parent class.");
}
}
class Child extends Parent {
void show() {
System.out.println("This is the child class.");
}}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.display();
child.show();
}
}

8. Output & Explanation of Given Code

class Person1 {
String name;
Person1() { System.out.println("In Person class"); }
void Print() { System.out.println("person name" + name); }
}

public class Student extends Person1 {


void Print() { System.out.println("student name" + name); }
Student() { System.out.println("In Student class"); }

public static void main(String[] args) {


Person1 person = null;
person = new Student();
person.name = "abc";
person.Print();
}
}
Output: (A) In Person class In Student class student nameabc

Explanation:
First, Person1 constructor runs, printing "In Person class".

Then, Student constructor runs, printing "In Student class".


person.Print() calls overridden method in Student, so it prints "student name abc".

9. Summary of super Keyword

The super keyword is used to:


Call a superclass method
Call a superclass constructor

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");
}
}

10. Blank Final Variable


A final variable that is not initialized at declaration but must be initialized in the constructor.

Example:
class Example {
final int x; // Blank final variable
Example() { x = 10; } // Must be initialized in constructor
}

11. Java Program to Find Area Using Interface

interface Shape {
double area();
}
class Rectangle implements Shape {
double length, breadth;
Rectangle(double l, double b) {
length = l;
breadth = b;
}

public double area() {


return length * breadth;
}
}

public class Main {


public static void main(String[] args) {
Rectangle r = new Rectangle(5, 10);
System.out.println("Area: " + r.area());
}
}

12. Method Overloading vs. Constructor Overloading

UNIT - IV(Minimum 8 Questions)


1. Outline on Java package and how is it used? CO1-U
2. Summarize about Exception Handling with its syntax CO1-U
3. What will be the output of the below code? Explain it.

import java.util.List;
import java.util.ArrayList; CO2-Apply

public class ListTester {


public static void main(String[] args) {
List<String>testList = new ArrayList<>();
testList.add(new String("hello"));
testList.add(new Integer(12));
}
}
4. Compare Checked Exceptions and Unchecked Exception. CO1-U
5. What will be the output of the below code? Explain it.
public class Tester {

public static void display() {


System.out.print(" inside display()");
throw new RuntimeException();
}

public static void main(String[] args) {


try {
System.out.print("main");
display();
} catch (Exception e) { CO2-Apply
System.out.print(" caught");
} finally {
System.out.print(" finally");
}
System.out.print(" end");
}
}
(A)Compilation error as 'throws' keyword is not used
(B)Caught Child Class Exception
(C)Compilation error because the Child Class is not throwable
(D)Compilation error because the catch block of a parent class exception must appear
after the catch block of a child class exception
6. What is the output of the following code snippet? Explain it.

public class TestException {

public static void main(String[] args) {


Integer totalValue = calculate(45); CO2-Apply
System.out.println(totalValue.intValue());
}
private static Integer calculate(inti) {
return null;
}
}
7. Consider the following code snippet as given below. What is the output ? Explain it.
import java.util.LinkedList;

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;

public class ListTester {


public static void main(String[] args) {
List<String>nameList = new ArrayList<>(); CO2-Apply

nameList.add(1,"One");
nameList.add(2,"Two");
for(String no:nameList){
System.out.println(no);
}
}
}
ANSWER:

1. Outline on Java package and how is it used? (CO1-U)

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:

To create a package: package mypackage;

To use a package: import mypackage.MyClass;

Example:

package mypackage;
public class MyClass {
public void show() {
System.out.println("Hello from MyClass");
}
}

2. Summarize about Exception Handling with its syntax (CO1-U)

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");
}

3. Output and Explanation of the Code (CO2-Apply)

import java.util.List;
import java.util.ArrayList;

public class ListTester {


public static void main(String[] args) {
List<String> testList = new ArrayList<>();
testList.add(new String("hello"));
testList.add(new Integer(12)); // Compilation Error
}
}

Output: Compilation Error


Reason: List<String> is a generic type that only allows String objects. Trying to add an Integer(12) violates
type safety.
4. Comparison of Checked and Unchecked Exceptions (CO1-U)

5. Output and Explanation of the Code (CO2-Apply)

public class Tester {


public static void display() {
System.out.print(" inside display()");
throw new RuntimeException();
}

public static void main(String[] args) {


try {
System.out.print("main");
display();
} catch (Exception e) {
System.out.print(" caught");
} finally {
System.out.print(" finally");
}
System.out.print(" end");
}
}

Output:

main inside display() caught finally end


Explanation:

main prints first.

display() prints " inside display()" and throws RuntimeException.

The exception is caught, printing " caught".

finally block executes, printing " finally".

" end" is printed last.

Correct Answer: (B) Caught Child Class Exception

6. Output and Explanation of the Code (CO2-Apply)

public class TestException {


public static void main(String[] args) {
Integer totalValue = calculate(45);
System.out.println(totalValue.intValue());
}
private static Integer calculate(int i) {
return null;
}
}

Output: NullPointerException
Explanation: totalValue is null, and calling intValue() on a null object causes NullPointerException.

7. Output and Explanation of the Code (CO2-Apply)

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:

Values are Not Same

Explanation:

Even though firstList and secondList contain Employee objects with the same empId, they are different
objects in memory.

contains() checks object references, not values.

8. Output and Explanation of the Code (CO2-Apply)

Output: IndexOutOfBoundsException
Explanation:

ArrayList is empty initially, so adding at index 1 is invalid, causing an exception.

UNIT - V(Minimum 8 Questions)


1. Write the syntax with an example, To create a string object and stores the array of
CO1-U
characters in it.
2. Develop a java Program using string constructor with input as ascii values and to display
the output as shown below:
CO2-Apply
ABCDEF
CDE
3. Develop a java Program to concatenate 2 strings”ABC” and “XYZ” using concat()
CO2-Apply
method
4. List and Explain any 5 character extraction method. CO1-U
5. Consider the following code snippet given below. What will be the output? Explain it.
Class xx
{
public static void main(String args[])
{
CO2-Apply
String s=”four:”+2+2;
System.out.println(s);
}
}
(A)four:22
(B)four: 4
(C)8
(D)None of the above

6. Develop a java program to reverse the given string


CO2-Apply
“INFORMATION TECHNOLOGY” using string reverse method
7. Summarize and Explain the string searching methods with its syntax CO1-U
8. What is the output of the following code snippet? Explain it.
public class Tester {
public static void main(String args[]) {
String input = "welcome to string functions";
input.toUpperCase();
System.out.println(input);
}
}

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)

public class AsciiString {


public static void main(String[] args) {
byte[] asciiValues = {65, 66, 67, 68, 69, 70}; // ABCDEF
String str = new String(asciiValues);
System.out.println(str);
String substr = new String(asciiValues, 2, 3); // CDE
System.out.println(substr);
}
}

Output:
ABCDEF
CDE

3. Java Program to Concatenate "ABC" and "XYZ" Using concat() (CO2-Apply)


public class StringConcat {
public static void main(String[] args) {
String str1 = "ABC";
String str2 = "XYZ";
String result = str1.concat(str2);
System.out.println(result); // Output: ABCXYZ
}
}

4. Five Character Extraction Methods (CO1-U

5. Output and Explanation of the Code (CO2-Apply)

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:2" (string concatenation)

"four:2" + 2 → "four:22"

Correct answer: (A) four:22

6. Java Program to Reverse a String Using StringBuilder (CO2-Apply)

public class ReverseString {


public static void main(String[] args) {
String str = "INFORMATION TECHNOLOGY";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed);
}
}

Output:

YGOLONHCET NOITAMROFNI

7. String Searching Methods with Syntax (CO1-U)

8. Output and Explanation of the Code (CO2-Apply)

public class Tester {


public static void main(String args[]) {
String input = "welcome to string functions";
input.toUpperCase();
System.out.println(input);
}
}

Output:

welcome to string functions

Explanation:

toUpperCase() returns a new string but does not modify input.


Since input is not reassigned, the original lowercase string is printed

PART – B(16 MARKS)


UNIT – I(Minimum 10 Questions)

1. Outline on the operators available in java with an example program

In Java, operators are symbols that perform operations on variables and


values. They can be classified into several categories based on the type of operation
they perform. Below is a detailed outline of the various operators available in Java,
followed by an example program to demonstrate their usage.

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

2. Relational (Comparison) Operators


Relational operators are used to compare two values. They return true or false
based on the result of the comparison.

==: 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.

&&: Logical AND


||: Logical OR
!: Logical NOT

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.

+: Unary plus (indicates a positive value)


-: Unary minus (negates a value)
++: Increment operator (increases a value by 1)
--: Decrement operator (decreases a value by 1)
!: Logical NOT (reverses the boolean value)

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.

&: Bitwise AND


|: Bitwise OR
^: Bitwise XOR (exclusive OR)
~: Bitwise NOT
<<: Left shift
>>: Right shift
>>>: Unsigned right shift

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.

2. (i)Quadratic equation is an equation with degree 2 in the form of ax2 +bx + c = 0


where a, b and c are the coefficients.
Implement a program to solve a quadratic equation.
Find the discriminant value using the formula given below.
discriminant = b2 - 4ac

• 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;

// Check the nature of roots and calculate accordingly


if (discriminant > 0) {
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
CO2-Apply (08)
System.out.println("The roots are " + root1 + " and " + root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.println("The root is " + root);
} else {
System.out.println("The equation has no real roots");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter coefficient a: ");


double a = scanner.nextDouble();
System.out.print("Enter coefficient b: ");
double b = scanner.nextDouble();

System.out.print("Enter coefficient c: ");


double c = scanner.nextDouble();

// Check if a is not zero (to ensure it's a quadratic equation)


if (a == 0) {
System.out.println("Coefficient 'a' cannot be zero in a quadratic equation.");
} else {
solveQuadratic(a, b, c);
}

scanner.close();
}
}

(ii) Implement a program to calculate the product of three positive integer


values. However, if one of the integers is 7, consider only the values to the
right of 7 for calculation. If 7 is the last integer, then display -1.
Note: Only one of the three values can be 7.

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;
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter first integer: ");


int a = scanner.nextInt();
System.out.print("Enter second integer: ");
int b = scanner.nextInt();

System.out.print("Enter third integer: ");


int c = scanner.nextInt();

// Validate inputs are positive


if (a <= 0 || b <= 0 || c <= 0) {
System.out.println("All integers must be positive.");
return;
}

// Count occurrences of 7
int sevenCount = 0;
if (a == 7) sevenCount++;
if (b == 7) sevenCount++;
if (c == 7) sevenCount++;

// Check if there is more than one 7


if (sevenCount > 1) {
System.out.println("Only one of the integers can be 7.");
return;
}

int result = calculateProduct(a, b, c);


System.out.println("Result: " + result);

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;

public class FarmAnimals {

public static String findRabbitsChickens(int heads, int legs) {


if (legs % 2 != 0) {
return "The number of legs cannot be odd.";
}
int chickens = (4 * heads - legs) / 2;
int rabbits = heads - chickens;
if (chickens < 0 || rabbits < 0 || (2 * chickens + 4 * rabbits != legs)) {
return "The number of chickens and rabbits cannot be determined.";
}

return "Chicken: " + chickens + ", Rabbit: " + rabbits;


}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the total number of heads: ");


int heads = scanner.nextInt();
System.out.print("Enter the total number of legs: ");
int legs = scanner.nextInt();

String result = findRabbitsChickens(heads, legs);

// Print the result


System.out.println(result);

scanner.close();
}
}

Output:1
Enter the total number of heads: 150
Enter the total number of legs: 500

Chicken: 50, Rabbit: 100

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.

4. (i)Develop a JAVA Program for the following scenario: CO2-Apply (08)

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:

Case 1: Regular Customer


Enter customer type (Regular/Guest): Regular
Enter number of food items: 4

Total cost after discount: Rs.570

Case 2: Guest Customer


Enter customer type (Regular/Guest): Guest
Enter number of food items: 3

Total cost: Rs.450

26) (ii)Develop a java program to generate Fibonacci series,where N=10.

ANSWER:
import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of N: ");
int n = sc.nextInt();

int first = 0, second = 1;


System.out.print("Fibonacci Series: ");

for (int i = 0; i < n; i++) {


System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}
sc.close();
}
}

OUTPUT:

Enter the value of N: 10


Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
5. (i)Develop a JAVA Program for the following scenario:
CO2- (08)
Apply
The assumption over here is that each food item costs Rs.150. The Regular
customers are provided with a 5% discount for their orders whereas the
Guests need to pay an additional delivery charge of Rs.5. First, the customer
type is checked, If the customer type is Regular or Guest. Also, for regular
customers, if the total cost exceeds Rs.300, a special gift voucher will be
provided to the customers. If customer type is invalid, a certain code should
execute. Find the total cost for an order.
ANSWER:
(08)
import java.util.Scanner; CO2-
public class FoodOrder { Apply

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of food items: ");


int items = sc.nextInt();
System.out.print("Enter customer type (Regular/Guest): ");
String customerType = sc.next();

double costPerItem = 150;


double totalCost = items * costPerItem;

if (customerType.equalsIgnoreCase("Regular")) {
double discount = totalCost * 0.05; // 5% discount
totalCost -= discount;

System.out.println("Total Cost after Discount: Rs." + totalCost);

if (totalCost > 300) {


System.out.println("Congratulations! You have earned a special gift
voucher.");
}
} else if (customerType.equalsIgnoreCase("Guest")) {
totalCost += 5; // Additional delivery charge
System.out.println("Total Cost including delivery charge: Rs." + totalCost);
} else {
System.out.println("Invalid customer type. Please try again.");
}

sc.close();
}
}

(ii) Develop a JAVA program to print the following Pyramid pattern

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

Total Cost after Discount: Rs.427.5


Congratulations! You have earned a special gift voucher.

Part (ii): For rows = 5, the output will be:

*
***
*****
*******
*********
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:

It evaluates a condition and executes a block of code if the condition is true.

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:

This is used when you have multiple conditions to check.

Syntax:

if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if none of the conditions are true
}

4. switch statement:

It evaluates an expression and matches it against different case values.

Syntax:

switch (variable) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no match
}
Example:

public class SelectionExample {


public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("Positive Number");
} else if (number < 0) {
System.out.println("Negative Number");
} else {
System.out.println("Zero");
}
}
}

This example checks if the number is positive, negative, or zero using the if-else
structure.

Iteration Control Structure in Java

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:

Used when the number of iterations is known beforehand.

Syntax:

for (initialization; condition; update) {


// Code to execute
}

2. while loop:

Executes a block of code as long as the condition is true.

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:

public class IterationExample {


public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
}
}

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)

given value n, where n is the number of elements in the sequence.1, 2, 4, 8, 16,


32, 64, ......, 1024
ANSWER:
public class GeometricSequence { (08)
CO2-
public static void main(String[] args) { Apply

int n = 10; // Will display sequence up to 1024

// Validate input
CO2-
if (n <= 0) { Apply
System.out.println("Please enter a positive number");
return;
}

System.out.println("Geometric Sequence with " + n + " elements:");


long term = 1;
for (int i = 1; i <= n; i++) {
System.out.print(term);
if (i < n) {
System.out.print(", ");
}
term *= 2; // Multiply by 2 for next term
}
System.out.println(); // New line at the end
}
}

OUTPUT:

Geometric Sequence with 11 elements:


1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024

(ii) Develop a JAVA program to print the following Number pattern

ANSWER:
public class NumberPattern {
public static void main(String[] args) {
// Number of rows needed is 7
int rows = 7;

// Outer loop for each row


for (int i = 1; i <= rows; i++) {
// Inner loop to print numbers from 1 to i
for (int j = 1; j <= i; j++) {
// Print number followed by space
System.out.print(j + " ");
}
// New line after each row
System.out.println();
}
}
}

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;

public class SeedNumberChecker {


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

System.out.print("Enter the potential seed number (X): ");


int x = scanner.nextInt();

System.out.print("Enter the target number (Y): ");


int y = scanner.nextInt();

if (isSeed(x, y)) {
System.out.println(x + " is a seed of " + y);
} else {
System.out.println(x + " is NOT a seed of " + y);
}
}

public static boolean isSeed(int x, int y) {


// Calculate the product of x and all its digits
int product = x;
int temp = x;

while (temp > 0) {


int digit = temp % 10;
product *= digit;
temp /= 10;
}

// Check if the product equals y


return product == y;
}
}

output
Test Case 1: 123 is a seed of 738

Enter the potential seed number (X): 123


Enter the target number (Y): 73

123 is a seed of 738


Explanation:
123 × 1 × 2 × 3 = 123 × 6 = 738 → So, 123 is a seed of 738.

Test Case 2: 24 is a seed of 192

Enter the potential seed number (X): 24


Enter the target number (Y): 192

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);

System.out.print("Enter the number of rows for Pascal's Triangle: ");


int rows = scanner.nextInt();

printPascalTriangle(rows);
}

public static void printPascalTriangle(int rows) {


for (int i = 0; i < rows; i++) {
// Print leading spaces
for (int j = 0; j < rows - i; j++) {
System.out.print(" ");
}

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;

public class OddNumberSum {


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

System.out.print("Enter the value of n: ");


int n = scanner.nextInt();

int sum = calculateOddSum(n);


System.out.println("Sum of first " + n + " odd numbers (skipping 1 number):
" + sum);
}

public static int calculateOddSum(int n) {


int sum = 0;
int count = 0;
int currentOdd = 1;

while (count < n) {


sum += currentOdd;
currentOdd += 4; // Skip the next odd by adding 4 instead of 2
count++;
}
return sum;
}
}

OUTPUT:
Enter the value of n: 1
Sum of first 1 odd numbers (skipping 1 number): 1

Enter the value of n: 3


Sum of first 3 odd numbers (skipping 1 number): 15
(1 + 5 + 9 = 15)

Enter the value of n: 5


Sum of first 5 odd numbers (skipping 1 number): 45
(1 + 5 + 9 + 13 + 17 = 45)
10. (i) Write a Java program to print Floyd’s triangle. CO2- (08)
Apply
ANSWER:
import java.util.Scanner; (08)
CO2-
Apply
public class FloydTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows for Floyd's Triangle: ");


int rows = scanner.nextInt();

printFloydTriangle(rows);
}

public static void printFloydTriangle(int rows) {


int number = 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(number + " ");
number++;
}
System.out.println();
}
}
}

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;

public class FindDuplicatesSimple {


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

System.out.print("Enter the size of the array: ");


int size = scanner.nextInt();
int[] arr = new int[size];

System.out.println("Enter the array elements:");


for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}

findDuplicates(arr);
}

public static void findDuplicates(int[] arr) {


System.out.print("Duplicate elements: ");
boolean foundDuplicate = false;

for (int i = 0; i < arr.length; i++) {


for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
System.out.print(arr[i] + " ");
foundDuplicate = true;
break; // Move to next element after finding first duplicate
}
}
}

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

UNIT – II(Minimum 10 Questions)

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;

public class Restaurant {


// Instance variables
private String restaurantName;
private long restaurantContact;
private String restaurantAddress;
private float rating;

// Constructor to initialize the instance variables


public Restaurant(String restaurantName, long restaurantContact, String
restaurantAddress, float rating) {
this.restaurantName = restaurantName;
this.restaurantContact = restaurantContact;
this.restaurantAddress = restaurantAddress;
this.rating = rating;
}

// Method to display restaurant details


public void displayRestaurantDetails() {
System.out.println("Restaurant Name: " + restaurantName);
System.out.println("Restaurant Contact: " + restaurantContact);
System.out.println("Restaurant Address: " + restaurantAddress);
System.out.println("Rating: " + rating + "/5");
}
}

Class: Tester

package SwiftFood;

public class Tester {


public static void main(String[] args) {
Restaurant restaurant = new Restaurant("Food Haven", 9876543210L, "123
Main Street, City Center", 4.5f)

restaurant.displayRestaurantDetails();
}
}

Output:

When the Tester class runs:

Restaurant Name: Food Haven


Restaurant Contact: 9876543210
Restaurant Address: 123 Main Street, City Center
Rating: 4.5/5

2. Problem Description: ABC Confectionary is a chocolate manufacturer. Every


chocolate which is manufactured will be with a default weight and cost. The cost
and weight might be modified later based on business needs. CO2- (16)
Apply
Create a class Chocolate, with a parameterized constructor and a default
constructor. Also, use the "this" keyword while initializing member variables
within the parameterized constructor.
Constructor Description:
• Chocolate( intbarCode, String name, double weight, double cost):

In the constructor initialize the member


variables:barCode, name, weight, and cost, according to the table
given below:

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;
}

// Method to display chocolate details


public void display() {
System.out.println("Chocolate Details:");
System.out.println("Barcode: " + barCode);
System.out.println("Name: " + name);
System.out.println("Weight: " + weight + "g");
System.out.println("Cost: $" + cost);
}

public static void main(String[] args) {


// Using default constructor
Chocolate defaultChoco = new Chocolate();
defaultChoco.display();

System.out.println();

// Using parameterized constructor


Chocolate customChoco = new Chocolate(102, "Dairy Milk", 15, 12.5);
customChoco.display();
}
}

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;

// Constructor to initialize book details


public Book(String author, String title, double price, String publisher, int stock) {
this.author = author;
this.title = title;
this.price = price;
this.publisher = publisher;
this.stock = stock;
}

// Method to display book details


public void displayBookDetails() {
System.out.println("Book Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: Rs." + price);
System.out.println("Publisher: " + publisher);
System.out.println("Stock: " + stock);
}
public boolean matches(String searchTitle, String searchAuthor) {
return
this.title.equalsIgnoreCase(searchTitle); &&
this.author.equalsIgnoreCase(searchAuthor);
}

// Method to process the purchase


public void purchaseBook(int copiesRequested) {
if (copiesRequested <= stock) {
System.out.println("Total Cost: Rs." + (price * copiesRequested));
stock -= copiesRequested; // Update stock
} else {
System.out.println("Required copies not in stock");
}
}
}

---
Class: BookShop

public class BookShop {


public static void main(String[] args) {
// Initialize book inventory
Book[] books = {
new Book("J.K. Rowling", "Harry Potter", 500, "Bloomsbury", 10),
new Book("George Orwell", "1984", 350, "Secker & Warburg", 5),
new Book("J.R.R. Tolkien", "The Hobbit", 400, "Allen & Unwin", 7)
};

Scanner sc = new Scanner(System.in);

// Input book title and author


System.out.print("Enter book title: ");
String searchTitle = sc.nextLine();
System.out.print("Enter author name: ");
String searchAuthor = sc.nextLine();

// Search for the book


boolean found = false;
for (Book book : books) {
if (book.matches(searchTitle, searchAuthor)) {
found = true;
System.out.println("\nBook Found:");
book.displayBookDetails();

// Request the number of copies


System.out.print("\nEnter number of copies required: ");
int copiesRequested = sc.nextInt();

// Process purchase
book.purchaseBook(copiesRequested);
break;
}
}

if (!found) {
System.out.println("\nBook not available");
}

sc.close();
}
}

OUTPUT:

Case 1: Book is Available and Copies in Stock

Enter book title: Harry Potter


Enter author name: J.K. Rowling

Book Found:
Book Title: Harry Potter
Author: J.K. Rowling
Price: Rs.500.0
Publisher: Bloomsbury
Stock: 10

Enter number of copies required: 3


Total Cost: Rs.1500.0

Case 2: Book is Not Available

Enter book title: The Great Gatsby


Enter author name: F. Scott Fitzgerald

Book not available

Case 3: Requested Copies Exceed Stock

Enter book title: 1984


Enter author name: George Orwell

Book Found:
Book Title: 1984
Author: George Orwell
Price: Rs.350.0
Publisher: Secker & Warburg
Stock: 5

Enter number of copies required: 6


Required copies not in stock
4. (i)Create a Customer class with following data members , String customerId;
CO2- (08)
String customerName; long contactNumber; String address; Apply
Create a parameterized constructor to initialize the members.
Create two customer objects and display the details of the two customers
using display_details() method.

ANSWER:
(08)

public class Customer { CO2-


// Data members Apply

private String customerId;


private String customerName;
private long contactNumber;
private String address;

// Parameterized constructor
public Customer(String customerId, String customerName, long contactNumber,
String address) {
this.customerId = customerId;
this.customerName = customerName;
this.contactNumber = contactNumber;
this.address = address;
}

// Method to display customer details


public void displayDetails() {
System.out.println("Customer ID: " + customerId);
System.out.println("Customer Name: " + customerName);
System.out.println("Contact Number: " + contactNumber);
System.out.println("Address: " + address);
}

// Main method to test the Customer class


public static void main(String[] args) {
// Creating two customer objects
Customer customer1 = new Customer("C001", "Alice", 9876543210L, "123
Main Street");
Customer customer2 = new Customer("C002", "Bob", 8765432109L, "456 Elm
Street");

// Displaying the details of the customers


System.out.println("Customer 1 Details:");
customer1.displayDetails();

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

(ii) Implement a class Calculator with the method mentioned below.


Method Description
findAverage()
Calculate the average of three numbers
Return the average rounded off to two decimal digits
Test the functionalities using the provided Tester class.

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
}

// Main method to test the Calculator class


public static void main(String[] args) {
Calculator calculator = new Calculator();

// Example input
double num1 = 25.5, num2 = 30.2, num3 = 45.8;

// Calculating and displaying the average


double average = calculator.findAverage(num1, num2, num3);
System.out.println("The average of " + num1 + ", " + num2 + ", and " + num3 +
" is: " + average);
}
}

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:

Problem Description: Suzanne is a journalist at InfyTV. She was working on the


"Save Tigers" documentary film along with her editors, photographers, camera
person, correspondents, and others. She has gathered the information regarding
the documentary from various sources. The source information is protected
within her team only. When this documentary is broadcasted, the public should
know about the documentary but not about the source information.So you being
a programmer at InfyTV write a program according to the following
conditions:

• Create a Java Project with the name Encapsulation And Abstraction


CO2- (16)
• Create a class InfyTV as shown in the class diagram given below: Apply

1. The details such as photographer, newsReporter, and correspondent


should be protected inside the team and hence declared as private
members.
2. Create a class tester with the main method and create an object of
class InfyTV and try to access the private member variables. Were you
able to access them?
3. Now try accessing the private members using the respective setters and
initialize them with the following values:

To show the documentary to the public, create a


method documentaryFilm() that displays the following output.

ANSWER:

// InfyTV.java
class InfyTV {
private String photographer;
private String newsReporter;
private String correspondent;

// Getter and Setter for photographer


public String getPhotographer() {
return photographer;
}

public void setPhotographer(String photographer) {


this.photographer = photographer;
}

// Getter and Setter for newsReporter


public String getNewsReporter() {
return newsReporter;
}

public void setNewsReporter(String newsReporter) {


this.newsReporter = newsReporter;
}

// Getter and Setter for correspondent


public String getCorrespondent() {
return correspondent;
}

public void setCorrespondent(String correspondent) {


this.correspondent = correspondent;
}

// Method to display the documentary details


public void documentaryFilm() {
System.out.println("A hundred years ago there were 100,000 tigers in
the world.");
System.out.println("Today there are as few as 3,200. Why are tigers
disappearing?...");
System.out.println("by Correspondent: " + correspondent);
System.out.println("Photographer: " + photographer);
System.out.println("newsReporter: " + newsReporter);
}
}

// Tester class
public class InfyTVTester {
public static void main(String[] args) {
// Create an object of InfyTV
InfyTV documentary = new InfyTV();

// Initialize private members using setters


documentary.setCorrespondent("Kimberely");
documentary.setNewsReporter("Hudson");
documentary.setPhotographer("Joshua");

// Display the documentary film


documentary.documentaryFilm();
}
}

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;
}

// Method to calculate product of digits


public static int productDigits(int num) {
int product = 1;
while (num > 0) {
product *= num % 10;
num /= 10;
}
return product;
}

public static void main(String[] args) {


int[] arr = {123, 98, 56, 45}; // Example input

for (int num : arr) {


int sumResult = sumDigits(num);
int productResult = productDigits(num);
System.out.println("Number: " + num + ", Max Value: " +
Math.max(sumResult, productResult));
}
}
}
OUTPUT:
Number: 123, Max Value: 6
Number: 98, Max Value: 72
Number: 56, Max Value: 30
Number: 45, Max Value: 20

(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;
}

// Method to add two complex numbers


public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imag + other.imag);
}
// Method to display the complex number
public void display() {
System.out.println(real + " + " + imag + "i");
}

public static void main(String[] args) {


Complex c1 = new Complex(3.2, 4.5);
Complex c2 = new Complex(2.3, 3.1);

Complex sum = c1.add(c2);


System.out.print("Sum of Complex Numbers: ");
sum.display();
}
}

OUTPUT:

Sum of Complex Numbers: 5.5 + 7.6i


7. The Metro Bank provides various types of loans such as car loans,business loans
and house loans to its account holders, i.e., customers.Implement a program to
determine the eligible loan amount and the EMI that the bank can provide to its
customers based on their salary and theloan type they expect to avail.
The values required for determining the eligible loan amount and the EMI
are:
• account number of the customer
• account balance of the customer
• salary of the customer
• loan type
• expected loan amount
• expected no. of EMIs
The following validations should be performed:
• The account number should be of 4 digits and its first digit should
be 1
• The customer should have a minimum balance of $1000 in the
account
CO2-
➢ Display appropriate error messages if the validations fail. Apply
(16)

➢ If the validations pass, determine whether the bank would provide theloan
or not.

The following are the criteria for a bank to provide loan:


The bank would provide the loan, only if the loan amount and the number
of EMIs expected by the customer is less than or equal to the loan
amount and the number of EMIs decided by the bank respectively. The
bank decides the eligible loan amount and the number of EMIs based on
the below table:

• 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;

public class MetroBankLoanSystem {


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

// Input customer details


System.out.println("Enter account number:");
int accountNumber = scanner.nextInt();

System.out.println("Enter account balance:");


double accountBalance = scanner.nextDouble();

System.out.println("Enter salary:");
double salary = scanner.nextDouble();

scanner.nextLine(); // Consume newline

System.out.println("Enter loan type (Car/House/Business):");


String loanType = scanner.nextLine();

System.out.println("Enter expected loan amount:");


double expectedLoanAmount = scanner.nextDouble();

System.out.println("Enter expected number of EMIs:");


int expectedEMIs = scanner.nextInt();

// Validate inputs
if (!validateAccountNumber(accountNumber)) {
System.out.println("Error: Account number should be 4 digits and start with
1");
return;
}

if (accountBalance < 1000) {


System.out.println("Error: Minimum account balance should be $1000");
return;
}

// Determine eligible loan amount and EMIs


double eligibleLoanAmount = 0;
int eligibleEMIs = 0;
boolean eligible = false;

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;
}

// Check loan eligibility


if (!eligible) {
System.out.println("Sorry, you are not eligible for the " + loanType + " loan
based on your salary.");
return;
}

if (expectedLoanAmount <= eligibleLoanAmount && expectedEMIs <=


eligibleEMIs) {
System.out.println("\nLoan Approved!");
System.out.println("Account Number: " + accountNumber);
System.out.println("Eligible Loan Amount: $" + eligibleLoanAmount);
System.out.println("Requested Loan Amount: $" + expectedLoanAmount);
System.out.println("Eligible EMIs: " + eligibleEMIs);
System.out.println("Requested EMIs: " + expectedEMIs);
} else {
System.out.println("\nSorry, we cannot provide the loan:");
if (expectedLoanAmount > eligibleLoanAmount) {
System.out.println("- Your expected loan amount exceeds the eligible
amount of $" + eligibleLoanAmount);
}
if (expectedEMIs > eligibleEMIs) {
System.out.println("- Your expected EMIs exceed the eligible EMIs of " +
eligibleEMIs);
}
}
}

private static boolean validateAccountNumber(int accountNumber) {


return accountNumber >= 1000 && accountNumber <= 1999;
}
}
OUTPUT:
LOAN APPROVED.
Enter account number:
1234
Enter account balance:
5000
Enter salary:
80000
Enter loan type (Car/House/Business):
House
Enter expected loan amount:
5000000
Enter expected number of EMIs:
48

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;

public class MatrixOperations {


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

System.out.print("Enter the number of rows: ");


int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();

int[][] matrix1 = new int[rows][cols];


int[][] matrix2 = new int[rows][cols];
int[][] sum = new int[rows][cols];
int[][] difference = new int[rows][cols];
CO2-
(16)
System.out.println("Enter elements of first matrix:"); Apply
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix1[i][j] = scanner.nextInt();
}
}

System.out.println("Enter elements of second matrix:");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
difference[i][j] = matrix1[i][j] - matrix2[i][j];
}
}

System.out.println("Sum of matrices:");
printMatrix(sum);

System.out.println("Difference of matrices:");
printMatrix(difference);

scanner.close();
}

public static void printMatrix(int[][] matrix) {


for (int[] row : matrix) {
for (int elem : row) {
System.out.print(elem + " ");
}
System.out.println();
}
}

}
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

double salary[] = {23500.0, 25080.0, 28760.0, 22340.0, 19890.0}

Create a class EmployeeRecord and write a program to implement the above


requirement. Refer to the output given below:

ANSWER:

public class EmployeeRecord {


public static void main(String[] args) {
// Initialize the salary array
double[] salary = {23500.0, 25080.0, 28760.0, 22340.0, 19890.0};

// Calculate the average salary


double averageSalary = calculateAverage(salary);

// Count employees with salaries above and below the average


int greaterCount = countGreaterThanAverage(salary, averageSalary);
int lesserCount = countLessThanAverage(salary, averageSalary);

// Display the results


System.out.println("The average salary of the employee is: " + averageSalary);
System.out.println("The no of emp having salary greater than the average is: " +
greaterCount);
System.out.println("The no of emp having salary lesser than the average is: " +
lesserCount);
}

// Method to calculate the average salary


public static double calculateAverage(double[] salary) {
double total = 0.0;
for (double s : salary) {
total += s;
}
return total / salary.length;
}

// Method to count salaries greater than the average


public static int countGreaterThanAverage(double[] salary, double average) {
int count = 0;
for (double s : salary) {
if (s > average) {
count++;
}
}
return count;
}

// Method to count salaries less than the average


public static int countLessThanAverage(double[] salary, double average) {
int count = 0;
for (double s : salary) {
if (s < average) {
count++;
}
}
return count;
}
}

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;

public void setAge(int age) { (10)


this.age = age; CO2-
} Apply

public int getAge() {


return age;
}
}

public class EncapsulationExample1 {


public static void main(String[] args) {
Person person = new Person();
person.setAge(25);
System.out.println("Person's Age: " + person.getAge());
}
}

OUTPUT:

Person's Age: 25

(ii)Develop a java program using encapsulation to display a person account


number, name, mail-idand amount.

use the instance variable as follows:


• private long acc_no;
• private String name,email;
• private float amount;

use these methods:


• long getAcc_no()
• void setAcc_no
• String getName()
• setName(String name)
• String getEmail()
• void setEmail(String email)
• float getAmount()
• void setAmount(float amount)

ANSWER:

class Account {
private long acc_no;
private String name, email;
private float amount;

public long getAcc_no() {


return acc_no;
}

public void setAcc_no(long acc_no) {


this.acc_no = acc_no;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public float getAmount() {


return amount;
}

public void setAmount(float amount) {


this.amount = amount;
}
}

public class EncapsulationExample2 {


public static void main(String[] args) {
Account acc = new Account();
acc.setAcc_no(1234567890L);
acc.setName("John Doe");
acc.setEmail("[email protected]");
acc.setAmount(5000.75f);

System.out.println("Account Number: " + acc.getAcc_no());


System.out.println("Name: " + acc.getName());
System.out.println("Email: " + acc.getEmail());
System.out.println("Amount: " + acc.getAmount());
}
}

OUTPUT:

Account Number: 1234567890


Name: John Doe
Email: [email protected]
Amount: 5000.75

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

public int getRollno() {


return rollno;
}

// Setter for rollno


public void setRollno(int rollno) {
this.rollno = rollno;
}
}
// Derived class Test from Student
class Test extends Student {
private int marks1;
private int marks2;

// Getter for marks1


public int getMarks1() {
return marks1;
}

// Setter for marks1


public void setMarks1(int marks1) {
this.marks1 = marks1;
}

// Getter for marks2


public int getMarks2() {
return marks2;
}

// Setter for marks2


public void setMarks2(int marks2) {
this.marks2 = marks2;
}
}

// Derived class Result from Test


class Result extends Test {
private int total;

// Method to calculate and display all members


public void display() {
// Calculate total
total = getMarks1() + getMarks2();

// Display all details


System.out.println("Roll Number: " + getRollno());
System.out.println("Marks 1: " + getMarks1());
System.out.println("Marks 2: " + getMarks2());
System.out.println("Total Marks: " + total);
}
}

// 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);

// Display all members


result.display();
}
}

Output:

Roll Number: 101


Marks 1: 85
Marks 2: 90
Total Marks: 175

2. Write a Java program that has a class Train with data


membersnoofseatsfirsttier, noofseatssecondtier, noofseatsthirdtier and methods
to set and display data. Derive a class Reservation that has data
membersseatsbookedfirst, seatsbookedsecond and seatsbookedthird and
methods to book and cancel tickets, and display the status.

ANSWER:
// Base class Train
class Train {
int noOfSeatsFirstTier;
int noOfSeatsSecondTier;
int noOfSeatsThirdTier;

// Method to set seat information


void setSeats(int firstTier, int secondTier, int thirdTier) { CO2-
(16)
noOfSeatsFirstTier = firstTier; Apply
noOfSeatsSecondTier = secondTier;
noOfSeatsThirdTier = thirdTier;
}

// Method to display seat information


void displaySeats() {
System.out.println("First Tier Seats: " + noOfSeatsFirstTier);
System.out.println("Second Tier Seats: " + noOfSeatsSecondTier);
System.out.println("Third Tier Seats: " + noOfSeatsThirdTier);
}
}

// Derived class Reservation


class Reservation extends Train {
int seatsBookedFirst;
int seatsBookedSecond;
int seatsBookedThird;

// Method to book tickets


void bookTickets(int first, int second, int third) {
if (seatsBookedFirst + first <= noOfSeatsFirstTier &&
seatsBookedSecond + second <= noOfSeatsSecondTier &&
seatsBookedThird + third <= noOfSeatsThirdTier) {
seatsBookedFirst += first;
seatsBookedSecond += second;
seatsBookedThird += third;
System.out.println("Booking Successful!");
} else {
System.out.println("Not enough seats available.");
}
}

// Method to cancel tickets


void cancelTickets(int first, int second, int third) {
if (seatsBookedFirst >= first && seatsBookedSecond >= second &&
seatsBookedThird >= third) {
seatsBookedFirst -= first;
seatsBookedSecond -= second;
seatsBookedThird -= third;
System.out.println("Cancellation Successful!");
} else {
System.out.println("Cannot cancel more tickets than booked.");
}
}

// Method to display booking status


void displayBookingStatus() {
System.out.println("Seats Booked - First Tier: " + seatsBookedFirst);
System.out.println("Seats Booked - Second Tier: " + seatsBookedSecond);
System.out.println("Seats Booked - Third Tier: " + seatsBookedThird);
}
}

public class Main {


public static void main(String[] args) {
Reservation reservation = new Reservation();
reservation.setSeats(50, 100, 150);

reservation.displaySeats();

reservation.bookTickets(10, 20, 30);


reservation.displayBookingStatus();

reservation.cancelTickets(5, 10, 15);

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

The category of the player is decided based on the average calculated by


the calculateAverageRating() method as follows:
Implement the tester class to know the rating of the player.

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
}

public void calculateAverageRating(float criticOneRating, float criticTwoRating) {


this.criticOneRating = criticOneRating;
this.criticTwoRating = criticTwoRating;
this.averageRating = (criticOneRating + criticTwoRating) / 2;
calculateCategory();
}

public void calculateAverageRating(float criticOneRating, float criticTwoRating,


float criticThreeRating) {
this.criticOneRating = criticOneRating;
this.criticTwoRating = criticTwoRating;
this.criticThreeRating = criticThreeRating;
this.averageRating = (criticOneRating + criticTwoRating + criticThreeRating) / 3;
calculateCategory();
}

// Method to determine category based on average rating


private void calculateCategory() {
if (averageRating > 8) {
category = 'A';
} else if (averageRating > 5 && averageRating <= 8) {
category = 'B';
} else if (averageRating > 0 && averageRating <= 5) {
category = 'C';
}
}

// Method to display player details


public void display() {
System.out.println("Player Position: " + playerPosition);
System.out.println("Player Name: " + playerName);
System.out.println("Critic 1 Rating: " + criticOneRating);
System.out.println("Critic 2 Rating: " + criticTwoRating);
if (criticThreeRating != 0) {
System.out.println("Critic 3 Rating: " + criticThreeRating);
}
System.out.println("Average Rating: " + averageRating);
System.out.println("Category: " + category);
System.out.println();
}
}

public class PlayerRatingTester {


public static void main(String[] args) {
PlayerRating player1 = new PlayerRating(1, "John Doe");
player1.calculateAverageRating(8.5f, 7.5f);
player1.display();

PlayerRating player2 = new PlayerRating(2, "Jane Smith");


player2.calculateAverageRating(9.0f, 8.5f, 9.5f);
player2.display();

PlayerRating player3 = new PlayerRating(3, "Mike Johnson");


player3.calculateAverageRating(4.5f, 5.5f);
player3.display();
}
}

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;

// Constructor with passport


public Registration(String customerName, String passportNo, long[] telephoneNo)
{
this.customerName = customerName;
this.passportNo = passportNo;
this.telephoneNo = telephoneNo;
}

// Constructor with license and PAN card


public Registration(String customerName, int licensenNo, String panCardNo,
long[] telephoneNo) {
this.customerName = customerName;
this.licensenNo = licensenNo;
this.panCardNo = panCardNo;
this.telephoneNo = telephoneNo;
}

// Constructor with voter ID and license


public Registration(String customerName, int voterId, int licensenNo, long[]
telephoneNo) {
this.customerName = customerName;
this.voterId = voterId;
this.licensenNo = licensenNo;
this.telephoneNo = telephoneNo;
}

// Constructor with PAN card and voter ID


public Registration(String customerName, String panCardNo, int voterId, long[]
telephoneNo) {
this.customerName = customerName;
this.panCardNo = panCardNo;
this.voterId = voterId;
this.telephoneNo = telephoneNo;
}

// Getters
public String getCustomerName() {
return customerName;
}

public String getPanCardNo() {


return panCardNo;
}

public int getVoterId() {


return voterId;
}

public String getPassportNo() {


return passportNo;
}

public int getLicensenNo() {


return licensenNo;
}

public long[] getTelephoneNo() {


return telephoneNo;
}

@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);
}
}

public class EnigmaRegistrationTester {


public static void main(String[] args) {
// Test case 1: Registration with passport
long[] phoneNumbers1 = {9876543210L, 9123456780L};
Registration reg1 = new Registration("John Doe", "A12345678",
phoneNumbers1);
System.out.println(reg1);
System.out.println("---------------------");

// Test case 2: Registration with license and PAN card


long[] phoneNumbers2 = {8765432109L, 8987654321L};
Registration reg2 = new Registration("Jane Smith", 123456, "ABCDE1234F",
phoneNumbers2);
System.out.println(reg2);
System.out.println("---------------------");

// Test case 3: Registration with voter ID and license


long[] phoneNumbers3 = {7654321098L, 8123456789L};
Registration reg3 = new Registration("Robert Johnson", 987654, 567890,
phoneNumbers3);
System.out.println(reg3);
System.out.println("---------------------");

// Test case 4: Registration with PAN card and voter ID


long[] phoneNumbers4 = {6543210987L, 7890123456L};
Registration reg4 = new Registration("Alice Brown", "FGHIJ5678K",
123456789, phoneNumbers4);
System.out.println(reg4);
}
}

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;

// Constructor to initialize box dimensions


Box(double l, double w, double h) {
length = l;
width = w;
height = h;
}

// Method to calculate the volume of the box


double volume() {
return length * width * height;
}
}

// Derived class: BoxWeight (inherits from Box)


class BoxWeight extends Box {
double weight;

// Constructor to initialize box dimensions and weight


BoxWeight(double l, double w, double h, double weight) {
super(l, w, h); // Call the parent class constructor
this.weight = weight;
}
}

// Derived class: Shipment (inherits from BoxWeight)


class Shipment extends BoxWeight {
double shippingCost;

// Constructor to initialize box dimensions, weight, and shipping cost


Shipment(double l, double w, double h, double weight, double shippingCost) {
super(l, w, h, weight); // Call the parent class constructor
this.shippingCost = shippingCost;
}

// Method to display shipment details


void displayShipmentDetails() {
System.out.println("Box Dimensions: " + length + " x " + width + " x " + height);
System.out.println("Weight: " + weight + " kg");
System.out.println("Shipping Cost: $" + shippingCost);
System.out.println("Volume of the box: " + volume() + " cubic units");
}
}

// Main class
public class BoxShipmentTest {
public static void main(String[] args) {
// Create a Shipment object
Shipment shipment = new Shipment(10, 5, 4, 15, 50);

// Display shipment details


shipment.displayShipmentDetails();
}
}

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;

// Constructor for Media


public Media(String title, double price) {
this.title = title;
this.price = price;
}

// Method to display Media details


public void display() {
System.out.println("Title: " + title);
System.out.println("Price: $" + price);
}
}

// Derived class Book from Media


class Book extends Media {
private int pages;

// Constructor for Book


public Book(String title, double price, int pages) {
super(title, price); // Call to parent class constructor
this.pages = pages;
}

// Method to display Book details


@Override
public void display() {
super.display(); // Call parent class display
System.out.println("Pages: " + pages);
}
}

// Derived class Tape from Media


class Tape extends Media {
private float time;

// Constructor for Tape


public Tape(String title, double price, float time) {
super(title, price); // Call to parent class constructor
this.time = time;
}

// Method to display Tape details


@Override
public void display() {
super.display(); // Call parent class display
System.out.println("Time: " + time + " minutes");
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create a Book object
Book book = new Book("Java Programming", 29.99, 450);

// Create a Tape object


Tape tape = new Tape("Learning Java", 19.99, 90.5f);

// Display details of the Book


System.out.println("Book Details:");
book.display();

// Display details of the Tape


System.out.println("\nTape Details:");
tape.display();
}
}
OUTPUT:

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;

// Constructor to initialize gear and speed


public Bike(int gear, int speed) {
this.gear = gear;
CO2-
this.speed = speed; (16)
Apply
}

// Method to apply brake and decrease speed


public void applyBrake(int value) {
speed -= value;
}

// Method to increase speed


public void speedUp(int value) {
speed += value;
}

// toString method to print data members


public String toString() {
return "Gear: " + gear + ", Speed: " + speed;
}
}
// MountainBike class that inherits from Bike
class MountainBike extends Bike {
int seatHeight;

// Constructor to initialize gear, speed, and seatHeight


public MountainBike(int gear, int speed, int seatHeight) {
super(gear, speed); // Calling Bike constructor
this.seatHeight = seatHeight;
}
public void setHeight(int newHeight) {
seatHeight = newHeight;
}

// Overridden
public String toString() {
return super.toString() + ", Seat Height: " + seatHeight;
}
}

// Main class to test the program


public class Main {
public static void main(String[] args) {
Bike bike = new Bike(5, 25);
System.out.println("Bike details: " + bike.toString());

MountainBike mountainBike = new MountainBike(6, 30, 15);


System.out.println("MountainBike details: " + mountainBike.toString());

mountainBike.speedUp(10);
mountainBike.applyBrake(5);
mountainBike.setHeight(20);

// Print updated details


System.out.println("Updated MountainBike details: " +
mountainBike.toString());
}
}

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;
}
}

class Box extends Shape {


double height;
// Default constructor
Box() {
super(); // Calls Shape's default constructor
this.height = 0;
}
// Parameterized constructor
Box(double length, double breadth, double height) {
super(length, breadth); // Calls Shape's parameterized constructor
this.height = height;
}

@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());

shopping.payBill(400.0); // Invalid payment

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());

creditCard.payBill(800.0); // Partial payment


System.out.println("Balance Due: " + creditCard.getBalanceDue());
}
}
// Base abstract class
abstract class RRPaymentServices {
protected double balance;
protected int customerID;

public RRPaymentServices(double balance, int customerID) {


this.balance = balance;
this.customerID = customerID;
}

public void setBalance(double balance) {


this.balance = balance;
}

public double getBalance() {


return balance;
}

public int getCustomerID() {


return customerID;
}

public abstract void payBill(double amount);


}

// ShoppingPayment class
class ShoppingPayment extends RRPaymentServices {
private static int counter = 1000;
private String paymentID;

public ShoppingPayment(double balance, int customerID) {


super(balance, customerID);
}

public String getPaymentID() {


return 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;

public CreditCardPayment(double balance, int customerID) {


super(balance, customerID);
this.balanceDue = 0;
this.cashBack = 0;
}

public String getPaymentID() {


return paymentID;
}

public double getCashBack() {


return cashBack;
}

public double getBalanceDue() {


return 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:

Shopping Payment Test:


Shopping payment successful for customer 1001
Payment ID: S1001
Error: Amount entered is not equal to the balance due.

Credit Card Payment Test:


Credit card payment successful for customer 2001
Payment ID: C1001
Cashback: 200.0
Partial payment received. Balance due: 200.0
10. Use the interfaces concept for the given scenario: The DataProvider provides an
efficient way for students to calculate their overall percentage of all the courses.
The totalMaximumMarks for all courses is 8000. Intern studied in Institute A,
where each semester comprises of 1000 marks, in which 900 marks are for
CO2- (16)
courses and 100 marks are kept for co-curricular activities (graceMarks). Apply
Whereas Trainee studied in Institute B where each semester comprises of 1000
marks for courses.

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
}
}

class Trainee implements DataProvider {


private int courseMarks;
private static final int TOTAL_MAXIMUM_MARKS = 8000;
// Constructor
Trainee(int courseMarks) {
this.courseMarks = courseMarks;
}
@Override
public double calcPercentage() {
return (courseMarks / (double) TOTAL_MAXIMUM_MARKS) * 100; // Calculate
percentage
}
}
// Main class
public class Main {
public static void main(String[] args) {

Intern intern = new Intern(4500); // Example: 4500 marks secured


System.out.println("Intern Percentage: " + intern.calcPercentage() +
"%");

Trainee trainee = new Trainee(7200); // Example: 7200 marks secured


System.out.println("Trainee Percentage: " + trainee.calcPercentage() +
"%");
}
}

OUTPUT:

Intern Percentage: 57.5%


Trainee Percentage: 90.0%
UNIT – IV(Minimum 10 Questions)

1. A bank wants to conduct examinations for recruitment. You need to develop an


application forthe applicants to submit their details by implementing the classes
based on the descriptiongiven below.

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;

public class GFG {


public static void main(String[] args) {
// Create ArrayLists L1 and L2
ArrayList<Integer> L1 = new ArrayList<>();
L1.add(0);
L1.add(1);
L1.add(1);
L1.add(2);

ArrayList<Integer> L2 = new ArrayList<>();


L2.add(1);
L2.add(2);
L2.add(3);

// Display L1 and L2
System.out.println("L1: " + L1);
System.out.println("L2: " + L2);

// Add L2 into L1 starting from index 1


L1.addAll(1, L2);
System.out.println("L1 after adding L2 at index 1: " + L1);

// Remove element at index 1 from L1


L1.remove(1);
System.out.println("L1 after removing element at index 1: " + L1);

// Print element at index 3 from L1


System.out.println("Element at index 3 of L1: " + L1.get(3));
// Replace element at index 0 with value 5
L1.set(0, 5);
System.out.println("L1 after replacing index 0 with 5: " + L1);

// 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;

public class StringArrayList {


public static void main(String[] args) {
// Create an ArrayList and add strings
ArrayList<String> list = new ArrayList<>();
list.add("C++");
list.add("Java");
list.add("C");
list.add("Python");

// Retrieve string at index 2


System.out.println("String at index 2: " + list.get(2));

// Change the string at index 2 to "Programming"


list.set(2, "Programming");
System.out.println("Updated list: " + list);

// Remove string at index 0


list.remove(0);
System.out.println("List after removing element at index 0: " + list);
}
}

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

A package in Java is a collection of related classes and interfaces grouped together.


Packages help in:

Organizing code efficiently


Avoiding class name conflicts
Controlling access through access modifiers
Improving maintainability and reusability

Types of Packages in Java

1. Built-in Packages: Predefined in Java (e.g., java.util, java.io)


2. User-defined Packages: Created by the programmer
CO1-U (16)

Creating a Package in Java

Steps to Create a Package:

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

Example: Creating and Using a Package

Step 1: Create a package named myPackage

// Save this file as MyClass.java inside a folder named "myPackage"


package myPackage;

public class MyClass {


public void showMessage() {
System.out.println("Hello from myPackage!");
}
}

Step 2: Compile the package

javac -d . MyClass.java

This creates a myPackage directory containing MyClass.class.

Step 3: Use the package in another class

// Save this file in the same directory as TestPackage.java


import myPackage.MyClass;

public class TestPackage {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.showMessage();
}
}

Step 4: Compile and Run

javac TestPackage.java
java TestPackage

Output:

Hello from myPackage!


5 Explain the accessibility of each access modifier inside packages.

ANSWER:

Access modifiers determine the visibility of classes, methods, and variables. The four
types are:

public: Accessible from any other class in any package.


CO1-U (16)
protected: Accessible within the same package and by subclasses (even if they are in
a different package).

default (no modifier): Accessible only within the same package.

private: Accessible only within the class itself.


Explanation with Examples

1. Public Modifier
Accessible everywhere, even from different packages.
package myPackage;

public class PublicExample {


public void show() {
System.out.println("Public method - Accessible everywhere");
}
}

import myPackage.PublicExample;

public class TestPublic {


public static void main(String[] args) {
PublicExample obj = new PublicExample();
obj.show(); // Accessible from another package
}
}

Output:

Public method - Accessible everywhere

2. Protected Modifier

Accessible within the same package and by subclasses in other packages.

package myPackage;

public class ProtectedExample {


protected void display() {
System.out.println("Protected method - Accessible within package and
subclasses");
}
}

package anotherPackage;
import myPackage.ProtectedExample;

public class TestProtected extends ProtectedExample {


public static void main(String[] args) {
TestProtected obj = new TestProtected();
obj.display(); // Allowed since TestProtected extends ProtectedExample
}
}

Output:

Protected method - Accessible within package and subclasses

3. Default (No Modifier)


Accessible only within the same package.

package myPackage;

class DefaultExample {
void message() {
System.out.println("Default method - Accessible only in the same package");
}
}

package anotherPackage;
import myPackage.DefaultExample;

public class TestDefault {


public static void main(String[] args) {
DefaultExample obj = new DefaultExample(); // Error! Not accessible outside
myPackage
obj.message();
}
}

Error:

DefaultExample is not public in myPackage; cannot be accessed from outside


package

4. Private Modifier

Accessible only within the same class.

package myPackage;

public class PrivateExample {


private void secret() {
System.out.println("Private method - Accessible only inside this class");
}

public void show() {


secret(); // Allowed within the same class
}
}

package anotherPackage;
import myPackage.PrivateExample;

public class TestPrivate {


public static void main(String[] args) {
PrivateExample obj = new PrivateExample();
obj.secret(); // Error! Private method not accessible outside the class
}
}

Error:
secret() has private access in myPackage.PrivateExample

Conclusion

1. public → Accessible everywhere


2. protected → Accessible within the package and by subclasses in different
packages
3. default (no modifier) → Accessible only within the same package
4. private → Accessible only inside the same class
6 Create a new Java Program with one package named com.infy.package1 which
contains the Student Class and another package
named com.infy.package2 which contains the StudentDetails class according to
the class diagrams given below.

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.

The StudentDetails class contains 2 methods i.e. calculatePercentage() and


displayStudentDetails(). The calculatePercentage() calculates and prints the
percentage of the student whose details are passed to it.
The displayStudentDetails() prints all the student details including the
studentId, studentName, totalMarks and totalMarksObtained in the format
given in the expected result.

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)

• Create a package with name MyInterface

• Interface with name GeoAnalyzer with variables pi,area and perimeter

• Create classes Circle, Ellipse and Rectangle

• Create a Main class as shape

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;
}

public double perimeter(){


return 2 * (length + width);
}
}

4)

package MyInterface;
public class Ellipse implements GeoAnalyzer
{
private double semiMajorAxis;
private double semiMinorAxis;

public Ellipse(double semiMajorAxis, double semiMinorAxis) {


this.semiMajorAxis = semiMajorAxis;
this.semiMinorAxis = semiMinorAxis;
}
@Override
public double area() {
return pi * semiMajorAxis * semiMinorAxis;
}
@Override
public double perimeter() {
return pi * (3 * (semiMajorAxis + semiMinorAxis) - Math.sqrt((3 *
semiMajorAxis + semiMinorAxis) * (semiMajorAxis + 3 * 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)

✓ Create five objects of employee class by passing appropriate


values to all the data members.
✓ Call checkEmployeeSalary() method for each of the
five Employee objects being passed and handle
the EmpSalaryException.
✓ Print the empName where the Salary is < 1000.

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 {

public static void checkEmployeeSalary(Employee emp) throws


EmpSalaryException {
if (emp.getEmpSalary() < 1000) {
throw new EmpSalaryException("Salary is less than 1000 for employee: " +
emp.getEmpName());
}
}
public static void main(String[] args) {
// Create five Employee objects
Employee[] employees = {
new Employee("John", 25, 1200),
new Employee("Alice", 30, 800),
new Employee("Bob", 28, 1500),
new Employee("Eve", 22, 900),
new Employee("Charlie", 35, 1100)
};

for (Employee emp : employees) {


try {
checkEmployeeSalary(emp);
} catch (EmpSalaryException e) {
System.out.println(e.getMessage());
}
}
}
}

OUTPUT:

Salary is less than 1000 for employee: Alice


Salary is less than 1000 for employee: Eve

9. How Exception is handled in Java. Give suitable illustrations

ANSWER:
Exception Handling in Java

Exception handling in Java is a mechanism to manage runtime errors,


ensuring that the program continues to execute smoothly even when unexpected
events occur.
An exception is an event that disrupts the normal flow of a program, such
as dividing by zero, accessing an invalid array index, or attempting to open a file
that doesn’t exist.
Java provides a robust framework to handle such exceptions using
keywords like try, catch, throw, throws, and finally.
This allows developers to gracefully recover from errors or terminate the
CO1-U (16)
program with meaningful feedback.

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.

Illustration of Exception Handling


Consider a simple example where a program attempts to divide two numbers
provided by the user:
java
public class DivisionExample {
public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b; // This will throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
}

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:

Try, Throw, Catch, and Finally Blocks

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.");
}

Even if no exception occurs, "Execution completed" will still print.

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.

UNIT – V(Minimum 10 Questions)

1. Complete the reverseEachWord() method given in the Tester class.


Method Description
reverseEachWord(String str)
Reverse each word in the string passed to the method without changing the
order of

the words and return the modified string.

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

2 Explain about string constructors and explain the character extractions of


string with necessary syntax and example program.

ANSWER:
String Constructor and Character Extraction in Java

Introduction

In Java, String is an immutable sequence of characters. The String class provides


various constructors for creating string objects and methods to extract characters
from a string.

String Constructors

Java provides multiple constructors to create String objects in different ways.


CO1-U (16)
1. Default Constructor

Syntax:

String str = new String();

Creates an empty string ("").

2. String from Another String

Syntax:

String str = new String("Hello");


Initializes a String with the provided value.

3. String from Character Array

Syntax:

char[] chars = {'J', 'a', 'v', 'a'};


String str = new String(chars);

Converts a character array into a string.

4. String from Byte Array

Syntax:

byte[] bytes = {65, 66, 67};


String str = new String(bytes);

Converts a byte array into a string ("ABC").

5. String from Substring of Character Array

Syntax:

char[] chars = {'H', 'e', 'l', 'l', 'o'};


String str = new String(chars, 1, 3);

Extracts a substring ("ell") from an array.

Example Program for String Constructors

public class StringConstructorDemo {


public static void main(String[] args) {
String str1 = new String();
String str2 = new String("Hello");
char[] chars = {'J', 'a', 'v', 'a'};
String str3 = new String(chars);
byte[] bytes = {65, 66, 67};
String str4 = new String(bytes);

System.out.println("Default: " + str1);


System.out.println("From String: " + str2);
System.out.println("From Char Array: " + str3);
System.out.println("From Byte Array: " + str4);
}
}

Character Extraction in String

Java provides several methods to extract characters from a String.

1. charAt(int index)

Returns the character at a specified index.

Syntax:

char ch = str.charAt(2);

2. getChars(int srcBegin, int srcEnd, char[] dest, int destBegin)

Copies a substring into a character array.

Syntax:

str.getChars(0, 4, destArray, 0);

3. toCharArray()

Converts the entire string into a character array.

Syntax:

char[] chars = str.toCharArray();

Example Program for Character Extraction

public class CharacterExtractionDemo {


public static void main(String[] args) {
String str = "Programming";

// 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.

3 Complete the moveSpecialCharacters() method given in the Tester class.


Method Description
moveSpecialCharacters(String str)

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) {

StringBuilder alphanumeric = new StringBuilder();


StringBuilder specialChars = new StringBuilder();

for (char ch : str.toCharArray()) {

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<>();

for (char ch : str.toCharArray()) {


charFrequencyMap.put(ch, charFrequencyMap.getOrDefault(ch, 0) + 1);
}
// Find the maximum frequency
int maxCount = 0;
for (int count : charFrequencyMap.values()) {
if (count > maxCount) {
maxCount = count;
}
}
// Return the maximum count
return maxCount;
}
public static void main(String args[]) {
String str = "success";
System.out.println("Count of the highest occurring character: "
+HighestOccuredCharCount(str));
String str = "associated";
System.out.println("Count of the highest occurring character: "
+HighestOccuredCharCount(str));

}
}

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:

public class StringModifier {


public static String removeDuplicatesAndSpaces(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
}
if (ch != ' ' && result.indexOf(ch) == -1) {
result += ch; // Add the character to the result
}
}
return result;

public static void main(String[] args) {


// Test cases
String test1 = "hello world";
String test2 = "java programming";

System.out.println("Original: \"" + test1 + "\" | Modified: \"" +


removeDuplicatesAndSpaces(test1) + "\"");
System.out.println("Original: \"" + test2 + "\" | Modified: \"" +
removeDuplicatesAndSpaces(test2) + "\"");

OUTPUT:
Original: "hello world" | Modified: "helowrd"
Original: "java programming" | Modified: "javprogmin

6. Develop the java code for the following method description:


Method description
checkpalindrome(String str)
• Check whether the string passed to the method is palindrome or not
• Return true if the string is palindrome or not
Test the functionalities using main() method of the tester class

CO2-
(16)
Apply

PROGRAM:
public class PalindromeChecker {
public static boolean checkPalindrome(String str)
{ str = str.toLowerCase();
int left = 0, right = str.length() - 1;

while (left < right) {


if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}

public static void main(String[] args) {


// Test cases
System.out.println(checkPalindrome("radar")); // True
System.out.println(checkPalindrome("Apple")); // False
System.out.println(checkPalindrome("level")); // True
System.out.println(checkPalindrome("hello")); // False
}

OUTPUT:

True
False
True
False

7.
Outline on string Buffer constructors with necessary syntax and example
program

ANSWER:
StringBuffer Constructors in Java

In Java, StringBuffer is a class used to create mutable (modifiable) strings.

Unlike String, which is immutable, StringBuffer allows modification of strings


without creating new objects.
CO1-U (16)
This makes it efficient for scenarios where frequent string manipulations are
required.

Java provides multiple constructors to initialize a StringBuffer object in different


ways.

Types of StringBuffer Constructors

Java offers four types of StringBuffer constructors:

1. Default Constructor (StringBuffer())


Syntax:

StringBuffer sb = new StringBuffer();

This constructor creates an empty StringBuffer object with an initial capacity of 16


characters.

If the buffer exceeds this capacity, it expands dynamically.

Example:

public class StringBufferDemo {


public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
System.out.println("Capacity: " + sb.capacity()); // Output: 16
}
}

2. String Argument Constructor (StringBuffer(String str))

Syntax:

StringBuffer sb = new StringBuffer("Hello");

This constructor initializes a StringBuffer with a given string.

The initial capacity is length of the string + 16.

Example:

public class StringBufferDemo {


public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
System.out.println("Content: " + sb); // Output: Java
System.out.println("Capacity: " + sb.capacity()); // Output: 20 (4+16)
}
}

3. Capacity Argument Constructor (StringBuffer(int capacity))

Syntax:

StringBuffer sb = new StringBuffer(50);

This constructor creates an empty StringBuffer with a specified initial capacity.


If the buffer exceeds this capacity, it increases automatically.

Example:

public class StringBufferDemo {


public static void main(String[] args) {
StringBuffer sb = new StringBuffer(30);
System.out.println("Capacity: " + sb.capacity()); // Output: 30
}
}

4. CharSequence Argument Constructor (StringBuffer(CharSequence cs))

Syntax:

StringBuffer sb = new StringBuffer(new StringBuilder("Hello"));

This constructor initializes a StringBuffer using a CharSequence such as StringBuilder


or String.

Example:

public class StringBufferDemo {


public static void main(String[] args) {
StringBuilder sbuilder = new StringBuilder("Java Programming");
StringBuffer sb = new StringBuffer(sbuilder);
System.out.println("Content: " + sb); // Output: Java Programming
}
}

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

(ii)Develop a java program to remove duplicate from an integer array .Replace


the place of duplicate integer with “0”
{
{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} }

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;
}

char[] arr1 = str1.toCharArray();


char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);

return Arrays.equals(arr1, arr2);


}

public static void main(String[] args) {


System.out.println(isAnagram("listen", "silent")); // True
System.out.println(isAnagram("hello", "world")); // False
}
}

OUTPUT:
True
False

(ii)Develop a java program to check whether the given string is palindrome or


not

PROGRAM:

public class PalindromeChecker {


public static boolean isPalindrome(String str) {
str = str.replaceAll("\\s", "").toLowerCase();
int left = 0, right = str.length() - 1;

while (left < right) {


if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}

public static void main(String[] args) {


System.out.println(isPalindrome("radar")); // True
System.out.println(isPalindrome("hello")); // False
}
}
OUTPUT:
True
false

You might also like