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

Labsheets of JavaFullStack

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)
10 views

Labsheets of JavaFullStack

Uploaded by

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

Labsheet 1

//JAVA 8 NEW FEATURES


//1. FUNCTIONAL INTERFACE
/* functional interface is an interface that consists exactly one
* abstract method. Unlike interface we can keep n number of abstract
* methods in an interface before java 8.
* Lambda expression is not applicable before java 8 other than
* functional interface
* @FunctionalInterface is used to declare an intterface as functional
* There will be many (apis to be used) open source libraries
* which consists of functional interface instead of interface.
Example Runnable , Clonable, Serializable, ActionListener
These are functional and marker interface
*/

//2. LAMDA EXPRESSION


//3. STREAM METHODS FOR COLLECTION
// create an interface with three methods , refactor it using functional
//interface
@FunctionalInterface
interface myinterface1 {
void method1();

}
@FunctionalInterface
interface myinterface2 {
void method2();

}
@FunctionalInterface
interface myinterface3 {
void method3();

}
//partial implementation of interface is not allowed before java8

public class TEST1 {

public static void main(String[] args) {


// object creation
//polymorphism or loose-coupling approach
myinterface1 R1=()->{
System.out.println(" method1 implemented in anonymous class1");
};
myinterface2 R2=()->{
System.out.println(" method2 implemented in anonymous class1");
};
myinterface3 R3=()->{
System.out.println(" method3 implemented in anonymous class1");
};
R1.method1();
R2.method2();
R3.method3();
R1=()->{
System.out.println("Method1 implemented in anonymous class2");
};
R2=()->{
System.out.println("Method2 implemented in anonymous class2");
};

R3=()->{
System.out.println("Method3 implemented in anonymous class2");
};
R1.method1();
R2.method2();
R3.method3();

Labsheet 2
import java.util.Scanner;

//create a functional interface shape to implement a method


// area() to print area of circle and square.
//use lambda expression
@FunctionalInterface
interface shape {
void area();
}
public class TEST2 {

public static void main(String[] args) {


shape r = ()->{
int radious;
double a;
Scanner sc = new Scanner(System.in);
System.out.println("Enter radious");
radious=sc.nextInt();
a=3.141*radious*radious;
System.out.println("area of anonymous circle is "+a);
};
r.area();
r=()-> {
int side;
double a;
Scanner sc = new Scanner(System.in);
System.out.println("Enter side");
side=sc.nextInt();
a=side*side;
System.out.println("area of anonymous square is "+a);
};
r.area();
}

Labsheet 3
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.stream.Collectors;
//LIST INTERFACE METHODS WITH ArrayList (IMPLEMENTED CLASS)
//there are 2 kinds of list to keep objects
//1. generic list to hold objects of primitive types-heterogeneous
//2. specific list to hold objects for both type(primitive and custom)-homogeneous
public class TEST3 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(7);
list.add(15);
list.add(42);
//how to check List created above
//List allows duplicates , preserves the insertion order
System.out.println(list);//possible bcz of toString()
//how to print objects inside the list object
System.out.println("using for-each");
for(Integer i:list) {
System.out.println(i);
}
System.out.println("using iterator");
ListIterator<Integer> itr=list.listIterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
//insert at begin , end and any position
System.out.println(list);
list.add(0,100);
System.out.println(list);
list.add(5,200);
System.out.println(list);
list.add(3,300);
System.out.println(list);
//delete object from list
list.remove(0);
System.out.println(list);
Integer ob = new Integer(200);
list.remove(ob);
System.out.println(list);
//searching an object
ob=new Integer(7);
if( list.contains(ob))
System.out.println("Present");
else
System.out.println("Not Present");
//find index of an object
System.out.println(list.indexOf(ob));
System.out.println("printing few elements......");
//printing few objects from the list
for (int i=0;i<=2;i++) {
System.out.println(list.get(i));
}

//soring in default/natural order


//sorting specific-primitive list
Collections.sort(list);
System.out.println("After sorting");
System.out.println(list);
list.add(19);
list.add(24);
list.add(53);
list.add(76);
System.out.println(list);
//filter only the odd integer objects from the above list
System.out.println("printing odd elements");
for(Integer i:list) {
if(i%2!=0)
System.out.println(i);
}
//create a separate list to hold all odd objects
List<Integer> oddlist=new ArrayList<Integer>();
for(Integer i:list) {
if(i%2!=0)
oddlist.add(i);
}

//LambdaExpression
oddlist= list.stream().filter(e->e%2!=0).collect(Collectors.toList());
System.out.println("Printing odd list...");
System.out.println(oddlist);
System.out.println(list);
boolean res=list.stream().allMatch(e->e%5==0);
System.out.println(res);
res=list.stream().anyMatch(e->e%5==0);
System.out.println(res);
res=list.stream().noneMatch(e->e%5==0);
System.out.println(res);

int greatest=list.stream().max((x,y)->Integer.compare(x, y)).get();


System.out.println("Greatest element in the list "+greatest);
int smallest=list.stream().min((x,y)->Integer.compare(x, y)).get();
System.out.println("Smallest element in the list "+smallest);
//try with method reference
long count=list.stream().count();
System.out.println("No. of objects "+count);
}
}

Labsheet 4
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ListIterator;

//List for custom objects


//pojo-plain old java object (legacy)
//constructor, setter and getter toString()
//equals() and hashCode()
class Student {
private int id;
private String name;
private double cgpa;
//shift alt s
public Student(int id, String name, double cgpa) {
this.id = id;
this.name = name;
this.cgpa = cgpa;
}
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getCgpa() {
return cgpa;
}
public void setCgpa(double cgpa) {
this.cgpa = cgpa;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", cgpa=" + cgpa + "]";
}
}

public class TEST4 {


public static void main(String[] args) {
//creating a list of custom student object
List<Student> studentlist=new ArrayList<Student>();
studentlist.add(new Student(389,"rohan",7.8));
studentlist.add(new Student(401,"dileep",8.6));
studentlist.add(new Student(388,"thousif",9.4));
studentlist.add(new Student(342,"upendra",8.3));
studentlist.add(new Student(609,"laxmi",7.9));
studentlist.add(new Student(712,"chandana",7.4));
studentlist.add(new Student(245,"shruthi",8.2));
studentlist.add(new Student(1,"asmita",8.6));
studentlist.add(new Student(75,"madiha",8.8));
studentlist.add(new Student(94,"rajkumar",7.8));
studentlist.add(new Student(742,"thasmay",5.8));
studentlist.add(new Student(729,"pavani",7.9));
studentlist.add(new Student(736,"vamshika",9.4));
studentlist.add(new Student(716,"srihitha",7.8));
studentlist.add(new Student(789,"harshitha",8.3));
//Displaying the list at a time
System.out.println("list as one object");
System.out.println(studentlist);
//Displaying objects present in the list
System.out.println("through forEach loop");
for(Student s:studentlist) {
System.out.println(s);
}
//Displaying through forEach
System.out.println("through forEach method");
studentlist.stream()
.forEach(x->System.out.println(x));
//Displaying through iterator
System.out.println("through list iterator");
ListIterator<Student> itr=studentlist.listIterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
//insert delete search
studentlist.add(0,new Student(765,"anjaneya",7));
studentlist.add(16,new Student(105,"pavan",7.2));
studentlist.add(10,new Student(749,"priya",8.8));
System.out.println(studentlist);
studentlist.remove(0);
System.out.println(studentlist);
studentlist.remove(new Student(749,"priya",8.8));
System.out.println(studentlist);
if(studentlist.contains(new Student(749,"priya",8.8)))
System.out.println("is present in the list");
else
System.out.println("is not present in the list");

//binary search
int p=Collections.binarySearch
(studentlist,new Student(342,"upendra",8.3),(x,y)-
>Integer.compare(x.getId(), y.getId()));
System.out.println("is present in the list at "+p+" index");
//binary search returns index of the object from a sorted collection
Student ob1=new Student(101,"amith",7.5);
Student ob2=new Student(100,"nithin",7.8);
Student ob3=new Student(102,"sreekanth",7.4);
Student ob4=new Student(109,"supriya",7.3);

List<Student> secondlist=new ArrayList<Student>();


secondlist.add(ob1);secondlist.add(ob2);secondlist.add(ob3);
System.out.println("second list "+secondlist);
Collections.sort(secondlist,(x,y)->Integer.compare(x.getId(), y.getId()));
int index=Collections.binarySearch(secondlist, ob4,(x,y)->Integer.compare(x.getId(),
y.getId()));//-1-p
System.out.println(index);
//sort by id
Collections.sort(studentlist,(x,y)->Integer.compare(x.getId(), y.getId()));
System.out.println("Ascending by id"+studentlist);
//sort by name
Collections.sort(studentlist,
(x,y)->x.getName().compareTo(y.getName()));
System.out.println("Ascending by name"+studentlist);
//sort by cgpa
Collections.sort(studentlist,
(x,y)->Double.compare(x.getCgpa(), y.getCgpa()));
System.out.println("Ascending by cgpa"+studentlist);

//sort by id
Collections.sort(studentlist,
(x,y)->Integer.compare(y.getId(), x.getId()));
System.out.println("Descending by id"+studentlist);
//sort by name
Collections.sort(studentlist,
(x,y)->y.getName().compareTo(x.getName()));
System.out.println("Descending by name"+studentlist);
//sort by cgpa
Collections.sort(studentlist,
(x,y)->Double.compare(y.getCgpa(), x.getCgpa()));
System.out.println("Descending by cgpa"+studentlist);
// sort using method reference
}
}
TestSpot1
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

class PicnicSpot {
String name;
double distance;
boolean hotelAndRestaurantAvailability;
double reviews;

public PicnicSpot(String name, double distance, boolean hotelAndRestaurantAvailability, double


reviews) {
this.name = name;
this.distance = distance;
this.hotelAndRestaurantAvailability = hotelAndRestaurantAvailability;
this.reviews = reviews;
}
//add getter and setter

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getDistance() {


return distance;
}

public void setDistance(double distance) {


this.distance = distance;
}

public boolean isHotelAndRestaurantAvailability() {


return hotelAndRestaurantAvailability;
}

public void setHotelAndRestaurantAvailability(boolean hotelAndRestaurantAvailability) {


this.hotelAndRestaurantAvailability = hotelAndRestaurantAvailability;
}

public double getReviews() {


return reviews;
}

public void setReviews(double reviews) {


this.reviews = reviews;
}
@Override
public String toString() {
return "PicnicSpot{" +
"name='" + name + '\'' +
", distance=" + distance +
", hotelAndRestaurantAvailability=" + hotelAndRestaurantAvailability +
", reviews=" + reviews +
'}';
}
}

public class PicnicSpotsAnalyzer {


public static void main(String[] args) {
// Creating a List of PicnicSpot objects
List<PicnicSpot> picnicSpots = new ArrayList<>();
picnicSpots.add(new PicnicSpot("Beach", 10.5, true, 4.2));
picnicSpots.add(new PicnicSpot("Mountain", 25.0, false, 4.5));
picnicSpots.add(new PicnicSpot("Park", 5.2, true, 4.0));
picnicSpots.add(new PicnicSpot("Lake", 15.8, false, 4.8));
picnicSpots.add(new PicnicSpot("Forest", 30.3, false, 4.1));

// Find the best spot as per distance


PicnicSpot bestSpotByDistance = picnicSpots.stream()
.min((x,y)->Double.compare(x.getDistance(),y.getDistance())).get();
System.out.println("Best spot as per distance: " + bestSpotByDistance);

// Find the best spot as per reviews


PicnicSpot bestSpotByReviews = picnicSpots.stream()
.max((x,y)->Double.compare(x.getReviews(),y.getReviews())).get();

System.out.println("Best spot as per reviews: " + bestSpotByReviews);

// Find the best spot as per hotel availability


PicnicSpot bestSpotByHotelAvailability = picnicSpots.stream()
.filter(x->x.isHotelAndRestaurantAvailability())
.findFirst()
.orElse(null);
System.out.println("Best spot as per hotel availability: " + bestSpotByHotelAvailability);
}
}

TestSpot2
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
class Hotel {
private String name;
private double dist_from_location;
private double charges;
private double reviews;

public double getReviews() {


return reviews;
}
public void setReviews(double reviews) {
this.reviews = reviews;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getCharges() {
return charges;
}
public void setCharges(double charges) {
this.charges = charges;
}
public double getDist_from_location() {
return dist_from_location;
}
public void setDist_from_location(double dist_from_location) {
this.dist_from_location = dist_from_location;
}

public Hotel(String name, double dist_from_location, double charges, double reviews) {


super();
this.name = name;
this.dist_from_location = dist_from_location;
this.charges = charges;
this.reviews = reviews;
}
public Hotel() {
super();
}
@Override
public String toString() {
return "Hotel [name=" + name + ", dist_from_location=" + dist_from_location + ",
charges=" + charges
+ ", reviews=" + reviews + "]";
}

}
class PicnicSpot {
String name;
double distance;
List<Hotel> hotels;
double reviews;
//add constructor with field
public PicnicSpot(String name, double distance, List<Hotel> hotels, double reviews) {
super();
this.name = name;
this.distance = distance;
this.hotels = hotels;
this.reviews = reviews;
}

public PicnicSpot() {
super();
}

//add getter and setter


public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
public List<Hotel> getHotels() {
return hotels;
}
public void setHotels(List<Hotel> hotels) {
this.hotels = hotels;
}
public double getReviews() {
return reviews;
}
public void setReviews(double reviews) {
this.reviews = reviews;
}
//add toString
@Override
public String toString() {
return "PicnicSpot [name=" + name + ", distance=" + distance + ", hotels=" + hotels +
", reviews=" + reviews
+ "]";
}
}

public class PicnicSpotsAnalyzer {


public static void main(String[] args) {
List<Hotel> hotellist1=new ArrayList<Hotel>();
List<Hotel> hotellist2=new ArrayList<Hotel>();
List<Hotel> hotellist3=new ArrayList<Hotel>();
List<Hotel> hotellist4=new ArrayList<Hotel>();
List<Hotel> hotellist5=new ArrayList<Hotel>();
hotellist1.add(new Hotel("Taj",9,5000,4.6));
hotellist1.add(new Hotel("Mayfair",7,4500,4.1));
hotellist1.add(new Hotel("PalaceVilla",14,3500,3.4));
hotellist2.add(new Hotel("Tajmahal",9,5000,4));
hotellist2.add(new Hotel("Blue Lagoon",7,4500,5));
hotellist2.add(new Hotel("MysoreTemple",14,3500,2.3));
hotellist2.add(new Hotel("KingsNight",14,3500,3.5));
hotellist3.add(new Hotel("Taj",9,5000,5));
hotellist3.add(new Hotel("Mayfair",7,4500,4));
hotellist3.add(new Hotel("PalaceVilla",14,3500,2.8));
hotellist3.add(new Hotel("Tajmahal",9,5000,4.8));
hotellist4.add(new Hotel("Blue Lagoon",7,4500,3.5));
hotellist4.add(new Hotel("MysoreTemple",14,3500,4.0));
hotellist4.add(new Hotel("KingsNight",14,3500,2));
hotellist5.add(new Hotel("PalaceVilla",14,3500,5));
hotellist5.add(new Hotel("Tajmahal",9,5000,4));
hotellist5.add(new Hotel("Blue Lagoon",7,4500,4.7));
hotellist5.add(new Hotel("MysoreTemple",14,3500,3.5));
hotellist5.add(new Hotel("KingsNight",14,3500,2.9));

// Creating a List of PicnicSpot objects


List<PicnicSpot> picnicSpots = new ArrayList<PicnicSpot>();
picnicSpots.add(new PicnicSpot("Beach", 10.5, hotellist1, 4.2));
picnicSpots.add(new PicnicSpot("Mountain", 25.0, hotellist2, 4.5));
picnicSpots.add(new PicnicSpot("Park", 5.2, hotellist3, 4.0));
picnicSpots.add(new PicnicSpot("Lake", 15.8, hotellist4, 4.8));
picnicSpots.add(new PicnicSpot("Forest", 30.3, hotellist5, 4.1));

// Find the best spot as per distance and find the best hotel
// as per distance
Hotel bestHotelByDistance = picnicSpots.stream()
.min((x,y)->Double.compare(x.getDistance(),y.getDistance())).get()
.getHotels().stream()
.min((x,y)->Double.compare(x.getDist_from_location(), y.getDist_from_location()))
.get();
System.out.println("Best Hotel as per distance: " + bestHotelByDistance);
// Find the best spot as per distance and find the best hotel
// as per price
PicnicSpot best_spot_as_per_distance=
picnicSpots.stream().min((x,y)->Double.compare(x.getDistance(), y.getDistance()))
.get();
System.out.println("Best spot as per distance "+best_spot_as_per_distance);

Hotel best_hotel_as_per_price= best_spot_as_per_distance.getHotels().stream()


.min((x,y)->Double.compare(x.getCharges(), y.getCharges())).get();

System.out.println("Best hotel as per price "+best_hotel_as_per_price);

// Find the best spot as per reviews


PicnicSpot bestSpotByReviews = picnicSpots.stream()
.max((x,y)->Double.compare(x.getReviews(),y.getReviews())).get();

System.out.println("Best spot as per reviews: " + bestSpotByReviews);

// Find the best spot as per hotel availability

}
}

Labsheet 5
/*objective - prepare a table of entries
consists of customerid as key and List of product
selected to purchase are values

Define a Product

Map<String, List<Product>>
sunny123--------------> {hp laptop, }
*/
import java.util.*;
//pojo
class Product {
private String prodId;
private String prodName;
private String prodCategory;
private double prodPrice;
// add getter setter, constructor , toString, equals and hashCode
public String getProdId() {
return prodId;
}
public void setProdId(String prodId) {
this.prodId = prodId;
}
public String getProdName() {
return prodName;
}
public void setProdName(String prodName) {
this.prodName = prodName;
}
public String getProdCategory() {
return prodCategory;
}
public void setProdCategory(String prodCategory) {
this.prodCategory = prodCategory;
}
public double getProdPrice() {
return prodPrice;
}
public void setProdPrice(double prodPrice) {
this.prodPrice = prodPrice;
}
public Product(String prodId, String prodName, String prodCategory, double prodPrice) {
super();
this.prodId = prodId;
this.prodName = prodName;
this.prodCategory = prodCategory;
this.prodPrice = prodPrice;
}
public Product() {
super();
}
@Override
public String toString() {
return "Product [prodId=" + prodId + ", prodName=" + prodName + ",
prodCategory=" + prodCategory
+ ", prodPrice=" + prodPrice + "]";
}
@Override
public int hashCode() {
return Objects.hash(prodCategory, prodId, prodName, prodPrice);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
return Objects.equals(prodCategory, other.prodCategory) &&
Objects.equals(prodId, other.prodId)
&& Objects.equals(prodName, other.prodName)
&& Double.doubleToLongBits(prodPrice) ==
Double.doubleToLongBits(other.prodPrice);
}

}
public class Test5 {
public static void main(String[] args) {
List<Product> productList1 = new ArrayList<Product>();
productList1.add(new Product("pres101","Java Complete Reference","book",700));
productList1.add(new Product("pres109","Python","snake",1000));
productList1.add(new Product("pres1125","HP Laptop","Electronic",45000));
productList1.add(new Product("pres1199","Iphone","Electronic",150000));
List<Product> productList2 = new ArrayList<Product>();
productList2.add(new Product("pres101","Java Complete Reference","book",700));
productList2.add(new Product("pres1101","water bottles","Acessories",700));
productList2.add(new Product("pres1230","Jeans","Clothes",3000));
productList2.add(new Product("pres1199","Ihone","Electronic",150000));
productList2.add(new Product("pres101","Java Complete Reference","book",700));
List<Product> productList3 = new ArrayList<Product>();
productList3.add(new Product("pres230","Sotalol","medicine",200));
productList3.add(new Product("pres238","Carvedilol","medicine",700));
productList3.add(new Product("pres239","Aciclovir","medicine",70));
productList3.add(new Product("pres245","Pantoprazol","medicine",240));
productList3.add(new Product("pres289","Nitroglyserin","medicine",1000));
Map<String, List<Product>> table =
new HashMap<String,List<Product>>();
table.put("PUNIV00448", productList3);
table.put("PUNIV01690", productList1);
table.put("PUNIV00123", productList2);
//Display the details of table
for(Map.Entry<String,List<Product>> e:table.entrySet()) {
System.out.println(e.getKey()+"->"+e.getValue());
}
//Display the details by name of products
for(Map.Entry<String,List<Product>> e:table.entrySet()) {
System.out.print(e.getKey()+"->");
e.getValue().stream().forEach(x->
System.out.print(x.getProdName()+","));
System.out.println();
}

TestOneToMany
package JDBC;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;
import java.sql.*;

/*there are students from section 6cse5 , each students have


atleast 2 addresses , create a database to manage student
address information in MYSQL
*/
//create POJO for student and address
class Student {
private int id;
private String name;
private double cgpa;
// alt shift s
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getCgpa() {
return cgpa;
}
public void setCgpa(double cgpa) {
this.cgpa = cgpa;
}
public Student(int id, String name, double cgpa) {
super();
this.id = id;
this.name = name;
this.cgpa = cgpa;
}
public Student() {
super();
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", cgpa=" + cgpa + "]";
}
@Override
public int hashCode() {
return Objects.hash(cgpa, id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
return Double.doubleToLongBits(cgpa) == Double.doubleToLongBits(other.cgpa) && id ==
other.id
&& Objects.equals(name, other.name);
}

}
class Address {
private String HouseNumber;
private String postOffice;
private String district;
private String state;
private int pin;
private String mobileNumber;
private int sid;
public String getHouseNumber() {
return HouseNumber;
}
public void setHouseNumber(String houseNumber) {
HouseNumber = houseNumber;
}
public String getPostOffice() {
return postOffice;
}
public void setPostOffice(String postOffice) {
this.postOffice = postOffice;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getPin() {
return pin;
}
public void setPin(int pin) {
this.pin = pin;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public Address(String houseNumber, String postOffice, String district, String state, int pin,
String mobileNumber,
int sid) {
super();
HouseNumber = houseNumber;
this.postOffice = postOffice;
this.district = district;
this.state = state;
this.pin = pin;
this.mobileNumber = mobileNumber;
this.sid = sid;
}
public Address() {
super();
}
@Override
public String toString() {
return "Address [HouseNumber=" + HouseNumber + ", postOffice=" + postOffice + ",
district=" + district
+ ", state=" + state + ", pin=" + pin + ", mobileNumber=" +
mobileNumber + ", sid=" + sid + "]";
}
@Override
public int hashCode() {
return Objects.hash(HouseNumber, district, mobileNumber, pin, postOffice, sid,
state);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Address other = (Address) obj;
return Objects.equals(HouseNumber, other.HouseNumber) &&
Objects.equals(district, other.district)
&& Objects.equals(mobileNumber, other.mobileNumber) && pin == other.pin
&& Objects.equals(postOffice, other.postOffice) && sid == other.sid
&& Objects.equals(state, other.state);
}

}
//create a datasource object-singleton
interface StudentDAO {
public boolean create(String dbn,String user,String pwd);
public int insertStudent(Student s);
public int updateStudent(int id, Student s);
public int deleteStudent(int id);
public List<Student> fetchAllStudents();
public Student fetchAStudent(int id);
}
class StudentDAOImpl implements StudentDAO {
private Connection cts=null;
public static StudentDAOImpl ob=null;
public static StudentDAOImpl createObject() {
if(ob==null)
ob=new StudentDAOImpl();
return ob;
}
private StudentDAOImpl() {}
public boolean create(String dbn,String user,String pwd) {
boolean result=true;
try {
cts=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/"+dbn,user,pwd);
Class.forName("com.mysql.jdbc.Driver");
Statement st=cts.createStatement();
// result=st.execute("create table student(id int primary key, name varchar(30), cgpa
double)");

}catch(Exception e) {
System.out.println(e);
}
if(result==true) {
return true;
}
else {
return false;
}
}
public int insertStudent(Student s) {
int response=0;
try {
String sql="insert into student values(?,?,?)";
PreparedStatement p=cts.prepareStatement(sql);
p.setInt(1, s.getId());
p.setString(2, s.getName());
p.setDouble(3, s.getCgpa());
response=p.executeUpdate();
}catch(Exception e) {
System.out.println(e);
}
return response;
}
public int updateStudent(int id, Student s) {
int response=0;
try {
String sql="update student set cgpa=? where id=?";
PreparedStatement p=cts.prepareStatement(sql);
p.setDouble(1, s.getCgpa());
p.setInt(2, s.getId());
response=p.executeUpdate();
}catch(Exception e) {
System.out.println(e);
}
return response;

}
public int deleteStudent(int id) {
int response=0;
try {
String sql="delete from student where id=?";
PreparedStatement p=cts.prepareStatement(sql);
p.setInt(1, id);
response=p.executeUpdate();
}catch(Exception e) {
System.out.println(e);
}
return response;
}
public List<Student> fetchAllStudents(){
List<Student> response=new ArrayList<Student>();
try {
String sql="select * from student";
PreparedStatement p=cts.prepareStatement(sql);
ResultSet r=p.executeQuery();
Student s;
while(r.next()) {
s=new Student();
s.setId(r.getInt(1));
s.setName(r.getString(2));
s.setCgpa(r.getDouble(3));
System.out.println(s.getId());
response.add(s);
}
}catch(Exception e) {
System.out.println(e);
}
return response;
}
public Student fetchAStudent(int id) {
return null;
}
}
interface AddressDAO {
public boolean create(String dbn,String user,String pwd);
public int insertAddress(Address s);
public int updateAddress(String hn, Address s);
public int deleteAddress(String hn);
public List<Address> fetchAllAddresses();
public Address fetchAAddress(String hn);
}
class AddressDAOImpl implements AddressDAO {
public static AddressDAOImpl ob=null;
private Connection cta=null;
public static AddressDAOImpl createObject() {
if(ob==null)
ob=new AddressDAOImpl();
return ob;
}
private AddressDAOImpl() {}
public boolean create(String dbn,String user,String pwd) {
boolean result=false;
try {
cta=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/"+dbn,user,pwd);
Class.forName("com.mysql.jdbc.Driver");
Statement st=cta.createStatement();
String query="create table address(HouseNumber varchar(30) primary key, postofc
varchar(10), district varchar(10), state varchar(10), pin int, mobilenumber varchar(13),sid int, foreign
key(sid) references student(id))";
result=st.execute(query);

}catch(Exception e) {
System.out.println(e);
}
if(result==true) {
return true;
}
else {
return false;
}
}
public int insertAddress(Address s) {
return 1;
}
public int updateAddress(String hn, Address s) {
return 1;
}
public int deleteAddress(String hn) {
return 1;
}
public List<Address> fetchAllAddresses(){
return null;
}
public Address fetchAAddress(String hn) {
return null;
}
}

public class TESTONETOMANY {


static StudentDAOImpl ob=StudentDAOImpl.createObject();
public static int insertStudent(Student s) {
return( ob.insertStudent(s));

}
public static int updateStudent(int id,Student s) {
return (ob.updateStudent(id, s));

}
public static int deleteStudent(int id) {
return(ob.deleteStudent(id));

}
public static List<Student> fetchAllStudent() {

return (ob.fetchAllStudents());
}

public static void main(String[] args) {


ob.create("6cse5", "root", "sunil");
char repeat='y';
int ch=0;
Scanner sc=new Scanner(System.in);
do {
System.out.println("Student CRUD.........");
System.out.println("Enter choice 1 for insert ");
System.out.println("Enter 2 for update");
System.out.println("Enter 3 for delete");
System.out.println("Enter choice 4 for fetch");
ch=sc.nextInt();
switch(ch) {
case 1:
Student s=new Student();
s=new Student();
System.out.println("Enter Id");
int id=sc.nextInt();
System.out.println("Enter Name");
String n=sc.next();
System.out.println("Enter cgpa");
double c=sc.nextDouble();
s.setId(id);s.setName(n);
s.setCgpa(c);
int res= insertStudent(s);
System.out.println(res+" student inserted");
break;
case 2:
s=new Student();
System.out.println("Enter Id");
id=sc.nextInt();
System.out.println("Enter Name");
n=sc.next();
System.out.println("Enter cgpa");
c=sc.nextDouble();
s.setId(id);s.setName(n);
s.setCgpa(c);
res= updateStudent(566,s);
System.out.println(res+" student updated");
break;
case 3:
System.out.println("enter id");
id=sc.nextInt();
res=deleteStudent(id);
System.out.println(res+" student deleted");
break;
case 4:
List<Student> list=fetchAllStudent();
System.out.println(list);
break;

}while(repeat!='n');

System.out.println("Table student created Sucessfully");


// AddressDAOImpl obb=AddressDAOImpl.createObject();
// res=obb.create("6cse5", "root", "sunil");
//System.out.println("Table address created Sucessfully");

You might also like