Study Materials Available

Access summaries, videos, slides, infographics, mind maps and more

View Materials

Class As The Basis Of All Computation - Questions & Answers

EXERCISE

Part A : Objective Type Questions

1. The access modifier allows the user to control which members of a class can be accessed by the method of another class.
(a) access modifier     (b) access control     (c) control modifier     (d) none of these

2. public, private, default and protected are types of access modifier.
(a) excess modifier     (b) data type     (c) access modifier     (d) none of these

3. Class variables are declared only once for a class and all the objects of the class will share these data members.
(a) Instance variables     (b) Class variables     (c) Object variables     (d) None of these

4. Instance variables are data members of the object. So memory will be allocated separately for each object.
(a) Memory variables     (b) Class variables     (c) Object variables     (d) Instance variables

5. An object or instance of a class can be created using the new operator.
(a) new     (b) instance     (c) dot     (d) type

6. Instance variables and methods can be accessed outside the class using the object variable and the dot operator.
(a) new     (b) instance     (c) dot     (d) type

7. Private access modifier is used to access the members of a class within itself only.
(a) Public     (b) Private     (c) Protected     (d) Default

8. Which of the following is a composite data type?
(a) byte     (b) class     (c) short     (d) double
Answer: (b) class

9. The arguments that appear in a method definition are known as formal parameters.
(a) formal     (b) actual     (c) method     (d) none of these

10. Encapsulation is defined as the wrapping of data in a single unit.
(a) Polymorphism     (b) Encapsulation     (c) Inheritance     (d) none of these

11. Objects are real life entities that have a definite state and behaviour.
(a) Classes     (b) Objects     (c) Method     (d) Variables


Part B : Solved Questions

1. How can you declare a class? What are the main parts of a class declaration?
Ans. A class declaration begins with the keyword 'class' followed by the name of the class and encloses the class body between braces.
The class body contains fields and methods for the class.
Syntax :<access modifier> class class_name
{
    Field /Attribute declarations, Method declarations;
}


2. What is an access modifier? Name the access modifiers in Java.
Ans. The access modifier allows the user to control which member of a class can be accessed by the members of other class. The modifiers in Java are public, private, default and protected.

3. What is the difference between class variables and instance variables?
Ans. Class variables (static variables) are members of the class. So they are declared only once for a class. All the objects of the class will share the same class variables.
Instance variables are data members of the object. So memory will be allocated separately for each object.


4. How can you create an instance of a class?
Ans. An object can be created by using the new operator and a constructor. The new operator allocates memory space for an object. For example to create an instance of a class apple, the statement would be: apple al=new apple();

5. How are member variables declared?
Ans. Member variable/field declaration has three components:
1. Zero or more access modifiers such as public or private.
2. The data type of member variable such as int, float etc.
3. Valid member variables/fields name.


6. Write a class (Studentinfo) declaration with following specifications.
rollno       2 digits roll number
div          character class of the student
dob          date of birth.
Make a nested class to store day (dd), month (mm) and year (yy) of birth.
Ans.
public class Studentinfo
{
    private int rollno;
    private char div;
    private class dob     //Nested class
    {
        private int dd;
        private int mm;
        private int yy;
        public int returndate()
        {
            .........
        }
    }
    public int date()
    {
        .........
    }
}


7. What is the difference between an object and a class?
Ans. A class is a blueprint to create objects. It is an abstract entity that represents a set of objects that share common characteristics and behaviour.
Example: Fruits is a class. Whereas apple, mango, guava are different objects of the class Fruits.


8. Write a function prototype of the following:
A function Poschar which takes a string argument and a character argument and returns an integer value.
Ans. int Poschar (String str1, char ch1)

9. Give a prototype of a function search which receives a sentence sentnc and a word wrd and return 1 or 0.
Ans. int search (String sentnc, String wrd)

10. Define Instance Variable. Give an example of the same.
Or
Explain instance varibale. Give an example.
Ans. The variables that belong to an object are called instance variables.
Example: public class Fruits
{
    public int price; // Instance variable
    public char colour; // Instance varibale
}


11. Every object has its own copy of instance variable. Name the keyword that distinguishes between instance variables and class variables.
Ans. static

12. Assign the value of pie (i.e. 3.142) to a variable with requisite data type.
Ans. float pie = 3.14;

13. (a) Write one difference between primitive data type and a composite data type.
(b) Give one example of a primitive data type and a composite data type.
Ans.
(a) A primitive data type actually represents a single value like byte, short, char, int, long, float, double and boolean. A composite data type is one that is composed of the primitive data types and can represent a set of values referenced under a single name.
(b) Primitive data type—Byte, composite data type—class


14. Mention any two attributes required for class declaration.
Ans. Two attributes required for class declaration are:
(i) class name        (ii) access specifier of the class



PRACTICAL SESSION

1. Create a class Address that will store the address of a person. Decide the fields and write a method called displayAddress() that will display the complete address of the object. Create atleast two object instances and store data for the data fields.
Ans.
class Address {
    String name;
    String addressLine;
    String city;

    void displayAddress() {
        System.out.println("Name: " + name);
        System.out.println("Address: " + addressLine + ", " + city);
    }

    public static void main(String args[]) {
        Address obj1 = new Address();
        obj1.name = "Rahul";
        obj1.addressLine = "MG Road";
        obj1.city = "Delhi";
        Address obj2 = new Address();
        obj2.name = "Priya";
        obj2.addressLine = "FC Road";
        obj2.city = "Pune";
        obj1.displayAddress();
        obj2.displayAddress();
    }
}


2. Create a class Telephone_Bill which will store data like name, address, units consumed, cost per unit and total amount payable.
Ans.
class Telephone_Bill {
    String name;
    String address;
    int units_consumed;
    double cost_per_unit;
    double total_amount_payable;
}


3. Remember the ABC Stationery Shop problem that was dealt in the previous chapter. It needed a system to store the following information :
The details of the Product which stores information about items and cost.
The Sale is the daily process where the customers purchase items of certain quantity.
(a) Write the program to implement the following classes with the given data member and methods. Assume the data types according to the data given.
Class Product (Data members: itemcategory, itemname, itemcost | Methods: void displayDetails())
Class Sale (Data members: itemname, salequantity, amount | Methods: void calculateAmount(), void displaySaleDetails())
(b) Create two objects i.e. instances of class Product as Product1, Product2 and two instances of class Sale as Sale1, Sale2
(c) In the main program, initialise the objects with given data.
(d) Call the method displayDetails() by the objects of class Product.
(e) In the method calculateAmount(), the statement must be written as: amount= salequantity * itemcost ;
(f) Call the methods by objects of class Sale: calculateAmount(), displaySaleDetails()
Ans.
class Product {
    String itemcategory;
    String itemname;
    double itemcost;
    void displayDetails() {
        System.out.println("Category: " + itemcategory + " | Name: " + itemname + " | Cost: " + itemcost);
    }
}
class Sale {
    String itemname;
    int salequantity;
    double amount;
    void calculateAmount(double itemcost) {
        amount = salequantity * itemcost;
    }
    void displaySaleDetails() {
        System.out.println("Item: " + itemname + " | Qty: " + salequantity + " | Amount: " + amount);
    }
    public static void main(String args[]) {
        Product Product1 = new Product();
        Product1.itemcategory = "Pen"; Product1.itemname = "Parker"; Product1.itemcost = 200;
        Product Product2 = new Product();
        Product2.itemcategory = "Pencil"; Product2.itemname = "NatrajHB"; Product2.itemcost = 2;

        Sale Sale1 = new Sale();
        Sale1.itemname = "Parker"; Sale1.salequantity = 5; Sale1.calculateAmount(Product1.itemcost);
        Sale Sale2 = new Sale();
        Sale2.itemname = "NatrajHB"; Sale2.salequantity = 2; Sale2.calculateAmount(Product2.itemcost);

        Product1.displayDetails();
        Product2.displayDetails();
        Sale1.displaySaleDetails();
        Sale2.displaySaleDetails();
    }
}


4. Assume that a Java class Employee is already defined, write another Java class Emp.
The member variables of class Employee are :
integer variable code and double variable salary
(a) Create an object of the class Employee.
(b) Assign the code for this object as 2001.
(c) Assign the salary for the object as Rs. 20000.00
(d) Increment the salary by Rs. 5000
(e) Displays all the details of the Employee object.
Ans.
class Emp {
    public static void main(String args[]) {
        Employee obj = new Employee();
        obj.code = 2001;
        obj.salary = 20000.00;
        obj.salary = obj.salary + 5000;
        System.out.println("Code: " + obj.code + ", Salary: " + obj.salary);
    }
}


5. (i) Create a class cuboid with the following specifications:
Class Name: Cuboid
Member Variables: Length, Breadth, Height
Member Methods: (a) Calculatearea()—to calculate total surface area.
(b) Calculatevolume()—to calculate volume.
(ii) Write Java statements to create objects of the above class and access member variables.
Ans.
class Cuboid {
    double Length, Breadth, Height;
    void Calculatearea() {
        double area = 2 * (Length * Breadth + Breadth * Height + Height * Length);
        System.out.println("Surface Area: " + area);
    }
    void Calculatevolume() {
        double volume = Length * Breadth * Height;
        System.out.println("Volume: " + volume);
    }
    public static void main(String args[]) {
        Cuboid c1 = new Cuboid();
        c1.Length = 10;
        c1.Breadth = 5;
        c1.Height = 2;
        c1.Calculatearea();
        c1.Calculatevolume();
    }
}


6. Design a class student that contains member variable to store name, student and grade. The member method should display name of the student along with his/her grade and id.
Ans.
class Student {
    String name;
    int studentId;
    char grade;
    void displayDetails() {
        System.out.println("Name: " + name + ", ID: " + studentId + ", Grade: " + grade);
    }
}


7. (i) Design a class Account with the following specifications:
Class name: Account
Member variables: accountholdername, accountnumber and balance
Member methods: display balance()—to display the balance of the account.
(ii) Create objects of the class to access the member methods.
Ans.
class Account {
    String accountholdername;
    int accountnumber;
    double balance;
    void display_balance() {
        System.out.println("Account Balance: " + balance);
    }
    public static void main(String args[]) {
        Account acc = new Account();
        acc.accountholdername = "John Doe";
        acc.accountnumber = 100234;
        acc.balance = 5000.0;
        acc.display_balance();
    }
}



ASSIGNMENT

Part A : Very Short Questions

1. What is the implication of a public modifier?
Ans. A public modifier makes the class members globally accessible from anywhere in the program, including outside the class and package.

2. If you use the private modifier before a data member, what does it mean?
Ans. It means the data member is accessible only within the same class where it is defined.

3. How can you create a class data member?
Ans. By adding the keyword 'static' before the data member declaration.

4. How can you initialse a class member within a class?
Ans. A class member can be initialized dynamically via a constructor or method, or statically by assigning a value directly at the time of declaration.

5. Which operator is used to create an object instance?
Ans. The 'new' operator.

6. Which operator must be used to invoke the methods of an object?
Ans. The dot (.) operator.

7. Which return type must be used if the method does not return any value?
Ans. void

8. Classify the following as primitive or non- primitive data types:
(i) char (ii) arrays (iii) int (iv) classes
Ans. Primitive: (i) char, (iii) int. Non-primitive (Composite): (ii) arrays, (iv) classes.

9. Name the keyword which makes the variable as a class variable.
Ans. static


Part B : Short Questions

1. Write short notes on class declaration and method declaration.
Ans. Class declaration: It defines a new class using the 'class' keyword, acting as a blueprint for creating objects. It holds data members and member methods.
Method declaration: It defines a block of code to perform a specific operation, containing access modifiers, a return type, method name, and an optional parameter list.


2. Explain in brief about Access Modifiers in Java.
Ans. Access modifiers restrict the scope of a class or its members. Java has four access modifiers: public (accessible everywhere), private (accessible only within the same class), protected (accessible within the package and by subclasses), and default (accessible only within the same package).

3. How can you access data members and member methods through an object ?
Ans. By using the object reference variable followed by the dot (.) operator. Example: objectName.variableName or objectName.methodName().

4. When will you use instance variables and class variables in a class ?
Ans. Use instance variables when each object requires its own separate copy of the data. Use class variables (declared with static) when all objects should share a single, common copy of the data.

5. How can you access class variables outside the class ?
Ans. Class variables can be accessed outside the class using the class name itself, followed by the dot operator. Example: ClassName.variableName.

6. What will you write in the parameter list of a method, if the method actually does not take any parameters ?
Ans. You leave the parameter list empty, writing only empty parentheses ().

7. Design a class RailwayTicket with following description :
Instance variables/data members:
String name : To store the name of the customer
String coach : To store the type of coach customer wants to travel
long mobno : To store customer 's mobile number
int amt : To store basic amount of ticket
int totalamt : To store the amount to be paid after updating the original amount
Member methods:
void accept () — To take input for name, coach, mobile number and amount.
void update() — To update the amount as per the coach selected (extra amount to be added in the amount as follows)
Type of Coaches: First_AC (700), Second_AC (500), Third_AC (250), Sleeper (None)
void display() — To display all details of a customer such as name, coach, total amount and mobile number.
Write a main method to create an object of the class and all the above member methods.
Ans.
import java.util.Scanner;
class RailwayTicket {
    String name;
    String coach;
    long mobno;
    int amt;
    int totalamt;

    void accept() {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter name: "); name = sc.nextLine();
        System.out.print("Enter coach: "); coach = sc.nextLine();
        System.out.print("Enter mobile no: "); mobno = sc.nextLong();
        System.out.print("Enter basic amount: "); amt = sc.nextInt();
    }

    void update() {
        if(coach.equals("First_AC")) totalamt = amt + 700;
        else if(coach.equals("Second_AC")) totalamt = amt + 500;
        else if(coach.equals("Third_AC")) totalamt = amt + 250;
        else totalamt = amt;
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Coach: " + coach);
        System.out.println("Mobile No: " + mobno);
        System.out.println("Total Amount: " + totalamt);
    }

    public static void main(String args[]) {
        RailwayTicket ticket = new RailwayTicket();
        ticket.accept();
        ticket.update();
        ticket.display();
    }
}
Quick Navigation:
Quick Review Flashcards - Click to flip and test your knowledge!
Question
In Object-Oriented Programming, what term describes real-life entities that possess a definite state and behaviour?
Answer
Objects
Question
What characteristic of an object represents its data or value?
Answer
State
Question
What characteristic of an object represents its operation or working?
Answer
Behaviour
Question
Which object characteristic is used exclusively by the JVM to distinguish one object from another?
Answer
Identity
Question
Why is an object considered an 'instance' of a class?
Answer
It represents one specific entity based on the class's blueprint.
Question
What is the primary difference between a class and an object regarding the number of entities they represent?
Answer
An object represents a single entity, whereas a class represents an entire set of such objects.
Question
The process of showing only essential features while hiding complex, unnecessary details is called _____.
Answer
Abstraction
Question
What term is used for the process of 'data hiding' to protect sensitive information from the user?
Answer
Abstraction
Question
How are certain data limits enforced in Java to implement abstraction and data protection?
Answer
Through the use of access specifiers.
Question
The mechanism of wrapping data and member functions into a single unit is defined as _____.
Answer
Encapsulation
Question
Once a programme is encapsulated, how can the hidden data be accessed?
Answer
Only by the member functions of that specific class.
Question
What is a primary benefit of encapsulation regarding code maintenance?
Answer
It allows the programmer to maintain and change independent packages easily.
Question
A _____ is a blueprint for an object that contains all necessary data for a specific purpose.
Answer
Class
Question
Why is a Java class referred to as a 'factory of objects'?
Answer
It allows for the creation of an unlimited number of objects from one blueprint.
Question
What are the two main components that represent the state and behaviour of an object within a class?
Answer
Data members and member methods.
Question
Which keyword is mandatory when defining a new class in Java?
Answer
class
Question
In a class definition, what name is given to the variables that store data?
Answer
Data members (or instance variables).
Question
What is the collective term for the member variables and member methods located inside a class?
Answer
Body of the class.
Question
Which type of variable is declared only once for a class and shared among all its objects?
Answer
Class variable
Question
What keyword must be used to create a class variable?
Answer
static
Question
Variables created for every individual object of a class are known as _____.
Answer
Instance variables
Question
A _____ is a group of statements designed to perform a specific operation within a class.
Answer
Method
Question
In a method declaration, what does the keyword `void` signify?
Answer
The method does not return any value.
Question
Which part of a method declaration tells the compiler the accessibility of the method?
Answer
The modifier (e.g. public).
Question
The first line of a method's declaration is known as the method _____.
Answer
Prototype
Question
What two elements constitute a 'Method Signature' in Java?
Answer
The method name and the data types of its arguments.
Question
In the method prototype `public static int sum(int a, int b)`, what is the return type?
Answer
int
Question
What general term is used to signify that programme control is moving to execute a specific method construct?
Answer
Calling (or invoking) a method.
Question
Arguments that appear within a method's definition are called _____ parameters.
Answer
Formal
Question
Arguments that appear within a method call are called _____ parameters.
Answer
Actual
Question
Which access specifier allows a member to be accessed all over the programme?
Answer
Public
Question
Which access specifier restricts access to only within the class where the member is defined?
Answer
Private
Question
If no access specifier is explicitly mentioned, which level of access is applied by default?
Answer
Default (accessible only within the same package).
Question
The `protected` access specifier allows access to the same package and to _____ in other packages.
Answer
Subclasses
Question
Why can a single Java file have only one public class?
Answer
The public class name must exactly match the source file name.
Question
What are the three distinct parts of every object declaration?
Answer
Declaration, Instantiation, and Initialisation.
Question
Which Java keyword is used to allocate memory on the heap for a newly created object?
Answer
new
Question
In the statement `add a = new add(10, 20);`, which part represents the object initialisation?
Answer
The call to the constructor `add(10, 20)`.
Question
What syntax is used to reference a specific data member (variable) of an object?
Answer
objectReference.variableName
Question
What syntax is used to invoke a specific method of an object?
Answer
objectReference.methodName(arguments)
Question
Data types that represent a single value like `byte`, `int`, or `char` are known as _____ data types.
Answer
Primitive
Question
How many primitive data types are available in Java?
Answer
8
Question
A variable is a named memory location that can hold a piece of information _____.
Answer
Temporarily
Question
What is the difference between static and dynamic initialisation of a variable?
Answer
Static is a direct value assignment; dynamic results from an expression or method call.
Question
What is a 'Composite Data Type' in Java?
Answer
A type composed of primitive data types that represents a set of values under one name.
Question
Why is a class considered a composite data type?
Answer
It can contain multiple data members of various primitive or reference types.
Question
How is the total memory size of a composite data type determined?
Answer
It is the sum of the sizes of all its individual data members.
Question
Beside classes, what is another example of a composite data type in Java?
Answer
Array
Question
When a primitive data type is passed as a method argument, what does the method receive?
Answer
A copy of the original data.
Question
When a composite data type is passed as a method argument, what does the method receive?
Answer
A reference to the original data.
Question
If a method changes a composite data argument, how does it affect the original object?
Answer
The change will affect the original data because it is passed by reference.
Question
In the variable declaration `float pie = 3.14;`, what is the data type?
Answer
float
Question
Which part of the class contains the code required for the lifecycle of the created objects?
Answer
The class body.
Question
What is the primary purpose of creating methods in a programme?
Answer
To increase code usability and efficiency through modularity.
Question
What term describes the first line of a method that includes its access modifier, return type, and parameters?
Answer
Method Prototype
Question
If a method is defined as `int Poschar(String str1, char ch1)`, what is its Method Signature?
Answer
Poschar(String, char)
Question
Which operator is used to access the members of a class through an object instance?
Answer
The dot (.) operator.
Question
In Java, what occurs during the 'Instantiation' phase of object creation?
Answer
Memory is allocated for the new object on the heap using the `new` keyword.
Question
What is the memory size of the primitive type `int` in Java?
Answer
4 bytes
Question
What is the memory size of the primitive type `char` in Java?
Answer
2 bytes