You are on page 1of 47

Re: MCS-024 - Object Oriented Technologies And Java Programming - MCA(2)/024/Assign/09 Posted On:

2/16/2010 1:22:07 PM

Question 2 : a) Explain why Java is platform independent. Also explain advantage of platform independence.

a)

When Java Code is compiled a byte code is generated which is independent of the system. This byte code is fed
to the JVM (Java Virtual Machine) which is resided in the system. Since every system has its own JVM, it doesn't
matter where you compile the source code. The byte code generated by the compiler can be interpreted by any
JVM of any machine. Hence it is called Platform independent Language.

Java's bytecodes are desgined to be read and interpreted in exactly same manner on any computer hardware or
operating system that supports Java Runtime Environment.

Advantages:

One of the key reasons Java technology is useful in a networked environment is that Java makes it possible to
create binary executables that will run unchanged on multiple platforms. This is important in a networked
environment because networks usually interconnect many different kinds of computers and devices. In a typical
enterprise environment, for example, a network might connect Macintoshes in the art department, UNIX
workstations in engineering, and PCs running Windows everywhere else. Although this arrangement enables
various kinds of computers and devices within the company to share data, it requires a great deal of
administration. Such a network presents a system administrator with the task of keeping different platform-specific
editions of programs up to date on many different kinds of computers. Programs that can run without change on
any networked computer, regardless of the computer's type, make the system

administrator's job simpler, especially if those programs can actually be delivered

across the network.

In addition, the emerging proliferation of network-enabled embedded devices represents another environment in
which Java's platform independence is useful. In the workplace, for example, various kinds of embedded devices,
such as printers, scanners, and fax machines, are typically connected to the internal network.

Network-connected embedded devices have also appeared in consumer domains, such as the home and car. In
the embedded world, Java's platform independence can also help simplify system administration. Jini technology,
which aims to bring plug and play to the network, simplifies the task of administering a dynamic environment of
network-connected embedded devices for both consumers at home and systems administrators at work. Once a
device is plugged into the network, it can access other devices attached to the network, and other devices can
access it.
To achieve this ease of connectivity, Jini-enabled devices exchange objects across the network, a technique that
would be impossible without Java's support for platform independence. From the developer's perspective, Java
can reduce the cost and time required to develop and deploy applications on multiple platforms. Even though
historically, many (or most) applications have been supported on only one platform, often the reason was that the
cost involved in supporting multiple platforms wasn't worth the added return. Java can help make multi-platform
support affordable for more types of programs.

On the other hand, Java's platform independence can act as a disadvantage as well as an advantage for software
developers. If you are developing and selling a software product, Java's support for platform independence can
help you to compete in more markets. Instead of developing a product that runs only on Windows, for example,
you can write one that runs on Windows, OS/2, Solaris, and Linux. With Java, you can have more potential
customers. The trouble is, so can everyone else. Imagine, for example, that you have focused your efforts on
writing great software for Solaris. Java makes it easier for others to write software that competes in your chosen
market niche. With Java, therefore, you may not only end up with more potential customers, but also with more
potential competitors. But perhaps most significantly for developers, the fact that Java code can run unchanged
on multiple platforms gives the network a homogeneous execution environment that enables new kinds of
distributed systems built around networkmobile objects. APIs such as object serialization, RMI (Remote Method
Invocation), and Jini take advantage of this underlying capability to bring objectoriented programming out of the
virtual machine and onto the network. (More

information on Jini is given in Chapter 4, Network Mobility.)

b) What are different relational operators in Java? Write a Java program to explain the use of relational operators.

The Equality and Relational Operators

The equality and relational operators determine if one operand is greater than, less

than, equal to, or not equal to another operand. The majority of these operators will

probably look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive
values are equal.

== equal to

!= not equal to

> greater than

>= greater than or equal to

< less than

<= less than or equal to

Programme :
public class marks

static int stud1;

public marks(int a)

stud1=a;

public void grade()

if((stud1>70)&&(stud1<100))

System.out.println(“Grade A”);

else

if((stud1>50)&&(stud1<70))

System.out.println(“Grade B”);

else

System.out.println(“Fail”);

public static void main(String args[])

marks m1=new marks(80);

m1.grade();

}}

The symbols && a n d || are the logical AND a n d OR operators used to evaluate logical

expressions. Use && and || in the evaluation of compound expressions of the form

• expression_1 && expression_2

where expression_1 and expression_2 each evaluate to a scalar, logical result.

The && and || operators support short-circuiting. This means that the second operand is valuated only when the
result is not fully determined by the first operand
ankita banerjee

Re: MCS-024 - Object Oriented Technologies And Java Programming - MCA(2)/024/Assign/09 Posted On:
2/16/2010 1:23:06 PM

Question 3 : a) What is variable size array? Write a program to explain the use of variable size array in Java.

Answer 3 (a):

The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that
can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or
shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you
may not know until run time precisely how large of an array you need. To handle this situation, the collections
framework defines ArrayList. In essence, an ArrayList is a variable-length array of object references. That is, an
ArrayList can 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.
ArrayList has the constructors shown here:

ArrayList( )

ArrayList(Collection c)

ArrayList(int capacity)

The first constructor builds an empty array list. The second constructor builds an array list that is initialized with
the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The
capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as
elements are added to an array list. The following program shows a simple use of ArrayList. An array list is
created, and then objects of type String are added to it. (Recall that a quoted string is translated into a String
object.) The list is then displayed. Some of the elements are removed and the list is displayed again.

// Demonstrate ArrayList.

import java.util.*;

class ArrayListDemo {
public static void main(String args[]) {

// create an array list

ArrayList al = new ArrayList();

System.out.println("Initial size of al: " + al.size());

// add elements to the array list

al.add("C");

al.add("A");

al.add("E");

al.add("B");

al.add("D");

al.add("F");

al.add(1, "A2");

System.out.println("Size of al after additions: " + al.size());

// display the array list

System.out.println("Contents of al: " + al);

// Remove elements from the array list

al.remove("F");

al.remove(2);

System.out.println("Size of al after deletions: " + al.size());

System.out.println("Contents of al: " + al);

The output from this program is shown here:

Initial size of al: 0

Size of al after additions: 7

Contents of al: [C, A2, A, E, B, D, F]

Size of al after deletions: 5

Contents of al: [C, A2, E, B, D]

Notice that a1 starts out empty and grows as elements are added to it. When
elements are removed, its size is reduced.

b) What is need of static method? Explain why main method in Java is always static.

Answer 3(b):

Static use no instance variables of any object of the class they are defined in. If you define a method to be static,
you will be given a rude message by the compiler if you try to access any instance variables. You can access
static variables, but except for constants, this is unusual. Static methods typically take all they data from
parameters and compute something from those parameters, with no reference to variables. This is typical of
methods which do some kind of generic calculation. A good example of this are the many utility methods in the
predefined Math class. Main () is staticand public : They are public because they must be accessible to the JVM
to begin execution of the program. Main is the first method that would get executed in any class. They are static
because they must be available for execution without an object instance. you may know that you need an object
instance to invoke any method. So you cannot begin execution of a class without its object if the main method
was not static.

shiva hari

Re: MCS-024 - Object Oriented Technologies And Java Programming - MCA(2)/024/Assign/09 Posted On:
2/16/2010 3:26:21 PM

1 b) What is encapsulation? Explain the advantages of encapsulation.

Answer 1 (b):

Encapsulation is the term given to the process of hiding all the details of an object

that do not contribute to its essential characteristics.

So, encapsulation hides the implementation details of the object and the only thing

that remains externally visible is the interface of the object. (i.e.: the set of all

messages the object can respond to)


Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they
are packaged and are only indirectly accessible via the interface of the object. The only way to access such an
encapsulated object is via message passing: one sends a message to the object, and the object itself selects the
method by which it will react to the message, determined by functions.

There is another form of encapsulation.

It is called object based encapsulation. Object-based encapsulation "packages" all the implementation details in
the object. All data and the implementation of all methods operating on this data are incorporated into the same
abstract entity representing the object. However, with this type of encapsulation an object can only make use of its
own attributes and private resources. An object-based encapsulation module has no direct access to the
implementation details of any of its acquaintances

Advantages:

Benefits of Encapsulation in oops:

Encapsulation makes it possible to separate an objects implementation from its

behavior to restrict access to its internal data. This restriction allows certain details of an objects behavior to be
hidden. It allows us to create a "black box" and protects an objects internal state from corruption by its clients.

Encapsulation is a technique for minimizing inter dependencies among modules by defining a strict external
interface. This way, internal coding can be changed without affecting the interface, so long as the new
implementation supports the same (or upwards compatible) external interface. So encapsulation prevents a
program from becoming so interdependent that a small change has massive ripple effects.

The implementation of an object can be changed without affecting the application that uses it for: Improving
performance, fix a bug, consolidate code or for porting.

Gurvir Kaur Sandhu


Re: MCS-024 - Object Oriented Technologies And Java Programming - MCA(2)/024/Assign/09 Posted On:
2/16/2010 3:27:53 PM

Question 4 : a) What is inheritance? Why abstract classes are used in inheritance? Write a program in Java to
explain use of abstract class in multilevel inheritance.

Answer 4 (a):

Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes,
and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence,
current gear). Yet

each also defines additional features that make them different: tandem bicycles have two seats and two sets of
handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a
lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In
this example, Bicycle now becomes the superclass of ountainBike, RoadBike, and TandemBike. In the Java
programming language, each class is allowed to have one direct superclass, and each superclass has the
potential for an unlimited number of subclasses:

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword,
followed by the name of the class to inherit from:

class MountainBike extends Bicycle

// new fields and methods defining a mountain bike would go here

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on
the features that make it unique. This makes code for your subclasses easy to read. However, you must take care
to properly document the state and behavior that each superclass defines, since that code will not appear in the
source file of each subclass.

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract
classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and followed by a
semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, the class itself must be declared abstract,

as in:

public abstract class GraphicObject {

// declare fields

// declare non-abstract methods

abstract void draw();

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract
methods in its parent class. However, if it does not, the subclass must also be declared abstract.

Abstract class A {

int x;

int y;

int get(int p, int q){

x=p; y=q; return(0);

void Show(){

System.out.println(x);

class B extends A{

void Showb(){

System.out.println("B");
}

class C extends B{

void display(){

System.out.println("C");

public static void main(String args[]){

A a = new B();

a.get(5,6);

a.Show();

b) Explain the need of package. Also explain different access rules for packages in Java programming.

Answer 4 (b):

Setting up Class Packages

It is easy to organize class files into packages. All you do is put related class files

in the same directory, give the directory a name that relates to the purpose of the classes, and add a line to the
top of each class file that declares the package name,

which is the same as the directory name where they reside. Declare the Packages Each *.java file needs a
package delcaration at the top that reflects the name of the directory. Also, the fruit order (client1 and view order
(client2) client class files need an import statement for the server package because they have to access the
remote server object at runtime.

As an example, the package declaration and import statements for the

RMIClient2.java class file look like this:

//package declaration

package client2;

import java.awt.Color;
import java.awt.GridLayout;

import java.awt.event.*;

import javax.swing.*;

import java.io.*;

import java.net.*;

import java.rmi.*;

import java.rmi.server.*;

import java.util.*;

import java.text.*;

//Import server package

import server.*;

Make Classes and Fields Accessible

With class files organized into packages, you have to declare the server classes in the server directory public so
they can be instantiated by client programs, which are created from classes in the client1 and client2 directories. If
you do not specify public, a class can only be instantiated by an object created from a class in the same package.
So client programs can access the fruit order data, the fields of the DataOrder

class have to be public too. The RemoteServer class and Send interface need to be public classes, but their fields
do not need to be public because the do not have public data.

Fields and methods without an access specifier such as public can only be accessed by objects created from
classes in the same package. Here is the new DataOrder class.

package server;

import java.io.*;

//Make class public

public class DataOrder implements Serializable{

//Make fields public

public String apples, peaches, pears, cardnum, custID;

public double icost;

public int itotal;

}
Access Rules

A package may be classified as one of the following:

1. Accessible

2. Forbidden

3. Internal

4. Internal with friends

PDE translates these runtime visibility rules into compiler access restriction rules at compile time. As a result, a
violation of a visibility rule is flagged by the compiler as a warning or an error - depending on the severity of that
violation. With this type of support at compile time, one is never caught by surprise by runtime class loading errors
and is always aware of internal type references. Accessible Packages Accessible packages are visible to
downstream plug-ins unconditionally. While API packages must clearly fall in this category, it is completely up to
the developer to decide what other packages exported by the plug-in ought to be given this level of visibility. In
order to declare a package as accessible, you must list it in the Exported Packages section on the Runtime of the
plug-in manifest editor and leave the default visibility setting as-is. Forbidden Packages You can hide a package
from downstream plug-ins at all times by excluding it from the list in the Exported Packages section on the
Runtime page of the plugin manifest editor.

References to types from a forbidden package result in class loading errors at runtime.

Internal Packages Internal packages are packages that are not intended for use by downstream plugins. These
packages are visible to downstream plug-ins by default.

Internal packages are hidden from downstream plug-ins only when Eclipse is launched in strict mode (i.e. when
you launch with the -Dosgi.resolverMode=strict VM argument).

Internal packages must be listed in the Exported Packages section on the Runtime page of the plug-in manifest
editor with the hidden option selected.
Reshma biju

Re: MCS-024 - Object Oriented Technologies And Java Programming - MCA(2)/024/Assign/09 Posted On:
2/16/2010 3:28:53 PM

Question 5: a) What is an exception? Explain different types of exceptions in Java.Also explain haw an exception
subclass are created, in Java.

Answer :a)

Exceptions are the customary way in Java to indicate to a calling method that an abnormal condition has
occurred. This article is a companion piece to this month's Design Techniques installment, which discusses how
to use exceptions appropriately in your programs and designs. Look to this companion article for a tutorial on the
nuts and bolts of what exceptions are and how they work in the Java language and virtual machine.

When a method encounters an abnormal condition (an exception condition) that it can't handle itself, it may throw
an exception. Throwing an exception is like throwing a beeping, flashing red ball to indicate there is a problem
that can't be handled where it occurred. Somewhere, you hope, this ball will be caught and the problem will be
dealt with. Exceptions are caught by handlers positioned along the thread's method invocation stack. If the calling
method isn't prepared to catch the exception, it throws the exception up to its calling method, and so on. If one of
the threads of your program throws an exception that isn't caught by any method along the method invocation
stack, that thread will expire. When you program in Java, you must position catchers (the exception handlers)
strategically, so your program will catch and handle all exceptions from which you want your program to recover.
there are two types of exceptions in java

1> checked exceptions

checked exceptions are also known as compile time exceptions as they are identified during compile time of the
program. Exception and all the subclasses of Exception class are checked exceptions

2> Unchecked exceptions

Unchecked Exceptions are also known as runtime exceptions as they are identified during the runtime of the
program. class RuntimeException and all the subclasses of RuntimeException are unchecked Exceptions
Exception subclass constructor Creates an exception subclass.

Syntax
public exception_subclass(CWConnectorExceptionObject excption) where exception_subclass is the name of the
exception subclass (as shown in Table 142). Parameters excption is an exception object that contains information
about the exception. Return values An object that represents a subclass of the CWException class.

b) Differentiate between String and String Buffer classes. Also write a program to append a given string.

b)

String and StringBuilder class stores strings. But when you cannot change a String

object after creating one.

eg: String name = "Prasad";

By saying you cannot change the name object means you cannot change the value in name object internally.
When you change the name object value to something else, a new String object is creating in memory and assign
the new value.

eg: name = "Prasad Reddy";

A new name object is creating in memory and the value "Prasad Reddy" is assinging to the newly created space.
But StringBuilder class occupies the same space even if you change the value. If you are doing string
concatenation StringBuilder class is far better in performance than String class.

You can use StringBuilder's Append() method to use concatenation. Java provides the StringBuffer and String
classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated,
objects of type String are read only and immutable. The StringBuffer class is used to represent characters that
can be modified.

The significant performance difference between these two classes is that StringBuffer is faster than String when
performing simple concatenations. In String manipulation code, character strings are routinely concatenated.
Using the String class, concatenations are typically performed as follows:

String str = new String ("Stanford ");

str += "Lost!!";

If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:
StringBuffer str = new StringBuffer ("Stanford ");

str.append("Lost!!");

Murty BVS

Re: MCS-024 - Object Oriented Technologies And Java Programming - MCA(2)/024/Assign/09 Posted On:
2/16/2010 3:30:17 PM

Question 6 : a) What is multithreading ? Explain how synchronization is achieved in a multithreaded program in


Java.

Answer a) :

Multithreaded programs are similar to the single-threaded programs that you have been studying. They differ only
in the fact that they support more than one concurrent thread of execution-that is, they are able to simultaneously
execute multiple sequences of instructions. Each instruction sequence has its own unique flow of control that is
independent of all others. These independently executed instruction sequences are known as threads.

If your computer has only a single CPU, you might be wondering how it can execute more than one thread at the
same time. In single-processor systems, only a single thread of execution occurs at a given instant. The CPU
quickly switches back and forth between several threads to create the illusion that the threads are executing at the
same time. Single-processor systems support logical concurrency, not physical concurrency. Logical concurrency
is the characteristic exhibited when multiple threads execute with separate, independent flows of control. On
multiprocessor systems, several threads do, in fact, execute at the same time, and physical concurrency is
achieved. The important feature of multithreaded programs is that they support logical concurrency, not whether
physical concurrency is actually achieved.
Many programming languages support multiprogramming. Multiprogramming is the logically concurrent execution
of multiple programs. For example, a program can request that the operating system execute programs A, B, and
C by having it spawn a separate process for each program. These programs can run in parallel, depending upon
the multiprogramming features supported by the underlying operating system. Multithreading differs from
multiprogramming in that multithreading provides concurrency within the context of a single process and
multiprogramming provides concurrency between processes. Threads are not complete processes in and of
themselves. They are a separate flow of control that occurs within a process.

An executing program is generally associated with a single process. The advantage of multithreading is that
concurrency can be used within a process to provide multiple simultaneous services to the user. Multithreading
also requires less processing overhead than multiprogramming because concurrent threads are able to share
common resources more easily. Multiple executing programs tend to duplicate resources and share data as the
result of more time-consuming interprocess communication.

How Java Supports Multithreading

Java's multithreading support is centered around the java.lang.Thread class. The Thread class provides the
capability to create objects of class Thread, each with its own separate flow of control. The Thread class
encapsulates the data and methods associated with separate threads of execution and allows multithreading to
be integrated within the object-oriented framework. Java provides two approaches to creating threads. In the first
approach, you create a subclass of class Thread and override the run() method to provide an entry point into the
thread's execution. When you create an instance of your Thread subclass, you invoke its start() method to cause
the thread to execute as an

independent sequence of instructions. The start() method is inherited from the Thread class. It initializes the
Thread object using your operating system's multithreading capabilities and invokes the run() method. You learn
how to create threads using this approach in the next section. The approach to creating threads identified in the
previous paragraph is very simple and straightforward. However, it has the drawback of requiring your Thread
objects to be under the Thread class in the class hierarchy. In some cases, as you'll see when you study applets
in Part VI, "Programming the Web with

Applets and Scripts," this requirement can be somewhat limiting. Java's other approach to creating threads does
not limit the location of your Thread objects within the class hierarchy. In this approach, your class implements the
java.lang.Runnable interface. The Runnable interface consists of a single method, the run() method, which must
be overridden by your class. The run() method provides an entry point into your thread's execution. In order to run
an object of your class as an independent thread, you pass it as an argument to a constructor of class Thread.
You learn how to create threads using this approach later in this chapter in the section titled "Implementing
Runnable."

Creating Subclasses of Thread In this section, you create your first multithreaded program by creating a subclass
of Thread and then creating, initializing, and starting two Thread objects from your class. The threads will execute
concurrently and display Java is hot, aromatic, and invigorating. to the console window.

The source code of the ThreadTest1 program.

class ThreadTest1
{

public static void main(String args[])

MyThread thread1 = new MyThread("thread1: ");

MyThread thread2 = new MyThread("thread2: ");

thread1.start();

thread2.start();

boolean thread1IsAlive = true;

boolean thread2IsAlive = true;

do {

if ( thread1IsAlive && !thread1.isAlive() ) {

thread1IsAlive = false;

System.out.println("Thread 1 is dead.");

if (thread2IsAlive && !thread2.isAlive()) {

thread2IsAlive = false;

System.out.println("Thread 2 is dead.");

} while(thread1IsAlive || thread2IsAlive);

}}

class MyThread extends Thread

static String message[] =

{ "Java", "is", "hot,", "aromatic,", "and", "invigorating."};

public MyThread(String id)

super(id);

public void run()


{

String name = getName();

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

randomWait();

System.out.println(name + message[i]);

}}

void randomWait()

try {

sleep((long)(3000*Math.random()));

} catch (InterruptedException x) {

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

}}}

This program creates two threads of execution, thread1 and thread2, from the MyThread class. It then starts both
threads and executes a do statement that waits for the threads to die. The threads display the Java is hot,
aromatic, and invigorating. message word by word, while waiting a short, random amount of time between each
word. Because both threads share the console window, the program's output identifies which threads were able to
write to the console at various times during the program's execution.

Run ThreadTest1 to get an idea of the output that it produces. Each time you run the program you might get a
different program display. This is because the program uses a random number generator to determine how long
each thread should wait before displaying its output. Look at the following output:

C:\java\jdg\ch08>java ThreadTest1

thread1: Java

thread2: Java

thread2: is

thread2: hot,

thread2: aromatic,

thread1: is
thread1: hot,

thread2: and

thread1: aromatic,

thread1: and

thread2: invigorating.

Thread 2 is dead.

thread1: invigorating.

Thread 1 is dead.

This output shows that thread1 executed first and displayed Java to the console window. It then waited to execute
while thread2 displayed Java, is, hot,, and aromatic,. After that, thread2 waited while thread1 continued its
execution. thread1 displayed is and then hot,. At this point, thread2 took over again. thread2 displayed and and
then went back into waiting. thread1 then displayed aromatic, and and. thread2 finished its execution by
displaying invigorating.. Having completed its execution, thread2 died, leaving thread1 as the only executing task.
thread1 displayed invigorating. and then completed its execution.

The ThreadTest1 class consists of a single main() method. This method begins by creating thread1 and thread2
as new objects of class MyThread. It then starts both threads using the start() method. At this point, main() enters
a do loop that continues until both thread1 and thread2 are no longer alive. The loop monitors the execution of the
two threads and displays a message when it has detected the death of each thread. It uses the isAlive() method
of the Thread class to tell when a thread has died. The thread1IsAlive and thread2IsAlive variables are used to
ensure that a thread's obituary is only displayed once.

The MyThread class extends class Thread. It declares a statically initialized array, named message[], that
contains the message to be displayed by each thread. It has a single constructor that invokes the Thread class
constructor via super(). It contains two access methods: run() and randomWait(). The run() method is required. It
uses the getName() method of class Thread to get the name of the currently executing thread. It then prints each
word of the output display message while waiting a random length of time between each print.

The randomWait() method invokes the sleep() method within a try statement. The sleep() method is another
method inherited from class Thread. It causes the currently executing task to "go to sleep" or wait until a randomly
specified number of milliseconds has transpired. Because the sleep() method throws the InterruptedException
when its sleep is interrupted (how grouchy!), the exception is caught and handled by the randomWait() method.

The exception is handled by displaying the fact that an interruption has occurred to the console window. It is not
possible for one thread to modify a shared variable while another thread is in the process of using or updating
same shared variable. This usually leads to significant errors. Synchronization in respect to multithreading
controls the access of multiple threads to shared resources.
b) Explain how files are handled in Java ? Write a program in Java to create a file and copy the content of an
already existing file into it.

Answer b) :

One of the first things a programmer learns with a new language is how to read and write to files, since the saving
and loading of data will be an important feature of most software he or she will eventually develop using that
language.

Java offers extensive - yet easy to use - file handling classes that make it a breeze

to read and write files. In this tutorial, we'll start by covering the basics of file input and output, as well as covering
some associated topics, such as trapping exceptions and I/O errors.

File output

Our first example will be a program that writes a string to a file. In order to use the

Java file classes, we must import the Java input/output package (java.io) in the following manner

import java.io.*;

Inside the main method of our program, we must declare a FileOutputStream object. For those familiar with C, a
FileOutputStream is analogous to a file handle. When we send a stream (or sequence) of data to the
FileOutputStream handle, data will be written to disk.

In Java, there exists a large number of extensions to the standard input and output stream classes. This is handy,
as the basic input and output streams deal only with the transfer of bytes - not the easiest way for us to write out
data. There's a wide variety of streams to choose from : if we were writing data such as bytes, integers, floats, or
other "data" orientated types, we might choose the DataOutputStream, whereas for text we'd use the PrintStream
class.

In this case, we wish to write a string to the file, and so we create a new PrintStream object that takes as its
constructor the existing FileOutputStream. Any data we send from PrintStream will now be passed to the
FileOutputStream, and ultimately to disk. We then make a call to the println method, passing it a string, and then
close the connection.
/*

* FileOutputDemo

* Demonstration of FileOutputStream and

* PrintStream classes

*/

import java.io.*;

class FileOutputDemo

public static void main(String args[])

FileOutputStream out; // declare a file output object

PrintStream p; // declare a print stream object

try

// Create a new file output stream

// connected to "myfile.txt"

out = new FileOutputStream("myfile.txt");

// Connect print stream to the output stream

p = new PrintStream( out );

p.println ("This is written to a file");

p.close();

catch (Exception e)

System.err.println ("Error writing to file");

}}}
Listing 1.0 - FileOutputDemo.java

After running the output example, and seeing that it wrote to our file, let's take a more detailed look at the code.
You may be wondering what the purpose of the try { .. } catch block is. Rather than checking for erroneous return
values (such as a null pointer when obtaining an output stream as is the case with C's fopen), we catch
exceptions.

Exceptions are events that occur in exceptional or unusual circumstances, such as error conditions. A method can
throw an exception, to indicate to the calling object that a non-standard circumstance has occurred. Thus, instead
of checking each and every file method call, we have one piece of code handling all possible errors! File input File
input under Java differs little from file output. We must import the Java IO package, and we create a file input
stream inside of a try { .. } catch block as in the previous example.

In this example, the file we open is given to us as the first command line parameter. We obtain this by examining
the args array of strings. Since an array is an actual object in Java, we can find the length of the array (and hence
the number of parameters) through the length attribute.

To do anything useful with file input, we create a DataInputStream which can handle reading in data as well as
lines of text. To determine if there is any data left to read, we call the available() method of our input stream. This
method returns the number of bytes remaining, which we check to see is not equal to zero. Then we call the
DataInputStream's readLine() method and print the result to the screen.

/*

* FileInputDemo

* Demonstrates FileInputStream and

* DataInputStream

*/

import java.io.*;

class FileInputDemo

public static void main(String args[])

// args.length is equivalent to argc in C


if (args.length == 1)

try

// Open the file that is the first

// command line parameter

FileInputStream fstream = new

FileInputStream(args[0]);

// Convert our input stream to a

// DataInputStream

DataInputStream in =

new DataInputStream(fstream);

// Continue to read lines while

// there are still some left to read

while (in.available() !=0)

// Print file line to screen

System.out.println (in.readLine());

in.close();

catch (Exception e)

System.err.println("File input error");

}}

else

System.out.println("Invalid parameters");

}
Listing 1.1 - FileInputDemo.java

import java.io.BufferedReader;

import java.io.FileReader;

public class File1{

public static void main(String[] args) {

try{

BufferedReader ds=new BufferedReader(new FileReader("c://a.txt"));

String str=ds.readLine();

System.out.println("File contains : "+str);

}catch(Exception e)

System.out.println(e);

Output :-

File contains : Hi from baluja abc

import java.io.BufferedWriter;

import java.io.FileWriter;

public class File2{

public static void main(String[] args) {

try{

BufferedWriter bw=new BufferedWriter(new FileWriter("c://b.txt"));

bw.write("Auspicious Day abc ");

bw.close();

}catch(Exception e)

System.out.println(e);

}
}

Output :-

b.txt::

Auspicious Day

Kulpreet Singh

Re: MCS-024 - Object Oriented Technologies And Java Programming - MCA(2)/024/Assign/09 Posted On:
2/16/2010 3:31:40 PM

Question 7: a) What is Layout Manager? Explain different layout available in Java.

Answer a) :

Layouts tell Java where to put components in containers (JPanel, content pane, etc). Every panel (and other
container) has a default layout, but it's better to set the layout explicitly for clarity. Create a new layout object
(using one of its constructors) and use the container's setLayout method to set the layout. Each layout has its own
way to resize components to fit the layout, and you must become familiar with these.

• FlowLayout - left to right, top to bottom. Good for initial testing. FlowLayout does not respect preferred size
information, so it may make variable size elements (eg, a graphics panel) extremely small.

• BorderLayout - north, east, south, west, and center areas. Has various rules for how components are stretched
to fit these areas. Both common and useful.
• GridLayout - equal sized grid elements.

• BoxLayout and Boxes - horizontal or vertical sequence of components.

• GridBagLayout - unequal sized grid. Can produce excellent results, but can be difficult to use.

• SpringLayout was added in Java 1.4, but is difficult for humans. It is rumored to be intended for authomatic
layout programs.

• CardLayout is good for something like a wizard interface which shows one of several possible layouts (think
about a stack of index cards)

• Tabbed panes are something like a card layout with tabs.

• The Null layout (absolute positioning) is possible, but is a bad idea.

• Tabbed panes are something like a card layout with tabs. They are not implemented as a layout, but as a type of
panel.

• Non-standard layout managers. Because of deficiencies in the standard Java

layout managers, several good, free, alternatives exist.

b) What is socket? Explain basic networking features of Java.

Answer b) :

Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The
server just waits, listening to the socket for a client to make a connection request.

On the client-side: The client knows the hostname of the machine on which the server is running and the port
number on which the server is listening. To make a connection request, the client tries to rendezvous with the
server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local
port number that it will use during this connection. This is usually assigned by the system.

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound
to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new
socket so that it can continue to listen to the original socket for connection requests while tending to the needs of
the connected client.

On the client side, if the connection is accepted, a socket is successfully created

and the client can use the socket to communicate with the server.

The client and server can now communicate by writing to or reading from their sockets.

Definition: A socket is one endpoint of a two-way communication link between two programs running on the
network. A socket is bound to a port number so that the TCP layer can identify the application that data is
destined to be sent.

Java Network Features: Intro

Most people assume that Java is a vehicle written for web browsers, i.e. to 'spice up' web pages. While we know
by know that that is not true at all, what is true that Java is a language written with the Internet in mind. Therefore,
Java has a lot of network support built in, and you can make use of it in a variety of ways. We will start our
'network explorations' by looking at the classes in the java.applet package, in particular at the

java.applet.AppletContext class: public abstract Applet getApplet(String name);

public abstract Enumeration getApplets();

public abstract AudioClip getAudioClip(URL url);

public abstract Image getImage(URL url);

public abstract void showDocument(URL url);

public abstract void showDocument(URL url, String target);

public abstract void showStatus(String status);

An AppletContext, usually, provides a hook to the current web browser used.

Therefore, using this class we should be able to load images, audio clips, display

messages in the status bar of our web browser, and display other web documents in
the web browser. Here, for example is a little applet that displays a message in the

browser's status bar. Of course, if you are not using a web browser (but, say, the

appletviewer) to look at this applet, nothing may happen (but also no error will

occur).

import java.applet.*;

import java.awt.*;

public class NetExample extends Applet

private AppletContext browser = null;

private Button showStatus = new Button("Show Status");

public void init()

Panel panel = new Panel();

panel.setLayout(new GridLayout(1,2));

panel.add(showStatus);

setLayout(new BorderLayout());

add("South", panel);

browser = getAppletContext();

public boolean action(Event e, Object o)

if (e.target == showStatus)

browser.showStatus("Here is something for your status line ...");

return true;

}}

IPv6 (Internet Protocol version 6) J2SETM 1.4 supports IPv6 in TCP and UDP-based applications, including
multicast, and will support most end-user applications in use today. See the IPv6 User Guide.
HTTP Digest Authentication

The HTTP digest authentication implementation has been updated to support proxies as well as origin servers,
and has also been updated to provide all capabilities defined in RFC2617, except for the auth-int mode.

A number of system properties have been added which modify the behavior of the digest authentication
mechanism. These are identified in the Networking Properties document.

Unconnected/Unbound Socket Support Allows more flexible socket creation, binding, and connection. Enables
manipulation of socket options before establishing or accepting connections. In addition a timeout can be
specified when establishing a connection.

New class javax.net.ssl.SSLSocket is a subclass of java.net.Socket that provides security through encryption. The
mechanism is called the Java Secure Socket Extension (JSSE), and it provides encryption for data sent via
sockets. See the JSSE Reference Guide for further information. Connected UDP Socket Support The
DatagramSocket.connect method now establishes the address association at native level. Where supported, this
allows an application to have visibility of ICMP port unreachable messages as an indication that the remote
application is unavailable.

Uniform Resource Indentifier (URI) Class java.net.URI is new in J2SE 1.4. It allows URI construction and parsing
without the presence of a protocol handler, which is not possible with the URL class. The URI class is compliant
with RFC 2396 and RFC 2732. FTP Protocol Handler Significant overhaul to make the functionality conform as
much as possible to the current standards (RFC 1738 & 959). This enhancement fixes several bugs

associated with FTP functionality. For example, passive mode for FTP works in J2SE 1.4.

JNDI DNS SP Support in InetAddress This enhancement in class java.net.InetAddress enables applications to
configure a pure Java name service provider by using a DNS name service provider through JNDI. See JNDI
DNS service provider settings in the Network

Properties document for information on enabling this support. URLEncoder and URLDecoder Improvements
Methods URLEncoder.encode(String s, String enc) and URLDecoder.decode(String s, String enc) have been
added to enable applications to use other character encoding/decoding schemes.

TCP Out-of-Band Data Two new methods in class java.net.Socket, sendUrgentData() and

getOOBInline(), provide limited support for TCP urgent data for support certain legacy applications. Urgent data
may be sent on any TCP socket. However, only partial support for receiving urgent data is provided. SOCKS Full
V5 (RFC 1928) & V4 TCP support with autonegociation with the proxy of which version to use. See the SOCKS
protocol support settings in the Network Properties document for information about using properties to specify the
SOCKS proxy server.

NetworkInterface

Class java.net.NetworkInterface is new in J2SE 1.4. It allows enumeration of interfaces and addresses. This new
class should be useful to applications deployed on multihomed and machines with multiple network interfaces
Reshma biju

Re: MCS-024 - Object Oriented Technologies And Java Programming - MCA(2)/024/Assign/09 Posted On:
2/16/2010 3:32:54 PM

Question 8 : a) Explain how databases are connected to a Java program.

Answer : a)

Java Database Connectivity (JDBC) is a programming framework for Java developers writing programs that
access information stored in databases, spreadsheets, and flat files. JDBC is commonly used to connect a user
program to a "behind the scenes" database, regardless of what database management software is used to control
the database. In this way, JDBC is cross-platform [ 1]. This article will provide an introduction and sample code
that demonstrates database access from Java programs that use the classes of the JDBC API, which is available
for free download from Sun's site [ 3].

A database that another program links to is called a data source. Many data sources, including products produced
by Microsoft and Oracle, already use a standard called Open Database Connectivity (ODBC). Many legacy C and
Perl programs use ODBC to connect to data sources. ODBC consolidated much of the commonality between
database management systems. JDBC builds on this feature, and increases the level of abstraction. JDBC-ODBC
bridges have been created to allow Java programs to connect to ODBC-enabled database software [ 1].

This article assumes that readers already have a data source established and are moderately familiar with the
Structured Query Language (SQL), the command language for adding records, retrieving records, and other basic
database manipulations. See Hoffman's tutorial on SQL if you are a beginner or need some refreshing [ 2]. Using
a JDBC driver Regardless of data source location, platform, or driver (Oracle, microsoft, etc.), JDBC makes
connecting to a data source less difficult by providing a collection of classes that abstract details of the database
interaction. Software engineering with JDBC is also conducive to module reuse. Programs can easily be ported to
a different infrastructure for which you have data stored (whatever platform you choose to use in the future) with
only a driver substitution.
As long as you stick with the more popular database platforms (Oracle, Informix, Microsoft, MySQL, etc.), there is
almost certainly a JDBC driver written to let your programs connect and manipulate data. You can download a
specific JDBC driver from the manufacturer of your database management system (DBMS) or from a third party
(in the case of less popular open source products) [ 5]. The JDBC driver for your database will come with specific
instructions to make the class files of the driver available to the Java Virtual Machine, which your program is going
to run. JDBC drivers use Java's built-in DriverManager to open and access a database from within your Java
program.

To begin connecting to a data source, you first need to instantiate an object of your

JDBC driver. This essentially requires only one line of code, a command to the DriverManager, telling the Java
Virtual Machine to load the bytecode of your driver into memory, where its methods will be available to your
program. The String parameter below is the fully qualified class name of the driver you are using for your platform
combination:

Class.forName("org.gjt.mm.mysql.Driver").newInstance();

Connecting to your database To actually manipulate your database, you need to get an object of the Connection
class from your driver. At the very least, your driver will need a URL for the database and parameters for access
control, which usually involves

standard password authentication for a database account. As you may already be aware, the Uniform Resource
Locator (URL) standard is good for much more than telling your browser where to find a web page:
http://www.vusports.com/index.html The URL for our example driver and database looks like this:
jdbc:mysql://db_server:3306/contacts/ Even though these two URLs look different, they are actually the same in
form: the protocol for connection, machine host name and optional port number, and the relative path of the
resource. Your JDBC driver will come with instructions detailing how to form the URL for your database. It will look
similar to our example.

You will want to control access to your data, unless security is not an issue. The standard least common
denominator for authentication to a database is a pair of strings, an account and a password. The account name
and password you give the driver should have meaning within your DBMS, where permissions should have been
established to govern access privileges.

b) Explain difference between applets and application programs.

Answer b) :

Applets as previously described, are the small programs while applications are larger programs. Applets don't
have the main method while in an application execution starts with the main method. Applets can run in our
browser's window or in an appletviewer. To run the applet in an appletviewer will be an advantage for debugging.
Applets are designed for the client site programming purpose while the applications don't have such type of
criteria. Applet are the powerful tools because it covers half of the java language picture. Java applets are the
best way of creating the programs in java. There are a less number of java programmers that have the hands on
experience on java applications. This is not the deficiency of java applications but the global utilization of internet.
It doesn't mean that the java applications don't have the place. Both (Applets and the java applications) have the
same importance at their own places. Applications are also the platform independent as well as byte oriented just
like the applets.

Applets are designed just for handling the client site problems. while the java applications are designed to work
with the client as well as server. Applications are designed to exists in a secure area. while the applets are
typically used. Applications and applets have much of the similarity such as both have most of the same features
and share the same resources. Applets are created by extending the java.applet.Applet class while the java
applications start execution from the main method. Applications are not too small to embed into a html page so
that the user can view the application in your browser. On the other hand applet have the accessibility criteria of
the resources. The key feature is that while they have so many differences but both can perform the same
purpose. Review of Java Applets: You have previously learned about the java applets.

To create an applet just create a class that extends the java.applet.Applet class and inherit all the features
available in the parent class. The following programs make all the things clear.

import java.awt.*;

import java.applet.*;

class Myclass extends Applet {

public void init() {

/* All the variables, methods and images initialize here will be called only

once because this method is called only once when the applet is first initializes */

public void start() {

/* The components needed to be initialize more than once in your applet are

written here or if the reader switches back and forth in the applets. This method can be called more than once.*/

public void stop() {

/* This method is the counterpart to start(). The code, used to stop the
execution is written here*/

public void destroy() {

/* This method contains the code that result in to release the resources to the

applet before it is finished. This method is called only once. */

public void paint(Graphics g) {

/* Write the code in this method to draw, write, or color things on the applet

pane are */

}}

In the above applet you have seen that there are five methods. In which two ( init() and destroy ) are called only
once while remaining three (start() , stop() , and paint() ) can be called any number of times as per the
requirements. The major difference between the two (applet and application) is that java applications are
designed to work under the homogenous and more secure areas.

On contrary to that, java applets are designed to run the heterogeneous and probably unsecured environment.
Internet has imposed several restrictions on it. Applets are not capable of reading and writing the user's file
system. This means that the applet neither can access nor place anything locally. To illustrate this lets take an
example.. Many Window based C applications uses the .INF file as the initialization file to store the information
about the application and any user preferences in 16-bit Windows or the Registry in 32-bit Windows. While in
case of current applet it is not possible. One more thing to point here is that applets are unable to use the native
methods, run any program on the user system or load shared libraries. The major security

concern here is that the local shared libraries and the native methods may results in the loophole in the java
security model.

Applets are not capable of communicating the server than one from which they are originating. There are the
cases in which an encryption key is used for the verification purpose for a particular applet to a server. But
accessing a remote server is not possible. The conclusion is that the java applets provides a wide variety of
formats for program execution and a very tight security model on the open environment as
on the Internet. Introduction to Java Application : Java applications have the majority of differences with the java
applets. If we talk at the source code level, then we don't extend any class of the standard java library that means
we are not restricted to use the already defined method or to override them for the execution of the program.
Instead we make set of classes that contains the various parts of the program and attach the main method with
these classes for the execution of the code written in these classes. The following program illustrate the structure
of the java application.

public class MyClass {

/* Various methods and variable used by the class MyClass are written here */

class myClass {

/* This contains the body of the class myClass */

public static void main(String args[]) {

/* The application starts it's actual execution from this place. **/

}}

The main method here is nothing but the system method used to invoke the application. The code that results an
action should locate in the main method. Therefore this method is more than the other method in any java
application. If we don't specify the main method in our application, then on running the application will through an
exception like this one: In the class MyClass: void main(String args[]) is undefined But at higher level major
concern is that in a typical java application security model, an application can access the user's file system and
can use native methods. On properly configuring the user's environment and the java application it will allow
access to all kind of stuff from the Internet.

In most of the cases it is seen that the java application seems like a typical C/C++ application. Now we are going
to create plenty of applications to exemplify some of the methods and features of a specific Java application. All of
them are console based Java applications because here we are not going to cover the AWT.

Java Applications : An Example Lets create an application that executes at the command prompt. Lets create a
new file named

ClassA.java.

public class ClassA{

//write the variables for Class

String Name;
int AccNumber;

float Bal;

//This method display the information on the screen.

void display(){

System.out.println("Name: " + Name);

System.out.println("Account Number: " + AccNumber);

System.out.println("Balance: " + Bal);

public static void main(String args[]) {

//Create an instance of ClassA

ClassA a = new ClassA();

//Assigning values to the variables in class ClassA

a.Name = "Vinod";

a.AccNumber = 467256282;

a.Bal =635;

//Draw the top border

for (int i = 0; i < 20; i++)

System.out.print("--");

//Title

System.out.println(" PARTICULARS");

//Call method to display the information

a.display();

//Draw bottom border

for (int i = 0; i < 20; i++)

System.out.print("--");

//Ending remark

System.out.println("End of display");

}
If the file ClassA.java and the javac.exe are in the same directory then compile the program just by giving the
following command.

c) Explain the use of finalize() methods of Java with an example.

Answer c) :

Since objects are dynamically allocated by using the new operator, you might be wondering how such objects are
destroyed and their memory released for later deallocation. In some languages, such as C++, dynamically
allocated objects must be manually released by use of a delete operator.

Java takes a different approach; it handles deallocation for you automatically. The technique that accomplishes
this is called garbage collection. It works like this: when no references to an object to an object exist, that object is
assumed to be no longer needed, and the memory occupied by the object can be reclaimed. There is no explicit
need to destroy objects as in C++. Garbage collection only occurs sporadically (if at all) during the execution of
your program. It will not occur simply because one or more objects exist that are no longer used. Furthermore,
different java run-time implementations will take varying approaches to garbage collection, but for the most part,
you should not have to think about it while writing your programs The finalize () Method Sometimes an object will
need to perform some action when it is destroyed. For example, if an object is holding some non-java resource
such as a file handle or window character font, then you might want to make sure these resources are freed
before an object is destroyed. To handle such situations, java provides a mechanism called finalization. By using
finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the
garbage collector.

To add a finalizer to a class, you simply define the finalize() method. The java run time calls that method
whenever it is about to recycle an object of that class. Inside the finalize() method you will specify those actions
that must be performed before an object is destroyed. The garbage collector runs periodically, checking for
objects that are no longer referenced by any running state or indirectly through other referenced objects. Right
before an asset is freed, the java run time calls the finalize() method on the object.

The finalize() method has this general form:

protected void finalize()

// finalization code here

Here, the keyword protected is a specifier that prevents access to finalize() by


code defined outside its class.

d) Write a program in Java to show the use of checkbox and choice list components.

Answer d) :

Example :- 2 Checkbox demo

package buttons;

import java.applet.*;

import java.awt.event.*;

import java.awt.*;

/* < applet code="buttons.CheckBoxDemo" width="500" height="500" >

* < /applet >

*/

public class CheckBoxDemo extends Applet implements ItemListener {

String msg="";

Checkbox win98,winNt,solaris,mac;

public void init()

win98=new Checkbox("windows 98/xp",null,true);

winNt=new Checkbox("windowsNt/2000");

solaris=new Checkbox("solaris");

mac=new Checkbox("macos");

add(win98);

add(winNt);

add(solaris);

add(mac);

win98.addItemListener(this);

winNt.addItemListener(this);
solaris.addItemListener(this);

mac.addItemListener(this);

public void itemStateChanged(ItemEvent e) {

repaint();

public void paint(Graphics g)

msg="current state :";

g.drawString(msg, 6, 80);

msg="windows 98/xp :"+win98.getState();

g.drawString(msg, 6, 100);

msg="windows Nt/2000 :"+winNt.getState();

g.drawString(msg, 6, 120);

msg="solaris :"+solaris.getState();

g.drawString(msg, 6, 140);

msg="macos :"+mac.getState();

g.drawString(msg, 6, 160);

:- Choice demo

package buttons;

import java.applet.*;

import java.awt.event.*;

import java.awt.*;

public class ChoiceDemo extends Applet implements ItemListener {

Choice os,browser;

String msg="";
public void init()

os=new Choice();

browser=new Choice();

os.add("window 98/xp");

os.add("window Nt/2000");

os.add("solaris");

os.add("macos");

browser.add("netscape3.x");

browser.add("netscape4.x");

browser.add("netscape5.x");

browser.add("netscape6.x");

browser.add("internet explorer 4.0");

browser.add("internet explorer 5.0");

browser.add("internet explorer 6.0");

browser.add("lynx 2.4");

browser.select("netscape4.x");

add(os);

add(browser);

os.addItemListener(this);

browser.addItemListener(this);

public void itemStateChanged(ItemEvent e) {

repaint();

public void paint(Graphics g)

msg="current os : ";

msg+=os.getSelectedItem();
g.drawString(msg, 6, 120);

msg="current browser : ";

msg+=browser.getSelectedItem();

g.drawString(msg, 6, 140);

e) Explain the use of GET and POST methods in servlet programming.

Answer e) :

sending simple GET requests from Java is extremely easy (be it an application or a servlet), but sending multipart
forms, like when you upload files, is painful. The former can be done in one method call that does all the
underground work. The latter requires explicitly creating an HTTP request, which may include generating multipart
boundaries while being careful with the exact amount and selection of newlines (e.g., println() would not always
do the right job).

This article provides a simple solution that will relieve the pain of sending form data (like POST requests) from
Java in most real-world scenarios. The intention is to make POST requests as simple as GET requests, even
when sending multiple files of varying type (archives, XML, HTML, plain text, etc.).

GET and POST Requests

The two main methods for sending form data to a Web server are GET and POST. This section demonstrates
how each method works in three scenarios. (Do not try to reproduce these at home. The URLs and e-mail
addresses are fake.)

Example 1. GET Request

The following form uses the GET method:

< form method="get" action="hi.iq/register.jsp" >

Name: < input type="text" name="name" value="J.Doe" >

email: < input type="text" name="email" [Email address not allowed in post] >

< input type="submit" >

< /form >

Example 2. POST Request


Now, let's replace 'GET' with 'POST' in the form HTML tag:

< form method="post" action="hi.iq/register.jsp" >

Name: < input type="text" name="name" value="J.Doe" >

email: < input type="text" name="email" [Email address not allowed in post] >

< input type="submit" >

< /form >

Kulpreet Singh

MCS-024 - Object Oriented Technologies and Java Programming - Question 1(a) Posted On: 2/23/2010
5:23:34 PM

Object-oriented programming (OOP''') is a programming paradigm that uses "objects" and their interactions to
design applications and computer programs.

Object Oriented vs Structured Programming

Structured programming can be seen as a subset or sub discipline of procedural

programming, one of the major programming paradigms. It is most famous for

removing or reducing reliance on the GOTO statement [1].

The rise of the Object Oriented concept brought us debugging comfort as well as

expandability as the programs were getting larger and larger and it became difficult

to debug. There were functions to reduce the size of the programs and improve
readability but it was never enough.

Object-oriented programming (OOP) is a programming language model organized

around “objects” rather than “actions” and data rather than logic. Historically, a

program has been viewed as a logical procedure that takes input data, processes it,

and produces output data. The programming challenge was seen as how to write

the logic, not how to define the data. Object-oriented programming takes the view

that what we really care about are the objects we want to manipulate rather than the

logic required to manipulate them [2].

Object Oriented Programming has many benefits over Structured programming.

Some of them are reusability, extensibility, reliability and maintainability. OOP

also helps to reduce large problems to smaller, more manageable problems. In

terms of extensibility and reusability, for instance: “Encapsulation allows the

internal implementation of a class to be modified without requiring changes to its

services (i.e. methods). It also allows new classes to be added to a system, without

major modifications to the system. Inheritance allows the class hierarchy to be

further refined, and combined with polymorphism, the superclass does not have to

“know” about the new class, i.e. modifications do not have to be made at the

superclass” [3].

Another important discussion would be; do we really need classes? Can we not just

use functions instead? Considerable amount of people think that functions are

faster and require less code. On the other hand, someone would argue that classes

are more modular. I do not have any strict opinion on this subject. But, I think it

really depends on what you would like to achieve. For instance, I cannot think of

any reason why you would want to use classes to perform a very simple task such

as checking if the user fills out the name – surname field on the form.

“One of the frequently claimed benefits of the OOP is that it is natural (therefore

more understandable), and is assumed to be cognitively similar to the way human

beings perceive and understand the real-world (Meyer, (1988); Rosson & Alpert
(1988); Rosson & Alpert(1990). Martin & Odell (1992, p.31) for example, states

“The way of thinking is more natural for most people than the techniques of

structured analysis and design. After all, the world consists of objects.” Mcfadden

& Hoffer(1994, p.) similarly note “The notation and approach of the object oriented

data model builds on these paradigms that people constantly use to cope

with complexity.” This claim, therefore assumes that it is more natural for

developers to decompose a problem into objects, at least as compared to the

traditional structured languages. In other words, it should be natural for developers

and users to map the problem into objects and into classification hierarchies.”

Kulpreet Singh

MCS-024 - Object Oriented Technologies and Java Programming - Question 8(a) Posted On: 2/23/2010
5:23:34 PM

Question 8 :(a) Explain how databases are connected to a Java program.

Java Database Connectivity (JDBC) is a programming framework for Java

developers writing programs that access information stored in databases,

spreadsheets, and flat files. JDBC is commonly used to connect a user program to a

"behind the scenes" database, regardless of what database management software is

used to control the database. In this way, JDBC is cross-platform [ 1]. This article

will provide an introduction and sample code that demonstrates database access

from Java programs that use the classes of the JDBC API, which is available for

free download from Sun's site [ 3].


A database that another program links to is called a data source. Many data

sources, including products produced by Microsoft and Oracle, already use a

standard called Open Database Connectivity (ODBC). Many legacy C and Perl

programs use ODBC to connect to data sources. ODBC consolidated much of the

commonality between database management systems. JDBC builds on this feature,

and increases the level of abstraction. JDBC-ODBC bridges have been created to

allow Java programs to connect to ODBC-enabled database software [ 1].

This article assumes that readers already have a data source established and are

moderately familiar with the Structured Query Language (SQL), the command

language for adding records, retrieving records, and other basic database

manipulations. See Hoffman's tutorial on SQL if you are a beginner or need some

refreshing [ 2].

Using a JDBC driver

Regardless of data source location, platform, or driver (Oracle, Microsoft, etc.),

JDBC makes connecting to a data source less difficult by providing a collection of

classes that abstract details of the database interaction. Software engineering with

JDBC is also conducive to module reuse. Programs can easily be ported to a

different infrastructure for which you have data stored (whatever platform you

choose to use in the future) with only a driver substitution.

As long as you stick with the more popular database platforms (Oracle, Informix,

Microsoft, MySQL, etc.), there is almost certainly a JDBC driver written to let

your programs connect and manipulate data. You can download a specific JDBC

driver from the manufacturer of your database management system (DBMS) or

from a third party (in the case of less popular open source products) [ 5]. The

JDBC driver for your database will come with specific instructions to make the

class files of the driver available to the Java Virtual Machine, which your program

is going to run. JDBC drivers use Java's built-in DriverManager to open and

access a database from within your Java program.

To begin connecting to a data source, you first need to instantiate an object of your
JDBC driver. This essentially requires only one line of code, a command to the

DriverManager, telling the Java Virtual Machine to load the bytecode of your

driver into memory, where its methods will be available to your program. The

String parameter below is the fully qualified class name of the driver you are

using for your platform combination:

Class.forName("org.gjt.mm.mysql.Driver").newInstance();

Connecting to your database

To actually manipulate your database, you need to get an object of the

Connection class from your driver. At the very least, your driver will need a

URL for the database and parameters for access control, which usually involves

standard password authentication for a database account.

As you may already be aware, the Uniform Resource Locator (URL) standard is

good for much more than telling your browser where to find a web page:

http://www.vusports.com/index.html

The URL for our example driver and database looks like this:

jdbc:mysql://db_server:3306/contacts/

Even though these two URLs look different, they are actually the same in form: the

protocol for connection, machine host name and optional port number, and the

relative path of the resource. Your JDBC driver will come with instructions

detailing how to form the URL for your database. It will look similar to our

example.

You will want to control access to your data, unless security is not an issue. The

standard least common denominator for authentication to a database is a pair of

strings, an account and a password. The account name and password you give the

driver should have meaning within your DBMS, where permissions should have

been established to govern access privileges.


Kulpreet Singh

MCS-024 - Object Oriented Technologies and Java Programming - Question 8(c) Posted On: 2/23/2010
5:23:34 PM

c) Explain the use of finalize() methods of Java with an example.

answer:

Since objects are dynamically allocated by using the new operator, you might

be wondering how such objects are destroyed and their memory released for

later reallocation. In some languages, such as C++, dynamically allocated

objects must be manually released by use of a delete operator.

Java takes a different approach; it handles deallocation for you

automatically. The technique that accomplishes this is called garbage

collection. It works like this: when no references to an object to an object exist,

that object is assumed to be no longer needed, and the memory occupied by the

object can be reclaimed. There is no explicit need to destroy objects as in C++.

Garbage collection only occurs sporadically (if at all) during the execution of

your program. It will not occur simply because one or more objects exist that

are no longer used. Furthermore, different java run-time implementations will

take varying approaches to garbage collection, but for the most part, you

should not have to think about it while writing your programs

The finalize () Method

Sometimes an object will need to perform some action when it is destroyed.

For example, if an object is holding some non-java resource such as a file

handle or window character font, then you might want to make sure these
resources are freed before an object is destroyed. To handle such situations,

java provides a mechanism called finalization. By using finalization, you can

define specific actions that will occur when an object is just about to be

reclaimed by the garbage collector.

To add a finalizer to a class, you simply define the finalize() method. The java

run time calls that method whenever it is about to recycle an object of that

class. Inside the finalize() method you will specify those actions that must be

performed before an object is destroyed. The garbage collector runs

periodically, checking for objects that are no longer referenced by any running

state or indirectly through other referenced objects. Right before an asset is

freed, the java run time calls the finalize() method on the object.

The finalize() method has this general form:

protected void finalize()

// finalization code here

Here, the keyword protected is a specifier that prevents access to finalize() by

code defined outside its class.

You might also like