You are on page 1of 27

CJP

49. State whether the following statements are true or false: (Nov-11)
(i) The elements in an array must be of primitive data types.
(ii) When invoking a constructor from a subclass, its super class’s no-arg constructor is
always invoked.
(iii) A protected data or method can be accessed by any class in the same package.

(iv) A method can change the length of an array passed as a parameter.


A->

i) False
ii) True
iii) True
iv) False

50. Explain inner class and working of concatenation operator + by giving examples.
A->
Inner class means one class which is a member of another class. There are
basically four types of inner classes in java.
1) Nested Inner class
2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes

String Concatenation by + (string concatenation) operator

Java string concatenation operator (+) is used to add strings.


For Example:

class TestStringConcatenation1{  
 public static void main(String args[]){  
String s="Sachin"+" Tendulkar";  
   System.out.println(s);//Sachin Tendulkar  
 }  
}

Output:Sachin Tendulkar
51. Give output of the following program: (Nov-11)
public class Test {
public static void main(String args[]) {
Count myCount = new Count();
int times=0;
for(int i=0;i<100;i++)
increment(myCount,times);
System.out.println("count is "+myCount.count);
System.out.println("times is "+times);
}
public static void increment(Count c,int times) {
c.count++;
times++;
}
}
class Count {
public int count;
Count(int c){ count=c; }
Count(){ count=1; }
}

A->
the output will be
count is 100
times is 06

52. Design a class named Fan to represent a fan. The class contains:
- Three constants named SLOW, MEDIUM and FAST with values 1, 2 and 3
to denote the fan speed.
- An int data field named speed that specifies the speed of the fan (default
SLOW).
- A boolean data field named f_on that specifies whether the fan is on
(default false).
- A double data field named radius that specifies the radius of the fan
(default 4).
- A data field named color that specifies the color of the fan (default blue).
- A no-arg constructor that creates a default fan.
- A parameterized constructor initializes the fan objects to given values.
- A method named display() will display description for the fan. If the fan is
on, the display() method displays speed, color and radius. If the fan is not on,
the method returns fan color and radius along with the message “fan is off”.
Write a test program that creates two Fan objects. One with default values
and the other with medium speed, radius 6, color brown, and turned on
status true. Display the descriptions for two created Fan objects.

A->
class Fan
{
public static final int SLOW=1,MEDIUM=2,FAST=3;
int speed;
boolean f_on;
double radius;
String color;

Fan()
{
speed=SLOW;
f_on=false;
radius=4;
color="blue";
}

Fan(int speed,double radius,String color,boolean f_on)


{
this.speed=speed;
this.radius=radius;
this.color=color;
this.f_on=f_on;
}

void display()
{
if(f_on==true)
{
System.out.println("Fan is on \n the speed is ="+speed+"\n the color is ="+color+"\n the
radius is ="+radius);
}
else
{
System.out.println("Fan is off \n the color of fan is ="+color+"\n the radius of fan is
="+radius);
}
}

public static void main(String [] args)


{
Fan obj = new Fan();
Fan obj1 = new Fan(MEDIUM,6,"brown",true);
obj.display();
obj1.display();
}
}

OUTPUT:

53. Define the Rectangle class that contains:


Two double fields x and y that specify the center of the rectangle, the
data field width and height , A no-arg constructor that creates the
default rectangle with (0,0) for (x,y) and 1 for both width and height.
2 A parameterized constructor creates a rectangle with the specified
x,y,height and width.
A method getArea() that returns the area of the rectangle.
A method getPerimeter() that returns the perimeter of the rectangle.
A method contains(double x, double y) that returns true if the specified
point (x,y) is inside this rectangle.
Write a test program that creates two rectangle objects. One with default
values and other with user specified values. Test all the methods of the class
for both the objects.

A->

class Rectangle
{
double x,y,height,width;

Rectangle()
{
x=0;
y=0;
height=1;
width=1;
}

Rectangle(double x,double y,double height,double width)


{
this.x=x;
this.y=y;
this.height=height;
this.width=width;
}

double getArea()
{
return height*width;
}

double getPerimeter()
{
return 2*(height+width);
}

boolean point(double x,double y)


{
double pointX = x;
double pointY = y;
if (pointX < (this.x + (this.width)) && pointX > (this.x - (this.width)) &&
           pointY < (this.y + (this.height)) && pointY > (this.y - (this.height)))
return true;
else
return false;
}

public static void main(String [] args)


{
Rectangle obj=new Rectangle();
Rectangle obj1=new Rectangle(5,2,10,50);
System.out.println("For default constructor");
System.out.println("Area = "+obj.getArea());
System.out.println("perimeter = "+obj.getPerimeter());
System.out.println("point inside rectangle ="+obj.point(0,0));
System.out.println("For default constructor");
System.out.println("Area = "+obj1.getArea());
System.out.println("perimeter = "+obj1.getPerimeter());
System.out.println("point inside rectangle ="+obj1.point(5,2));

}
}

OUTPUT:
54. It is required to compute SPI (semester performance index) of n
students of your college for their registered subjects in a semester. Declare
a class called student having following data members: id_no ,
no_of_subjects_registered, subject_code , subject_credits, grade_obtained
and spi.
- Define constructor and calculate_spi methods.
- Define main to instantiate an array for objects of class student to process
data of n students to be given as command line arguments.

A->
import java.util.Scanner;

class Student
{
int id_no,no_of_sub_registered;
int[] sub_code=new int[7];
int[] sub_credit=new int[7];
String[] grade_obtain=new String[10];
int[] grade_point=new int[10];
double spi;
int sum=0,sum1=0;

Student()
{
no_of_sub_registered=7;
sub_code[0]=150001;
sub_credit[0]=2;
sub_code[1]=150701;
sub_credit[1]=5;
sub_code[2]=150702;
sub_credit[2]=6;
sub_code[3]=150703;
sub_credit[3]=6;
sub_code[4]=150704;
sub_credit[4]=4;
sub_code[5]=150705;
sub_credit[5]=1;
sub_code[6]=150606;
sub_credit[6]=6;
}

void calculate_spi()
{

for(int i=0;i<=6;i++)
{

if(grade_obtain[i].equals("AA"))
grade_point[i]=10;
else if(grade_obtain[i].equals("AB"))
grade_point[i]=9;
else if(grade_obtain[i].equals("BB"))
grade_point[i]=8;
else if(grade_obtain[i].equals("BC"))
grade_point[i]=7;
else if(grade_obtain[i].equals("CC"))
grade_point[i]=6;
else if(grade_obtain[i].equals("CD"))
grade_point[i]=5;
else if(grade_obtain[i].equals("DD"))
grade_point[i]=4;
else if(grade_obtain[i].equals("FF"))
grade_point[i]=0;

this.sum = sum+(sub_credit[i]*grade_point[i]);
this.sum1 = sum1+sub_credit[i];

spi = sum/sum1;
System.out.println("your spi is = "+spi);
}

public static void main(String [] args)


{
Scanner jaimin=new Scanner(System.in);
Student obj=new Student();
int length =args.length;

if(length <= 0)
{
System.out.println("enter enrollment no list");
}

for(int k=0;k < length ; k++)


{
System.out.println("Enter details about grade obtain for each subject \n \n");
System.out.println("subject code \t subject credit \t obtain grade \n");
System.out.println("------------------------------------------------ \n");

for(int i=0;i<=6;i++)
{
System.out.print(obj.sub_code[i]+"\t \t \t"+ obj.sub_credit[i] +"\t \t \t");
String r=jaimin.nextLine();
obj.grade_obtain[i]=r;

obj.calculate_spi();
}
}
}

OUTPUT:
55. Declare a class called coordinate to represent 3 dimensional Cartesian
coordinates( x, y and z). Define following methods:
- constructor
- display, to print values of members
- add_coordinates, to add three such coordinate objects to produce a
resultant coordinate object. Generate and handle exception if x, y and
z coordinates of the result are zero.
- main, to show use of above methods.

A->
import java.lang.Exception;

class Cartesian extends Exception


{
double result;
double x,y,z;
Cartesian()
{

}
Cartesian(double x,double y,double z)
{
this.x=x;
this.y=y;
this.z=z;
}

void display()
{
System.out.println("value of x = "+x);
System.out.println("value of y = "+y);
System.out.println("value of z = "+z);
}

void add_coordinates() throws Cartesian


{
result=x+y+z;
System.out.println("the Addition of three coordinates is"+result);
if(result == 0)
{
throw new Cartesian();
}

public static void main(String [] args)


{
Cartesian obj=new Cartesian(5,5,-10);
obj.display();
try
{
obj.add_coordinates();
}
catch(Cartesian j)
{
System.out.println("Exception Generated \n try different coordiante values");
}

OUTPUT:

56. Declare a class called employee having employee_id and


employee_name as members. Extend class employee to have a subclass
called salary having designation and monthly_salary as members. Define
following:
- Required constructors
- A method to find and display all details of employees drawing salary
more than Rs. 20000/-.
- Method main for creating an array for storing these details given as
command line arguments and showing usage of above methods.

A->
import java.util.Scanner;
class Employee
{
String[] employee_id;
String[] employee_name;
}

class Salary extends Employee


{
String[] Designation;
double[] monthly_salary;

Salary(int j)
{
/*initialization of array */

employee_name=new String[j];
employee_id=new String[j];
Designation=new String[j];
monthly_salary= new double[j];

void display(int j)
{

System.out.println("---------------------------------------------------------------");
System.out.println("---------------------------------------------------------------");
System.out.println("\t Details of employee who have salary above 20000");
System.out.println("---------------------------------------------------------------");
System.out.println("---------------------------------------------------------------\n \n");

System.out.format("%-15s %-15s %-25s %-10s %n","employee id","employee


name","employee Designation","Monthly Salary");
System.out.println("----------------------------------------------------------------------------");
for(int i=0;i<j;i++)
{

if(monthly_salary[i]>=20000)
{
System.out.format("%-15s %-15s %-25s %-10s
%n",employee_id[i],employee_name[i],Designation[i],monthly_salary[i]);

}
}
}

public static void main(String [] args)


{
Scanner jaimin=new Scanner(System.in);
int length=args.length;

Salary obj = new Salary(length);

if(length==0)
{
System.out.println("please enter employee id");
}
for(int i=0;i<length;i++)
{
obj.employee_id[i]=args[i];

System.out.println("\n\n enter the details of \""+args[i]+"\" employee id");

System.out.print("\n name of employee -->");


obj.employee_name[i]=jaimin.next();

System.out.print("\n Designation of employee -->");


obj.Designation[i]=jaimin.next();

System.out.print("\nMonthly salary of employee -->");


obj.monthly_salary[i]=jaimin.nextDouble();

obj.display(length);
}
}

OUTPUT:
57. Define time class with hour and minute. Also define addition method to
add two time objects.
A->

58. Write a program to create circle class with area function to find area of
circle.
A->
class AreaOfCircle
{
   public static void main(String args[])
    {  
      
      Scanner s= new Scanner(System.in);
        
         System.out.println("Enter the radius:");
         double r= s.nextDouble();
         double  area=(22*r*r)/7 ;
         System.out.println("Area of Circle is: " + area);      
   }
}

OUTPUT:
Enter the radius:
7
Area of circle : 154
59. Use of Inheritance, Inheriting Data members and Methods, constructor in
inheritance, Multilevel Inheritance – method overriding

A->
Use of inheritance
o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Use of inheriting data member and methods

 The inherited fields can be used directly, just like any other fields.
 We can declare new fields in the subclass that are not in the
superclass.
 The inherited methods can be used directly as they are.
Use of constructor in inheritance

the constructor of a base class used to instantiate the objects of the base class and
the constructor of the derived class used to instantiate the object of the derived class.

Use of multilevel inheritance

With the help of multilevel inheritance we can extend a class in another class, which
extends another class

Use of method overriding

o Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.

o Method overriding is used for runtime polymorphism

60. Explain Dynamic Method Dispatch with example

A->
In Java, Dynamic method dispatch is a technique in which object refers to
superclass but at runtime, the object is constructed for subclass.

In the dynamic dispatch method technique, we can declare a super class


reference variable equal to sub class object like this:
SuperClass sc = new ChildClass(); // sc is super class reference variable
which is pointing to child class object.
Dynamic dispatch method is important because it is a process through which
Java implements runtime polymorphism. 
Example:
package dynamicMethodDispatchProgram;
public class A
{
void m1()
{
System.out.println("m1-A");
}
}
public class B extends A
{
// Overriding m1() method.
void m1()
{
System.out.println("m1-B");
}
}
public class C extends B
{
// Overriding m1() method.
void m1()
{
System.out.println("m1-C");
}
}
public class Test
{
public static void main(String[] args)
{
A a = new A();
a.m1();

B b = new B();
b.m1();

C c = new C();
c.m1();

A a2;
a2 = b;
a2.m1();
a2 = c;
a2.m1();
B b2 = c;
b2.m1();
}
}

OUTPUT: m1-A
m1-B
m1-C
m1-B
m1-C
m1-C

61. Differentiate Method Overloading and Method Overriding with example.


A->

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.

2) Method overloading is performed within Method overriding occurs in two classes that


class. have IS-A (inheritance) relationship.

3) In case of method overloading, parameter In case of method overriding, parameter must


must be different. be same.

4) Method overloading is the example Method overriding is the example of run time
of compile time polymorphism. polymorphism.

5) In java, method overloading can't be Return type must be same or covariant in


performed by changing return type of the method overriding.
method only. Return type can be same or
different in method overloading. But you
must have to change the parameter.
Example of method overloading
class MethodOverloadingEx{
static int add(int a, int b){return a+b;}
static int add(int a, int b, int c){return a+b+c;}
public static void main(String args[]) {
System.out.println(add(4, 6));
System.out.println(add(4, 6, 7));
}
}

OUTPUT:
//Here, add with two parameter method runs
10
// While here, add with three parameter method runs
17

Example of method overriding


class Animal{
void eat(){System.out.println("eating.");}
}
class Dog extends Animal{
void eat(){System.out.println("Dog is eating.");}
}
class MethodOverridingEx{
public static void main(String args[]) {
Dog d1=new Dog();
Animal a1=new Animal();
d1.eat();
a1.eat();
}
}
OUTPUT:
// Derived class method eat() runs
Dog is eating
// Base class method eat() runs
eating

62.Explain inheritance with its types and example


A->
i)Single inheritance
When a class extends another one class only then we  call it a single
inheritance. The below flow diagram shows that class B extends only one
class which is A. Here A is a parent class of B and B would be  a child
class of A.

ii) Multiple Inheritance

“Multiple Inheritance” refers to the concept of one class extending (Or


inherits) more than one base class. The inheritance we learnt earlier had the
concept of one base class or parent. The problem with “multiple inheritance” is
that the derived class will have to manage the dependency on two base
classes.
iii)Multilevel inheritance

Multilevel inheritance refers to a mechanism in OO technology where one


can inherit from a derived class, thereby making this derived class the base
class for the new class. As you can see in below flow diagram C is subclass or
child class of B and B is a child class of A. 

iv)Hierarchical inheritance

in such kind of inheritance one class is inherited by many sub classes. In


below example class B,C and D inherits the same class A. A is parent class
(or base class) of B,C & D.

v)Hybrid inheritance

In simple terms you can say that Hybrid inheritance is a combination


of Single and Multiple inheritance. A typical flow diagram would look like
below. A hybrid inheritance can be achieved in the java in a same way as
multiple inheritance Using interfaces. 
63. Define polymorphism with its need. Define and explain static and dynamic binding
using program.

A->

Polymorphism in Java is a concept by which we can perform a single action in


different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism means
many forms.

There are two types of polymorphism in Java: compile-time polymorphism and


runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.

Static binding : when type of the object is determined at compiled time, it is known
as static binding.

Dynamic bynding : when type of the object is determined at run-time, it is known as


dynamic binding.

Example of static binding

class Dog{  
private void eat(){System.out.println("dog is eating...");}    
 public static void main(String args[]){  
Dog d1=new Dog();  
 d1.eat();  
 }  

Example of dynamic binding
class Animal{  
 void eat(){System.out.println("animal is eating...");}  
}    
class Dog extends Animal{  
 void eat(){System.out.println("dog is eating...");}    
 public static void main(String args[]){  
 Animal a=new Dog();  
a.eat();  
 }  
}  

64. Handle multilevel constructors – super keyword, Stop Inheritance – Final keywords
A->

The super keyword in Java is a reference variable which is used to refer immediate


parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

The final keyword in java is used to restrict the user. The java final keyword can
be used in many context. Final can be:

1. variable

2. method

3. class

The final keyword can be applied with the variables, a final variable that have no
value it is called blank final variable or uninitialized final variable. It can be initialized
in the constructor only. The blank final variable can be static also which will be
initialized in the static block only.
65. Explain keywords - super and throws

A->

Super is a keyword of Java which refers to the immediate parent of a class and is used
inside the subclass method definition for calling a method defined in the superclass. A
superclass having methods as private cannot be called. Only the methods which are public
and protected can be called by the keyword super. It is also used by class constructors to
invoke constructors of its parent class.

Use of superclass

 Super variables refer to the variable of a variable of the parent class.


 Super() invokes the constructor of immediate parent class.
 Super refers to the method of the parent class.

The Java throws keyword is used to declare the exception information that


may occur during the program execution. It gives information about the
exception to the programmer. It is better to provide the exception handling
code so that the normal flow of program execution can be maintained.

66.Explain following with example:

i) super ii) final

A->

i)Super

Super is a keyword of Java which refers to the immediate parent of a


class and is used inside the subclass method definition for calling a
method defined in the superclass. A superclass having methods as
private cannot be called. Only the methods which are public and
protected can be called by the keyword super. It is also used by class
constructors to invoke constructors of its parent class.

Example:
class employee {
int wt = 8;
}

class clerk extends employee {


int wt = 10;  //work time
void display() {
System.out.println(super.wt); //will print work time of clerk
}

public static void main(String args[]) {


clerk c = new clerk();
c.display();
}

ii)final

Final is a keyword in Java that is used to restrict the user and can be used in many
respects. Final can be used with:

 Class
 Methods
 Variables

When a class is declared as final, it cannot be extended further. 

Example:

import java.util.*;
import java.lang.*;
import java.io.*;

class stud {
final int val;
stud() {
val = 60;
}
void method() {
System.out.println(val);
}
public static void main(String args[]) {
stud S1 = new  stud();
S1.method();
}

}
67. Explain the followings: (i) this, super, final.

A->

i) This

The this keyword refers to the current object in a method or constructor.

The most common use of the this keyword is to eliminate the confusion


between class attributes and parameters with the same name (because a
class attribute is shadowed by a method or constructor parameter).

ii) super

Super is a keyword of Java which refers to the immediate parent of a


class and is used inside the subclass method definition for calling a
method defined in the superclass. A superclass having methods as
private cannot be called. Only the methods which are public and
protected can be called by the keyword super. It is also used by class
constructors to invoke constructors of its parent class.

iii)final

Final is a keyword in Java that is used to restrict the user and can be used in many
respects. Final can be used with:

 Class
 Methods
 Variables

When a class is declared as final, it cannot be extended further

68. What are final class, final function and final variable in java? Explain with example.

A->

Final class

If you make any class as final, you cannot extend it.

Example:

final class Bike{}  
class Honda1 extends Bike{  
void run(){System.out.println("running safely with 100kmph");}      
public static void main(String args[]){  
Honda1 honda= new Honda1();  
  honda.run();  
}  
}

Final function
If you make any method as final, you cannot override it.

Example:
class Bike{  
final void run(){System.out.println("running");}  
}       
class Honda extends Bike{  
void run(){System.out.println("running safely with 100kmph");}       
public static void main(String args[]){  
Honda honda= new Honda();  
honda.run();  
}  
}

Final variable
If you make any variable as final, you cannot change the value of final variable(It
will be constant).

Example:
class Bike9{  
final int speedlimit=90;//final variable  
void run(){  
speedlimit=400;  
}  
public static void main(String args[]){  
Bike9 obj=new  Bike9();  
obj.run();  
}  
69.Explain Cosmic superclass and its methods.
A->

You might also like