0% found this document useful (0 votes)
28 views38 pages

JAVA2 Merged

The program develops a Java application using JDBC that connects to a database and allows users to perform CRUD operations on an employee table through a menu. It uses prepared statements to insert, update, delete and retrieve data from the table.

Uploaded by

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

JAVA2 Merged

The program develops a Java application using JDBC that connects to a database and allows users to perform CRUD operations on an employee table through a menu. It uses prepared statements to insert, update, delete and retrieve data from the table.

Uploaded by

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

Ex no:

PROGRAM USING JDBC CRUD OPERATIONS


Date:

Question
Develop a Java program to connect with database and retrieve following details:
• Write a Java code to insert records by reading input from user.
• Display all the details which are stored in Nobel Prize table.
• Display the details of the Nobel Prize winners who got for the subject Peace.
• Delete the NobelPrize winners who got NobelPrize before 1930.

Aim
To write a java program to connect database and perform CRUD operations in NobelPrize table.

Program / Source Code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class noble_prize {
public static Connection getConnect() throws Exception
{
String url="jdbc:mysql://localhost:3306/noble";
String username="root";
String password="root";
Connection con=DriverManager.getConnection(url,username,password);
return con;
}
public static void create_table() throws Exception
{
Connection con=getConnect();
String query="create table noble_prize(Name varchar(50),Year int,Subject
varchar(50))";
Statement s=con.createStatement();
s.execute(query);
con.close();
}
public static void insert(String name,int year,String subject) throws Exception
{
Connection con=getConnect();
String query="insert into noble_prize values(?,?,?)";
PreparedStatement ps=con.prepareStatement(query);
ps.setString(1,name);
ps.setInt(2,year);
ps.setString(3,subject);
ps.execute();
con.close();

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


}
public static void display() throws Exception
{
Connection con=getConnect();
String query="select * from noble_prize";

System.out.println("===============================================");
System.out.println("Name\t\t\tYear\t\tSubject");

System.out.println("===============================================");
Statement s=con.createStatement();
ResultSet rs=s.executeQuery(query);
while(rs.next())
{
System.out.println(rs.getString(1)+"\t\t"+rs.getInt(2)+"\t\t"+rs.getString(3));
}

System.out.println("===============================================");
con.close();
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
try {
create_table();
for(int i=0;i<5;i++) {
System.out.print("Enter name: ");
String s=sc.nextLine();
System.out.print("Enter year: ");
int n=sc.nextInt();
sc.nextLine();
System.out.print("Enter subject: ");
String sub=sc.nextLine();
insert(s,n,sub);
}
insert("Rabindhranath Tagore",1917,"Literature");
display();
Connection con=getConnect();
String query1="select * from noble_prize where Subject='Peace'";
Statement s=con.createStatement();
ResultSet rs=s.executeQuery(query1);
rs.next();
System.out.println("\nPeace winners: "+rs.getString(1)+" "+rs.getInt(2));
String query2="delete from noble_prize where Year<1930";
s.executeUpdate(query2);
display();
}
catch(Exception e)
{
e.printStackTrace();
}
}}

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING PREPARED STATEMENT IN JDBC
Date:

Question
Given the following table containing information about employees of an organization,
develop a small java application, using JDBC, which displays a menu for the user consisting
of following options: (Use Prepared Statement for Executing Queries)
1. Add Record 2. Modify Record 3. Delete Record
4. Display one Record 5. Display All 6. Exit

Aim
To write a java program to connect database and perform CRUD operations using prepared
statement.

Program / Source Code:


package mod2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class employee {


public static void create_table(Connection con) throws Exception{
String query="create table Employee(Emp_No int,First_Name
varchar(50),Last_Name varchar(50),Date varchar(15),Designation varchar(30),Dept
varchar(20),Basic_salary int)";
Statement s=con.createStatement();
s.execute(query);
}
public static void insert(Connection con,int Emp_no,String name1,String name2,String
date,String desig,String dept,int salary) throws Exception
{
String query="insert into Employee values(?,?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(query);
ps.setInt(1,Emp_no);
ps.setString(2, name1);
ps.setString(3, name2);
ps.setString(4,date);
ps.setString(5,desig);
ps.setString(6,dept);
ps.setInt(7,salary);
ps.executeUpdate();
}
public static void display(Connection con,int id) throws Exception{
String query="select * from Employee where Emp_no=?";
PreparedStatement ps=con.prepareStatement(query);
ps.setInt(1,id);

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


ResultSet rs=ps.executeQuery();
rs.next();
System.out.println("Employee no: "+rs.getInt(1)+"\nDesignation
"+rs.getString(5)+"\nDepartment: "+rs.getString(6)+"\nSalary: "+rs.getInt(7));
}
public static void update(Connection con,int id,String desig,int salary) throws Exception {
String query1="update Employee set Designation=? where Emp_no=?";
PreparedStatement ps1=con.prepareStatement(query1);
ps1.setString(1,desig);
ps1.setInt(2,id);
ps1.executeUpdate();
String query3="update Employee set Basic_salary=? where Emp_no=?";
PreparedStatement ps3=con.prepareStatement(query3);
ps3.setInt(1,salary);
ps3.setInt(2,id);
ps3.executeUpdate();
}
public static void delete(Connection con,int id) throws Exception
{
String query="delete from Employee where Emp_no=?";
PreparedStatement ps=con.prepareStatement(query);
ps.setInt(1,id);
ps.executeUpdate();
}
public static void displayAll(Connection con) throws Exception
{
String query="select * from Employee";
Statement s=con.createStatement();
ResultSet rs=s.executeQuery(query);
while(rs.next())
{
System.out.println("Employee no: "+rs.getInt(1)+" First Name:
"+rs.getString(2)+" LastName "+rs.getString(3)+" Date "+rs.getString(4)+" Designation
"+rs.getString(5)+" Department: "+rs.getString(6)+" Salary: "+rs.getInt(7));
}
}

public static void main(String[] args) {


String url="jdbc:mysql://localhost:3306/Employees";
String username="root";
String password="root";
Scanner sc=new Scanner(System.in);
try {
Connection con=DriverManager.getConnection(url,username,password);
System.out.println("Choices\n1.Add employee\n2.Update record\n3.Remove
employee\n4.Display employee detail\n5.Display all\n");
create_table(con);
insert(con,1001,"Ashish","Kulkarni","19-04-2024","Architect","R&D",50000);
insert(con,1002,"Sushma","Shah","19-01-2024","Officer","Purchase",30000);
insert(con,1003,"Rahul","G","19-01-2024","Clerk","Stores",10000);
insert(con,1004,"Chahat","Punja","19-01-2024","Manager","HR",12000);

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


insert(con,1005,"Ranjan","Srivastava","19-01-2024","Clerk","Accounts",20000);
insert(con,1006,"Suman","J","19-01-2024","Officer","Accounts",23000);
System.out.print("Enter your choice: ");
int ch=sc.nextInt();
while(ch!=0) {
if(ch==1)
{
System.out.print("Employee ID: ");
int id=sc.nextInt();
sc.nextLine();
System.out.print("Employee’s First Name: ");
String fname=sc.nextLine();
System.out.print("Employee’s last Name: ");
String lname=sc.nextLine();
System.out.print("Join Date: ");
String date=sc.nextLine();
System.out.print("Department: ");
String dept=sc.nextLine();
System.out.print("Designation: ");
String desig=sc.nextLine();
System.out.print("Salary: ");
int salary=sc.nextInt();
insert(con,id,fname,lname,date,dept,desig,salary);
System.out.print("Inserted successfully");
}
else if(ch==2)
{
System.out.print("Enter emp_id: ");
int id=sc.nextInt();
display(con,id);
sc.nextLine();
System.out.print("Enter designation: ");
String d=sc.nextLine();
System.out.print("Enter salary: ");
int s=sc.nextInt();
update(con,id,d,s);
System.out.print("Updated successfully");
}
else if(ch==3)
{
System.out.print("Enter emp_id: ");
int id=sc.nextInt();
delete(con,id);
System.out.print("Deleted successfully");
}
else if(ch==4)
{
System.out.print("Enter emp_id: ");
int id=sc.nextInt();
display(con,id);
}

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


else if(ch==5)
{
displayAll(con);
}
System.out.print("\nEnter your choice: ");
ch=sc.nextInt();
}
con.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING CALLABLE STATEMENT IN JDBC
Date:

Question
1) Develop a Java program to connect with database and retrieve following details: 1) Add a new book
‘HTML, CSS & JavaScript’ by Laura Lemay, Prentice Hall, Rs.250.00 using Prepared Statement.
2) Display all the details which are stored in Books table. 3) Create a Procedure to increase the price
of books by Rs.200. 4) Create a Procedure to add new record into table. 5) Execute procedures using
Callable Statement.

Aim
To write a java program to connect jdbc and perform CRUD operations using callable statement.

Program / Source Code:


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
public class BookProgram {
public static void main(String[] args){
try{
Class.forName("com.mysql.cj.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/ajp";
String username="root";
String password="root";
Connection conn=DriverManager.getConnection(url,username,password);
Scanner sc=new Scanner(System.in);
System.out.println("Adding records to the table using prepared statement:");
System.out.print("Entrer title: ");
String title=sc.nextLine();
System.out.print("Enter author :");
String author=sc.nextLine();
System.out.print("Enter publication :");
String publication=sc.nextLine();
System.out.print("Enter price :");
float price=sc.nextFloat();
String query1="INSERT INTO book VALUES(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(query1);
ps.setString(1, title); ps.setString(2, author); ps.setString(3,
publication); ps.setFloat(4, price);
int rows=ps.executeUpdate();
if(rows>0) System.out.println("Inserted successfully");
else System.out.println("Rows not inserted");
System.out.println("\nUpdating price");
System.out.print("Enter title: "); title=sc.nextLine();
CallableStatement cs=conn.prepareCall("{call updatePrice(?)}");
cs.setString(1, title); cs.execute();
String query2="SELECT * FROM book";
PreparedStatement ps1=conn.prepareStatement(query2);

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


ResultSet rs=ps1.executeQuery();
System.out.println("Displaying book table : ");
while(rs.next()){
System.out.printf("%-40s %-20s %-20s %.2f\n",rs.getString("title"),
rs.getString("author"),rs.getString("publication"),rs.getFloat("price"));
System.out.println("\nAdding records to the table using callable statement:");
System.out.print("Enter title: ");
title=sc.nextLine();
System.out.print("Enter author :");
author=sc.nextLine();
System.out.print("Enter publication :");
publication=sc.nextLine();
System.out.print("Enter price :");
price=sc.nextFloat();
CallableStatement cs1=conn.prepareCall("{call insertbook(?,?,?,?)}");
cs1.setString(1, title);cs1.setString(2, author);
cs1.setString(3, publication);
cs1.setFloat(4, price); cs1.execute();
PreparedStatement ps2=conn.prepareStatement(query2);
ResultSet rs1=ps2.executeQuery();
System.out.println("Displaying book table : ");
while(rs1.next())
System.out.printf("%-40s %-20s %-20s %.2f\n",rs1.getString("title"),
rs1.getString("author"),rs1.getString("publication"),rs1.getFloat("price"));
sc.close(); rs.close(); rs1.close(); ps.close(); ps1.close(); ps2.close();
cs.close();cs1.close();conn.close();
}}}}}}catch(Exception e){ e.printStackTrace(); }
Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING JUNIT
Date:

Question
Write a Java program to test the function using JUnit & check whether it is finding the Nth Fibonacci
number.Try to fix the logical errors if any.

Aim
To write a java program that checks Fibonacci number is found correctly.

Program / Source Code:

public class FibonacciSequence {


public int nthFibonacci(int num) {
if (num == 1)
return 0;
else if (num == 2)
return 1;
return nthFibonacci(num - 1) + nthFibonacci(num - 2);
}
}
import static org.junit.Assert.*;
import org.junit.Test;
public class fibonacciTest {
@Test
public void test1() {
fibonacci f=new fibonacci();
int res=f.nthFibonacci(5);
assertEquals(3,res);
}
@Test
public void test2()
{
fibonacci f=new fibonacci();
int res=f.nthFibonacci(7);
assertEquals(8,res);
}
}

Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING JUNIT
Date:

Question
Create the class and implement the method to check given string is a palindrome and return the
result. Create a Junit test class to test the above class.

Aim
To write a java program that checks palindrome string is found correctly..

Program / Source Code:

public class MyUnit {


public boolean palindromeCheck(String input){
StringBuilder sb=new StringBuilder(input);
sb.reverse();
if(input.equals(sb.toString()))
return true;
else
return false;
}
}
import static org.junit.Assert.*;
import org.junit.Test;
public class PalindromeTest {
@Test
public void test1(){
MyUnit m=new MyUnit();
assertTrue(m.palindromeCheck("malayalam"));
}
@Test
public void test2(){
MyUnit m=new MyUnit();
assertFalse(m.palindromeCheck("Java"));
}}

Output

Result

Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING JUNIT
Date:

Question

Create the class and implement the method to find number of digits in a given string. Create a Junit
test class to test the above class.

Aim
To write a java program that checks number of digits is found correctly.

Program / Source Code:


public class Count {
public int digitCount(String input){
int cnt=0;
for(int i=0;i<input.length();i++){
if(input.charAt(i)>='0' && input.charAt(i)<='9') {
cnt+=1;
}
}
return cnt;
}}
public class CountTest {
@Test
public void test1() {
Count obj=new Count();
assertEquals(5,obj.digitCount("123abc@45"));
}
@Test
public void test2() {
Count obj=new Count();
assertEquals(0,obj.digitCount("Hello"));
}
}
Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING JUNIT
Date:

Question
Test the functions of Calculate class using JUnit. Print binary function is used to print the binary
equivalent of the given number. Note: Try to fix the logical errors in these functions.

Aim
To write a java program that checks the binary form of a number is found correctly.

Program / Source Code:

import java.util.Arrays;
public class Calculate {
public byte add(byte b1, byte b2) {
return (byte)(b1+b2);
}public short add(short b1,short b2) {
return (short)(b1+b2);
}public int[] printBinary(byte number) {
int[] result;
if (number < 16) result = new int[4];
else if (number < 32) result = new int[5];
else if (number < 64) result = new int[6];
else result = new int[7];
for(int i = result.length - 1; number > 0; i--) {
result[i] = number % 2;
number = (byte) (number / 2);
}
return Arrays.copyOfRange(result, i + 1, result.length);
}
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class CalculateTest {
byte input;
int[] expected;

public CalculateTest(byte input,int[] expected) {


this.input=input;
this.expected=expected;
}
@Parameters
public static Collection<Object[]> data() {
Object[][] array= {{(byte)5,new int[]{1,0,1}},{(byte)15,new int[]{1,1,1,1}},{(byte)31,new
int[]{1,1,1,1,1}}};

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


return Arrays.asList(array);
}
Calculate c=new Calculate();
@Test
public void testAddByte() {
assertEquals(8,c.add((byte)3,(byte)5));
}
@Test
public void testAddShort() {
assertEquals(300,c.add((short)100,(short)200));
}
@Test
public void testPrintBinaryParameterized() {
assertArrayEquals(expected,c.printBinary(input));
}
}

Output:

Result

Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:
PROGRAM USING JUNIT
Date:

Question
Create a test suite class for the above exercises 2 & 3 and test the methods.

Aim
To write a java program that test the program using suite method.

Program / Source Code:

public class MyUnit {


public boolean palindromeCheck(String input){
StringBuilder sb=new StringBuilder(input);
sb.reverse();
if(input.equals(sb.toString()))
return true;
else
return false;
}
}
import static org.junit.Assert.*;
import org.junit.Test;
public class PalindromeTest {
@Test
public void test1(){
MyUnit m=new MyUnit();
assertTrue(m.palindromeCheck("malayalam"));
}
@Test
public void test2(){
MyUnit m=new MyUnit();
assertFalse(m.palindromeCheck("Java"));
}}
public class Count {
public int digitCount(String input){
int cnt=0;
for(int i=0;i<input.length();i++){
if(input.charAt(i)>='0' && input.charAt(i)<='9') {
cnt+=1;
}
}
return cnt;
}}
public class CountTest {
@Test
public void test1() {
Count obj=new Count();
assertEquals(5,obj.digitCount("123abc@45"));

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


}
@Test
public void test2() {
Count obj=new Count();
assertEquals(0,obj.digitCount("Hello"));
}
}
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({PalindromeTest.class,CountTest.class})
public class TestSuite {
}

Output

Result
Thus, the java program was executed successfully and the output was verified.

21PE04 – Advanced Java Programming 717822P339-PRIYA.C


Ex no:7.1
PROGRAM USING FUNCTIONAL INTERFACE
Date:

Question:
A function interface ArrayProcess is defined as follows
public interface ArrayProcess {
int apply( int[] array );
}
Write a lambda expression for the following tasks
• find the maximum value in the array,
• find the minimum value in an array,
• counts the occurrence of a given value occurs in an array
• find the sum of the values in the array, and
• find the average of the values in the array.

Aim:
To write a java program to create functional interface to perform some tasks in the given array.

Program/Source Code:
package Module1;
import java.util.*;
@FunctionalInterface
interface ArrayProcess{
int apply(int[] array);
}
class process implements ArrayProcess{
//Finding Maximum Value.
Scanner sc = new Scanner(System.in);
public int apply(int[] arr) {
ArrayProcess findmax = array->{int max=array[0];
for(int j=1;j<array.length;j++)
{
if(max<array[j])
{
max=array[j];
}
}
return max;
};
//Minimum Element
ArrayProcess findmin=array->{
int min=array[0];
for(int j=1;j<array.length;j++)
{

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


if(min>array[j])
{
min=array[j];
}
}
return min;
};

//Occurence of the character


ArrayProcess occur =array->{
System.out.println("Enter the target value : ");
int target = sc.nextInt();
int k,c=0;
for(k=0;k<array.length;k++)
{
if(array[k]==target)
{
c++;
}
}
return c;
};
//Sum of the Array
ArrayProcess sum=array->{
int s=0;
for(int j=0;j<array.length;j++)
{
s+=array[j];
}
return s;
};

//Average of the Array


ArrayProcess average=array->{
int s=0;
for(int j=0;j<array.length;j++)
{
s+=array[j];
}
return s/array.length;
};
System.out.println("Maximum Element : "+findmax.apply(arr));
System.out.println("Minimmum Element : "+ findmin.apply(arr));
System.out.println("Occurence of the Element : "+occur.apply(arr));
System.out.println("Sum of the Array : "+sum.apply(arr));
System.out.println("Average of the Array : "+average.apply(arr));
return 0;
}
}
public class Main {
public static void main(String args[])

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the size of the Array: ");
int n = sc.nextInt();
int i;
int[] arr= new int[n];
System.out.println("Enter the array Elements: ");
for(i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
process p = new process();
p.apply(arr);
}
}
OUTPUT:

RESULT:
Thus the java program using functional interface executed successfully and output was
verified.

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Ex no:7.2
PROGRAM USING FUNCTIONAL INTERFACE
Date:

Question:
Write a Java program to demonstrate working of Consumer interface based on the
following design requirements

• Create 5 Employee object and store it in a list


• Print the Name and email of all the employee objects in the list
• Print the employee details those who are earning above
30,000.
• Print all the employee details with the skill set "Java"
• Print all the employee details with the designation "Developer"

Aim:
To write a java program to create functional interface to perform some tasks in the given array.

Program/Source Code:
package Module1;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Consumer;
class Employee {
private int employeeId;
private String name;
private double salary;
private String designation;
private List<String> skills;
private String email;
private Address address{
public Employee(int employeeId, String name, String email, String designation, Address address,
List<String> skills,double salary) {
this.employeeId = employeeId;
this.name = name;
this.email = email;
this.designation = designation;
this.address = address;
this.skills = skills;
this.salary=salary;
}

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


public int getEmployeeId()
{ return employeeId;}
public void setEmployeeId(int employeeId)
{ this.employeeId = employeeId;}
public String getName()
{ return name;}
public void setName(String name)
{ this.name = name;}
public double getSalary()
{ return salary;}
public void setSalary(double salary)
{ this.salary = salary;}
public String getDesignation()
{ return designation;}
public void setDesignation(String designation)
{ this.designation = designation;
}
public List<String> getSkills()
{ return skills;
}
public void setSkills(List<String> skills)
{ this.skills = skills;
}
public String getEmail(){
return email;
}
public void setEmail(String email)
{ this.email = email;
}
public Address getAddress()
{ return address;
}
public void setAddress(Address address)
{ this.address = address;
}
public String toString() {
return "Employee ID: " + getEmployeeId() + "\n" +
"Name: " + getName() + "\n" +
"Email: " + getEmail() + "\n" +
"Designation: " + getDesignation() + "\n"
+"Address: " + getAddress() + "\n" + "Skills: " +
getSkills()+"\n";
}
}
class Address{
private String door;
private String street;
private String district;
private String state;
private int pincode;

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


public Address(String door, String street, String district, String state, int pincode)
{ this.door = door;
this.district = district;
this.street = street;
this.state = state;
this.pincode = pincode;
}
public String getDoor()
{ return door;
}
public String getDistrict()
{ return district;
}
public String getStreet()
{ return street;
}
public String getState()
{ return state;
}
public int getPincode()
{ return pincode;
}
@Override
public String toString() {
return getDoor() + " " + getStreet() + " " + getDistrict() + " " + getStreet() + " " + getPincode();
}
}

public class TestEmployee {


public static void main(String[] args)
{ System.out.println("Creating employee list. ");
List<Employee> empList = new ArrayList<Employee>();
Address add1 = new Address("12/7", "Gandhi park", "Coimbatore", "Tamilnadu", 641032);
Address add2 = new Address("1/7", "Town Hall", "Coimbatore", "Tamilnadu", 641604);
Address add3 = new Address("15", "Mahesh street", "Tirupur", "Tamilnadu", 641605);
Address add4 = new Address("62", "Nehru street", "Coimbatore", "Tamilnadu", 641032);
Address add5 = new Address("1/555", "Nethaji street", "Erode", "Tamilnadu", 641001);

Employee e1 = new Employee(1001, "Priya", "[email protected]", "Developer", add1,


Arrays.asList("C", "C++"),40000.00);
Employee e2 = new Employee(1002, "Shinchan", "[email protected]", "Junior Developer",
add2, Arrays.asList("Java", "C++"),25000.00);
Employee e3 = new Employee(1003, "Doremon", "[email protected]", "HR", add3,
Arrays.asList("Python", "C++"),25000.00);
Employee e4 = new Employee(1004, "MotuPatlu", "[email protected]", "Tester", add4,
Arrays.asList("Java", "C++"),10000.00);
Employee e5 = new Employee(1005, "HarryPotter", "[email protected]", "Developer", add5,
Arrays.asList("C", "HTML"),15000.00);
empList.addAll(Arrays.asList(e1, e2, e3, e4, e5));
Consumer<Employee> c1 = employee -> System.out.println("Name : "+ employee.getName() +
" Email: " + employee.getEmail());
Consumer<Employee> c2 = employee -> { if (employee.getSalary() > 30000)
System.out.println(employee); };

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Consumer<Employee> c3 = employee -> { if (employee.getSkills().contains("Java"))
System.out.println(employee); };
Consumer<Employee> c4 = employee -> { if (employee.getDesignation().equals("Developer"))
System.out.println(employee); };
System.out.println("\nDisplaying name and e-mail id of the employees: ");
for (Employee emp : empList) {
c1.accept(emp);
}
System.out.println("\nEmployee details who earn more than 30000:");
for (Employee emp : empList) {
c2.accept(emp);
}
System.out.println("\nEmployee details with skill set 'Java' :");
for (Employee emp : empList) {
c3.accept(emp);
}
System.out.println("\nEmployee details with designation 'Developer': ");
for (Employee emp : empList) {
c4.accept(emp);
}}}

OUTPUT:

RESULT:
Thus the java program using functional interface executed successfully and output was
verified.

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Ex no:7.3
PROGRAM USING FUNCTIONAL INTERFACE
Date:

Question:
Write a Java program to demonstrate working of Predicate interface based on the following
design requirements

• Create 5 Address object and store it in a list


• Print the address details which has the pin Code 641032.
• Print the address details which has the city Coimbatore.
• Print all the address details which has multiple phone numbers.
Aim:
To write a java program to create functional interface to perform some tasks in the given array.

Program/Source Code:
package Module3;
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
class Address {
private int doorNo;
private String street;
private String city;
private int pinCode;
private Set<Long> phoneNumber;
public Address(int doorNo, String street, String city, int pinCode, Set<Long> phoneNumber)
{ this.doorNo = doorNo;
this.street = street;
this.city = city;
this.pinCode = pinCode;
this.phoneNumber = phoneNumber;
}
public void setdoorNo(int doorNo)
{ this.doorNo = doorNo;
}
public void setStreet(String street)
{ this.street = street;
}

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


public void setCity(String city)
{ this.city = city;
}
public void setphoneNumber(Set<Long> phoneNumber)
{ this.phoneNumber = phoneNumber;}
public void setpinCode(int pinCode)
{ this.pinCode = pinCode;
}
public int getdoorNo()
{ return doorNo;
}
public String getStreet()
{ return street;
}
public String getCity() {return city;}
public Set<Long> getphoneNumber() {
return phoneNumber;}
public int getPincode() {
return pinCode;}
public String toString() {
return "DoorNo: " + getdoorNo() + " Street: " + getStreet() + " City: " + getCity() + "
PhoneNumber: " + getphoneNumber() + " Pincode : " + getPincode();}}
public class TestAddress {

public static void main(String[] args)

{ List<Address> addList = new ArrayList<>();

Address add1 = new Address(101, "Gandhipuram", "Coimbatore", 641032, new


HashSet<>(Arrays.asList(123434L)));

Address add2 = new Address(102, "Gandhipark", "Theni", 625515, new


HashSet<>(Arrays.asList(2345678L)));

Address add3 = new Address(103, "A B C Street", "Madurai", 625514, new


HashSet<>(Arrays.asList(3456789L)));

Address add4 = new Address(104, "Netaji Nagar", "Namakkal", 6641032, new


HashSet<>(Arrays.asList(876534L)));
Address add5 = new Address(105, "Nehru Nagar", "Tripur", 625512, new
HashSet<>(Arrays.asList(111111L, 2222222L)));
addList.addAll(Arrays.asList(add1, add2, add3, add4, add5));
Predicate<Address> p1 = a -> a.getPincode() == 641032;
Predicate<Address> p2 = a -> a.getCity().equals("Coimbatore");
Predicate<Address> p3 = a -> a.getphoneNumber().size() > 1;

// Print address details which have pincode 641032


System.out.println("\nAddress details which have pincode '641032': ");
addList.forEach(address -> {
if (p1.test(address)) System.out.println(address);
});

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


// Print address details which have city Coimbatore
System.out.println("\nAddress details which have city Coimbatore:");
addList.forEach(address -> {
if (p2.test(address)) System.out.println(address);
});

// Print address details which have more than one phone number
System.out.println("\nAddress details which have more than one phone Number:");
addList.forEach(address -> {
if (p3.test(address)) System.out.println(address);
});
}
}
OUTPUT:

RESULT:
Thus the java program using functional interface executed successfully and output was
verified.

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Ex no:8.1
PROGRAM USING LAMBDA EXPRESSION
Date:

Question:
Write a Java program to print Fibonacci series for integer value n. Use Function<T>
functional interface and lambda expression that accepts integer value n and print
Fibonacci series.
Aim:
To write a java program that generates Fibonacci series using lambda expression.
Program/Source Code:
package Module1;
import java.util.Scanner;
import java.util.function.Function;
public class Fibonacci {
public static void main(String
args[]){ Function<Integer,Integer>
f=(n)->{
int t1=0;
int t2=1;
int i;
System.out.print(t1 + " " +t2+" ");
for(i=3;i<=n;i++){
int t3=t1+t2;
System.out.print(t3+" ");
t1=t2;
t2=t3;}
return 0;
};
Scanner sc = new Scanner(System.in);
System.out.print("Enter the integer n: ");
int n=sc.nextInt();
f.apply(n);
}}
OUTPUT:

RESULT:
Thus the java program using lambda expression was executed successfully and output was
verified.

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Ex no:8.2
PROGRAM USING LAMBDA EXPRESSION
Date:

Question:
Write a Java program for the generation of OTP (One Time Password) as 6-digit number using
Supplier interface. Use random () method to generate the OTP.

Aim:
To write a java program that generates OTP using Supplier Interface

Program/Source Code:
package Module1;
import java.util.function.Supplier;
import java.util.Random;
public class OTP {
public static void main(String[] args)
{
Supplier<Integer> OTP=()->new Random().nextInt(900000)+100000;
System.out.println("OTP(One Time PassWord) : "+OTP.get());
}
}

OUTPUT:

RESULT:
Thus the java program using lambda expression was executed successfully and output was
verified.

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Ex no:8.3
PROGRAM USING LAMBDA EXPRESSION
Date:

Question:
Generate a secure random password in Java using Supplier interface.
The criteria for a valid password:
• The length of the password should be eight characters.
• The first and last character should be capital letters.
Aim:
To write a java program that generates password using Supplier Interface.

Program/Source Code:
package Module3;

import java.util.Random;
import java.util.function.Supplier;
import java.util.*;
public class generatePassword{
public static void main(String[] args)
{ Supplier<String>passwordSupplier=()-
>{
String upp="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lower=upp.toLowerCase();
String alp=upp+lower;
Random random=new Random();
StringBuilder password=new StringBuilder();
char first=alp.charAt(random.nextInt(alp.length()));
char last=alp.charAt(random.nextInt(alp.length()));
password.append(first);
for(int i=1;i<=6;i++) {
char c=alp.charAt(random.nextInt(alp.length()));
password.append(c);}
password.append(last);
return password.toString();};
String password=passwordSupplier.get();
System.out.println("Generated Password:"+password);}}
OUTPUT:

RESULT:
Thus the java program using lambda expression was executed successfully and output was
verified.

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Ex no:8.4
PROGRAM USING LAMBDA EXPRESSION
Date:

Question:
Write a Java program to create a list of strings and convert lowercase letters to uppercase letters
using stream map () function.
Aim:
To write a java program to create list of strings and convert them to uppercase letters.

Program/Source Code:
package Module1;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class StringListConversion
{ public static void main(String args[])
{
List<String> list =Arrays.asList("shinchan","doremon","apple","java");
List<String> upper = list.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println("Original List : "+list);
System.out.println("Uppercase List : "+upper);
}
}

OUTPUT:

RESULT:
Thus the java program using lambda expression was executed successfully and output was
verified.

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Ex no:9.1
PROGRAMS USING STREAMS
Date:

Question:
Write a Java program to demonstrate working of Stream.
• Create ArrayList emp that will store list of employee objects.
• Display the employee objects whose salary is less than 10000. (Hint: Use stream,
filter concepts).
• Increment 2000 for the employee who is getting the salary less than 5000 using map.
• Sort the employee based on the salary in descending order (i.e highest salary should
come on top).

Aim:
To write java program to create arraylist employee and display the list using filters.
Program/Source Code:
package Module1;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Arrays;
import java.util.stream.Collectors;
class Emp{
private int empId;
private String empName;
private int salary;

public Emp(int empId, String empName,int


salary){ this.empId=empId;
this.empName=empName; this.salary=salary;}
public int getEmpId(){
return empId;}
public void setEmpId(int
empId){ this.empId=empId;}
public String
getEmpName(){ return
empName;}
public void setEmpName(String
empName){ this.empName=empName;}
public int getSalary(){
return salary;}

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


public void setSalary(int
salary){ this.salary=salary;}
public String toString(){
return "EmpId :"+getEmpId()+" EmpName: "+getEmpName()+" salary: "+getSalary();}}
public class TestEmp {
public static void main(String args[])
{
List<Emp> emp = new ArrayList<>();
Emp e1= new Emp(101,"Lucy",12000);
Emp e2= new Emp(102,"Zaara",20000);
Emp e3= new Emp(103,"Anelia",3000);
emp.addAll(Arrays.asList(e1,e2,e3));

System.out.println("Employees with less than 10000");


emp.stream().filter(e->e.getSalary()<10000).forEach(System.out::println);

System.out.println("Increasing the salary 2000 who got less than 5000");


emp.stream().filter(e->e.getSalary()<5000).forEach(e->e.setSalary(e.getSalary()+2000));

List<Emp> sortedBySalaryDesc = emp.stream()


.sorted(Comparator.comparingInt(Emp::getSalary).reversed())
.collect(Collectors.toList());

System.out.println("\nEmployees sorted by salary in descending order:");


sortedBySalaryDesc.forEach(System.out::println);
}
}
OUTPUT:

RESULT:
Thus the java program using lambda expression was executed successfully and output was
verified.

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Ex no:9.2
PROGRAMS USING STREAMS
Date:

Question:
Implement following UML diagram and Write a Java program for Comparison Based Stream
Operations using below requirements.

Aim:
To write a java program to create Student list and sort the list based on cgpa .
Program/Source Code:
package Module1;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.ArrayList;
class Student
{ private int id;
private String name;
private double cgpa;
public Student(int id,String name,double cgpa)
{ this.id=id;
this.name=name;
this.cgpa=cgpa;}
public int getId()
{ return this.id;}
public void setId(int id) { this.id=id;}
public String getName()
{ return this.name;}
public void setString(String name)
{ this.name=name;}
public double getCgpa()
{ return this.cgpa;}
public void setCgpa(double cgpa)
{ this.cgpa=cgpa;}
@Override

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


public String toString() {
return "Student[ID="+this.getId()+",Name="+this.getName()+",cgpa="+this.getCgpa()+"]";}}
public class TestStudent {
public static void main(String
args[]){ List<Student> stu = new
ArrayList<>(); Student s1 = new
Student(101,"Dore",9.04);
Student s2 = new Student(102,"Mechan",8.95);
Student s3 = new Student(103,"Mickey",8.05);
stu.addAll(Arrays.asList(s1,s2,s3));
System.out.println("Displaying student list");
stu.forEach(System.out::println);
List<Student> sort = stu.stream()
.sorted(Comparator.comparingDouble(Student::getCgpa)).collect(Collectors.toList());
System.out.println("\nAfter sorting the student list based on CGPA");
sort.forEach(System.out::println);
double maxCGPA =
sort.stream().mapToDouble(Student::getCgpa).max().orElse(Double.MIN_VALUE);
double minCGPA =
sort.stream().mapToDouble(Student::getCgpa).min().orElse(Double.MAX_VALUE);
System.out.println("\nMaximum CGPA : "+maxCGPA);
System.out.println("Minimum CGPA : "+minCGPA);}}
OUTPUT:

RESULT:
Thus the java program using lambda expression was executed successfully and output was
verified.

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Ex no:10
PROGRAMS USING FILTERS
Date:

Question:
Create a LinkedList and add 100 random numbers. Find and display number which is
divisible by 8 from LinkedList. Count the numbers which is divisible by 11. (Hint: Use
stream, filter, count concepts).
Aim:
To write a java program that generates list of 100 numbers and display the number divisible by 8.
Program/Source Code:
package Module1;
import java.util.List;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
public class StreamRandom{
public static void main(String args[]){
List<Integer> ls = newArrayList<>();
int i;
Random r = new Random();
for(i=0;i<100;i++){
ls.add(r.nextInt());}
List<Integer> divide8 = ls.stream().filter(val -> val%8==0).toList();
divide8.forEach(System.out::println);
long divide11 = ls.stream().filter(val -> val%11==0).count();
System.out.println("Total Numbers divided by 11 : "+divide11);}}
OUTPUT:

RESULT:
Thus the java program using lambda expression was executed successfully and output was
verified.

21PE04-ADVANCED JAVA PROGRAMMING 717822P339-PRIYA.C


Register Number Course Code/Title

Name of the Name of the


Student Evaluator

Excellent Very Good Acceptable Considerable Below Expectations


Criterion Weightage
(5) (4) (3) (2) (1)

Capability of
Entire procedures are Most of procedures are Some of Few of procedures No procedures are
writing Procedure /
5 written clearly. written clearly. procedures are are written clearly. written.
Drawing Flow
written
Chart undoubtedly.
Some experiments
Capability of All experiments are Some experiments are are written Major errors in Experiments are not
writing program / written precisely written accurately. accurately and experiment writing. written/wrong
5
Constructing based on the question. minor errors in the experiment written.
circuits program.
Represent all data
Validation of 5 appropriately. Finding Partly outputs are found. Minor parts of Major part of output Wrong output/no
Output of results are clear. output are found. not found. output found.

Overall Completion 100% target has been 75% target has been 50% target has been 25% target has been Less than 25% target
of experiments in 5 completed. completed. completed. completed. has been completed.
Lab

Submission of Lab
Completion of Proper Time (i.e.) in next Very poor
Record in proper time
Record 5 lab session, with proper Poor presentation. presentation. Late Submission.
but not with proper
documentation.
documentation.

Signature of the Evaluator with date


Date

Exp No 10
Criterion

Capability of writing Procedure /


Drawing Flow Chart

Capability of writing program /


Constructing circuits

Validation of Output

Overall Completion of
experiments in Lab

Completion of Record

Total Marks (out of 25)

Faculty Signature

You might also like