0% found this document useful (0 votes)
13 views11 pages

Java Cie 2

Uploaded by

Ayaan Nehal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views11 pages

Java Cie 2

Uploaded by

Ayaan Nehal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

SAQ

Q1,Difference between array list and Vector class


Ans:
Vector Array List
Vector is synchronized. Array List is not synchronized.
Vector increments 100% means doubles Array List increments 50% of current
the array size if the total number of array size if the number of elements
elements exceeds than its capacity. exceeds from its capacity.
Vector is a legacy class. Array List is not a legacy class.
Vector is slow because it is synchronized Array List is fast because it is non-
synchronized.
A Vector can use the Iterator interface or Array List uses the Iterator interface to
Enumeration interface to traverse the traverse the elements.
elements.
Q2, Draw the hierarchy of collection interface.
Ans:

Q3, write a java program using Timer class


Ans:import java.util.Timer;
import java.util.TimerTask;
class Helper extends TimerTask
{
public static int i = 0;
public void run()
{
System.out.println("Timer ran " + ++i);
}
}
public class Test
{
public static void main(String[] args)
{
Timer timer = new Timer();
TimerTask task = new Helper();
timer.schedule(task, 2000, 5000);
}
}
Output:
Timer ran 1
Timer ran 2
Timer ran 3
Timer ran 4
Timer ran 5
Q4, Define event listeners?
Ans: Listeners: Listeners are used for handling the events generated from the
source. Each of these listeners represents interfaces that are responsible for handling
events.
To perform Event Handling, we need to register the source with the listener.
Q5,write a simple java applet displaying HELLO WORLD?
Ans: import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!", 20, 20);
}
}
<html>
<head>
<title>Hello World Applet</title>
</head>
<body>
<applet code="HelloWorldApplet.class" width="200" height="100">
</applet>
</body>
</html>
Q6,How is applet differ from stand alone applications
Ans: Applet:
Runs in a web browser or applet viewer
Sandbox environment with restricted access to system resources
Limited security privileges
Embedded GUI within a web page
Deployed as a .class or JAR file
Lifecycle managed by browser or applet viewer
Standalone Application:
Runs as a separate process
Full access to system resources
No security restrictions
Standalone GUI
Deployed as an executable file or JAR file
Lifecycle managed by operating system

Q7, difference between J Text Field and J Text Area


Ans:
J Text Field J Text Area
A single-line text input field A multi-line text input field
Used for entering short text strings, Used for entering larger blocks of
such as names, addresses, or phone text, such as comments,
numbers descriptions, or articles

Has a fixed width, but can be resized Can be resized to display multiple
lines of text
Does not support multiple lines of Supports multiple lines of text, with
text line wrapping and scrolling
Supports basic editing features, such Supports advanced editing features,
as cut, copy, and paste such as text formatting, font styles,
and colors
Can be used for password fields, Can be used for displaying read-only
with asterisks (*) or dots (·) masking text, such as help messages or
the input instructions

Q8,List out the features of Swing in Java?


Ans: Swing is a set of GUI components for Java. It provides a rich set of features such as:
--Lightweight components
--Pluggable look and feel
--Layout managers
--Accessibility API
--Internationalization and localization support

LAQ
01,BUILD a Java program to copy the content of one file to another file?
Ans:
import java.io.*;

public class FileCopier {


public static void main(String[] args) {

String sourceFile = "source.txt";

String destinationFile = "destination.txt";

try {

FileInputStream fis = new FileInputStream(sourceFile);

FileOutputStream fos = new


FileOutputStream(destinationFile);

byte[] buffer = new byte[1024];

int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fis.close();
fos.close();

System.out.println("File copied successfully!");


} catch (IOException e) {
System.err.println("Error copying file: " +
e.getMessage());
}
}
}

Q3, write a java program to illustrate the use of string tokenizer


Ans:
import java.util.Scanner;
import java.util.StringTokenizer;
// class to accept integers and find the sum using StringTokenizer class public class StringToken
{
public static void main( String args[] )
{
// accept the values at run time
Scanner scanner = new Scanner( System.in );
System.out.println( "Enter sequence of integers (with space betwen them) and press Enter" );
// getting the count of integers that were entered String digit = scanner.nextLine();
// creating object of StringTokenizer class
StringTokenizer tokens = new StringTokenizer( digit); int i=0,dig=0,sum=0,x;
// loop to determine the tokens and find the sum
while ( tokens.hasMoreTokens() )
{
String s=tokens.nextToken(); dig=Integer.parseInt(s); System.out.print(dig+""); sum=sum+dig;
}
System.out.println(); System.out.println( "sum is "+sum );
}
}

Q4,what is serialization write a program to demonstrate serialization concept?


Ans: Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly
used in Hibernate, RMI, JPA, EJB and JMS technologies.

import java.io.*;
class Studentinfo implements Serializable {
String name;
int rid;
static String contact;
Studentinfo(String n, int r, String c) {
this.name = n;
this.rid = r;
Studentinfo.contact = c;
}
}
public class SerializableDemo {
public static void main(String args[]) throws Exception {
Studentinfo si = new Studentinfo("Abhi", 104, "110044");
System.out.println("Serialization started");
FileOutputStream fos = new FileOutputStream("student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(si);
System.out.println("Serialization ended");
System.out.println("Deserialization started");
FileInputStream fis = new FileInputStream("student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
si = (Studentinfo) ois.readObject();
System.out.println("Deserialization ended");
System.out.println("Student object details:");
System.out.println(si.name);
System.out.println(si.rid);
System.out.println(Studentinfo.contact);
}
}
Output:
Serialization started
Serialization ended
Deserialization started
Deserialization ended
Student object details:
Abhi
104
110044
Q5, create an application program in java to demonstrate mouse event, handling key
events ?
Ans: mouse:
import java.awt.*;
importjava.awt.event.*;
importjava.applet.*;
/*
<applet code="Mouse" width=300 height=100>
</applet>
*/
public class Mouse extends Applet implements MouseListener, MouseMotionListener
{
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
public void mousePressed(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
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);
}
}

=>handling key events:


import java.awt.*;
importjava.awt.event.*;
importjava.applet.*;
/*
<applet code="Key" width=300 height=100>
</applet>
*/
public class Key extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEventke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEventke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEventke)
{
msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}
Q6, Write a Java program that connects to the database using JDBC type 1 driver

Ans:
import java.sql.*; class Create
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con;
con=DriverManager.getConnection("jdbc:odbc:csec”,”system”,”mlrit”) Statement
stmt=con.createStatement();
String sql = "CREATE TABLE REGISTRATION " + "(id INTEGER not NULL, " +
" first VARCHAR(255), " + " last VARCHAR(255), " + " age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
con.close();

}//try
catch(Exception e)
{
e.printStackTrace();
}
}
}
Q7, Difference between generic servlet and http servlet
Ans:
Generic Servlet HttpServlet

Location Works with multiple protocols (HTTP, Specifically designed for handling
FTP, SMTP, etc.). HTTP protocol.
Functionality Generic, protocol-independent Extends Generic Servlet to handle
servlet implementation. HTTP-specific tasks.
Methods Implements the Extends Generic Servlet and adds
javax.servlet.Servlet interface. HTTP-specific methods.
Requests Handles requests from various Handles specifically HTTP requests
protocols. and related tasks.
HttpServletRequest Not available. Provides additional methods for
handling HTTP requests.
HttpServletResponse Not available. Provides additional functionality
for HTTP responses.
Common Usage Used for servlets handling non- Used for servlets handling HTTP
HTTP protocols. requests and responses.

Q8, Explain the following classes in detail with an example program


JLabel, ImageIcon, JTextField, JScrollPane, JList, JComboBox.
Ans:

1.JLabel: JLabel is a class of Java Swing. It is used to display a short string or an image icon. JLabel can display
text, image or both. JLabel is only a display of text or image and it cannot get focus. JLabel is inactive to input
events such as mouse focus or keyboard focus.
2.ImageIcon: ImageIcon is a class of Java Swing. It is used to display an image in a GUI application.
ImageIcon can be created from an image file or from an array of bytes.

3.JTextField: JTextField is a class of Java Swing. It is used to create a single-line text field for accepting user input.

4.JScrollPane: JScrollPane is a class of Java Swing. It is used to create a scrollable view of a component that is
larger than the visible area.

5.JList: JList is a class of Java Swing. It is used to create a list of items that can be selected by the user.

6.JComboBox: JComboBox is a class of Java Swing. It is used to create a drop-down list of items that can be
selected by the user

Example:
import javax.swing.*;
import java.awt.*;

public class SwingComponentsExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Components Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a panel to hold all the components


JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// Add a label with an image
JLabel label = new JLabel("Hello, World!", new ImageIcon("image.jpg"), JLabel.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 24));
panel.add(label, BorderLayout.NORTH);

// Add a text field


JTextField field = new JTextField("Enter your name", 20);
panel.add(field, BorderLayout.CENTER);

// Add a scroll pane with a text area


JTextArea area = new JTextArea(10, 20);
area.setText("This is a large text area that requires scrolling.");
JScrollPane scrollPane = new JScrollPane(area);
panel.add(scrollPane, BorderLayout.EAST);

// Add a list
String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};
JList<String> list = new JList<>(items);
panel.add(new JScrollPane(list), BorderLayout.WEST);

// Add a combo box


String[] options = {"Option 1", "Option 2", "Option 3"};
JComboBox<String> comboBox = new JComboBox<>(options);
panel.add(comboBox, BorderLayout.SOUTH);

// Add the panel to the frame


frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}

You might also like