2ND Ia QP Pattern Solution
2ND Ia QP Pattern Solution
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"
*/
/*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
/*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;
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.
/*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
*/