Java Programming
Java Programming
Q.13 Distinguish between Java applications and Java Applet (Any 2 points) Q.15 List any eight features of Java.
Ans: Features of Java:
1. Data Abstraction and Encapsulation 2. Inheritance
3. Polymorphism 4. Platform independence
5. Portability 6. Robust
7. Supports multithreading 8. Supports distributed applications
9. Secure 10. Architectural neutral
11. Dynamic
iv) drawArc () Q.10 Write a program to add 2 integer, 2 string and 2 float values in a vector.
drawArc( ) It is used to draw arc. Remove the element specified by the user and display the list.
Syntax: void drawArc(int x, int y, int w, int h, int start_angle, int sweep_angle); Code: -
where x, y starting point, w & h are width and height of arc, and start_angle is import java.io.*;
starting angle of arc sweep_angle is degree around the arc import java.lang.*;
Example: g.drawArc(10, 10, 30, 40, 40, 90); import java.util.*;class vector2
{ {
public static void main(String args[]) float price;
{ int stock_position;
vector v=new vector(); BookInfo(String a, String t, String p, float amt, int s)
Integer s1=new Integer(1); {
Integer s2=new Integer(2); super(a, t, p);
String s3=new String("fy"); price = amt;
String s4=new String("sy"); stock_position = s;
Float s7=new Float(1.1f); }
Float s8=new Float(1.2f); void show()
v.addElement(s1); {
v.addElement(s2); System.out.println("Book Details:");
v.addElement(s3); System.out.println("Title: " + title);
v.addElement(s4); System.out.println("Author: " + author);
v.addElement(s7); System.out.println("Publisher: " + publisher);
v.addElement(s8); System.out.println("Price: " + price);
System.out.println(v); System.out.println("Stock Available: " + stock_position);
v.removeElement(s2); }
v.removeElementAt(4); }
System.out.println(v); class Exp6_1
} {
} public static void main(String[] args)
{
Q.11 Develop a program to create a class ‘Book’ having data members author, title BookInfo ob1 = new BookInfo("Herbert Schildt", "Complete Reference", "ABC
and price. Derive a class 'Booklnfo' having data member 'stock position’ and Publication", 359.50F,10);
method to initialize and display the information for three objects. BookInfo ob2 = new BookInfo("Ulman", "system programming", "XYZ Publication",
Ans: 359.50F, 20);
class Book BookInfo ob3 = new BookInfo("Pressman", "Software Engg", "Pearson Publication",
{ 879.50F, 15);
String author, title, publisher; ob1.show();
Book(String a, String t, String p) ob2.show();
{ ob3.show();
author = a; }
title = t; }
publisher = p; OUTPUT
} Book Details:
} Title: Complete Reference
class BookInfo extends Book Author: Herbert Schildt
Publisher: ABC Publication } }
Price: 2359.5 Use the java compiler to compile the applet “Hellojava.java” file.
Stock Available: 10 C:\jdk> javac Hellojava.java
Book Details: After compilation “Hellojava.class” file will be created. Executable applet is nothing but
Title: system programming the .class file of the applet, which is obtained by compiling the source code of the
Author: Ulman applet. If any error message is received, then check the errors, correct them and compile
Publisher: XYZ Publication the applet again.
Price: 359.5 We must have the following files in our current directory.
Stock Available: 20 o Hellojava.java
Book Details: o Hellojava.class
Title: Software Engg o HelloJava.html
Author: Pressman If we use a java enabled web browser, we will be able to see the entire web page
Publisher: Pearson Publication containing the applet. We have included a pair of <APPLET..> and </APPLET> tags in
Price: 879.5 the HTML body section.
Stock Available: 15 The <APPLET…> tag supplies the name of the applet to be loaded and tells the browser
how much space the applet requires. The <APPLET> tag given below specifies the
Q.12 Mention the steps to add applet to HTML file. Give sample code. minimum requirements to place the HelloJava applet on a web page. The display area
Ans: Adding Applet to the HTML file: for the applet output as 300 pixels width and 200
Steps to add an applet in HTML document pixels height. CENTER tags are used to display area in the center of the screen.
1. Insert an <APPLET> tag at an appropriate place in the web page i.e. in the body <APPLET CODE = hellojava.class WIDTH = 400 HEIGHT = 200 > </APPLET>
section of HTML file.
2. Specify the name of the applet’s .class file. Example: Adding applet to HTML file:
3. If the .class file is not in the current directory then use the codebase parameter to Create Hellojava.html file with following code:
specify: - a. the relative path if file is on the local system, or <HTML>
b. the uniform resource locator(URL) of the directory containing the file if it is on a <! This page includes welcome title in the title bar and displays a welcome message.
remote computer. Then it specifies the applet to be loaded and executed. >
4. Specify the space required for display of the applet in terms of width and height in <HEAD> <TITLE> Welcome to Java Applet </TITLE> </HEAD>
pixels. <BODY> <CENTER> <H1> Welcome to the world of Applets </H1> </CENTER>
5. Add any user-defined parameters using <param> tags <BR>
6. Add alternate HTML text to be displayed when a non-java browser is used. <CENTER>
7. Close the applet declaration with the </APPLET> tag. <APPLET CODE=HelloJava.class WIDTH = 400 HEIGHT = 200 > </APPLET>
Open notepad and type the following source code and save it into file name </CENTER>
“Hellojava.java” </BODY>
import java.awt.*; </HTML>
import java.applet.*;
public class Hellojava extends Applet{ Q.13 Write a program to copy contents of one file to another.
public void paint (Graphics g){ Code: -
g.drawString("Hello Java",10,100); import java.io.*;
class copyf
{ Q.17 Explain exception handling mechanism. w.r.t. try, catch, throw and finally.
public static void main(String args[]) throws IOException
{ Q.18 Write a Java program to find out the even numbers from 1 to 100 using for loop.
BufferedReader in=null;
BufferedWriter out=null; Q.19 Explain any four visibility controls in Java.
try
{ Q.20 Explain single and multilevel inheritance with proper example.
in=new BufferedReader(new FileReader("input.txt"));
out=new BufferedWriter(new FileWriter("output.txt")); Q.21 Write a java applet to display the following output in Red color. Refer Fig No. 1.
int c;
while((c=in.read())!=-1)
{
out.write(c);
}
System.out.println("File copied successfully");
}
finally Fig No. 1.
{
if(in!=null) Q.22 Explain switch case and conditional operator in java with suitable example.
{
in.close(); Q.23 Draw and explain life cycle of Thread.
}
if(out!=null) Q.24 Write a java program to sort an 1-d array in ascending order using bubble-sort.
{
out.close(); Q.25 Explain how to create a package and how to import it.
}
} Q.26 Explain: -
} i) drawLine
} ii) drawOval
iii) drawRect
SUM-22 questions iv) drawArc
Q.16 Write the difference between vectors and arrays. (any four points)
{
public static void main(String args[])
{
abc a=new abc(3.14f,5.0f);
a.display();
a.area();
}
}
Q.40 Explain the concept of platform independence and portability with respect
to Java language. (Note: Any other relevant diagram shall be considered).
Ans: Java is a platform independent language. This is possible because when a java
program is compiled, an intermediate code called the byte code is obtained rather
than the machine code. Byte code is a highly optimized set of instructions designed
to be executed by the JVM which is the interpreter for the byte code. Byte code is
not a machine specific code. Byte code is a universal code and can be moved
anywhere to any platform. Therefore java is portable, as it can be carried to any
platform. JVM is a virtual machine which exists inside the computer memory and is
a simulated computer within a computer which does all the functions of a computer.
Only the JVM needs to be implemented for each platform. Although the details of
Q.39 List any four methods of string class and state the use of each. the JVM will defer from platform to platform, all interpret the same byte code.
Ans: The java.lang.String class provides a lot of methods to work on string. By the
help of these methods, We can perform operations on string such as trimming,
concatenating, converting, comparing, replacing strings etc.
1) to Lowercase (): Converts all of the characters in this String to lower case.
Syntax: s1.toLowerCase()
Example: String s="Sachin";
System.out.println(s.toLowerCase());
Output: sachin
2) to Uppercase(): Converts all of the characters in this String to upper case
Syntax: s1.toUpperCase()
Example: String s="Sachin";
System.out.println(s.toUpperCase()); Q.41 Explain the types of constructors in Java with suitable example.
Output: SACHIN (Note: Any two types shall be considered).
3) trim(): Returns a copy of the string, with leading and trailing whitespace omitted. Ans: Constructors are used to initialize an object as soon as it is created. Every time
Syntax: s1.trim() an object is created using the ‘new’ keyword, a constructor is invoked. If no
Example: String s=" Sachin "; constructor is defined in a class, java compiler creates a default constructor.
System.out.println(s.trim()); Constructors are similar to methods but with to differences, constructor has the same
Output: Sachin name as that of the class and it does not return any value.
4) replace ():Returns a new string resulting from replacing all occurrences of old The types of constructors are:
Char in this string with new Char. 1. Default constructor
Syntax: s1.replace(‘x’,’y’) 2. Constructor with no arguments
3. Parameterized constructor {
4. Copy constructor System.out.println("Roll no is: "+roll_no);
1. Default constructor: Java automatically creates default constructor if there is no System.out.println("Name is : "+name);
default or parameterized constructor written by user. Default constructor in Java }
initializes member data variable to default values (numeric values are initialized as 0, public static void main(String a[])
Boolean is initialized as false and references are initialized as null). {
Eg; Student s = new Student();
class test1 s.display();
{ }
int i; }
boolean b; 3. Parametrized constructor: Such constructor consists of parameters. Such
byte bt; constructors can be used to create different objects with datamembers having
float ft; different values.
String s; Eg;
public static void main(String args[]) class Student
{ {
test1 t = new test1(); // default constructor is called. int roll_no;
System.out.println(t.i); String name;
System.out.println(t.s); Student(int r, String n)
System.out.println(t.b); {
System.out.println(t.bt); roll_no = r;
System.out.println(t.ft); name=n;
} }
} void display()
2.Constructor with no arguments: Such constructors does not have any {
parameters. All the objects created using this type of constructors has the same System.out.println("Roll no is: "+roll_no);
values for its datamembers. System.out.println("Name is : "+name);
Eg: }
class Student public static void main(String a[])
{ {
int roll_no; Student s = new Student(20,"ABC");
String name; s.display();
Student() }
{ }
roll_no = 50; 4.Copy Constructor: A copy constructor is a constructor that creates a new object
name="ABC"; using an existing object of the same class and initializes each instance variable of
} newly created object with corresponding instance variables of the existing object
void display()
passed as argument. This constructor takes a single argument whose type is that of public void run()
the class containing the constructor. {
Eg; for(int i = 1;i<=20;i++) {
class Rectangle System.out.println(i);
{ }
int length; }
int breadth; public static void main(String a[])
Rectangle(int l, int b) {
{ MyThread t = new MyThread();
length = l; t.start();
breadth= b; }
} }
//copy constructor 2. By implementing the runnable interface.
Rectangle(Rectangle obj) Runnable interface has only on one method- run().
{ Eg:
length = obj.length; class MyThread implements Runnable
breadth= obj.breadth; {
} public void run()
public static void main(String[] args) {
{ for(int i = 1;i<=20;i++)
Rectangle r1= new Rectangle(5,6); {
Rectangle r2= new Rectangle(r1); System.out.println(i);
System.out.println("Area of First Rectangle : "+ (r1.length*r1.breadth)); }
System .out.println("Area of First Second Rectangle : "+ (r1.length*r1.breadth)); }
} public static void main(String a[])
} {
MyThread m = new MyThread();
Q.42 Explain the two ways of creating threads in Java. Thread t = new Thread(m);
Ans: Thread is a independent path of execution within a program. t.start();
There are two ways to create a thread: }
1. By extending the Thread class. }
Thread class provide constructors and methods to create and perform operations on a
thread. This class implements the Runnable interface. When we extend the class Q.43 Distinguish between Input stream class and output stream class.
Thread, we need to implement the method run(). Once we create an object, we can Ans: -Java I/O (Input and Output) is used to process the input and produce the
call the start() of the thread class for executing the method run(). output. Java uses the concept of a stream to make I/O operation fast. The java.io
Eg: package contains all the classes required for input and output operations. A stream is
class MyThread extends Thread a sequence of data. In Java, a stream is composed of bytes.
{
id=Integer.parseInt(br.readLine());
name=br.readLine();
}
catch(Exception ex)
{}
}
void display()
{
System.out.println("The id is " + id + " and the name is "+ name);
}
public static void main(String are[])
{
student[] arr;
arr = new student[5];
int i;
for(i=0;i<5;i++)
{
arr[i] = new student();
}
for(i=0;i<5;i++)
{
arr[i].SetData();
}
Q.44 Define a class student with int id and string name as data members and a for(i=0;i<5;i++)
method void SetData ( ). Accept and display the data for five students. {
Code: - arr[i].display();
import java.io.*; }
class student }
{ }
int id;
String name; Q.45 Explain dynamic method dispatch in Java with suitable example.
BufferedReader br = new BufferedReader(new Ans: Dynamic method dispatch is the mechanism by which a call to an overridden
InputStreamReader(System.in)); method is resolved at run time, rather than compile time.
void SetData() When an overridden method is called through a superclass reference, Java
{ determines which version (superclass/subclasses) of that method is to be executed
try based upon the type of the object being referred to at the time the call occurs. Thus,
{ this determination is made at run time.
System.out.println("enter id and name for student");
At run-time, it depends on the type of the object being referred to (not the type of {
the reference variable) that determines which version of an overridden method will // object of type A
be executed A a = new A();
A superclass reference variable can refer to a subclass object. This is also known // object of type B
as upcasting. Java uses this fact to resolve calls to overridden methods at run time. B b = new B();
Therefore, if a superclass contains a method that is overridden by a subclass, then // object of type C
when different types of objects are referred to through a superclass reference C c = new C();
variable, different versions of the method are executed. // obtain a reference of type A
Here is an example that illustrates dynamic method dispatch: A ref;
// A Java program to illustrate Dynamic Method // ref refers to an A object
// Dispatch using hierarchical inheritance ref = a;
class A // calling A's version of m1()
{ ref.m1();
void m1() // now ref refers to a B object
{ ref = b;
System.out.println("Inside A's m1 method"); // calling B's version of m1()
} ref.m1();
} // now ref refers to a C object
class B extends A ref = c;
{ // calling C's version of m1()
// overriding m1() ref.m1();
void m1() }
{ }
System.out.println("Inside B's m1 method");
} Q.46 Describe the use of following methods:
} (i) Drawoval ( )
class C extends A (ii) getFont ( )
{ (iii) drawRect ( )
// overriding m1() (iv) getFamily ( )
void m1() Ans:
{ (i) Drawoval ( ): Drawing Ellipses and circles: To draw an Ellipses or circles used
System.out.println("Inside C's m1 method"); drawOval() method can be used.
} Syntax: void drawOval(int top, int left, int width, int height)
} The ellipse is drawn within a bounding rectangle whose upper-left corner is specified
// Driver class by top and left and whose width and height are specified by width and height.To
class Dispatch draw a circle or filled circle, specify the same width and height.
{ Example: g.drawOval(10,10,50,50);
public static void main(String args[])
(ii) getFont ( ): It is a method of Graphics class used to get the font property if(fr!=null)
Font f = g.getFont(); fr.close();
String fontName = f.getName(); }
Where g is a Graphics class object and fontName is string containing name of the }
current font. }
(iii) drawRect ( ): The drawRect() method display an outlined rectangle.
Syntax: void drawRect(int top,int left,int width,int height) Q.48 Describe instance Of and dot (.) operators in Java with suitable example.
The upper-left corner of the Rectangle is at top and left. The dimension of the Ans: Instance of operator:
Rectangle is specified by width and height. The java instance of operator is used to test whether the object is an instance of the
Example: g.drawRect(10,10,60,50); specified type (class or subclass or interface).The instance of in java is also known as
(iv) getFamily ( ): The getfamily() method Returns the family of the font. type comparison operator because it compares the instance with type. It returns either
String family = f.getFamily(); true or false. If we apply the instance of operator with any variable that has
Where f is an object of Font class null value, it returns false.
Example:
Q.47 Write a program to count number of words from a text file using stream class Simple1
classes. (Note : Any other relevant logic shall be considered) {
Code: - public static void main(String args[])
import java.io.*; {
public class FileWordCount Simple1 s=new Simple1();
{ System.out.println(sinstanceofSimple1); //true
public static void main(String are[]) throws IOException }
{ }
File f1 = new File("input.txt"); dot (.) operator:
int wc=0; The dot operator, also known as separator or period used to separate a variable or
FileReader fr = new FileReader (f1); method from a reference variable. Only static variables or methods can be accessed
int c=0; using class name. Code that is outside the object's class must use an object reference
try or expression, followed by the dot (.) operator, followed by a simple field name.
{ Example:
while(c!=-1) this.name=”john”; where name is a instance variable referenced by
{ ‘this’ keyword
c=fr.read(); c.getdata(); where getdata() is a method invoked on object ‘c’.
if(c==(char)' ')
wc++; Q.49 Explain the four access specifiers in Java.
} Ans: There are 4 types of java access modifiers:
System.out.println("Number of words :"+(wc+1)); 1. private
} 2. default
finally 3. Protected
{ 4. public
1) private access modifier: The private access modifier is accessible only within Q.52 Write a program to copy content of one file to another file.
class. Code: -
2) default access specifier: If you don’t specify any access control specifier, it is class fileCopy
default, i.e. it becomes implicit public and it is accessible within the program. {
3) protected access specifier: The protected access specifier is accessible within public static void main(String args[]) throws IOException
package and outside the package but through inheritance only. {
4) public access specifier: The public access specifier is accessible everywhere. It FileInputStream in= new FileInputStream("input.txt");
has the widest scope among all other modifiers. FileOutputStream out= new FileOutputStream("output.txt");
int c=0;
Q.50 Differentiate between method overloading and method overriding. try
{
while(c!=-1)
{
c=in.read();
out.write(c);
}
System.out.println("File copied to output.txt....");
}
finally
{
if(in!=null)
in.close();
if(out!=null)
Q.51 Differentiate between Java Applet and Java Application (any four points) out.close();
}
}
}
6 MARKS BufferedReader br= new BufferedReader(new InputStreamReader(System.in) );
System.out.println("Enter a word:");
SUM-22 questions String str= br.readLine();
Q.1 How to create user defined package in Java. Explain with an suitable example. try
{
Q.2 Write a Java program in which thread A will display the even numbers between if (str.compareTo("MSBTE")!=0) // can be done with equals()
1 to 50 and thread B will display the odd numbers between 1 to 50. After 3 iterations throw new NoMatchException("Strings are not equal");
thread A should go to sleep for 500ms. else
System.out.println("Strings are equal");
Q.3 What is constructor? List types of constructors. Explain paramaterized }
constructor with suitable example. catch(NoMatchException e)
{
Q.4 Write a Java program to count the number of words from a text file using stream System.out.println(e.getMessage());
classes. }
}
Q.5 Explain the difference between string class and string buffer class. Explain any }
four methods of string class.
Q.8 Write a program to create a class 'salary with data members empid', ‘name'
Q.6 Write a Java applet to draw a bar chart for the following values. and ‘basicsalary'. Write an interface 'Allowance’ which stores rates of
calculation for da as 90% of basic salary, hra as 10% of basic salary and pf as
8.33% of basic salary. Include a method to calculate net salary and display it.
Ans: interface allowance
{
double da=0.9*basicsalary;
Q.7 Define an exception called 'No Match Exception' that is thrown when the
double hra=0.1*basicsalary;
password accepted is not equal to "MSBTE'. Write the program.
double pf=0.0833*basicsalary;
Ans: import java.io.*;
void netSalary();
class NoMatchException extends Exception
}
{
class Salary
NoMatchException(String s)
{
{
int empid;
super(s);
String name;
}
float basicsalary;
}
Salary(int i, String n, float b)
class test1
{
{
empid=I;
public static void main(String args[]) throws IOException
name=n;
{
basicsalary =b;
} Q.9 Compare array and vector. Explain elementAT( ) and addElement( )
void display() methods.
{
System.out.println("Empid of Emplyee="+empid);
System.out.println("Name of Employee="+name);
System.out.println("Basic Salary of Employee="+ basicsalary);
}
}
class net_salary extends salary implements allowance
{
float ta;
net_salary(int i, String n, float b, float t)
{
super(i,n,b);
ta=t;
}
void disp()
{
display();
System.out.println("da of Employee="+da);
}
public void netsalary()
{
double net_sal=basicsalary+ta+hra+da;
System.out.println("netSalary of Employee="+net_sal);
}
}
class Empdetail
{
public static void main(String args[])
{
net_salary s=new net_salary(11, “abcd”, 50000);
s.disp();
s.netsalary();
}
}
elementAT( ): The elementAt() method of Java Vector class is used to get the {
element at the specified index in the vector. Or The elementAt() method returns an System.out.println("palindrome");
element at the specified index. }
addElement( ): The addElement() method of Java Vector class is used to add the else
specified element to the end of this vector. Adding an element increases the vector {
size by one. System.out.println("not palindrome");
}
Q.10Write a program to check whether the string provided by the user is }
palindrome or not. }
Ans: import java.lang.*;
import java.io.*; Q.11 Define thread priority ? Write default priority values and the methods to
import java.util.*; set and change them.
class palindrome Ans: Thread Priority:
{ In java each thread is assigned a priority which affects the order in which it is
public static void main(String arg[ ]) throws IOException scheduled for running. Threads of same priority are given equal treatment by the java
{ scheduler.
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Default priority values as follows
System.out.println("Enter String:"); The thread class defines several priority constants as: -
String word=br.readLine( ); MIN_PRIORITY =1
int len=word.length( )-1; NORM_PRIORITY = 5
int l=0; MAX_PRIORITY = 10
int flag=1; Thread priorities can take value from 1-10.
int r=len; getPriority(): The java.lang.Thread.getPriority() method returns the priority of the
while(l<=r) given thread.
{ setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or
if(word.charAt(l)==word.charAt(r)) assign the priority of the thread to newPriority. The method throws
{ IllegalArgumentException if the value newPriority goes out of the range, which is 1
l++; (minimum) to 10 (maximum).
r--; import java.lang.*;
} public class ThreadPriorityExample extends Thread
else {
{ public void run()
flag=0; {
break; System.out.println("Inside the run() method");
} }
} public static void main(String argvs[])
if(flag==1) {
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample(); tf2 = new TextField();
ThreadPriorityExample th3 = new ThreadPriorityExample(); tf2.setBounds(50, 100, 150, 20);
System.out.println("Priority of the thread th1 is : " + th1.getPriority()); l3=new Lable(“Result”);
System.out.println("Priority of the thread th2 is : " + th2.getPriority()); l3.setBounds(10, 110, 150, 20);
System.out.println("Priority of the thread th2 is : " + th2.getPriority()); tf3 = new TextField();
th1.setPriority(6); tf3.setBounds(50, 150, 150, 20);
th2.setPriority(3); tf3.setEditable(false);
th3.setPriority(9); b1 = new Button("+");
System.out.println("Priority of the thread th1 is : " + th1.getPriority()); b1.setBounds(50, 200, 50, 50);
System.out.println("Priority of the thread th2 is : " + th2.getPriority()); b2 = new Button("-");
System.out.println("Priority of the thread th3 is : " + th3.getPriority()); b2.setBounds(120,200,50,50);
System.out.println("Currently Executing The Thread : " + b3 = new Button("*");
Thread.currentThread().gtName()); b3.setBounds(220, 200, 50, 50);
System.out.println("Priority of the main thread is : " + b4 = new Button("/");
Thread.currentThread().getPrority(); b4.setBounds(320,200,50,50);
Thread.currentThread().setPriority(10); b1.addActionListener(this);
System.out.println("Priority of the main thread is : " + b2.addActionListener(this);
Thread.currentThread().getPiority()); b3.addActionListener(this);
} b4.addActionListener(this);
} add(tf1);
add(tf2);
Q.12 Design an applet to perform all arithmetic operations and display the add(tf3);
result by using labels. textboxes and buttons. add(b1);
Ans: import java.awt.*; add(b2);
import java.awt.event.*; add(b3);
public class sample extends Frame implements ActionListener add(b4);
{ setSize(400,400);
Label l1, l2,l3; setLayout(null);
TextField tf1, tf2, tf3; setVisible(true);
Button b1, b2, b3, b4; }
sample() public void actionPerformed(ActionEvent e)
{ {
l1=new Lable(“First No.”); String s1 = tf1.getText();
l1.setBounds(10, 10, 50, 20); String s2 = tf2.getText();
tf1 = new TextField(); int a = Integer.parseInt(s1);
tf1.setBounds(50, 50, 150, 20); int b = Integer.parseInt(s2);
l2=new Lable(“Second No.”); int c = 0;
l2.setBounds(10, 60, 50, 20); if (e.getSource() == b1){
c = a + b; import java.awt.*;
} import java.applet.*;
else if (e.getSource() == b2){ public class hellouser extends Applet
c = a - b; {
else if (e.getSource() == b3){ String str;
c = a * b; public void init()
else if (e.getSource() == b4){ {
c = a / b; str = getParameter("username");
} str = "Hello "+ str;
String result = String.valueOf(c); }
tf3.setText(result); public void paint(Graphics g)
} {
public static void main(String[] args) { g.drawString(str,10,100);
new sample(); }
} }
} <HTML>
<Applet code = hellouser.class width = 400 height = 400>
Q.13 Explain how to pass parameter to an applet ? Write an applet to accept <PARAM NAME = "username" VALUE = abc> </Applet>
username in the form of parameter and print “Hello <username>”. </HTML>
Ans: Passing Parameters to Applet (OR)
• User defined parameters can be supplied to an applet using <PARAM…..> tags. import java.awt.*;
• PARAM tag names a parameter the Java applet needs to run, and provides a value import java.applet.*;
for that parameter. /*<Applet code = hellouser.class width = 400 height = 400>
• PARAM tag can be used to allow the page designer to specify different colors, <PARAM NAME = "username" VALUE = abc>
fonts, URLs or other data to be used by the applet. </Applet>*/
To set up and handle parameters, two things must be done. public class hellouser extends Applet
1. Include appropriate <PARAM..>tags in the HTML document. {
The Applet tag in HTML document allows passing the arguments using param tag. String str;
The syntax of <PARAM…> tag public void init()
<Applet code=”AppletDemo” height=300 width=300> {
<PARAM NAME = name1 VALUE = value1> </Applet> str = getParameter("username");
NAME:attribute name str = "Hello "+ str;
VALUE: value of attribute named by }
corresponding PARAM NAME. public void paint(Graphics g)
2. Provide code in the applet to parse these parameters. The Applet access their {
attributes using the getParameter method. g.drawString(str,10,100);
The syntax is: String getParameter(String name); }
Program: - }
Q.14 Write a program to perform following task
(i) Create a text file and store data in it.
(ii) Count number of lines and words in that file.
Ans: import java.util.*;
import java.io.*;
class Model6B
{
public static void main(String[] args) throws Exception
Ans: interface Salary
{
{
int lineCount=0, wordCount=0;
double Basic Salary=10000.0;
String line = "";
void Basic Sal();
BufferedReader br1 = new BufferedReader(new
}
InputStreamReader(System.in));
class Employee
FileWriter fw = new FileWriter("Sample.txt");
{
//create text file for writing
String Name;
System.out.println("Enter data to be inserted in file: ");
int age;
String fileData = br1.readLine();
Employee(String n, int b)
fw.write(fileData);
{
fw.close();
Name=n;
BufferedReader br = new BufferedReader(new
age=b;
FileReader("Sample.txt"));
}
while ((line = br.readLine()) != null)
void Display()
{
{
lineCount++; // no of lines count
System.out.println("Name of Employee :"+Name);
String[] words = line.split(" ");
System.out.println("Age of Employee :"+age);
wordCount = wordCount + words.length;
}
// no of words count
}
}
class Gross_Salary extends Employee implements Salary
System.out.println("Number of lines is : " + lineCount);
{
System.out.println("Number of words is : " + wordCount);
double HRA,TA,DA;
}
Gross_Salary(String n, int b, double h,double t,double d)
}
{
super(n,b);
Q.15 Implement the following inheritance
HRA=h;
TA=t;
DA=d;
} Object firstElement()-Returns the first component (the item at index 0) of this
public void Basic_Sal() vector.
{ Object elementAt(int index)-Returns the component at the specified index.
System.out.println("Basic Salary :"+Basic_Salary); int indexOf(Object elem)-Searches for the first occurence of the given argument,
} testing for equality using the equals method.
void Total_Sal() Object lastElement()-Returns the last component of the vector.
{ Object insertElementAt(Object obj,int index)-Inserts the specified object as a
Display(); component in this vector at the specified index.
Basic_Sal(); Object remove(int index)-Removes the element at the specified position in this
double Total_Sal=Basic_Salary + TA + DA + vector.
HRA; void removeAllElements()-Removes all components from this vector and sets its
System.out.println("Total Salary :"+Total_Sal); size to zero.
}
} Q.17 Explain the concept of Dynamic method dispatch with suitable example.
class EmpDetails Ans: Method overriding is one of the ways in which Java supports Runtime
{ public static void main(String args[]) Polymorphism. Dynamic method dispatch is the mechanism by which a call to an
{ Gross_Salary s=new overridden method is resolved at run time, rather than compile time.
Gross_Salary("Sachin",20,1000,2000,7000); When an overridden method is called through a superclass reference, Java
s.Total_Sal(); determines which version (superclass/subclasses) of that method is to be executed
} based upon the type of the object being referred to at the time the call occurs. Thus,
} this determination is made at run time.At run-time, it depends on the type of the
object being referred to (not the type of the reference variable) that determines which
Q.16 Describe the use of any methods of vector class with their syntax. version of an overridden method will be executed
(Note: Any method other than this but in vector class shall be considered for A superclass reference variable can refer to a subclass object. This is also known as
answer). upcasting. Java uses this fact to resolve calls to overridden methods at run time.
Ans: boolean add(Object obj)-Appends the specified element to the end of this If a superclass contains a method that is overridden by a subclass, then when
Vector. different types of objects are referred to through a superclass reference variable,
Boolean add(int index,Object obj)-Inserts the specified element at the specified different versions of the method are executed. Here is an example that illustrates
position in this Vector. dynamic method
void addElement(Object obj)-Adds the specified component to the end of this dispatch:
vector, increasing its size by one. / A Java program to illustrate Dynamic Method
int capacity()-Returns the current capacity of this vector. // Dispatch using hierarchical inheritance
void clear()-Removes all of the elements from this vector. class A
Object clone()-Returns a clone of this vector. {
boolean contains(Object elem)-Tests if the specified object is a component in this void m1()
vector. {
void copyInto(Object[] anArray)-Copies the components of this vector into the System.out.println("Inside A's m1 method");
specified array. }
} // now ref refers to a C object
class B extends A ref = c;
{ // calling C's version of m1()
// overriding m1() ref.m1();
void m1() }
{ }
System.out.println("Inside B's m1 method"); Output:
} Inside A’s m1 method
} Inside B’s m1 method
class C extends A Inside C’s m1 method
{ Explanation:
// overriding m1() The above program creates one superclass called A and it’s two
void m1() subclasses B and C. These subclasses overrides m1( ) method.
{ 1. Inside the main() method in Dispatch class, initially objects of
System.out.println("Inside C's m1 method"); type A, B, and C are declared.
} 2. A a = new A(); // object of type A
} 3. B b = new B(); // object of type B
// Driver class C c = new C(); // object of type C
class Dispatch
{ Q.18 Write a program to create two threads. One thread will display the
public static void main(String args[]) numbers from 1 to 50 (ascending order) and other thread will display numbers
{ from 50 to 1 (descending order).
// object of type A Code: - class Ascending extends Thread
A a = new A(); {
// object of type B public void run()
B b = new B(); {
// object of type C for(int i=1; i<=15;i++)
C c = new C(); {
// obtain a reference of type A System.out.println("Ascending Thread : " + i);
A ref; }
// ref refers to an A object }
ref = a; }
// calling A's version of m1() class Descending extends Thread
ref.m1(); {
// now ref refers to a B object public void run()
ref = b; {
// calling B's version of m1() for(int i=15; i>0;i--) {
ref.m1(); System.out.println("Descending Thread : " + i);
} Q.20 Write a program to input name and salary of employee and throw user
} defined exception if entered salary is negative.
} Code: - import java.io.*;
public class AscendingDescending Thread class NegativeSalaryException extends Exception
{ {
public static void main(String[] args) public NegativeSalaryException (String str)
{ {
Ascending a=new Ascending(); super(str);
a.start(); }
Descending d=new Descending(); }
d.start(); public class S1
} {
} public static void main(String[] args) throws IOException
{
Q.19 Explain the command line arguments with suitable example. BufferedReaderbr= new BufferedReader(new
Ans: Java Command Line Argument: InputStreamReader(System.in));
The java command-line argument is an argument i.e. passed at the time of running System.out.print("Enter Name of employee");
the java program. String name = br.readLine();
The arguments passed from the console can be received in the java program and it System.out.print("Enter Salary of employee");
can be used as an input. So, it provides a convenient way to check the behaviour of int salary = Integer.parseInt(br.readLine());
the program for the different values. You can pass N (1,2,3 and so on) numbers of Try
arguments from the command prompt. Command Line Arguments can be used to {
specify configuration information while launching your application. There is no if(salary<0)
restriction on the number of java command line arguments. You can specify any throw new NegativeSalaryException("Enter Salary amount
number of arguments Information is passed as Strings. They are captured into the isnegative");
String args of your main method Simple example of command-line argument in java System.out.println("Salary is "+salary);
In this example, we are receiving only one argument and printing it. To run this java }
program, you must pass at least one argument from the command prompt. catch (NegativeSalaryException a)
class CommandLineExample {
{ System.out.println(a);
public static void main(String args[]){ }
System.out.println("Your first argument is: "+args[0]); }
} }
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Q.21 Describe the applet life cycle in detail. Ans: import java.util.*;
Ans: class VectorDemo
{
public static void main(String[] args)
{
Vector v = new Vector();
v.addElement(new Integer(5));
v.addElement(new Integer(15));
v.addElement(new Integer(25));
v.addElement(new Integer(35));
Below is the description of each applet life cycle method: v.addElement(new Integer(45));
init(): The init() method is the first method to execute when the applet is executed. System.out.println("Original array elements are
Variable declaration and initialization operations are performed in this method. ");
start(): The start() method contains the actual code of the applet that should run. The for(int i=0;i<v.size();i++)
start() method executes immediately after the init() method. It also executes {
whenever the applet is restored, maximized or moving from one tab to another tab in System.out.println(v.elementAt(i));
the browser. }
stop(): The stop() method stops the execution of the applet. The stop() method v.insertElementAt(new Integer(20),1); // insert
executes when the applet is minimized or when moving from one tab to another in new element at 2nd position
the browser. v.removeElementAt(0);
destroy(): The destroy() method executes when the applet window is closed or when //remove first element
the tab containing the webpage is closed. stop() method executes just before when v.removeElementAt(3);
destroy() method is invoked. The destroy() method removes the applet object from //remove fourth element
memory. System.out.println("Array elements after insert
paint(): The paint() method is used to redraw the output on the applet display area. and remove operation ");
The paint() method executes after the execution of start() method and whenever the for(int i=0;i<v.size();i++)
applet or browser is resized. {
The method execution sequence when an applet is executed is: System.out.println(v.elementAt(i));
init() }}}
start()
paint() Q.23 Define package. How to create user defined package? Explain with
The method execution sequence when an applet is closed is: example.
stop() Ans: Java provides a mechanism for partitioning the class namespace into more
destroy() manageable parts. This mechanism is the package. The package is both naming and
visibility-controlled mechanism. Package can be created by including package as the
Q.22 Write a program to create a vector with five elements as (5, 15, 25, 35, 45). first statement in java source code. Any classes declared within that file will belong
Insert new element at 2nd position. Remove 1st and 4th element from vector. to the specified package. Package defines a namespace in which classes are stored.
The syntax for defining a package is:
package pkg; Q.24 Write a program to create two threads one thread will print even no.
Here, pkg is the name of the package between 1 to 50 and other will print odd number between 1 to 50.
eg : package Ans: import java.lang.*;
mypack; class Even extends Thread
Packages are mirrored by directories. Java uses file system directories to store {
packages. The class files of any classes which are declared in a package must be public void run()
stored in a directory which has same name as package name. The directory must {
match with the package name exactly. A hierarchy can be created by separating try
package name and sub package name by a period(.) as pkg1.pkg2.pkg3; which {
requires a directory structure as pkg1\pkg2\pkg3. for(int i=2;i<=50;i=i+2)
Syntax: {
To access package In a Java source file, import statements occur immediately System.out.println("\t Even thread :"+i);
following the package statement (if it exists) and before any class definitions. sleep(500);
Syntax: }
import pkg1[.pkg2].(classname|*); }
Example: catch(InterruptedException e)
package package1; {System.out.println("even thread interrupted");
public class Box }
{ }
int l= 5; }
int b = 7; class Odd extends Thread
int h = 8; {
public void display() public void run()
{ {
System.out.println("Volume is:"+(l*b*h)); try
} {
} for(int i=1;i<50;i=i+2)
Source file: {
import package1.Box; System.out.println("\t Odd thread :"+i);
class volume sleep(500);
{ }
public static void main(String args[]) }
{ catch(InterruptedException e)
Box b=new Box(); {System.out.println("odd thread interrupted");
b.display(); }
} }
} }
class EvenOdd
{
public static void main(String args[])
{
new Even().start();
new Odd().start();
}
}