Professional Documents
Culture Documents
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.
class A
{
void disp(int k)
{
----
}
void disp(int k,int p)
{
----
}
}
class A
{
void disp(int k)
{
----
}
}
class B extends A
{
void disp(int k)
{
----
}
}
Differences
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");
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
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?
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.
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.
class B
{
A temp;
}
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
{
----
}
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.
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();
}
}
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");
}
}
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);
}
}
(b) NullPointerException
try
{
B b;
}
catch(NullPointerException e)
{
}
(c) NumberFormatException
try
{
String x="R";
int a=Integer.pasreInt(x);
}
catch(NumberFormatException e)
{
}
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");
}
}
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
Unchecked Exception
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.
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
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");
}
}
}
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.
Explain how threads with different priorities execute in environment which supports
priorities and which doesn’t support priorities.
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.
What are the methods supported by the following interfaces. Explain each of them
(a) ActionListener interface
• 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
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);
}
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");
}
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);
}
}
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);
}
}
• Drawing Functions
There are several drawing functions available in Graphics class
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 draws a dashed line and dotted line using applet.
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
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
• 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
• 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
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);
}
}
• 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);
}
}
}
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.
Component
|
|
Container
|
|
----------------
| |
Window Panel
| |
| |
Frame JPanel
|
|
JFrame
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);
}
}
JFC
JTextComponent
JComponent
|
|
JTextComponent
|
--------------
| |
JTextArea JTextField
| |
JEditorPane JPasswordField
JTextArea
JTextField
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.
What are various JFC containers? List them according to their functionality. Explain
each of them with examples.
JList does not support scrolling. Why? How this can be remedied? Explain with an
example.
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());
}
}
}