object oriented programming and java (mc221) july 2005.doc

23
Question Paper Object Oriented Programming and Java (MC221): July 2005 Section A : Basic Concepts (30 Marks) This section consists of questions with serial number 1 - 30. Answer all questions. Each question carries one mark. Maximum time for answering Section A is 30 Minutes. 1. A process that involves recognizing and focusing on the important characteristics of a situation or object is known as: (a) Encapsulation (b) Polymorphism (c) Abstraction (d) Inheritance (e) Object persistence. < Answer > 2. Which statement is true regarding an object? (a) An object is what classes instantiated are from (b) An object is an instance of a class (c) An object is a variable (d) An object is a reference to an attribute (e) An object is not an instance of a class. < Answer > 3. In object oriented programming, composition relates to (a) The use of consistent coding conventions (b) The organization of components interacting to achieve a coherent, common behavior (c) The use of inheritance to achieve polymorphic behavior (d) The organization of components interacting not to achieve a coherent common behavior (e) The use of data hiding to achieve polymorphic behavior. < Answer > 4. In object oriented programming new classes can be defined by extending existing classes. This is an example of: (a) Encapsulation (b) Interface (c) Composition (d) Inheritance (e) Aggregation. < Answer > 5. Which of the following does not belong: If a class inherits from some other class, it should < Answer >

Upload: amitukumar

Post on 12-Dec-2015

8 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Object Oriented Programming and Java (MC221)  July 2005.doc

Question PaperObject Oriented Programming and Java (MC221): July 2005

  Section A : Basic Concepts (30 Marks)  

         This section consists of questions with serial number 1 - 30.       Answer all questions.       Each question carries one mark.       Maximum time for answering Section A is 30 Minutes.

 

 

1. A process that involves recognizing and focusing on the important characteristics of a situation or object is known as:

(a) Encapsulation (b) Polymorphism (c) Abstraction (d) Inheritance (e) Object persistence.

< Answer >

2. Which statement is true regarding an object?

(a) An object is what classes instantiated are from(b) An object is an instance of a class(c) An object is a variable(d) An object is a reference to an attribute(e) An object is not an instance of a class.

< Answer >

3. In object oriented programming, composition relates to

(a) The use of consistent coding conventions (b) The organization of components interacting to achieve a coherent, common behavior (c) The use of inheritance to achieve polymorphic behavior (d) The organization of components interacting not to achieve a coherent common behavior(e) The use of data hiding to achieve polymorphic behavior.

< Answer >

4. In object oriented programming new classes can be defined by extending existing classes. This is an example of:

(a) Encapsulation (b) Interface (c) Composition (d) Inheritance (e) Aggregation.

< Answer >

5. Which of the following does not belong: If a class inherits from some other class, it should

 (a) Make use of the parent class's capabilities(b) Over-ride or add the minimum to accomplish the derived class' purpose(c) Over-ride all the methods of its parent class(d) Make sure the result "IS-A-KIND-OF" its base class(e) Make sure the result “contains” its base class.

< Answer >

6. Object oriented inheritance models the

(a) "is a kind of" relationship (b) "has a" relationship (c) "want to be" relationship (d) inheritance does not describe any kind of relationship between classes (e) “contains” of relationship.

< Answer >

7. The wrapping up of data and functions into a single unit is called

(a) Encapsulation (b) Abstraction

< Answer >

Page 2: Object Oriented Programming and Java (MC221)  July 2005.doc

(c) Data Hiding (d) Polymorphism (e) Message passing.

8. Polymorphism

(a) Is not supported by Java (b) Refers to the ability of two or more objects belonging to different classes to respond to exactly the

same message in different class-specific ways (c) Simplifies code maintenance (d) Not simplifies code manintenance(e) Refers to the ability of two or more objects belonging to different classes to respond to exactly the

same message in different class –specific ways and simplifies code maintenance.

< Answer >

9. In object oriented programming new classes can be defined by extending existing classes. This is an example of:

(a) Encapsulation (b) Interface (c) Composition (d) Inheritance (e) Aggregation.

< Answer >

10. Given a class named student, which of the following is a valid constructor declaration for the class?

(a) Student (student s) { } (b) Student student ( ) { }(c) Private final student ( ) { } (d) Void student ( ) { }(e) Static void student(){ }.

< Answer >

11. What is garbage collection in the context of Java?

(a) The operating system periodically deletes all of the java files available on the system.(b) Any package imported in a program and not used is automatically deleted.(c) When all references to an object are gone, the memory used by the object is automatically

reclaimed.(d) The JVM checks the output of any Java program and deletes anything that doesn't make sense.(e) When all references to an object are gone the memory used by the object is not reclaimed.

< Answer >

12. The concept of multiple inheritance is implemented in Java by

I. Extending two or more classes.II. Extending one class and implementing one or more interfaces.III. Implementing two or more interfaces. (a) Only (II) (b) (I) and (II) (c) (II) and (III)(d) Only (I) (e) Only (III).

< Answer >

13. In Java, declaring a class abstract is useful

(a) To prevent developers from further extending the class (b) When it doesn't make sense to have objects of that class (c) When default implementations of some methods are not desirable (d) To force developers to extend the class not to use its capabilities (e) When it makes sense to have objects of that class.

< Answer >

14. What is the error in the following class definitions?

Abstract class xy {

abstract sum (int x, int y) { } }

(a) Class header is not defined properly.(b) Constructor is not defined.(c) Method is not defined properly(d) Method is defined properly(e) No error.

< Answer >

15. Which of these field declarations are legal within the body of an interface? < Answer >

Page 3: Object Oriented Programming and Java (MC221)  July 2005.doc

(a) Private final static int answer = 42 (b) public static int answer=42(c) final static answer =42 (d) int answer (e) No error.

16. A package is a collection of

(a) Classes (b) Interfaces (c) Editing tools(d) Classes and interfaces (e) Editing tools and interfaces.

< Answer >

17. A method within a class is only accessible by classes that are defined within the same package as the class of the method. Which one of the following is used to enforce such restriction?

(a) Declare the method with the keyword public(b) Declare the method with the keyword private(c) Declare the method with the keyword protected(d) Do not declare the method with any accessibility modifiers(e) Declare the method with the keyword public and private.

< Answer >

18. Basic Java language functions are stored in which of the following java package?

(a) java.lang (b) java.io (c) java.net (d) java.util (e) java.awt.

< Answer >

19. Which of the following is a member of the java.lang package?

(a) List (b) Queue (c) Math (d) Stack (e) Process.

< Answer >

20. Which of the following has a method names flush( )?

(a) Input stream (b) Output Stream(c) Reader stream (d) Input reader stream(e) Input output stream.

< Answer >

21. What is the fundamental unit of information of writer streams?

(a) Characters (b) Bytes(c) Files (d) Records (e) Information.

< Answer >

22. File class is included in which package?

(a) java.io package (b) java.lang package(c) java.awt package (d) java.net.package(e) java.util.package.

< Answer >

23. Given the code

String s1 = “ yes” ;String s2 = “ yes “ ;String s3 = new String ( s1);

Which of the following would equate to true? (a) s1 == s2 (b) s1 = s2 (c) s3 == s1 (d) s3=s1 (e) s1!=s2.

< Answer >

24. URL stands for

(a) Universal reader locator (b) Universal reform loader(c) Uniform resource loader (d) Uniform resource locator(e) Uniform reader locator.

< Answer >

25. What is the sequence of major events in the life of an applet?

(a) init, start, stop, destroy (b) start, init , stop , destroy(c) init, start , destroy, stop (d) init, start, destroy(e) destroy, start, init, stop.

< Answer >

Page 4: Object Oriented Programming and Java (MC221)  July 2005.doc

26. Which of the following is true in regard to applet execution?

(a) Applets loaded from the same computer where they are executing have the same restrictions as applets loaded from the network. 

(b) Applets loaded and executing locally have none of the restrictions faced by applets that get loaded from the network.

(c) Applets loaded and executing locally have some restrictions faced by applets that get loaded from the network.

(d) Applets cant react to user input and change dynamically

(e) Applets can be run independently.

< Answer >

27. What is the return type of the method getID() defined in AWTEvent class

(a) Int (b) long (c) Object (d) Component (e) float.

< Answer >

28. Which of the following events will cause a thread to die?

(a) The method sleep( ) is called(b) The method wait( ) is called(c) Execution of the start( ) method ends(d) Execution of the run( ) method ends(e) Execution of the run() method is called.

< Answer >

29. What will be the result of the expression 13 & 25?

(a) 38 (b) 25 (c) 9 (d) 12 (e) 21.

< Answer >

30. Which of the following statements are true regarding the finalize( ) method?

(a) The finalize ( ) method must be declared with protected accessibility(b) The compiler will fail to compile the code that explicitly tries to call the finalize( ) method(c) The body of the finalize ( ) method can only access other objects that are eligible for garbage

collection(d) The finalize ( ) method can be overloaded(e) The finalize() method cant be overloaded.

< Answer >

 

  END OF SECTION A  

 

Page 5: Object Oriented Programming and Java (MC221)  July 2005.doc

 

Section B : Problems (50 Marks)

This section consists of questions with serial number 1 – 5.Answer all questions. Marks are indicated against each question.Detailed workings should form part of your answer. Do not spend more than 110 - 120 minutes on Section B.

1. a. Why is Java known as platform-neutral language? Explain the importance of JVM in Java.

b. What do you mean by dynamic initialization of a variable? Give an example.

(5 + 5 = 10 marks) < Answer >

2. a. What are objects? How are they created from a class?

b. What is a constructor? What are its special properties?

(5 + 5 = 10 marks) < Answer >

3. a. What is meant by method overriding? What is the difference between methods overloading from method overriding.

b. Distinguish between static and dynamic polymorphism.

(5 + 5 = 10 marks) < Answer >

4. a. Define Applet and give the syntax of the applet tag in an HTML file.b. Write a short note on the following:i. IP Address.ii. URL.

(2 + 8 = 10 marks) < Answer >

5. a. What is JDBC? How do you connect to the Database?

b. Give the sequence of steps to invoke a SQL query using JDBC.

(5 + 5 = 10 marks) < Answer >

 

END OF SECTION B

Section C : Applied Theory (20 Marks)

This section consists of questions with serial number 6. Do not spend more than 25 -30 minutes on section C.

 

6. a. Given below are two files :

File Employee.java

package purchase;

public class Employee

{

protected double age = 35;

Page 6: Object Oriented Programming and Java (MC221)  July 2005.doc

}

import purchase.Employee;

public class Company

{

public static void main (String args[ ] )

{

Employee e= new Employee ( );

System.out.println ( “Age = “ + e.age );

}

}

Will the file Company.java compile? Explain the reason briefly.

b. Consider the following class file :

import java.awt.*;

import java.io.*;

package studentbase;

class Test

{

void display ( )

 

{

System.out.println (“Results”);

}

}

Will it compile? Give reason for the answer.

c. How will the following program lay out its buttons.

import java.awt.*;

public class MyClass

{

Public static void main(String args[])

{

String [] labels = {"A","B","C","D","E","F"};

Window win = new Frame ();

win.setLayout(new GridLayout(1,0,2,3));

for(int i=0;i < labels.length;i++)

win.add(new Button(labels[i]));

Page 7: Object Oriented Programming and Java (MC221)  July 2005.doc

win.pack ();

win.setVisible (true);

}

}

d. Is it possible to have multiple catch blocks? Give reason and Illustrate with an example.

(6 + 2 + 2 + 10 = 20 marks) < Answer >

END OF SECTION C 

END OF QUESTION PAPER

 

 

Suggested AnswersObject Oriented Programming and Java (MC221): July

2005

Section A : Basic Concepts1. Answer : (c)

Reason : The insulation of data from direct access by the program is called as the data abstraction.Data abstraction also called as data hiding, is the mechanism where by the code and the data it manipulates are wrapped into a single unit.

< TOP >

2. Answer : (b)

Reason : An object is an instance of a class. Objects are created from class definitions that implement abstractions.

< TOP >

3. Answer : (b)

Reason : Composition is about an object that is made up of other objects, referred as "containment. Composition implies that the life cycles are more strongly linked, that means Whole is responsible for the life time of Part.

< TOP >

4. Answer : (d)

Reason : Inheritance is a mechanism that enables one class to inherit all of the behaviour (methods ) and attributes (instance variables) of another class. A class that inherits from another class is called a subclass and the class that gives the inheritance is called a superclass.

< TOP >

5. Answer : (c)

Reason : In a class hierarchy, when a method in a subclass has the same method signature as that of the superclass, then the method in the subclass is said to “override” the method in superclass. When an overridden method exists in the subclass, the subclass objects always refer its own. The subclass overridden method hides ( or blocks ) that of the superclass method.

< TOP >

6. Answer : (a) < TOP >

Page 8: Object Oriented Programming and Java (MC221)  July 2005.doc

Reason : As it models generalization relationship it takes “is a kind of “keyword.

7. Answer : (a)

Reason : Data encapsulation is the method of wrapping up of data and functions into a single unit.

< TOP >

8. Answer : (e)

Reason : As Polymorphism refers to the ability of two or more objects belonging to different classes to respond to exactly the same message in different class-specific ways. It also simplifies code manintenance.

< TOP >

9. Answer : (d)

Reason : As inheritance is nothing but extending existing classes whereas the others are for different purpose.

< TOP >

10. Answer : (a)

Reason : A constructor cannot specify any return type, not even void. A constructor cannot be final, static or abstract.

< TOP >

11. Answer : (c)

Reason : As the remaining all contradict the functionality of JVM.

< TOP >

12. Answer : (c)

Reason : The remaning are not opt solutions for the concept of multiple inheritance.

< TOP >

13. Answer : (b)

Reason : As other Choices are contradicting the meaning of Abstract Class .

< TOP >

14. Answer : (c)

Reason : method is not defined properly.

< TOP >

15. Answer : (b)

Reason : The remaining are all illegal.

< TOP >

16. Answer : (d)

Reason : Editing tools are not the part of packages.So d is the correct Answer.

< TOP >

17. Answer : (d)

Reason : The desired accessibility is package accessibility, which is the default accessibility for members that have no accessibility modifier. Package is not an accessibility modifier.

< TOP >

18. Answer : (a)

Reason : The basic language functions are stored in a package inside of the java package called java.lang.

< TOP >

19. Answer : (b)

Reason : Math is a member of the java.lang package whereas the remaining are not.

< TOP >

20. Answer : (b)

Reason : Output stream has the method flush ( ) that flushes the output stream.

< TOP >

21. Answer : (a)

Reason : Writer streams uses characters as their fundamental unit of information.

< TOP >

Page 9: Object Oriented Programming and Java (MC221)  July 2005.doc

22. Answer : (a)

Reason : File class is included in inputoutput

< TOP >

23. Answer : (a)

Reason : == is a comparision operator whereas = is an assignment operator.

< TOP >

24. Answer : (d)

Reason : The abbreviation of URL uniform resource locator.

< TOP >

25. Answer : (a)

Reason : The remaining all are incorrect because the sequence of major events are wrong.

< TOP >

26. Answer : (b)

Reason : The remaining Choices are contradicting the properties of applets.

< TOP >

27. Answer : (a)

Reason : Int is the return type of the method getID() in AWTEvent Class.

< TOP >

28. Answer : (d)

Reason : A thread dies when the execution of the run( ) method ends. The call to the start method is asynchronous, that is, it returns immediately, and it enables the thread for running. Calling the sleep( ) or wait( ) methods will only block the thread temporarily.

< TOP >

29. Answer : (c)

Reason : 11001&1101==9;

< TOP >

30. Answer : (d)

Reason : The finalize( ) method like any method can be called explicitly if it is accessible. Intended purpose of the method is to be called by the garbage collector in order to clean up before an object is destroyed. Overloading the finalize ( ) method is allowed, but only the method with the original signature will be called by the garbage collector.

< TOP >

Page 10: Object Oriented Programming and Java (MC221)  July 2005.doc

Section B : Problems

 

1. a. Java is known as platform-neutral language as it is not tied to any particular hardware or operating system. Java programs can be executed any where on any system. They can be moved from one computer system to another, anywhere and anytime. Changes and upgrades in operating systems, processors and system resources will not force any changes in the programs.

The Java Virtual Machine is the engine that actually executes a Java program. When a Java program is run, the instructions are not executed directly by the hardware of the local system, instead an interpreter or "virtual processor" walks through the instructions step by step and carries out the action the instruction represents. Java compiler produces and intermediate code known as bytecode .

 

 

The machine specific code is generated by the Java interpreter by acting as an intermediary between the byte code and the real machine as shown below :

 

b. Dynamic initialization is the method of initializing the variables dynamically at runtime using any expression valid at the time the variable is declared .

For example, here is a short program that computes the area of a circle given the radius of it :

// Dynamic initialization

Class DynInit {

Public static void main (String args { } ) {

double r = 5.0;

double p=3.14

 

//a is dynamically initialized

double a = pi * (r * r )

System.out.println (‘Area is “, + a );

}

}

Here, three local variables are used- r, p, a – are declared. The first two r, p, a re initialized by constants. However, a is initialized dynamically to the area of the circle. Initialization expression may use any element valid at the time of the initialization, including calls to methods, other variables, or literals.

 < TOP >

Page 11: Object Oriented Programming and Java (MC221)  July 2005.doc

 

2.

a. An object is a specific instance of a class. An object in java is essentially a block of memory that contains space to store all the instance variables.

The process of creating objects from a class is called instantiation. The object is created using the class and is a concrete instance of the abstraction that the class represents. An object must be created before it can be used in a program. In Java objects are manipulated through object references. The process of creating objects involves the following steps:

 

1. Declaration of a variable to store the object reference.

This involves declaring a reference variable of the appropriate class to store the reference to the object.

2.            Creating an object.

This involves using the new operator in conjunction with a call to a constructor, to create an instance of the class.

Eg : Creating an object of type Circle

Circle C1; // declareC1 = new Circle( ); // instantiate

This first statement declares a variable to hold the object reference and the second one actually assigns the object reference to the variable.

 

b. A constructor is a method, which is invoked when an object of a class is created. It has no return type in java. Its name must be same as the name of class. It can accept parameter. Here we look at how they function in java.

Class student{int age;string name;

student( ) //constructor{age=0;name="kiran";}

Page 12: Object Oriented Programming and Java (MC221)  July 2005.doc

In java the overloading of constructors is possible. An overloading means using same name of constructor with different parameters. An example is given.

Class student{int age;string name;

student() //constructor{age=0;name="kiran";}

student(int n, string s) // constructor overloading{age=n;name=s;}

Properties:     Constructors enable an object to initialize itself when created.     Constructors have the same name as that of the class.     They do not specify a return type, not even void.

They return the instance of the class itself

 < TOP >

3.

a. In a class hierarchy , when a method in a subclass has the same method signature as that of the superclass, then the method in the subclass is said to “override” the method in superclass. When an overridden method exists in the subclass, the subclass object always refer its own. The subclass overridden method hides ( or blocks ) that of the superclass method.

Example :

Class X

{

int i,j;

X ( int a , int b)

{

i = a;

j = b;

}

void show( )

{

System.out.println (“ i and j : “ + i + “ “ + j ); }

}

Class Y extends X

Page 13: Object Oriented Programming and Java (MC221)  July 2005.doc

{

int k;

Y ( int a , int b , int c )

{

super ( a, b );

k = c;

}

void show ( )

{ System.out.println ( “ k : “ + k );

}

}

 

 

Class Overridedemo

{

public static void main (String args [ ] )

{

Y subob = new Y ( 1,2,3 );

subob. Show ( );

}

}

 

Output : k : 3

 

When show( ) is invoked on an object of type Y, the version of the show( ) defined in Y is used. That is, the version show ( ) inside Y overrides the version declared in X.

b. Static polymorphism : In static polymorphism, which method is to be called is decided at compile time only. Method overloading is an example of static polymorphism. In Method overloading the same method name is used many times in the same class, but with different parameters. Depending on the parameters passed, it is decided at compile as which method is to be called. Parameters are the deciding factor (not return type) for the compiler to decide which method is to be called actually at run-time. In static polymorphism, decision is take at compile-time (contrast with dynamic polymorphism).

Dynamic polymorphism (also called dynamic method dispatch) is the mechanism by which a call to an overridden function is resolved at run-time ( not at compile time). Dynamic method dispatch is the method by which Java implements run-time polymorphism. When an overridden method is called through a superclass reference, Java determines which version of that method is to be executed based upon the type of the object being referred at the time the call occurs. Thus this determination is made at run time. When different type of objects are referred to , different versions of an overridden method will be called. It is the type of object being referred to (not the type of reference variable) that determines which version of an overridden method will be executed. Therefore, if a superclass contains a method that is overridden by a subclass, then , when different types of objects are referred to through a superclass reference variable, different versions of the methods are executed.

 < TOP >

4. a. Java applets are compiled Java programs that are stored on a Web server. A Java applet is a special kind of program because it can't run on its own. It needs a Web browser to give it a home. When your Web browser encounters a reference to a Java applet in a Web page, it sends a request to the server that gave it the Web page to send along the compiled code for the applet as well. 

Page 14: Object Oriented Programming and Java (MC221)  July 2005.doc

The APPLET tag is used to start an applet from both an HTML document and from an applet viewer. An applet viewer will execute each APPLET tag that it finds in a separate window, while web browsers like Netscape Navigator, Internet Explorer, and Hot Java will allow many applets on a single page.

The syntax for the standard APPLET tag is shown here. The bracketed items are optional.

< APPLET

[ CODE BASE = Codebase URL ]

CODE = appletFile

[ ALT = alternateText]

[ Name = applet Instance Name ]

WIDTH = pixels HEIGHT = pixels

[ALIGN = alignment ]

[VSPACE = pixels ] [ HSPACE = pixels ]

>

[ <PARAM NAME = Attribute Name VALUE = Attribute Value > ]

[ <PARAM NAME = Attribute Name2 VALUE = Attribute Value > ]

……

[ HTML Displayed in the absence of Java ]

< / APPLET .

 

b. a. An IP address (Internet Protocol Address) is a number that uniquely identifies each computer on the net. All internet address consists of 32-bit values (called Ipv4 – Internet Protocol, version 4).Latest

addressing scheme, called IPv 6 (Internet Protocol, version 6) uses a 128-bit value to represent an address. It supports larger address space.

For example, 1.160.10.240 could be an IP address. 

b. URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet. The following is an example of a URL which addresses the Java Web site hosted by Sun Microsystems:  

 

A URL has two main components:

    Protocol identifier

    Resource name

The protocol identifier and the resource name are separated by a colon and two forward slashes. The protocol identifier indicates the name of the protocol to be used to fetch the resource. The example uses the Hypertext Transfer Protocol (HTTP), which is typically used to serve up hypertext documents. HTTP is just one of many different protocols used to access different types of resources on the net. Other protocols include File Transfer Protocol (FTP), Gopher, File, and News.

The resource name is the complete address to the resource. The format of the resource name depends entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one or more of the components listed in the following table:

Host Name: The name of the machine on which the resource lives.

Filename: The pathname to the file on the machine.

Port Number : The port number to which to connect (typically optional).

Page 15: Object Oriented Programming and Java (MC221)  July 2005.doc

Reference : A reference to a named anchor within a resource that usually identifies a specific location within a file (typically optional).

 

< TOP >

5. a. The steps to follow for executing an SQL query in JDB:

1.            Connect to the database

A JDBC database is identified by its URL. First invoke the getConnection ( ) method on the DriverManager class and pass it the URL for the database. The DriverManager will locate a Driver object that can handle the URL ; it then returns a connection object that uses this driver.

2.            Obtain a statement object

Invoke createStatement( ) method on the connection object; it will return a statement object.

3.            Execute the Query

Invoke the executeQuery ( ) method on the statement object and pass it the SQL SELECT in a string ; it will execute the query and return the results in a ResultSet object.

4.            Position the cursor to the next row

Invoke next ( ) method to point the cursor to the next row in the ResultSet object. The cursor will point to the first row after we invoke next ( ) for the first time.

Diagram for invoking a SQL Queue

5.            Retrieve the row values one Column at a time

We must invoke a getxxx ( ) call for each column value that we need to retrieve. The exact function we invoke depends on the column’s SQL type. In the above scenario, we invoke getInt ( ) ,

getBigDecimal ( ), getString ( ) ,and getBoolean( ) to retrieve four column values of SQLTYPE INTEGER, DECIMAL, VARCHAR ,and BIT.

6.            Repeat while there are rows to be processed

Repeat the last two steps as long as next ( ) returns true; it returns false if there are no more rows.

7.            Release the statement object

Invoke close ( ) to free the resources associated with the statement object.

8.            Release the connection object

Invoke close ( ) to free the resources associated with the connection object.

b. There are two steps in establishing a connection

(1) loading the driver    

Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:

Class.forName("jdbc.DriverXYZ");  

 

(2) making the connection

Page 16: Object Oriented Programming and Java (MC221)  July 2005.doc

 When establishing a connection, have the appropriate driver connect to

DBMS. The following line of code illustrates the general

idea:

String url = "jdbc:odbc:Fred";Connection con = DriverManager.getConnection(url, "Fernanda", "J8");  

< TOP >

Section C: Applied Theory

 

6. a. No, the file Company.java will not compile. The field age in the Employee class should be declared as public.

The three access specifiers, private, public and protected, provide a variety of ways to produce many levels of access required.

Any thing declared public can be accessed from any where. Anything declared private cannot be seen outside of its class. When a member does not have an explicit access specification , it is visible to subclasses as well as to other classes in the same package. This is default access. When an element is to be seen outside the current package, but only to classes that subclass the class directly, then declare that element protected.

 Class members Access

   Private No modifier Protected Public

Same class Yes Yes Yes Yes

Same package subclass

No Yes Yes Yes

Same package non-subclass

No Yes Yes Yes

Different package subclass

No No Yes Yes

Different package non-subclass

No No No Yes

 b. No, The package definition must come first. The given problem is contradicting to the definition of a

package.

c.          After careful observation of the program the output of the code is that its displays all buttons in a single row.

d. There may be situations where more than one exception could be raised by a single piece of code. To handle this type of situation, we can specify two or more catch blocks, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches with that of the exception thrown is executed. If one catch block is executed, the others are bypassed, and execution continues after the try/catch block. The following example traps two different exception types:

The following program illustrate multiple catch statements:

Page 17: Object Oriented Programming and Java (MC221)  July 2005.doc

Class CatchDemo {

public static void main (String args [ ] ) {

try {

int a = 5, b = 0;

int marks [ ] = {10, 20};

System.out.printin (a/b);

 

 

System.out.println (marks [3]);

}

catch (Arithmetic Exception e) {

System.out.println (“Do not divide by zero sir “+e);

}

catch (ArrayIndexOutOfBounds Exception e) {

System.out.println (“Do not access an element that does not exist

sir” + e);

}

System.out.printin (“After try / catch blocks,”);

}

}

In the above code, the statement marks [3] is never executed as program terminates at the statement a / b. If we make b some integer value, marks [3] is executed and thereby second catch block is executed. Remember, one try block can throw only one exception at a time and when an exception is thrown control comes out of the try block in search of a suitable catch block. Once, the control comes out of the try block, it never enters back again. It is advised to split the above try block into two try blocks to make a robust program.

< TOP >

 

< TOP OF THE DOCUMENT >