0% found this document useful (0 votes)
0 views39 pages

Java Lab Programs

Java Lab programs for diploma Students

Uploaded by

Remya Sukumaran
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)
0 views39 pages

Java Lab Programs

Java Lab programs for diploma Students

Uploaded by

Remya Sukumaran
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
You are on page 1/ 39

1.

1 Install and Setup java environment

Step 1: Verify that it is already installed or not

Step 2: Download JDK and Install JDK

Click Next to continue


Just Choose Development Tools and click Next

Set up is being ready

Choose the Destination folder in which you want to install JDK. Click Next to continue with
the installation.
Set up is installing Java to the computer

We have successfully installed Java SE development kit 8. Close the installation set up.
Step 4 : Set the Permanent Path

Right click on "this PC". It can be named as "My Computer" in some systems. Choose
"properties" from the options
The screen looks like the above image will open. Click on "Advanced system settings" to
continue.

Above window will open. Click on "Environment Variables" to continue.

Enter "path" in variable name and enter the path to the bin folder inside your JDK in the
variable value. Click OK.
Now Java Path has been set up.
Open the Command prompt and type "javac".
The Java has been installed on our system. Now, we need to configure IDE Eclipse in order
to execute JavaFX applications
1.2 Install java editor (Eclipse for Enterprise Java) and configure workspace
Execution of first java program

Step 1:

Step 2:
Step 4:

Step 5:
Testing if eclipse is working well

Output
2.1 Code, execute and debug programs that uses different datatypes
public class DataTypes {

public static void main(String[] args) {


boolean result = true;
System.out.println("boolean type data: "+result);
char a = 'A';
System.out.println("char type data: "+a);
byte b=100;
System.out.println("byte type data: "+b);
short s=20000;
System.out.println("short type data: "+s);
int i= 400000000;
System.out.println("int type data: "+i);
long l=6000000000000000000l;
System.out.println("long type data: "+l);
float f=234.567f;
System.out.println("float type data: "+f);
double d= 1234.65768;
System.out.println("double type data: "+d);
String str="Java is a programming language";
System.out.println("String type data: "+str);
}
}
Output:
boolean type data: true
char type data: A
byte type data: 100
short type data: 20000
int type data: 400000000
long type data: 6000000000000000000
float type data: 234.567
double type data: 1234.65768
String type data: Java is a programming language

2.2 Code, execute and debug programs that uses different types of variables
public class StudentDetails {

String stdName; //non static variable


static long phoneNo; //static variable
public static void main(String[] args) {
int stdId = 101; // local variable
StudentDetails s1 = new StudentDetails();
s1.stdName = "Hari";
phoneNo=9876543210l;
System.out.println(stdId+" "+s1.stdName+" "+phoneNo);

}
}
Output:
101 Hari 9876543210
3.1 Code, execute and debug programs that uses different types of constructors
a. Default Constructor
package mypack;
public class Hello {
public static void main(String[] args) {
System.out.println("Hello class has a default constructor");
}
}
Output:
Hello class has a default constructor

b. Non Parameterized Constructor


package mypack;
public class HelloWorld {
String name;
HelloWorld() {
this.name="HelloWorld class has non parameterized
constructor";
}
public static void main(String[]args) {
HelloWorld obj=new HelloWorld();
System.out.println(obj.name);
}
}
Output:
HelloWorld class has non parameterized constructor

c. Parameterized Constructor
public class StudentDetails {
String studName;
int studId;

StudentDetails(String name,int id) {


this.studName=name;
this.studId=id;
}

void details(){
System.out.println("ID: "+studId+" Name: "+studName);
}

public static void main(String[]args) {


StudentDetails s1=new StudentDetails("Rose",101);
StudentDetails s2=new StudentDetails("Lilly",102);
s1.details();
s2.details();
}
}
Output:
ID: 101 Name: Rose
ID: 102 Name: Lilly

d. Copy Constructor
public class Employee {
String empName;
Employee(String name){
this.empName = name;
}
Employee(Employee e) {
this.empName = e.empName;
}
void info(){
System.out.println("Name: "+empName);
}
public static void main(String[]args){
Employee emp1=new Employee("Abhi");
Employee emp2=new Employee(emp1);
emp1.info();
emp2.info();
}
}
Output:
Name: Abhi
Name: Abhi

3.2 Code, execute and debug programs that uses different to perform autoboxing
and unboxing
package myPack;
public class Boxing {
public static void main(String[] args) {
int a = 50;
Integer a1 = Integer.valueOf(a);//Boxing
Integer a2 = a;//AutoBoxing
System.out.println("a1 = "+a1);
System.out.println("a2 = "+a2);
}
}
Output:
a1 = 50
a2 = 50

package myPack;
public class UnBoxing {
public static void main(String[] args) {
Integer obj = new Integer(5);
int a = obj.intValue();//UnBoxing
int b = obj;//AutoUnBoxing
System.out.println("a = "+a);
System.out.println("b = "+b);
}
}
Output:
a = 5
b = 5

3.3 Code, execute and debug programs that uses different arithmetic operators.
Program to swap 2 variables using third variable
package myPack;
public class Swap {
public static void main(String[] args) {
int x=10;
int y=20;
System.out.println("Before swapping: x=" +x+", y="+ y);
x=x+y;
y=x-y;
x=x-y;
System.out.println("After swapping: x=" +x+", y="+y);
}
}
Output:
Before swapping: x=10, y=20
After swapping: x=20, y=10

Program to swap 2 variables without using third variable


package mypack;
public class Swap3 {
public static void main(String[] args) {
int x=10;
int y=20;
System.out.println("Before swapping: x=" +x+", y="+ y);
int temp=x;
x=y;
y=temp;
System.out.println("After swapping: x=" +x+", y="+y);
}
}
Output:
Before swapping: x=10, y=20
After swapping: x=20, y=10

Program to find largest of 3 numbers using ternary operator


package myPack;
public class Ternary {
public static void main(String[] args) {
int a=45, b=57, c=34, result;
result = a>b ? (a>c ? a:c):(b>c ? b:c);
System.out.println("The greatest number = "+result);
}
}
Output:
The greatest number = 57

4.1 Install memory monitoring tool and observe how JVM allocates memory
Step 1 Step2

Step 3
4.2 Memory allocation explanation through the program
package mypack;
public class Demo {
public static void main(String[] args) throws Throwable {
Demo2 de=new Demo2();
de.finalize();
de=null;
System.gc();
System.out.println("Inside the main method");
}
protected void finalize() {
System.out.println("Object is destroyed by the garbage
collector");
}
}
Output:
Object is destroyed by the garbage collector
Object is destroyed by the garbage collector
Inside the main method
5.1 Code, execute and debug programs that uses different control statements.
IF – ELSE
package mypack;
public class EvenOdd {
public static void main(String args[]) {
int num=5;
if(num%2==0)
System.out.println(num + " is an even number");
else
System.out.println(num + " is an odd number");
}
}
Output:
5 is an odd number

SWITCH CASE
package mypack;
public class Month {
public static void main(String[] args) {
int month=13;
switch (month) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
case 4:
System.out.println("April");
break;
case 5:
System.out.println("May");
break;
case 6:
System.out.println("June");
break;
case 7:
System.out.println("July");
break;
case 8:
System.out.println("August");
break;
case 9:
System.out.println("September");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("November");
break;
case 12:
System.out.println("December");
break;
default:
System.out.println("No month");
}
}
}
Output:
No month

FOR LOOP
package mypack;
public class ForLoopExample {
public static void main(String[] args) {
// Using a for loop to print numbers from 1 to 10
for (int i = 1; i <= 10; i++)
System.out.print(i + " ");
}
}
Output:
1 2 3 4 5 6 7 8 9 10

WHILE LOOP
package mypack;
import java.util.Scanner;
public class CountDigits {
public static void main(String[] args) {
System.out.println("Enter the number");
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
int count=0;
while(num>0) {
num/=10;
count++;
}
System.out.println("The number of digits in given number
is "+count);
sc.close();
}
}
Output:
Enter the number
123
The number of digits in given number is 3
DO WHILE LOOP
package mypack;
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number;
// Prompt the user to enter a number
do {
System.out.print("Enter a number (negative to exit): ");
number = sc.nextInt();
System.out.println("You entered: " + number);
} while (number >= 0); // Continue until a negative number
is entered

System.out.println("Exiting the loop. You entered a negative


number.");
sc.close(); // Close the scanner to prevent resource leaks
}
}
Output:
Enter a number (negative to exit): 2
You entered: 2
Enter a number (negative to exit): -56
You entered: -56
Exiting the loop. You entered a negative number.

NESTED FOR LOOP


package mypack;
public class NestedFor {
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++)
System.out.print("*");
System.out.println();
}
}
}
Output:
*
**
***
****

6.1 Code, execute and debug program that uses encapsulation concept.
package mypack;
public class Encapsulation {
private int id;
private String name;
public void setId(int id) {
this.id=id;
}
public void setName(String name) {
this.name=name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}

package mypack;
public class Encapsulation1 {
public static void main(String[] args) {
Encapsulation e=new Encapsulation();
e.setId(254);
e.setName("Uday");
System.out.println(("ID: " +e.getId());
System.out.println("Name: " + e.getName());
}
}
Output:
ID: 254
Name: Uday

6.2 Define class & implement simple calculator and check compliance with
SRP.
ADDITION CLASS
package calculator;
public class Addition {
public void performAddition(int num1,int num2) {
int result = num1+num2;
System.out.println("Sum of 2 numbers "+result);
}
}

SUBTRACTION CLASS
package calculator;
public class Subtraction {
public void performSubtraction(int num1,int num2) {
int result = num1-num2;
System.out.println("Difference of 2 numbers "+result);
}
}

MULTIPLICATION CLASS
package calculator;
public class Multiplication {
public void performMultiplication(int num1,int num2) {
int result = num1*num2;
System.out.println("Product of 2 numbers "+result);
}
}

DIVISION CLASS
package calculator;
public class Division {
public void performDivision(int num1,int num2) {
int result = num1/num2;
System.out.println("Quotient of 2 numbers "+result);
}
}

CALCULATOR CLASS
package calculator;
import java.util.Scanner;

public class Calculator {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter 2 numbers ");
int num1=sc.nextInt();
int num2=sc.nextInt();

Addition add=new Addition();


add.performAddition(num1,num2);

Subtraction sub=new Subtraction();


sub.performSubtraction(num1,num2);
Multiplication mul=new Multiplication();
mul.performMultiplication(num1,num2);

Division div=new Division();


div.performDivision(num1,num2);
sc.close();
}

Output:
Enter 2 numbers
800
40
Sum of 2 numbers 840
Difference of 2 numbers 760
Product of 2 numbers 32000
Quotient of 2 numbers 20
7.1 Code, execute and debug programs that uses array concept
public class MatrixAddition {
public static void main(String[] args) {
// Initialize and declare matrices
int[][] a = { {1, 2, 3}, {3, 4, 5}, {5, 6, 7} };
int[][] b = { {1, 1, 1}, {2, 2, 2}, {3, 3, 3} };
//creating another matrix to store sum of 2 matrices
int[][] c = new int[3][3]; // sum of 3x3 matrix is 3x3

// Calculate sum of matrices and display result


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
c[i][j] = a[i][j] + b[i][j];
System.out.print(c[i][j]+ " ");
}
System.out.println();
}
}
}
Output:
2 3 4
5 6 7
8 9 10

7.2 Code, execute and debug programs to perform string manipulation.


import java.util.Scanner;
public class Palindrome {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String original = sc.nextLine();
String reverse = "";
for(int i = original.length()-1; i>=0; i--)
reverse+=original.charAt(i);
if (original.equalsIgnoreCase(reverse))
System.out.println(original + " is a palindrome.");
else
System.out.println(original + " is not a
palindrome.");
sc.close();
}
}

Output:
Enter a string: Level
Level is a palindrome.
8.1 Code, execute and debug programs that uses inheritance concept
Single Level Inheritance
First class
package singleLevelInheritance;
public class A {
public void print_A() {
System.out.println("The method print_A is in class A");
}
}
Second class
public class B extends A{
public void print_B() {
System.out.println("The method print_B is in class B");
}
}
Main class
public class Main {
public static void main(String[] args) {
A obj = new A();
obj.print_A();
//obj.print_B(); Compile time error since parent class
cannot access child class member
B obj1 = new B();
obj1.print_B(); //child class accessing it's own member
obj1.print_A();//child class accessing parent class
member
}
}
Output:
The method print_A is in class A
The method print_B is in class B
The method print_A is in class A
Multi Level Inheritance
First class
package multiLevelInheritance;
//Grandparent class
public class A {
public void print_A() {
System.out.println("The method print_A is in class A");
}
}
Second class
//Parent class
public class B extends A{
public void print_B() {
System.out.println("The method print_B is in class B");
}
}
Third class
//Child class
public class C extends B{
public void print_C() {
System.out.println("The method print_C is in class C");
}
}
Main class
public class Main {
public static void main(String[] args) {
A obj = new A();
obj.print_A();

B obj1 = new B();


obj1.print_B();
obj1.print_A();

C obj2 = new C();


obj2.print_C();
obj2.print_B();
obj2.print_A();
}
}
Output:
The method print_A is in class A
The method print_B is in class B
The method print_A is in class A
The method print_C is in class C
The method print_B is in class B
The method print_A is in class A
Hierarchical Inheritance
First class
package hierarchicalInheritance;
//Parent class
public class A {
public void print_A() {
System.out.println("The method print_A is in class A");
}
}
Second class
//Child1 class
public class B extends A{
public void print_B() {
System.out.println("The method print_B is in class B");
}
}
Third class
//Child2 class
public class C extends A{
public void print_C() {
System.out.println("The method print_C is in class C");
}
}
Main class
public class Main {
public static void main(String[] args) {
A obj = new A();
obj.print_A();

B obj1 = new B();


obj1.print_B();
obj1.print_A();

C obj2 = new C();


obj2.print_C();
obj2.print_A();
}
}
Output:
The method print_A is in class A
The method print_B is in class B
The method print_A is in class A
The method print_C is in class C
The method print_A is in class A
Multiple Inheritance
First interface
package multipleInheritance;
public interface A {
public void print_A();
}
Second interface
public interface B {
public void print_B();
}
Third class
public class C implements A,B{
public void print_A() {
System.out.println("print_A from interface A is
implemented in class C");
}
public void print_B() {
System.out.println("print_B from interface B is
implemented in class C");
}
public void print_C() {
System.out.println("print_C is in class C");
}
}
Main class
public class Main {

public static void main(String[] args) {


A obj = new C();
obj.print_A();
B obj1 = new C();
obj1.print_B();
C obj2 = new C();
obj2.print_C();
obj2.print_B();
obj2.print_A();
}
}
Output:
print_A from interface A is implemented in class C
print_B from interface B is implemented in class C
print_C is in class C
print_B from interface B is implemented in class C
print_A from interface A is implemented in class C

8.2 Design a class & implement file parser and check compliance with OCP.
package ocp;
Arithmetic Interface
public interface Arithmetic {
double perform(double a, double b);
}

Addition class
public class Addition implements Arithmetic{
@Override
public double perform(double a, double b) {
return a + b;
}
}

Subtraction class
public class Subtraction implements Arithmetic {
@Override
public double perform(double a, double b) {
return a - b;
}
}

Calculator class
public class Calculator {
public double calculate(Arithmetic arithmetic, double a,
double b)
{
return arithmetic.perform(a, b);
}
}

Main Class
public class Main {

public static void main(String[] args) {


Calculator obj = new Calculator();
System.out.println( obj.calculate(new Addition(), 10,
20));
System.out.println(obj.calculate(new Subtraction(), 10,
20));
}
}

Output:
30.0
-10.0
9.1 Code, execute and debug programs that uses static binding
package polymorphism;

public class MethodOverloading {


public int add(int a, int b) {
System.out.print("Method with two integer parameters called ");
return a + b;
}

public int add(int a, int b, int c) {


System.out.print("Method with three integer parameters called ");
return a + b + c;
}

public double add(double a, double b) {


System.out.print("Method with two double parameters called ");
return a + b;
}

public static void main(String[] args) {


MethodOverloading calc = new MethodOverloading();

System.out.println(calc.add(5, 10));
System.out.println(calc.add(5, 10, 15));
System.out.println(calc.add(5.5, 10.5));
}
}
Output:
Method with two integer parameters called 15
Method with three integer parameters called 30
Method with two double parameters called 16.0
9.2 Code, execute and debug programs that uses dynamic binding
package polymorphism;
Animal class
public class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
Dog class
public class Dog extends Animal{
@Override
public void makeSound() {
System.out.println("Dog barks");

}
}
Cat class
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat meows");
}
}
Cow class
class Cow extends Animal {
@Override
public void makeSound() {
System.out.println("Cow moos");
}
}
Main class
public class Main {
public static void main(String[] args) {
// Animal reference but Dog object
Animal animal1 = new Dog();
// Animal reference but Cat object
Animal animal2 = new Cat();
// Animal reference but Cow object
Animal animal3 = new Cow();

animal1.makeSound();
animal2.makeSound();
animal3.makeSound();
}
}
Output:
Dog barks
Cat meows
Cow moos
10.1 Code, execute and debug programs that uses abstract class to achieve
abstraction

package abstraction;
Abstract class
public abstract class Demo {
abstract public void m1();
public void m2() {
System.out.println("m2 is in abstract Demo class");
}
}

Concrete class
public class Sample extends Demo {
@Override
public void m1() {
System.out.println("m1 is in concrete Sample class");
}
public static void main(String[] args) {
Demo d = new Sample();
d.m1();
d.m2();
}
}
Output:
m1 is in concrete Sample class
m2 is in abstract Demo class
10.2 Code, execute and debug programs that uses interface to achieve
abstraction

package abstraction;
Interface
public interface DemoInterface {
abstract public void m1();
abstract public void m2();
}

Class
public class SampleTest implements DemoInterface{

@Override
public void m1() {
System.out.println("m1 is implemented in SampleTest
concrete class");
}

@Override
public void m2() {
System.out.println("m2 is implemented in SampleTest
concrete class");
}

public static void main(String []args) {


DemoInterface di = new SampleTest();
di.m1();
di.m2();
}
}
Output:
m1 is implemented in SampleTest concrete class
m2 is implemented in SampleTest concrete class
11.1 Code, execute and debug programs in java to handle checked and
unchecked exceptions

Example for Unchecked Exception


public class UnCheckedException {

public static void main(String[] args) {


System.out.println("Statement 1");
try {
int[] a = new int[3];
a[3]=30;
}
catch(ArithmeticException e) {
System.out.println("ArithmeticException occurred");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutofBoundsException
occurred");
}
catch(Exception e) {
System.out.println("Exception occurred");
}
finally {
System.out.println("In finally block");
}
System.out.println("Statement 2");
}

}
Output:
Statement 1
ArrayIndexOutofBoundsException occurred
In finally block
Statement 2

Example for checked Exception

package exceptions;
import java.io.FileInputStream;

public class CheckedException {


public static void main(String[] args) {
FileInputStream fin = new
FileInputStream("C://myfile.txt");
int k;
while((k=fin.read())!=-1)
System.out.println((char)k);
fin.close();
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException

11.2 Code, execute and debug programs in java to read the content of the file
and write the content to another file

import java.io.*;

public class HandlingFile {


public static void main(String[] args) throws Exception{
String path="C:\\Users\\Remya\\Desktop\\";

File f1 = new File(path+"hello.txt");


File f2 = new File(path+"helloworld.txt");
OutputStream fout = new FileOutputStream(f2);
fout.close();

FileWriter fw = new FileWriter(f2);


FileReader fr = new FileReader(f1);

int i;
while((i = fr.read())!=-1)
fw.write(i);
System.out.println("File is written successfully");
fr.close();
fw.close();
}
}
Output: File is written successfully
12 Design an interface & implement it like one that builds different types of
toys and check compliance with ISP.

First interface
public interface Toy {
void setPrice(double price);
void setColor(String color);
}

Second interface
public interface Movable {
void move();
}

Third interface
public interface Flyable {
void fly();
}

House Class
public class ToyHouse implements Toy {
double price;
String color;
@Override
public void setPrice(double price) {
this.price=price;
}
@Override
public void setColor(String color) {
this.color=color;
}
@Override
public String toString() {
return "ToyHouse- Price: "+price+" Color: "+color;
}
}
Car Class
public class ToyCar implements Toy, Movable{
double price;
String color;
@Override
public void setPrice(double price) {
this.price=price;
}

@Override
public void setColor(String color) {
this.color=color;
}

@Override
public void move() {
System.out.println("ToyCar : Start moving car");

@Override
public String toString() {
return "ToyCar Movable- Price: "+price+" Color: "+color;
}
}
Plane Class
public class ToyPlane implements Toy, Movable, Flyable{

double price;
String color;
@Override
public void setPrice(double price) {
this.price=price;
}

@Override
public void setColor(String color) {
this.color=color;
}

@Override
public void move() {
System.out.println("ToyPlane : Start moving plane");
}

@Override
public void fly() {
System.out.println("ToyPlane : Start flying plane");
}

@Override
public String toString() {
return "ToyPlane Movable and Flyable- Price: "+price+"
Color: "+color;
}
}

ToyBuilder Class
public class ToyBuilder {
public static ToyHouse buildToyHouse() {
ToyHouse toyHouse = new ToyHouse();
toyHouse.setPrice(15.00);
toyHouse.setColor("Green");
return toyHouse;
}

public static ToyCar buildToyCar() {


ToyCar toyCar = new ToyCar();
toyCar.setPrice(25.00);
toyCar.setColor("Red");
toyCar.move();
return toyCar;
}

public static ToyPlane buildToyPlane() {


ToyPlane toyPlane = new ToyPlane();
toyPlane.setPrice(125.00);
toyPlane.setColor("White");
toyPlane.move();
toyPlane.fly();
return toyPlane;
}
}

ToyBuilder Main Class


public class ToyBuilderTest {

public static void main(String[] args) {


ToyHouse toyHouse = ToyBuilder.buildToyHouse();
System.out.println(toyHouse);
ToyCar toyCar = ToyBuilder.buildToyCar();
System.out.println(toyCar);
ToyPlane toyPlane = ToyBuilder.buildToyPlane();
System.out.println(toyPlane);

}
Output:

ToyHouse- Price: 15.0 Color: Green


ToyCar : Start moving car
ToyCar Movable- Price: 25.0 Color: Red
ToyPlane : Start moving plane
ToyPlane : Start flying plane
ToyPlane Movable and Flyable- Price: 125.0 Color: White
13. Code, execute and debug programs to connect to database through JDBC
and perform basic DB operation

mysql> create database test1;


Query OK, 1 row affected (0.23 sec)
mysql> use test1;
Database changed
mysql> create table Student(ID int, Name varchar(255), Dept varchar(255));
Query OK, 0 rows affected (0.46 sec)

mysql> show tables;


+-----------------+
| Tables_in_test1 |
+-----------------+
| student |
+-----------------+
1 rows in set (0.16 sec)

mysql> insert into student (ID,Name,Dept) values (1,'Abhishek','CS');


Query OK, 1 row affected (0.17 sec)

mysql> insert into student (ID,Name,Dept) values (2,'Ajay','CS');


Query OK, 1 row affected (0.04 sec)

mysql> insert into student (ID,Name,Dept) values (3,'Anitha','CS');


Query OK, 1 row affected (0.07 sec)

mysql> insert into student (ID,Name,Dept) values (4,'Anjali','CS');


Query OK, 1 row affected (0.08 sec)

mysql> insert into student (ID,Name,Dept) values (5,'Anushree','CS');


Query OK, 1 row affected (0.02 sec)

mysql> select * from student;


+------+----------+------+
| ID | Name | Dept |
+------+----------+------+
| 1 | Abhishek | CS |
| 2 | Ajay | CS |
| 3 | Anitha | CS |
| 4 | Anjali | CS |
| 5 | Anushree | CS |
+------+----------+------+
import java.sql.*;

public class JDBC {

static final String DB_URL =


"jdbc:mysql://localhost:3306/test1";

static final String USER = "root";


static final String PASS = "root";
static final String QUERY = "SELECT * FROM Student";
public static void main(String[] args) {
// Open a connection
try {
Connection conn = DriverManager.getConnection(DB_URL,
USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY); // Extract data
from result set
while (rs.next()) { // Retrieve by column name
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Name: " + rs.getString("name")
+"\t");
System.out.print(", Dept: " + rs.getString("dept")
+"\n");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}

Output:
ID: 1, Name: Abhishek , Dept: CS
ID: 2, Name: Ajay , Dept: CS
ID: 3, Name: Anitha , Dept: CS
ID: 4, Name: Anjali , Dept: CS
ID: 5, Name: Anushree , Dept: CS

You might also like