Before Exercise must Watch this recorded video.
Question 1
Why is a class known as composite data type?
A composite data type is one which is composed with various primitive data types. A class can contain various primitive data types as its data members so it is known as a composite data type.
Question 2
Name the types of data used in a class.
Access Specifiers
Instance Variables
Class Variables
Local Variables
Constructors
Member Methods
Question 3
What is the purpose of the new operator?
The purpose of new operator is to instantiate an object of the class by dynamically allocating memory for it.
Question 4
Can a class be referred to as user defined data type?
Since a class is created by the user, it is also known as user defined data type.
Question 5
What is public access of a class?
When a class is declared with public access specifier it is said that the class is publicly accessible. A publicly accessible class is visible everywhere both within and outside its package. For example:
public class Example {
//Class definition
}
Question 6
How are private members of a class different from public members?
private members of a class are accessible only within the class in which they are declared. public members of the class are accessible both within and outside their class.
Question 7
Mention any two attributes required for class declaration.
Two attributes required for class declaration are the keyword 'class' and the name of the class.
Question 8
Explain instance variables. Give an example.
Variables that are declared inside a class without using the keyword 'static' and outside any member methods are termed instance variables. Each object of the class gets its own copy of instance variables. For example, in the below class:
class Cuboid {
private double height;
private double width;
private double depth;
private double volume;
public void input(int h, int w, int d) {
height = h;
width = w;
depth = d;
}
public void computeVolume() {
volume = height * width * depth;
System.out.println("Volume = " + volume);
}
}
height, width, depth and volume are instance variables.
Question 9
Explain any two types of access specifiers.
private — A data member or member method declared as private is only accessible inside the class in which it is declared.
public — A data member or member method declared as public is accessible inside as well as outside of the class in which it is declared.
Question 10
What is meant by private visibility of a method?
A member method of a class declared with private access specifier is said to have private visibility. Only other member methods of its class can call this method.
Question 1
How can class be used as user defined data types? Explain it with the help of an example.
Since a class is created by the user, it is also known as user defined data type. Take the example of the below class:
class Cuboid {
private double height;
private double width;
private double depth;
private double volume;
public void input(int h, int w, int d) {
height = h;
width = w;
depth = d;
}
public void computeVolume() {
volume = height * width * depth;
System.out.println("Volume = " + volume);
}
}
After defining this class, I can use Cuboid as a new data type and create variables of Cuboid type as shown below:
public static void main(String[] args) {
Cuboid c1 = new Cuboid();
c1.input(5, 10, 5);
c1.computeVolume();
Cuboid c2 = new Cuboid();
c2.input(2, 4, 9);
c2.computeVolume();
}
This is how we can use class as a user defined data type.
Question 2
Differentiate between built-in data types and user defined data types.
Built-In Data Types
Built-In Data Types are fundamental data types defined by Java language specification.
Sizes of Built-In Data Types are fixed.
Built-In Data Types are available in all parts of a Java program.
Built-In Data Types are independent components.
User Defined Data Types
User Defined Data Types are created by the user.
Sizes of User Defined data types depend upon their constituent members.
Availability of User Defined data types depends upon their scope.
User Defined data types are composed of Built-In Data Types.
Question 3
Which of the following declarations are illegal and why?
(a) class abc{...}
Legal
(b) public class NumberOfDaysWorked{...}
Legal
(c) private int x;
Legal
(d) private class abc{...}
Illegal — only 'public' or no access specifier are allowed for class declaration
(e) default key getkey(...)
Illegal — member method can't be explicitly marked 'default'
Question 4
Why can't every class be termed as user defined data type?
The classes that contain public static void main(String args[]) method are not considered as user defined data type. Only the classes that don't contain this method are called user defined data type. The presence of public static void main(String args[]) method in a class, converts it into a Java application so it is not considered as a user defined data type.
Question 5
Differentiate between static data members and non-static data members.
Static Data Members
They are declared using keyword 'static'.
All objects of a class share the same copy of Static data members.
They can be accessed using the class name or object.
Non-Static Data Members
They are declared without using keyword 'static'.
Each object of the class gets its own copy of Non-Static data members.
They can be accessed only through an object of the class.
Question 6
Differentiate between private and protected visibility modifiers.
Private members are only accessible inside the class in which they are defined and they cannot be inherited by derived classes. Protected members are also only accessible inside the class in which they are defined but they can be inherited by derived classes.
Question 7
Differentiate between instance variable and class variable.
Instance Variable
They are declared without using keyword 'static'.
Each object of the class gets its own copy of instance variables.
Each object of the class gets its own copy of instance variables.
Class Variable
They are declared using keyword 'static'.
All objects of a class share the same copy of class variables.
Each object of the class gets its own copy of instance variables.
They can be accessed using the class name or object.
Question 1
Write a class program to accept two numbers as instance variables. Use the following functions for the given purposes:
Class Name — Calculate
void inputdata() — to input both the values
void calculate() — to find sum and difference
void outputdata() — to print sum and difference of both the numbers
Use a main method to call the functions.
import java.util.Scanner;
public class Calculate
{
private int a;
private int b;
private int sum;
private int diff;
public void inputdata() {
Scanner in = new Scanner(System.in);
System.out.print("Enter first number: ");
a = in.nextInt();
System.out.print("Enter second number: ");
b = in.nextInt();
}
public void calculate() {
sum = a + b;
diff = a - b;
}
public void outputdata() {
System.out.println("Sum = " + sum);
System.out.println("Difference = " + diff);
}
public static void main(String args[]) {
Calculate obj = new Calculate();
obj.inputdata();
obj.calculate();
obj.outputdata();
}
}
Question 2
Write a class program with the following specifications:
Class Name — Triplet
Data Members — int a, b, c
Member Methods:
void getdata() — to accept three numbers
void findprint() — to check and display whether the numbers are Pythagorean Triplets or not.
import java.util.Scanner;
public class Triplet
{
private int a;
private int b;
private int c;
public void getdata() {
Scanner in = new Scanner(System.in);
System.out.print("Enter a: ");
a = in.nextInt();
System.out.print("Enter b: ");
b = in.nextInt();
System.out.print("Enter c: ");
c = in.nextInt();
}
public void findprint() {
if ((Math.pow(a, 2) + Math.pow(b, 2)) == Math.pow(c, 2))
System.out.print("Numbers are Pythagorean Triples");
else
System.out.print("Numbers are not Pythagorean Triples");
}
public static void main(String args[]) {
Triplet obj = new Triplet();
obj.getdata();
obj.findprint();
}
}
Question 3
import java.util.Scanner;
public class Employee
{
private int pan;
private String name;
private double taxincome;
private double tax;
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter pan number: ");
pan = in.nextInt();
in.nextLine();
System.out.print("Enter Name: ");
name = in.nextLine();
System.out.print("Enter taxable income: ");
taxincome = in.nextDouble();
}
public void cal() {
if (taxincome <= 250000)
tax = 0;
else if (taxincome <= 500000)
tax = (taxincome - 250000) * 0.1;
else if (taxincome <= 1000000)
tax = 30000 + ((taxincome - 500000) * 0.2);
else
tax = 50000 + ((taxincome - 1000000) * 0.3);
}
public void display() {
System.out.println("Pan Number\tName\tTax-Income\tTax");
System.out.println(pan + "\t" + name + "\t"
+ taxincome + "\t" + tax);
}
public static void main(String args[]) {
Employee obj = new Employee();
obj.input();
obj.cal();
obj.display();
}
}
Question 4
import java.util.Scanner;
public class Discount
{
private int cost;
private String name;
private double dc;
private double amt;
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter customer name: ");
name = in.nextLine();
System.out.print("Enter article cost: ");
cost = in.nextInt();
}
public void cal() {
if (cost <= 5000)
dc = 0;
else if (cost <= 10000)
dc = cost * 0.1;
else if (cost <= 15000)
dc = cost * 0.15;
else
dc = cost * 0.2;
amt = cost - dc;
}
public void display() {
System.out.println("Name of the customer\tDiscount\tAmount to be paid");
System.out.println(name + "\t" + dc + "\t" + amt);
}
public static void main(String args[]) {
Discount obj = new Discount();
obj.input();
obj.cal();
obj.display();
}
}
Question 5
import java.util.Scanner;
public class Telephone
{
private int prv;
private int pre;
private int call;
private String name;
private double amt;
private double total;
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter Customer Name: ");
name = in.nextLine();
System.out.print("Enter previous reading: ");
prv = in.nextInt();
System.out.print("Enter present reading: ");
pre = in.nextInt();
}
public void cal() {
call = pre - prv;
if (call <= 100)
amt = 0;
else if (call <= 200)
amt = (call - 100) * 0.9;
else if (call <= 400)
amt = (100 * 0.9) + (call - 200) * 0.8;
else
amt = (100 * 0.9) + (200 * 0.8) + ((call - 400) * 0.7);
total = amt + 180;
}
public void display() {
System.out.println("Name of the customer\tCalls made\tAmount to be paid");
System.out.println(name + "\t" + call + "\t" + total);
}
public static void main(String args[]) {
Telephone obj = new Telephone();
obj.input();
obj.cal();
obj.display();
}
}
Question 6
import java.util.Scanner;
public class Interest
{
private int p;
private float r;
private int t;
private double interest;
private double amt;
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter principal: ");
p = in.nextInt();
System.out.print("Enter time: ");
t = in.nextInt();
}
public void cal() {
if (t == 1)
r = 6.5f;
else if (t == 2)
r = 7.5f;
else if (t == 3)
r = 8.5f;
else
r = 9.5f;
interest = (p * r * t) / 100.0;
amt = p + interest;
}
public void display() {
System.out.println("Principal: " + p);
System.out.println("Interest: " + interest);
System.out.println("Amount Payable: " + amt);
}
public static void main(String args[]) {
Interest obj = new Interest();
obj.input();
obj.cal();
obj.display();
}
}
Question 7
import java.util.Scanner;
public class Library
{
private String name;
private int price;
private int day;
private double fine;
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter name of the book: ");
name = in.nextLine();
System.out.print("Enter printed price of the book: ");
price = in.nextInt();
System.out.print("For how many days fine needs to be paid: ");
day = in.nextInt();
}
public void cal() {
if (day <= 7)
fine = day * 0.25;
else if (day <= 15)
fine = (7 * 0.25) + ((day - 7) * 0.4);
else if (day <= 30)
fine = (7 * 0.25) + (8 * 0.4) + ((day - 15) * 0.6);
else
fine = (7 * 0.25) + (8 * 0.4) + (15 * 0.6) + ((day - 30) * 0.8);
}
public void display() {
System.out.println("Name of the book: " + name);
System.out.println("Fine to be paid: " + fine);
}
public static void main(String args[]) {
Library obj = new Library();
obj.input();
obj.cal();
obj.display();
}
}
Question 8
import java.util.Scanner;
public class Loan
{
private int time;
private double principal;
private double rate;
private double interest;
private double amt;
public void getdata() {
Scanner in = new Scanner(System.in);
System.out.print("Enter principal: ");
principal = in.nextInt();
System.out.print("Enter time: ");
time = in.nextInt();
}
public void calculate() {
if (time <= 5)
rate = 15.0;
else if (time <= 10)
rate = 12.0;
else
rate = 10.0;
interest = (principal * rate * time) / 100.0;
amt = principal + interest;
}
public void display() {
System.out.println("Interest = " + interest);
System.out.println("Amount Payable = " + amt);
}
public static void main(String args[]) {
Loan obj = new Loan();
obj.getdata();
obj.calculate();
obj.display();
}
}
Question 9
import java.util.Scanner;
public class Honda
{
private int type;
private int cost;
private double newCost;
public void gettype() {
Scanner in = new Scanner(System.in);
System.out.print("Enter type: ");
type = in.nextInt();
System.out.print("Enter cost: ");
cost = in.nextInt();
}
public void find() {
switch (type) {
case 2:
newCost = cost + (cost * 0.1);
break;
case 4:
newCost = cost + (cost * 0.12);
break;
default:
System.out.println("Incorrect type");
break;
}
}
public void printcost() {
System.out.println("Type: " + type);
System.out.println("New cost: " + newCost);
}
public static void main(String args[]) {
Honda obj = new Honda();
obj.gettype();
obj.find();
obj.printcost();
}
}
Question 10
import java.util.Scanner;
public class Mobike
{
private int bno;
private int phno;
private int days;
private int charge;
private String name;
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter Customer Name: ");
name = in.nextLine();
System.out.print("Enter Customer Phone Number: ");
phno = in.nextInt();
System.out.print("Enter Bike Number: ");
bno = in.nextInt();
System.out.print("Enter Number of Days: ");
days = in.nextInt();
}
public void compute() {
if (days <= 5)
charge = days * 500;
else if (days <= 10)
charge = (5 * 500) + ((days - 5) * 400);
else
charge = (5 * 500) + (5 * 400) + ((days - 10) * 200);
}
public void display() {
System.out.println("Bike No.\tPhone No.\tName\tNo. of days \tCharge");
System.out.println(bno + "\t" + phno + "\t" + name + "\t" + days
+ "\t" + charge);
}
public static void main(String args[]) {
Mobike obj = new Mobike();
obj.input();
obj.compute();
obj.display();
}
}
Question 11
import java.util.Scanner;
public class Caseconvert
{
private String str;
private String convStr;
public void getstr() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the string: ");
str = in.nextLine();
}
public void convert() {
char arr[] = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i)))
arr[i] = Character.toLowerCase(str.charAt(i));
else if (Character.isLowerCase(str.charAt(i)))
arr[i] = Character.toUpperCase(str.charAt(i));
else
arr[i] = str.charAt(i);
}
convStr = new String(arr);
}
public void display() {
System.out.println("Converted String:");
System.out.println(convStr);
}
public static void main(String args[]) {
Caseconvert obj = new Caseconvert();
obj.getstr();
obj.convert();
obj.display();
}
}
Question 12
import java.util.Scanner;
public class Vowel
{
private String s;
private int c;
public void getstr() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the string: ");
s = in.nextLine();
}
public void getvowel() {
String temp = s.toUpperCase();
c = 0;
for (int i = 0; i < temp.length(); i++) {
char ch = temp.charAt(i);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O'
|| ch == 'U')
c++;
}
}
public void display() {
System.out.println("No. of Vowels = " + c);
}
public static void main(String args[]) {
Vowel obj = new Vowel();
obj.getstr();
obj.getvowel();
obj.display();
}
}
Question 13
A bookseller maintains record of books belonging to the various publishers. He uses a class with the specifications given below:
Class name — Stock
Data Members:
String title — Contains title of the book
String author — Contains author name
String pub — Contains publisher's name
int noc — Number of copies
Member Methods:
void getdata() — To accept title, author, publisher's name and the number of copies.
void purchase(int t, String a, String p, int n) — To check the existence of the book in the stock by comparing total, author's and publisher's name. Also check whether noc >n or not. If yes, maintain the balance as noc-n, otherwise display book is not available or stock is under flowing.
Write a program to perform the task given above.
import java.util.Scanner;
public class Stock
{
private String title;
private String author;
private String pub;
private int noc;
public void getdata() {
Scanner in = new Scanner(System.in);
System.out.print("Enter book title: ");
title = in.nextLine();
System.out.print("Enter book author: ");
author = in.nextLine();
System.out.print("Enter book publisher: ");
pub = in.nextLine();
System.out.print("Enter no. of copies: ");
noc = in.nextInt();
}
public void purchase(String t, String a, String p, int n) {
if (title.equalsIgnoreCase(t) &&
author.equalsIgnoreCase(a) &&
pub.equalsIgnoreCase(p)) {
if (noc > n) {
noc -= n;
System.out.println("Updated noc = " + noc);
}
else {
System.out.println("Stock is under flowing");
}
}
else {
System.out.println("Book is not available");
}
}
public static void main(String args[]) {
Stock obj = new Stock();
obj.getdata();
obj.purchase("wings of fire", "APJ Abdul Kalam",
"universities press", 10);
obj.purchase("Ignited Minds", "APJ Abdul Kalam",
"Penguin", 5);
obj.purchase("wings of fire", "APJ Abdul Kalam",
"universities press", 20);
}
}
Question 14
Write a program by using class with the following specifications:
Class name — Characters
Data Members:
String str — To store the string
Member Methods:
void input (String st) — to assign st to str
void check_print() — to check and print the following:
(i) number of letters
(ii) number of digits
(iii) number of uppercase characters
(iv) number of lowercase characters
(v) number of special characters
import java.util.Scanner;
public class Characters
{
private String str;
public void input(String st) {
str = st;
}
public void check_print() {
int cLetters = 0, cDigits = 0, cUpper = 0, cLower = 0,
cSpecial = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z') {
cLetters++;
cUpper++;
}
else if (ch >= 'a' && ch <= 'z') {
cLetters++;
cLower++;
}
else if (ch >= '0' && ch <= '9') {
cDigits++;
}
else if (!Character.isWhitespace(ch)) {
cSpecial++;
}
}
System.out.println("Number of Letters: " + cLetters);
System.out.println("Number of Digits: " + cDigits);
System.out.println("Number of Upppercase Characters: "
+ cUpper);
System.out.println("Number of Lowercase Characters: "
+ cLower);
System.out.println("Number of Special Characters: "
+ cSpecial);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the string: ");
String s = in.nextLine();
Characters obj = new Characters();
obj.input(s);
obj.check_print();
}
}
Question 15
import java.util.Scanner;
public class Student
{
private String name;
private int eng;
private int hn;
private int mts;
private double total;
private double avg;
public void accept() {
Scanner in = new Scanner(System.in);
System.out.print("Enter student name: ");
name = in.nextLine();
System.out.print("Enter marks in English: ");
eng = in.nextInt();
System.out.print("Enter marks in Hindi: ");
hn = in.nextInt();
System.out.print("Enter marks in Maths: ");
mts = in.nextInt();
}
public void compute() {
total = eng + hn + mts;
avg = total / 3.0;
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Marks in English: " + eng);
System.out.println("Marks in Hindi: " + hn);
System.out.println("Marks in Maths: " + mts);
System.out.println("Total Marks: " + total);
System.out.println("Average Marks: " + avg);
}
public static void main(String args[]) {
Student obj = new Student();
obj.accept();
obj.compute();
obj.display();
}
}
Question 16
import java.util.Scanner;
public class ParkingLot
{
private int vno;
private int hours;
private double bill;
public void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter vehicle number: ");
vno = in.nextInt();
System.out.print("Enter hours: ");
hours = in.nextInt();
}
public void calculate() {
if (hours <= 1)
bill = 3;
else
bill = 3 + (hours - 1) * 1.5;
}
public void display() {
System.out.println("Vehicle number: " + vno);
System.out.println("Hours: " + hours);
System.out.println("Bill: " + bill);
}
public static void main(String args[]) {
ParkingLot obj = new ParkingLot();
obj.input();
obj.calculate();
obj.display();
}
}
Question 17
import java.util.Scanner;
public class ElectricityBill
{
private String n;
private int units;
private double bill;
public void accept() {
Scanner in = new Scanner(System.in);
System.out.print("Enter customer name: ");
n = in.nextLine();
System.out.print("Enter units consumed: ");
units = in.nextInt();
}
public void calculate() {
if (units <= 100)
bill = units * 2;
else if (units <= 300)
bill = 200 + (units - 100) * 3;
else {
double amt = 200 + 600 + (units - 300) * 5;
double surcharge = (amt * 2.5) / 100.0;
bill = amt + surcharge;
}
}
public void print() {
System.out.println("Name of the customer\t\t: " + n);
System.out.println("Number of units consumed\t: " + units);
System.out.println("Bill amount\t\t\t: " + bill);
}
public static void main(String args[]) {
ElectricityBill obj = new ElectricityBill();
obj.accept();
obj.calculate();
obj.print();
}
}
Question 18
import java.util.Scanner;
public class RailwayTicket
{
private String name;
private String coach;
private long mobno;
private int amt;
private int totalamt;
private void accept() {
Scanner in = new Scanner(System.in);
System.out.print("Enter name: ");
name = in.nextLine();
System.out.print("Enter coach: ");
coach = in.nextLine();
System.out.print("Enter mobile no: ");
mobno = in.nextLong();
System.out.print("Enter amount: ");
amt = in.nextInt();
}
private void update() {
if(coach.equalsIgnoreCase("First_AC"))
totalamt = amt + 700;
else if(coach.equalsIgnoreCase("Second_AC"))
totalamt = amt + 500;
else if(coach.equalsIgnoreCase("Third_AC"))
totalamt = amt + 250;
else if(coach.equalsIgnoreCase("Sleeper"))
totalamt = amt;
}
private void display() {
System.out.println("Name: " + name);
System.out.println("Coach: " + coach);
System.out.println("Total Amount: " + totalamt);
System.out.println("Mobile number: " + mobno);
}
public static void main(String args[]) {
RailwayTicket obj = new RailwayTicket();
obj.accept();
obj.update();
obj.display();
}
}