You are on page 1of 40

Write a program that will compute the following series:

1/1 + 1/2 + 1/3 + ...... + 1/n


public class Suhrit
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
double sum=0.0;
for(int i=1;i<=n;i++)
sum=sum+(1.0/i);
System.out.println("Sum is "+sum);
}
}
1/1 + 1/2 + 1/22+ ....... + 1/2n
public class Suhrit
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
double sum=0.0;
for(int i=0;i<=n;i++)
sum=sum+(1.0/Math.pow(2,i));
System.out.println("Sum is "+sum);
}
}
What are conventional styles for class names, method names, constants and
variables?
a. Class Names: Begins with Capital Letters and each word is of the class is capitalized
(Title Case)
i. eg: ArrayIndexOutOfBoundsException (A,I,O,O,B and E are capital letters)
b. Method Names:Begins with small letters and other words of the method are
capitalized (Title Case except first letter)
i. eg: parseInt, showMessageDialog
c. Constant Names:All letters are capitalized (Upper Case)
i. eg:INFORMATION_MESSAGE,PI
d. Variables: All letters are small letters (Lower Case)
i. eg:area,area_of_the_circle
Can a java run on any machine? What is needed to run java on a computer?
(a) Yes! Java has portablity feature
(b) Requires JVM, Java Virtual Machine
Explain the concept of keywords. List some java keywords.
o Reserved words which are not used as variable names, those are having
predefined meaning, are called as keywords.
o Java reserved keywords which are used for developing programs.
o For example: if, while, for, final, abstract etc
o But const and goto are reserved but not used.
o Java 1.5 added enum keyword for enumerations
Describe the genesis of java. Also write brief overview of java
o Java was created by a group of team members at Sun Microsystems.
o First name of java is OAK, Object Application Kernal
o Java was developed for targeting microcontrollers like home appliances
o It's architecture neutral feature motivates towards Internet Programming
o Because of Security and portability, java gained importance related to Internet
o Applet programming in Java is source for Internet
o Bytecode, object code for java program, is suitable any OS or browser which
contains JVM, Java Virtual Machine
o Important buzzwords of java are simple, distributed, dynamic, interpreted,
robust, multi-threaded, Object-orinted, multithreaded
o MEMORY TIP: SRI-HARD-SPOD
 : Simple, Robust, Interpreted,High Performance, Architecture-Neutral,
Reliable, Dynamic, Secure,Portable, Object-Oriented, Distributed
List and explain the control statements used in java. Also describe the syntax of the
control statements with suitable illustration.
for,while,do-while,if-else,switch

for(initialization;condition;increment)
{
----
}
while(condition)
{
----
}
do
{
-----------
}
while(condition)
if (condition)
{
---
}
else
{
---
}
switch(expression)
{
case op1: { }
break;
case op2: { }
break;
...
default: { }
}
What are command line arguments? How are they useful?
Values passed at run time through java command are called as command-line arguments.
eg: java myprogram 1 2 3
(here 1, 2 and 3 are command line arguments)
These values are stored in arguments(args[]) of main( )
What are symbolic constants? How are they useful in developing programs?
o Symbolic Constants means constants defined thorugh final keyword
o Two types of symbolic constants are there
o One is Pre-defined like Math.PI etc.
o Another one user-defined like final int MAXNUM=300
Write a program that will read an unspecified number of integers and will determine
how many positive and negative values have been read. Your program ends when
the input is 0

import java.util.Scanner;
public class SuhritPosNeg
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int pos=0,neg=0,suh=0;
do
{
System.out.print("Enter Number (0 to Stop) ");
suh=s.nextInt();
if (suh>0)
pos++;
else if (suh<0)
neg++;
}
while(suh!=0);
System.out.println("Number of Positives "+pos);
System.out.println("Number of Negatives "+neg);
}
}

Write a program to convert the given temperature in Fahrenheit to Celsius using the
following conversion formula C = (F - 32)/1.8 And display the values in a tabular
form.

public class SuhritFahCel


{
public static void main(String args[])
{
double suhf=25.0,suhc=0.0;
System.out.println("---------------------------");
System.out.println("Fahrenheit Celsius");
System.out.println("---------------------------");
do
{
suhc=(suhf-32)/1.8;
System.out.printf("%5.2f\t\t%5.2f\n",suhf,suhc);
suhf=suhf+1.0;
}
while(suhf<40.0);
System.out.println("---------------------------");
}
}
What is an array? Why arrays are easier to use compared to a bunch of related
variables?
o Array is collection of similar datatype (homogeneous) elements
o With the help of an index we can access all elements in array, but it is not
possible with a bunch of related variables
o Arrays stored at consecutive memory locations, but if we declare bunch
variables, they stored at different locations
Write a program for transposition of a matrix using arraycopy command.

public class SuhritArCopy


{
public static void main(String args[])
{
int a[][]={{3,4,1},{1,3,5},{7,7,7}};
int b[][]=new int[3][3];
int i,j,temp1[],temp2[];
temp1 =new int[9];
temp2 =new int[9];
int k=0;
System.out.println("Given Matrix by Suh");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
for(i=0,k=0;i<3;i++)
for(j=0;j<3;j++)
temp1[k++]=a[i][j];
for(i=0,j=0,k=0;i<9;i++)
{
System.arraycopy(temp1,j,temp2,i,1);
j+=3;
if(j>=9)
j=++k;
}
System.out.println("Transposed Matrix by Rit");
for(i=0,k=0;i<3;i++)
{
for(j=0;j<3;j++)
{ b[i][j]=temp2[k++];
System.out.print(b[i][j]+" ");
}
System.out.println();
}
}
}

What is a constructor? What are its special properties?

o Constructor is a method which is autocally called when object is created.


o Constructor name is similar name with class name
o Constructor don't have return type
o Constructors can be overloaded
Ex:
class class-name
{
// No args constructor or default
class-name()
{
------
}

//Single args constructor


class-name(arg)
{
------
}
}
How do we invoke a constructor?

o By creating object using new keyword


 Emp e=new Emp();
 Calls constructor of emp class

What are objects? How are they created from a class?

o Objects are instances of class


o According theory, any real world entity which state, identity, behavior is called
objects
o By using new operator, objects are created
 Student s=new Student();
 Here s is object and calls constructor of student
o But
 Student x,y,z;
 only creates objects for Student class

What is class? How does it accomplish data hiding?

o Class is blue print for the objects


o Class defines the structure and behavior for objects
o Implementation details of methods are hidden is called data hiding
o private members of class can be accessed only with in the class

How do classes help us to organize our programs?

o We can achieve bottom-up approach


o Free flow of variables is avoided
o classes can be organized as heirarchy with the help of inheritance
o Implementation details are hidden
o Easy to organize the programs

Compare and contrast overloading and overriding methods.


o Overloading means usage of same method name with different signatures
(different number of parameters and different type of parameters)

class A
{
void disp(int k)
{
----
}
void disp(int k,int p)
{
----
}
}

o Overriding means using same method name and same number/type of


arguments in super and sub classes.

class A
{
void disp(int k)
{
----
}
}
class B extends A
{
void disp(int k)
{
----
}
}

Differences

 Overloading related to same class, overriding related to sub class and


super class
 Overloading contains same method name with different signature,
overriding contains same method name and same signature in sub-
super classes
How does String class differ from the StringBuffer class?
o Strings are fixed-length constants, StringBuffers are variable-length constants
o Objects of String class are not changeable (Immutable)
o Objects of StringBuffer class be change like insert, delete some of characters
from objects

Write program to do the following:


i. To output the question “who is the inventor of java”?
ii. To accept an answer
iii. To print out “Good” and then stop, if the answer is correct.
iv. To output the message “try again”, if the answer is wrong
v. To display the correct answer when the answer is wrong even at the third
attempt.

Points-wise Answer

for(int i=1;i<=3;i++)
{
 JOptionPane.showMessageDialog(null,"Who is the inventor of Java");
 String ans=JOptionPane.showInputDialog("Give Answer ");
 if (ans.equals("Patrick"))
JOptionPane.showMessageDialog(null,"Good");
 else
JOptionPane.showMessageDialog(null,"Try Again");
}
if(i==4)
 JOptionPane.showMessageDialog(null,"Answer is Patrick");

Code Segment

for(int i=1;i<=3;i++)
{
JOptionPane.showMessageDialog(null,"Who is the inventor of Java"); String
ans=JOptionPane.showInputDialog("Give Answer "); if (ans.equals("Patrick"))
JOptionPane.showMessageDialog(null,"Good");
else
JOptionPane.showMessageDialog(null,"Try Again");
}
if(i==4)
JOptionPane.showMessageDialog(null,"Answer is Patrick");

Briefly explain following:


(a) final & this keywords
 final keyword used to declare a variblae which can't be changed (Constants)
 final with method name means, that method can't be overridden in sub classes
 final with class name means, that class can't be inherited
 this refers to current object
 this.variable means current object's variable
 this.method( ) means methods belongs to current class
 this( ) is used as constructor call
(b) garbage collection

o Java provides garbage collection, means that automatically unused objects are
collected
o Every java program contains two threads one executes main program other
executes garbage collection
o Java not provided delete keyword, because of this garbage collection

(c) passing parameter-call by value


o Variables passed into methods are called as call-by values
 Changes not affect original variables
o objects passed into methods are called as call-by reference
 Changes affect original objects

(d) Overloading methods & Constructors.


 Overloading Methods

class Employee
{
void disp( )
{
----
}
void disp(int eno)
{
----
}
void disp(int eno,String name)
{
----
}
}

 Overloading Constructors

class Employee
{
Employee( )
{
----
}
Employee(int enum)
{
----
}
Employee(int enum,String name)
{
----
}
}

What is the difference between equality of objects and equality of objects and
equality of references that refer to them?

o Equality of objects means verifies references (==)


o Equality of objects of references means verifies actual contents (equals)
o When you assign object reference variable to another object reference
variables means, it is only a copy of the reference (=)
What is the difference between a public member and a private member of a class?

o public members can be accessible in any other class


o private members can't be accessible in other classes

write an application that computes the value of ex by using the formula:


ex = 1 + x/1! + x2/2! + x3/3! + ..........
int fact=1;
double sum=1.0;
for(int i=1;i<=n;i++)
{
fact=fact*i;
sum=sum+Math.pow(x,i)/fact;
}

What is the purpose of using a method? How do you declare a method? How do you
invoke a method?

What is method overloading? Can you define two methods that have same name but
different parameter types? Can you define two methods in a class that have
identical method names and parameter profile with different return value types or
different modifier ?

Create an abstract class with no methods. Derive a class and add a method. Create a
static method that takes a reference to the base class, downcasts it to the derived
class, and calls the method. In main( ), demonstrate that it works. Now put the
abstract declaration for the method in the base class, thus eliminating the need for
the downcast.

Without Method declared in A


abstract class A
{
}
class B extends A
{
void disp()
{
System.out.println("Well");
}
}
class C
{
public static void main(String args[])
{
A t;
B k=new B();
t=(A)k;
t.disp();
}
}

With Method declared in A


abstract class A
{
abstract void disp();
}

class B extends A
{
void disp()
{
System.out.println("Well");
}
}
class C
{
public static void main(String args[])
{
A t;
t=new B();
t.disp();
}
}

Is there any alternative solution for Inheritance. If so explain the advantages and
disadvantages of it.

o Yes! there is other alternative for inheritance


o This is called as object composition
o Objects declared as member variables is called object composition
o
 Ex:
class A
{
---
}

class B
{
A temp;
}

o Advantages of using Inheritance


 Reusability
 Reliablity
 Code sharing
 Decreased Maintanance
o Disadvantages of Using Inheritance
 Slower than spcialized codes
 Message passing more costly operation
 Overuse or improper use increases complexity
Explain about Object class in detail.

o Object is super class for all classes in Java


o With out extending Object class, other classes can inherit methods of Object
class
o Hence is called as special class in Java
o Some of the methods of Object class are
 equals( ): to compare two objects
 clone( ): to get duplicate
 toString( ): to convert into string type
 getClass( ): to get class of an object finalize( ): execeted before garbage
collection

Create an inheritance hierarchy of Rodent: Mouse, Gerbil, Hamster, etc. In the base
class, provide methods that are common to all Rodents, and override these in the
derived classes to perform different behaviors depending on the specific type of
Rodent. Create an array of Rodent, fill it with different specific types of Rodents,
and call your base-class methods. Explain the output.

class Rodent
{
void eat( )
{
}
}
class Mouse extends Rodent
{
void eat( )
{
System.out.println("MOUSE Eating");
}
}
class Gerbil extends Rodent
{
void eat( )
{
System.out.println("GERBIL Eating");
}
}
class Hamster extends Rodent
{
void eat( )
{
System.out.println("HAMSTER Eating");
}
}
public class test
{
public static void main(String args[])
{
Rodent r[]=new Rodent[3];
r[0]=new Mouse();
r[1]=new Gerbil();
r[2]=new Hamster();
r[0].eat();
r[1].eat();
r[2].eat();
}
}

Output:
MOUSE Eating
GERBIL Eating
HAMSTER Eating

What are the types of inheritances in java? Explain each of them in detail.
Java Supports Inheritances
Single, Heirarchy and Multilevel

Single
class A
{
----
}
class B extends A
{
----
}

Heirarchy
class A
{
----
}
class B extends A
{
----
}
class C extends A
{
----
}

Multi-Level
class A
{
----
}
class B extends A
{
----
}

class C extends B
{
----
}

Explain about final classes,final methods and final variables?

Explain about the abstract class with example program?

Add a new method in the base class of Shapes.java that prints a message, but don’t
override it in the derived classes. Explain what happens. Now override it in one of
the derived classes but not the others, and Explain what happens. Finally, override
it in all the derived classes, Explain in detail about each situation.

Create a base class with an abstract print( ) method that is overridden in a derived
class. The overridden version of the method prints the value of an int variable
defined in the derived class. At the point of definition of this variable, give it a
nonzero value. In the base-class constructor, call this method. In main( ), create an
object of the derived type, and then call its print( ) method. Explain the results.

Write a program to create a private inner class that implements a public


interface.Write a method that returns a reference to an instance of the private inner
class, upcast to the interface. Show that the inner class is completely hidden by
trying to downcast to it.

interface C
{
}
class A
{
private class B implements C
{
}
B get( )
{ return new B( );
}
}
public class Show
{
public static void main()
{
A x=new A();
// error B y=new B();
}
}

Prove that all the methods in an interface are automatically public.


interface C
{
void get( );
}

class B implements C
{
void get( )
{
System.out.println("Well");
}
}
public class Show
{
public static void main()
{
B y=new B();
y.get( );
}
}

Generates compile time error states that void get( ) is not defined as public, hence all the
methods in an interface are automatically public.

Write a program create an interface U with three methods. Create a class A with a
method that produces a reference to a U by building an anonymous inner class.
Create a second class B that contains an array of U. B should have one method that
accepts and stores a reference to a U in the array, a second method that sets a
reference in the array (specified by the method argument) to null and a third
method that moves through the array and calls the methods in U. In main( ), create
a group of A objects and a single B. Fill the B with U references produced by the A
objects. Use the B to call back into all the A objects. Remove some of the U
references from the B.

interface U
{
void get1();
void get2();
void get3();
}
class A
{
//Anonymous Inner class
void get(new U() { })
{
System.out.println("Well");
}
}
public class Show
{
public static void main()
{
A y=new A();
}
}

Create an interface with at least one method, in its own package. Create a class in a
separate package. Add a protected inner class that implements the interface. In a
third package, inherit from your class and, inside a method, return an object of the
protected inner class, upcasting to the interface during the return.

package p1;
interface A
{
void get1( );
void get2( );
void get3( );
}
import p1.*;
package p2;
class B
{
protected class C implements A
{
---
}
}
import p2.*;
package p3;
class D extends B
{
public C get( )
{
return new C( );
}
}

Write a program to create a class with a non default constructor and no default
constructor. Create a second class that has a method which returns a reference to
the first class. Create the object to return by making an anonymous inner class that
inherits from the first class.

class A
{
A(int s) { };
}
class B
{
public A getB( )
{
return new A( );
}
}
class D
{
//Anonymous Inner class
void getD(new B() { })
{
System.out.println("Well");
}
}

Prove that the fields in an interface are implicitly static and final.

interface C
{
int res=1000;
}

class B implements C
{
void get( )
{
System.out.println("Well");
}
}

public class Show


{
public static void main()
{
B y=new B();
System.out.println(B.res);
B.res=2000;
}
}

 Not generates any error regarding B.res means that res is static
but not defined as static in interface
 Generates compile time error states that res is final and can't change(can't assign a value
to final variable), but not defined as final in interface
 Means that the fields in an interface are implicitly static and final.

Create three interfaces, each with two methods. Inherit a new interface from the
three, adding a new method. Create a class by implementing the new interface and
also inheriting from a concrete class. Now write four methods, each of which takes
one of the four interfaces as an argument. In main( ), create an object of your class
and pass it to each of the methods.
interface A
{
void getA1(); void getA2();
}
interface B
{
void getB1(); void getB2();
}
interface C
{
void getC1(); void getC2();
}
interface D extends A,B,C
{
void getD();
}
class E
{
}
class F extends E implements D
{
public void getD() { }
public void getA1() { }
public void getA2() { }
public void getB1() { }
public void getB2() { }
public void getC1() { }
public void getC2() { }
public void get1(A k) { }
public void get2(B k) { }
public void get3(C k) { }
public void get4(D k) { }
}
public class ClueIV7
{
public static void main(String ar[])
{
F c=new F();
c.get1(c);
c.get2(c);
c.get3(c);
c.get4(c);
}
}

What is a package? How do we design a package?

How do we add a class or interface to a package?

What is interface? Write a program to demonstrate how interfaces can be extended.


What is package? How do you create a package? Explain about the access protection
in packages?

Explain the following exceptions with the help of examples:


(a) ArithmeticException
try
{
int d=0;
int b=5/d;
}
catch(ArithmeticException e)
{
}

(b) NullPointerException
try
{
B b;
}
catch(NullPointerException e)
{
}

(c) NumberFormatException
try
{
String x="R";
int a=Integer.pasreInt(x);
}
catch(NumberFormatException e)
{
}

With the help of an example, explain multithreading by extending thread class.


class A extends Thread
{
A()
{
start();
}
public void run()
{
for(int i=1;i<=100;i++)
System.out.println("XYZ");
}
}

Implementing Runnable interface and extending thread, which method you prefer
for multithreading and why.
class A implements Runnable
{
Thread t;
A( )
{
t=new Thread( );
t.start( );
}
public void run( )
{
for(int i=1;i<=100;i++)
System.out.println("XYZ");
}
}

What is the role of stack in exception handling?

o Stacks are useful for handling exceptions in smooth fashion


o Not advisiable to simply throw some exceptions deep in the call stack
o Restarting the state back to its original value before the operation is started is
complex

Give the classification of exceptions

o Checked Exception
 Exceptions that are caught at compile time, eg: InterruptedException
o Unchecked Exception
 Exceptions that are not caught at compile time, eg:
ArithmeticException
Example for Checked Exception
public class A
{
public static void main(String args[])
{
Thread.sleep(300);
}
}
Compilation of above program generate error by stating that
InterruptedException is not handled, hence it is Checked Exception
Example for Unchecked Exception
public class A
{
public static void main(String args[])
{
int c=5/0;
}
}
Compilation of above program not generate any error but, at runtime you can
observe ArithmeticException, hence it is UncheckedException
What is the difference between unchecked and checked exceptions in java?
o Checked Exception
 Exceptions that are caught at compile time, eg: InterruptedException
o Unchecked Exception
 Exceptions that are not caught at compile time, eg:
ArithmeticException
Compilation of program generate error by stating that InterruptedException
is not handled, hence it is Checked Exception
Compilation of program not generate any error but, at runtime you can
observe ArithmeticException, hence it is UncheckedException
Give the list of different unchecked exceptions in java and their meaning.
o Checked Exception
 Exceptions that are caught at compile time, eg: InterruptedException
o Unchecked Exception
 Exceptions that are not caught at compile time, eg:
ArithmeticException
Types of Unchecked Exceptions
 NumberFormatException: Trying to converting string to integers
 ArrayIndexOutOfBoundsException: Usage out of range index in array
 NullPointerException: invalid usage null reference
 ArithmeticException: Trying to apply division by zero
 StringIndexOutOfBoundsException: Usage out of range index in string

Explain in detail any two unchecked exceptions

Unchecked Exception

• Exceptions that are not caught at compile time, eg: ArithmeticException

Example for Unchecked Exception


public class A
{
public static void main(String args[])
{
int c=5/0;
int a=Integer.parseInt("T");
}
}

Compilation of above program not generate any error but, at runtime you can observe
ArithmeticException and NumberFormatException, hence they are Unchecked Exceptions
Handling of Exceptions
public class A
{
public static void main(String args[])
{
try
{
int c=5/0;
}
catch(ArithmeticException e)
{
System.out.println("div by zero");
}
try
{
int a=Integer.parseInt("T");
}
catch(NumberFormatException e)
{
System.out.println("can't convert");
}
}
}

In JAVA, is exception handling implicit or explicit or both. Explain with the help of
example java programs.

• In JAVA, is exception handling both implicit and explicit.


• Implicit exception handling is exceptions are automatically called
• Explicit exception handling is exceptions are not automatically called
o Checked Exception
 Exceptions that are caught at compile time, eg: InterruptedException
o Unchecked Exception
 Exceptions that are not caught at compile time, eg:
ArithmeticException
Example for Checked Exception
public class A
{
public static void main(String args[])
{
Thread.sleep(300);
}
}
Compilation of above program generate error by stating that
InterruptedException is not handled, hence it is Checked Exception
Example for Unchecked Exception
public class A
{
public static void main(String args[])
{
int c=5/0;
}
}
Compilation of above program not generate any error but, at runtime you can
observe ArithmeticException, hence it is UncheckedException
Is it possible to achieve true parallelism using multithreading. What are the
limitations in it?
• Multithreading
o Mutlithreading is possible in Java also can achieve true parallelism
o Thread is part of process
o Process is program under execution
o Simulatenous running of threads is possible, it is called as Multithreading
• Limitations
o Overuse of multithreading slowdowns the process
o Some times threads leads to deadlock conditions
o Synchronization is one reason deadlock situation

What is the role of priorities in multithreading. What are its limitations? How do you
set and get priority values for threads in Java.

• Priorities in Threads
o With the help of priorities we can change the execution of process
o We can assign high priority to speed up running process
o We can assign low priority to slow down running process
• Limiations for usage of priorities
o Predfined values only can be used
o Also creates problems with run time execution
• Methods for usage of priorities
o setPriority( ): to set priority for thread
o getPriority(): returns priority for current thread
• Constants defined related to priorities
o LOW_PRIORITY: constant with value 1 for low priority
o NORM_PRIORITY: constant with value 5 for normal priority
o HIGH_PRIORITY: constant with value 10 for high priority

Give the Class hierarchy in Java related to exception handling. Briefly explain each
class.
Exception
|
|
------------------------------------------------------
| | |
| | |
InterruptedException RuntimeException ClassNotFoundException
|
------------------------------------------
| | |
IllegalArgumentException ArithmeticException IndexOutOfBoundsException
| |
| |
NumberFormatException ------------------------------------
| |
ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException

What is the necessity of exception handling? Explain exception handling taking


“divide-by-zero” as an example.

public class A
{
public static void main(String args[])
{
try
{
int d=0;
int b=5/d;
System.out.println("Not executed");
}
catch(ArithmeticException e)
{
System.out.println("Error for division by zero");
}
}
}

What is the meaning of rethrowing an exception? When it is useful.

What are the limitations of exception handling feature of java. [8+8]

Why thread is called light weight task and process heavy weight task.
What are the different things shared by different threads of a single process. What
are the benefits of sharing?

Is multithreading suitable for all types of applications. If yes explain any such
application. If no, explain any application for which multithreading is not desired.

Define multithreading. Give an example of an application that needs multithreading.

How multithreading in single processor system is different from multithreading in


multiprocessor system. Explain.

Explain throws statement in Java with the help of an example program.

What is the difference between throw and throws statement.

Explain how threads with different priorities execute in environment which supports
priorities and which doesn’t support priorities.

what are the functions available in java related to priority.

Why creating a subclass of Frame is preferred over creating an instance of Frame


when creating a window.

o Creation of subclass means inheriting all the features of super class (Class X
extends Frame)
o Current class automatically work similar to the super class
o Easy to code the things
o Automatically constructor of super class is called with super( ) keyword
o Reusablity is achieved through this kind of feture
o Increase reliability
• But
o Instance creation for frame means it is like object composition
o Object composition is also used for creation for Frames
o Compared to inheritance, object composition overhead process is high
o We need to create instance with the help of new, hence better to use
inheritance feature for creating Frame

Explain the steps in creating a subclass of frame with the help of examples.

Steps In Creation of Frame

1. import the required awt package


2. create sub class for Frame class
3. create constructor with necessary initialization
4. Use super( ) to set the title of frame
5. Use setSize( ) to set width and height of frame
6. Add necessary components in the frame
7. Create a public class that contains main( ) method
8. Create an object for your frame class and setVisible(true)
• This above steps illustrated in the following example:

import java.awt.*; // Step 1


class MyFrame extends Frame // Step 2
{
Label lbl;
MyFrame() // Step 3
{
super("This is MyFrame"); //Step 4
setSize(300,400); //Step 5
lbl=new Label("Hello! I am SuhrIT");
add(lbl); //Step 6
}
}
public class Suhrit //Step 7
{
public static void main(String args[])
{
MyFrame f=new MyFrame(); //Step 8
f.setVisible(true);
}
}

What are the methods supported by the following interfaces. Explain each of them
(a) ActionListener interface

 ActionListener is an interface that contains the following method


 public void actionPeformed(ActionEvent e)

• This method is used for responding any kind of action like Click, double click or
change etc.
• Objects that invoke must register before using them like
• btn.addActionListener(this); //Here btn is object for Button class

 Example for ActionListener


import java.awt.*;
import java.awt.event.*;
class Suhrit extends Frame implements ActionListener
{
static int k=1;
Button btn;
Suhrit( )
{
super("Suhrit Click");
btn=new Button("Click Me");
add(btn);
btn.addActionListener(this);
setSize(200,200);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource( )==btn)
btn.setLabel("Button Clicked "+(k++)+" Times");
}
}
public class Example
{
public static void main(String args[])
{
Suhrit s=new Suhrit( );
s.setVisible(true);
}
}

(b) MouseMotionListener interface

o MouseMotionListener is an interface which contains the following two


methods
 public void mouseDragged(MouseEvent me)
 public void mouseMoved(MouseEvent me)
o MouseEvent is class that contains methods related mouse positions, for
example getX( ), getY( ) methods return X and Y positions
o mouseDragged method is invoked when you click and move mouse
o mouseMoved method is invoked when you move mouse
o showStatus( ) method in the following example is used to show any message
during applet execution
o addMouseMotionListener( ) method is registering current Applet/Frame with
mouse motion events, Now current object can respond to mouse motion events

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

/*
<applet code=Suhrit.class width=300 height=300>
</applet>
*/
public class Suhrit extends Applet implements MouseMotionListener
{
public void init()
{
addMouseMotionListener(this);
}

public void mouseDragged(MouseEvent me)


{
showStatus("Dragging at "+me.getX()+", "+me.getY());
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving at "+me.getX()+", "+me.getY());
}
}

(c) TextListener interface

o TextListener is an interface which contains the following method


 public void textChanged(TextEvent me)
o TextEvent is class that contains methods related text
o textChanged method is invoked automatically when there is a change in text
o showStatus( ) method in the following example is used to show any message
during applet execution
o addTextListener( ) method is registering current Applet/Frame with mouse
motion events, Now current object can respond to mouse motion events

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=Suhrit.class width=300 height=300>
</applet>
*/
public class Suhrit extends Applet implements TextListener
{
TextField tf;
public void init()
{
tf=new TextField();
add(tf);
tf.addTextListener(this);
}
public void textChanged(TextEvent me)
{
showStatus("change of text");
}

What is the functionality supported by java related to Fonts.

o Java Provides an easy way for using Fonts


o In awt package there Font class for this purpose
o To create a Font, we can use the following syntax
 Font f=new Font(font-name,font-style,font-size)
 font-names are like Timesroman, Arial, Sans Serif, Serif etc
 font-styles are like Font.PLAIN,Font.BOLD,Font.ITALIC
 font-size specifies point size for fonts
o for example, observe the following statement
o Font f=new Font("SansSerif",Font.BOLD,20);
 Sets bold character 20-length sansserif model font
• Observe the following sample program

import java.awt.*;
import java.applet.*;
/*
<applet code=ClueVI3a width=300 height=300>
</applet>
*/
public class ClueVI3a extends Applet
{
Font f;
public void init()
{
f=new Font("TimesRoman",Font.BOLD,20);
setFont(f);
}
public void paint(Graphics g)
{
g.drawString("SUHRIT",2,30);
g.drawString("SOLUTIONS",2,80);
}
}

How using different fonts improves the user interface.

o Fonts enhances user interface


o Earlier days all text is displayed in similar manner
o It creates monotony for the user
o With the help of fonts, you can high light important points
o You can show difference between headings,sub-headings and main text
o With the help of underlined text, you can attract user
o Different fonts, definitely help in increase of readbility of user interface
What are the methods supported by KeyListener interface and MouseListener
interface. Explain each of them with examples.
• Mouse Listener
o MouseListener is an interface, available in java.awt package
o This provides essential functionality of mouse related events
o addMouseListener(this) is used to register mouse events
o Methods available in MouseListener are
 public void mouseEntered(MouseEvent me)
 public void mouseExited(MouseEvent me)
 public void mouseClicked(MouseEvent me)
 public void mousePressed(MouseEvent me)
 public void mouseReleased(MouseEvent me)
o Purpose of above methods are self-explanatory
• Key Listener
o KeyListener is an interface, available in java.awt package
o All essential methods related to key events are defined in this interface
o addKeyListener(this) is used to register key events
o Methods available in KeyListener are
 public void keyPressed(KeyEvent ke)
 public void keyReleased(KeyEvent ke)
 public void keyTyped(KeyEvent ke)
o KeyEvent contains methods like getKeyChar( ) to get the typed
character
• Example Program for Mouse Listener
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code=ClueVI4a width=300 height=300>
</applet>
*/
public class ClueVI4a extends Applet implements MouseListener
{
Font f;
public void init()
{
addMouseListener(this);
}
public void mouseEntered(MouseEvent me)
{
showStatus("SUHRIT Mouse E N T E R E D");
}
public void mouseExited(MouseEvent me)
{
showStatus("SUHRIT Mouse Exited");
}
public void mouseReleased(MouseEvent me)
{
showStatus("SUHRIT Mouse Released");
}
public void mouseClicked(MouseEvent me) { }
public void mousePressed(MouseEvent me)
{
showStatus("Mouse P R E S S E D");
}
}

How event driven programming is different from Procedure oriented programming.


 Event Driven Programming
• Programming that deals with various kinds of actions is called as event driven
programming. A dynamic program which can respond to user actions
 Procedure-Oriented Programming
• Main program that dividies into various procedures is called procedure-oriented
programming. Either procedure-oriented or object-oriented programs can use event
driven programming approach. For example, you can add actions to both kind of
programming.
Give overview of Java’s event handling mechanism.

Steps In Creation of Event Hanlding Program

1. import the required awt.event package


2. create sub class for Frame class and implement required listener (eg:
ActionListener)
3. create constructor with necessary initialization
4. Use setSize( ) to set width and height of frame
5. Add necessary components in the frame
6. Add required listeners for the related components (Register)
7. Add required methods for the registered listeners
8. Create a public class that contains main( ) method
9. Create an object for your frame class and setVisible(true)
o Above steps illustrated in the following example:

import java.awt.*;
import java.awt.event.*;
class Suhrit extends Frame implements ActionListener
{
Button btn;
Suhrit( )
{
super("Suhrit Click");
btn=new Button("Click Me");
add(btn);
btn.addActionListener(this);
setSize(200,200);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource( )==btn)
btn.setLabel("Button Clicked ");
}
}
public class Example
{
public static void main(String args[])
{
Suhrit s=new Suhrit( );
s.setVisible(true);
}
}

Define Graphics context. How do you obtain graphics context.

Explain in brief different drawing functions of Java.

• Drawing Functions
There are several drawing functions available in Graphics class

o Graphics class is available in java.awt package


o Some of the drawing functions are
 drawString( ): This method is used to display string message at
required location
 For example: g.drawString("Suhrit",3,30); draws string at 3rd line 30
column
 drawLine( ): Draws line from (x1,y1) coordinates to (x2,y2)
 For example: g.drawLine(20,30,400,300) draws a line
 drawRect( ): Draws a rectangle from (x,y) position with given width
and height
 drawOval( ): Draws oval from (x,y) position with given width and
height
 drawPolygon( ): Draws polygon for given x array and y array points
 drawRoundRect( ): Draws rounded rectangle
 drawImage( ): Displays image in panel
o Following program illustrates some of the drawing functions
o
import java.awt.*;
import java.applet.*;
/*
<applet code=suhrit66b width=300 height=300>
</applet>
*/
public class suhrit66b extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10,10,50,50);
g.drawRect(10,10,50,50);
g.drawRoundRect(10,150,50,50,30,10);
g.drawOval(10,100,30,30); //circle
g.drawOval(100,100,30,60); //oval
g.drawString("SUHRIT",5,10);
}
}

What is Delegation Event model? Explain it. What are its benefits?

Define Event. Give examples of events. Define event handler. How it handles events.

• Event
o Event means action (Generally made at runtime)
o State change of objects defined through events
• Examples for events
o Example events TextEvent (changes in text), MouseEvent (moving,dragging
etc), ActionEvent (any kind of action)
• EventHandler
o Event Handler is code which handles the events occurred during run time
o For example: public void textChanged(TextEvent te) is used to handle changes
applied to text
• How it handles
o By registering the components with listeners, event handler can handle the
required events
o For example:t1.addTextListner(this);
• The following program illustrates the event handling related to AcitonListner

import java.awt.*;
import java.awt.event.*;
class Suhrit extends Frame implements ActionListener
{
static int k=1;
Button btn;
Suhrit( )
{
super("Suhrit Click");
btn=new Button("Click Me");
add(btn);
btn.addActionListener(this);
setSize(200,200);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource( )==btn)
btn.setLabel("Button Clicked "+(k++)+" Times");
}
}
public class Example
{
public static void main(String args[])
{
Suhrit s=new Suhrit( );
s.setVisible(true);
}
}

Write a java program which creates human face.

Write a java program which draws a dashed line and dotted line using applet.

Write a java program to draw a polygon of eight edges.

Why do you use frames?

Explain the syntax and functionality of different methods related to Frames.

What is the use of JPasswordField? Explain with an aid of an application program.

o JPasswordField
 To accept passwords from the user, we can use JPasswordField
 Automatically * will be displayed when user type characters
 Instead of *, if you want to display other character we need to use
setEchoChar.
 To access the typed text, we can use getTexT( ) method

import java.awt.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code=Suhrit.class width=300 height=300>
</applet>
*/
public class Suhrit extends JApplet
{
JPasswordField tf;
public void init()
{
tf=new JPasswordField();
add(tf);
}
}
What are the differences between JPopupMenu and JMenu?

• JPopupMenu
o This kind of menu is invoked when user click on right key of mouse
o No main menu is required here
o Automatically menu invoked
• JMenu
o Normal menus are added with the help of JMenu
o A main menu is required which contains set of menus

Differentiate following with suitable examples:


(a) Frame, JFrame

o Frame
 Frame is awt component
 This requires java.awt package
 Default layout is Borderlayout
 It include default container
o JFrame
 JFrame is swing compoent
 This requires javax.swing package
 Default layout is Flowlayout
 It not include default container
 Required getContentPane( ) to get default constructor

(b) Applet, JApplet

• Applet
o Applet is awt component
o This requires java.awt package
o Default layout is Flowlayout
• JApplet
o JApplet is swing compoent
o This requires javax.swing package
o Default layout is Borderlayout

(c) Menu, Jmenu

• Menu
o Menu is awt component
o This requires java.awt package
o There is no default menu bar
• JMenu
o JMenu is swing compoent
o This requires javax.swing package
o There is default menu bar

Explain the following:


(a) Creating an applet
Creation of Applets
o To create any user-defined applet class, that class must be sub-class of applet.
For example...

 public class MyApplet extends Applet


 or
 public class Rajesh extends Applet
o Second point to remeber is applets are defined applet package, so we need to
import that particular package in applet program.
 import java.applet.Applet;
 or
 import java.applet.*;
o Other required package for applets is awt, which stands for abstract window
toolkit. AWT provides all the required classes related to designing like Graphics.
 import java.awt.*;
o Atleast one method like init( ) or paint(Graphics g) required for a simple
applet, observe the following complete program.

import java.awt.*;
import java.applet.*;
/*
<applet code=Suhrit height=300 width=300>
</applet>
*/
public class Suhrit extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to U",30,40);
}
}

(b) Passing parameters to applets


Passing Parameters to Applet

 <Param> tag is used to add parameters to the applets


 Values of Param tag can be accessed with the help of getParam
Method
 Parameters to applets can be compared with command line
arguments
 Here parameters are passed in the form of PARAM tag.
 Param contains two properties Name and Value
The following program illustrates passing parameters
import java.awt.*;
import java.applet.*;
/*
<Applet code=MyThird.class width=300 height=300>
<Param name="X" value="hai">
</applet>
*/
public class MyThird extends Applet
{
String s;
public void paint(Graphics g)
{
s=getParam("X");
g.drawString(s,3,30);
}
}
(c) Adding graphics and colors to applets
Setting Colors to the Graphics

• There are two ways to set color for graphics one is using Color class and
other way is using directly with Color values.
o For example, g.setColor(Color.blue) or
o g.setColor(Color.red)
• Other way is calling constructor of Color class by passing red, green and blue
values.
o Color c=new Color(100,0,0);
o Here is 100 for red, 0 for green and 0 for blue.
o After that set the c for the Graphics object as follows:
o g.setColor(c);

// The following program illustrates this.


import java.awt.*;
import java.applet.*;
/*
<Applet code=MyThird.class width=300 height=300>
</applet>
*/
public class MyThird extends Applet
{
public void paint(Graphics g)
{
Color c=new Color(255,0,0);
g.setColor(Color.cyan);
for(int i=10;i<=70;i+=5)
{
g.drawLine(30,50,i,300); g.setColor(c);

}
}
}
Explain various methods of Applet class with necessary examples.
Methods of Applet Class
init( ) Called before applet initialized
start( ) Called before applet started
stop( ) Called after applet stopped
destroy( ) Called before applet is terminated
getImage( ) Returns image object
getCodeBase( ) Returns URL associated with applet code
play( ) Default clip to play
isActive( ) Returns true when applet is started
o The following code applet demonstrates first three methods

import java.awt.*;
import java.applet.*;
/*
<applet code=Suhrit height=300 width=300>
</applet>
*/
public class Suhrit extends Applet
{
Button btn;
public void init()
{
btn=new Button("OK");
}
public void start()
{
add(btn);
}
public void stop()
{
btn=null;
}
public void paint(Graphics g)
{
g.drawString("Welcome to U",30,40);
}
}
What are containers? List various containers. Explain the usage of JPanel with
example.
Various elements of Container
Panel Concrete sub class of container
Window Top level window for the frames
Frame Sub class of window and has a title bar, menu bar etc.

o Hierarchy diagram for Component and container

Component
|
|
Container
|
|
----------------
| |
Window Panel
| |
| |
Frame JPanel
|
|
JFrame

JPanel

o JPanel provides the drawing area with in a container


o It is subclass for Panel component
o The following code applet demonstrates JPanel

import java.awt.*;
import java.applet.*;
/*
<applet code=Suhrit height=300 width=300>
</applet>
*/
public class Suhrit extends Applet
{
JPanel p;
JButton btn;
public void init()
{
p=new JPanel();
p.setLayout(new FlowLayout());
}
public void start()
{
p.add(btn);
add(p);
}
}

What is JFC? Explain the differences between JTextArea, JTextComponent,


JTextField with examples.

JFC

o Stands for Java Foundation Classes


o These are also known as third party tools
o Available at javax.swing package
o Addtional graphical user interface methods

JTextComponent

o This class doesn't have required constructors


o We can't create objects for this class
o Super class for all text classes like JTextField
o Essential methods related to Text fields available here
o The following diagram shows the relation with other subclasses

JComponent
|
|
JTextComponent
|
--------------
| |
JTextArea JTextField
| |
JEditorPane JPasswordField

JTextArea

o Multiple line text field is called as text area


o Allows to type more than one line
o Some of the getter methods are getRows( ),getColumns( ), getLineCount( ) etc.
o Some of the setter methods are setRows( ),setColumns( ) etc.
Example Program for JTextArea is as follows:
import javax.swing.*;
/*
<applet code=suh width=300 height=300>
</applet>
*/
public class suh extends JApplet
{
JTextArea tf;
public void init()
{
tf=new TextArea(5,20);
add(tf);
}
}

JTextField

• User Data can be accepted through JTextField


• Allows to type single line
• Some of the methods are setText( ) and getText( ) etc.
Example Program for JTextField is as follows:
import javax.swing.*;
/*
<applet code=suh width=300 height=300>
</applet>
*/
public class suh extends JApplet
{
JTextField tf;
public void init()
{
tf=new TextField(20);
add(tf);
}
}
Briefly explain the components of AWT.
Various elements of Container
Panel Concrete sub class of container
Window Top level window for the frames
Frame Sub class of window and has a title bar, menu bar etc.

o Hierarchy diagram for Component and container

Component
|
|
Container
|
|
----------------
| |
Window Panel
| |
| |
Frame JPanel
|
|
JFrame
o The following code applet demonstrates first three methods
import java.awt.*;
import java.applet.*;
/*
<applet code=Suhrit height=300 width=300>
</applet>
*/
public class Suhrit extends Applet
{
JPanel p;
JButton btn;
public void init()
{
p=new JPanel();
p.setLayout(new FlowLayout());
}
public void start()
{
p.add(btn);
add(p);
}
}

Create an applet with two toolbars. One toolbar should be created using JButtons
and a separator and another toolbar should be created using 3 custom Action
classes. Add one to the ”north” and another to the ”south” sides of border layout.
When the user clicks one of the buttons in the toolbar, it will print a message to the
console stating that which button is being pressed from which toolbar. Add
functionalities to the buttons such as New, Open, Close, Save, Cut, Copy, Paste.

Explain the functionality of JComponent with example. Differentiate JComponent


and JPanel.

What are various JFC containers? List them according to their functionality. Explain
each of them with examples.

In what way JList differ from JComboBox?

JList does not support scrolling. Why? How this can be remedied? Explain with an
example.

Explain the steps involved in creating JCheckBox, JRadioButton, JButton, JLabel.

Write a program that creates a user interface to perform integer divisions. The user
enters two numbers in the textfields, Num1 and Num2. The division of Num1 and
Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or
Num2 were not an integer, the program would throw a NumberFormatException. If
Num2 were Zero, the program would throw an ArithmeticException Display the
exception in a message dialog box.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SuhritDivision extends JFrame implements ActionListener {
Container c;
JButton btn;
JLabel lbl1,lbl2,lbl3;
JTextField tf1,tf2,tf3;
JPanel p;
SuhritDivision() {
super("Exception Handler");
c=getContentPane();
c.setBackground(Color.red);
btn=new JButton("DIVIDE");
btn.addActionListener(this);
tf1=new JTextField(30);
tf2=new JTextField(30);
tf3=new JTextField(30);
lbl1=new JLabel("NUM 1");
lbl2=new JLabel("NUM 2");
lbl3=new JLabel("RESULT");
p=new JPanel();
p.setLayout(new GridLayout(3,2));
p.add(lbl1); p.add(tf1);
p.add(lbl2); p.add(tf2);
p.add(lbl3); p.add(tf3);
c.add(new JLabel("Division"),"North");
c.add(p,"Center");
c.add(btn,"South");
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn) {
try {
int a=Integer.parseInt(tf1.getText());
int b=Integer.parseInt(tf2.getText());
int c=a/b;
tf3.setText(""+c);
}
catch(NumberFormatException ex) {
tf3.setText("--");
JOptionPane.showMessageDialog(this,"Only Integer Division");
}
catch(ArithmeticException ex) {
tf3.setText("--");
JOptionPane.showMessageDialog(this,"Division by zero");
}
catch(Exception ex) {
tf3.setText("--");
JOptionPane.showMessageDialog(this,"Other Err "+ex.getMessage());
}
}
}

public static void main(String args[]) {


SuhritDivision b=new SuhritDivision();
b.setSize(300,300);
b.setVisible(true);
}
}
Write a Java program that creates three threads. First thread displays “Good
Morning” every one second, the second thread displays “Hello” every two seconds
and the third thread displays “Welcome” every three seconds.

class tst implements Runnable {


String name;
Thread t;
Arun(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("newThread : " +t);
t.start();
}
public void run() {
try {
for(int i=5;i > 0;i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + "exiting");
}
}
class LabPro16
{
public static void main(String args[])
{
new tst("Good Morning");
new tst("Hello");
new tst("Welcome");
try {
Thread.sleep(10000);
}
catch(InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting");
}
}

You might also like