0% found this document useful (0 votes)
26 views

Lab Sheet - Module 1 - Record - Writing

Uploaded by

Sherry Kalkeri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Lab Sheet - Module 1 - Record - Writing

Uploaded by

Sherry Kalkeri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

CSE3151 – JAVA FULL STACK DEVELOPMENT

LAB SHEET – MODULE-1


Ex No: 1 Illustrate the concept of Serialization and Deserialization using File

AIM:

To implement the Serialization and Deserialization using File and demonstrated in a Java
console application.

ALGORITHM:

Step 1: Creating a Student class and are serializing the object of the Student class.

Step 2: Serialization of an Object of type Student. A text file called f.txt is created with the
help of the FileOutputStream class. Serializing the object by using the writeObject() method
of ObjectOutputStream class.

Step 3: For deserializing the object by using the readObject() method


of ObjectInputStream class

Serialization and Deserialization

Persist.java
import java.io.Serializable;
import java.io.*;
class Student implements Serializable{
int id;
String name;
transient int age;
Student (int id, String name, int age){
this.id = id;
this.name = name;
this.age = age;
}
}
public class Persist {
public static void main(String [] args) {
try {
Student s1 = new Student(123, "Ravi", 22);
FileOutputStream fout = new FileOutputStream("D:\\JAVA
FSD\\7CST1_WORKSPACE\\FILES\\f1.txt");
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
out.close();
System.out.println("Success...");
}catch(Exception e) {
System.out.println(e);
}
}
}

Depersist.java
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DePersist {
public static void main(String[] args) {
try {
ObjectInputStream fin = new ObjectInputStream(new
FileInputStream("D:\\JAVA FSD\\7CST1_WORKSPACE\\FILES\\f1.txt"));
Student s = (Student)fin.readObject();
System.out.println(s.id+" "+s.name+" "+s.age);
fin.close();
}catch(Exception e) {
System.out.println(e);
}
}
}

RESULT:

Thus the Serialization and Deserialization using File was implemented in a Java console
application.
Illustration of Collection framework by using Collection, Iterator and Comparator interfaces.

AIM:
To implement the collection framework by develop a java console application.

ALGORITHM:
Step 1 : Student class contains fields and age and a parameterized constructor.
Step 2: AgeComparator class defines comparison logic based on the age.
Step 3: NameComparator class provides comparison logic based on the name.
Step 4: FeesComparator class provides comparison logic based on the fees.
Step 5: Main class printing the values of the object by sorting on the basis of name, age and fees.

import java.io.*;
import java.util.*;
class Student {
int rollno;
String name;
float fees;
String branch;
int year;
int sem;
int age;
static String clg;
public Student(int rollno,String name,float fees,String branch,int year,int sem,int
age) {
this.rollno = rollno;
this.name = name;
this.fees = fees;
this.branch = branch;
this.year = year;
this.sem = sem;
this.age = age;
clg="PU";
}
@Override
public String toString() {
return rollno + " "+ name + " " + fees + " " + branch + " " + year + sem + " " +
age + " " + clg + "\n";
}
}
class AgeComparator implements Comparator {
public int compare(Object o1, Object o2) {
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
class NameComparator implements Comparator <Student>{
public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name);
}
}
class FeesComparator implements Comparator <Student>{
public int compare(Student s1, Student s2) {
if(s1.fees==s2.fees)
return 0;
else if(s1.fees>s2.fees)
return 1;
else
return -1;
}
}
public class Temp1 {
public static void main(String[] args) {
ArrayList sl=new ArrayList();
sl.add(new Student(1,"Shiva",10000.00f,"cse",1,1,18));
sl.add(new Student(2,"Venky",15000.00f,"ise",1,2,20));
sl.add(new Student(3,"Jesus",17000.00f,"ece",1,1,19));
sl.add(new Student(3,"Alla",12000.00f,"eee",1,1,19));
sl.add(new Student(3,"Budha",11000.00f,"mech",1,1,21));
System.out.println("\nSorting by Name");
System.out.println("_______________");
Collections.sort(sl,new NameComparator());
Iterator itr=sl.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+ st.fees+ " " + st.branch+ " " +
st.year + " " + st.sem + " " + st.age + " " + Student.clg);
}
System.out.println("\nSorting by age");
System.out.println("______________");
Collections.sort(sl,new AgeComparator());
Iterator itr2=sl.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st.rollno+" "+st.name+" "+ st.fees+ " " + st.branch+ " " +
st.year + " " + st.sem + " " + st.age + " " + Student.clg);
}
System.out.println("\nSorting by fees");
System.out.println("______________");
Collections.sort(sl,new FeesComparator());
Iterator itr3=sl.iterator();
while(itr3.hasNext()){
Student st=(Student)itr3.next();
System.out.println(st.rollno+" "+st.name+" "+ st.fees+ " " + st.branch+ " " +
st.year + " " + st.sem + " " + st.age + " " + Student.clg);
}
} }
Database Connectivity:

Write the useful classes , interface and methods available in sql.*

Solution : Principal JDBC interfaces and classes under sql.*;

Let’s take an overview look at the JDBC’s main interfaces and classes which we’ll use in this
article. They are all available under the java.sql package:

 Class.forName() : Here we load the driver’s class file into memory at the runtime. No
need of using new or creation of object.
 DriverManager: This class is used to register driver for a specific database type (e.g.
Oracle Database in this tutorial) and to establish a database connection with the server
via its getConnection() method.
 Connection: This interface represents an established database connection (session)
from which we can create statements to execute queries and retrieve results, get
metadata about the database, close connection, etc.
 Statement and PreparedStatement: These interfaces are used to execute static SQL
query and parameterized SQL query, respectively. Statement is the super interface of
the PreparedStatement interface. Their commonly used methods are:
1. boolean execute(String sql): executes a general SQL statement. It returns true if the
query returns a ResultSet, false if the query returns an update count or returns
nothing. This method can be used with a Statement only.
2. int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement
and returns an update account indicating number of rows affected (e.g. 1 row
inserted, or 2 rows updated, or 0 rows affected).
 ResultSet executeQuery(String sql): executes a SELECT statement and returns
a ResultSet object which contains results returned by the query.
 ResultSet: contains table data returned by a SELECT query. Use this object to iterate
over rows in the result set using next() method.
 SQLException: this checked exception is declared to be thrown by all the above
methods, so we have to catch this exception explicitly when calling the above classes’
methods.
Demonstrate with a java console application that connect with MySQL database and perform
database operations

AIM:
To develop a Java console application that demonstrates the connection with MySQL
database and perform various operations on it.

ALGORITHM:
Step 1: create employee database by using create database employee; and use employee;
commands.
Step 2: create a table in the mysql database by
create table emp(rno int(10),name varchar(40),age int(3));
Step 3: Register the JDBC driver: to initialize a driver so that open a communication channel
with the database.

Step 4: Open a connection: use the getConnection() method to create a Connection object,
which represents a physical connection with the database.

Step 5: Execute a query: requires to use an object of type Statement for building and submitting
an SQL statement to the database.

Step 6: Extract data from the result set: use the appropriate getXXX() method to retrieve the
data from the result set.

Step 7: Clean up the environment: to explicitly close all database resources versus relying on
the JVM’s garbage collection.

create table employee1 (eno int, ename varchar(30), age int);

import java.sql.*;
import java.util.*;
public class Test2 {
public static void main(String[] args) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con= DriverManager.getConnection
("jdbc:mysql://localhost:3306/userinfo","root","rahman");
Statement stmt=con.createStatement();
int ans=1;
do {
System.out.println("1. Insert a record ");
System.out.println("2. Delete a record ");
System.out.println("3. Modify/Edit a record ");
System.out.println("4. Display list of records ");
Scanner sc = new Scanner(System.in);
System.out.println("Enter your choice:");
int ch = sc.nextInt();
String ename;
int eno,age;
String query="";
switch(ch) {
case 1:
System.out.println("Enter employee number:");
eno = sc.nextInt();
System.out.println("Enter employee name:");
ename = sc.next();
System.out.println("Enter employee age:");
age = sc.nextInt();
query = "INSERT INTO employee1 " + "VALUES (" + eno+ ",'" +
ename+"',"+ age+")";
stmt.executeUpdate(query);
break;
case 2:
System.out.println("Enter employee number:");
eno = sc.nextInt();
query = "delete from employee1 where eno='"+eno+"'";
stmt.executeUpdate(query);
System.out.println("Record is deleted from the table
successfully..................");
break;
case 3:
PreparedStatement ps = null;
query = "update employee1 set ename=? where eno=? ";
ps = con.prepareStatement(query);
System.out.println("Enter employee number:");
eno = sc.nextInt();
System.out.println("Enter employee name:");
ename = sc.next();
ps.setString(1, ename);
ps.setInt(2, eno);
ps.executeUpdate();
System.out.println("Record is updated successfully......");
break;
case 4:
ResultSet rs=stmt.executeQuery("select * from employee1");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getInt(3));
}
System.out.println("Enter another(1/0)");
ans = sc.nextInt();
}while(ans==1);
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

Illustration of Collection framework access by using Lambda Expression.


AIM:
To implement the collection framework and access by using Lambda Expression and
demostrate with a java console application.

ALGORITHM:
Step 1 : Student class contains fields such as rno,name,fees and age and a parameterized
constructor.
Step 2: To sort the names by using Collections sort method and Lambda expression.Access the
collection by using Lambda expression wyhin for statement.
Step 2: To sort the age by using Collections sort method and Lambda expression.Access the
collection by using Lambda expression wyhin for statement.
Step 2: To sort the fees by using Collections sort method and Lambda expression.Access the
collection by using Lambda expression wyhin for statement.
Step 5: Main class printing the values of the object by sorting on the basis of name, age and fees.

Program:
import java.util.*;

class Student{
int rno;
String name;
int age;
float fees;

public Student(int rno, String name, int age, float fees) {


super();
this.rno = rno;
this.name = name;
this.age = age;
this.fees = fees;
}

@Override
public String toString() {
return rno + " " + name + " " + age + " " + fees;
}
}
class temp {
public static void main(String[] args) {
List <Student> s = new <Student>ArrayList();
s.add(new Student(1,"abc",20,20000.00f));
s.add(new Student(2,"xyz",15,15000.00f));
s.add(new Student(3,"def",10,10000.00f));

System.out.println("Sorting on the basis of name...");


// implementing lambda expression
Collections.sort(s,(s1,s2)->{return s1.name.compareTo(s2.name);});
for(Student l:s){
System.out.println(l);
}
System.out.println("Sorting by age");
Collections.sort(s,(s1,s2)-> s1.age - s2.age);
s.forEach((l)->System.out.println(l));

System.out.println("Sorting by Fees");
Collections.sort(s,(s1,s2)-> (int)s1.fees - (int)s2.fees);
s.forEach((l)->System.out.println(l));

}
}

RESULT:
Thus the collection framework was implemented with Collection, and access by using
Lambda expression that can be demonstrated with a java console application.

You might also like