0% found this document useful (0 votes)
23 views13 pages

2ND Ia QP Pattern Solution

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

2ND Ia QP Pattern Solution

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

Q No.

Question and Answer

1. Implement a Java code to find the factorial of a given number using recursion
technique.
Answer:
Recursion: Recursion is the process of defining something in terms of itself.
Recursion is the attribute that allows a method to call itself.
A method that calls itself is said to be recursive.
Example:
/*Implement a Java code to find the factorial of a given number using recursion
technique.*/

import java.io.*;
class Factorial
{
//Recursive Method
int fact(int n)
{
if((n==0)||(n==1)) return 1;
else return(n*fact(n-1));
}
}
public class FactorialDemo
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int num=0;
Factorial f=new Factorial();
try
{
System.out.println("Enter a number");
num=Integer.parseInt(br.readLine());
System.out.println("fact("+num+")="+f.fact(num));
}
catch (NumberFormatException nfe)
{
System.out.println(nfe);
}

}
}
/*OUTPUT
Enter a number
6
fact(6)=720

Enter a number
6.0
java.lang.NumberFormatException: For input string: "6.0"
*/

2. & Demonstrate with a Java code the method overloading concept.


11. Answer:
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 (type signatures) are different.
When this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading. Method overloading is one of the ways that Java
supports polymorphism.
Example:
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// Overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}

public class Overload {


public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}

/*OUTPUT
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
*/
3. Implement a Java code to find the nth Fibonacci number using recursion technique.
Answer
Recursion: Recursion is the process of defining something in terms of itself.
Recursion is the attribute that allows a method to call itself.
A method that calls itself is said to be recursive.
Example:
import java.io.*;
class Fibonacci
{
//Recursive Method
int fib(int n)
{
if(n==0) return 0;
if(n==1) return 1;
return fib(n-2)+fib(n-1);
}
}
public class FibonacciDemo
{
public static void main(String[] args) throws IOException
{
Fibonacci f=new Fibonacci();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int n=0;
try
{
System.out.println("Enter nth term");
n=Integer.parseInt(br.readLine());
if(n<0)
{
System.out.println("Term should be >0");
return;
}
System.out.println(n+"(st/nd/rd/th) Fibonacci number is:
"+f.fib(n));

}
catch (NumberFormatException e)
{
System.out.println(e);
}
}
}
/*OUTPUT

Enter nth term


0
0(st/nd/rd/th) Fibonacci number is: 0

Enter nth term


1
1(st/nd/rd/th) Fibonacci number is: 1

Enter nth term


2
2(st/nd/rd/th) Fibonacci number is: 1

Enter nth term


3
3(st/nd/rd/th) Fibonacci number is: 2

Enter nth term


-9
Term should be >0
*/
4. Demonstrate with a Java code the constructor overloading concept.
Answer:
Answer:
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 (type signatures) are different.
When this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading. Method overloading is one of the ways that Java
supports polymorphism.
Example:
// Demonstrate Constructor overloading.

// Demonstrate method overloading.


class OverloadConstructorDemo {
OverloadConstructorDemo() {
System.out.println("No parameters");
}
// Overload OverloadConstructorDemo for one integer parameter.
OverloadConstructorDemo(int a) {
System.out.println("a: " + a);
}
// Overload OverloadConstructorDemo for two integer parameters.
OverloadConstructorDemo(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// Overload OverloadConstructorDemo for a double parameter
OverloadConstructorDemo(double a) {
System.out.println("double a: " + a);
}
}

public class OverloadConstructor {


public static void main(String args[]) {
double result;
// call all versions of OverloadConstructorDemo()
new OverloadConstructorDemo();
new OverloadConstructorDemo(10);
new OverloadConstructorDemo(10,20);
new OverloadConstructorDemo(9.99);
}
}

/*OUTPUT
No parameters
a: 10
a and b: 10 20
double a: 9.99
*/
5. & 12. Implement a Java code to demonstrate single level inheritance.
Answer:
Inheritance is one of the cornerstones of object-oriented programming because it
allows the creation of hierarchical classifications. Using inheritance, you can create a
general class that defines traits common to a set of related items. This class can then be
inherited by other, more specific classes, each adding those things that are unique to it.
In the terminology of Java, a class that is inherited is called a superclass. The class that
does the inheriting is called a subclass. Therefore, a subclass is a specialized version of
a superclass. It inherits all of the members defined by the superclass and adds its own,
unique elements.
Example:
//Demonstrate single-level inheritance
//Create a super-class
class College
{
void displayCollege()
{
System.out.println("Inside College");
}
}
//Create a sub-class
class Department extends College
{
void displayDepartment()
{
System.out.println("Inside Department");
}
}
//Driver class
class Tester
{
public static void main(String args[])
{
Department d=new Department();
d.displayCollege();
d.displayDepartment();
}
}
/*OUTPUT
Inside College
Inside Department
*/
6. & 13. Illustrate with a Java code how to call superclass constructors using super keyword
from sub-class.
Answer:
A subclass can call a constructor defined by its superclass by use of the following form
of super: super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the superclass.
super( ) must always be the first statement executed inside a subclass’
constructor.
Example:
class Box
{
private double width;
private double height;
private double depth;

Box(double width,double height,double depth)


{
this.width=width;
this.height=height;
this.depth=depth;
}
double volume()
{
return width*height*depth;
}
}
class BoxWeight extends Box
{
double weight;
BoxWeight(double width,double height,double depth,double weight)
{
//Calling super class constructor
super(width,height,depth);
this.weight=weight;
}
}
public class BoxDemo
{
public static void main(String[] args)
{
//System.out.println("Hello World!");
BoxWeight b1=new BoxWeight(3,4,3,0.99);
System.out.println("Box volume: "+b1.volume());
System.out.println("Box weight: "+b1.weight);
}
}
/*OUTPUT
Box volume: 36.0
Box weight: 0.99
*/
7. Illustrate with a Java code the method overriding concept.
Answer:
In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass. When an overridden method is called from
within its subclass, it will always refer to the version of that method defined by the
subclass. The version of the method defined by the superclass will be hidden.
Example:
//Demonstrate Method Overriding
// Method overriding.
class A {
int i, j;

A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
/*OUTPUT
k=3
*/
8. Illustrate with a table the Java Access Controls of a class member.
Answer:
The following table illustrate Access Controls:
Access Control: It is an important feature of Encapsulation. Through encapsulation,
you can control what parts of a program can access the members of a class. By
controlling access, you can prevent misuse.

How a member can be accessed is determined by the access modifier attached to its
declaration. Java’s access modifiers are public, private, and protected. Java also
defines a default access level.

Private: When a member of a class is specified as private, then that member can only
be accessed by other members of its class. private is a keyword.
Public: When a member of a class is modified by public, then that member can be
accessed by any other code. public is a keyword.
Protected: protected applies only when inheritance is involved. protected is a
keyword.
Default public: Is also called package private i.e. all members are visible within the
same package. There is no keyword.

9. Implement a Java code to demonstrate call by reference argument passing.


Answer:
There are two ways that a computer language can pass an argument to a subroutine:
 Call by value- All primitive types are passed by value.
 Call by reference- A reference to an argument is passed.
Example:
//Demonstrate call by reference argument passing
// Objects are passed through their references.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;//o.a=o.a*2;
o.b /= 2;//o.b=o.b/2;
}
}
class PassObjRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
}
}

/*OUTPUT
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
*/

10. Interpret with a Java code snippet the, static and final keywords in Java.
Answer:
1. Static keyword
 There will be times when you will want to define a class member that will be
used independently of any object of that class.
 Normally, a class member must be accessed only in conjunction with an object
of its class.
 However, it is possible to create a member that can be used by itself, without
reference to a specific instance.
 To create such a member, precede its declaration with the keyword static.
 When a member is declared static, it can be accessed before any objects of
its class are created, and without reference to any object.
 You can declare both methods and variables to be static.
 The most common example of a static member is main( ). main( ) is declared as
static because it 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.

//Demonstrate static
public class StaticDemo
{
static int result;
int a=10,b=2;
//static method
static void display()
{
System.out.println("Result="+result);
}
//non-static method
void compute()
{
StaticDemo.result=a/b;
}
public static void main(String[] args)
{
StaticDemo obj=new StaticDemo();
obj.compute();
StaticDemo.display();
}
}
/*OUTPUT
Result=5
*/
2. final keyword
The keyword final has three uses. First, it can be used to create the equivalent of a
named constant. The other two uses of final apply to inheritance.

A field can be declared as final. Doing so prevents its contents from being modified,
making it, essentially, a constant. This means that you must initialize a final field when
it is declared.
Example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;

In addition to fields, both method parameters and local variables can be declared
final.
 Declaring a parameter final prevents it from being changed within the method.
 Declaring a local variable final prevents it from being assigned a value more
than once.
The keyword final can also be applied to methods and classes:
 Using final to Prevent Overriding and
 Using final to Prevent Inheritance.
Example:
To prevent method overriding:
Class A{
void display(){}
final int compute(){}
}
Class B extends A
{
//cannot override the method compute
//can only override the method display
}
To prevent inheritance
final Class A{
void display(){}
int compute(){}
}
Class B extends A // class B cannot inherit class A
{
}

14. Illustrate with a Java code how to access superclass instance variable and method
from sub-class.
Answer:
class SuperClass
{
int a;
SuperClass(int a)
{
this.a=a;
}
void display()
{
System.out.println("Super class method called");
}
}
class SubClass extends SuperClass
{
int a;
//call super class constructor
SubClass(int a,int b)
{
super(a);
this.a=b;
}
void display()
{
//call super class instance variable
System.out.println("Super class variable a="+super.a);
//call super class method
super.display();
//call subclass instance variable
System.out.println("Sub-class variable a="+a);
//call subclass method
System.out.println("Sub-class method called");
}
}
public class SuperClassTester
{
public static void main(String[] args)
{
SubClass obj=new SubClass(20,10);
obj.display();
}
}
/*OUTPUT
Super class variable a=20
Super class method called
Sub-class variable a=10
Sub-class method called
*/

You might also like