Professional Documents
Culture Documents
M1086 Chapter 3
M1086 Chapter 3
M1086 Chapter 3
1) What are the objects and their properties involved in the solution below
questions:
A: blue colour is the property of the cars, cars are the object and the number of
blue cars is showing the quantity of blue cars running in Bengaluru. (Bengaluru
Refers to Class name here) As it is a specific city of India or showing specific class
name.
b) Find the city where in the road, number of blue cars is maximum?
A: city is the object since it specifies certain city name and road is the class name.
Again, Blue colour is the property of the cars, cars are the object and the number
of blue cars is showing the quantity of blue cars.
3) We have three options as: i) Tiger ii) White Tiger iii) 2 year old White Tiger
named Tipu. Which among these is a class and why?
A: Tiger and White Tiger are the classes A/q to definition of class(class is the
blueprint of an object) and 2 year old white tiger named Tipu is the object since it
refers to specific tiger i.e. 2 year old white tiger named Tipu.
A: While the default hashcode in the common implementations does use the
object address to generate it, it’s not reversible (and the address being used is an
implementation detail, not a specified functionality). Even if it were possible, the
address of an object can change during the runtime (whereas the default
hashcode doesn’t), so it wouldn’t be a viable approach even if there were a way
to reverse it
public Dog() {
numberOfLegs = 4;
hasOwner = false;
system.out.println(“Woof!”);
In that example, bark() and the variables numberOfLegs and hasOwner are
private, which means only the Dog class has access to them.
7) What is Encapsulation?
b) Providing and defining public setter and getter methods to modify and view
the variables values and access them outside the class only through getters and
setters.
Example -:
// save as Employee.java
this.name = name
//save as EncapTest.java
class EncapTest {
e.setname("sumaya");
system.out.println(e.getName());
A: If getters and setters are made private then the private getter/setter methods
provide a place for adding extra behavior or error checking code. They can
provide a place for logging state changes or access to the fields.
A: Like methods, constructors can have any of the access modifiers: public,
protected, private, or none (often called package or friendly). Unlike methods,
constructors can take only access modifiers. Therefore, constructors cannot be
abstract , final , native , static , or synchronized .
11) Can we achieve job of a constructor user defined method?
A: Constructor are used to create so that overload will be less on compiler and in
case of member function we need to call it by operators and memory
consumption is higher. A constructor’s purpose is to initialize an object with the
data provided to the constructor and, perhaps more importantly, ensure that the
object is in a consistent and valid state before control is passed back to the calling
program. The purpose of a constructor function is to initialize the data members
that belong to a particular object instance. For example, we have a class that
defines a Person, and specifies that instances have a numeric data member called
age. It’s the role of the constructor to initialize age to a valid initial value
(presumably zero in this case).
A: Object types are defined using classes For EgIf we’re building an application
that records information about dogs, for example, we might want to define a Dog
class so that we can create our own Dog objects, and record the name, weight
and breed of each dog:
As, the things an object knows about itself are its properties. They
represent an object’s state (the data), and each object of that type can have
unique values. So In the above figure: the Dog’s Name, Weight, breed are the
Properties and bark() is a function. A Dog class, for example, might have specific
name, weight and breed properties. The things an object can do are its functions.
They determine an object’s behaviour, and may use the object’s properties. The
Dog class, for example, might have a bark function.
THE CODE:
class Dog (val name: String, var weight: Int, val breed: String) {
THE CODE-:
import java.util.Scanner;
// Default constructor
public MyPet_1_lab7() {
this.breed = null;
this.name = null;
this.age = 0;
this.breed = a_breed;
this.name = a_name;
this.age = an_age;
this.inHumanYears = inHumanYears();
}
// Accessor methods for each instance variable
return this.breed;
return this.name;
return this.age;
this.breed = a_breed;
this.name = a_name;
this.age = an_age;
this.inHumanYears = inHumanYears();
return true;
if ((double)age >= 2 ){
return (inHumanYears);
else
inHumanYears = age*15;
return (inHumanYears);
return inHumanYears;
system.out.println(dog);
a) If we use the third constructor when we create the Dog Object the breed and
name fields are set to our desired values on one statement.
b)If we omit a constructor, the java compiler creates one for us internally. This
default constructor has no parameters and no code so it really does nothing.
16) A retail store wants to keep track of item id and item price of the five items
sold by them. Based on the item purchased by the customer, item price must be
identified and the computation of bill amount must be done as per the price and
quantity of the item purchased. Write a program to implement the above
scenario.
b) Search for the item purchased by the customer (assume it to be 5001) in the
item ids arrays and identify the respective price. Display and appropriate error
message if the item is not found in the array.
c) If the item is found i) Compute the bill amount as quantity purchased * price
identified. ii) display the bill id, customer id, purchase id, quantity purchased,
discount and bill amount.
d)Change the purchase item id value to 5006 and run the program again and
observe the result.
A: import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Product {
this.pname = pname;
this.qty = qty;
this.price = price;
this.totalPrice = totalPrice;
return pname;
return qty;
return price;
int quantity = 0;
do {
productName = scan.nextLine();
system.out.print("Quantity: ");
quantity = scan.nextInt();
price = scan.nextDouble();
overAllPrice += totalPrice;
choice = scan.next().charAt(0);
scan.nextLine();
Product.displayFormat();
// overall price
Employee
-empId:int
-empName:string
-empDesign:string
-empDept:string
+employee()
+getters()
+setters()
+employee(int, string, string, string)
Write a program, which creates an instance of employee class and sets the
values for all the attributes.
a) While setting value for empName, setEmpName() method should check for
NullPointer and display appropriate error message.
b) While setting value for empDesig, the designation must have any of the
following values: developer, tester, lead or manager. If none of these values in
matching, then setter method should display “Invalid designation” error
message.
c) While setting value for empDept, the Department must have any of the
following rules: TTH, RCM, Digital, DevOps. If none of these values is matching,
then setter method should display ‘Invalid Dept’ error message.
String name;
String Designation;
String Department;
this.name = name;
this.Designation = Designation;
this.Department = Department;
18) Develop a program that assists bookstore employees. For each book, the
program should track the book’s title, its price, its year of publication, and the
author’s name. Develop an appropriate Java Class. Create instances of the class
to represent these three books:
A: import java.util.*;
Name = Sc.nextLine();
Author = Sc.nextLine();
Publication = Sc.nextLine();
Cost = Sc.nextDouble();
void calculate() {
void display() {
b.input();
b.display();
b.calculate();
19) XYZ bank wants to maintain Customer details. It will register the customer
details whenever a person opens an account with the bank. Below is the
Customer class diagram:
customer
-custId : int
-custName : string
-custAdress : string
-accType : string
-custBalance : double
At times, the customer registration process changes, here are the guidelines:
1) Admin may register customer by filling only ID, name and address details.
import java.util.*;
int m, p;
string n, b, c;
double d,a;
system.out.println(" Enter the mobile no., name, DOB , billing address, city ,
res.phone no., Amount outstanding");
m = in.nextInt();
p = in.nextInt();
n = in.nextLine();
b = in.nextLine();
c = in.nextLine();
d = in.nextRead();
a = in.nextRead();
20) Implement below given class diagram, Invoke constructor and methods of
this class by creating appropriate object in main method.
Saving Account
-balance : double
-interestRate : int
-accountNo : int
+savingAccount()
+savingAccount(double, int,int)
+void WithDraw(double amount)
+void CalculateInterest()
A: import java.util.*;
class bank_account {
String name, type;
long account_number;
double balance_amount;
name = n;
account_number = a;
type = t;
balance_amount = b;
void deposit(double d) {
if(d > 0) {
balance_amount = balance_amount + d;
else
system.out.println("Invalid Amount");
void withdraw(double w) {
balance_amount = balance_amount - w;
}
else
system.out.println("Invalid Amount");
void display() {
String n, t;
long a;
double b;
n = Sc.nextLine();
a = Sc.nextLong();
t = Sc.nextLine();
system.out.print("Enter Balance : ");
b = Sc.nextDouble();
bank.display();
double d = Sc.nextDouble();
bank.diposit(d);
bank.display();
double w = Sc.nextDouble();
bank.withdraw(w);
bank.display();
21) A coffee shop would like to find out the customer feedback rating about its
services. The customer class shown below:
customer
-Name :string
-MobileNo : string
-feedbackRating : double
+customer()
+customer(string ,string,double)
+getters()
+setters()
Example: Assume that the shop will collect feedback from ‘N’ customers.
Following are the sample customer feedback values.
Customer 1: 3 out of 5
Customer 2: 4 out of 5
A: class ObjectArray {
obj[0].setData(1,2);
obj[1].setData(3,4);
obj[0].showData();
obj[1].showData();
}
class Customer {
int a; int b;
a=c; b=d;
b. As the thing an object knows about itself are its properties. They represent an
object’s state(the data), and each object of that type can have unique value.So In
the above figure: the Company’s name, employees, employee’s number, manager
and salary are the properties and
employees[],getName(),getEmployees(),addTeamMembe
r(),getTeamMember(),getSalary(),getemployeeNumber(),
getSalary(),getManager(),getLengthofContract() are the functions. A Company
class for example might have specific name, employees, employee’s number,
manager and salary properties. The Thing an object can do are its functions. They
determine an object’s behaviour, and may use object’s properties. The company
class, for example might have
employees[],getName(),getEmployees(),addTeamMembe
r(),getTeamMember(),getSalary(),getemployeeNumber(),
getSalary(),getManager(),getLengthofContract() functions.
THE CODE -:
Class Company(val empname: String, val employees: String, var Salary: Int, var
empnumber: Int, val Manager: String) {
….
c. As the thing an object knows about itself are its properties. They represent an
object’s state (the data), and each object of that type can have unique value. So In
the above figure: the Company’s name, employees, employee’s number, manager
and salary are the attributes and methods.
-studentid : int
--studentName : string
_markes : float
-secondchance : boolean
+ student(int,string,string)
+getstudentId() : int
+getStudentName():string
+getMarks() : int
+getScecondChance(): Boolean
+identifyMarks(float): void
+identifyMarks(float,float) : void
A: Class student {
};
The static data member is defined outside the class or variable or function name
as:
We can also initialize the static data member at the time of its definition as:
A: import java.util.Scanner;
import java.util.Arrays;
class Student {
name=tname;
marks=tmarks;total=ttotal;
name=tname;
return id;
return name;
return marks;
return total;
}
class SearchSort {
st[j]=st[j+1];
st[j+1]=temp;
st[j+1]=temp;
st[j]=st[j+1]; st[j+1]=temp;
for(int i=0;i<n;i++)
system.out.println(st[i]);
int flag=0;
for(int i=0;i<n;i++)
return -1;
int flag=0;
for(int i=0;i<n;i++)
{
if(st[i].getName().equalsIgnoreCase(key))
return i;
return -1;
int nos=0;
while(true){
switch(choice) {
case 1:
int tid=sc.nextInt();
String tname=sc.next();
for(int i=0;i<tmarks.length;i++)
tmarks[i]=sc.nextInt();
ttotal=ttotal+tmarks[i];
nos++; break;
case 2:
for(int i=0;i<nos;i++)
system.out.println(st[i]);
break;
case 3:
system.out.println("enter id to search");
int key=sc.nextInt();
if(index == -1)
else
system.out.println("search element found at index " + index +" student details
are " +st[index]);
break;
case 4:
String key1=sc.next();
index = SearchSort.linearSearch(st,nos,key1);
if(index == -1)
else
break;
case 5:
int key2=sc.nextInt();
index = SearchSort.linearSearch(st,nos,key2);
if(index == -1)
Else
break;
case 6:
SearchSort.sortById(st,nos);
break;
case 7:
SearchSort.sortByTotal(st,nos);
break;
case 8:
System.exit(0);
25) Create a method which accepts array of ‘Student’ objects and returns
Student object who has scored highest marks.
b) Name
c) Branch
d) Score
A: import java.util.*;
class Marks { public static void main() {
int i, max=0;
for(i=0;imax)
x=name[i]; max=a[i];
e) EXIT
A: import java.util.Scanner;
class BankDetails {
accno = sc.next();
acc_type = sc.next();
name = sc.next();
balance = sc.nextLong();
}
amt = sc.nextLong();
long amt;
amt = sc.nextLong();
else
if (accno.equals(ac_no))
showAccount();
return (true);
return (false);
C[i].openAccount();
int ch;
do {
ch = sc.nextInt();
switch (ch) {
case 1:
C[i].showAccount();
break;
case 2:
found = C[i].search(ac_no);
if (found)
break;
if (!found)
break;
case 3:
ac_no = sc.next();
found = false;
found = C[i].search(ac_no);
if (found)
C[i].deposit()
break;
if (!found)
break;
case 4:
ac_no = sc.next();
found = false;
found = C[i].search(ac_no);
if (found)
{
C[i].withdrawal();
break;
if (!found)
break;
break;