Vous êtes sur la page 1sur 13

CS-74

Course Code Course Name Programming Assignment No Sources: IGNOU Bokklet. : : : CS 74 Introduction to Internet BCA (6) 74/Assignment 2012

Answer all the questions. 1) Differentiate between the followings with examples i)Applet and application program Ans: Applet Applets can only be executed inside aJava-compatible container, such as amodern Web Browser. Applets can be embedded in HTMLpages and downloaded over theInternet Applets execute under strict securitylimitations that disallow certainoperations, such as accessing files orsystems services on the userscomputer also called sand box security Applets are the programs writtenspecially for distribution over anetwork. (ii) Ans: Thread and process Application Program Applications can be executed from thecommand line with a booting utilitysuch as javac.exe or Java.exe Applications have no special support inHTML for embedding or downloading so run on specific location.

Applications have no inherent securityrestrictions. Applications are system level programsi.e., these programs run in thebackground and dont involve userinteraction, for example, serveradministration, security manager, etc.

Process is a program in execution. Suppose there r two processes that means that occurs at different-different memory location. and the context switching b/w process is more expensive.bcz it will take more time from one memory allocation to other memory allocation.that is why Process is called HEAVY WEIGHT PROCESS. Thread is smallest part of program.and It is independent sequential path of execution with in a program. Suppose there r two threads that means that occurs at same memory location bcz of smallest part of program.

and the context switching b/w threads is less expensive rather than process.that is why Thraed is called Light WEIGHT PROCESS. (iii) Ans: Final and finalize

Final: The final keyword is used in to declare constant ie in several different contexts as a modifier meaning that what it modifies cannot be changed in some sense. final classes: The final class will not be subclassed, and informs the compiler that it can perform certain optimizations it otherwise could not. It also provides some benefit in regard to security and thread safety. final methods: A method that is declared final cannot be overridden in a subclass final fields: When a field is declared final, it is a constant which will not and cannot change. Ex: 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 Ans: Method Overloading/Method Overriding 2) Answer the following questions. (i) i) Why do we use interfaces in Java? Explain with examples. Ans: Click Here (ii) What happens if an abstract modifier is applied to class? Explain. Ans: Click Here (iii) When do we use PageInt ()? Explain with the example. Ans: (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. Ans: Click here for Definition and use Prevent method: The first step you can take to hide the internal implementation of a package is to declare as public only those types that are needed by other packages. When you declare a class or interface, it is by definition contained in a package. If you want a class or interface to be accessible to types declared in other packages, you must declare it public. If you do not declare it public, it will only be accessible to types in the same package. Example: java.io, javax.swing, java.awt, java.util.java.sql., java.servlet etc. (v) What is the purpose of text field? List and explain its construction and important methods.

Ans: In GUI environment text field is taken to get input from user in one line. So it is also called container of text. To construct it you need to import import javax.swing.JTextField; package. then Create text field object as: JTextField nameTextField = new JTextField(); Add it to your container as on panel: nameLabel.setLabelFor(nameTextField); Important methods: void addActionListener (ActionListener Handler)Configures an event handler for the TextField. String getText ()Returns the text in the field void setBackground (Color BackgroundColor)Sets the background color of the TextField .void setEditable (boolean Editable)Sets the field as being editable or fixed. void setFont (Font TextFont)Sets the font for this component .void setText (String Text)Sets the text for the field. 3) Define the following terms and their purpose. (i) Panel Ans: 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. Here is an example of how to set the layout manager when creating the panel. JPanel p = new JPanel(new BorderLayout()); Adding Components:When you add components to a panel, you use the add method. Exactly which arguments you specify to the add method depend on which layout manager the panel uses. When the layout manager is FlowLayout, BoxLayout, GridLayout, or SpringLayout, you will typically use the one-argument add method, like this: aFlowPanel.add(aComponent); aFlowPanel.add(anotherComponent); (ii) Frame 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. Since the border area is included in the overall size 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 following FrameDemo code shows how to create and set up a frame. //1. Create the frame. JFrame frame = new JFrame("FrameDemo");

//2. Optional: What happens when the frame closes? frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//3. Create components and put them in the frame. //...create emptyLabel... frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); //4. Size the frame. frame.pack(); //5. Show it. frame.setVisible(true); (iii) Java is distributed: Ans:Features like RMI (remote method invocation) allow a Java program to invoke a method of an object residing on a remote system (or a different JVM). This is needed in a distributed environment. JavaBeans and CORBA are also essential in a networked environment. (iv) Java is robust: To develop a multi-platform envoronment it must be ensured that program must be relibly execute on any platform. Java provides compile time as well as run time error checking. During compile time syntax error in programs are checked and at run time exceptions are trapped. Java memory management does not allow creation of pointers and has automatic garbage collection once the memory is not required (v) Java is interpreted: Java byte codes are interpreted before running on system, So the speed is little bit slower. Sun Micor System has recently developed java chips which makes it little bit faster. It still work to improve its speed. 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. Ans: import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class TextConcatenate implements ActionListener{ public static void main(String args[]){ Frame frm=new Frame(My Frame); frm.setVisible(true); frm.setSize(400, 400); frm.setLayout(new FlowLayout()); Button btn=new Button(Append);

btn.addActionListener(new TextConcatenate()); TextField tf=new TextField(50); TextArea ta=new TextArea(10,20); frm.add(tf); frm.add(ta); frm.add(btn); } public void actionPerformed(ActionEvent ae){ String str= tf.getText(); //System.out.print(str); ta.setText(ta.getText()+str); } } (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. Ans: import javax.swing.*; public ArraySort{ int a[]=null; public ArraySort(){ a[]=new int[20]; } public void input(){ int i; for ( i=0; i<20;i++) { a[i]=Integer.parseInt(JOptionPane.InputDialogBox(Enter the number); } } public void sort(){ int i; int j; int temp; for(i=0;i<19;i++) { for(j=1;j<20;j++) { if(a[i]<a[j]) { temp=a[j]; a[j]=a[i]; a[i]=temp; } } } }

public void display(){ int i; for ( i=0; i<20;i++) { System.out.println(a[i]); } } public static void main(String args[]) { ArraySort as=new ArraySort(); as.input(); as.sort(); as.display(); } (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. Ans: class GCD { int gcd(int m,int n) { if(n==0) return m; else if(n>m) return gcd(n,m); else return gcd(n,m%n); } public static void main(String[] args) { int num1=Integer.parseInt(args[0]); int num2=Integer.parseInt(args[1]); GCD obj=new GCD(); System.out.println(GCD of +num1+ and +num2+ is +obj.GCD(num1,num2)); } } (iv) Write a program that accepts name of a file as command line and displays its content. Ans: import java.io.*; class CharStream{ public static void main(String args[]) { try{ String fName=args[0]; File file=new File(fName); FileReader fr=new FileReader(file); while((a=fr.read())!=-1) { System.out.println((char)a);

} }catch(Exception e){ System.out.println(e.toString()); } } }

Abstraction
1. Definition 2. Abstract class 3. Interface Definition: Abstraction is the process of hiding the complexity and showing the functionality to the end user. For ex: Suppose a television, We dont know how it works but we can only use its functionality. > There are two ways to achieve abstraction in java: 1. Through abstract class 2. Through interface 1. Abstract Class Note: >a class can be a abstract class without having a abstract method > If a class have a abstract method in this case the class must be a abstract class > An abstract class can have concrete method as well as abstract methods. > We cant create an object of abstract class it means it becomes your liability to create an object of abstract class. It means an abstract class always run with inheritance. So, in other word we can say that abstract class cant instantiated. Ex: A class which has abstract as well as concrete methods: // A Simple demonstration of abstract.

abstract class AbstractTest { abstract void secMethod(); void firstMethod() { System.out.println("Hello!, concrete method"); }

class Inheit extends AbstractTest { void secMethod() { System.out.println("Hello!, Impliment abstract method"); }

public static void main(String arg[]) { Inheit i =new Inheit(); i.secMethod(); i.firstMethod(); } } Q. Can i have a constructor in abstract class? Yes, because a constructor is used here to initializs data member also. abstract class AbsTest{ AbsTest() {

System.out.println("Abstract class constructor"); } public abstract void asset(); public void asset() {} } Note: > Whenever you want ot achieve 0-99% abstraction, then to for abstract class. > Whenever you want to achieve 100% abstract, then go for interface. When to use Abstract Methods & Abstract Class? Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations These subclasses extend the same Abstract class and provide different implementations for the abstract methods Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class. 2. Interface:An interface is a named collection of method definitions (without implementations). An interface can also include constant declarations. For ex: Suppose a rectangle and triangle which may implement shape interface. Because both have common properties as area and perimeter although there implementation difference. Defining Interfaces: To define an interface write interface name first with interface keyword public interface [InterfaceName] { //some methods without the body } interface shape { //common properties void perimeter(int i,int j); void area(); } class Rectangle implements shape {

//implimentation of perimeter method public void perimeter(int p,int m) { System.out.println("The perimeter of rectangle is " + p*m); } //implimentation of area method public void area() { System.out.println("The area of rectangle is "); } public static void main(String arg[]) { Rectangle rect = new Rectangle(); rect.perimeter(5,7); rect.area(); } } Hierarchy of interface: >First hierarchy: You need o extends a class then we implements interface. >Interface needs to be implements. No body in the interface, child is responsible for giving body to interface method. Note fro interview: 1. All methods in interface is by default abstract and dont need to use abstract keyword. 2. whenever we want to achieve 100% abstraction then we choose interface. 3. All the variables which you are declearing in a interfaces are public static final, they are used to define constant in java. 4. Interface cant instantiated. 5. There is no constructor in interface. 6. Can a interface extends another interface > Yes 7. Can a class implements more than one interface > Yes 8. Can a interface extends class > No 9. ?? Note: Problem of Rewriting an ExistingInterface :-Consider an interface that you have developed called prg: public interface prg { void doSomething(int i, double x);

int doSomethingElse(String s); } Suppose that, at a later time, you want to add a third method to prg, so that the interface now becomes: public interface prg { void doSomething(int i, double x); int doSomethingElse(String s); boolean didItWork(int i, double x, String s); } If you make this change, all classes that implement the old prg interface will break because they dont implement all methods of the the interface anymore

Package
Definition: A package is a group of related functionality providing better protection and access management. Many Times When we get chance to create a small project then we put all the class file in a single folder but it is difficult to manage them for a large project so, the concept of package comes. Package in java is nothing but folders where related types are being stored. We can say in other words that ackage is a way of group of related classes and interfaces according to their functionality. It resolves name conflict between class names. How to create Package: Just put your package name before your class file preceding with package keyword will create your package. // A program to create a package with name "mypackage" package mypackage;

class Arithimatic { void addition(int i,int j) { System.out.println("The addition of two numbers is" + (i+j)); } void substraction(int i,int j) { System.out.println("The differnce of two numbers is" + (i-j));

} void multiplication(int i,int j) { System.out.println("The product of two numbers is" + (i*j)); } void division(int i,int j) { System.out.println("The quotient of two numbers is" + (i/j)); } } Note: Save the class file having same name as class, Compile syntax: javac -d . Arithimatic.java (Here -d is used for package creation, and . denotes current directory) Run syntax: mypackage.Arithimatic > Java does not allow us to execute a class file in alone, either we have to put package name before class name or we have to import the package in another class before using it. As in above example we can run the program by using mypackage with our class name Arithimatic. > We can put many class definition in a single package. > Package statement should be the first statement in our file. > Each and every class is inside package in java. Java supplies a default package to all program i.e. package. . It creates current directory. > We can create nested package in java i.e. package call inside another package. > We can create subpackage also as: package.mypackage.Account;. How to use package in another class file: To use a package in our class file we have to write import keyword followed by package name before class syntax. // A program to create use package with name "mypackage" import mypackage.Arithimatic;

class Calculator { public static void main(String arg[]) { Arithimatic a=new Arithimatic();

Calculator c=new Calculator(); a.addition(5,4); }

} Note: If we want to access class and methods in another class then it should be public.

Vous aimerez peut-être aussi