0% found this document useful (0 votes)
20 views26 pages

Advanced Java Lab Practical Record

Uploaded by

surendarrs064
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)
20 views26 pages

Advanced Java Lab Practical Record

Uploaded by

surendarrs064
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

SRI KRISHNA ARTS AND SCIENCE

COLLEGE An Autonomous College Affiliated to


Bharathiar University Coimbatore - 641 008.

DEPARTMENT OF COMPUTER SCIENCE ADVANCED JAVA

LAB

PRACTICAL RECORD
NAME:
ROLL NUMBER:

CLASS:

PROGRAMME:

COURSE CODE:
SRI KRISHNA ARTS AND SCIENCE
COLLEGE An Autonomous College Affiliated to
Bharathiar University Coimbatore - 641 008.
Certified bonafide record of work done by during the year 2022 – 2023.

Staff In-charge Head of the department

Submitted to Sri Krishna Arts & Science College (Autonomous) End Semester examinations held on

Internal Examiner External Examiner


DECLARATION

I hereby declare that this record of observation is based on the experiments carried out and recorded by me
during
the laboratory classes of “ ” conducted by SRI KRISHNA ARTS AND SCIENCE COLLEGE, Coimbatore-
641 008.

Date:
Name of the student : Signature of the student Roll Number :
Countersigned by staff
CONTENT
[Link]. Date Title of the Experiment Page No Sign

1 Lambda Expression

2 Linked List Class

3 Reduce and Filter

4 TCP/IP Communication

5 Form using Labels, Textboxes and


Button Controls

6 JMenu and JMenuItem

7 Java Beans

8 Database Connectivity

9 Servlet application using Cookies


and Sessions

10 JSP Tags

11 JSP Custom Tags

12 Spring Application

Ex: 1 Lambda

interface NumericTest{
boolean test (int n);
}
class Lambda{
public static void main(String[] args)
{
NumericTest isEven =(n)->(n%2)==1;
if([Link](10))[Link]("10 is even");
if([Link](9))[Link]("9 is not
even"); }
}
OUTPUT:

Ex: 2 Linked List

public class linkedlist {


public static void main(String[] args)
{
LinkedList<String> Names = new
LinkedList<String>(); [Link]("Steve");
[Link]("Smith");
[Link]("Daniel");
[Link]("Linked list:" +Names);
[Link]("Alan");
[Link]("Added list:" +Names);
String Name = [Link](1);
[Link]("Accesed list:" +Name);
[Link](2, "Surya");
[Link]("Updating list:" +Names);
String Name1 = [Link](2);
[Link]("Removed elemnt:" +Name1);
[Link]("Final Linked list:" +Names);
}

}
OUTPUT:

Ex: 3 Reduce & Filter Method

import [Link].*;
import [Link];
import [Link];

public class stream


{
public static void main(String[] args)
{
List<Product>productList =new ArrayList<Product>();
[Link](new Product(1,"HP Laptop", 25000f));
[Link](new Product(2,"Dell Laptop", 30000f));
[Link](new Product(3,"Lenovo Laptop",
28000f)); [Link](new Product(4,"Sony Laptop",
27000f)); [Link](new Product(5,"Apple Laptop",
90000f)); List<Float>productPriceList =
[Link]()
.filter(p->[Link] < 30000)
.map(p->[Link])
.collect([Link]());
[Link]("Filtered stream list:"
+productPriceList); Float totalPrice = [Link]()
.map(product->[Link])
.reduce(0.0f,(sum,price)->sum+price);
[Link]("Reduced stream list:"
+totalPrice); }
}
OUTPUT:

Ex: 4 TCP/IP Protocol

//Gossip Server
import [Link].*;
import [Link].*;
public class GossipServer
{
public static void main(String[] args) throws
Exception {
ServerSocket sersock = new
ServerSocket(4000); [Link]("Server
ready for chatting");
Socket sock = [Link]( );
// reading from keyboard (keyRead object)
BufferedReader keyRead = new
BufferedReader(new InputStreamReader([Link]));
// sending to client (pwrite object)
OutputStream ostream = [Link]();
PrintWriter pwrite = new PrintWriter(ostream,
true);

// receiving from server ( receiveRead object)


InputStream istream = [Link]();
BufferedReader receiveRead = new
BufferedReader(new InputStreamReader(istream));

String receiveMessage, sendMessage;


while(true)
{
if((receiveMessage = [Link]()) !=
null) {
[Link](receiveMessage);
}
sendMessage = [Link]();
[Link](sendMessage);
[Link]();
}
}
}
//Gossip Client
import [Link].*;
import [Link].*;
public class GossipClient
{
public static void main(String[] args) throws Exception
{
Socket sock = new Socket("[Link]", 4000);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new
InputStreamReader([Link]));
// sending to client (pwrite object)
OutputStream ostream = [Link]();
PrintWriter pwrite = new PrintWriter(ostream, true);

// receiving from server ( receiveRead object)


InputStream istream = [Link]();
BufferedReader receiveRead = new
BufferedReader(new InputStreamReader(istream));

[Link]("Start the chitchat, type and press Enter key");

String receiveMessage, sendMessage;


while(true)
{
sendMessage = [Link](); // keyboard reading
[Link](sendMessage); // sending to server
[Link](); // flush the data
if((receiveMessage = [Link]()) != null)
//receive from server
{
[Link](receiveMessage); // displaying at DOS
prompt }
}
}
}
OUTPUT:
Ex: 5 Label, Textboxes, Button Control

import [Link].*;
import [Link].*;

public class Prg05 extends JFrame


{
private JLabel lb1;
private JTextField tx1;
private JButton btn;
public Prg05()
{
Clicklistener click= new Clicklistener();
lb1 = new JLabel("Enter your name here:");
tx1 = new JTextField(20);
btn = new JButton("submit");
[Link](click);
JPanel jp = new JPanel();
[Link](lb1);
[Link](tx1);
[Link](btn);
add(jp);
}
public static void main(String[] args)
{
Prg05 jf = new Prg05();
[Link]("This is a frame");
[Link](300, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
private class Clicklistener implements
ActionListener {
public void actionPerformed(ActionEvent e)
{
if ([Link]() == btn)
{
[Link]("The value is submitted");
}
}}}
OUTPUT:

Ex: 6 JMenu &JMenuItem


import [Link].*;
import [Link].*;

public class MenuEx implements ActionListener


{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll,New,open,quit;
JTextArea ta;
MenuEx()
{
f=new JFrame();
New = new JMenuItem("New");
quit = new JMenuItem("Exit");
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
mb=new JMenuBar();
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");
[Link](New);
[Link](quit);

[Link](cut);[Link](copy);[Link](paste);[Link](selectAll
); [Link](file);[Link](edit);[Link](help);
ta=new JTextArea();
[Link](5,5,360,320);
[Link](mb);
[Link](ta);
[Link](mb);
[Link](null);
[Link](400,400);
[Link](true);
}
public void actionPerformed(ActionEvent
e) {
if([Link]()==New)
{
new MenuEx();
}
if([Link]()==quit)
{
[Link](0);
}
if([Link]()==cut)
[Link]();
if([Link]()==paste)
[Link]();
if([Link]()==copy)
[Link]();
if([Link]()==selectAll)
[Link]();
}
public static void main(String[] args)
{
new MenuEx();
}
}
OUTPUT:
Ex: 7 Bean

//[Link]

import [Link];
public class Person
{
public String firstName;
public String lastName;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
[Link]=firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
[Link]=lastName;
}
}

//BeanEx

public class BeanEx


{
public static void main(String[] args)
{
Person person = new Person();
[Link]("Stephen");
[Link]("Mark");
[Link]("Java Bean
Data:"+[Link]() + " " +[Link]());
}
}
OUTPUT:
Ex: 8 JDBC Application & JDBC Driver

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class jdbcdemo {

public static void main(String[] args) {


// TODO Auto-generated method stub
String model,cc,mileage,color,price;
[Link]("Enter Bike MODELNAME, CC,
MILEAGE, COLOR, PRICE");
Scanner sc = new Scanner([Link]);
model = [Link]();
cc = [Link]();
mileage = [Link]();
color = [Link]();
price = [Link]();

String databaseURL =
"jdbc:ucanaccess://[Link]";
try {

Connection conn =
[Link](databaseURL);
[Link]("Connected to ms acess");
String sql = "INSERT INTO BIKETABLE
(MODEL_NAME,CC,MILEAGE,COLOR,PRICE) VALUES (?,?,?,?,?)";

PreparedStatement p = [Link](sql);
//Statement p = [Link]();
[Link](1, model);
[Link](2, cc);
[Link](3, mileage);
[Link](4, color);
[Link](5, price);

//Statement statement = [Link]();


int rows = [Link]();
if(rows>0)
{
[Link]("A Vehicle data is inserted");

}
sql ="SELECT * FROM BIKETABLE";
Statement st = [Link]();
ResultSet result = [Link](sql);
[Link]("\n MODELNAME CC MILEAGE
COLOR PRICE\n ");

while([Link]())
{
model=[Link]("MODEL_NAME");
cc=[Link]("CC");
mileage=[Link]("MILEAGE");
color=[Link]("COLOR");
price=[Link]("PRICE");

[Link](model + "\t" + cc + "\t" +


mileage + "\t" + color + "\t" + price);
}

[Link]();
}
catch(SQLException e) {
[Link]();
}
}

}
OUTPUT:
Ex: 9 Servlet Application using Cookies and

Sessions //[Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response){
try{

[Link]("text/html");
PrintWriter out = [Link]();

String n=[Link]("userName");
[Link]("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie


object [Link](ck);//adding cookie in the
response

//creating submit button


[Link]("<form action='SecondServlet'>");
[Link]("<input type='submit' value='go'>");
[Link]("</form>");

[Link]();

}catch(Exception e){[Link](e);}
}
}

//SecondServlet

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

/**
* Servlet implementation class SecondServlet
*/
public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response){
try{

[Link]("text/html");
PrintWriter out = [Link]();

Cookie ck[]=[Link]();
[Link]("Hello "+ck[0].getValue());

[Link]();

}catch(Exception e){[Link](e);}
}
}

//[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>
OUTPUT:
Ex: 10 JSP Tags

//[Link]
<%@ page language="java" contentType="text/html; charset=UTF-
8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h3> Login here </h3>
<form action="user_login" method="post">
<table style="width: 20%">
<tr> <td>UserName</td>
<td><input type="text" name="username" /></td></tr>
<tr> <td>Password</td>
<td><input type="password" name="password"
/></td></tr> </table>
<input type="submit" value="Login" /></form>
</body>
</html>

//user_login.java

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class user_login extends HttpServlet {


public user_login() {
super();
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String username =
[Link]("username"); String password =
[Link]("password");
if([Link]() || [Link]() )
{
RequestDispatcher requ =
[Link]("[Link]");
[Link](request, response);
}
else
{
RequestDispatcher requ =
[Link]("login_2.jsp");
[Link](request, response);
}
}

//login_2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-


8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>User Logged In</title>
</head>
<body>
<table style="width: 20%">
<tr><td>
<% String username = [Link]("username");
%> <a>Welcome user, you have logged in.</a></td></tr>
<tr></tr><tr><td></td><td><a
href="[Link]"><b>Logout</b></a></td></tr>
</table>
</body>
</html>
OUTPUT:
Ex: 11 JSP Custom Tags

//[Link]

import [Link];
import [Link];
import [Link];
import [Link];

public class MyTagHandler extends TagSupport{

public int doStartTag() throws JspException {


JspWriter out=[Link]();//returns the instance
of JspWriter
try{
[Link]([Link]().getTime());//printing date and
time using JspWriter
}catch(Exception e){[Link](e);}
return SKIP_BODY;//will not evaluate the body content of the
tag }
}

//[Link]

<%@ page language="java" contentType="text/html; charset=UTF-


8" pageEncoding="UTF-8"%>
<%@ taglib uri="WEB-INF/[Link]" prefix="m" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Current Date and Time is: <m:today/>

</body>
</html>

//[Link](created using xml file)

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library
1.2//EN" "[Link]
<taglib>

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>[Link]
<tag>
<name>today</name>
<tag-class>[Link]</tag-
class> </tag>
</taglib>
OUTPUT:

Ex: 12 Spring Application

//[Link](Class file)

public class HelloWorld {


private String message;

public void setMessage(String message){


[Link] = message;
}
public void getMessage(){
[Link]("Your Message : " + message);
}
}

//[Link]

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns = "[Link]


xmlns:xsi = "[Link]
xsi:schemaLocation = "[Link]
[Link] [Link]">

<bean id = "helloWorld" class =


"com.Prg12_1.HelloWorld"> <property name = "message"
value = "Hello World!"/>
</bean>

</beans>

//[Link]

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) { ApplicationContext context =
new ClassPathXmlApplicationContext("[Link]");
HelloWorld obj = (HelloWorld)
[Link]("helloWorld"); [Link](); } }
OUTPUT:

Common questions

Powered by AI

Using Servlet applications with cookies and sessions for client state management offers several advantages, such as maintaining user state across multiple requests without having to store information on the client-side, enhancing security and user experience. Sessions provide a more secure storage mechanism compared to cookies because they store data on the server side, only exposing a session ID to the client. However, disadvantages include increased server memory usage for storing session data and potential session hijacking if not managed properly. Cookies, while lighter, pose security and privacy issues as they store data on the client-side .

Java Beans play a crucial role in Java programming by providing a reusable software component model that follows a specific set of conventions. They facilitate reusability through properties, events, and methods that conform to specific naming patterns, making them easy to manipulate within a development environment. Encapsulation is achieved as Java Beans typically have private fields with public getter and setter methods, allowing controlled access and modification of the data. This promotes modular and maintainable code, especially in large applications where components need to be reused and extended .

The JDBC API simplifies database connectivity in Java by providing a common interface for various relational databases. The typical steps involved in interacting with a database include establishing a connection using DriverManager, creating a Statement or PreparedStatement for executing SQL queries, processing the ResultSet obtained from queries, and finally closing the connection to release resources. JDBC abstracts these processes, allowing developers to execute complex queries and transactions without concerning themselves with specific database protocols, ensuring SQL compliance and portability .

The Stream API with reduce and filter methods optimizes the processing of collections by providing a higher-level abstraction for aggregation and condition-based operations. Streams can be processed in parallel, leveraging multi-core architecture which traditional for-loops cannot do inherently. Filter method constructs a stream with only elements that satisfy a predicate, while reduce aggregates the elements of the stream into a single summary result. This leads to more concise and potentially more efficient code compared to for-loops, which require explicit iteration logic and manual aggregation operations .

JSP Tags and Custom Tags enhance JSP scripting capabilities by providing a tag-based mechanism to encapsulate reusable logic in JSPs, shielding complexities of scripting from the page itself. JSP tags come in standard libraries like JSTL which cover common tasks, whereas custom tags allow developers to define new tags tailored to specific applications. Both integrate with Java Servlets by allowing servlet-generated data to be easily embedded in HTML pages, enabling dynamic content generation. This simplifies web development by promoting separation of concerns, making JSP pages cleaner and easier to manage .

Lambda expressions in Java enhance functional programming by providing a clear and concise way to represent a single abstract method interface, commonly known as functional interfaces. This allows for cleaner code by eliminating the need for anonymous class instantiations, especially useful in event handling or implementing Runnable. In practical applications, they result in more readable and concise code, facilitate parallel operations, and improve the performance of multi-core systems due to concise lambda function executions .

The TCP/IP communication process in Java, as exemplified by the Gossip Server and Client, involves several essential steps. First, the server creates a ServerSocket to listen for incoming client connections on a specified port. Once a client connection is accepted using Socket, both server and client establish Input and OutputStreams to send and receive data. The server listens for messages using BufferedReader and responds through PrintWriter. Similarly, the client sends messages by reading input from the console and forwarding them to the server via the socket's output stream. This setup ensures a bi-directional communication channel essential for TCP/IP-based applications .

The Spring Framework plays a significant role in Java application development by offering a comprehensive infrastructure for developing Java applications. It impacts application modularity and dependency management through its Inversion of Control (IoC) and Dependency Injection (DI) features, which promote loosely coupled architectures. Spring’s aspect-oriented programming (AOP) capabilities also allow separation of cross-cutting concerns like security and transaction management. This results in modular applications where components can be easily maintained or replaced without affecting others, significantly improving the maintainability and scalability of enterprise-level applications .

GUI components like JMenu and JMenuItem improve user interaction in Java applications by providing a structured menu interface that is intuitive and easy to navigate. These components allow for grouping of related actions, improving the overall user experience. Key considerations for effective implementation include ensuring that menus are logically organized, responsive, and accessible, and that they fit the overall look and feel of the application. Proper event handling is critical, as actions related to menu items should be responsive and perform the intended functionality without delay .

The LinkedList class in Java is significant as it allows for dynamic memory allocation, unlike arrays which have a fixed size. LinkedList efficiently supports add, remove, and access operations at any position by adjusting the references of the nodes. Adding elements involves creating a new node and updating the pointers of adjacent nodes, while removing elements involves adjusting the pointers to bypass the node. Access operations in a LinkedList are less efficient than arrays because it involves traversing from the head of the list to the desired position, making operations O(n) as compared to O(1) in arrays .

You might also like