0% found this document useful (0 votes)
44 views

Module 2 QB

Uploaded by

shadow.range03
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Module 2 QB

Uploaded by

shadow.range03
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 17

Bapuji Educational Association ®

Bapuji Institute of Engineering and Technology, Davangere–577 004


Department of Artificial Intelligence &Machine Learning

Object Oriented Programming with


Course Title Course Code BCS306A
JAVA
Course
Bhagya S G Semester 3rd
Coordinator

Course Outcome Statements : After the successful completion of the course, the students will be able to
CO1 Demonstrate proficiency in writing simple programs involving branching and looping structures.
CO2 Design a class involving data members and methods for the given scenario.
CO3 Apply the concepts of inheritance and interfaces in solving real world problems.
CO4 Use the concept of packages and exception handling in solving complex problem.
CO5 Apply concepts of multithreading, autoboxing and enumerations in program development.

Module: 2 Question Bank Academic year: 2023-2024


Q. Marks RBT
Questions Level
CO
No.
1 Explain Class with an example? 5 L2 2
2 What are Constructors? Explain two types of Constructors. 6 L2 2
3 Explain static variable and static methods in JAVA. 6 L2 2
4 Write a program to perform Stack operation using proper class & methods 8 L3 2
5 Explain memory allocation and use of garbage collector in JAVA 6 L2 2
6 Explain use of this keyword in JAVA. 6 L2 2
7 Write a JAVA program demonstrating Method Overloading. 8 L3 2
Distinguish between Method Overloading and Method Overriding in Java, L2 2
8 8
with suitable example.
9 How do you overload constructor? Explain with a program 6 L3 2
10 Differentiate between constructors and Methods 5 L2 2
11 Write a Java program to demonstrate Recursion. 8 L3 2
12 Explain two types of argument passing in Java. 8 L2 2

Course Coordinator Coordinator Program Coordinator


Bhgaya S G DQAC HOD, Dept. of AI& ML
Module: 2 Question Bank with Solutions Academic year: 2023-2024
+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

Q. Marks RBT
Questions & Answers Level
CO
No.
1 Explain Class with an example? 5 L2 2
 A class is a template for an object, and an object is an instance of a
class.
 A class is declared by use of the class keyword.
 A simplified general form of a class definition is shown here:

class classname {
type instance-variable1;

type instance-variable2; // ...


type instance-variableN;

type methodname1(parameter-list) { // body of method


}

type methodname2(parameter-list) { // body of method


}

// ...
type methodnameN(parameter-list) { // body of method
}

 The data, or variables, defined within a class are called instance


variables. The code is contained within methods. Collectively, the
methods and variables defined within a class are called members of
the class. In most classes, the instance variables are acted upon and
accessed by the methods defined for that class. Thus, as a general
rule, it is the methods that determine how a class’ data can be used.
 Variables defined within a class are called instance variables
because each instance of the class (that is, each object of the class)
contains its own copy of these variables. Thus, the data for one
object is separate and unique from the data for another.

A Simple Class:Here is a class called Box that defines three instance


variables: width, height, and depth. Currently, Box does not contain any
methods (but some will be added soon).

Simple Example:

class Box {
double width;

+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

double height;
double depth;

class BoxDemo2 {

public static void main(String args[]) {


Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

// assign values to mybox1's instance variables


mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;

/* assign different values to mybox2's instance variables */


mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;

// compute volume of first box

vol = mybox1.width * mybox1.height * mybox1.depth;


System.out.println("Volume is " + vol);

// compute volume of second box

vol = mybox2.width * mybox2.height * mybox2.depth;


System.out.println("Volume is " + vol);
}

}
Output:
Volume is 3000.0
Volume is 162.0

As you can see, mybox1’s data is completely separate from the data
contained in mybox2.
What are Constructors? Explain two types of Constructors. 2
A constructor in Java is similar to a method that is invoked when an object of the
2 class is created. 6 L2

Unlike Java methods, a constructor has the same name as that of the class and
does not have any return type.
+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

For example,
class Test {
Test() {
// constructor body
}
}

Here, Test() is a constructor. It has the same name as that of the class and doesn't
have a return type.

Types of Constructor: constructors can be divided into 3 types:


1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor

1. Java No-Arg Constructors


Similar to methods, a Java constructor may or may not have any
parameters (arguments).
If a constructor does not accept any parameters, it is known as a no-
argument constructor. For example,
private Constructor() {
// body of the constructor
}
Example 2: Java private no-arg constructor
class MainNoArgs {

int i;

// constructor with no parameter


private MainNoArgs () {
i = 5;
System.out.println("Constructor is called");
}

public static void main(String[] args) {

// calling the constructor without any parameter


MainNoArgs obj = new MainNoArgs ();
System.out.println("Value of i: " + obj.i);
}
}
Output:
Constructor is called
Value of i: 5

In the above example, we have created a constructor Main(). Here, the


+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

constructor does not accept any parameters. Hence, it is known as a no-


arg constructor.

2. Java Parameterized Constructor


A Java constructor can also accept one or more parameters. Such
constructors are known as parameterized constructors (constructor with
parameters).
Example 4: Parameterized constructor
class MainPC {
String languages;

// constructor accepting single value


MainPC(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}

public static void main(String[] args) {

// call constructor by passing a single value


MainPC obj1 = new MainPC ("Java");
MainPC obj2 = new MainPC ("Python");
MainPC obj3 = new MainPC ("C");
}
}

Output:
Java Programming Language
Python Programming Language
C Programming Language

In the above example, we have created a constructor named Main().


Here, the constructor takes a single parameter. Notice the expression,

Main obj1 = new Main("Java");

Here, we are passing the single value to the constructor. Based on the
argument passed, the language variable is initialized inside the
constructor.
Explain static variable and static methods in JAVA. L2 2
 When a member is declared static, it can be accessed before any
3 6
objects of its class are created, and without reference to any object.
Both methods and variables can be declared as static. Example of
a static member is main( ). main( ) is declared as static because it
+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

must be called before any objects exist.


 Instance variables declared as static are, essentially, global
variables. When objects of its class are declared, no copy of a
static variable is made. Instead, all instances of the class share the
same static variable.
 Methods declared as static have several restrictions:
 They can only directly call other static methods of their
class.
 They can only directly access static variables of their class.
 They cannot refer to this or super in any way
 If you need to do computation in order to initialize your static
variables, you can declare a static block that gets executed exactly
once, when the class is first loaded. The following example shows
a class that has a static method, some static variables.
//Demonstrate static variables, methods, and blocks.
class UseStatic {

static int a = 3; static int b;

static void meth (int x) {


System .out .println ("x =" + x);
System .out .println ("a = " + a);
System .out .println ("b = " + b);
}

static {
System .out .println ("Static block initialized.");
b = a*4;
}
public static void main (String args[]) {
meth (42);
}
}
Output:
Static block initialized.
x =42
a=3
b = 12
Write a program to perform Stack operation using proper class & L3 2
methods
4 8
import java.util.ArrayList;
import java.util.EmptyStackException;
+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

import java.util.List;

class Stack {
private List<Integer> items;

public Stack() {
this.items = new ArrayList<>();
}

public boolean isEmpty() {


return items.isEmpty();
}

public void push(int item) {


items.add(item);
}

public int pop() {


if (isEmpty()) {
throw new EmptyStackException();
}
int poppedItem = items.remove(items.size() - 1);
return poppedItem;
}

public int peek() {


if (isEmpty()) {
throw new EmptyStackException();
}
return items.get(items.size() - 1);
}

public int size() {


return items.size();
}
}

public class Main {


public static void main(String[] args) {
Stack stack = new Stack();

System.out.println("Is the stack empty? " + stack.isEmpty());

+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

stack.push(1);
stack.push(2);
stack.push(3);

System.out.println("Top element: " + stack.peek());


System.out.println("Stack size: " + stack.size());
int poppedItem = stack.pop();
System.out.println("Popped item: " + poppedItem);
System.out.println("Stack size after pop: " + stack.size());

System.out.println("Is the stack empty now? " + stack.isEmpty());


}
}
Explain memory allocation and use of garbage collector in JAVA L2 2
Memory allocation and use of garbage collector in JAVA
 Garbage Collection is process of reclaiming the runtime unused
memory automatically. In other words, it is a way to destroy the
unused objects.
 It makes java memory efficient because garbage collector removes
the unreferenced objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM)
so we don't need to make extra efforts.
 How can an object be unreferenced?
1) By nulling a reference:
Employee e=new Employee();
e=null;
5 2) By assigning a reference to another: 6
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2; //now the first object referred by e1 is available for
garbage collection
3) By anonymous object:
new Employee();
 The finalize() method is invoked each time before the object is
garbage collected. This method can be used to perform cleanup
processing. This method is defined in Object class as:
protected void finalize(){}
 Note: The Garbage collector of JVM collects only those objects
that are created by new keyword. So if you have created any
object without new, you can use finalize method to perform
cleanup processing (destroying remaining objects).
 The gc() method is used to invoke the garbage collector to perform
+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

cleanup processing. The gc() is found in System and Runtime


classes.
public static void gc(){}
 Note: Garbage collection is performed by a daemon thread called
Garbage Collector(GC). This thread calls the finalize() method
before object is garbage collected.
 Simple Example:
public class TestGarbage1{
public void finalize() {
System.out.println("object is garbage collected");
}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected
Explain use of this keyword in JAVA. L2 2

The this keyword

this is a keyword in Java which is used as a reference to the object of the current
class, with in an instance method or a constructor. Using this you can refer the
members of a class such as constructors, variables and methods.
Note − The keyword this is used only within instance methods or constructors

6 6

In general, the keyword this is used to −

 Differentiate the instance variables from local variables if they have


same names, within a constructor or a method.
class Student {
int age;
Student(int age) {
this.age = age;
}
+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

}
 Call one type of constructor (parametrized constructor or default) from
other in a class. It is known as explicit constructor invocation.
class Student {
int age
Student() {
this(20);
}

Student(int age) {
this.age = age;
}
}

Example

Here is an example that uses this keyword to access the members of a class. Copy
and paste the following program in a file with the name, This_Example.java.

public class This_Example {


// Instance variable num
int num = 10;

This_Example() {
System.out.println("This is an example program on keyword
this");
}

This_Example(int num) {
// Invoking the default constructor
this();

// Assigning the local variable <i>num</i> to the instance


variable <i>num</i>
this.num = num;
}

public void greet() {


System.out.println("Hi Welcome to Tutorialspoint");
}

public void print() {


// Local variable num
int num = 20;

// Printing the local variable


System.out.println("value of local variable num is : "+num);

// Printing the instance variable


System.out.println("value of instance variable num is :
+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

"+this.num);

// Invoking the greet method of a class


this.greet();
}

public static void main(String[] args) {


// Instantiating the class
This_Example obj1 = new This_Example();

// Invoking the print method


obj1.print();

// Passing a new value to the num variable through parametrized


constructor
This_Example obj2 = new This_Example(30);

// Invoking the print method again


obj2.print();
}
}

Output:
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint.
Write a JAVA program demonstrating Method Overloading. L3 2
• In Java, it is possible to define two or more methods within the
same class that share the same name, as long as their parameter
declarations are different, methods are said to be overloaded, and
the process is referred to as method overloading.
7  When an overloaded method is invoked, Java uses the type and/or 8
number of arguments as its guide to determine which version of
the overloaded method to actually call. Thus, overloaded methods
must differ in the type and/or number of their parameters. While
overloaded methods may have different return types, the return
type alone is insufficient to distinguish two versions of a method.
 When Java encounters a call to an overloaded method, it simply
+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

executes the version of the method whose parameters match the


arguments used in the call.

Output:
No parameters a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Distinguish between Method Overloading and Method Overriding in L2 2
8 8
Java, with suitable example.

+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

Method Overloading Method Overriding

Method overloading is a Method overriding is a run-time


compile-time polymorphism. polymorphism.

Method overriding is used to


Method overloading helps to grant the specific
increase the readability of the implementation of the method
program. which is already provided by its
parent class or superclass.

It is performed in two classes


It occurs within the class.
with inheritance relationships.

Method overloading may or Method overriding always


may not require inheritance. needs inheritance.

In method overloading, In method overriding, methods


methods must have the same must have the same name and
name and different signatures. same signature.

In method overloading, the


In method overriding, the return
return type can or can not be
type must be the same or co-
the same, but we just have to
variant.
change the parameter.

Static binding is being used for Dynamic binding is being used


overloaded methods. for overriding methods.

It gives better performance. The


Poor Performance due to reason behind this is that the
compile time polymorphism. binding of overridden methods
is being done at runtime.

Private and final methods can Private and final methods can’t
+ be overloaded. be overridden.
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

How do you overload constructor? Explain with a program L3 2


Constructors Overloading in Java
Similar to Java method overloading, we can also create two or more
constructors with different parameters. This is called constructors
overloading.

Example 6: Java Constructor Overloading

class Main {

String language;

// constructor with no parameter


Main() {
this.language = "Java";
}

// constructor with a single parameter


Main(String language) {
this.language = language;
}
9 6
public void getName() {
System.out.println("Programming Langauage: " + this.language);
}

public static void main(String[] args) {

// call constructor with no parameter


Main obj1 = new Main();

// call constructor with a single parameter


Main obj2 = new Main("Python");

obj1.getName();
obj2.getName();
}
}

Output:
Programming Language: Java
Programming Language: Python

In the above example, we have two constructors: Main() and Main(String


language). Here, both the constructor initialize the value of the variable

+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

language with different values.

Based on the parameter passed during object creation, different


constructors are called and different values are assigned.

It is also possible to call one constructor from another constructor. To


learn more, visit Java Call One Constructor from Another.
Differentiate between constructors and Methods L2 2
10 5

Write a Java program to demonstrate Recursion. L3 2


• Recursion is the process of defining something in terms of itself.
As it relates to Java programming, recursion is the attribute that
allows a method to call itself. A method that calls itself is said to
be recursive.
• The classic example of recursion is the computation of the
factorial of a number.

11 8

 The factorial of a number N is the product of all the whole


numbers between 1 and N. For example, 3 factorial is 1 × 2 × 3 ×,
or 6. Here is how a factorial can be computed by use of a recursive
method:
 Output:

+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

 Explanation:
 Here is how it works. When fact( ) is called with an
argument of 1, the function returns 1; otherwise, it returns
the product of fact(n–1)*n. To evaluate this expression,
fact( ) is called with n–1. This process repeats until n
equals 1 and the calls to the method begin returning.
 When you compute factorial of 3, the first call to fact( )
will cause a second call to be made with an argument of 2.
This invocation will cause fact( ) to be called a third time
with an argument of 1. This call will return 1, which is then
multiplied by 2 (the value of n in the second invocation).
This result (which is 2) is then returned to the original
invocation of fact( ) and multiplied by 3 (the original value
of n). This yields the answer,6. You might find it
interesting to insert println( ) statements into fact( ), which
will show at what level each call is and what the
intermediate answers are.
Explain two types of argument passing in Java. L2 2
There are two ways of passing an argument to a subroutine.
1. call-by-value: This approach copies the value of an argument into the
formal parameter of the subroutine. Therefore, changes made to the
parameter of the subroutine have no effect on the argument.

12 8

+
Bapuji Educational Association ®
Bapuji Institute of Engineering and Technology, Davangere–577 004
Department of Artificial Intelligence &Machine Learning

Output
a and b before call: 15 20
a and b after call: 15 20
 the operations that occur inside meth( ) have no effect on the
values of a and b used in the call; their values here did not change
to 30 and 10.
2. call-by-reference: In this approach, a reference to an argument (not the
value of the argument) is passed to the parameter. Inside the subroutine,
this reference is used to access the actual argument specified in the call.
This means that changes made to the parameter will affect the argument
used to call the subroutine.

Output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10

 As you can see, in this case, the actions inside meth( ) have
affected the object used as an argument.

You might also like