Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

A.

M JAIN COLLEGE (SHIFT-II)


DEPARTMENT OF SOFTWARE APPLICATIONS
PREVIOUS YEAR QUESTION AND ANSWER
PROGRAMMING IN JAVA (UNIT-V)

2marks

1)Define datagram?(apr-13,nov-14,apr-15)
A datagram is an independent, self-contained message sent over the network in form of
bytes whose destination are not guaranteed.

2)Name any four layout managers in java?(apr-13)


The four layout managers are;
1)Flow Layout Manager.
2)Border Layout Manager.
3)Grid Layout Manager.
4)Card Layout Manager.

3)What is a host?(apr-12)
A host is a computer or other device connected to a computer network. A network host
may offer information resources, services, and applications to users or other nodes on the
network. A network host is a network node that is assigned a network layer host address.

4)What is the use of font class?(apr-12)


The Font class states fonts, which are used to render text in a visible way. some of the
font style are; plain,italic,bold etc. syntax: Font(string name, int style, int size)

5)Define controls?(nov-13)
Controls are defined as a package that provides an integrated set of classes to manage
user interface components like windows, dialog boxes, buttons, check boxes, lists , menus ,
scrollbars and text fields.

6)Give the expansion of URL?(nov-13)


URL stands for Uniform Resource Locator (or) Universal Resource Locator. It points to
resource files on the internet.
7)What is a tag?(nov-13)
A tag is a command in an html document that identifies the type of document component.
Attributes are used in a tag.

8)What is AWT?(apr-14,nov-15)
An expansion for AWT is Abstract Window Tool Kit. It is a package that provides an
integrated set of classes to manage user interface components like windows, dialog boxes,
buttons, check boxes, lists, menus, scrollbars and text fields.
9)What is a proxy server?(apr-16)
A proxy server is a server acts as an intermediary for requests from clients seeking
resources from other servers.

10)What is menu?(apr-16)
A menu is a list of commands or choices offered to the user. Menus are commonly used
in GUI operating systems and allow a user to access various options the software program is
capable of performing. some of the components are,JMenuBar — implements a menu bar;
JMenu — implements a menu, a popup window containing JMenuItems that is displayed when
the user selects an item on the JMenuBar.

11)Give the expansion of TCP/IP?(apr-15)


TCP stands for Transmission Control Protocol,IP stands for Internet Protocol ,which
allows for reliable communication between two applications. TCP is typically used over the
Internet Protocol, which is referred to as TCP/IP.

12)What is URL?(apr-14,nov-15)
Refer question no:6 in 2 marks.
5marks

1)Explain the various parts of URL class in java?(apr-12,apr-13)


The Java URL class represents an URL. URL is an acronym for Uniform Resource
Locator. It points to a resource on the World Wide Web. For ex: http://www.college.com/office
A URL contains many information;
1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.school.com is the server name.
3. Port Number: It is an optional attribute. If we write http//ww.college.com:80/office/ , 80
is the port number. If port number is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index1.jsp is the file name. The
java.net.URL class provides many methods. The important methods of URL class are
given below,

Method Description
public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.


public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.


public URLConnection openConnection() it returns the instance of URLConnection
i.e. associated with this URL.
Example :
import java.io.*;
import java.net.*;
public class url1
{
public static void main(String args[])
{
try
{
url1 url=new url1("http://www.college.com/office");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Protocol: http
Host Name: www.college.com
Port Number: -1
File Name: /office

2)Give a brief account on InetAddress class?(nov-15)


Java InetAddress class represents an IP address. The java.net.InetAddress class provides
methods to get the IP of any host name for example:www.college.com, www.google.com,
www.facebook.com etc.
Commonly used methods of InetAddress class
Method
Public static InetAddress getByName(String It returns the instance of InetAddress
host throws UnknownHostException conatining LocalHost IP and name.
Public static InetAddress getLocalHost() It returns the instance of InetAddress
throws UnknownHostException conatining LocalHost name and address.
Public String getHostName() It returns the host name of the IP address.
Public String getHostAddress() It retturns the IP address in string format.

Example:
import java.io.*;
import java.net.*;
public class InetDemo
{
public static void main(String args[])
{
try
{
InetAddress ip=InetAddress.getByName("www.college.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Host Name: www.college.com
IP Address: 206.51.231.148

3)Explain color class in java?(nov-13)


The Color class states colors in the default sRGB color space or colors in arbitrary color
spaces identified by a ColorSpace.
Class declaration:The declaration for java.awt.Color class:
public class Color extends Object implements Paint,Serializable
Field:The fields for java.awt.geom.Arc2D class:
1. static Color black -- The color black.
2. static Color BLACK -- The color black.
3. static Color blue -- The color blue.
4. static Color BLUE -- The color blue.
5. static Color cyan -- The color cyan.
6. static Color CYAN -- The color cyan.
Class constructors:
S.No Constructor & Description
1 Color(ColorSpace cspace, float[] components, float alpha)-Creates a color in the
specified ColorSpace with the color components specified in the float array and the
specified alpha.
2 Color(float r, float g, float b)-Creates an opaque sRGB color with the specified red,
green, and blue values in the range (0.0 - 1.0).
3 Color(float r, float g, float b, float a)-Creates an sRGB color with the specified red,
green, blue, and alpha values in the range (0.0 - 1.0).
4 Color(int rgb)-Creates an opaque sRGB color with the specified combined RGB
value consisting of the red component in bits 16-23, the green component in bits 8-15,
and the blue component in bits 0-7.
5 Color(int r, int g, int b)-Creates an opaque sRGB color with the specified red, green,
and blue values in the range (0 - 255).
6 Color(int r, int g, int b, int a)-Creates an sRGB color with the specified red, green,
blue, and alpha values in the range (0 - 255).

Methods:
1. int getBlue()-Returns the blue component in the range 0-255 in the default sRGB space.
2. static Color getColor(String nm)-Finds a color in the system properties.
3. int getGreen()-Returns the green component in the range 0-255 in the default sRGB
space
4. int getRed()-Returns the red component in the range 0-255 in the default sRGB space.
5. int getRGB()-Returns the RGB value representing the color in the default sRGB
ColorModel.

Example:
import java.awt.*;
import java.applet.*;
/*<applet Code="color" Width=500 Height=200>
</applet>*/
public class color extends Applet
{
public void paint(Graphics g)
{
Font plainFont = new Font("Serif", Font.PLAIN, 24);
g.setFont(plainFont);
g.setColor(Color.red);
g.drawString("Welcome to college", 50, 70);
g.setColor(Color.green);
g.drawString("hai", 50, 120);
}
}
Output:
Welcome to college
hai

4)Explain the class hierarchy for panel and frame?(nov-13)


The class hierarchy for panel and frame as follows,

1)Panel: panel class is concrete sub class of Container. Panel does not contain title bar, menu
bar or border.

2)Frame:It’s a sub class of Window and have resizing canvas. It is a container that contain
several different components like button, title bar, textfield, label etc. In Java, most of the AWT
applications are created usingFrame window.
class constructors:
1) Frame() throws HeadlessException
2) Frame(String title) throws HeadlessException .
There are two ways to create a Frame. They are,
1) By Instantiating Frame class
2) By extending Frame class
Example:
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
First f=new First();
}
}
Output:

5)Explain Border Layout?(apr-15)


The BorderLayout is used to arrange the components in five regions: north, south, east, west
and center. Each region (area) may contain one component only. It is the default layout of frame
or window. The BorderLayout provides five constants for each region:
1) public static final int NORTH
2) public static final int SOUTH
3) public static final int EAST
4) public static final int WEST
5) public static final int CENTER
Class Constructors:
1) BorderLayout(): creates a border layout but with no gaps between the components.
2) BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Method:
1) void addLayoutComponent(Component comp, Object constraints)-Adds the
specified component to the layout, using the specified constraint object.
2) void addLayoutComponent(String name, Component comp)-If the layout manager
uses a per-component string, adds the component comp to the layout, associating it with
the string specified by name.
3) int getHgap()-Returns the horizontal gap between components.
4) int getVgap()-Returns the vertical gap between components.
5) String toString()-Returns a string representation of the state of this border layout.
Example:
import java.applet.*;
import java.awt.*;
public class BorderButtons extends Applet
{
public void init()
{
setLayout(new BorderLayout(20, 10));
Button b1= new Button (“North”);

Button b2= new Button (“South”);


Button b1= new Button (“East”);
Button b1= new Button (“West”);
Button b1= new Button (“Center”);
add(b1,”North”);
add(b2,”South”);
add(b3,”East”);
add(b4,”West”);
add(b5,”Center”);
}
}

Output:

6)What is socket?How TCP/IP socket is created?(nov-14)


A socket is one endpoint of a two-way communication link between two programs
running on the network. A socket is bound to a port number so that the TCP layer can identify
the application that data is destined to be sent to.java provides two types of sockets,they are
1.stream socket.
2.Datagram socket.
1.stream socket:
The stream communication protocol is known as TCP (transfer control protocol). TCP is
a connection-oriented protocol. We must establish a connection between the pair of sockets.
While one of the sockets listens for a connection request (ie)server, the other asks for a
connection (ie)client. Once two sockets have been connected, they can be used to transmit data
in both (or either one of the) directions.
Class Constructors:
1) Socket(String host, int port) throws UnknownHostException, IOException-This
method attempts to connect to the specified server at the specified port. If this constructor
does not throw an exception, the connection is successful and the client is connected to
the server.
2) Socket(InetAddress host, int port) throws IOException-This method is identical to the
previous constructor, except that the host is denoted by an InetAddress object
Methods:
1) public InputStream getInputStream()-returns the InputStream attached with this socket
2) public OutputStream getOutputStream()-returns the OutputStream attached with this
socket
3) public synchronized void close()-closes this socket.
4) public Socket accept()-returns the socket and establish a connection between server and
client

2.Datagram socket:
The datagram communication protocol, known as UDP (user datagram protocol), is a
connectionless protocol, DatagramPacket is a message that can be sent or received. If you send
multiple packet, it may arrive in any order. packet delivery is not guaranteed.
Class constructors:
1) DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it
with the available Port Number on the localhost machine.
2) DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and
binds it with the given Port Number.
3) DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a
datagram socket and binds it with the specified port number and host address.

Example :server:
import java.io.*;
import java.net.*;
public class MyServer
{
public static void main(String args[])
{
Try
{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Client:
import java.io.*;
import java.net.*;
public class MyClient
{
public static void main(String args[])
{
Try
{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
10marks

1)Describe the various AWT controls in java?(nov-14,nov-15)


The various AWT controls in java are,
1. Label
2. Button
3. Check Boxes
4. List
5. Scroll Bar
6. Choice
7. Text Area

1.Label :Label is a passive control because it does not create any event when accessed by the
user. The label control is an object of Label. A label displays a single line of read-only text.
Class declaration:
The declaration for java.awt.Label class:
public class Label extends Component implements Accessible
Field:
Following are the fields for java.awt.Component class:

1. static int CENTER -- Indicates that the label should be centered.


2. static int LEFT -- Indicates that the label should be left justified.
3. static int RIGHT -- Indicates that the label should be right justified.

Class constructors:
S.No Constructor & Description
1 Label()-Constructs an empty label.
2 Label(String text)-Constructs a new label with the specified string of text, left justified.
3 Label(String text, int alignment)-Constructs a new label that presents the specified string
of text with the specified alignment.

Methods:
1)int getAlignment()-Gets the current alignment of this label.
2)String getText()-Gets the text of this label
3)void setAlignment(int alignment)-Sets the alignment for this label to the specified
alignment.

2.Button:It is a control component that has a label and generates an event when pressed. When a
button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling
processEvent on the button. The button's processEvent method receives all events for the button;
it passes an action event along by calling its own processActionEvent method.

Class declaration:The declaration for java.awt.Button class:


public class Button extends Component implements Accessible
Class constructors:
S.No Constructor & Description
1 Button()-Constructs a button with an empty string for its label.

2 Button(String text)-Constructs a new button with specified label.

Methods:
1.void addActionListener(ActionListener l):Adds the specified action listener to
receive action events from this button.
2.String getActionCommand():Returns the command name of the action event fired by
this button.
3.String getLabel():Gets the label of this button.
4.void setActionCommand(String command):Sets the command name for the action
event fired by this button.
5.void setLabel(String label):Sets the button's label to be the specified string.

3.Checkbox:It is a graphical component that can be in either an on (true) or off (false) state.
Class declaration:The declaration for java.awt.Checkbox class:
public class Checkbox extends Component implements ItemSelectable,Accessible
Class constructors:
S.No Constructor & Description
1 Checkbox()- Creates a check box with an empty string for its label.
2 Checkbox(String label)-Creates a check box with the specified label.
3 Checkbox(String label, boolean state)-Creates a check box with the specified label and
sets the specified state.
4 Checkbox(String label, boolean state, CheckboxGroup group)-constructs a Checkbox
with the specified label, set to the specified state, and in the specified check box group.
5 Checkbox(String label, CheckboxGroup group, boolean state)-Creates a check box
with the specified label, in the specified check box group, and set to the specified state.
Methods:
1. CheckboxGroup getCheckboxGroup()-Determines this check box's group.
2. void addItemListener(ItemListener l)-Adds the specified item listener to receive item
events from this check box.
3. String getLabel()-Gets the label of this check box.

4.List:It represents a list of text items. The List component presents the user with a scrolling list
of text items.
Class declaration:The declaration for java.awt.List class:
public class List extends Component implements ItemSelectable, Accessible
Class constructors:
S.No Constructor & Description
1 List()-Creates a new scrolling list.
2 List(int rows)-Creates a new scrolling list initialized with the specified number of visible
lines.
3 List(int rows, boolean multipleMode)-Creates a new scrolling list initialized to display
the specified number of rows.
Methods:
1. void add(String item)-Adds the specified item to the end of scrolling list.
2. void add(String item, int index)-Adds the specified item to the the scrolling list at the
position indicated by the index.
3. int getItemCount()-Gets the number of items in the list.

5.Scrollbar: It represents a scroll bar component in order to enable user to select from range of
values.
Class declaration:The declaration for java.awt.Scrollbar class:
public class Scrollbar extends Component implements Adjustable, Accessible
Field:The fields for class:
1. static int HORIZONTAL --A constant that indicates a horizontal scroll bar.
2. static int VERTICAL --A constant that indicates a vertical scroll bar.
Class constructors:
S.No Constructor & Description
1 Scrollbar()-Constructs a new vertical scroll bar.
2 Scrollbar(int orientation)-Constructs a new scroll bar with the specified orientation.
3 Scrollbar(int orientation, int value, int visible, int minimum, int maximum)-Constructs
a new scroll bar with the specified orientation, initial value, visible amount, and minimum
and maximum values.

Methods:
1. int getBlockIncrement()-Gets the block increment of this scroll bar.
2. int getMaximum()-Gets the maximum value of this scroll bar.

6.Choice control:It is used to show pop up menu of choices. Selected choice is shown on the top
of the menu.
Class declaration:The declaration for java.awt.Choice class
public class Choice extends Component implements ItemSelectable, Accessible
Class constructors:
S.No Constructor & Description
1 Choice()-Creates a new choice menu.
Methods:
1. void add(String item)-Adds an item to this Choice menu.
2. String getItem(int index)-Gets the string at the specified index in this Choice menu.
3. int getSelectedIndex()-Returns the index of the currently selected item.
4. void removeAll()-Removes all items from the choice menu.

7.TextArea:A TextArea object is a text component that allows for the editing of a multiple lines
of text.The scroll bar is automatically appears which help us to scroll the text up & down and
right & left.
Class declaration:The declaration for java.awt.TextArea class:
public class TextArea extends TextComponent
Field:The fields for java.awt.TextArea class:
1. static int SCROLLBARS_BOTH -- Create and display both vertical and horizontal
scrollbars.
2. static int SCROLLBARS_HORIZONTAL_ONLY -- Create and display horizontal
scrollbar only.
3. static int SCROLLBARS_NONE -- Do not create or display any scrollbars for the text
area.
4. static int SCROLLBARS_VERTICAL_ONLY -- Create and display vertical scrollbar
only.
Class constructors:
S.No Constructor & Description
1 TextArea()-Constructs a new text area with the empty string as text.
2 TextArea(int rows, int columns)-Constructs a new text area with the specified
number of rows and columns and the empty string as text.
3 TextArea(String text)-Constructs a new text area with the specified text.
4 TextArea(String text, int rows, int columns)-Constructs a new text area with the
specified text, and with the specified number of rows and columns.
5 TextArea(String text, int rows, int columns, int scrollbars)-Constructs a new text
area with the specified text, and with the rows, columns, and scroll bar visibility as
specified.
Methods:
1. void append(String str)-Appends the given text to the text area's current text.
2. void insert(String str, int pos)-Inserts the specified text at the specified position in this
text area.
3. void replaceRange(String str, int start, int end)-Replaces text between the indicated
start and end positions with the specified replacement text.
Example:
import java.applet.Applet;
import java.awt.Button;
import java.awt.Font;
/*<applet code="control" width=200 height=200>
</applet>*/
public class control extends Applet
{
public void init()
{
Label label1 = new Label("hai");
add(label1);
Button button1 = new Button("click");
Font myFont = new Font("Courier", Font.ITALIC,12);
button1.setFont(myFont);
add(button1);
Checkbox checkbox1 = new Checkbox("1");
checkbox1.setBackground(Color.red);
add(checkbox1);
List list = new List(2);
list.add("One");
list.add("Two");
add(list);
}
}

2)Explain in detail about the scrollbar control with an example program?(nov-13)


Scrollbar control represents a scroll bar component in order to enable user to select from
range of values.
Class declaration:The declaration for java.awt.Scrollbar class:
public class Scrollbar extends Component implements Adjustable, Accessible
Field:The fields for java.awt.Image class:
static int HORIZONTAL --A constant that indicates a horizontal scroll bar.
static int VERTICAL --A constant that indicates a vertical scroll bar.
Class constructors
S.No Constructor & Description
1 Scrollbar()-Constructs a new vertical scroll bar.
2 Scrollbar(int orientation)-Constructs a new scroll bar with the specified orientation.
3 Scrollbar(int orientation, int value, int visible, int minimum, int maximum)-
Constructs a new scroll bar with the specified orientation, initial value, visible amount,
and minimum and maximum values.
Class methods
S.No Method & Description
1 void addAdjustmentListener(AdjustmentListener l)-Adds the specified adjustment
listener to receive instances of AdjustmentEvent from this scroll bar.
2 void addNotify()-Creates the Scrollbar's peer.
3 int getBlockIncrement()-Gets the block increment of this scroll bar.
4 int getMaximum()-Gets the maximum value of this scroll bar.
5 int getMinimum()-Gets the minimum value of this scroll bar.
6 int getPageIncrement()
Deprecated. As of JDK version 1.1, replaced by getBlockIncrement().
7 int getUnitIncrement()
Gets the unit increment for this scrollbar.
8 int getValue()
Gets the current value of this scroll bar.
9 Boolean-Returns true if the value is in the process of changing as a result of actions
being taken by the user.
10 int getVisibleAmount()
Gets the visible amount of this scroll bar.
Example:
import java.awt.*;
import java.applet.*;
/*<APPLET Code="Scroll" Width=500 Height=200>
</APPLET>*/
public class Scroll extends Applet
{
Scrollbar bar = new Scrollbar(Scrollbar.VERTICAL, 10, 0, 1, 100);
public void init( )
{
add(bar);
}
}

4)Explain the various Layout managers in java?(apr-14,apr-16)


The layout manager is associated with every Container object. Each layout manager is an
object of the class that implements the LayoutManager interface.The Layout managers is set by
the setLayout() method.The general format is void setLayout (LayoutManager obj)
The various layout managers are;
1) Border Layout Manager.
2) Flow Layout Manager.
3)Grid Layout Manager.

1) Border Layout Manager: The BorderLayout is used to arrange the components in five
regions: north, south, east, west and center. Each region (area) may contain one component only.
It is the default layout of frame or window. The BorderLayout provides five constants for each
region:
1) public static final int NORTH
2) public static final int SOUTH
3) public static final int EAST
4) public static final int WEST
5) public static final int CENTER
Class Constructors:
1) BorderLayout(): creates a border layout but with no gaps between the components.
2) BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Method:
1) void addLayoutComponent(Component comp, Object constraints)-Adds the
specified component to the layout, using the specified constraint object.
2) void addLayoutComponent(String name, Component comp)-If the layout manager
uses a per-component string, adds the component comp to the layout, associating it with
the string specified by name.
3) int getHgap()-Returns the horizontal gap between components.
4) int getVgap()-Returns the vertical gap between components.
6) String toString()-Returns a string representation of the state of this border layout.

Example:
import java.applet.*;
import java.awt.*;
public class BorderButtons extends Applet
{
public void init()
{
setLayout(new BorderLayout(20, 10));
Button b1= new Button (“North”);
Button b2= new Button (“South”);
Button b3= new Button (“East”);
Button b4= new Button (“West”);
Button b5= new Button (“Center”);
add(b1,”North”);
add(b2,”South”);
add(b3,”East”);
add(b4,”West”);
add(b5,”Center”);
}
}
Output:

2)Flow Layout Manager:The FlowLayout is used to arrange the components in a line, one after
another.It is the default layout of applet or panel.
Fields:
1) public static final int LEFT
2) public static final int RIGHT
3) public static final int CENTER
4) public static final int LEADING
5) public static final int TRAILING
Class Constructors:
1) FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2) FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3) FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Methods:
1) int getAlignment()-Gets the alignment for this layout.
2) void addLayoutComponent(String name, Component comp)-Adds the specified
component to the layout.
3) void layoutContainer(Container target)-Lays out the container.
Example:
import java.applet.*;
import java.awt.*;
public class flow extends Applet
{
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT,5,5));
for(int i= 1,i<6;i++)
{
add(new Button(“ ”+i);
}
}
}
Output:

3)Grid Layout Manager: The GridLayout is used to arrange the components in rectangular
grid. One component is displayed in each rectangle.It automatically arranges components in a
grid.
Class Constructors:
1) GridLayout(): creates a grid layout with one column per component in a row.
2) GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3) GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.
Methods:
1) void addLayoutComponent(String name, Component comp)-Adds the specified
component with the specified name to the layout.
2) int getColumns()-Gets the number of columns in this layout.
3) int getHgap()-Gets the horizontal gap between components.
4) int getRows()-Gets the number of rows in this layout.
Example:
import java.applet.*;
import java.awt.*;
public class grid extends Applet
{
Button b1,b2;
GridLayout g=new GridLayout(2,2);
public void init()
{
setLayout(g);
b1=new Button(“how”);
b2=new Button(“Are”);
b3=new Button(“You”);
b4=new Button(“hai”);
add(b1);
add(b2);
add(b3);
add(b4);
}
}
Output:
How Are
You hai

5)Explain any five classes in java.util package?(apr-13)


Java.util package provides various classes that perform different utility functions.It
includes a class for working with dates ,generating random numbers. Some of the util packages
are,
1. Date class
2. Random class
3. String tokenzier class
4. Vector class
5. Calendar class
1.Date class:
The java.util.Date class represents a specific instant in time, with millisecond precision.
Class constructor:
1. Date()-This constructor allocates a Date object and initializes it so that it represents the
time at which it was allocated, measured to the nearest millisecond.
2. Date(long date)-This constructor allocates a Date object and initializes it to represent the
specified number of milliseconds since the standard base time known as "the epoch",
namely January 1, 1970, 00:00:00 GMT.
Methods:
1. boolean after(Date when)-This method tests if this date is after the specified date.
2. boolean before(Date when)-This method tests if this date is before the specified date.
3. boolean equals(Object obj)-This method compares two dates for equality.

2.Random class:
The java.util.Random class instance is used to generate a stream of pseudorandom
numbers.Following are the important points about Random:
The class uses a 48-bit seed, which is modified using a linear congruential formula.
The algorithms implemented by class Random use a protected utility method that on each
invocation can supply up to 32 pseudorandomly generated bits.
Class constructor:
1. Random()-This creates a new random number generator.
2. Random(long seed)-This creates a new random number generator using a single long
seed.
Methods:
1. protected int next(int bits)-This method generates the next pseudorandom number.
2. int nextInt()-This method returns the next pseudorandom, uniformly distributed int value
from this random number generator's sequence.
3. long nextLong()-This method returns the next pseudorandom, uniformly distributed long
value from this random number generator's sequence.

3.StringTokenizer :
The java.util.StringTokenizer class allows an application to break a string into tokens.Its
methods do not distinguish among identifiers, numbers, and quoted strings.This class methods do
not even recognize and skip comments.
Class constructor:
1. StringTokenizer(String str)-This constructor a string tokenizer for the specified string.
2. StringTokenizer(String str, String delim)-This constructor constructs string tokenizer
for the specified string.
3. StringTokenizer(String str, String delim, boolean returnDelims)-This constructor
constructs a string tokenizer for the specified string.
Methods:
1. int countTokens()-This method calculates the number of times that this tokenizer's
nextToken method can be called before it generates an exception.
2. String nextToken()-This method returns the next token from this string tokenizer.

4.vector class:
The java.util.Vector class implements a growable array of objects. Similar to an Array, it
contains components that can be accessed using an integer index. The important points about
Vector:
1. The size of a Vector can grow or shrink as needed to accommodate adding and removing
items.
2. Each vector tries to optimize storage management by maintaining acapacity and
a capacityIncrement.
3. Vector is synchronized.This class is a member of the Java Collections Framework.
Class constructor:
1. Vector()-This constructor is used to create an empty vector so that its internal data array
has size 10 and its standard capacity increment is zero.
2. Vector(int initialCapacity)-This constructor is used to create an empty vector with the
specified initial capacity and with its capacity increment equal to zero.
Methods:
1. boolean add(E e)-This method appends the specified element to the end of this Vector.
2. void add(int index, E element)-This method inserts the specified element at the
specified position in this Vector.
3. void clear()-This method removes all of the elements from this vector.

5.calendar class:
The java.util.calendar class is an abstract class that provides methods for converting between
a specific instant in time and a set of calendar fields such as YEAR, MONTH,
DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting
the date of the next week.The important points about Calendar:
1. This class also provides additional fields and methods for implementing a concrete
calendar system outside the package.
2. Calendar defines the range of values returned by certain calendar fields.
Fields:
1. static int DATE -- This is the field number for get and set indicating the day of the
month.
2. static int DAY_OF_MONTH -- This is the field number for get and set indicating the
day of the month.
3. static int DAY_OF_WEEK -- This is the field number for get and set indicating the day
of the week.
Example:

import java.util.*;
public class RandomDemo
{
public static void main( String args[] )
{
Random randomno = new Random();
int value = randomno.nextInt();
System.out.println("Value is: " + value);
}
}
Output:

Value is: -187902182

6)Desribe the various methods of AWT classes and write a program using AWT?(APR-
15)

The hierarchy of Java AWT classes and methods are,


1.Container:
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

2.Window:
The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.
3.Panel:
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

4. Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Methods:
1. public void add(Component c)- inserts a component on this component
2. public void setSize(int width,int height)- sets the size (width and height) of the
component.
3. public void setLayout(LayoutManager m)- defines the layout manager for the
component.
4. public void setVisible(boolean status)- changes the visibility of the component, by
default false

There are two ways to create a frame in AWT.


1. By extending Frame class.
2. By creating the object of Frame class.
The various AWT controls in java are,
1. Label
2. Button
3. Check Boxes
4. List
5. Scroll Bar
6. Choice
7. Text Area
Example:
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);
add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
First f=new First();
}
}
Output:

7)Explain the various AWT classes in java?(apr-12)


Answer:Refer question no:6 in 10 mark.

You might also like