CS-74x - Ignou Study Centre

hundredcarriageΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 3 χρόνια και 8 μήνες)

89 εμφανίσεις

Visit for more solved assignments:
http://www.myignou.in


CS


74 SOLVED ASSIGNMENTS 2012

Presented by

MYIGNOU.IN


Course Code




:

CS


74

Course Name



:

Introduction to Intern
et

Programming

Assignment No



:

BCA

(6)


74/Assignment 2012

Maximum Marks



:

100

Last Date of Submission


:

30
th

April, 201
2
/30
th

October, 2012


Answer all the questions.


1
)

Differentiate between the followings with examples








(i)

Applet and application program

Answer:

An applet is client side program which is downloaded in client side and run in the browser. Applet
program cannot access network connection like opening socket, writing to socket. A class extending
java.awt.Applet class which has methods like init(), sta
rt(), stop(), destroy(),paint() overridden. And cannot
write to client side files i.e. hard disk.



An application runs standalone with a support of virtual machine. An application does not have any restrictions
as Applets have over network and file relate
d activities. They are free to open sockets over a network read and
write to a file.


(ii)

Thread and process

Answer:
The major difference between threads and processes is:


1)

Threads share the address space of the process that created it; processes have their ow
n address
space.

2)

Threads have direct access to the data segment of its process; processes have their own copy of
the data segment of the parent process.

3)

Threads can directly communicate with other threads of its process; processes must use
interprocess com
munication to communicate with sibling processes.

4)

Threads have almost no overhead; processes have considerable overhead.

5)

New threads are easily created; new processes require duplication of the parent process.

6)

Threads can exercise considerable control over

threads of the same process; processes can only
exercise control over child processes.

7)

Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the
other threads of the process;
changes to the parent process do

not affec
t child processes.


(iii)

Final and finalize

Answer:

Final is used for making a class no
-
sub
-
classable, and making a member variable as a constant which
cannot be modified. Finally is usually used to release all the resources utilized inside the try block. All the
resources present in the finalize method wil
l be garbage collected whenever GC is called. Though finally and
Visit for more solved assignments:
http://www.myignou.in


finalize seem to be for a similar task there is an interesting difference here. This is because the code in finally
block is guaranteed of execution irrespective of occurrence of exception, w
hile execution of finalize is not
guaranteed. Finalize method is called by the garbage collector on an object when the garbage collector
determines that there are no more references to the object.


(iv)

Method Overloading and overriding a method


(20 Marks)

An
swer:

The major difference between
Method Overloading and overriding a method

is given in the following
table:


Method Overloading

Overriding A Method

Happening within the same class.

Happening between super class and sub class.

Method signature should
not be same.

Method signature should be same.

It happen at time of compliance or we can say overloading
is the early binding or static binding.

It happen on time of run time or we can say overriding is
dynamic binding or let binding.

Method can have any
return type.

Method return type must be same as super class method

Method can have any access level.

Method must have same or wide access level than super
class method access level.



2
)

Answer the following questions.









(i)

Why do we use
interfaces in Java? Explain with examples.


Answer:

Java
doesn’t

support Multiple Inheritance. For that we can use Interface.


Interface is like the gateway to communicate between
two

classes.


Not always we write methods in Interface, we can also create o
bjects in the Interface. The Object which will be
shared between two classes can be created in an Interface.


Creating separate Interface is one of the key
factors

of Software Engineering. Suppose Class "A" has many
methods depends on several Classes' objects. Think that, one method creates connection depends on Class B
object and another method makes business rules depending on Class C object. In this situation, yo
u can actually
use to
separate

Interface for better performance. Or sometimes you want to hide your detail
implementation,

you can use interface as a representation of a class and interface method is like abstract so implementation
depends on the client cl
ass. Or interface is the contract between two
parties

where one party will implement to
that contract and other party will use that contract to invoke the implementation.
That

means contract will
rename same but implementation can vary freely.


Let’s consi
der the following example:

abstract Animal {

void talk();

}

we can extend this of course and make

class Cow extends Animal;

class Horse extends Animal;


the advantage, of course, is we can then have an array

Aninal[] animals;

animals[0] = new Cow();

animal
s[1] = new Horse();


not to mention a lot less coding.

Visit for more solved assignments:
http://www.myignou.in



animals[0] overides a talk() of abstract Animals;

animals[1] overides a talk() of abstract Animals;


that's all fine, this is a monolithic vertical idea

but what if you wanted a HorseCow? A Frankenste
in, if you will. The heirachy changes into a diamond
-
shape


---------
Animal

Horse
-------------
Cow

-------
HorseCow

Animal HorseCow = new Animal();

HorseCow.talk(); // which method()?????? Horse.talk() or Cow.talk()?


We can do a slight re
-
design...

class
CattleProd {

static void makeItTalk(Talkative subject) {

subject.talk();

}

Interface Talkative {

void talk();

}

Then, abstract Animal will implement Talkative. To use our new tool...

CattleProd prod = new CattleProd();

prod.makeItTalk(Cow); // or animals[0
] to use a 'for loop'

prod.makeItTalk(Horse);

prod.makeItTalk(HorseCow);


Interface gives you much more polymorphism and clean revisions capabilities.



(ii)

What happens if an abstract modifier is applied to class? Explain.


Answer:

The
classes

which have one
or more abstract methods are abstract. To declare a class as abstract, use
the abstract keyword in front of the class keyword, before the class declaration. Abstract classes cannot be
instantiated. Similarly the new keyword cannot be used to create an obje
ct of the abstract class. Remember that
the constructors and static variables cannot be declared as abstract. Any subclass of an abstract class must either
implement all of the abstract methods in the superclass or be itself declared abstract.


The followi
ng example declares area ( ) as an abstract method inside AbsDemo class. This means that all
classes derived from AbsDemo must override area( ).


abstract class AbsDemo

{


double len;


double width;


AbsDemo(double num, double num1)


{


len = num;


width = num1;


}


abstract double area();

}


class Square extends AbsDemo

Visit for more solved assignments:
http://www.myignou.in


{


Square(double num, double num1)


{


super(num, num1);


}


double area()


{


System.out.println("Area of the Squa
re is : ");


return len * width;


}

}


class Rectangle extends AbsDemo

{


Rectangle(double num, double num1)


{


super(num, num1);


}


double area()


{


System.out.println("Area of the Rectangle is : ");


return len * width;


}

}


class AreaDemo

{



public static void main(String args[])



{




AbsDemo aObj;




Square sObj = new Square(10, 10);




Rectangle rObj = new Rectangle(20, 25);




aObj = sObj;





System.out.println("Calculated : " + aObj.area());




aObj = rObj;




System.out.println("Calculated : " + aObj.area());




}

}


In above program an object of AbsDemo cannot be declared abstract. All the subclasses of AbsDemo override
the method,
area( ). The variable aObj is declared as a reference to AbsDemo, i.e. it does not refer to an object
of any class derived from AbsDemo.


(iii)

When do we use PageInt ()? Explain with the example.


Answer:
ASP.NET pages raise life
-
cycle events such as Init, Load
, PreRender, and others. By default, you

can bind page events to methods using a naming convention of Page_eventname. For example, to

create a handler for the page's Load event, you can create a method named Page_Load. At run

time, ASP.NET will find method
s based on this naming convention and automatically perform

the binding between the event and the method. You can use the convention of Page_eventname

for any event exposed by the Page class.


(iv)

How do you define package in Java? How do you prevent a class f
rom

being accessed from one package to another package? List some

important packages.


Answer: Defining Package in Java

Visit for more solved assignments:
http://www.myignou.in


The name of the package must be preceded by the keyword
package

and this must be the first statement in a
Java source file. This is followed by defining a class:


Example:


package myFirstPackage;

public class MyPackageClass

{

(Body of the class)

}


W
e can prevent a class from being accessed from one package to
another package by making that class private.


Core packages in Java SE 6


java.lang




basic language functionality and fundamental types

java.util




collection data structure classes

java.io





file operations

java.math




multiprecision arithmetics

ja
va.nio




the New I/O framework for Java

java.net




networking operations, sockets, DNS lookups, ...

java.security



key generation, encryption and decryption

java.sql



Java Database Connectivity (JDBC) to access databases

java.awt



basic hierarchy o
f packages for native GUI components

javax.swing



hierarchy of packages for platform
-
independent rich GUI components

java.applet




classes for creating an applet


(v)

What is the purpose of text field? List and explain its construction and important
methods.





(25 Marks)


Answer
:
A TextField object is a text component that allows for the editing of a single line of text.


Here is the code that produces these four text fields:



TextField tf1, tf2, tf3, tf4;


// a blank text field


tf1 = new TextField();


// blank field of 20 columns


tf2 = new TextField("", 20);


// predefined text displayed


tf3 = new TextField("Hello!");


// predefined text in 30 columns


tf4 = new TextField("Hello", 30);




Every
time the user types a key in the text field, one or more key events are sent to the text field. A KeyEvent
may be one of three types: keyPressed, keyReleased, or keyTyped. The properties of a key event indicate which
of these types it is, as well as additi
onal information about the event, such as what modifiers are applied to the
key event and the time at which the event occurred.


The key event is passed to every KeyListener or KeyAdapter object which registered to receive such events
using the component's

addKeyListener method. (KeyAdapter objects implement the KeyListener interface.)


Visit for more solved assignments:
http://www.myignou.in


It is also possible to fire an ActionEvent. If action events are enabled for the text field, they may be fired by
pressing the Return key.


The TextField class's processEven
t method examines the action event and passes it along to
processActionEvent. The latter method redirects the event to any ActionListener objects that have registered to
receive action events generated by this text field.


TextFields provide an area where
you can enter and edit a single line of text. To create a text field, use one of
the following constructors:


TextField():




creates an empty TextField with no specified width.

TextField(int):



creates an empty text field with enough width to display the

specified number of
characters (this has been depreciated in Java2).

TextField(String):


creates a text field initialized with the given string.

TextField(String, int)
:

creates a text field with specified text, and specified width.


For example, the foll
owing line creates a text field 25 characters wide with the string "Brewing Java" as its
initial contents: TextField txtfld = new TextField ("Brewing Java", 25); add(txtfld);


TextField, can use methods like:


setText():



Used to set the text in text fiel
d.

getText():



Used to get the text currently contained by text field.

setEditable():


Used to provide control whether the content of text field may be modified by user or not.

isEditable():



It returns true if the text in text filed may be changed and f
alse otherwise.



3)


Define the following terms and their purpose.








(i)

Panel

Answer:

Panels in widget toolkits often have no specific graphic characteristics, but are mainly used to group
children widgets together. They allow
having

a better control on the layout of the widgets.


For example, in this XUL definition, two horizontal hbox panels are enclosed in a vertical vbox panel, alongside
with two buttons. This allows to be sure that the label and the textboxes for the Login and th
e Password fields
are correctly aligned.


<vbox>


<hbox>


<label control="login" value="Login:"/>


<textbox id="login"/>


</hbox>


<hbox>


<label control="pass" value="Password:"/>


<textbox id="pass"/>


</hbox>


<
button id="ok" label="OK"/>


<button id="cancel" label="Cancel"/>

</vbox>


Visit for more solved assignments:
http://www.myignou.in




(ii)

Frame


Answer:
A Frame is a top
-
level window with a title and a border.


The size of the frame includes any area designated for the border. The dimensions of the border area may

be
obtained using the getInsets method; however, since these dimensions are platform
-
dependent, a valid insets
value cannot be obtained until the frame is made displayable by either calling pack or show. Since the border
area is included in the overall si
ze of the frame, the border effectively obscures a portion of the frame,
constraining the area available for rendering and/or displaying subcomponents to the rectangle which has an
upper
-
left corner location of (insets.left, insets.top), and has a size of
width
-

(insets.left + insets.right) by height
-

(insets.top + insets.bottom).


The default layout for a frame is BorderLayout.


A frame may have its native decorations (i.e. Frame and Titlebar) turned off with setUndecorated. This can only
be done while t
he frame is not displayable.


In a multi
-
screen environment, you can create a Frame on a different screen device by constructing the Frame
with Frame(GraphicsConfiguration) or Frame(String title, GraphicsConfiguration). The GraphicsConfiguration
object is
one of the GraphicsConfiguration objects of the target screen device.


In a virtual device multi
-
screen environment in which the desktop area could span multiple physical screen
devices, the bounds of all configurations are relative to the virtual
-
coordina
te system. The origin of the virtual
-
coordinate system is at the upper left
-
hand corner of the primary physical screen. Depending on the location of
the primary screen in the virtual device, negative coordinates are possible, as shown in the following figu
re.



Visit for more solved assignments:
http://www.myignou.in


In such an environment, when calling setLocation, you must pass a virtual coordinate to this method. Similarly,
calling getLocationOnScreen on a Frame returns virtual device coordinates. Call the getBounds method of a
GraphicsConfiguration to find i
ts origin in the virtual coordinate system.


The following code sets the location of the Frame at (10, 10) relative to the origin of the physical screen of the
corresponding GraphicsConfiguration. If the bounds of the GraphicsConfiguration is not taken int
o account, the
Frame location would be set at (10, 10) relative to the virtual
-
coordinate system and would appear on the
primary physical screen, which might be different from the physical screen of the specified
GraphicsConfiguration.



Frame f = new

Frame(GraphicsConfiguration gc);


Rectangle bounds = gc.getBounds();


f.setLocation(10 + bounds.x, 10 + bounds.y);




Frames are capable of generating the following types of WindowEvents:



WINDOW_OPENED


WINDOW_CLOSING


WINDOW_CLOSED



WINDOW_ICONIFIED


WINDOW_DEICONIFIED


WINDOW_ACTIVATED


WINDOW_DEACTIVATED


WINDOW_GAINED_FOCUS


WINDOW_LOST_FOCUS


WINDOW_STATE_CHANGED


(iii)

Java is distributed


Answer:

"Java has an extensive library of routines for coping with TCP/IP
protocols like HTTP and FTP.

Java
applications can open and access objects across the net via URLs with the same ease as

when accessing a local
file system."


Java's pretty solid in this respect. Support for TCP, UDP, and basic Socket communication is exce
llent and
getting better. The class libraries allov IPv6 to be plugged in easily. A varioty of high
-
level abstractions for
network communication and distributed processing are available including applets, servlets, aglets, remote
method invocation (RMI), a
nd more. The only missing piece is raw IP or ICMP.


(iv)

Java is robust


Answer
: The multi
-
platform environment of the web places high demand on the reliability of the program to
execute on a variety of systems. Thus, high priority has been given to create robu
st and highly reliable programs
in the design of Java.


It provides extensive compile
-
time checking followed by a second level of runtime checking. The most
common problems in programming languages are related to memory management and exception handling.


The memory management model of Java does not allow the creation of pointers. Java has a true array which
allows subscript checking to be performed. Thus, Java programmers need not worry about freeing or corrupting
memory as the programs cannot overwrite th
e end of a memory buffer. Also Java has automatic garbage
collection once the memory is no longer required.

Visit for more solved assignments:
http://www.myignou.in



(v)

Java is interpreted






(15 Marks)


Answer
:

Java bytecodes are translated on the fly to native machine instructions (interpreted) and not stored
anywhere. And since linking is a more incremental and lightweight process, the development process can be
much more rapid and exploratory.



As a pa
rt of the bytecode stream, more compile
-
time information is carried over and available at runtime.
This is what the linker's type checks are based on. It also makes programs more amenable to debugging.



4
)

Write the following Program, run and show its res
ults.







(i)

Write a program that let the user enter text from the text field and then append it to the
text areas.

package Patterns.TextField;

import javax.swing.JFrame;

import javax.swing.JTextField;

import javax.swing.JTextArea;

import
java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

public class TextFieldEx extends JFrame

{ // Instantiate a textfield for input and a textarea for output.

private JTextField input = new JTextField(15);

private JTextArea output = new JTextA
rea(5, 15);

public TextFieldEx()

{ // Register a listener with the textfield

TextFieldListener tfListener = new TextFieldListener();

input.addActionListener(tfListener);

// Don't let the user change the output.

output.setEditable(false);

// Add all the wid
gets to the applet

this.getContentPane().add(input);

this.getContentPane().add(output);

input.requestFocus(); // start with focus on this field

}

// The listener for the textfield.

private class TextFieldListener implements ActionListener

{ public void act
ionPerformed(ActionEvent evt)

{ String inputString = input.getText();

output.append(inputString + "
\
n");

input.setText("");

}

}

}

(ii)

Write a program in Java to find the largest and the smallest of n numbers stored in array,
where n is a positive number.

Answer:


import static java.lang.System.*;

import java.io.*;



class LargestSmallest

{


public static void main(String[] args)


{



int[] arr;



int n,i;

Visit for more solved assignments:
http://www.myignou.in




BufferedReader br=new BufferedReader (new InputStreamReader(System.in));



out.print("Please enter how many numbers the array should hold : ");



try




{





n=Integer.parseInt(br.readLine());





arr=new int[n];





out.println("
\
nEnter "+n+" numbers in the array
\
n");





for(i=0;i<n;i++)






{







out.print("Array["+i+"] =
");







arr[i]=Integer.parseInt(br.readLine());













}







bubbleSort(arr);






out.println("
\
n
\
t
\
t
\
t=================================================
\
n
\
t
\
t
\
t
\
tThe


Largest number is "+arr[n
-
1]);





out.println("
\
t
\
t
\
t
\
tThe Smallest number is

"+arr[0]+"
\
n
\
t
\
t


\
t=================================================");




}



catch(Exception e)




{





out.println("The following error has occured
\
n"+e);




}





}




private static void bubbleSort(int[] intArray)


{







int n = intArray.length;


int temp = 0;




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



{


for(int j=1; j < (n
-
i); j++)




{




if(intArray[j
-
1] > intArray[j])





{


//swap the elements!


temp = intArray[j
-
1];


intArray[j
-
1] = intArra
y[j];


intArray[j] = temp;


}




}


}




}

}



(iii)

Write a recursive program in Java for the greatest common
divisor (GCD).

Given two positive integers, GCD is the largest integer that divides the both.

Visit for more solved assignments:
http://www.myignou.in


Answer:


import java.io.BufferedReader;

import java.io.InputStreamReader;


class RecursiveGcd

{


public static void main(String arr[])


{



long x,y,g;



BufferedReader br=new BufferedReader(new InputStreamReader(System.in));



System.out.println("A program for the greatest common divisor (GCD) by given
two positive integers.");



System.out.print("Please enter first positive integer : ");


try

{




x=Long.
parseLong(br.readLine());



System.out.print("Please enter second positive integer : ");



y=Long.parseLong(br.readLine());



g=gcd(x,y);



System.out.print("Greatest Common Divisor (GCD) = "+g);



}


catch(Exception e)



{



System.out.print("Please fix t
his error : "+e);



}


}


public static long gcd(long a, long b)


{



if (b==0)




{return a; }



else




{return gcd(b, a%b); }


}

}



(iv)

Write a program that accepts name of a file as command line and displays its
content.







(40 Marks)

Answer:


import java.io.*;


class ReadFile

{


public static void main(String[] args)


{



// creat an input file stream



FileInputStream infile;



int b;



try




{





//
connect

infile stream to the required file





infile=new FileInputStream (args[0]);






//

Read and display data





while((b=infile.read())!=
-
1)





{






System.out.print((char)b);





}





infile.close();




}



catch(IOException e)

Visit for more solved assignments:
http://www.myignou.in





{





System.out.println(e);




}


}

}