JAVA Notes Unit 5 Print
JAVA Notes Unit 5 Print
Layout Managers
import java.awt.*;
// Frame settings
frame.setSize(450, 300);
frame.setVisible(true);
}
}
2. GridLayout
Feature Description
All components are given equal size regardless
Equal Size Cells
of their content.
Fills Left to Right, Top to Bottom Components are placed row by row.
Constructor of GridLayout
import java.awt.*;
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
frame.setSize(400, 300);
frame.setVisible(true);
}
}
3. FlowLayout
Feature Description
Alignment Left, center (default), or right alignment.
Automatically wraps components to a new line when
Component Wrapping
space runs out.
You can set horizontal and vertical gaps between
Spacing
components.
Flexibility Easy to use and perfect for small layouts.
Constructors of FlowLayout:
FlowLayout()
FlowLayout(int alignment)
import java.awt.*;
// Frame settings
frame.setSize(500, 300);
frame.setVisible(true);
}
}
4. CardLayout
Feature Description
Stacked Layout Only one component (card) is visible at a time.
Allows switching between cards using .next(),
Navigation Methods
.previous(), .show(), etc.
Useful for multi-step forms, tutorials, and tab-like
Best for Wizards/Forms
interfaces.
Flexible Can contain multiple panels or other components.
Constructor of CardLayout
CardLayout()
CardLayout(int hgap, int vgap)
import java.awt.*;
import java.awt.event.*;
// Frame Settings
frame.setSize(450, 300);
frame.setVisible(true);
}
}
5. GridBagLayout
Feature Description
Flexible Layout Allows rows and columns of different sizes.
Precise Positioning Components can span multiple rows/columns.
Weighting System Components can grow/shrink dynamically.
Constraints-Based Uses GridBagConstraints to control placement.
Spacing Control Allows setting gaps between components.
Constructor of GridBagLayout
GridBagLayout()
GridBagConstraints
Constraint Description
gridx, gridy Specifies the row and column position.
gridwidth, gridheight Determines how many columns/rows a component spans.
weightx, weighty Controls how much space a component gets when resizing.
Defines the component's alignment (e.g., CENTER, EAST,
anchor
WEST).
Determines how the component should expand
fill
(HORIZONTAL, VERTICAL, BOTH).
insets Specifies padding around the component.
import java.awt.*;
import java.awt.event.*;
// Buttons
Button loginButton = new Button("Login");
Button cancelButton = new Button("Cancel");
gbc.gridx = 0; gbc.gridy = 0;
frame.add(uname, gbc);
gbc.gridx = 1; gbc.gridy = 0;
frame.add(user, gbc);
gbc.gridx = 0; gbc.gridy = 1;
frame.add(pwd, gbc);
gbc.gridx = 1; gbc.gridy = 1;
frame.add(password, gbc);
gbc.gridwidth = 2;
gbc.anchor = GridBagConstraints.CENTER; // Centering buttons
frame.add(loginButton, gbc);
gbc.gridx = 1; gbc.gridy = 2;
frame.add(cancelButton, gbc);
// Frame settings
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Applets PART-2
Concepts of Applets, life cycle of an applet, creating applets, passing parameters to
applets.
Applets are small Java programs that can be embedded in web pages and run
in Java-enabled web browser or an appletviewer tool.
Although applets are now considered outdated due to security concerns and lack
of browser support.
Hierarchy of Applet
java.applet.Applet class
Lifecycle of an Applet
The applet life cycle can be defined as the process of how the object is created,
started, stopped, and destroyed during the entire execution of its application. It
basically has five core methods namely init(), start(), stop(), paint() and
destroy().These methods are invoked by the browser to execute.
The lifecycle of an applet is managed by the browser (or appletviewer tool) and
involves the following methods:
Method Description
Called once when the applet is first loaded. Initialization tasks
init()
like setting up UI components are done here.
Called after init() and also each time the applet is restarted
start()
(e.g., when the user revisits the page).
Called to redraw the content of the applet. All GUI drawing
paint(Graphics g)
happens here.
Called when the user leaves the web page or switches to
stop()
another tab.
Called when the applet is being removed completely from
destroy()
memory. Cleanup is done here.
import java.applet.Applet;
import java.awt.*;
import java.util.Date;
/*
<applet code="AppletLifeCycle" width=300 height=200>
<param name="greeting" value="Welcome to Java Applet">
<param name="author" value="VJIT">
</applet>
*/
public class AppletLifeCycle extends Applet
{
// Instance variables to store parameter values
private String greetingMessage;
private String author;
if (greetingMessage == null)
{
greetingMessage = "Hello, this is a default greeting!";
}
if (author == null)
{
author = "Unknown Author";
}
System.out.println("Applet Initialized");
}
// Called when the applet is stopped (i.e., the user navigates away)
@Override
public void stop()
{
System.out.println("Applet Stopped");
}
In Browser
In Command Prompt
JDBC (Java Database Connectivity) is a Java API that enables Java programs
to connect to and interact with databases (such as MySQL, Oracle, SQL Server,
PostgreSQL, etc.).
We can use JDBC API to access tabular data stored in any relational database.
By the help of JDBC API, we can perform CRUD(Create, Read, Update, Delete)
operations from the database. It is like Open Database Connectivity (ODBC) provided
by Microsoft.
JDBC Architecture
JDBC Drivers
JDBC Driver is a software component that enables java application to interact with
the database.
Advantages:
Easy to use with ODBC-supported databases.
Disadvantages:
Platform dependent (requires native ODBC driver).
Performance is poor.
Deprecated in Java 8 and removed in later versions.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not written
entirely in java.
Advantages:
Disadvantages:
The Network Protocol Driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully
written in java.
Advantages:
Platform independent.
No Client-Side DB driver needed.
Good for Intranet-Based Applications.
Disadvantages:
JDBC calls → Direct communication with the database using Java Sockets
No Native Libraries or Middleware required
Advantages:
Pure Java → Platform Independent.
Best performance.
Most commonly used today (e.g., MySQL Connector/J, Oracle Thin Driver).
Disadvantages:
One driver per database type.
Example Driver Class:
Class.forName("com.mysql.cj.jdbc.Driver"); // For MySQL 8+
Class Description
Manages the set of available JDBC drivers. Establishes a
DriverManager
connection with a database using a driver.
Interfaces Description
Represents an active connection to a database. Used to create
Connection
statements and manage transactions.
Used to execute static SQL queries (e.g., SELECT * FROM
Statement
table).
Represents the result of an SQL SELECT query. Allows data
ResultSet
navigation and extraction.
Precompiled SQL statement (used for dynamic queries with
PreparedStatement
parameters)
SQLException Handles SQL errors
1. DriverManager Class
Method Description
Attempts to establish a
getConnection(String url) connection using the
provided URL.
Example:
2. Connection Interface
3. Statement Interface
4. PreparedStatement Interface
5. ResultSet Interface
Method Description
Moves the cursor to the next row
next()
(returns false if no more rows).
getString(String columnLabel) Retrieves String data from a column.
getInt(String columnLabel) Retrieves int data from a column.
getDouble(String columnLabel) Retrieves double data.
wasNull() Checks if last column read was SQL NULL.
close() Closes the ResultSet.
6. SQLException Class
Method Description
getMessage() Returns the error message.
getErrorCode() Returns vendor-specific error code.
getSQLState() Returns the SQLState string.
printStackTrace() Prints the exception trace.
Class.forName("com.mysql.jdbc.Driver");
while (rs.next())
{
System.out.println(rs.getString("name"));
}
con.close();
// This code is for establishing connection with MySQL database and retrieving data
*7. close
*/
import java.io.*;
import java.sql.*;
class create
Statement st = con.createStatement();
st.execute(sql);
System.out.println("Connection Closed....");
Output:
import java.sql.*;
class StudentInsertionApplication
{
public static void main(String[] args) throws ClassNotFoundException,SQLException
{
String url= "jdbc:mysql://localhost:3306/vjit"; // Database details
String username = "root"; // MySQL credentials
String password = "vjit";
Class.forName("com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Established successfully");
Statement st = con.createStatement();
int c = st.executeUpdate("insert into students values(6703,'Rahul','HYD',20)");
System.out.println(c + "\t Student Record inserted successfully");
st.close();
con.close();
}
}
Output:
import java.sql.*;
import java.util.*;
class StudentDeleteApplication
{
public static void main (String[]args) throws ClassNotFoundException, SQLException
{
String url= "jdbc:mysql://localhost:3306/vjit"; // Database details
String username = "root"; // MySQL credentials
String password = "vjit";
Class.forName("com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Established successfully");
Statement st = con.createStatement();
Scanner sc = new Scanner(System.in);
System.out.println("ENTER STUDENT NUMBER");
int rno = sc.nextInt();
import java.sql.*;
import java.util.*;
class StudentsDetails
{
public static void main (String[]args) throws ClassNotFoundException, SQLException
{
String url= "jdbc:mysql://localhost:3306/vjit"; // Database details
String username = "root"; // MySQL credentials
String password = "vjit";
Class.forName("com.mysql.cj.jdbc.Driver"); // Driver name
Connection con = DriverManager.getConnection(url, username, password);
System.out.println("Connection Established successfully");
Statement st = con.createStatement();
System.out.println("\n\nStudent Details: ");
System.out.println("----------------------");
ResultSet rs = st.executeQuery("select * from students");
while(rs.next())
{
System.out.println("Roll No: " + rs.getInt(1));
System.out.println("First Name: " + rs.getString(2));
Output: