cs-74 solved assignment 2012

14
www.ignousolvedassignments.com Connect on Facebook : http://www.facebook.com/pages/IgnouSolvedAssignmentscom/346544145433550 Subscribe and Get Solved Assignments Direct to your Inbox : http://feedburner.google.com/fb/a/mailverify?uri=ignousolvedassignments_com Course Code : CS 74 Course Name : Introduction to Internet Programming Assignment No : BCA (6) 74/Assignment 2012 Maximum Marks : 100 Last Date of Submission : 30 th April, 2012/30 th October, 2012 1) Differentiate between the followings with examples (i) Applet and application program (ii) Thread and process (iii) Final and finalize (iv) Method Overloading and overriding a method Answer (i) Applet and application program *Applet 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. import java.awt.*; import java.applet.*; class Myclass extends Applet {

Upload: shekhar-rawat

Post on 15-Dec-2015

221 views

Category:

Documents


1 download

DESCRIPTION

eg

TRANSCRIPT

www.ignousolvedassignments.com

Connect on Facebook :

http://www.facebook.com/pages/IgnouSolvedAssignmentscom/346544145433550

Subscribe and Get Solved Assignments Direct to your Inbox :

http://feedburner.google.com/fb/a/mailverify?uri=ignousolvedassignments_com

Course Code : CS – 74

Course Name : Introduction to Internet Programming

Assignment No : BCA (6) – 74/Assignment 2012

Maximum Marks : 100

Last Date of Submission : 30th

April, 2012/30th

October, 2012

1) Differentiate between the followings with examples (i) Applet and application program

(ii) Thread and process (iii) Final and finalize (iv) Method Overloading and overriding a method

Answer (i) Applet and application program *Applet 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.

import java.awt.*; import java.applet.*;

class Myclass extends Applet {

www.ignousolvedassignments.com

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

www.ignousolvedassignments.com

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 */ }}

*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. **/ }}

(ii) Thread and process

www.ignousolvedassignments.com

Process:

• An executing instance of a program is called a process. • Some operating systems use the term 'task' to refer to a program that is being executed. • A process is always stored in the main memory also termed as the primary memory or

random access memory. • Therefore, a process is termed as an active entity. It disappears if the machine is rebooted. • Several process may be associated with a same program. • On a multiprocessor system, multiple processes can be executed in parallel. • On a uni-processor system, though true parallelism is not achieved, a process scheduling

algorithm is applied and the processor is scheduled to execute each process one at a time yielding an illusion of concurrency.

• Example: Executing multiple instances of the 'Calculator' program. Each of the instances are termed as a process.

Thread:

• A thread is a subset of the process. • It is termed as a 'lightweight process', since it is similar to a real process but executes

within the context of a process and shares the same resources allotted to the process by the kernel (See kquest.co.cc/2010/03/operating-system for more info on the term 'kernel').

• Usually, a process has only one thread of control - one set of machine instructions executing at a time.

• A process may also be made up of multiple threads of execution that execute instructions concurrently.

• Multiple threads of control can exploit the true parallelism possible on multiprocessor systems.

• On a uni-processor system, a thread scheduling algorithm is applied and the processor is scheduled to run each thread one at a time.

• All the threads running within a process share the same address space, file descriptor, stack and other process related attributes.

• Since the threads of a process share the same memory, synchronizing the access to the shared data withing the process gains unprecedented importance.

(iii) Final and finalize

final fields You may also declare fields to be final. This is not the same thing as declaring a method or

class to be final. When a field is declared final, it is a constant which will not and cannot change. It can be set once (for instance when the object is constructed, but it cannot be changed

www.ignousolvedassignments.com

after that.) Attempts to change it will generate either a compile-time error or an exception

(depending on how sneaky the attempt is).

Fields that are both final, static, and public are effectively named constants. For instance a

physics program might define Physics.c, the speed of light as public class Physics { public static final double c = 2.998E8;

Finalize: Finalize() is a method. Every class inherits the finalize() method from java.lang.Object. The method is called by the garbage collector when it determines no more references to the object exist. The Object finalize method performs no actions but it may be overridden by any class. Normally it should be overridden to clean-up non-Java resources ie closing a file

}

( iv ) Method Overloading and overriding a method

Method Overloading Method overloading means having two or more methods with the same name but different signatures in the same scope. These two methods may exist in the same class or anoter one in base class and another in derived class. class Person { private String firstName; private String lastName; Person() { this.firstName = ""; this.lastName = ""; } Person(String FirstName) { this.firstName = FirstName; this.lastName = ""; } Person(String FirstName, String LastName) { this.firstName = FirstName; this.lastName = LastName;

www.ignousolvedassignments.com

} }

Method Overriding Method overriding means having a different implementation of the same method in the inherited class. These two methods would have the same signature, but different implementation. One of these would exist in the base class and another in the derived class. These cannot exist in the same class. Overriding methods Overriding method definitions In a derived class, if you include a method definition that has the same name and exactly the same number and types of parameters as a method already defined in the base class, this new definition replaces the old definition of the method. Explanation A subclass inherits methods from a superclass. Sometimes, it is necessary for the subclass to modify the methods defined in the superclass. This is referred to as method overriding. The following example demonstrates method overriding. Step 1 In this example we will define a base class called Circle class Circle { //declaring the instance variable protected double radius; public Circle(double radius) {

this.radius = radius; } // other method definitions here public double getArea() {

return Math.PI*radius*radius; }//this method returns the area of the circle }// end of class circle When the getArea method is invoked from an instance of the Circle class, the method returns the area of the circle. Step 2 The next step is to define a subclass to override the getArea() method in the Circle class. The derived class will be the Cylinder class. The getArea() method in the Circle class computes the area of a circle, while the getArea method in the Cylinder class computes the surface area of a cylinder. The Cylinder class is defined below. class Cylinder extends Circle { //declaring the instance variable protected double length;

www.ignousolvedassignments.com

public Cylinder(double radius, double length)

{ super(radius); this.length = length;

} // other method definitions here public double getArea() {

// method overriden here return 2*super.getArea()+2*Math.PI*radius*length;

}//this method returns the cylinder surface area }// end of class Cylinder When the overriden method (getArea) is invoked for an object of the Cylinder class, the new definition of the method is called and not the old definition from the superclass(Circle).

2) Answer the following questions.

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

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

Example : In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows: interface Bicycle {

// wheel revolutions per minute void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement);

}

** class ACMEBicycle implements Bicycle {

// remainder of this class // implemented as before

} **

www.ignousolvedassignments.com

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

The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.

In this example, the class Square must provide an implementation of Area because it derives

from ShapesClass

Example :

abstract class ShapesClass

{ abstract public int Area();

} class Square : ShapesClass {

int x, y; // Not providing an Area method results // in a compile-time error. public override int Area() {

return x * y; }

}

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

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 methods 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 from being accessed from one package to another package? List some important packages.

Packages are group of inter-related classes.eg-In math class we can do addition ,subtraction etc. example of classes are : java.applet which is used for implementing and creating applets. You can prevent class from being accessed from one package to another package by declaring class name as private

www.ignousolvedassignments.com

Important java packages are

Java Advanced Imaging - JAI Java Data Objects - JDO JavaHelp Java Media Framework - JMF Java Naming and Directory Interface - JNDI

Java Speech API JSAPI Java 3D J3D Java OpenGL JOGL

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

A TextField object is a text component that allows for the editing of a single line of text. For example, the following image depicts a frame with four text fields of varying widths. Two of

these text fields display the predefined text "Hello".

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 additional 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.) 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.

www.ignousolvedassignments.com

The TextField class's processEvent 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.

3) Define the following terms and their purpose.

(i) Panel The Panel class provides general-purpose containers for lightweight components. By default, panels do not add colors to anything except their own background; however, you can easily add borders to them and otherwise customize their painting. Details can be found in Performing Custom Painting. In many types of look and feel, panels are opaque by default. Opaque panels work well as content panes and can help with painting efficiently, as described in Using Top-Level

Containers. You can change a panel's transparency by invoking the setOpaque method. A transparent panel draws no background, so that any components underneath show through.

(ii) Frame

HTML frames allow authors to present documents in multiple views, which may be independent windows or subwindows. Multiple views offer designers a way to keep certain information visible, while other views are scrolled or replaced. For example, within the same window, one frame might display a static banner, a second a navigation menu, and a third the main document that can be scrolled through or replaced by navigating in the second frame.

(iii) Java is distributed

A distributed object-based system is a collection of objects that isolates the requesters of services (clients) from the providers of services (servers) by a well-defined encapsulating interface. In other words, clients are isolated from the implementation of services as data representations and executable code. This is one of the main differences that distinguishes the distributed object- based model from the pure client/server model. In the distributed object-based model, a client sends a message to an object, which in turns interprets the message to decide what service to perform. This service, or method, selection could be performed by either the object or a broker. The Java Remote Method Invocation (RMI) and the Common Object Request Broker Architecture (CORBA) are examples of this model. RMI is a distributed object system that enables you to easily develop distributed Java applications. Developing distributed applications in RMI is simpler than developing with sockets since there is no need to design a protocol, which is an error-prone task. In RMI, the developer has the illusion of calling a local method from a local class file, when in fact the arguments are shipped to the remote target and interpreted, and the results are sent back to the callers.

www.ignousolvedassignments.com

(iv) Java is robust

Java is robust because it is highly supported language, meaning that unlike C you cannot crash your computer with a bad program. Also, another factor in its robustness is its portability across many Operating systems, with is supported by the Java Virtual Machine. ( v ) Java is interpreted Java is both compiled and interpreted. At first, the Java source code (in .java files) is compiled into the so-called Bytecode (.class files). The Bytecode is a pre-compiled, platform independent version of your program. The .class files can be used on any operating system. When the Java application is started, the Bytecode is interpreted by the Java Virtual Mashine. Because the Bytecode is pre-compiled, Java does not have the disadvantages of classical interpreted languages, like BASIC.

4) Write the following Program, run and show its results.

(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 JTextArea(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 widgets to the applet this.getContentPane().add(input); this.getContentPane().add(output);

www.ignousolvedassignments.com

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

} // The listener for the textfield. private class TextFieldListener implements ActionListener { public void actionPerformed(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.

import java.util.Arrays; public class MinMaxValues{ public static void main (String args[]){

int numbers[]= {1,5,-9,12,-3,89, 18,23,4,-6}; //Find minimum (lowest) value in array using loop System.out.println("Minimum Value = " + getMinValue(numbers)); //Find maximum (largest) value in array using loop System.out.println("Maximum Value = " + getMaxValue(numbers));

//Find maximum (largest) value in array using loop public static int getMaxValue(int[] numbers){

int maxValue = numbers[0]; for(int i=1;i<numbers.length;i++){

if(numbers[i] > maxValue){ maxValue = numbers[i];

} } return maxValue;

} //Find minimum (lowest) value in array using loop public static int getMinValue(int[] numbers){

int minValue = numbers[0]; for(int i=1;i<numbers.length;i++){

if(numbers[i] < minValue){ minValue = numbers[i];

www.ignousolvedassignments.com

}

} return minValue;

}

(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. /***Java program to calculate GCD of two numbers by recursive method ****/

import java.util.*; class GCD { public static void main(String[] args) { int a,b; System.out.print("enter the first number: "); Scanner in = new Scanner(System.in); a = in.nextInt(); // assigning first value to variable a System.out.print("enter the second number: "); b = in.nextInt(); // assigning second value to variable b System.out.println("GCD of "+a+" and "+b+" is "+gcd(a,b)+"."); // result is obtained here by calling function gcd(a,b) } static int gcd (int a,int b) // here we create a function to calculate gcd { int result=0; if (a==b) result = a; else if(a>b) result = gcd(a-b,b); // recursive calling else result = gcd(a,b-a); //recursive calling return result; }}

(iv) Write a program that accepts name of a file as command line and displays

its content.

import java.io.*;

www.ignousolvedassignments.com

import java.util.Scanner;

/** Read and write a file using an explicit encoding. Removing the encoding from this code will simply cause the system's default encoding to be used instead. */ public final class ReadWriteTextFileWithEncoding { /** Requires two arguments - the file name, and the encoding to use. */ public static void main(String... aArgs) throws IOException { String fileName = aArgs[0]; String encoding = aArgs[1]; ReadWriteTextFileWithEncoding test = new ReadWriteTextFileWithEncoding( fileName, encoding

); test.write(); test.read();

} /** Read the contents of the given file. */ void read() throws IOException { log("Reading from file."); StringBuilder text = new StringBuilder(); String NL = System.getProperty("line.separator"); Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding); try { while (scanner.hasNextLine()){ text.append(scanner.nextLine() + NL);

} } finally{ scanner.close();

} log("Text read in: " + text);

}