0% found this document useful (0 votes)
42 views62 pages

Java Programming Exercises and Solutions

The document contains multiple Java programming tasks, including class and method definitions for various applications such as calculating areas, managing employee details, and implementing singleton patterns. Each task provides code snippets with comments guiding the completion of functions and classes to meet specified requirements. The document is structured into weeks with different programming assignments focusing on object-oriented principles and Java syntax.

Uploaded by

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

Java Programming Exercises and Solutions

The document contains multiple Java programming tasks, including class and method definitions for various applications such as calculating areas, managing employee details, and implementing singleton patterns. Each task provides code snippets with comments guiding the completion of functions and classes to meet specified requirements. The document is structured into weeks with different programming assignments focusing on object-oriented principles and Java syntax.

Uploaded by

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

Week 2

Ppa1

Consider the program given below. Complete the program according


to the instructions provided in the comments such that the program
satisfies the given test cases.

import [Link].*;

class Rectangle{

int w; //width

int h; //height

//LINE-1: write the function setw(int) to initialize w

public void setw(int a)

w=a;

//LINE-2: write the function seth(int) to initialize h

public void seth(int b)

h=b;

//LINE-3: write the function area() to return area of rectangle

public int area()

int a=w*h;

return(a);

public class FClass{


public static void main(String[] args) {

Scanner sc= new Scanner([Link]);

int w = [Link]([Link]());

int h = [Link]([Link]());

Rectangle r = new Rectangle();

[Link](w);

[Link](h);

int area = [Link]();

[Link](area);

Ppa2

import [Link].*;

class FClass {

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

String s1 = [Link]();

evenDisplay(s1);

//Define evenDisplay(String) method here

public static void evenDisplay(String s)

int l=[Link]();

for(int i=0;i<l;i+=2)

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

}
Grpa1

Write a program to find the sum of the following series up to n terms.


12 + ( 12 + 22 ) + ( 12 + 22 + 32 ) + ......... + ( 12 + 22 + .... + n2 )

import [Link].*;

public class SeriesSum {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link]();

//Fill your code here

int sum=0;

for(int i=1;i<=n;i++)

for(int j=1;j<=i;j++)

sum+=[Link](j,2);

[Link](sum);

Grpa2

Complete the definition of the given class by defining appropriate


constructors and member functions such that it is in coherence with
the given main method and produce the required output.
import [Link];
class Employee{

String ename;

String eid;

String edept;

public Employee(){

ename = "guest";

//Define the required methods

public Employee(String name, String id, String dept) {

[Link] = name;

[Link] = id;

[Link] = dept;

public void copyDept(Employee e) {

[Link] = [Link];

public void displayDetails() {

[Link]("ename : " + ename);

[Link]("eid : " + eid);

[Link]("edept : "+ edept);

public class FClass

public static void main(String args[])

Scanner s = new Scanner([Link]);

Employee e1 = new Employee();


//Enter name of the employee

String name = [Link]();

//Enter id of the employee

String id = [Link]();

//Enter department of the employee

String dept = [Link]();

Employee e2 = new Employee(name,id,dept);

[Link](e2);

//Copies the department name of e2 into e1's department name.

[Link]();

Grpa3

Complete the definition of the given class by defining appropriate


constructors and member functions such that it is in coherence with
the given main method and produce the required output

import [Link].*;

class Employee

String eid;

String ename;

String eprojects[];
//Define all the required methods here

public Employee(String id, String name, String[] project) {

[Link] = id;

[Link] = name;

[Link] = project;

public Employee(Employee e) {

[Link] = [Link];

[Link] = [Link];

[Link] = [Link];

public void display() {

[Link]("id:" + eid);

[Link]("name:" + ename);

[Link]("projects:");

eprojects[0] = "P001";

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

[Link](eprojects[i] + ":");

public void mutator()

[Link] = "Mr "+ [Link];

[Link][0] = null;

public class FClass

{
public static void main(String[] args)

Scanner s = new Scanner([Link]);

String project[] = {"P001","P002","P003"};

//Enter the id of employee

String id = [Link]();

//Enter the name of employee

String name = [Link]();

Employee e1 = new Employee(id,name,project);

Employee e2 = new Employee(e1);

//The copy constructor must copy all the data members.

[Link]();

[Link]();

Week3

Ppa1

Write a class named Calculator that has the following methods:


• sum(double a, double b) that prints the value of a + b
• subtraction(double a, double b) that prints the value of a - b
• multiply(double a, double b) that prints the value of a * b
• division(double a, double b) that prints the value of a / b
Write another class named UpdatedCalculator that inherits all the
methods of Calculator and also has the following method:
• remainder(double a, double b) that prints the value of a % b
import [Link].*;

class Calculator{

// Fill the code

public void sum(double a,double b)

[Link](a+b);

public void subtraction(double a,double b)

[Link](a-b);

public void multiply(double a,double b)

[Link](a*b);

public void division(double a,double b)

[Link](a/b);

class UpdatedCalculator extends Calculator{

// Fill the code

public void remainder(double a,double b)

[Link](a%b);

public class CalculatorCheck{

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);


double n1 = [Link]();

double n2 = [Link]();

Calculator c = new Calculator();

[Link](n1, n2);

[Link](n1, n2);

[Link](n1, n2);

[Link](n1, n2);

UpdatedCalculator uc = new UpdatedCalculator();

[Link](n1, n2);

Ppa2

Consider the following Java program.


Implement the code as instructed in the comment, such that it
satisfies the given test cases and is in coherence with the
given main function.

import [Link].*;

class Point{

private int x, y;

// implement the constructor and

// override the toString() and equals() methods

public Point(int x1, int y1){

this.x = x1;

this.y = y1;

public String toString(){


return "(" + this.x + ", " + this.y + ")";

// override the toString() and equals() methods

public Boolean equals(Point p){

if(p.x == this.x && p.y == this.y){

return true;

}else{

return false;

class FClass{

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int x1 = [Link]();

int y1 = [Link]();

int x2 = [Link]();

int y2 = [Link]();

Point p1 = new Point(x1, y1);

Point p2 = new Point(x2, y2);

if([Link](p2))

[Link](p1 + "==" + p2);

else

[Link](p1 + "!=" + p2);

}
Grpa1

import [Link].*;

class Person{

private String name;

private long aadharno;

public Person(String name, long aadharno){

[Link] = name;

[Link] = aadharno;

public void print() {

[Link]("name : " + name);

[Link]("aadharno : " + aadharno);

class Employee extends Person{

private double salary;

//implement the constructor

public Employee(String name,long aadharno,double sal)

super(name,aadharno);

[Link]=sal;

//override print method

public void print()

[Link]();

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

class ContactEmployee extends Employee{

final private static double hourlyPay = 100.00;

private int contactHour;

double salary;

//implement the constructor

public ContactEmployee(String name,long aadharno,int contactHour)

super(name,aadharno,contactHour*hourlyPay);

[Link]=contactHour;

//salary is computed as contactHour * hourlyPay

public void print(){

[Link]();

class FClass{

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

String nm1 = [Link]();

String nm2 = [Link]();

long adh1 = [Link]();

long adh2 = [Link]();

double sal = [Link]();

int cont = [Link]();


Employee[] eArr = new Employee[2];

eArr[0] = new Employee(nm1, adh1, sal);

eArr[1] = new ContactEmployee(nm2, adh2, cont);

for(Employee e : eArr)

[Link]();

Grpa2

import [Link].*;

class Shape{

public int area() {

return 0;

public int volume() {

return 0;

class Rectangle extends Shape{

private int w, h;

//implement Rectangle class

public Rectangle(int w,int h)

this.w=w;

this.h=h;

public int area()

return(w*h);

}
}

class Cube extends Shape{

private int a;

//implement Cube class

public Cube(int a)

this.a=a;

public int volume()

return(a*a*a);

class FClass{

private static void caller(Shape s) {

if(s instanceof Rectangle) {

//check if s is of type Rectangle

[Link]([Link]());

else if(s instanceof Cube) {

//check if s is of type Cube

[Link]([Link]());

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int w = [Link]();
int h = [Link]();

int a = [Link]();

caller(new Rectangle(w, h));

caller(new Cube(a));

Grpa3

Create BankAccount class that has the following instance variables


and methods:
Instance variables:
• accountNumber
• name
• balance
• final variable: minBalance
Private method:
checkMinBalance(amount) - returns false if balance -
amount <= minBalance else returns true

Public methods:

balance( ) - prints the balance


deposit(amount) - updates balance = balance + amount
withdraw(amount) - calls the checkMinBalance(amount) method,
if it returns true update balance = balance -
amount else prints Transaction failed

import [Link].*;

class BankAccount{

int accountNumber;

String name;
int balance;

final int minBalance = 100;

private boolean checkMinBalance(int amount){

if(balance - amount <= minBalance){

return false;

else{

return true;

//Fill the code here

public BankAccount(int accno,String name,int bal)

[Link]=accno;

[Link]=name;

[Link]=bal;

public void balance()

[Link](balance);

public void deposit(int amount)

balance=balance+amount;

public void withdraw(int amt)

if(checkMinBalance(amt))

balance=balance-amt;

}
else

[Link]("Transaction failed");

class AccountCheck{

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int amnt = [Link]( );

int amnt1 = [Link]( );

BankAccount b = new BankAccount(1890, "rahul", 1000);

[Link](amnt);

[Link]();

[Link](amnt1);

[Link]();

Week4

Ppa1

import [Link].*;

interface Searchable{

public int search(int start_index, Object key);

class Char{

private char c;

public Char(char c_) {

c = c_;
}

public boolean equals(Object d) {

//implement equals() for Char

Char ch = (Char) d;

if (c == ch.c ){

return true;

}else {

return false;

class CharArray implements Searchable{

private Char[] carr;

public CharArray(Char[] carr_){

carr = carr_;

public int search(int start_index, Object key) {

//search the key in array carr from the index start_index

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

if (carr[i].equals(key)){

return i;

return -1;

//if the key found, return index of the first occurrence of the key

//else return -1

}
class FrequencyCounter{

public static int getFrequency(Searchable ob, Object key){

int i=0;

if (ob instanceof CharArray) {

//count occurrences of the key in ob using search function

int count = 0 , j = 0;

j = [Link](i, key);

while (j > -1){

if ( j != -1){

count += 1;

j = [Link](j+1 ,key);

return count;

else

return 0;

class FClass{

public static void main(String[] args) {

String str;

char c;

Scanner sc = new Scanner([Link]);

str = [Link]();

c = [Link]().charAt(0);

Char key = new Char(c);

Char[] cA = new Char[[Link]()];

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

cA[i] = new Char([Link](i));


}

CharArray caObj = new CharArray(cA);

[Link]([Link](caObj, key));

Ppa2

Both the Voter and EVM classes must be created in such a way that
they enforce the existence of only a single instance at a time. Each
Voter object must be mapped with a unique EVM object and vice
versa. A Voter must be allocated an EVM and then the voting process
should start, once voting is completed that particular EVM should be
freed and the next voter should be called.
Again a new EVM must be allocated to the next voter like previously
and the process continues till all the voters cast their votes.

import [Link];

class Voter{

// Define appropriate variables for implementing singleton behaviour

// in accordance with the given coded parts and sample output

static Voter new_voter;

static int total_no_of_voters;

static int current_voter_count;

private Voter() {

// [Link]("1 Inside firstvoter " + "EVm no " + EVM.evm_count +

// " voterno " + Voter.current_voter_count);

current_voter_count++;
}

public static Voter getVoter() {

//implement singleton behaviour

// [Link]("2 Inside firstvoter " + "EVm no " + EVM.evm_count +

// "voterno " + Voter.current_voter_count + new_voter);

if(new_voter == null){

new_voter = new Voter();

return new_voter;

}return null;

public void firstVoter(){

// [Link]("3 Inside firstvoter " + "EVm no " + EVM.evm_count +

// "voterno " + Voter.current_voter_count );

if(new_voter != null) {

EVM new_machine = [Link](new_voter);

new_machine.startVoting();

public void callNewVoter() {

// Write code to setup a new EVM object for the new voter

// [Link]("4 Inside firstvoter " + "EVm no " + EVM.evm_count +

// "voterno " + Voter.current_voter_count);

if(Voter.current_voter_count < Voter.total_no_of_voters){

Voter v = [Link]();

EVM evm = [Link](v);

//Ignore the following 6 lines of code


//but do not delete this code in your submission

//========================================================================

try {

EVM x = [Link](null);

[Link]();

}catch(NullPointerException e) {

[Link]("EVM is Singleton");

//========================================================================

// Resume writing your code here

[Link]();

} // Hint: Write code to start voting for the new user on the new EVM

class EVM{

// Define appropriate variables for implementing singleton behaviour

// in accordance with the given coded parts and sample output

static Voter current_voter;

static EVM new_evm;

static int evm_count;

private EVM(Voter v) {

// [Link]("a Inside firstvoter " + "EVm no " + EVM.evm_count +

// "voterno " + Voter.current_voter_count);

current_voter = v;

evm_count++;

public static EVM getEVM(Voter v) {

// Implement singleton behaviour


// [Link]("b Inside firstvoter " + "EVm no " + EVM.evm_count +

// "voterno " + Voter.current_voter_count);

if (new_evm == null){

new_evm = new EVM(v);

return new_evm;

return null;

public void startVoting() {

// Complete voting for the current voter and call the next voter

// Hint : Use callback here

// [Link]("c Inside firstvoter " + "EVm no " + EVM.evm_count +

// "voterno " + Voter.current_voter_count);

[Link]("voting under process on EVM number "+EVM.evm_count);

[Link]("Voting completed for voter "+Voter.current_voter_count);

Voter.new_voter = null;

EVM.new_evm = null;

EVM.current_voter.callNewVoter();

public class Election{

public static void main(String args[]) {

Scanner s = new Scanner([Link]);

Voter.total_no_of_voters = [Link]();

// Assume input is always non zero

Voter v = [Link]();
//Trying to create another voter when one voter is in the middle of

//voting process, students can ignore this try-catch block of code

try {

Voter x = [Link]();

[Link]();

} catch(NullPointerException e) {

[Link]("Voter is Singleton");

//Starting the first vote of the day

[Link]();

Grpa1

Create an abstract class StringOperations that has the following


abstract methods:
• String reverse(String s)
• int vowelCount(String s)

Create StringReverse class that extends StringOperations class but


defines only String reverse(String s) method. It reverses the string
which is passed as parameter and returns the reversed string.
Create UpdatedStrings class that extends StringReverse class and
defines int vowelCount(String s) method. It counts the vowels in the
string which is passed as parameter and returns the count.

import [Link].*;

abstract class StringOperations{


public abstract String reverse(String s);

public abstract int vowelCount(String s);

//Fill the code here

abstract class StringReverse extends StringOperations{

public String reverse(String s){

String S = "";

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

S = [Link](i) + S;

return (S);

class UpdatedStrings extends StringReverse{

public int vowelCount(String s){

int count = 0;

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

if ([Link](j) == 'a' || [Link](j) == 'e' || [Link](j) == 'i' || [Link](j) == 'o' || [Link](j) ==


'u'){

count += 1;

return count;

class Example {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

String s = [Link]();

UpdatedStrings str = new UpdatedStrings();


[Link]("Reverse of "+ s + " is "+ [Link](s));

[Link]("Vowel count of "+ s + " is "+ [Link](s));

Grpa2

import [Link].*;

interface Iterator{

public boolean has_next();

public Object get_next();

class Sequence{

private final int maxLimit = 80;

private SeqIterator _iter = null;

int[] iArr;

int size;

//implement the parameterized constructor to initialize size

int p=0;

int iter=0;

public Sequence(int s){

size=s;

[Link]=new int[s];

//implement addTo(elem) to add an int elem to the sequence

public void addTo(int n){

[Link][this.p]=n;

this.p++;

}
//implement get_Iterator() to return Iterator object

public Iterator get_Iterator(){

return new SeqIterator();

private class SeqIterator implements Iterator{

int indx;

public SeqIterator(){

indx = -1;

//implement has_next()

public boolean has_next() {

if (iter<size){

return true;

}else{

return false;}

//implement get_next()

public Object get_next() {

int r_val=iArr[iter];

iter++;

return r_val;

class FClass{

public static void main(String[] args) {

Sequence sObj = new Sequence(5);

Scanner sc = new Scanner([Link]);

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

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

Iterator i = sObj.get_Iterator();

while(i.has_next())

[Link](i.get_next() + ", ");

Week 5

Ppa1

Given a class name as input, complete the Java code to print the
count of public and declared methods, fields and constructors in the
class. For each method in class ClassStats below, fill in the
missing code as described in the comments. Each method takes the
class name as input.

import [Link].*;

import [Link].*;

class ClassStats{

public static int getPubMethodCount(String cname) {

try {

//add code to return the count of

//public methods in the given class

Class c = [Link](cname);

Method[] m = [Link]();

return [Link];

}catch(Exception e) { return -1; }

public static int getAllMethodCount(String cname) {

try {
//add code to return the count of all

//declared methods in the given class

Class c = [Link](cname);

Method[] meth = [Link]();

return [Link];

}catch(Exception e) { return -1; }

public static int getPubFieldCount(String cname) {

try {

//add code to return the count of

//public fields (instance variables) in the given class

Class c = [Link](cname);

Field[] f = [Link]();

return [Link];

}catch(Exception e) { return -1; }

public static int getAllFieldCount(String cname) {

try {

//add code to return the count of

//all fields (instance variables) in the given class

Class c = [Link](cname);

Field[] fil = [Link]();

return [Link];

}catch(Exception e) { return -1; }

public static int getPubContCount(String cname) {

try {

//add code to return the count of

//public constructors in the given class

Class c = [Link](cname);

Constructor[] co = [Link]();
return [Link];

}catch(Exception e) { return -1; }

public static int getAllContCount(String cname) {

try {

//add code to return the count of

//all constructors in the given class

Class c = [Link](cname);

Constructor[] con = [Link]();

return [Link];

}catch(Exception e) { return -1; }

class FClass{

public static void main(String[] args) {

String cname;

Scanner sc = new Scanner([Link]);

cname = [Link]();

[Link]("Constructor: " +

[Link](cname) + ", " +

[Link](cname));

[Link]("Fields: " +

[Link](cname) + ", " +

[Link](cname));

[Link]("Methods: " +

[Link](cname) + ", " +

[Link](cname));

}
Ppa2

Complete the Java code given below that takes as input a string array,
where each string is assured to be either an integer or a double in
string format. Your code must segregate the two types - integer and
double - and print the double values followed by the integer values.
For this, your code must iterate through the input array, and add each
element to the appropriate array based on its type.

import [Link];

class ConvertArrays{

public Double doubleArr[]=new Double[3];

public Integer intArr[]=new Integer[3];

public int x=0,y=0,z=0;

public void convert(String[] arr){

//loop through the arr and store each element

//in the appropriate array

for (String elem : arr){

if ([Link](".") ){

doubleArr[x] = [Link](elem);

x++;

else {

intArr[y] = [Link](elem);

y++;

public <T> void display(T[] arr){

for(T elements:arr)
[Link](elements+" ");

[Link]();

public class Programming {

public static void main(String[] args) {

Scanner scanner=new Scanner([Link]);

String arr[]= new String[6];

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

arr[i]=[Link]();

ConvertArrays conArrays=new ConvertArrays();

[Link](arr);

[Link]("===After conversion Arrays===");

[Link]([Link]);

[Link]([Link]);

Grpa1
Given as input two integers n_1,n_2 and two double
values d_1,d_2 complete the Java code to form two complex
numbers c_1 and c_2, as described below, and print their sum.

• The real parts of c_1 and c_2 are n_1 and d_1 respectively,
whereas their imaginary parts are n_2 and d_2, respectively.
• Define a generic class ComplexNum with the following
members.
o Instance variables r and i

o A constructor to initialize r and i

o A method add()to return the sum of the two instances

of generic type ComplexNum


o A method that overrides the toString() method in

the Object class so that the format of the output is


in accordance with those in the test cases.

import [Link].*;

//Add your code for ComplexNum here

class ComplexNum<T extends Number> {

public Number real;

public Number imag;

public ComplexNum(Number real, Number imag) {

[Link] = real;

[Link] = imag;

public <T extends Number> ComplexNum<T> add(ComplexNum<T> c) {

return new ComplexNum<>([Link]() + [Link](),


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

}
public String toString() {

return [Link]() + " + " + [Link]() + "i";

class FClass{

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n1, n2;

double d1, d2;

n1 = [Link]();

n2 = [Link]();

d1 = [Link]();

d2 = [Link]();

ComplexNum<Integer> c1 = new ComplexNum<Integer>(n1, n2);

ComplexNum<Double> c2 = new ComplexNum<Double>(d1, d2);

ComplexNum<Double> c3 = [Link](c2);

[Link](c1 + " + " + c2 + " = " + c3);

Grpa2
Write a Java code that takes as input a positive number (length of an
array here), and two arrays of that length - one of integers and
another of strings. The code must also take an integer and a String as
input, and print the number of occurrences of the integer and the
string in the integer array and the string array, respectively.

Format of input:
Length of the arrays
Elements in the integer array (in separate lines)
Element to count in the integer array
Elements in the string array (in separate lines)
Element to count in the string array

Variables used in the code:


len - represents length of array
s1 - represents an element to be counted for in Integer array
s2 - represents an element to be counted for in String array

import [Link].*;

class ArrayExample <T>{

T[] a;

// Define constructor(s) as needed

public ArrayExample(T[] a) {

this.a = a;

// Define method display() that print the elements of array a

public void display() {

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

[Link](a[i] + " ");

[Link]();
}

// Define method elementCount(T x) that

// counts the no. of times x is present in the array a

public int elementCount(T x) {

int count = 0;

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

if (a[i].equals(x)) {

count++;

return count;

public class ArrayObject{

public static void main(String[] args){

Scanner sc = new Scanner([Link]);

int len = [Link](); //Taking input for length of the array

Integer[] x = new Integer[len];

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

x[i] = [Link](); //Taking input for Integer array

//Write the code here to create an object obj for Integer array

ArrayExample<Integer> obj = new ArrayExample<Integer>(x);

int s1 = [Link](); //Taking input for the value to be counted

String[] y = new String[len];

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

y[i] = [Link](); //Taking input for String array

}
//Write the code here to create an object obj1 for String array

ArrayExample<String> obj1 = new ArrayExample<String>(y);

String s2 = [Link](); //Taking input for the value to be counted

[Link]();

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

[Link]();

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

Week6

Grpa1
Given as input a set of four objects of
class CricketPlayer complete the Java code to segregate the
players represented by these objects into batsmen and bowlers.

• Create an ArrayList object to store the four objects


of CricketPlayer. Segregate them as batsmen and
bowlers based on the following criteria:
o A player is termed as a batsman if his/her average runs per

match are greater than 25.


o A player is termed as a bowler if his/her average wickets

per match are greater than 1.


• Create ArrayList bt to store the batsmen
and ArrayList bw to store the bowlers. Observe that the
same player could belong to both the lists.
• Print the list of bowlers in a line, followed by the list of batsmen
in the next line, using
the displayPlayers(ArrayList<CricketPlayer>
bw, ArrayList<CricketPlayer> bt) method.

import [Link].*;

class CricketPlayer{

private String name;

private int wickets;

private int runs;

private int matches;

public CricketPlayer(String s, int w, int r, int m){

[Link] = s;

[Link] = w;

[Link] = r;

[Link] = m;
}

public String getName(){

return name;

public int getWickets(){

return wickets;

public int getRuns(){

return runs;

public double avgRuns(){

return runs/matches;

public double avgWickets(){

return wickets/matches;

public class Main {

// Define displayPlayers() method here

// Define displayPlayers() method here

public static void displayPlayers(ArrayList<CricketPlayer> bw, ArrayList<CricketPlayer> bt)

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

[Link]([Link](i).getName() + " ");

[Link]("");

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

[Link]([Link](i).getName() + " ");

}
}

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

CricketPlayer p1 = new CricketPlayer([Link](), [Link](),

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

CricketPlayer p2 = new CricketPlayer([Link](), [Link](),

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

CricketPlayer p3 = new CricketPlayer([Link](), [Link](),

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

CricketPlayer p4 = new CricketPlayer([Link](), [Link](),

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

// Define ArrayList objects here

// Batsman ArrayList

ArrayList<CricketPlayer> bt = new ArrayList<CricketPlayer>();

// Bowler ArrayList

ArrayList<CricketPlayer> bw = new ArrayList<CricketPlayer>();

// All Players ArrayList

CricketPlayer[] all = {p1, p2, p3, p4};

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

if(all[i].avgRuns() > 25){

[Link](all[i]);
}

if(all[i].avgWickets() > 1){

[Link](all[i]);

displayPlayers(bw, bt);

Grpa2

Write a program that checks for balanced parentheses in an


expression i.e. whether the pairs and the order of "{ ", " } ”, " ( ", " ) ”,
" [ ", " ] ” are correct in the given input.
The program should keep taking expressions as input one after the
other, until the user enters the word `done' (not case-sensitive). After
all the expressions are input, for each input, the program should print
whether the given expression is balanced or not (the order of the
output should match the order of the input). If an input expression is
balanced, print Balanced else print Not Balanced

import [Link].*;

public class Test3{

public static boolean balanceCheck(String sequence) {

//Write your code here


Stack<Character> brackets = new Stack<Character>();

char[] left = { '{', '(', '[' };

char[] right = { '}', ')', ']' };

HashMap<Character, Character> map = new HashMap<>();

[Link]('(', ')');

[Link]('[', ']');

[Link]('{', '}');

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

char x = [Link](i);

boolean leftContains = false;

boolean rightContains = false;

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

if(left[j] == x){

leftContains = true;

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

if(right[j] == x){

rightContains = true;

}
if (leftContains) {

[Link](x);

} else if (rightContains) {

if([Link]()){

// [Link]("Not balanced");

return false;

char y = [Link]();

if ([Link](y) != x) {

// [Link]("Not balanced");

return false;

// [Link]("Balanced");

if([Link]())

return true;

return false;

public static void main(String args[]) {

Scanner s = new Scanner([Link]);

ArrayList<String> expr_arr= new ArrayList<String>();

String inp=null;

do {
inp = [Link]();

if(![Link]("Done"))

expr_arr.add(inp);

}while(![Link]("Done"));

for(String expr : expr_arr) {

if(balanceCheck(expr)) {

[Link]("Balanced");

else {

[Link]("Not Balanced");

Live coding question

Wk2

Q1
import [Link].*;

class Student {

private String name;

private double marks [];

public Student(String name, double[] marks) {

[Link] = name;

[Link] = marks;

public String getName() {

return ([Link]);

public double findTotal() {

double total = 0.0;

for (double i : [Link]) {

total = total + i;

return (total);

public class Test {

public static String getMax(Student[] student) {

double max_marks = 0.0;

String max_student = "";

for (Student i : student) {

double total_marks = [Link]();

if (total_marks > max_marks) {

max_student = [Link]();

max_marks = total_marks;
}

return max_student;

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

Student[] arr = new Student[3];

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

String name = [Link]();

double[] m = {[Link](), [Link](), [Link]()};

arr[i] = new Student(name, m);

[Link](getMax(arr));

Q2
import [Link].*;

class Employee{

String name;

String[] projects;

public Employee(String n, String[] proj){

name = n;

projects = proj;

public Employee(Employee e){

[Link] = [Link];

int l = [Link];

[Link] = new String[l];

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

[Link][i] = [Link][i];

public void setName(String n) {

name = n;

public void setProject(int index, String proj) {

projects[index] = proj;

public String getName() {

return name;

public String getProject(int indx) {

return projects[indx];

public class Test {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

String[] proj = {"PJ1", "PJ2", "PJ3"};

Employee e1 = new Employee("Surya", proj);

Employee e2 = new Employee(e1);

[Link]([Link]());

[Link](0, [Link]());

[Link]([Link]() + ": " + [Link](0));

[Link]([Link]() + ": " + [Link](0));

Wk3

Q1
import [Link];

class Faculty{

private String name;

private double salary;

public Faculty(String name, double salary) {

[Link] = name;

[Link] = salary;

public double bonus(float percent){

return (percent/100.0)*salary;

public String getDetails() {

return name + ", " + salary;

public String getDetails(float percent ) {

return getDetails()+ ", bonus = "+bonus(percent);

class Hod extends Faculty{

private String personalAssistant;

public Hod(String name, double salary, String pa) {

super(name, salary);

[Link] = pa;

public double bonus(float percent){

return 0.5*[Link](percent);

public String getDetails() {

return [Link]()+", "+ personalAssistant;

public String getDetails(float percent ) {


return getDetails()+", "+bonus(percent);

public class InheritanceTest{

public static void main(String[] args) {

Scanner sc=new Scanner([Link]);

Faculty obj1 = new Faculty([Link](), [Link]());

Faculty obj2 = new Hod([Link](), [Link](), [Link]());

[Link]([Link]());

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

[Link]([Link]());

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

Wk4

Q1
import [Link].*;

abstract class UPIPayment{

abstract void payment();

abstract void rewards();

class PhonePay extends UPIPayment{

private int amount;

public PhonePay(int amount) {

[Link] = amount;

public void payment() {

[Link]("Phone pay:Payment success:");

rewards();

public void rewards() {

if(amount < 500)

[Link]("Sorry no rewards");

else if(amount >= 500)

[Link]("10 off on next mobile rc");

class Paytm extends UPIPayment{

private int amount;

public Paytm(int amount) {

[Link] = amount;

public void payment() {

[Link]("Paytm:Payment success:");

rewards();

public void rewards() {


if(amount < 500)

[Link]("Sorry no rewards");

else if(amount >= 500)

[Link]("10 off on next DTH rc");

class UPIUser{

public void transferAndGetRewards(UPIPayment obj) {

[Link]();

public class AbstractTest {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int a1 = [Link]();

int a2 = [Link]();

UPIUser u = new UPIUser();

[Link](new PhonePay(a1));

[Link](new Paytm(a2));

}
Q2

import [Link].*;

interface Appraisable{

default void appraisal(Teacher t){

[Link]([Link]()+([Link]()/100)*5000);

public abstract void checkAndUpdateSalary();

interface SpecialAppraisable extends Appraisable{


default void spAppraisal(Teacher t){

[Link]([Link]()+([Link]()/100)*10000);

class Teacher implements SpecialAppraisable{

private String name;

private double salary;

private double stuPassPer;

public Teacher(String name, double salary, double stuPassPer) {

[Link] = name;

[Link] = salary;

[Link] = stuPassPer;

public double getSalary() {

return salary;

public void setSalary(double salary) {

[Link] = salary;

public double getstuPassPer() {

return stuPassPer;

public String toString() {

return name + ", " + salary + ", " + stuPassPer;

public void checkAndUpdateSalary() {

if(stuPassPer >= 60 && stuPassPer < 75)

appraisal(this);

else if(stuPassPer >= 75 && stuPassPer <= 100)

spAppraisal(this);

}
}

public class InterfaceTest {

public static void printUpdatedTeachList(Teacher[] tList) {

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

tList[i].checkAndUpdateSalary();

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

[Link](tList[i]);

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

Teacher tArr[] = new Teacher[3];

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

tArr[i] = new Teacher([Link](), [Link](), [Link]());

[Link](tArr);

}
Q3

import [Link];

interface Generatable{

abstract void feeGenerate(Student s);

class Student {
private String name;

private double fee;

private int backlogs;

public Student(String name, int backlogs) {

[Link] = name;

[Link] = backlogs;

public void setFee(double fee) {

[Link] = fee;

public int getBacklogs() {

return backlogs;

public String toString() {

return name + ", " + fee + ", " + backlogs;

class ExamBranch{

private class Regular implements Generatable{

public void feeGenerate(Student s) {

[Link](1500.00);

private class Supple implements Generatable{

public void feeGenerate(Student s) {

if([Link]() == 1)

[Link](1500 + 500);

else if([Link]() == 2)

[Link](1500 + 1000);

else if([Link]() >=3 )

[Link](1500 + 2000);
}

public Generatable getRegularFee() {

return new Regular();

public Generatable getSuppleFee() {

return new Supple();

public class PrivateClassTest {

public static Student[] getStudentsFee(Student sList[]){

ExamBranch obj;

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

if(sList[i].getBacklogs()==0) {

obj=new ExamBranch();

[Link]().feeGenerate(sList[i]);

else {

obj=new ExamBranch();

[Link]().feeGenerate(sList[i]);

return sList;

public static void main(String[] args) {

Scanner sc=new Scanner([Link]);

Student[] sArr = new Student[3];

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

sArr[i] = new Student([Link](), [Link]());

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

[Link](sArr[i]);

Wk5

Q1

import [Link].*;

class Point<T extends Number>{

T x, y;

public Point(T x, T y) {

this.x = x;

this.y = y;

}
public Point<Double> mid(Point<?> p){

Point<Double> pt = new Point<Double>(0.0, 0.0);

pt.x = ([Link]() + [Link]()) / 2;

pt.y = ([Link]() + [Link]()) / 2;

return pt;

public String toString() {

return "(" + x + "," + y + ")";

public class Test{

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

Point<Integer> p1 = new Point<Integer>([Link](), [Link]());

Point<Double> p2 = new Point<Double>([Link](), [Link]());

Point<Double> p3 = [Link](p2);

[Link](p3);

Wk6

Q1
import [Link].*;

class Shop{

private String name;

private int nsold;

public Shop(String s, int ns){

[Link] = s;

[Link] = ns;

public String getName(){

return name;

public int getItemSold(){

return nsold;

}
}

public class MapTest {

public static void printShopName(ArrayList<Shop> sList) {

Map<String, Integer> m = new LinkedHashMap<String, Integer>();

String shop = "";

int sold = 0;

for(Shop s: sList)

[Link]([Link](), [Link]([Link](),0)+[Link]());

for ([Link]<String, Integer> entry : [Link]()){

if([Link]()> sold) {

shop = [Link]();

sold = [Link]();

[Link](shop+" : "+sold);

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

ArrayList<Shop> list = new ArrayList<Shop>();

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

[Link](new Shop([Link](), [Link]()));

printShopName(list);

Common questions

Powered by AI

Encapsulation in the BankAccount class is achieved by keeping instance variables private and providing public methods for interaction, ensuring controlled access. The checkMinBalance private method safeguards data integrity by restricting balance withdrawals that may harm the account's stability, verifying before updating the balance. This design ensures that only well-defined operations affect the account state, maintaining balance integrity through the regulated interface .

Polymorphism through method overriding is implemented in the ContactEmployee and Employee classes. Both classes override the print method inherited from the Person class to provide specific implementations. In ContactEmployee, the print method is overridden to include additional details specifically for this subclass, extending upon the Employee's implementation which already customizes its superclass (Person) method. This permits using a superclass reference to invoke subclass methods, which will execute based on the specific subclass instance being used .

The ComplexNum class showcases the application of Generics by allowing type T to be any Number subclass, offering enhanced type safety and flexibility. Generics enable methods like add to operate over different numeric types without the risk of ClassCastException, thus allowing for efficient handling of various number operations involving both integer and floating-point arithmetic. This generality reduces code duplication while maintaining type integrity across different Number types within the same class framework .

The StringReverse class is an abstract class that implements the reverse method from its superclass, StringOperations. It demonstrates the use of abstract classes by defining a specific method (reverse) and leaving others (vowelCount) abstract for future subclass implementations, such as in UpdatedStrings, which extends StringReverse and provides a concrete implementation for vowelCount. StringReverse's reverse method takes a string and returns its reverse, whereas UpdatedStrings' vowelCount counts vowels within the input string, illustrating method inheritance and specialization in subclasses .

The inheritance hierarchy in the classes Person, Employee, and ContactEmployee demonstrates object-oriented programming principles such as encapsulation, inheritance, and polymorphism. The Person class contains private data fields (encapsulation) for name and aadharno, ensuring data is accessible only through public interfaces. Employee inherits from Person, adding a salary attribute and showcasing inheritance by extending the base class functionality. Furthermore, polymorphism is demonstrated by overriding the print method in Employee and ContactEmployee, allowing each subclass to provide a specific implementation despite sharing a common interface .

The class definitions utilize inheritance by having Rectangle and Cube extend the base class Shape. This establishes a hierarchy where Rectangle and Cube inherit the properties and methods of Shape. Although Shape provides general methods for area and volume, Rectangle overrides the area method to calculate the area of a rectangle (width * height), while Cube overrides the volume method to calculate the volume of a cube (a^3). This demonstrates method overriding, allowing each subclass to provide specific functionality pertinent to its dimensions .

Method overriding is seen in Hod's bonus method which overrides Faculty's bonus by providing a Hod-specific bonus calculation, reflecting polymorphism. Method overloading occurs with getDetails in Faculty, where it has two versions: one with no parameter and another that takes a float argument (percent). Overloading supports multiple method signatures in Faculty while overriding lets Hod specify its bonus calculation, thus demonstrating distinct use cases in inheritance to tailor or expand functionality across subclasses .

Early return strategies in methods like add in the ComplexNum class can improve readability and performance slightly by negating the need for additional condition checks or unnecessary processing after the main operation. The early left-return optimizes resource management by immediately outputting results upon successful conditions, impacting performance positively by minimizing overhead in certain scenarios. However, the performance impact may be marginal unless numerous conditions are nested or computational complexity inflates .

The Iterator design pattern in the Sequence and SeqIterator classes facilitates sequential access to elements without exposing the underlying collection structure. It's implemented by creating a SeqIterator class with methods has_next and get_next. SeqIterator keeps track of its current position, iterates through the Sequence array, and hides the complex iteration logic, encapsulating it within an accessible interface. This promotes flexibility by allowing external traversal mechanisms on Sequence objects .

Private nested classes within ExamBranch, such as Regular and Supple, implement the Generatable interface to encapsulate fee generation logic based on student backlogs. This encapsulation allows these nested classes to focus on specific fee logic while keeping it hidden from the outer world, maintaining clean separation of concerns. The interface ensures that methods like feeGenerate are implemented conforming to the defined contract, thus providing flexibility and encapsulation within ExamBranch, enforcing a strict modular design .

You might also like