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

2nd-cs

Uploaded by

wutibyku
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

2nd-cs

Uploaded by

wutibyku
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

SUMMER– 18

(b) Which are the restrictions present for static declared


methods? 4M
Ans:
 Restrictions on static variables :
1. Static variables become class variables.

2. They get initialized only once in the entire life time of the program.

3. They cannot be called by the object of the class in which they are defied.

4. A static method can operate only on static variables without objects otherwise non static
variables cannot be handled by a static method without using their respective class object.

(c) Define a class and object. Write syntax to create class and
object with an example.
Ans:
 Java is complete object oriented programming language. All program code and data reside in
object and class. Java classes create objects and objects will communicate between using
methods.
 Class:
 A „class‟ is a user defined data type.
Data and methods are encapsulated in
class.

 It is a template or a pattern which is


used to define its properties.

 Java is fully object oriented language.


All program code and data reside within
objects and classes.

1|Page
 Object:

1. It is a basic unit of Object Oriented Programming and represents the real life entities.
2. A typical Java program creates many objects, which as you know, interact by invoking
methods.
3. An object consists of state ,behavior and identity.
4. Syntax:

class_name object=new class_name();

5. Example:

class Student

int id; //field or data member or instance variable String name;

public static void main(String args[])

Student s1=new Student(); //creating an object of Student

System.out.println(s1.id); //accessing member through reference variable

System.out.println(s1.name);

(c) Enlist types of constructor. Explain any two with example.


Ans:
 Types of constructors in java:
1. Default constructor (no-arg constructor)

2. Parameterized constructor

3. copy constructor

 Default Constructor:

2|Page
A constructor is called "Default Constructor" when it doesn't have any parameter.

 Syntax of default constructor:

<class_name>()

 Example:

class Bike1

Bike1()

System.out.println("Bike is created");

public static void main(String args[])

Bike1 b=new Bike1();

 Parameterized Constructor:
1. A constructor which has a specific number of parameters is called parameterized
constructor.
2. Parameterized constructor is used to provide different values to the distinct objects.

 Example:

class Student4

3|Page
int id;

String name;

Student4(int i,String n)

id = i;

name = n;

void display()

System.out.println(id+" "+name);

public static void main(String args[])

Student4 s1 = new Student4(111,"Karan");

Student4 s2 = new Student4(222,"Aryan");

s1.display();

s2.display();

 Copy Constructor:
A copy constructor is used for copying the values of one object to another object.

 Example:

class Student6

int id;

4|Page
String name;

Student6(int i,String n)

id = i;

name = n;

Student6(Student6 s)

id = s.id;

name =s.name;

void display()

System.out.println(id+" "+name);}

public static void main(String args[]){

Student6 s1 = new Student6(111,"Karan");

Student6 s2 = new Student6(s1); //copy constructor called

s1.display();

s2.display();

Winter 2017

1. (A) (a) Explain inheritance and polymorphism features of


Java.
5|Page
Ans.:
 Inheritance:
1) Inheritance is the process by which one object acquires the properties of another object.
2) It supports the concept of hierarchical classification. Without the use of hierarchies, each
object would need to define all the characteristics explicitly.
3) By use of inheritance, an object need only define those qualities that make it unique within its
class.
4) It can inherit the general attributes from its parent. It is the inheritance mechanism that makes
it possible for one object to be a specific instance of a more general case.
5) For e.g.:
Parrot is a classification of Bird. Therefore Parrot is a subclass of Bird. Parrot inherits a lot
many features of the class Bird plus some additional features.
class Bird
{

}
class Parrot extends Bird
{

 Polymorphism:

1) It is a feature that allows one interface to be used for a general class of actions.
2) The specific action is determined by the exact nature of the situation.
3) By this concept it is possible to design a generic interface to a group of related activities.
For E.g:-
void add(int a, int b)
{
int sum = a+b;
System.out.println(sum);
}
void add(float a, float b)
{
float sum = a+b;
System.out.println(sum);
}
6|Page
(b) Write any two methods of array list class with their syntax.
Ans.
 booleanadd(E e):

Appends the specified element to the end of this list

 void add(int index, E element) :

Inserts the specified element at the specified position in this list.

 void clear():

Removes all of the elements from this list

 Objectclone():

Returns a shallow copy of this ArrayList instance

 booleancontains(Object o):

Returns true if this list contains the specified element.

 Eget(int index):

Returns the element at the specified position in this list.

 intindexOf(Object o):

Returns the index position of the element in the list

 booleanisEmpty() :

Returns true if the list is empty.

 intlastIndexOf(Object o):

Returns the index of the last occurrence of the object specified.

 boolean remove(Object o):

Removes the first occurrence of the object from the list if it is present.

 int size():

returns the number of elements in the list.

7|Page
(b) What is the multiple inheritance? Write a java program to
implement multiple inheritance.
Ans.:
 Multiple inheritance:
It is a feature in which a class inherits characteristics and features from more than one super class
or parent class.

Java cannot have more than one super class. Therefore interface is used to support multiple
inheritance in java. Interface specifies what a class must do but not how it is done.

Eg:

interface MyInterface

int strength=60;

void method1();

class MyBaseClass

String str;

MyBaseClass(String str)

this.str = str;

8|Page
}
public void display() {

System.out.println("Class: "+str);

public class MyClass extends MyBaseClass implements MyInterface

float total;

MyClass(String str, float t)

super(str);

total = t;

public void method1()

float avg = total/strength;

System.out.println("Avg is "+avg);

public static void main(String a[])

MyClass c = new MyClass("Fifth Sem",1300.0f);

c.display();

c.method1();

9|Page
(a) Describe following string class method with example:
(i) compareTo( )
(ii) equalsIgnoreCase( )
Ans.:

(i) compareTo( ):
Syntax:
intcompareTo(Object o)

OR
intcompareTo(String anotherString)

There are two variants of this method. First method compares this String to another Object and
second method compares two strings lexicographically.

Eg.

String str1 = "Strings are immutable";

String str2 = "Strings are immutable";

String str3 = "Integers are not immutable";

int result = str1.compareTo( str2 );

System.out.println(result);

result = str2.compareTo( str3 );

System.out.println(result);

(ii) equalsIgnoreCase( ):
public Boolean equalsIgnoreCase(String str)

This method compares the two given strings on the basis of content of the string irrespective of
case of the string.
10 | P a g e
Example:
String s1="javatpoint";

String s2="javatpoint";

String s3="JAVATPOINT";

String s4="python";

System.out.println(s1.equalsIgnoreCase(s2));//true because content and case both are same.

System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored.

System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same.

(c) Explain method overriding with suitable example.


(Note: Any other example shall be considered)
Ans.:
 Method Overriding in Java:
If subclass (child class) has the same method as declared in the parent

class, it is known as method overriding in java. If subclass provides

the specific implementation of the method that has been provided by

one of its parent class, it is known as method overriding.

Method overriding is used for runtime polymorphism.

 Example:
class Vehicle{

void run()

System.out.println("Vehicle is running");

11 | P a g e
}

class Bike2 extends Vehicle

void run()

System.out.println("Bike is running safely");

public static void main(String args[])

Bike2 obj = new Bike2();

obj.run();

(a) What is importance of super and this keyword in inheritance?


Illustrate with suitable example.
(Note: Any appropriate example shall be considered)
Ans.
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. Whenever a subclass needs to refer to its immediate superclass, it can do so by use
of the keyword super.

Super has two general forms. The first calls the super class constructor. The second is used to
access a member of the superclass that has been hidden by a member of a subclass.

super() is used to call base class constructer in derived class. Super is used to call overridden
method of base class or overridden data or evoked the overridden data in derived class.
12 | P a g e
E.g.: use of super()

class BoxWeightextends Box

BowWeight(int a ,intb,int c ,int d)

super(a,b,c) // will call base class constructer Box(int a, int b, int c)

weight=d // will assign value to derived class member weight.

E.g.: use of super.


Class Box

Box()

void show()

//definition of show

} //end of Box class

Class BoxWeight extends Box

BoxWeight()

void show() // method is overridden in derived

13 | P a g e
{

Super.show() // will call base class method

 The this Keyword


Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the
this keyword. this can be used inside any method to refer to the current object. That is, this is
always a reference to the object on which the method was invoked. You can use this anywhere a
reference to an object of the current class’ type is permitted. To better understand what this refers
to, consider the following version of Box( ): // A redundant use of this.

Box(double w, double h, double d)

this.width = w;

this.height = h;

this.depth =d;

 Instance Variable Hiding


when a local variable has the same name as an instance variable, the local variable hides the
instance variable. This is why width, height, and depth were not used as the names of the
parameters to the Box( ) constructor inside the Box class. If they had been, then width would have
referred to the formal parameter, hiding the instance variable width.

// Use this to resolve name-space collisions.

Box(double width, double height, double depth)

this.width = width;

this.height = height;

this.depth = depth;

}
14 | P a g e
(a) What is the use of wrapper classes in Java? Explain float
wrapper with its methods.
Ans.:
 Use :
Java provides several primitive data types. These include int (integer values), char (character),
double (doubles/decimal values), and byte (single-byte values). Sometimes the primitive data type
isn't enough and we may have to work with an integer object.

Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive.

 Float wrapper Class:


Float wrapper class is used to wrap primitive data type float value in an object.

 Methods :
1) floatValue( ) method:
It is used to return value of calling object as float.

2) isInfinite( ) method:
True if, value of calling object is infinite, otherwise false.

3) isNaN( ) method:
True if, value of calling object is not a number, otherwise false.

4) floatToIntBits( ) method: It is used to return IEEE


compatible single precision bit pattern for n.

5) hashCode(float value) method:


It is used to find hash code of calling object.

6) intBitsToFloat(int bits ) method:


It is used to return float of IEEE compatible single precision bit pattern for n.

7) parseFloat( ) method:
15 | P a g e
It is used to return float of a number in a string in radix 10.

8) toString(float f ) method:
It is used to find the string equivalent of a calling object.

9) valueOf(String s) method:
It is used to return Float object that has value specified by str.

10) compare(float f1, float f2) method:


It is used to compare values of two numbers. If it returns a negative value, then, n1<n2. If it returns
a positive value, then, n1>n2. If it returns 0, then both the numbers are equal.

11) compareTo (float f1) method:


It is used to check whether two numbers are equal, or less than or greater than each other. If the
value returned is less than 0 then, calling number is less than x. If the value returned is greater than
0 then, calling number is greater than x. If value returned is 0, then both numbers are equal.

12) equals(Object obj) method:


It is used to check whether two objects are equal. It returns true if objects are equal, otherwise
false.

(e) Describe access control specifiers with example.


Ans.:
 There are 4 types of java access modifiers:
1. private

2. default

3. protected

4. public

1) private access modifier:


The private access modifier is accessible only within class.

16 | P a g e
 Example:
class test

private int data=40;

private void show()

System.out.println("Hello java");

public class test1

public static void main(String args[])

testobj=new test();

System.out.println(obj.data);//Compile Time Error

obj.show();//Compile Time Error

In this example, we have created two classes test and test1. Test class contains private data
member and private method. We are accessing these private members from outside the class, so
there is compile time error

2) default access specifier :


If you don’t specify any access control specifier, it is default, i.e. it becomes implicit public and it
is accessible within the program anywhere.

17 | P a g e
 Example :
class test

int data=40; //default access

void show() // default access

System.out.println("Hello java");

public class test1

public static void main(String args[])

testobj=new test();

System.out.println(obj.data);

obj.show();

3) protected access specifier:


The protected access specifier is accessible within package and outside the package but through
inheritance only.

 Example :
test.java

package mypack;

public class test

{
18 | P a g e
protected void show()

System.out.println("Hello java");

//test1.java

Import mypack.test;

class test1 extends test

public static void main(String args[])

test1obj=new test1();

obj.show();

4) public access specifier:


The public access specifier is accessible everywhere. It has the widest scope among all other
modifiers.

 Example :
test.java

package mypack;

public class test

public void show()

System.out.println("Hello java");
19 | P a g e
}

//test1.java
import mypack.test;

class test1 ///inheritance not required

public static void main(String args[])

test1obj=new test1();

obj.show();

Summer 2017

(a) What is single level inheritance? Explain with suitable example.


(Note: Any appropriate program may be written).
Ans.:
1) Single level inheritance enables a derived class to inherit properties and behavior from a
single parent class.
2) It allows a derived class to inherit the properties and behavior of a base class, thus enabling
code reusability as well as adding new features to the existing code.
3) This makes the code much more elegant and less repetitive. Single level inheritance can be
represented by the following

20 | P a g e
 Example:
class SingleLevelInheritanceParent

int l;

SingleLevelInheritanceParent(int l)

this.l = l;

void area()

int a = l*l;

System.out.println("Area of square :"+a);

class SingleLevelInheritanceChild extends SingleLevelInheritanceParent

SingleLevelInheritanceChild(int l)

super(l);

void volume()

int v;

v= l*l*l;

System.out.println("Volume of the cube is "+v);

21 | P a g e
}

void area()

int a;

a = 6*l*l;

System.out.println("Total surface area of a cube is "+a);

class SingleLevelInheritance

public static void main(String args[])

SingleLevelInheritanceChild cube = new

SingleLevelInheritanceChild(2);

cube.volume();

cube.area();

(a) Explain the following methods of string class with syntax and
example:
(i) substring()
(ii)replace()
(Note: Any other example can be considered)
Ans.:
22 | P a g e
(i) substring():
 Syntax:

String substring(intstartindex)

startindex specifies the index at which the substring will begin.It will returns a copy of the
substring that begins at startindex and runs to the end of the invoking string

(OR)

String substring(intstartindex,intendindex)

Here startindex specifies the beginning index,andendindex specifies the stopping point. The string
returned all the characters from the beginning index, upto, but not including,the ending index.

 Example :

System.out.println(("Welcome”.substring(3)); //come

System.out.println(("Welcome”.substring(3,5));//co

(ii) replace():
This method returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.

 Syntax:

String replace(char oldChar, char newChar)

 Example:

String Str = new String("Welcome”);

System.out.println(Str.replace('o', 'T')); // WelcTme

(e) State three uses of final keyword.


Ans.:
 Uses of final keyword:
1. Prevent overriding of method:

23 | P a g e
To disallow a method to be overridden final can be used as a modifier at the start of declaration.
Methods written as final cannot be overridden.

e.g.

class test

final void disp() //prevents overidding

System.out.println(“In superclass”);

class test1 extends test

voiddisp()

// ERROR! Can't override

System.out.println("Illegal!");

2. Prevent inheritance:
Final can be used to even disallow the inheritance, to do this a class can be defined with final
modifier, declaring a class as final declares all its method as final

e.g.
final class test

void disp()

24 | P a g e
System.out.println(“In superclass”);

Class test1 extends test // error as class test is final

3. Declaring final variable:


Variable declared final, it is constant which will not and can not change.

final int FILE_NEW = 1;

(b) What is garbage collection in Java? Explain finalize method in Java.


(Note: Example optional)
Ans.:
 Garbage collection:
Garbage collection is a process in which the memory allocated to objects, which are no longer in
use can be freed for further use.

ynchronously when system is out of memory or asynchronously


when system is idle.

it is performed automatically. So it provides better memory management.

e invoked explicitly by writing statement

System.gc(); //will call garbage collector.

 Example:
public class A

int p;
25 | P a g e
A()

p = 0;

class Test

public static void main(String args[])

A a1= new A();

A a2= new A();

a1=a2; // it deallocates the memory of object a1

 Method used for Garbage Collection finalize:


called by garbage collector on an object when garbage
collection determines that there are no more reference to the object.

se of system resources or to perform other


cleanup.

ctions that are to be performed before an object is to be


destroyed, can be defined. Before an object is freed, the java run-time calls the finalize() method on

the object.

 General Form :
protected void finalize()

// finalization code here

26 | P a g e
}

(b) What is the use of ArrayList class? State any two methods with their
use from ArrayList.
Ans.:
 Use of ArrayList class:
1. ArrayList supports dynamic arrays that can grow as needed.

2. ArrayList is a variable-length array of object references. That is, an ArrayListcan dynamically


increase or decrease in size. Array lists are created with an initial size. When this size is exceeded,
the collection is automatically enlarged. When objects are removed, the array may be shrunk.

 Methods of ArrayList class :


1. void add(int index, Object element):
Inserts the specified element at the specified position index in this list.

Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index
>size()).

2.boolean add(Object o):


Appends the specified element to the end of this list.

booleanaddAll(Collection c)

Appends all of the elements in the specified collection to the end of this list, in the order that they
are returned by the specified collection's iterator.

Throws NullPointerException if the specified collection is null.

3. booleanaddAll(int index, Collection c):


Inserts all of the elements in the specified collection into this list,

starting at the specified position. Throws NullPointerException if

the specified collection is null.

4. void clear():
Removes all of the elements from this list.

27 | P a g e
5. boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this
list contains at least one element e such that (o==null ? e==null : o.equals(e)).

6. void ensureCapacity(intminCapacity)
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the
number of elements specified by the minimum capacity argument.

7. Object get(int index)


Returns the element at the specified position in this list.

Throws IndexOutOfBoundsException

if the specified index is is out of range (index < 0 || index >= size()).

8. intindexOf(Object o):
Returns the index in this list of the first occurrence of the specified element, or -1 if the List does
not contain this element.

9. intlastIndexOf(Object o):
Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not
contain this element.

10. Object remove(int index):


Removes the element at the specified position in this list. Throws

IndexOutOfBoundsException

if index out of range (index < 0 || index >= size()).

11. protected void removeRange(intfromIndex, inttoIndex):


Removes from this List all of the elements whose index is between fromIndex, inclusive and
toIndex, exclusive.

12. Object set(int index, Object element):


Replaces the element at the specified position in this list with the specified element. Throws
IndexOutOfBoundsException

if the specified index is is out of range (index < 0 || index >= size()).
28 | P a g e
13. int size():
Returns the number of elements in this list.

14. Object[] toArray():


Returns an array containing all of the elements in this list in the correct order. Throws
NullPointerException

if the specified array is null.

15. Object[] toArray(Object[] a):


Returns an array containing all of the elements in this list in the correct order; the runtime type of
the returned array is that of the specified array.

16.void trimToSize()
Trims the capacity of this ArrayList instance to be the list's current size.

17. Object clone():


Returns a shallow copy of this ArrayList.

29 | P a g e
30 | P a g e
31 | P a g e

You might also like