Upload
manalidubal
View
217
Download
0
Embed Size (px)
Citation preview
8/12/2019 OOPJ_GTU_Dec-2010
1/30
GTU Exam Paper Solution: By Paresh Bhavsar
Paresh Bhavsar (www.j2eetrainer.com) Page 1
OOOOPPJJ((OObbjjeeccttOOrriieenntteeddPPrrooggrraammmmiinnggJJaavvaa))
GGTTUUEEXXAAMMPPAAPPEERRSSOOLLUUTTIIOONNYYEEAARR::22001100((DDeecc))
BByyPPaarreesshhBBhhaavvssaarr0099332288557766220000//bbhhaavvssaarr..eerr@@ggmmaaiill..ccoomm
wwwwww..jj22eeeettrraaiinneerr..ccoomm
mailto:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]8/12/2019 OOPJ_GTU_Dec-2010
2/30
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.
8/12/2019 OOPJ_GTU_Dec-2010
3/30
GTU Exam Paper Solution: By Paresh Bhavsar
Paresh Bhavsar (www.j2eetrainer.com) Page 3
class X1 {
void test(){
8/12/2019 OOPJ_GTU_Dec-2010
4/30
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 showingfile/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();}
}
}
8/12/2019 OOPJ_GTU_Dec-2010
5/30
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
8/12/2019 OOPJ_GTU_Dec-2010
6/30
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();
8/12/2019 OOPJ_GTU_Dec-2010
7/30
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();
}
}
8/12/2019 OOPJ_GTU_Dec-2010
8/30
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 {
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).
8/12/2019 OOPJ_GTU_Dec-2010
17/30
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 {
private T t;
public MyGenericClass(T t){
this.t = t;
}
}
class MyGenericDemo {
public static void main(String[] args) {Car c1 = new Car();
MyGenericClassgenClass = new MyGenericClass(c1); }
}
Whenever we create any List /Map or Set we use generics to store specific
objects to the Collection for example,
List list = new ArrayList();
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.
8/12/2019 OOPJ_GTU_Dec-2010
18/30
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 methodsaddition() 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;
}
}
8/12/2019 OOPJ_GTU_Dec-2010
19/30
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();
8/12/2019 OOPJ_GTU_Dec-2010
20/30
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);
}
}
8/12/2019 OOPJ_GTU_Dec-2010
21/30
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");
8/12/2019 OOPJ_GTU_Dec-2010
22/30
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();
}
}
}
8/12/2019 OOPJ_GTU_Dec-2010
23/30
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");
8/12/2019 OOPJ_GTU_Dec-2010
24/30
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);
}
}
8/12/2019 OOPJ_GTU_Dec-2010
25/30
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 exceptionare handled.
3. finally block is helpful in relasing the resources because it is always
executed.
8/12/2019 OOPJ_GTU_Dec-2010
26/30
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];
}
}
8/12/2019 OOPJ_GTU_Dec-2010
27/30
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, ArrayIndexOutofBoundsExceptionusing 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.");
8/12/2019 OOPJ_GTU_Dec-2010
28/30
GTU Exam Paper Solution: By Paresh Bhavsar
Paresh Bhavsar (www.j2eetrainer.com) Page 28
}
static int test(int rollno) {
if(rollno
8/12/2019 OOPJ_GTU_Dec-2010
29/30
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 rruunn() {
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...
}
}
8/12/2019 OOPJ_GTU_Dec-2010
30/30
GTU Exam Paper Solution: By Paresh Bhavsar
} catch (Exception e) {
e.printStackTrace();
}
}
}