Ajp All Practicals

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 97

`

Program: Computer Engineering (NBA Accredited)


Course - Advanced Java Programming (22515)
Practical Answer Sheet

Name of Student Swati Padhi


Roll No. 20203C0038

Class CO5I-C

Experiment No 1

Title of Experiment Write the program to demonstrate the use of AWT component.

Experiment-1

1. Develop a program using Label to display message “Welcome to Java”.

Program code :

Import.java.awt.*;
Class Exp1
{
Public static void main(String args[])
{
Frame f= new Frame();
f.setVisible(true);
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setTitle(“Experiment no.1”); Label
l1=new Label(“Welcome to Java”);
f.add(1);

1
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet

`
}
}
OutPut:

2. Devlop a program to select multiple languages known to user.

Program code:

import.java.awt.*; class
Expt1
{
Public static void main(String args[])
{
Frame f= new Frame();
f.setVisible(true);
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setTitle(“Experiment no.1”);

2
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet

`
Checkbox c1=new Checkbox(“Marathi”);
Checkbox c2=new Checkbox(“English”);
Checkbox c3=new Checkbox(“Hindi”);
Checkbox c4=new Checkbox(“Sanskrit”);

f.add(c1);
f.add(c2);
f.add(c3);
f.add(c4);
}
}
Output:

3. Write a program to create three Buttons with Caption Ok, Reset and Cancel.
Program code:

import.java.awt.*; class
Expt1

3
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet

`
{
Public static void main(String args[])
{

Frame f= new Frame; f.setVisible(true); f.setSize(400,400);

f.setLayout(new FlowLayout());
f,setTitle(“Experiment no.1”); Button
b1=new Button(“OK”);
Button b2=new Button(“RESET”);
Button b3=new
Button(“CANCEL”); f.add(b1);
f.add(b2);
f.add(b3);
}
}
Output:

4
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet

Practical related questions


1. State the difference between CheckBox and RadioButton Ans.

1 Radio buttons aíe used when we need to pick a single A checkbox authoíises us to choose one oí
option out of vaíious available alteínatives. moíe options.

2
Heíe we use an HľML <input> tag and set the íadio as We use the HľML <input> tag followed by
a type attíibute. the checkbox attíibute.

3 Radio button is a single contíol unit. Checkbox is a multiple contíol unit.

4
When we need to íestíict the useí’s selection to just It is opeíated when we need to peímit the
one option, then we use it. useí to choose multiple options.

5 It is shown as a little ciícle on the scíeen. It is shown as a small squaíe box.

2. Write the use of setEnabled() method.


Ans. The code setEnabled(false), disables the TextField it is not selectable and user
can’t copy data from it and also user cannot able edit or copy it is just used for
preventing purpose from being edited but it well still look the same as TextField
without setEnabled() method.

3. Draw the life cycle of an Applet.


Ans.

5
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet

Dated signature of
Marks Obtained
Teacher

Process Product Total


Related (35) Related (15) (50)

6
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Name of Student Swati Padhi


Roll No. 20203C0038
Class CO5I-C
Experiment No 2
Title of Experiment Write a program to design a form using the components List and Choice

Experiment-2

1. Develop an applet/application using List components to add names of 10


different cities.

Ans

Program code:

import java.awt.*;

import java.applet.*;

/*

<applet code=”T1” width=300 height=300> </applet>*/

Public class T1 extends Applet

Public void init()

List L= new List(10,true);

1
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
L.add(“Mumbai”);

L.add(“Pune”);

L.add(“Delhi”);

L.add(“Hydrabad”);

L.add(“Bengaluru”);

L.add(“Chennai”);

L.add(“Kolkata”);

L.add(“Ahemdabad”);

L.add(“Amritsar”);

L.add(“Agra”);

Add(L);

Output:

2
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

2. Develop applet/application to select multiple names of news papers

Ans.

Program code:

import java.awt.*;

import java.applet.*;

/*

<applet code=”T1” width=300 height=300> </applet>*/

Public class T1 extends Applet

Public void init()

3
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
{

List L= new List(10,true);

L.add(“Lokmat”);

L.add(“Sakal”);

L.add(“Indian Express”); add(L);

Output:

4
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
Practical Relates Questions
1. Write the name of components used in following output.

Ans. List is used in the above output.

2. State the difference between List and Choice control.

Ans.

3. Write the use of getSelecteItem() and getSelectedIndex() for List.

Ans.

5
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
i. getSelectedItem()

The getSelectedItem()method returns the label of the selected item.


The label is the string used in the add() or addItem() call.

ii. getSelectedIndex()

The getSelectedIndex() method returns integer array of the selected


items. If nothing is selected, the array will be empty.

Marks Obtained Dated


signature of
Teacher

Process Product Tota l


Related (35) Related (15) (50)

6
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Name of Student Swati Padhi


Roll No. 20203C0038
Class CO5I-C
Experiment No 3
Title of Experiment Write a program to design simple calculator with the use of Grid Layout

Experiment-3

1. Write a program to generate following output.

Ans.

Program code:

Import java.awt.*; class

{
public static void main(String args[])

1
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
{
Frame f=new Frame();
f.setVisible(true);

f.setSize(500,500);

f.setLayout(new GridLayout(3,2));
Button b1=new Button(“Button1”);

Button b2=new Button(“Button2”);

Button b3=new Button(“Button3”);

Button b4=new Button(“Button4”); Button b5=new

Button(“Button5”);

f.add(b1);

f.add(b2);

f.add(b3);

f.add(b4);

f.add(b5);

}
}

Output:

2
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

2. Write a program to generate following output using Border Layout.

Ans.

Program code:

Import java.awt.*;

Class R

3
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
public static void main(String args[])

Frame f=new Frame();

f.setVisible(true);

f.setSize(500,500);

f.setLayout(new BorderLayout() ); 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”);

f.add(b1,BorderLayout.NORTH);

f.add(b2,BorderLayout.SOUTH);

f.add(b3,BorderLayout.EAST);

f.add(b4,BorderLayout.WEST);

f.add(b5,BorderLayout.CENTER);

Output:

4
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Practical Related Questions


1. Give name of default Layout for different container.
Ans. FlowLayout is default layout for different container.

2. List the name of BorderLayout regions.


Ans. i. BorderLayout.CENTER

ii. BorderLayout.EAST iii.

BorderLayout.WEST iv.

BorderLayout.NORTH

v. BorderLayout.SOUTH

5
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
3. Write the default horizontal and vertical gap in flowLayout.
Ans. The default horizontal and vertical gap will be 5 pixels

4. Write the use of Insets in border layout.

Ans. The insets class provide a way to encapsulate the layout


margins of the four different sides of a container.

Marks Obtained Dated


signature of
Teacher

Process Product Tota l


Related (35) Related (15) (50)

6
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Name of Student Swati Padhi


Roll No. 20203C0038
Class CO5I-C
Experiment No 4
Title of Experiment Use of CardLayout to write a program to create a two level deck
that allows the user to select an operating system

Experiment-4

1. Write Java program to display following output.

Ans.

Program code.

1
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
Import java.awt.Button;

Import java.awt.GridBagConstraints;
Import java.awt.GridBagLayout;

Import javax.swing.*;

Public class FridBagLayoutExample extends JFrame{

Public static void main(String[] args){


GridBagLayoutExample a = new GridBagLayoutExample();

Public GridBagLayoutExample(){

GridBagLayout grid = new GridBagLayout();

GridBagConstraints gbc = new

GridBagConstraints(); setLayout(grid);

setTitle(“Griding Layout Example”); GridBagLayout

layout = new GridBagLayouy(); this.setLayout layout

= new GridBagLayout(); gbc.fill =

GridBagConstraints.HORIZONTAL; gbc.gridx=0;

gbc.gridy=0; this.add(new

Button(“Button One”), gbc); gbc.gridx =1; gbc.gridy

=0; this.add(new Button(“Button two”),gbc); gbc.fill

= GridBagConsstraints.HORIZONTAL; gbc.ipady =

20; gbc.gridx = 0; gbc.gridy =1; this.add(new Button(“Button

Three”), gbc); gbc.gridx =1;

2
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
gbc.gridy =1; this.add(new Button(“Button

Four”), gbc); gbc.gridx =0; gbc.gridy =2; gbc.fill=

GridBagConstraints.HORIZONTAL;

gbc.gridwidth = 2; this.ad(new

Button(“Button Five”),gbc);

setSize(300,300);

setPreferredSize(getSize()); setVisible(true);

Output:

3
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

2. Write Java Program to display following Output

4
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Ans.

Program code:

Import java.awt.*;

Class GridBagLayoutExample extends Frame

{
GridBagLayoutExample()

setLayout(new FlowLayout() ); Lablel b = new


Label(“Name”);

TextField t =new TextField(10);

Label c =new Label (“Comments”);

TextArea ta =new TextArea(6,15);

Button bs = new Button(“Submit”);


add(b);

add(t); add(c);

add(ta); add(bs);

5
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
class GridBagLayoutJavaExamplel

Public static void main (String args[])

GridBagLayoutExample frame = new

GridBagLayoutExample(); frame.setTitle(“GridBagLayout in

Java Example”); frame.setSize(300,200);

frame.setVisible(true);

Output:

6
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
Practical Relates Questions
1. State difference between GridLayout and GridBagLayout.

Ans

2. Explain constructor of GridBagLayout.

Ans.
GridBagLayout class is a flexible layout manager. It is used to aligns the components
horizontally, vertically, or along their baseline. It doesn’t require the components of the same
size. Each GridBagLayout object manages a rectangular grid of cells, dynamic with each
component occupying one or more cells, called its display area. GridBagLayout components
are associated with the instance of GridBagConstraints. These constraints are used to define the
component’s display area and their positions. In addition to its constraints object, the
GridBagLayout also considers each component’s minimum and preferred sizes in order to

7
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

`
determine a component’s size. GridBagLayout components are also arranged in the rectangular
grid but can have different sizes and can occupy the multiple rows or columns. Constructor:
GridBagLayout(): It is used to creates a grid bag layout manager.

Marks Obtained Dated


signature of
Teacher

Process Product Tota l


Related (35) Related (15) (50)

8
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Name of Student Swati Padhi


Roll No. 202030038
Class CO5I-C
Experiment No 5
Title of Experiment Write a program using AWT to create a menu bar where menu bar contains
menu items such as File, Edit, View and create a submenu under the File
menu: New and Open.

Experiment-5

1. Find errors in following program and display output as shown below.

Import java.awt.*;

Import java.awt.evemt.*;

Public class MenuDemo1 extends Frame

MenuBar mb;

MenuItem m1,m2,m3,m4;

MenuShortcut ms;

MenuDemo1()

setTItle(“MenuBar Demo”);

setSize(500,500); setLayout(null);

1
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

ms=new

MenuShortcut(KeyEvent.VK_X);

mn=new Menu(“File”): mb=new

MenuBar();

m1=new MenuItem(“New…,”);

m2=new MenuItem(“Open..,”);

m3=new MenuItem(“Save

As..”); m4=new

MenuItem(“Exit”,Ms);

ma.add(m1); mn.add(m2);

mn.addd(m3);

mn.addSeperator();

mn.add(m4); mb.add(mn);

Public static void nain(String[]args)

MenuDemo1 md=new MenuDemo1();

md.setVisible(true);

2
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Ans. Error is Main method not found in class MenuDemo1,


please define the main method as: public static void main(

String[] args) or a javaFX application class must extend


javafx.application.Application

New program code:


Import java.awt.*;

Import java.awt.evemt.*;

Public class MenuDemo1 extends Frame

MenuBar mb;

MenuItem m1,m2,m3,m4;

MenuShortcut ms;

MenuDemo1()

3
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

setTItle(“MenuBar Demo”);

setSize(500,500); setLayout(null); ms=new

MenuShortcut(KeyEvent.VK_X); mn=new

Menu(“File”):

mb=new MenuBar(); m1=new MenuItem(“New…”);

m2=new

MenuItem(“Open..”); m3=new

MenuItem(“Save As..”); m4=new

MenuItem(“Exit”,ms);mn.add(m1)

mn.add(m2); mn.addd(m3);

mn.addSeperator(); mn.add(m4); mb.add(mn);

Public static void nain(String[]args) {

MenuDemo1 md=new MenuDemo1();

md.setVisible(true); } }

Output:

4
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Practical Related Questions


1. Write the use if setEnabled() method.

Ans. The cod esetEnabled(false), disables the TextField it is not selectable


and user can’t copy data from it and also user cannot able edit or copy, it
is just used for preventing purpose from being edited, but it will still look
the same as TextField without setEnabled() method.

2. Write the procedure to assign shortcut key to the Menu Item.

Ans.

i. JMenuBar – To create a menu bar. ii.

JMenu – To create a menu.

iii. JMenuItem – To create a menu item

5
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet
iv. JmenuIt
em.setMnemonic(KeyEvent. VK_N) – A set keyboard shortcut to a
menu item

To create shuBar – To shortcut

Assign the shortcut:

mnuNew.setMnemonic(KeyEvent.VK_N);

VK N: ALT+n

You can set VK_A to VK_Z

3. Write a syntax and use of addSeparator() method.

Ans. Syntax :

i. public void add separator() – This will append anew separator to


the end of the menu.

ii. Public void add separator(Dimension Size)- This will append a


Separator of a specified size to the end of the tool bar.

Marks Obtained Dated


signature of
Teacher

Process Product Tota l


Related (35) Related (15) (50)

6
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Name of Student Swati Padhi


Roll No. 20203C0038
Class CO5I-C
Experiment No 6
Title of Experiment Write a program using swing to display a ScrollPane and JComboBox in an
JApplet with the items – English, Marathi, Hindi, Sanskrit.

Experiment 6

1. Write a program to develop a frame to select the different states of India using
JComboBox.

Ans.

Program code:

Import javax.swing.*;

Public class Aaa

Aaa(){

JFrame f= new JFrame();

String a[] = {“Maharashtra”, “Punjab”, “Gujarat”, “TamilNadu”);

JcomboBox cb=new JComboBox(a); Cb.setBounds(50,50,90,20);

f.add(cb); f,setLayou(null);

f.setSize(400,400);

f.setVisible(true);

1
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Public static void main(String args[])

{new Aaa();}

Output:

2. Devlop a program to demonstrate the use of ScorllPane in Swings.

Ans. Program code:

Import java.awt.*;

Import class Aaa {

Private statuc void Scroll(){

Final JFrame f = new JFrame();

2
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

f.setSize(500,500);

f.setVisible(true);

f.setDefaultCloseOperation(J/frame.EXIT_ON_CLOSE);

f.getContentPane(). setLayout(new FlowLayout());

JTextArea t = new JTextArea(20,20);

JScrollPane s1 = new JScrollPane(t);

S1.setHorinzontalScrooBarane.HORIZONTAL_SCROLLBAR_ALWAYS);

S1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

F.getContentPane(). Add(s1);

Public static void main (String args[]){

Javax.swing.SwingUtilities.invokeLater(new Runnable() {

Pubic void run() {

Scroll();

}}; } }

Output:

3
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Practical Relate Questions


1. State the difference between AWT and Swing.

Ans.

4
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

2. State the features of Swing.

Ans.

i. Light Weight – Swing components are independent of native


Operating systems API as Swing API controls are rendered
mostly using pure Java code instead of underlying operating
system calls.

ii. Rich Controls – Swing provides a rich set of advanced controls


like tree, tabbedPane, slider, colorpicker, and table controls. iii.
Highly customizable – Swing controls can be customized in a
very easy way as cisual appearance is independent of internal
representation.
3. Name the method to obtain ContentPane in swing.

Ans. getContentPane()

In java Swing, the layer that is used to hold objects is called the
fcontent pane. The getContentPane() method retrieves the content pane
layer so the you can add an object to it The content pane is an object
created by the Java run time environment.

This method is used to obtain ContentPane in swing

5
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Marks Obtained Dated


signature of
Teacher

Process Product Tota l


Related (35) Related (15) (50)

6
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Name of Student Swati Padhi

Roll No. 202030038


Class CO5I-C

Experiment No 7

Title of Experiment Write a program to create a JTree.

Experiment 7

1. Write a Jtree program to show root directory and its subFolders of your Systems.

Ans.

Program code:

Import java.io.*:

Public class Main{

Public static void main (String[] args)

{ File[] roots =File.listRoots();

System.out.println(roots[i].toString());

} } } */

// second program for displaying root directories

//importing classes/files

Import java.io*;

Import java.io.File;

Class Main{

1
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet
// main
driver code

Public static void main(String[] args)

{ try

File[] files = dir.listfiles(); for

(File file : files) {

if(file.isDirectory()) {

System.out.println{
“directory:”+ file.getCanonicalPath()};

displayDirectory(file);

// simply get the path else

System.out.println{

“file:”+ file.getCanonicalPath()};

} }

Catch(IOException e) {

e.printStackTrace();

} } }

2
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet
Output:

Practical Related Questions:


1. State the use of JTree is Swing.

ans.

i. The Jtree class is used to display the tree structured data or


hierarchical data.

ii. It has a root node at the top most which is apparent for all nofres in
the tree.

iii. It inherits JComponent class.

2. State the use of getPathForLocation{} method.

Ans. getPathForLacation{} – It is used to translate a mouse cclick on a


specific point of the tree to a tree path.

3. List different package used to implement JTree programs.

3
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet
Ans.

i. Import java.awt.*; ii. Import java.awt.Component; iii. Import

java.awt.Container; iv. Import javax.swing;

v. Import javax.swing.JComponent; vi.

Import javax.swing.JTree;

Marks Obtained Dated


signature of
Teacher

Process Product Tota l


Related (35) Related (15) (50)

4
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Name of Student Swati Padhi


Roll No. 20203C0038
Class CO5I-C
Experiment No 10
Title of Experiment Write a program to demonstrate status of key on Applet window
such as KeyPressed, KeyReleased, KeyUp, KeyDown

Experiment No.10

1. Develop a program to accept two numbers and display product of two numbers
when user pressed ”Multiply” button.
Ans.
Program code:

Import java.awt.*;
Import java.awt.event.*;
Public class Exp10 extends Frame implements ActionListener
{
Label l1, l2, l3;
Textfield tf1;
Int num1, num2;
Exp10(int n1, int n2)
{ setSize(400,400); setLayout(
new FlowLayout()); setVisible(true);
num1=n1;
num2=n2; l1=new
Label(“num1:”+n1); l2= new
Label(“num2:” +n2);

1
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

tf1 = new TextField(30);

Button b1= new Button(“Multiply”);

Add(l1);
Add(l1);
Add(l1);
Add(l1)

Add(l2);
Add(b1);
Add(tf1);
B1.addActionListener(this);
}
Public void actionPerformed(ActionEvrent e) // overriding the keyPressed() method
of Keylistener interface
{
Tf1.setText(“Multication is:” +num1*num2);

}
Public static vpoid main(String[][ args)
{

New Exp10(12,13);

} }
Output:

2
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

Practical Related Questions


1. Name any four Event Listener interfaces.
Ans. Four Event Listener Interface
are: i. ActionListener ii.
ItemListener iii. KeyListener iv.
MouseListener
2. State the situation when all three events of KeyListener interface are
generated?
Ans.
Import java.awt.*;
Import java.awt.event.*;
Public class Exp10 extends Frame implements KeyListener
{
Label l;
TextArea area; Exp10(){
setSize(400,400);

3
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

setLayout(null);
setVisible(true); l
= new Label();
l.setBounds (20, 50, 100, 20);
area = new TextArea();
area.adKeyListener(this);
add(l); add(area);
}
Public void keyPressed (KeyEvent e) //overriding the keypressed()
method of KeyListener interface { l.setText (“Key Pressed”);
}
Public void keyReleased (KeyEvent e) //overriding the keyReleased()
method of KeyListener interface

{ l.setText(“Key Released”);
}
Public void keyTyped (keyEvent e) // overriding the keyTyped() method of
Keylistener interface

{
}
Public static void main(String[] args)
{
New Expt10();

}
}

3. Elaborate the terms Event, Source and Listener.


Ans.

4
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet
i.
Event:- Event is an object that describes state chage in a source.
Event may also occur that are not directly caused by
interactions with the UI.
Applet are event driven programs. Tjere are several types of events. ii.
Event Sources:- A source is an object that generates an event. Sources may
generate more than one type of event. A source must registr listeners I
order for the listeners to receive notification about specific type of event.
Each type of event has its own registration method. iii. Event Listener:- A
listener is an object that is notified when an event occurs. It has two major
requirements. It must registered with one or more Sources to receive
notification about specific type of events.
4. List various methods of ActionListener interface.
Ans. Method in ActionListener interface
i. Void actionPeerformed(ActionEvent e) Invoked when an
action occurs.

Marks Obtained Dated


signature of
Teacher

Process Product Tota


Related (35) Related (15) l
(50)

5
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22517)
Practical Answer Sheet

6
Name of Student Swati Padhi
Roll No. 20203C0038
Class CO5I-C
Experiment No 11
Title of Experiment Write a program to demonstrate various mouse events using
MouseListener and MouseMotion listener interface.

Experiment-11

1. Write a program to change the background color of Applet when user performs events
using Mouse.

Ans.

Import java.applet.*;

Import java.awt.*;

Import java.awt.event.*;

/*<Applet code =”e1” width=300 height=200></applet>*?

Public class e1 extends Applet implements MouseListener

Public void init()

{
addMouseListener(this);

Public void mouseClicked(MouseEvent e)

{
setBackgrounf(Color.YELLOW);

Public void mouseEntered(MouseEvent e)

{
}
Public void mouseExitedd(MouseEvent e)

{
}

Public void mousePressed(MouseEvent e)

Public void mouseReleased(MouseEvent e)

{
}

Output:

2. Write a program to count the number of clicks performed by the user in a Frane window.

Ans.

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

/* <APPLET CODE ="MouseDemo" WIDTH=300 HEIGHT=200> </APPLET> */ public

class MouseDemo extends Applet implements MouseListener


{

Label l;
public void init()

setLayout(null); l=new Label("Hello Mouse");

l.setBounds(50,150,200,100); add(l);

public void mousePressed(MouseEvent e)

l.setText("Mouse Pressed no. of clicks:" + e.getClickCount() + "at position" + e.getX() + ","+


e.getY());

public void mouseReleased(MouseEvent e)

l.setText("Mouse Released; # of clicks:"+e.getClickCount());

public void mouseEntered(MouseEvent e)

l.setText("Mouse Entered");

public void mouseExited(MouseEvent e)

l.setText("Mouse exited");

}
public void mouseClicked(MouseEvent e)

l.setText("mouse clicked(# of clicks:"+e.getClickCount());

}
3. Write a program to demonstrate the use o f mouse Dragged and mouseMoved method of
MouseMotionListener.

Ans.

Import java.awt.*;
Import java.awt.event.*;
Import java.applet.*;
/*<applet code=”MouseMotionEventTest.class” height=300 width=300></applet>*/

Public class MouseMotionEventTest extends implements MouseMotionListener


{
String msg=””;
Int mouseX=0,mouseY=0;
Public void init()
{
addMouseMOtionListener(this);
}
Public void mouseDragged(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY(); msg=””;
showStatus(“Dragging mouse at”+mouseX+”,”+mouseY”);

repaint();
}
Public void mouseMoved(MouseEvent me)
{
showStatus(“Moving mouse at”+me.getX()+”,”+me.getY());

}
Public void paint (Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}

Output:

Practical Related Questions

1. List various method of MouseListener and MouseMotionListener

Ans. There are five types of event that MouseListener can generate:

I. Void mouseReleased(MouseEvent e): Mouse key is released

II. Void mouseClicked(MouseEvent e): Mouse key is released

III. Void mouseExited(MouseEvent e): Mouse exited the component

IV. Void mouseEnterd(MouseEvent e): Mouse eneterd the component

V. Void mousepressed(MouseEvent e): Mouse key is pressed

There are two types of events that MOuseMOtionListener can generate.


1. Void MouseDragged(MouseEvent e): Invoked when a mouse button is pressed in the
component and dragged. Events are passed until the user releases the mouse button.

2. Void mouseMoved(MouseEvent e):Invoked when the mouse cursor is moved from one
point to another within the component, without pressing any mouse buttons.
2. Do all componets generate the MouseEvent

Ans “YES” all components generate mouse event in java.

3. Write the steps to obtain the coordinate of MouseClick.

Ans. The coordinates of the mouse when ever a click takes place can be found by detecting the
click event with an event listener and finding the event’s x and y position.

4. Write the steps to register for MouseEvents

Ans. A MouseEvent object is also passed to every MOuseMotionListener or


MouseMotionAdpter object which is registered to receive mouse motion events using the
component’s addMouseMotionListener method.

Marks

Dated signature of
arks Obtained Teacher
Process Product
Related(35) Related(15) Total(50)

`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet
7
Name of Student Swati Padhi
Roll No. 20203C0038
Class CO5I-C
Experiment No 12
Title of Experiment Write a program to demonstrate the use of JTextField and
JPasswordField using Listener Interface.

Experiment-12

1. Write a program using JPasswordField and JTextField to demonstrate the use of user authentication.
Ans.
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Public class A extends JFrame implements ActionListener
{
JButton nutton;
JTextField jtf;
JPasswodField jpf;
JLabel j1, j2;
Public A()
{
setVisible(true);
setTitle(“MyFrame”);
setSize(300,300); setLayout(new FlowLayout());
j1=new
JLabel(“User Name”); j2=new
JLabel(“Password”); jtf= new
JTextField(15); button = new
JButton(“Submit”); add(j1);
add(jtf); add(j2); add(jpf);
add(button);
button.addActionListener(this);
}
Public void actionPerformed(ActionEvent e)
{
String s1,s2;
S1= jtf.getText();
S2=jpf.getText();
If(s1.equals(“Prakash Koyander””)&&(s2.equals(“123”)))
{
JOptionPane.showMessageDialog(this, “Authenticated User”);
}
Else
{
JOprionPane.show MessageDialog(this, “Unauthorized User”);
}
Pubic static void main(String[] args)
{
A frame2 = new A();
}
}
Output:

2. Write a program using JTextField to perform the addition of two numbers.


Ans.
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Public class A extends JFrame implements ActionLIstener
{
JButton button;
JTextField jtf1, jtf2, jtf3;
JLabel j1, j2,j3;
Public A()
{
setVisible(true);
setTitle(“MyFrame”);
setSize(300,300); setLayout.(new FlowLayout());
j1=new
JLabel(“First NUmber”); j2=new
JLabel(“Second Number”); jtf1=
new JTextField(15); jtf2=new
JTextField(15):
jtf3=new JTextField(15); button =
new JButton(“Addition”); add(j1);
add(jtf1); add(j2); add(jtf2);
add(button); add(j3); add(jtf3);
button.addActionListener(this);
}
Public void actionPerformed(ActionEvent e)
{
Int n1, n2, n3; n1
=Integer.parseInt(jtf1.getText());
n2=Integer.parseInt(jtf.getText());
n3=n1+n2;
jtf3.setText(Integer.toString(n3));
}
Public static void main(String[] args)
{
A frame2 = new A():
}
}
Output :

3. Write a program using JPassworField to accept password from user and if the length is less
tha 6 characters then error message should be displayed “Password length must be > 6
characters”. Ans.

import java.awt.BorderLayout; import


java.awt.event.ActionEvent; import
java.awt.event.ActionListener; import
java.awt.event.WindowAdapter; import
java.awt.event.WindowEvent; import
javax.swing.BorderFactory; import
javax.swing.JFrame;

import javax.swing.JLabel; import javax.swing.JOptionPane;


import
javax.swing.JPanel;
import javax.swing.JPasswordField; public class
JTextFieldDemo

public static void main(String[] args) { final JFrame


frame = new JFrame();

JLabel l1 = new JLabel("Enter the password: "); JPasswordField a


= new JPasswordField(10); a.setEchoChar('*');

a.addActionListener(new ActionListener() { public


void actionPerformed(ActionEvent e) {

JPasswordField input = (JPasswordField) e.getSource()

char[] password = input.getPassword(); if


(password.length < 6) {

JOptionPane.showMessageDialog(frame,"Password length must be > 6


characters.");

});

JPanel panel = new JPanel(new BorderLayout());


panel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20
)); panel.add(l1, BorderLayout.WEST);

panel.add(a, BorderLayout.CENTER); frame.setContentPane(panel);


frame.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e) { System.exit(0);

});

frame.pack();
frame.setVisible(tru e);
}

}
Output:

Practical Related Questions

1. Write the use of setEchoChar() method which suitable example.


Ans. Once a password text field is created, setEchoChar(char) method can be used to
obsecure input with the specified character.
2. Write the advantages of using JPasswordField over JTextField
Ans. JPasswordField: The JPasswordField allows the user to enter the input text in the form
of password characters.
JTextField: It allows the user to input the single line of text in JTextField component.

3. Which component can be used to accept the multiline input from user.

Ans. The JTextArea class provides a component that displauys multiple lines of text and optionally
allows the user to edit the text. If you need to obtain only one line of input from the user, you
should use a text field.

MARKS

Dated signature of
arks Obtained Teacher
Process Product
Related(35) Related(15) Total(50)
mm

`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet
7
Name of Student Swati Padhi
Roll No. 20203C0038
Class CO5I-C
Experiment No 14
Title of Experiment Write a program to demonstrate the use of InetAddress class and its
factory methods.

Experiment-14

1. Develop a program using InetAddress class to retrieve IP


Address of computer when hostname is entered by the user
Ans import java.net.*; import
java.util.*; public class
InetAddressDemo

public static void main(String[] args){ String str;

Scanner input = new Scanner(System.in);


System.out.print("\n Enter host name: ");
str = input.nextLine(); try {

InetAddress address = InetAddress.getByName(str);


System.out.println("IP address: " + address.getHostAddress());

catch (UnknownHostException ex) {


System.out.println("Not found" + str);

}
Output:

Practical Related Questions:

1. Write any four differences between IPv4 and IPv6

Ans
IP v4 IP v6

1. IPv4 protocol has address length of 1. On other hand IPv6 has 128-bit
32-bit represented in decimal format address length represented in
and it supports Manual and DHCP hexadecimal format and supports
configuration. Auto-configuration and
renumbering configuration.
2. IPv4 is being used as less 2. IPv6 has its inbuilt security
secure protocol as its security feature named as IPSEC (Internet
section is dependent on Protocol Security) which provide
application i.e., it is proportional additional security feature along
to the security that is provided or with the security provided or
implemented at application level. implemented at application
level.

3. In IPv4 fragmentation is 3. In IPv6 the fragmentation is


performed by both Sender performed only by sender routers.
and Forwarding routers.

4. In IPv4 Encryption and 4. In IPv6 both Encryption and

Authentication facility not provided. Authentication facility are available.

2. Write the use of getByName() and getAllByName() methods.

Ans getByName(): getByName() method returns the IP Address of the host


specified. If the host is a literal IP address, then only its validity is checked.
Syntax: public static InetAddress getByName(String host) getAllByName():
getAllByName() method returns an array of IP addresses for the given
host.

Syntax: public static InetAddress[] getAllByName(String host)

3. Write the steps to assign IP Address to your machine.

Ans Step 1: Click Start Menu > Control Panel > Network and Sharing Center or
Network and Internet > Network and Sharing Center.
Step 2: Click Change adapter settings.

Step 3: Right-click on Wi-Fi or Local Area Connection.

Step 4: Click Properties.

Step 5: Select Internet Protocol Version 4 (TCP/IPv4).

Step 6: Click Properties.

Step 7: Select Use the following IP address.

Step 8: Enter the IP address, Subnet mask, Default gateway, and DNS
server.

Step 9: Click OK.

MARKS
Dated signature of
arks Obtained Teacher
Process Product
Related(35) Related(15) Total(50)
`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet
6
Name of Student Swati Padhi
Roll No. 20203C0038
Class CO5I-C
Experiment No 15
Title of Experiment Write a program to demonstrate the use of URL and URLConnection class
and its methods

Experiment-15 Exercise:

1. Write a program using URL class to retrieve the host,protocol,port and file of
URL http://www.msbte.org.in

Ans

import java.net.*; public


class Demo{ public static void

main(String[] args){ try{

URL url=new URL("http://www.msbte.org.in");


System.out.println("Host Name: "+url.getHost());

System.out.println("Protocol: "+url.getProtocol()); System.out.println("Port


Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());

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

Output:

2. Write a program using URL and URLConnection class to retrieve the date,
content type, content length information of any entered URL.

Ans
import java.net.*;

import java.io.*; import java.util.Date; class A

public static void main(String args[]) throws Exception

{ int

a;

URL b = new
URL("https://www.esakal.com/");
URLConnection hpCon = b.openConnection();
long d = hpCon.getDate(); if(d==0)

System.out.println("No date information."); else

System.out.println("Date: " + new Date(d));


System.out.println("Content-Type: " + hpCon.getContentType()); d
= hpCon.getExpiration(); if(d==0)

System.out.println("No expiration information."); else System.out.println("Expires:


" + new Date(d)); d = hpCon.getLastModified(); if(d==0)

System.out.println("No last-modified information."); else


System.out.println("Last-Modified: " + new Date(d)); int
len = hpCon.getContentLength(); if(len == -1)

System.out.println("Content length unavailable."); else


System.out.println("Content-Length: " + len);

}}

Output:

Practical Related Questions:

1. Write the use of openConnection() method of URLConnection class.

Ans The openConnection() method returns the object of URLConnection class.

Syntax: public URLConnection openConnection () throws IOException{}

2. Write the name of exception that can be thrown by URL class.

Ans MalformedURLException is the name of exception that can be thrown by URL


class.

3. Name the package in which URL class is defined.

Ans java.net is the package in which URL class is defined.

Marks
Dated signature of
Marks Obtained
Teacher
Process Product
Related(35) Related(15) Total(50)
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet

`
6
Name of Student Swati Padhi
Roll No. 20203C0038
Class CO5I-C
Experiment No 18
Title of Experiment Write a program to demonstrate the use of URL and URLConnection class
and its methods

Experiment-18

Exercise

1. Develop a program to create employee table in database having two columns


“emp_id” and “emp_name”. Ans

import java.sql.*; class JDBCDemo


{

public static void main(String args[]) { try


{

Class.forName("com.mysql.jdbc.Driver");
Connection con =

DriverManager.getConnection("jdbc:mysql://localhost:3306/emp","root", "");
Statement s = con.createStatement();

s.execute("create table employee ( emp_id varchar(20),emp_name varchar(20))");

s.execute("insert into employee values('19202C1005','Aidihim')");


s.execute("select * from employee");

ResultSet rs = s.getResultSet(); if
(rs != null) while ( rs.next() )

System.out.println("Employee ID: " + rs.getString(1));


System.out.println("Employee Name: " + rs.getString(2));
}

s.close(); con.close();

}
catch (Exception e)
{

System.out.println(e);

OUTPUT:

On Next page
1. Develop a program to display the name and roll_no of students from

“student table” having percentage > 70 .


Ans
import java.sql.*; class
marks {

public static void main(String args[]) { try


{

Class.forName("com.mysql.jdbc.Driver");
Connection con =

DriverManager.getConnection("jdbc:mysql://localhost:3306/marks","root","");
Statement s = con.createStatement();
s.execute("create table student ( stu_id varchar(10),stu_name varchar(20),marks
Integer(3))");

s.execute("insert into student values('142','Aidihim',74)");


s.execute("insert into student values('131','Adi',69)");
s.execute("select * from student where marks > 70");
ResultSet rs = s.getResultSet(); if (rs != null) while ( rs.next()
){

System.out.println("Student ID: " + rs.getString(1) );


System.out.println("Student Name: " + rs.getString(2) );
System.out.println("Student Marks: " + rs.getInt(3) );

s.close(); con.close();

catch (Exception e){


System.out.println(e);

}
Output:
On next Page
`

Practical Related Questions

1. List the advantages of JDBC over ODBC


Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet
Ans a) JDBC

b) JDBC create XML structure of data from database automatically.

c) In JDBC no content conversion is required.

d) JDBC support query and stored procedure.

e) JDBC support modules.

2. Write the Use of Class.forName()

Ans Class.forName() method returns the class object associated with the class
object associated with the class or interface passed as first parameter.

3. Write the steps to establish the DSN oriented connection and DSN Less
connection.

Ans Steps for DSN oriented connection:

1. connect to a DSN

2. Write SQL statement that will query the database

3. Fetch the data from the database

4. Close the connection

Steps for DSN Less connection:

1. Create an instance of the connection object

2. Define connection string, specify database driver

3. Write the SQL statement that will query the database

`
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet
4.

5. Close the connection and record set objects freeing up resources


Marks

Dated signature of
arks Obtained Teacher
Process Product
Related(35) Related(15) Total(50)

8
Name of Student Swati Padhi
Roll No. 20203C0038
Class CO5I-C
Experiment No 22
Title of Experiment Write a Servlet program to send username and password using HTML
forms and authenticate the user.

Experiment-22

Exercise
1. Develop servlet program to retrieve data from List and Radio Button using
HTML Forms. Ans
index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Welcome
<br>
<br>
<form action="Form">
Email : <input type="text" name="email"> <br>

User Name: <input type="text" name="uname"> <br>


Password: <input type="password" name="pass"> <br>
Gender : <input type="radio" name="gender" value="male" checked>
Male <input type="radio" name="gender" value="female">
Female <br>

Course: <select name="Course">

<option name="Course">Advanced Java </option>

<option name="Course">Javascript</option>

</select>

<input type="submit" value="Submit"> <input type="reset">

</form>

</body>

</html>

Form.java

import java.io.IOException; import


java.io.PrintWriter; import

javax.servlet.ServletException; import

javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
@WebServlet("/MyForm") public

class Form extends HttpServlet

{
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException

{
String em = request.getParameter("email");
String un = request.getParameter("uname");
String pa = request.getParameter("pass"); String
ge = request.getParameter("gender"); String co =
request.getParameter("Course");
response.setContentType("text/html");
PrintWriter pw=response.getWriter();

pw.write("<h2> Following data received sucessfully.. <h2> <br>");


pw.write("<h3> Email: "+ em +" </h3>");

pw.write("<h3> User name: "+ un +" </h3>");


pw.write("<h3> Password: "+ pa +" </h3>");
pw.write("<h3> Gender: "+ ge +" </h3>"); pw.write("<h3> Course:
"+ co +" </h3> "); pw.write("</h3>");

Output:
2. Develop a program to receive student subject marks through HTML forms
TextField and send the response as passed or Failed in Examination.

Ans

Form.java

import java.io.IOException; import


java.io.PrintWriter;

import javax.servlet.ServletException; import


javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest; import


javax.servlet.http.HttpServletResponse; public class logs
extends HttpServlet

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


IOException, ServletException

{
PrintWriter pw = res.getWriter(); res.setContentType("text/html");
String name = req.getParameter("name"); String
marks = req.getParameter("marks"); int m =
Integer.parseInt(marks); if(m>=80)
{ pw.println("Passed");

else{ pw.println("Failed");

public void doPost(HttpServletRequest req,HttpServletResponse res) throws


IOException, ServletException
{

doGet(req,res);

index.html

<!DOCTYPE html>

<html>

<body>

<form action="Form">
Enter the name:<input type ="text" name ="name">
Enter the marks:<input type ="text" name ="marks">
<input type="submit" value="Enter">

</select>

</form>

</body>

</html>

Output:

Practical Related Questions

1. List the types of servlet and default port for there services.

Ans There are two main servlet types, generic and HTTP:
1) Generic servlets

a) Generic servlets extend javax.servlet.GenericServlet.

b) Generic servlets are protocol independent. They contain no inherent


HTTP support or any other transport protocol.

c) Default port number is 8080.

2) HTTP servlets

a) Generic servlets extend javax.servlet.HttpServlet.

b) Generic servlets have built-in HTTP protocol support and are more
useful in a Sun Java System Web Server environment.

Default port number is 8080.

2. List the difference between doGet() and doPost() method of servlet.

Ans

GET(doGet()) POST(doPost())

HTTP Request The request contains Along with request line


only the request line and header it also

and the HTTP header. contains HTTP body.


Parameter Passing The form elements are The form elements are
passed to the server by passed in the body of
appealing at the end of the HTTP request.
the URL.

Size The parameter data is Can send huge amount


limited (the limit of data to the server.
depends on the
container)

Usage Generally used to fetch Generally used to


some information from process the sent data.
the host.

2. Explain ServletConfig and ServletContext.

Ans ServletConfig: ServletConfig is an object containing some initial parameters


or configuration information created by Servlet Container and passed to
the servlet during initialization.

ServletContext: ServletContext is
the object created by Servlet
Container to share initial parameters
or configuration information to the
whole application.

3. Explain ServletInputStream Class and ServletOutputStream Class with


methods.
Ans ServletInputStream class provides stream to read binary data such as image
etc. from the request object. It is an abstract class.

The getInputStream() method of ServletRequest interface returns the instance of


ServletInputStream class.

There are only one method defined in the ServletInputStream class.

1. int readLine(byte[] b, int off, int len) it reads the input stream.

ServletOutputStream class provides a stream to write binary data into the


response. It is an abstract class.

The getOutputStream() method of ServletResponse interface returns the instance


of ServletOutputStream class.

The ServletOutputStream class provides print() and println() methods that are
overloaded.

1. void print(boolean b){}

2. void print(char c){}

3. void print(int i){}

4. void print(long l){}

5. void print(float f){}

6. void print(double d){}

7. void print(String s){}

8. void println{}

9. void println(boolean b){}


10.void println(char c){}
11.void println(int i){}
12.void println(long l){}
13.void println(float f){}
14.void println(double d){}
15.void println(String s){}

Marks

Dated signature of
Marks Obtained Teacher
Process
Related(35) Product Related(15) Total(50)
Program: Computer Engineering (NBA Accredited)
Course - Advanced Java Programming (22515)
Practical Answer Sheet

`
12

You might also like