0% found this document useful (0 votes)
91 views59 pages

Ctood Assignment2

The document contains instructions for a programming exam with 7 questions. Question 1 asks to write code to convert meters to feet and output the result. Question 2 asks about differences between static and instance members. Question 3 asks to write code to read integers from a file and count even and odd numbers. Question 4 asks to create a Student class with attributes, accessors, mutators and a display method. Question 5 asks to create a BMI class to calculate and output BMI information. Question 6 asks to create a Ticket class to book movie tickets with class attributes and accessors. Question 7 asks about results of string operations. Question 8 asks to create a Book class with attributes and parameterized constructor.

Uploaded by

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

Ctood Assignment2

The document contains instructions for a programming exam with 7 questions. Question 1 asks to write code to convert meters to feet and output the result. Question 2 asks about differences between static and instance members. Question 3 asks to write code to read integers from a file and count even and odd numbers. Question 4 asks to create a Student class with attributes, accessors, mutators and a display method. Question 5 asks to create a BMI class to calculate and output BMI information. Question 6 asks to create a Ticket class to book movie tickets with class attributes and accessors. Question 7 asks about results of string operations. Question 8 asks to create a Book class with attributes and parameterized constructor.

Uploaded by

CRAZY GAMER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 59

Koneru Lakshmaiah Education Foundation

Academic year: 2020-2021


Sem-In Examinations-I,
B. Tech. (BT/CE/CSE/ECE/ECSE/EEE), 2020 Batch
I/IV, 2nd Semester
19CS1203: Object Oriented Programming

Time: 2 hours Date:31/03/2021


Max. Marks: 50
1. Draw the class diagram and code the logic to read the number of meters (of type double)
through console, convert it into feet, display the result (HINT: 1 meter = 3.2786 feet)
4.5M

Class diagram 2M

Demo

+convertToFeet(meters:double):doubl
e
+main(args: String[]):void

Code: 2.5M
import java.util.Scanner;

publicclassDemo {

publicstaticdouble convertToFeet(doublemeters)
{
returnmeters*3.2786;
}
publicstaticvoid main(String[] args)
{
Scanner sc=new Scanner(System.in);
doublemeters=sc.nextDouble();
System.out.printf(" meters in feet = %.2f", convertToFeet(meters));

Output:
12
meters in feet = 39.34

(or)

2. Illustrate the differences between static and instance members of class 4.5
Marks

3. Draw the class diagram and code the logic to read a set of integers from a file and count
the number of even and odd numbers. Display the output on console.
8M
Class diagram
2M

Demo

+main(args: String[]):void

Program:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

publicclass ReadFromFile {

publicstaticvoid main(String[] args) throws


FileNotFoundException
{
File f = new File("data.txt");
Scanner sc = new Scanner(f);
inteven=0,odd=0;
while(sc.hasNextInt())
{
intt=sc.nextInt();
if(t%2 == 0)
even++;
else
odd++;
}
System.out.println("Number of evens ="+even);
System.out.println("Number of odds ="+odd);
sc.close();
}
}
(Or)
4. Draw the class diagram and develop the code for the class Student with ID, name and
mobile has private attributes. Also write the accessors, mutators for the attributes and
method display data in the following format ID: 200003001 Name: John Mobile:
1234567890 8M
Class diagram:4M

Student
-Id:int
-Name:String
-Mobile:long
+setId(id:int):void
+setName(name:String):void
+setMobile(mobile:long):void
+getId():int
+getName():String
+getMobile():long
+ display():void
Fig: Class diagram
Code:
package p1;
import java.util.Scanner;
class Student
{
private int id;
private String name;
private long mobile;
public void setId(int id)
{
this.id=id;
}
public void setName(String name)
{
this.name=name;
}
public void setMobile(long mobile)
{
this.mobile=mobile;
}
void int getId()
{
return id;
}
void String getName()
{
return name;
}
void long getMobile()
{
return mobile;
}
void display()
{
System.out.println(“ID: ”+getId()+”Name: ”+getName()+”Mobile:
”+getMobile());
}
public static void main(Sting args[])
{
Student s1=new Student();
Scanner sc=new Scanner(System.in);
System.out.println(“Enter Id,name and mobile number”);
s1.setId(sc.nextInt());
s1.setName(sc.next());
s1.setMobile(sc.nextLong());
s1.display();
}
}

5. Design a class BMI as per the class diagram. Enhance the design by modularizing to
package level. The formula for BMI (Body Mass Index) is weight in kilograms divided by
height in meters squared. The data must be printed in the following format. NAME: ABC
HEIGHT: 1.65 WEIGHT: 70 BMI: 25.7. Develop the main in Demo class to test the
capabilities of the above BMI class. 12.5M

BMI

-name: String
-height: double
-weight: double

+setData(n : String, h: double, w: double):void


+computeBMI():double
+toString():String

Code:

package p1;

class BMI
8M
{
private String name;
privatedoubleheight, weight;
publicvoid setData(String n, doubleh, doublew)
{
name=n;
height=h;
weight=w;
}
publicdouble computeBMI()
{
returnweight/(height*height);
}
public String toString()
{
return String.format("NAME: %s HEIGHT: %.2f WEIGHT: %.0f BMI: %.2f
",name,height,weight,computeBMI());
}
}
publicclass Demo {
4.5M
publicstaticvoid main(String args[]) {
BMI ob = new BMI();
ob.setData("ABC",1.65,70);
System.out.println(ob);
}
}
6. The supervisor of a movie theatre decides to automate Ticket Booking. The task
is to develop a class Ticket with TicketID, number of seats, date and fare as
instance data members and a static fields totalSeatsBooked and
totalTicketsBooked. Write getters and setters. Draw the class diagram and a
TicketDemo class to create object and access Ticket class methods. (Input data to
be read from console.)
12.5M
package stringmethod;
import java.util.Scanner; // Class Diagram 4M
public class TicketDemo // 3.5M for Demo class
{
public static void main(String[] args)
{
Ticket obj=new Ticket();
Scanner s=new Scanner(System.in);
System.out.println("Enter the TicketId:");
long a=s.nextLong();
obj.setId(a);
System.out.println("Enter the number of Seats:");
int b=s.nextInt();
obj.setSeats(b);
System.out.println("Enter the Fare:");
long d=s.nextLong();
obj.setFare(d);
System.out.println("Enter the Date:");
String c=s.next();
obj.setDate(c);
Ticket.totalTicketsBooked=1;
Ticket.totalSeatsBooked=obj.getSeats();
String cc=obj.getDate();
long dd=obj.getFare();
System.out.println("Total Tickets
Booked="+Ticket.totalTicketsBooked);
System.out.println("Total Seats
Booked="+Ticket.totalSeatsBooked);
System.out.println("Total Fare="+(obj.getSeats()*dd));
System.out.println("DATE="+cc);
s.close();
}

}
---------------------------------------------------
package Stringmethod;
public class Ticket
{
private long TicketID;
private int no_of_seat;
private String date;
private long fare;
static long totalSeatsBooked;
static long totalTicketsBooked;
void setId(long id)
{
TicketID=id;
}
void setSeats(int seat)
{
no_of_seat=seat;
}
void setDate(String dat)5M
{
date=dat;
}
void setFare(long rate) {
fare=rate;
}
long getId()
{
return TicketID;
}
int getSeats()
{
return no_of_seat;
}
String getDate()
{
return date;
}
long getFare()
{
return fare;
}
}
7. Suppose that s1, s2, and s3 are three strings, given as follows:
4.5M

String s1 = "Welcome to Java";

String s2 = "Programming is fun";

String s3 = "Welcome to Java";

What are the results of the following expressions? Justify your answer

(a) s1 == s2 (b) s2 == s3 (c) s1.equals(s2)

(d) s1.equals(s3) (e) s1.compareTo(s2) (f) s2.compareTo(s3)

a) false b) false c) false d) true e) 7 f) -7 Each ½


marks

A separated memory is allocated for data which is not same in string pool.Here == compares the
memory location address stored in s1,s2,s3. Since the data in s1,s2 and s2,s3 are not same, a
separate memory is allocated in string pool which have different addresses. Hence a) and b) are
false.

equals function compares the data present in s1, s2 and s1, s3 in c) and d)

compareTo returns the ascii difference of the first character differing in s1, s2 and s2, s3 in e)
and f)

Q8) Assume a class Book with the following attributes – ISBN (long), Title (String),
Price(double), Year (integer). Write the parameterized constructor with 4 arguments
and draw the class diagram. Class Diagram-> 2.5M
Book
+ ISBN: long
+ Title: String
+ Price: double
+ Year: int
Book(i:long,t:String,p:double,y:int)
Book(long i, String t, double p, int y)
{
ISBN=i;
Title= t; -> 2M
Price= p;
Year= y;
}
Q9) Modularize to package level and draw the class diagram to develop a class called Date that
includes a month(type int), a day(type int) and a year(type int). The class should have a
parameterized constructor that initializes 3 instance variables. Provide a method toString() that
displays the month, day and year separated by forward slashes (/). Write a test application named
DateTest that demonstrates class Date’s capabilities.  8M

Class Diagram : 4M

package p1

DateClass

-day: int

-month:int

-year:int

+DateClass(day:int, month:int, year:int)

+toString():String

package p2

Test

+main(args: String[]):void

Code: 4M
package p1;

publicclass DateClass
{
privateintday, month, year;

public DateClass(intday, intmonth, intyear) {


this.day = day;
this.month = month;
this.year = year;
}

publicString toString() {
returnday + "/" + month + "/" + year ;
}

package p2;
importp1.DateClass;
publicclass Test {

publicstaticvoid main(String[] args) {


DateClassob=newDateClass(12/10/2020);
System.out.println(ob);
}

Q10) Some websites impose certain rules for passwords. Suppose the password rules are
as
follows: ¦ A password must have at least eight characters. ¦ A password consists of only
letters and digits. Write main () method that prompts the user to enter a password and
a static methodisValidPassword() that expects a string argument and returns boolean
type aftervalidating the password.
import java.util.Scanner;
class Password
{
String pass;

staticbooleanisValidPassword(String p)
{
if((p.length()>=8) &&p.matches(".*[a-zA-Z].*") &&p.matches(".*[0-9].*"))
{
return true;
}3M
else
{ return false; }
}
}
public class Passwordrule
{
public static void main(String[] args)
{
String pas;
Scanner s=new Scanner(System.in);
System.out.println("Enter the password");
pas=s.next();
boolean res=Password.isValidPassword(pas);
if(res==true)2M
{
System.out.println("password is valid");
}
else
{
System.out.println("password is invalid");
}
}
}

11. Draw the class diagram modularized to package level and develop a class “Dictionary” that
contains the following information (a) Name of a person (b) mobile number (both as private
attributes). The main() demo class must be able to store details of 10 person and display a menu
with the following options. 1. Add new person information 2. Display all data.

package esan;
publicclass Dictionary {
private String name;
privatelongmob;
publicDictionary(String name,longmob){
this.name=name;
this.mob=mob;
}
public String toString() {
return"Name="+name+" Mobile No="+mob+" \n";
}
}

package tgan;
import java.util.Scanner;
import esan.Dictionary;
publicclass DictionaryDemo {
publicstaticvoid main(String[] args) {
Dictionary[] d=new Dictionary[10];
Scanner sc=new Scanner(System.in);
intsize=0;
booleanrepeat=true;
while(repeat) {
System.out.println("1. addNewPerson\n2.Display\n others
exit");
intoption=sc.nextInt();
switch(option)
{
case 1:
d[size]=new Dictionary(sc.next(),sc.nextLong());
size++;
break;
case 2:
for(inti=0;i<size;i++)
System.out.println(d[i]);
break;
default:
repeat=false;
}
}
sc.close();
}

Q12) The Election commission requires the following task to be done. Draw the class diagram
modularized to package level and code the following specifications: A class Voter with ID, name and
age as private attributes. Write Constructor, toString() method. The VoterDemo has main() method
which reads and stores data of 10 voters and display a menu with following operations
12.5M

1. Add new Voter

2. Search Voter based on id

Code:
package p1;

publicclass Voter
4.5
{
privatelongid;
private String name;
privateintage;
public Voter(longid, String name, intage) {

this.id = id;
this.name = name;
this.age = age;
}
publiclong getId()
{
returnid;
}
public String toString() {
return"id=" + id + ", name=" + name + ", age=" + age;
}

}
package p2;
import java.util.Scanner;

import p1.Voter;
publicclass VoterDemo 8M
{
publicstaticvoid Search(Voter ob[], longkey, intnov)
{
for(inti=0;i<nov;i++)
{
if(ob[i].getId() == key)
{
System.out.println(ob[i]);
return;
}
}
System.out.println(" Voter id not found");
}
publicstaticvoid main(String[] args) {
Scanner sc = new Scanner(System.in);
Voter ob[]=new Voter[10];
intnov=0;
while(true)
{
System.out.println("Enter 1. 1. Add new Voter 2. Search Voter
based on id");
intchoice=sc.nextInt();
switch(choice)
{
case 1:
System.out.println("enter voter id, name and
age");
ob[nov]=new
Voter(sc.nextLong(),sc.next(),sc.nextInt());
nov=nov+1;
break;
case 2:
System.out.println("enter the voter id to be
searched");
longkey=sc.nextLong();
Search(ob,key,nov);
break;
default: return;

}
}
}

}
Koneru Lakshmaiah Education Foundation
Academic year: 2019-2020
Sem-In Examinations-I,

B. Tech. (BT/CE/CSE/ECE/ECSE/EEE), 2019 Batch

I/IV, 2nd Semester


19CS1203: Object Oriented Programming

Time: 2 hours Max. Marks: 50

Answer Key
Part-A ( 4 x 3 marks = 12 marks )

1) Given the lengths of 2 sides of a right-angled triangle through console, write a java
program to print the length hypotenuse. (Hypotenuse = (side12 + side2 )1/2 )
package p1;
importjava.util.Scanner;
public class Triangle {

publicstaticvoid main(String[] args) {


int side1,side2;
Scanner sc=newScanner(System.in);
System.out.println("enter side1,side2 values");
side1=sc.nextInt();
side2=sc.nextInt();
double angle=Math.sqrt(Math.pow(side1,2)+Math.pow(side2,2));
System.out.println(angle);
}
}

2) The marks of students in a class are specified as command line arguments, the task is
finding the maximum and average of the marks. Write a program to perform the above
task.
public class Marks {

publicstaticvoid main(String[] args) {


int sum=0;
for(int i=0;i<args.length;i++)
{
int x=Integer.parseInt(args[i]);
sum=sum+x;
}
doubleavg=sum/args.length;
System.out.println("Total Marks="+sum);
System.out.println("Average Marks="+avg);
}}
3) Suppose that s1, s2, and s3 are three strings, given as follows:
String s1 = "Welcome to Java";
String s2 = "Programming is fun";
String s3 = "Welcome to Java";
What are the results of the following expressions?
(a) s1 == s2 (b) s2 == s3 (c) s1.equals(s2)
(d) s1.equals(s3) (e) s1.compareTo(s2) (f) s2.compareTo(s3)
a) false b) false c) false d) true e) 7 f) -7 Each ½ marks
4) Assume a class Book with the following attributes – ISBN (long), Title (String),
Price(double), Year (integer). Write the parameterized constructor with 4 arguments
and draw the class diagram.
Book
+ ISBN: long
+ Title: String
+ Price: double
+ Year: int
Book(i:long,t:String,p:double,y:int)
Book(long I, String t, double p, int y)
{
ISBN=i;
Title= t;
Price= p;
Year= y;
}
Part – B ( 4x5marks =20Marks)
5)The financial officer of a company stores the following data of a department in a file.
a) Employee name b) Number of hours worked in week c) Hourly pay rate Develop a
program to read the data and print the amount each employee needs to obtain.
package p1;
importjava.io.File;
importjava.io.IOException;
importjava.util.Scanner;
importjava.util.StringTokenizer;
public class Employee
{
private String ename;
privateintnohrs;
privateintnpr;
public static void main(String[] args) throws IOException
{
float f, h;
String s;
Scanner inFile = new Scanner(new File("C:\\Users\\eclipse workspace \\
Question5 \\src\\p1\\Employee.txt.txt"));
while (inFile.hasNext())
{
String line = inFile.nextLine();
StringTokenizerst = new StringTokenizer(line,"\t");
s = st.nextToken();
f = Float.parseFloat(st.nextToken());
h = Float.parseFloat(st.nextToken());
System.out.println(s +" has worked for "+f+ " hrs, the amount he/she is get is "+ (f*h));
}
inFile.close();
}
}

6)The Course class has the following private fields: courseCode, courseTitle (both of
type String) and credits (type int). It also contains assessors and mutators for each
attribute.
1. courseCode must have 6 characters (only digits and characters)
2. Credits must be a positive value less than 6.
Also code the toString( ) method to display the data of courses and draw the class
diagram.

Class Diagram

P1
Course
- courseCode : String
- courseTitle : String
- credits : int
- getCourseCode():String
- getCourseTitle():String
- getCredits(): int
- setCourseCode(c:String):boolean
- setCourseTitle(t:String): Boolean
- setCredits(cre:int): Boolean
+ toString():String
-setCourse(t:String, c:String, cre:int): void
+ main(args[] : String) : void

Program
package p1;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;

public class Course


{
private String courseCode;
private String courseTitle;
privateint credits;
private String getCourseCode()
{
returnthis.courseCode;
}

private String getCourseTitle()


{
returnthis.courseTitle;
}

privateintgetCredits()
{
returnthis.credits;
}

privatebooleansetCourseCode(String c)
{
int cc=c.length();
Pattern p=Pattern.compile("[^A-Za-z0-9]*");
Matcher m=p.matcher(c);
boolean b=m.find();
if(cc==6 && b)
{
return true;
}
return false;
}

privatebooleansetCourseTitle(String t)
{
Pattern p=Pattern.compile("[^A-Za-z]");
Matcher m=p.matcher(t);
boolean b=m.find();
if (b)
{
return true;
}
return false;
}

privatebooleansetCredits(intcre)
{
if(cre>=1 &&cre<6)
{
return true;
}
return false;
}

public String toString()


{
String str = String.format("Course Code:%s%nCourse Title:%s%n"
+ "Credits:%d",getCourseCode(),getCourseTitle(),getCredits());
returnstr;
}

private void setCourse(String t,String c, intcre)


{
if(setCourseTitle(t) &&setCourseCode(c) &&setCredits(cre))
{
this.courseCode = c;
this.credits = cre;
this.courseTitle = t;
}
return;
}

public static void main(String[] args)


{
Course c1=new Course();
c1.setCourse("Object Oriented Programming", "19CS03",4);
System.out.println(c1);
}
}
Output
Course Code:19CS03
Course Title:Object Oriented Programming
Credits:4

7) Develop a class called Date that includes three pieces of information as instance
variables—a month (type int), a day (type int) and a year (type int). The class should
have a parameterized constructor that initializes the three instance variables. Provide a
set and a get method for each instance variable. Set the data only when values are
positive. Provide a method toString() that displays the month, day and year separated
by forward slashes (/). Write a test application named DateTest that demonstrates class
Date’s capabilities.
class Date
{
int day;
int month;
int year;
Date(intd,intm,int y)
{
day=d;
month=m;
year=y;
}
booleansetdate(intday,intmonth,int year)
{
if(day>0&&month>0&&year>0)
{
this.day=day;
this.month=month;
this.year=year;
return true;
}
else
{
return false;
}
}
public intgetDay() {
return day;
}
public intgetMonth() {
return month;
}
2M
public intgetYear() {
return year;
}
public String toString()
{
String s=String.format("%d / %d /%d",getMonth(),getDay(),getYear()); -
>1M
return s;
}
}

public class Datetest


{
public static void main(String[] args)
{
Date d=new Date(1,1,1970);
d.setdate(27, 12,1983);
System.out.print(d);
}
}

8) Some websites impose certain rules for passwords. Suppose the password rules are as
follows: ¦ A password must have at least eight characters. ¦ A password consists of only
letters and digits. Write main () method that prompts the user to enter a password and
a static method isValidPassword() that expects a string argument and returns boolean
type after validating the password.
import java.util.Scanner;
class Password
{
String pass;

staticbooleanisValidPassword(String p)
{
if((p.length()>=8) &&p.matches(".*[a-zA-Z].*") &&p.matches(".*[0-9].*"))
{
return true;
}
else
{ return false; }
}
}
public class Passwordrule
{
public static void main(String[] args)
{
String pas;
Scanner s=new Scanner(System.in);
System.out.println("Enter the password");
pas=s.next();
boolean res=Password.isValidPassword(pas);
if(res==true)
{
System.out.println("password is valid");
}
else
{
System.out.println("password is invalid");
}
}
}
Part – C {2 x 9 Marks = 18 Marks}

9) The supervisor of a movie theatre decides to automate Ticket Booking. The task is to
develop a class Ticket with TicketID, number of seats, date and fare as instance data
members and a static fields totalSeatsBooked and totalTicketsBooked. Write getters
and setters. Draw the class diagram and a TicketDemo class to create object and access
Ticket class methods. (Input data to be read from console.)
package stringmethod;
import java.util.Scanner;
public class TicketDemo
{
public static void main(String[] args)
{
Ticket obj=new Ticket();
Scanner s=new Scanner(System.in);
System.out.println("Enter the TicketId:");
long a=s.nextLong();
obj.setId(a);
System.out.println("Enter the number of Seats:");
int b=s.nextInt();
obj.setSeats(b);
System.out.println("Enter the Fare:");
long d=s.nextLong();
obj.setFare(d);
System.out.println("Enter the Date:");
String c=s.next();
obj.setDate(c);
Ticket.totalTicketsBooked=1;
Ticket.totalSeatsBooked=obj.getSeats();
String cc=obj.getDate();
long dd=obj.getFare();
System.out.println("Total Tickets
Booked="+Ticket.totalTicketsBooked);
System.out.println("Total Seats
Booked="+Ticket.totalSeatsBooked);
System.out.println("Total Fare="+(obj.getSeats()*dd));
System.out.println("DATE="+cc);
s.close();
}

}
---------------------------------------------------
package Stringmethod;
public class Ticket
{
private long TicketID;
private int no_of_seat;
private String date;
private long fare;
static long totalSeatsBooked;
static long totalTicketsBooked;
void setId(long id)
{
TicketID=id;
}
void setSeats(int seat)
{
no_of_seat=seat;
}
void setDate(String dat)
{
date=dat;
}
void setFare(long rate) {
fare=rate;
}
long getId()
{
return TicketID;
}
int getSeats() {return no_of_seat;}
String getDate() {
return date; }
long getFare() { return fare;}
}
10) A cab booking app is to be launched. The task is to store data of Passengers in a
class
with attributes Name, Mobile, distance and fare. Write mutators for
a) name – has only characters
b) mobile – 10 digits
c) distance - must be a positive value (in terms of kms)
A method to compute fare at the rate of Rs.10 per km and toString() method to print
data. Modularize to package level with main () in PassengerDemo class to create an
object and obtain the data through console.
package p1;
publicclass Passanger {
private String name,mobile;
privateint distance;
publicboolean setName(String a)
{
int i;
for(i=0;i<a.length();i++)
{
if(a.charAt(i)>=65 &&a.charAt(i)<=90 || a.charAt(i)>=97 &&a.charAt(i)<=122)
continue;
else
returnfalse;
}
name=a;
returntrue;
}
publicboolean setMobile(String b)
{

if(b.length()==10)
{mobile=b;
returntrue;
}
else
returnfalse;
}
publicboolean setDistance(int a)
{
if(a>0)
{
distance = a;
returntrue;
}
returnfalse;

}
public String getName()
{
return name;
}
public String getMobile()
{
return mobile;
}
publicint getDistance()
{
return distance;
}

publicint getFare()
{
return distance *10;
}
public String toString()
{
return "name = "+getName()+"\n"+"mobile no = "+getMobile()+"\n"+"distance =
"+getDistance()+"\n"+"fare ="+getFare();
}
}

package p2;
import java.util.Scanner;
import p1.Passanger;
public class PassangerDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Passanger p=new Passanger();
String a,b;
int c;
a=sc.next();
b=sc.next();
c=sc.nextInt();
if(p.setName(a)&&p.setMobile(b)&&p.setDistance(c))
System.out.println(p.toString());
else
System.out.println("wrong format");
sc.close();
}}

11) The Election Commission requires the following task to be done. A class Voter with
ID,
name, age and address as fields. Write toString() , getter methods and setData() method.
The VoterDemo has main () method which reads and stores data of 10 voters and
displays a menu with following operations:
a) Add new voter
b) Search voter based on ID
c) Search voter whose name starts with "A”

package p2;
publicclass Voter
{
privatelongid;
private String name,address;
privateintage;
publicvoidsetData(longid, String name,intage,Stringaddress)
{
this.id=id;
this.name=name;
this.age=age;
this.address=address;
}
public String toString()
{
return"Voter id = "+id+" Voter Name =" +name+" Voter age =" +age+"\n Address =
"+address;
}
publiclonggetId()
{
returnid;
}
publicStringgetName()
{
return name;
}
}
package p2;

importjava.util.Scanner;

publicclassVoterDemo
{
publicstaticintlinearSearch(Voter v[],intn,longkey)
{
for(inti=0;i<n;i++)
{
if(v[i].getId()==key)
returni;
}
return -1;
}
publicstaticvoidlinearSearch(Voter v[],intn)
{
intflag=0;
for(inti=0;i<n;i++) {
2M
if(v[i].getName().charAt(0) == 'A'){
flag=1;
System.out.println(v[i]);}
}
if(flag ==0)
System.out.println("no voter whose name starts with A");
}
publicstaticvoid main(String[] args)
{
Voter v[]=new Voter[10];
Scanner sc = new Scanner(System.in);
intchoice,nov=0,index;
while(true)
{
System.out.println("Menu");
System.out.println("1. Add new voter");
System.out.println("2. Search voter based on ID");
System.out.println("3. Search voter whose name starts with 'A'");
System.out.println("4. exit");
choice =sc.nextInt();
switch(choice)
{
case 1:
v[nov]=newVoter();
System.out.println("Enter id, name, age and address of voter");
longid=sc.nextLong();
sc.nextLine();
String name=sc.nextLine();
intage=sc.nextInt();
sc.nextLine();
String address=sc.nextLine();
v[nov].setData(id,name,age,address);
nov++;
break;
case 2:
System.out.println("enter the id of voter");
longkey=sc.nextLong();
index=linearSearch(v,nov,key);
if(index != -1)
{
System.out.println("voter details are");
System.out.println(v[index]);
}
else
System.out.println("Search id not found");

break;
case 3:
linearSearch(v,nov);
break;
case 4:
System.exit(0);
}
}
}
}
12) A vehicle registration portal accepts the following data from Vehicle owners:
a) Vehicle Number – 8 letters (can contain digits and characters)
b) Wheeler (either 2 or 4)
c) Owner name – can contain only characters
d) Mobile – 10 digits. Draw the class diagram and Vehicle class contains parameterized
constructor, toString() methods. The Vehicle Demo class has a main () method which
reads and stores data of 5 vehicles from a file and displays the menu with following
operations: a) Add data b) Display data based on vehicle number c) Print data of all
vehicles
package automobiles;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.File;
public class Vehicle {
private String vno;
private int wheeler;
private String owner;
private long mobile;
Vehicle() { }
Vehicle(String vno,int wheeler,String owner,long mobile)
{
this.vno=vno;
this.wheeler=wheeler;
this.owner=owner;
this.mobile=mobile;
}
public void writeRecord()throws Exception
{
FileWriter fw=new FileWriter("C:\\Users\\srira\\eclipseworkspace\\automobiles\\src
\\automobiles\\vehinfo",true);
PrintWriter pw=new PrintWriter(fw);
pw.write("\n"+vno+"\t"+wheeler+"\t"+owner+"\t"+mobile);
pw.close();
}
public void display(String vno)throws Exception
{
File f=new File("C:\\Users\\srira\\eclipse-workspace\\automobiles\\src\\automobiles\\
vehinfo");
Scanner s=new Scanner(f);
while(s.hasNextLine())
{
String no=s.next();
int w=s.nextInt();
String o=s.next();
long m=s.nextLong();
if(no.equals(vno))
{
System.out.println(this);
break;
}
}
}
public void display()throws Exception
{
File f=new File("C:\\Users\\srira\\eclipse-workspace\\automobiles\\src\\automobiles\\
vehinfo");
Scanner s=new Scanner(f);
while(s.hasNextLine())
{
String no=s.next();
int w=s.nextInt();
String o=s.next();
long m=s.nextLong();
System.out.println(this);
}

public String toString()


{
return("Vehicle Number:"
+this.vno+"\nWheeler:"+this.wheeler+"\nOwner:"+this.owner+"\nMobile:"+this.mobile);
}
}

package automobiles;
import java.util.Scanner;
public class VehicleDemo {

public static void main(String[] args)throws Exception{

int choice;
Scanner s=new Scanner(System.in);
Vehicle v[]=new Vehicle[5];
for(int i=0;i<2;i++)
{
System.out.println("Enter vehicle number:");
String no=s.next()+s.nextLine();
System.out.println("Enter vehicle type:");
int w=s.nextInt();
System.out.println("Enter vehicle owner:");
String o=s.next()+s.nextLine();
System.out.println("Enter mobile:");
long m=s.nextLong();
v[i]=new Vehicle(no,w,o,m);
v[i].writeRecord();
}

do
{
System.out.println("1.Add data\n2.Display Data based on vehicle number\n
3.Print the data of all vehicles\n");
choice=s.nextInt();
switch(choice)
{
case 1:
String no=s.next()+s.nextLine();
int w=s.nextInt();
String o=s.next()+s.nextLine();
long m=s.nextLong();
Vehicle vi=new Vehicle(no,w,o,m);
vi.writeRecord();
break;
case 2:
Vehicle ve=new Vehicle();
System.out.println("Enter vehicle number");
ve.display(s.nextLine());
break;
case 3:
for(int i=0;i<v.length;i++)
v[i].display();
break;
default:System.out.println("INVALIED");
}
}while(choice!=0);
s.close();
}
}
SEMESTER IN I EXAM

COURSE CODE: 19CS1203

COURSE NAME: Object Oriented Programming

ANSWER KEY

1 : Define the terms class, object and explain about access specifiers.

Class: A class is a group of objects which have common properties. It is a template


or blueprint from which objects are created. It is a logical entity. It can't be
physical. A class in Java can contain: Fields, Methods, Constructors, Blocks,
Nested class and interface

Syntax:

class <class_name>{ 1.5M

member variable(s);

member method(s);

Object: An object is an instance of a class. A class is a template or blueprint from


which objects are created. So, an object is the instance(result) of a class.

Syntax: 1M

class_name objname=new class_name();

Access specifier or modifier in Java: 2M

The access specifier in Java specifies the accessibility or scope of a field, method,
constructor, or class. There are four types of Java access specifiers :

Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will
be the default.

Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.

Public: The access level of a public modifier is everywhere. It can be accessed


from within the class, outside the class, within the package and outside the
package.

2. Draw the class diagram for the following and Develop a java program that
reads the number of kilograms of type double, through console, converts it to
pounds, displays the result.(HINT: 1kg = 2.2046 pounds )

CLASS DIAGRAM -1.5 M

package pack8;

import java.util.Scanner;

public class Kgtopound{

private double kg;

private void convertKgToPounds(double k) 2M

{ this.kg=k;
System.out.println("After conversion: \n"+ this.kg +" kg =" +(this.kg*2.2046)+"
"+"pounds");

public static void main(String[] args) {

Kgtopound kg=new Kgtopound(); 1M

Scanner sc=new Scanner (System.in);

System.out.print(" Enter value in kilogram(S):");

double n=sc.nextDouble();

kg.convertKgToPounds(n);

sc.close();

3.

public class Book{

private long isbn;

private String title;

private double price;

public void setIsbn(long i)

{this.isbn=I;}

public void setTitle(String t)

{this.title=t;}

public void setPrice(double p)

{this.price=p;}
public longgetIsbn()

{return isbn;}

public StringgetTitle()

{return title;}

public doublegetPrice()

{return price;}

public String toString()

String s;

s=String.format(“ISBN: %d Title: %s Price: %.2f”,getIsbn(),getTitle(),getPrice());

return s;

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

Book b=new Book();

System.out.println(“Enter isbn,title,price of book:”);

b.setIsbn(sc.nextLong());

b.setTitle(sc.next());

b.setPrice(sc.nextDouble());

system.out.println(b);

}
4.
public class First
{
    public static void main(String[] args)
  { 
 int sum=0,m1,m2,m3,m4,m5,m6,avg;
for(int i=0;i<args.length;i++)
 {
      sum=sum+Integer.parseInt(args[i]);
}
  avg=sum/6;
 System.out.println(avg);
 m1=Integer.parseInt(args[0]);
 m2=Integer.parseInt(args[1]);
 m3=Integer.parseInt(args[2]);
 m4=Integer.parseInt(args[3]);
 m5=Integer.parseInt(args[4]);
 m6=Integer.parseInt(args[5]);
 if(m1>m2&&m1>m3&&m1>m4&&m1>m5)
 {
 System.out.println(m1);
 }
 else if(m2>m3&&m2>m4&&m2>m5)
 System.out.println(m2);
 else if(m3>m4&&m3>m5)
 System.out.println(m3);
 else if(m4>m5)
 System.out.println(m4);
 else
 System.out.println(m5);
}}

5 a)
package question5;

public class Passengers {

private String name;

private long mobile;

private int distance;

private int fare;

public boolean setDistance(int d)

if(d>0)

distance=d;

return true;

else

return false;

public void setName(String name)

this.name=name;

public void setMobile(long mobile)

{
this.mobile=mobile;

public String getName()

return name;

public long getMobile()

return mobile;

public int getDistance()

return distance;

public int computeFare()

fare=distance*10;

return fare;

public String toString()

String s=String.format("NAME=%s\nMOBILE=%d\nDISTANCE=%d\nFARE=
%d",getName(),getMobile(),getDistance(),computeFare());

return s;
}

package temp;

import java.util.Scanner;

import question5.Passengers;

public class Demo {

public static void main(String[] args)

Passengers r=new Passengers();

Scanner sc=new Scanner(System.in);

System.out.println("enter the passenger name");

String name=sc.next();

System.out.println("enter the mobile no");

long mobile=sc.nextLong();

System.out.println("enetr the distance");

int distance=sc.nextInt();

r.setName(name);

r.setMobile(mobile);

r.setDistance(distance);

System.out.println(r.toString());

sc.close();

}
6. package question6;

public class Course { ---------------------------------------------------- 2M

private String courseCode;

private String courseTitle;

private int credits;

public String getCourseCode() {

return courseCode;

public boolean setCourseCode(String courseCode) {

if(courseCode.length()<=6&&courseCode.matches("^(?=.*[A-Z])(?=.*[0-9])[A-
Z0-9]+$"))
{

this.courseCode = courseCode; ------------------ 1M

return true;

else

return false;

public String getCourseTitle() {

return courseTitle;

@Override

public String toString() { ---------------------- 1M

return "Course [courseCode=" + courseCode + ", courseTitle=" + courseTitle + ",


credits=" + credits + "]";

public void setCourseTitle(String courseTitle) {

this.courseTitle = courseTitle;

public int getCredits() {

return credits;

public boolean setCredits(int credits) { ------------------- 1M


if(credits>0&&credits<6)

this.credits = credits;

return true;

else

System.out.println("Invalied Credits");

return false;

package question6; --------------------------------- 2M

import java.util.*;

public class CourseDemo {

public static void main(String[] args) {

Scanner scan=new Scanner(System.in);

String cc;

String ct;

int cr;

Course c=new Course();

System.out.println("Enter course code"); ------------ 2M

cc=scan.nextLine();

if(!c.setCourseCode(cc))
{

System.out.println("Invalied Course Code");

System.out.println("Enter course Title");

ct=scan.nextLine();

c.setCourseTitle(ct);

System.out.println("Enter credits"); ---------------- 1M

cr=Integer.parseInt(scan.nextLine());

if(!c.setCredits(cr))

System.out.println("Inavalied Credits");

System.out.println(c);

scan.close();

INPUT/OUTPUT:

Enter course code

20SC1101

Invalied Course Code

Enter course Title

Enter course code

20S11

Enter course Title


CTD

Enter credits

Invalied Credits

Inavalied Credits

Course [courseCode=20S11, courseTitle=CTD, credits=0]

Enter course code

20SC11

Enter course Title

OOP

Enter credits

Course [courseCode=20SC11, courseTitle=OOP, credits=5]

Class Diagram --------------- 2.5M


7.

Class TwoDimensionalPoint {

double x, y;

TwoDimensionalPoint (double x, double y)

This.x=x;

This.y =y;
}

8.

Class Loan

Int loanAmount, numberOfYears;

Double annualROI;

Loan ()

loanAmount=0;

numberOfYears=0;

annualROI=0;

Loan (int la, int noi)

This ();

loanAmount=la;

numberOfYears=noi;

}
9. Draw the class Diagram and code the class Triangle with base and height as
private attributes of type double. Define a no argument constructor and overload it
with parameterized constructor. Also write a method area() that computes the area
of a triangle and returns the result and code the toString() method.

Solution:

import java.util.Scanner;

public class Triangle { 2M

private double base;

private double height;

public Triangle(){ 1M

base = 2;

height = 4;

public Triangle(double base,double height) { 1M

this.base = base;

this.height = height;

public double area() { 1M

return 0.5*base*height;

public String toString() { 1M

String s;

s="Base:"+base+"\nHeight:"+height+"\nArea:"+area();

return s;

}
public static void main(String[] args) { 2M

Scanner sc = new Scanner(System.in);

Triangle ob = new Triangle();

System.out.println(ob);

System.out.println("Enter values of base & height:");

double b = sc.nextDouble();

double h = sc.nextDouble();

Triangle ob1 = new Triangle(b,h);

System.out.println(ob1);

sc.close();

Class Diagram:

10. Let S1 be “Welcome” and s2 be “welcome” .Write the code for the following
statements and justify the answer.

a) Check whether s1 has a prefix AAA

b) Check whether s1 has a suffix AAA

c) Create a new String s3 that appends s1 & s2


d) Create a substring of s1 starting from 1

e) Create a substring of s1 from 1 to 4

f) Compare two strings case insensitively

g) Compare two strings case sensitively

h) Print the first occurrence of 'e' in s1

Solution:

public class Question10 {

public static void main (String [] args) {

String s1 = "Welcome";

String s2 = "welcome";

//check whether s1 has a prefix AAA ---------------------------1M

boolean b = s1.startsWith ("AAA");

System.out.println (b);

//check whether s1 has a suffix AAA ---------------------------1M

b=s1.endsWith ("AAA");

System.out.println (b);

//Create a new String s3 that appends s1 & s2 ------------------1M

String s3 = s1+s2;

System.out.println (s3);

//Create a substring of s1 starting from 1 ------------------------1M

String s4 = s1.substring (1);

System.out.println (s4);

//Create a substring of s1 from 1 to 4 ---------------------------1M

String s5 = s1.substring (1,5);


System.out.println (s5);

//Compare two strings case insensitively ---------------------------1M

System.out.println (s1.equalsIgnoreCase (s2));

//Compare two strings case sensitively ----------------------------1M

System.out.println (s1.equals (s2));

//Print the first occurrence of 'e' in s1 -------------------1M

System.out.println (s1.indexOf (‘e’);

}}

11

package mypack1;

publicclass LinearEquation {
privateinta,b,c,d,e,f,x,y;
publicLinearEquation(inta,intb,intc,intd,inte,intf)
{
this.a=a;
this.b=b;
this.c=c;
this.d=d;
this.e=e;
this.f=f;
}
publicboolean isSolvable()
{
intresult;
result=(this.a*this.d)-(this.b*this.c);
if(result==0)
returnfalse;
else
returntrue;
}
publicint getX()
{
this.x=(e*d-b*f)/(a*d-b*c);
returnthis.x;
}
publicint getY()
{
this.y=(a*f-e*c)/(a*d-b*c);
returnthis.y;
}
}
package mypack2;
import mypack1.LinearEquation;
import java.util.Scanner;
publicclass LinearDemo {
publicstaticvoid main(String args[])
{
Scanner sc=new Scanner(System.in);
inta,b,c,d,e,f;
System.out.println("enter a,b,c,d,e,f");
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
d=sc.nextInt();
e=sc.nextInt();
f=sc.nextInt();
LinearEquation le=new
LinearEquation(a,b,c,d,e,f);
if(le.isSolvable())
{
System.out.println("x="+le.getX()
+"y="+le.getY());
}
else
System.out.println("the equation has no
solution");

12. Modularize the design to package level and develop the code. A Vehicle registration
portal accepts the following data from Vehicle owners: a) Vehicle Number
b)Wheeler(either 2or4)-validate in setter c) Owner name d) Mobile. The Vehicle class
contains parameterised constructor, toString() methods. The vehicledemo class has a
main() method which reads and stores data of 5 vehicles and displays the menu with
following operations: a) Add data 2) Display data based on vehicle number.
(12.5Marks)

Package level Modularization:


- - > 2.5M

In vehicle class:
package First;
public class Vehicle
{
private String Vno;
private int wel;
private String own;
private long pno;

Vehicle(String no,int wh,String w,long p)


{
this.Vno=no;
this.wel=wh;
if (wh==2||wh==4)
this.wel=wh;
else
System.out.println("Please enter 2 or 4 in Wheeler");
this.own=w;
this.pno=p;
} - > 2M

public String getvno() { return this.Vno;}


public int getwel() { return this.wel;}
public String getwon(){ return this.own;}
public long getpno() { return this.pno;} - > 1M

public String toString()


{
String s="Vehicle Number =" + getvno();
s= s+ "\n2/3 Wheeler =" + getwel();
s= s+"\nName of the Owner =" + getwon();
s= s+"\nPhone Number = " + getpno();
return s;
} - > 2M
}

In VehicleDemo class:
package First;
import java.util.Scanner;

public class Vehicle_demo


{
public static Vehicle vhi[]=new Vehicle[5];
public static Scanner sr=new Scanner(System.in);

public static void Addvehicle()


{
for(int i=0;i<5;i++)
{
System.out.println("Enter Vehicle number and type of Wheeler");
String vno=sr.next();
int w=sr.nextInt();

System.out.println("Enter Owner name and Moblile Number");


String name=sr.next();
long ph=sr.nextLong();
vhi[i]= new Vehicle(vno,w,name,ph);
} - > 2M
}

public static void DisplayBasedOnVehicleNumber()


{
System.out.println("Enter the vehicle number");
String str=sr.next();
int pos=-1;
for(int i=0;i<5;i++)
{
if(vhi[i].getvno().equals(str))
{ pos=i;
break;
}
}
System.out.println(vhi[pos]);
} - > 2M

public static void main(String args[])


{
while(true)
{
System.out.println("*** Main Menu***");
System.out.println("1)Add Vehicle detail");
System.out.println("2)Display based on vehicle number");
System.out.println("3) Exit");
System.out.println("What operation you want to do?");
int cho=sr.nextInt();
switch(cho)
{
case 1:Addvehicle(); break;
case 2:DisplayBasedOnVehicleNumber();break;
case 3:System.exit(0);
default:System.out.println("Enter only 1,2,3");
}
} - > 1M
}

You might also like