You are on page 1of 30

GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 1








O OO OP PJ J ( (O Ob bj je ec ct t O Or ri ie en nt te ed d P Pr ro og gr ra am mm mi in ng g J Ja av va a) )
G
G
T
T
U
U
E
E
X
X
A
A
M
M
P
P
A
A
P
P
E
E
R
R
S
S
O
O
L
L
U
U
T
T
I
I
O
O
N
N

Y YE EA AR R: : 2 20 01 10 0 ( (D De ec c) )
B By y P Pa ar re es sh h B Bh ha av vs sa ar r
0 09 93 32 28 85 57 76 62 20 00 0 / / b bh ha av vs sa ar r. .e er r@ @g gm ma ai il l. .c co om m
w ww ww w. .j j2 2e ee et tr ra ai in ne er r. .c co om m








GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 2

Q . 1 (a) Differentiate between constructor and method of class. Define
method overloading and its purpose. Write a program to demonstrate
constructor overloading.
Methods are functional units of the class. Each method signature includes -
1. name (e.g. add)
2. return type (e.g. void
3. parameters (e.g. int x, int y)
Below mentioned are some of the examples of the methods.
1. int test (int x, int y) { < }
2. void run (double speed) { < }
There are three characteristics of constructor. (diff between constructor and
method)
1. Constructor does not have return type.
2. Constructor does not have name MUST be same as class name.
3. Constructors are called only at the time of the object creation.
Below mentioned is constructor example
class Student {
int rollno;
Student(int rollno){
this.rollno = rollno;
}
}
Method overloading supports static polymorphism. Overloaded methods
are defined in the same class. Overloaded methods have same method
name but different no. of parameters or type of parameters. For example
below mentioned are overloaded methods.
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 3

class X1 {
void test() {
<
}
void test(int x) {
<
}
void test(double x) {
<
}
}
Overloaded methods allows programmer to remember only one method
name having different functionality within the same class.
Constructor is used to initialize the instance variable. Java class always
have default constructor if we do not create any parameterized constructor.
Below mentioned program demonstrate the constructor overloading.
class Student {
char grade;
Student() {
grade = C;
}
Student(char grade) {
this.grade = grade;
}
}
class StudentDemo {
public static void main(String args[]) {
Student s1 = new Student(); // s1 will have grade value C
Student s2 = new Student(A); // s2 will have grade value A
}
}

GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 4

Q. 1 (b)
Write a program to create directories (/home/abc/bcd/def/ghi/jkl) in the
home directory /home/abc and list the files and directories showing
file/directory, file size. Read-write-execute permissions. Write destructor
to destroy the data of a class.
import java.io.File;
public class MyFileDemo {
public static void main(String[] args) throws Exception {
File f = new File("/home/abc", "bcd");
// if windows OS change to d:/home/abc (home and abc should //
be already created in the d:/
f = new File(f,"def");
createNewDir(f);
f = new File(f,"ghi");
createNewDir(f);
f = new File(f,"jlk");
createNewDir(f);
f = new File("/"); // if windows OS change / to d:/
String[] list = f.list();
for(String s : list){
f = new File(f, s);
System.out.println(f.getAbsolutePath());
}
}
public static void createNewDir(File f) {
if(!f.exists()) {
f.mkdir();
}
}
}

GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 5

Q. 2 (a)
Define polymorphism with its need? Define and explain static and
dynamic binding using program?

Poly means many. When we have one behavior which is implemented in
many ways we can achieve polymorphism. For example below, we have
two constructor of the Student class. Default constructor and
parameterized constructor. This is called constructor overloading. We can
also have method overloading, in below example we have setValues
method with two arguments and another method with one argument only.
class Student {
private int id; // id and name cannot be accessed outside the class
private String name;
public void setValues(int rollno, String name) {
this.rollno = rollno;
this.name = name;
}
public void setValues(int rollno) { // method overloading
this.rollno = rollno;
}
public Student() {
}
public Student(int rollno, String name) { // constructor overloading
this.rollno = rollno;
this.name = name;
}
}

It is clear from above example that names of the method remains the same
which is setValues. There is change in no. of parameters. Now when
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 6

Student class object needs to call setValues method it can call setValues
method with one Parameter or with two parameters.
We have seen that static polymorphism is achieved using method
overloading. To understand dynamic polymorphism lets first understand
method overriding concept. Method overriding is achieved by keeping
method signature same. Method signature includes return type, name of
the method and arguments. For example, if we have printStudent method
to be overridden we will write the printStudent method with the same
signature in the sub-class. Below mentioned example explain the same
concept.
class Student {
int id;
String name;
public void printStudent() {
System.out.println(I am student);
}
}

class EnggStudent extends Student {
public void printStudent() { // overridden method
System.out.println(I am Engineering student);
}
}
class ScienceStudent extends Student {
public void printStudent() { // overridden method
System.out.println(I am Science student);
}
}
class StudentDemo {
public static void main(String args[]){
Student s1 = new Student();
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 7

s1.printStudent();
EnggStudent s2 = new EnggStudent();
s2.printStudent();
ScienceStudent s3 = new ScienceStudent();
S3.printStudent();
}
}
As we can see in mentioned example, printStudent method is overridden
in sub-class. The implementation of the method is different. Now, if we
create the student class object and call the printStudent method, we will
have o/p printed on the console screen will be I am Student. We can
create object of the EnggStudent and call printStudent method, o/p will be
I am Engineering Student.

Ideally we should have created reference of the Student Class which is
pointing to the object of Student class, EnggStudent and ScienceStudent.
class StudentDemo {
public static void main(String args[]){
Student s1 = new Student();
s1.printStudent();
s1 = new EnggStudent(); // same reference (s1) pointing to
// EnggStudent now
s1.printStudent();
s1 = new ScienceStudent(); // same reference(s1) pointing to
// CommerceStudent now
s1.printStudent();

}
}
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 8

Q. 2 (a) Explain single and multiple inheritances in java. Write a program
to demonstrate combination of both types of inheritance as shown in
figure 1. i.e.hybrid inheritance


Single inheritance is when one java class extends another Java class or
implements one interface. For example,
class C1 extends C2 {
<
}
class C1 implement I1 {
<
}


GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 9

Mutilple inheritance is supported in java. One java class can NOT extends
two classes.
class C1 extends C1,C2 {
<
}
Below mentioned is program which represents the figure 1
Solution 1:
interface A {
<
}
interface B {
<
}

class C implements A , B {
<
}

class D extends C {
<
}



GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 10

Solution 2:
class A {
<
}
interface B {
<
}

class C extends A implements B {
<
}

class D extends C {
<
}



GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 11

Q. 2 (b) Write a program to demonstrate the multipath inheritance for the
classes having relations as shown in figure 2.


Below mentioned is program which represents the figure 2
Solution 1:
interface A {
<
}

class B implements A {
<
}

interface C extends A {
<
}

class D extends B implements C {
<
}



GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 12

Solution 2:

interface A {
<
}

interface B extends A {
<
}

interface C extends A {
<
}

class D implements B, C {
<
}


Key Points for extends and implements.
1. Class can extends only one class
2. Class can implements more than one interfaces
3. Interface can extends only one interface
4. Interface CAN NOT implements / extends class

GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 13

Q. 3 (a)
Define generics in Java. Write a program to demonstrate generic interface
and generic method.

Generics is facility added in java programming in 2004 as a part of J2SE 1.5
This allows type or method to operate on objects of various types while
providing compile time safety. Common use of generics is when using Java
Collection that can hold objects of any type, to specify the type of objects
store in it.
Below mentioned is a simple program to create generics.
interface MyGenericInterface <T> {
boolean checkForEquals(T t1, T t2);
}
class MyGenericClass<T> implements MyGenericInterface <T> {
@Override
public boolean checkForEquals(T t1, T t2) {
return t1==t2;
}
}
class MyGenericDemo {
public static void main(String[] args) {
Car c1 = new Car();
Car c2 = new Car();
MyGenericInterface <Car> genClass = new MyGenericClass<Car> ();
boolean result = genClass.checkForEquals(c1, c2);
System.out.println("Result is " + result);
}
}
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 14

Whenever we create any List /Map or Set we use generics to store specific
objects to the Collection for example,
List<String> list = new ArrayList<String>();
Generics ensures that now, we can add only string objects to thelist. If we
try to add any objects other than string it shows compilation error. So using
Generics compile time check of the objects type is possible and no
ClassCastException will be generated.

GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 15

Q.3 (b)
Define and write a program to differentiate between pass by value and
pass by reference?

Pass by Value is when we pass primitives (int, short, long, double, boolean,
float etc) to the method or constructor arguments.
Pass by reference is when we pass the reference of the object to the method
as a parameter.
When we pass by value, another variable (memory location) is created
where the value from the original variable is copied into the new variable.
Change of value in the method does not affect the original copy of the
variable.
When we pass by value, another reference is created. Both references
points to the same object. Any reference changing the value will have effect
on second reference also as both refers to the same object.
Below mentioned program having two functions to display the same.
class Pass {
int x;
void increment(int x){ // pass by value
x++;
}


void increment(Pass p1){
p1.x ++;
}
}
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 16

class PassDemo {
public static void main(String[] args) {
Pass p = new Pass();
p.x = 100;
increment(p.x);
increment(p);
System.out.println(p.x);
} }
When we will run this program answer will be 101. Because first increment
function calling -> increment(p.x); is pass by value in which p.x value is
copied into another variable x (x is local variable in the increment method).
Changing the value of the x does not affect the original value (p.x).
When we call the increment method and passing p as a reference, p1
reference also points to the same object where p is pointing. So any change
in the p1 (p1.x++) will affect the value of p (p.x will be incremented also).


GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 17

Q. 3 (a)
Define generics in Java. Write a program to demonstrate generic class
and constructor.
Generics is facility added in java programming in 2004 as a part of J2SE 1.5
This allows type or method to operate on objects of various types while
providing compile time safety. Common use of generics is when using Java
Collection that can hold objects of any type, to specify the type of objects
store in it.
Below mentioned is a simple program to create generics.
class MyGenericClass <T> {
private T t;
public MyGenericClass(T t){
this.t = t;
}
}
class MyGenericDemo {
public static void main(String[] args) {
Car c1 = new Car();
MyGenericClass<Car> genClass = new MyGenericClass<Car>(c1); }
}
Whenever we create any List /Map or Set we use generics to store specific
objects to the Collection for example,
List<String> list = new ArrayList<String>();
Generics ensures that now, we can add only string objects to thelist. If we
try to add any objects other than string it shows compilation error. So using
Generics compile time check of the objects type is possible and no
ClassCastException will be generated.
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 18

Q. 3 (b)
Differentiate between abstract class and interface specifying matrices of
differences. Write a program to define abstract class, with two methods
addition() and subtraction(). addition() is abstract method. Implement
the abstract method and call that method using a program(s).

abstract Class Interface
Abstract class has atleast one
abstract method
Interface has all abstract method
By default methods are NOT
abstract and public in abstract class
By default all methods are abstract
and public in interface
abstract classes are extended by
other class using extends keyword.
Interfaces are implemented by other
class using implements keyword
One class can not extends two or
more abstract classes
One class can implements two or
more interfaces
Variables defined in the abstract are
NOT static and final by default
Variables defined in the interfaces
are static and final by default

abstract class MyClass {
abstract int addition(int x, int y);
int substraction(int x, int y) {
return x - y;
}
}

class MyClassImpl extends MyClass {
int addition(int x, int y) {
return x + y;
}
}

GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 19

class MyClassImplDemo {
public static void main(String[] args) {
MyClassImpl cls = new MyClassImpl();
int result = cls.addition(10, 20);
System.out.println("Result is " + result);
}
}
Q. 4 (a)
Write an event handling program to handle feedback form of GTU
examination system using your creativity.
public class prjFeedbackForm {
public static void main(String [ ] args) {
Frame frame = new Frame("GTU Feedback Form");
Panel p = new Panel(new GridLayout(6, 2,0,20));
Label lName = new Label("Enter Name :");
final TextField tfName = new TextField(10);
Label lCourse = new Label("Course Name");
final TextField tfCourse = new TextField(10);
Label lCollegeName = new Label("CollegeName");
final TextField tfCollege = new TextField(10);
Label lComment = new Label("Enter Comment");
final TextField tfComments = new TextField(10);
CheckboxGroup group = new CheckboxGroup();
final Checkbox cb1 = new Checkbox("Good",group,true);
final Checkbox cb2 = new Checkbox("Excellent",group,true);
Button b = new Button("Send");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = tfName.getText();
String course = tfCourse.getText();
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 20

String comments = tfComments.getText();
String college = tfCollege.getText();
System.out.println("Name of the Student " + name);
System.out.println("Course of the Student " + course);
System.out.println("Comments from the Students " +
comments);
System.out.println("College Name " + college);
}
});

p.add(lName);
p.add(tfName);
p.add(lCourse);
p.add(tfCourse);
p.add(lCollegeName);
p.add(tfCollege);
p.add(lComment);
p.add(tfComments);
p.add(cb1);
p.add(cb2);
p.add(b);
frame.add(p);
frame.setLocation(200, 200);
frame.setSize(200, 240);
frame.setVisible(true);
}
}


GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 21

Q. 4 (b)
Write a program to replace all word1 by word2 from a file1, and
output is written to file2 file and display the no. of replacement.

class command {

public static void main(String[] args) {
System.out.println(args[0]);
File f = new File(args[0]);
if (f.exists()) {
System.out.println("file exist");
} else {
System.out.println("File does not exist");
return;
}
try {
FileReader fr = new FileReader(f);
StringBuffer str = new StringBuffer();
int i = fr.read();
while (i != -1) {
str.append((char) i);
i = fr.read();
}
System.out.println(str);
String content = str.toString();
StringTokenizer tokenizer = new StringTokenizer(content,
"word1");
System.out.println(tokenizer.countTokens());
content = content.replaceAll("word1", "word2");
System.out.println(content);
int counter = 0;
int index = content.indexOf("word2");
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 22

while(index!=-1){
counter++;
index = content.indexOf("word2",index+"word2".length());
}
System.out.println(counter);
FileOutputStream fos = new FileOutputStream(args[0]);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}

}
}


GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 23

Q. 4 (a)
Write an event handling program to handle e-mail sending form using
your creativity.

import java.awt.Button;
import java.awt.*;
import java.awt.event.*;

public class EmailSendDemo extends Frame {

public EmailSendDemo(String frameName) {
super(frameName);
}

public static void main(String args[]){

EmailSendDemo frame = new EmailSendDemo("Email Send Form");

Panel panel = new Panel();

Label lSend = new Label("To ");
Label lcc = new Label("cc ");
Label lbcc = new Label("bcc ");

final TextField tfSend = new TextField(10);
final TextField tfcc = new TextField(10);
final TextField tfbcc = new TextField(10);
final TextField tfsubject = new TextField(10);
final TextArea taContent = new TextArea(10,15);

Button bSend = new Button("send");
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 24

bSend.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
String toEmailAddress = tfSend.getText();
String ccEmailAddress = tfcc.getText();
String bccEmailAddress = tfbcc.getText();
String msg = tfsubject.getText();
String content = taContent.getText();
System.out.println("Sending Email ...");
}
});

panel.add(lSend);
panel.add(tfSend);
panel.add(lcc);
panel.add(tfcc);
panel.add(lbcc);
panel.add(tfbcc);
panel.add(taContent);
panel.add(bSend);

frame.add(panel);
frame.setSize(150,350);
frame.setVisible(true);

}
}
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 25


Q. 5 (a)
Explain the importance of Exception handling in java. Write a program to
handle NoSuchMethodException, ArrayIndexOutofBoundsException
using try-catch-finally and throw.

Below mentioned are some of the benefits of exception handling.

1. Program does not abruptly stops. Program continues excecution as if
nothing has happened.
2. Exceptions are unwanted situation, which programmer wants to
handle. Using try block as guarged block and catch block exception
are handled.
3. finally block is helpful in relasing the resources because it is always
executed.


GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 26

public class ExcTest {

public static void main(String[] args) {
try {
testNoSuchMethodExcetpion(); // NoSuchMethodException is
// checked. Method must be called from try block only.
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
}

pop(11); // no need to call from try-catch as
// ArrayIndexOutofBounds is unchecked exception

}

static void testNoSuchMethodExcetpion() throws
NoSuchMethodException {
throw new NoSuchMethodException("Exception NoSuchMethod.");
}
static int[] x = new int[10];
static int pop(int position) {
if(position>=0)
throw new ArrayIndexOutOfBoundsException("Arrays max size :
10");
else
return x[position];
}
}


GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 27

Q. 5 (a)
Explain the importance of Exception handling in java. Write a program to
handle NoSuchMethodException, ArrayIndexOutofBoundsException
using try-catch-finally and throw.

Difference between error and exception
1. All exception as sub-classes of exception class while all errors are
sub-classes of Error class
2. Error cannot be handled programmatically.
3. Exception can be handled using try-catch block by java programs.
4. OutofMemoryError is an example of Error while Exception examples
are ArithmaticException, IOException etc.

public class ExcTest {

public static void main(String[] args) {
try {
testInterruptedExcetpion(); // NoSuchMethodException is
// checked. Method must be called from try block only.
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
test();
}
static void testInterruptedExcetpion () throws InterruptedExcetpion {

throw new InterruptedExcetpion ("Exception InterruptedException.");

GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 28

}



static int test(int rollno) {
if(rollno<=0)
throw new IllegalArgumentException("roll no can not be
negative");
/* no need to call from try-catch and declare throws clause as
IllegalArgumentException is unchecked exception */
else
return x[position];
}
}

Q. 5 (b)
Write a program to add (keyword, URL) list for a web crawler in suitable
data structure in concurrent manner but one process at a time, and
retrieving data from the data structure in concurrent manner.

public class URLDemo implements Runnable {
static Hashtable<String, String> data = new Hashtable<String,
String>();
boolean isAdd;

public static void m ma ai in n(String[] args) {
URLDemo add = new URLDemo();
add.isAdd = true;

Thread t1 = new Thread(add);
t1.setName("ADD Thread : ");
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 29

t1.start();

URLDemo retrieve = new URLDemo();
retrieve.isAdd = false;

Thread t2 = new Thread(retrieve);
t2.setName("RETRIEVE Thread : ");
t2.start();

Thread t3 = new Thread(retrieve);
t3.setName("RETRIEVE Thread : ");
t3.start();
}
public void r ru un n() {
try {
int x = 0;
while (true) {
if (isAdd) {
x++;
data.put("key" + x, "URL : " + x);
Thread.sleep(1000); // to see better output...
System.out.println("Key Successfully added. " + data);
} else {
String key = "key" + (int)(Math.random()*100);
String url = data.get(key);
// genereted some random key and searching for
if (url != null) {
System.out.println("URL for key is " + url);
} else {
System.out.println("No key found : " + key);
}
Thread.sleep(1000); // to see better output...
}
}
GTU Exam Paper Solution: By Paresh Bhavsar

Paresh Bhavsar (www.j2eetrainer.com) Page 30

} catch (Exception e) {
e.printStackTrace();
}
}
}