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

JAVA LAB MANUAL Stu

The document provides 10 Java programs with their code to perform tasks like finding roots of a quadratic equation, finding the sum of digits of a number, finding the sum of N numbers, reversing a number, counting odd-even and positive-negative numbers in an array, using multilevel inheritance to create vehicle classes, using compile time polymorphism to find area of shapes, using runtime polymorphism to dispatch methods, performing linear search on an array, and sorting an array using selection sort.

Uploaded by

Gnana Sekhar
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)
42 views

JAVA LAB MANUAL Stu

The document provides 10 Java programs with their code to perform tasks like finding roots of a quadratic equation, finding the sum of digits of a number, finding the sum of N numbers, reversing a number, counting odd-even and positive-negative numbers in an array, using multilevel inheritance to create vehicle classes, using compile time polymorphism to find area of shapes, using runtime polymorphism to dispatch methods, performing linear search on an array, and sorting an array using selection sort.

Uploaded by

Gnana Sekhar
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/ 77

1.

FIND THE ROOTS OF THE QUADRATIC EQUATION

PROGRAM:

import java.util.*;
public class Example
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int a;
System.out.println("enter the a value");
a=s.nextInt();
int b;
System.out.println("enter the b value");
b=s.nextInt();
int c;
System.out.println("enter the c value");
c=s.nextInt();
double temp1 = Math.sqrt(b * b - 4 * a * c);
double root1 = (-b + temp1) / (2*a) ;
double root2 = (-b - temp1) / (2*a) ;
System.out.println("The roots of the Quadratic Equation \"2x2 + 6x + 4 = 0\" are "+root1+"
and "+root2);
}
}

OUTPUT:

1
RESULT:

2
2. FIND THE SUM OF DIGITS

PROGRAM:
import java.util.Scanner;
public class Digit
{
public static void main(String args[])
{
int m, n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
m = s.nextInt();
while(m > 0)
{
n = m % 10;
sum = sum + n;
m = m / 10;
}
System.out.println("Sum of Digits:"+sum);
}
}

OUTPUT:

3
RESULT:

4
3. FIND THE SUM OF ‘N’ NUMBERS
PROGRAM:
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int i, n, sum=0, num;
Scanner scan = new Scanner(System.in);

System.out.print("How many Number You want to Enter to Add them ? ");


n = scan.nextInt();

System.out.print("Enter " +n+ " numbers : ");


for(i=0; i<n; i++)
{
num = scan.nextInt();
sum = sum + num;
}
System.out.print("Sum of all " +n+ " numbers is " +sum);
}
}

OUTPUT:

5
RESULT:

6
4. REVERSE THE GIVEN NUMBER

PROGRAM:
import java.util.Scanner;
 class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;
System.out.println("Enter the number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
System.out.println("Reverse of entered number is "+reverse);
}
}

OUTPUT:

7
RESULT:

5. FIND THE COUNT OF ODD-EVEN


NUMBERS AND NEGATIVE-POSITIVE NUMBERS

AIM:

ALGORITHM:

8
PROGRAM:
import java.util.Scanner;
public class Examples
{
public static void main (String[] args)
{
int i,x,a[] = new int[10];
int n=0,p=0,e=0,o=0;
Scanner input = new Scanner(System.in);
for(i=0;i<5;i++) {
System.out.println("Enter Number :");
a[i] = input.nextInt();
}
for(i=0;i<5;i++) {
if(a[i]<0)
n++;
else
p++;
x=a[i]%2;
if(x==0)
e++;
else
o++;
}

9
System.out.println("Total Even Numbers = "+e);
System.out.println("Total Odd Numbers = "+o);
System.out.println("Total Negative Numbers = "+n);
System.out.println("Total Positive Numbers = "+p);
}
}
OUTPUT:

RESULT:

6. CREATE CLASS VEHICLE AND DERIVE SUBCLASS USING


MULTILEVEL INHERITANCE
AIM:

ALGORITHM:

10
PROGRAM:
import java.util.*;
class Vehicle
{
String color;
int speed;
int size;
void attributes()
{
System.out.println("Color : " + color);
System.out.println("Speed : " + speed);
System.out.println("Size : " + size);
}
}
class Car extends Vehicle
{
int gears;
void attributescar()
{
System.out.println("Color of Car : " + color);
System.out.println("Speed of Car : " + speed);
System.out.println("Size of Car : " + size);
System.out.println("No of gears of Car : " + gears);
}
}
public class Test {

11
public static void main(String args[]) {
Car b1 = new Car();
b1.color = "Blue";
b1.speed = 200 ;
b1.size = 22;
b1.gears = 5;
b1.attributescar();
}
}
OUTPUT:

RESULT:

7. FIND AREA OF DIFFERENT

SHAPES USING COMPILE TIME POLYMORPHISM


AIM:

ALGORITHM:

12
PROGRAM:

import java.util.*;

class overload

void area(float x)

System.out.println("The area of square is "+Math.pow(x,2)+"sq.units");

void area(float x , float y)

System.out.println("The area of Rectangle is "+x*y+"sq.units");

void area1(double r)

double z=3.14*r*r;

System.out.println("The area of circle "+z+"sq.units");

class polymorphism

public static void main(String[] args)

overload s=new overload();

s.area(5);

13
s.area(5,6);

s.area1(5);

OUTPUT

RESULT:

8. DISPATCH METHOD USING RUNTIME POLYMORPHISM

AIM

ALGORITHM

14
PROGRAM

import java.io.*;
class A
{
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A
{
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A
{
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch{
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A

15
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
OUTPUT

D:\p1>javac Dispatch.java

D:\p1>java Dispatch

Inside A's callme method

Inside B's callme method

Inside C's callme method

D:\p1>

RESULT

9. SEARCH ELEMENT IN GIVEN ARRAY USING LINEAR


SEARCH
AIM:

ALGORITHM:

16
PROGRAM:

import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();

for (c = 0; c < n; c++)


{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}

17
}
if (c == n) /* Element to search isn't present */
System.out.println(search + " isn't present in array.");
}
}
OUTPUT:

RESULT:

10. SORT THE ELEMENT IN A GIVEN

ARRAY USING SELECTION SORT TECHNIQUES


AIM:

ALGORITHM:

18
PROGRAM:

import java.util.Scanner;

public class Sort

public static void main(String args[])

int size, i, j, temp;

int arr[] = new int[50];

Scanner scan = new Scanner(System.in);

System.out.print("Enter Array Size : ");

size = scan.nextInt();

System.out.print("Enter Array Elements : ");

for(i=0; i<size; i++)

arr[i] = scan.nextInt();

System.out.print("Sorting Array using Selection Sort Technique..\n");

for(i=0; i<size; i++)

for(j=i+1; j<size; j++)

19
{

if(arr[i] > arr[j])

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

System.out.print("Now the Array after Sorting is :\n");

for(i=0; i<size; i++)

System.out.print(arr[i]+ " ");

OUTPUT:

20
RESULT:

11. COUNT THE NUMBER OF WORDS IN A STRING AND THE


NUMBER OF CHARACTERS IN EACH WORD
AIM:

ALGORITHM:

21
PROGRAM:

import java.util.*;

class CountWord{

static void count(String str)

// Create an char array of given String

char[] ch = str.toCharArray();

for (int i = 0; i < ch.length; i++) {

// Declare an String with empty initialization

String s = "";

// When the character is not space

while (i < ch.length && ch[i] != ' ') {

// concat with the declared String

s = s + ch[i];

i++;

if (s.length() > 0)

System.out.println(s + "->" + s.length());

22
}

public static void main(String[] args)

String str ="Life is Beautiful";

count(str);

OUTPUT:

RESULT:

12. FIND INDEX OF CHARACTERS


AIM:

ALGORITHM:

23
PROGRAM:

import java.util.*;

public class IndexofExample{

public static void main(String args[]) {

String str1 = new String("This is a BeginnersBook tutorial");

String str2 = new String("Beginners");

String str3 = new String("Book");

String str4 = new String("Books");

System.out.println("Index of B in str1: "+str1.indexOf('B'));

System.out.println("Index of B in str1 after 15th char:"+str1.indexOf('B', 15));

System.out.println("Index of B in str1 after 30th char:"+str1.indexOf('B', 30));

System.out.println("Index of string str2 in str1:"+str1.indexOf(str2));

System.out.println("Index of str2 after 15th char"+str1.indexOf(str2, 15));

System.out.println("Index of string str3:"+str1.indexOf(str3));

System.out.println("Index of string str4"+str1.indexOf(str4));

System.out.println("Index of harcoded string:"+str1.indexOf("is"));

System.out.println("Index of hardcoded string after 4th char:"+str1.indexOf("is", 4));

OUTPUT:

24
RESULT:

13. FIND LENGTH, REPLACE, CONCATENATE AND UPPERCASE


CONVERSION OF GIVEN STRING
AIM:

ALGORITHM:

25
PROGRAM:

import java.util.*;

public class Example

public static void main(String[] args)

String str="count me";

System.out.println(str.length());

System.out.println(str.replace('m','M'));

System.out.println(str.toUpperCase());

String str1="Java";

String str2=str1.concat("Programming");

System.out.println(str2);

26
OUTPUT:

RESULT:

14. MAINTAIN THE STUDENTS RECORD USING ARRAYLIST


CLASS
AIM:

ALGORITHM:

27
PROGRAM:

import java.util.*;

class arraylist

public static void main(String[] args)

ArrayList<String>obj=new ArrayList<String>();

obj.add("Name: User");

obj.add("Branch: CSE");

obj.add("Reg.no: 19171****");

System.out.println("Student Information\n"+obj);

OUTPUT:

28
RESULT:

15. MAINTAIN THE BANK RECORDS USING HASHTABLE


AIM:

ALGORITHM:

29
PROGRAM

import java.util.*;

class Hash

public static void main(String args[])

Map<Integer,String> cust=new Hashtable<Integer,String>();

cust.put(101,"A");

cust.put(102,"b");

cust.put(103,"d");

System.out.println("Record are"+cust);

cust.remove(102);

System.out.println("after removing"+cust);

System.out.println(cust.size());

30
OUTPUT:

RESULT:

16. INSERTING, APPENDING AND REVERSING THE ELEMENTS


USING ITERATOR
AIM

ALGORITHM

31
PROGRAM

import java.util.*;
public class IteratorDemo
{
public static void main(String args[])
{
// Create an array list
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// Use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}

32
System.out.println();
// Modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}

OUTPUT

D:\javac IteratorDemo.java

D:\java IteratorDemo

Original contents of al: C A E B D F

Modified contents of al: C+ A+ E+ B+ D+ F+

33
Modified list backwards: F+ D+ B+ E+ A+ C+

D:\

RESULT

17. DIVIDING THE NUMBER BY ZERO


AIM:

ALGORITHM:

34
PROGRAM

import java.util.*;

public class Zero

public static void main(String[] args)

try

int number = 100/0;

}catch(Exception e)

System.out.println("Caught Exception while trying to divide 100 by zero :


"+e.toString());

35
OUTPUT:

RESULT:

Hence the java program for dividing number by zero is executed successfully

18. EXCEPTION HANDLING USING MULTIPLE CATCH STATEMENTS

AIM:

36
ALGORITHM:

PROGRAM:

import java.util.*;
class Exceptions
{
public static void main(String args[])
{
int a[]={5,10};
int b=5,y;
try
{
int x=a[2 ] / b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index error");
}
catch(ArrayStoreException e){

37
System.out.println("Wrong data Type");
}
y=a[1]/a[0];
System.out.println("y= " +y);
}
}
OUTPUT:

RESULT:

19. CREATE THE MULTIPLE THREADS IN A SINGLE PROGRAM


USING JOIN METHOD

AIM:

38
ALGORITHM:

PROGRAM:

import java.util.*;

class TestJoinMethod1 extends Thread

public void run()

for(int i=1;i<=5;i++)

try

Thread.sleep(500);

catch(Exception e)

System.out.println(e);

39
System.out.println(i);

public static void main(String args[])

TestJoinMethod1 t1=new TestJoinMethod1();

TestJoinMethod1 t2=new TestJoinMethod1();

TestJoinMethod1 t3=new TestJoinMethod1();

t1.start();

try

t1.join();

catch(Exception e){

System.out.println(e);

t2.start();

t3.start();

OUTPUT:

40
RESULT:

20. SET AND GET THE NAME FOR THE MULTIPLE THREADS
AIM:

41
ALGORITHM:

PROGRAM:

import java.io.*;

class ThreadNaming extends Thread


{
     
    ThreadNaming(String name)
    {
        
        super(name);
    }
 
    public void run()
    {
        System.out.println("Thread is running.....");
    }
}
 
class GFG
{
    public static void main (String[] args)
    {
        ThreadNaming t1 = new ThreadNaming("Saveetha");
        ThreadNaming t2 = new ThreadNaming("Java");
         

42
        System.out.println("Thread 1: " + t1.getName());
        System.out.println("Thread 2: " + t2.getName());
         
        t1.start();
        t2.start();
    }
}

OUTPUT:

RESULT:

21. SET AND GET THE PRIORITY FOR THE MULTIPLE

THREADS

43
AIM:

ALGORITHM:

PROGRAM:

import java.lang.*;
 
class ThreadDemo extends Thread
{
    public void run()
    {
        System.out.println("Inside run method");
    }
 
    public static void main(String[]args)
    {
        ThreadDemo t1 = new ThreadDemo();
        ThreadDemo t2 = new ThreadDemo();
        ThreadDemo t3 = new ThreadDemo();
 
        System.out.println("t1 thread priority : " +
                              t1.getPriority());
        System.out.println("t2 thread priority : " +
                              t2.getPriority());
        System.out.println("t3 thread priority : " +
                              t3.getPriority());
 

44
        t1.setPriority(2);
        t2.setPriority(5);
        t3.setPriority(8);
 
  
        System.out.println("t1 thread priority : " +
                              t1.getPriority()); 
        System.out.println("t2 thread priority : " +
                              t2.getPriority());
        System.out.println("t3 thread priority : " +
                              t3.getPriority()); 
        System.out.print(Thread.currentThread().getName());
        System.out.println("Main thread priority : "
                       + Thread.currentThread().getPriority());
 
        Thread.currentThread().setPriority(10);
        System.out.println("Main thread priority : "
                       + Thread.currentThread().getPriority());
    }
}
OUTPUT:

RESULT:

22. IMPLEMENT WITHDRAW AND DEPOSIT OPERATION FOR BANK


USING SYNCHRONIZATION AND INTER-THREAD
COMMUNICATION

45
AIM

ALGORITHM

PROGRAM

class Customer{
int amount=10000;

synchronized void withdraw(int amount)


{
System.out.println("going to withdraw...");

if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{
wait();
}
catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw completed...");
System.out.println(amount);

46
}

synchronized void deposit(int amount)


{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class TestIC{
public static void main(String args[]){
final Customer c=new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();

}
}

OUTPUT:
D:\javac TestIC.java
D:\java TestIC
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...
15000
D:\

RESULT

23. FINDING LARGEST ELEMENT FOR DIFFERENT TYPES


USING BOUNDED TYPE PARAMETERS IN GENERICS

47
AIM

ALGORITHM

PROGRAM

import java.io.*;

public class MaximumTest

// determines the largest of three Comparable objects

public static <T extends Comparable<T>> T maximum(T x, T y, T z) {

T max = x; // assume x is initially the largest

if(y.compareTo(max) > 0) {

max = y; // y is the largest so far

if(z.compareTo(max) > 0) {

max = z; // z is the largest now

48
}

return max; // returns the largest object

public static void main(String args[])

System.out.printf("Max of %d, %d and %d is %d\n\n",

3, 4, 5, maximum( 3, 4, 5 ));

System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",6.6, 8.8, 7.7,


maximum( 6.6, 8.8, 7.7 ));

System.out.printf("Max of %s, %s and %s is %s\n","pear","apple", "orange",


maximum("pear", "apple", "orange"));

OUPUT

D:\javac MaximumTest.java

D:\java MaximumTest

Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

Max of pear, apple and orange is pear

D:\

RESULT

24. WRITE AND READ THE BYTES USING FILEINPUTSTREAM


AND FILEOUTPUT STREAM CLASS
AIM:

49
ALGORITHM:

Program-1

Program-2

PROGRAM 1:

import java.io.FileOutputStream;

public class FileOutputStreamExample

public static void main(String args[])

try

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

50
fout.write(65);

fout.close();

System.out.println("success...");

catch(Exception e)

System.out.println(e);

PROGRAM 2:

import java.io.FileInputStream;

public class DataStreamExample

public static void main(String args[])

try {

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=fin.read();

System.out.print((char)i);

fin.close();

}catch(Exception e){System.out.println(e);}

OUTPUT 1:

51
OUTPUT 2:

RESULT:

25. WRITE AND READ THE STRING USING FILEINPUTSTREAM


AND FILEOUTPUT STREAM CLASS
AIM:

52
ALGORITHM:

Program-1

Program-2

PROGRAM1:

import java.io.FileOutputStream;

public class FileOutputStreamExample

public static void main(String args[])

try

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

String s="Welcome to javaclass.";

53
byte b[]=s.getBytes();//converting string into byte array

fout.write(b);

fout.close();

System.out.println("success...");

catch(Exception e)

System.out.println(e);

PROGRAM 2:

import java.io.FileInputStream;
public class DataStreamExample
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}
fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT 1:

54
OUTPUT 2:

RESULT:

26. WRITE A COMMON DATA TO DIFFERENT FILES USING


CHARARRAYWRITER CLASS
AIM:

55
ALGORITHM:

PROGRAM:

import java.util.*;

public class CharArrayWriterExample

public static void main(String args[])throws Exception

CharArrayWriter out=new CharArrayWriter();

out.write("Welcome to javaTpoint");

FileWriter f1=new FileWriter("D:\\a.txt");

FileWriter f2=new FileWriter("D:\\b.txt");

FileWriter f3=new FileWriter("D:\\c.txt");

FileWriter f4=new FileWriter("D:\\d.txt");

out.writeTo(f1);

out.writeTo(f2);

out.writeTo(f3);

out.writeTo(f4);

56
f1.close();

f2.close();

f3.close();

f4.close();

System.out.println("Success...");

OUTPUT:

RESULT:

27. CREATE THE USERNAME AND GET THE PASSWORD USING


CONSOLE CLASS
AIM:

57
ALGORITHM:

Program-1:

Program-2

PROGRAM 1:

import java.io.Console;

class User{

public static void main(String args[]){

Console c=System.console();

System.out.println("Enter your name: ");

String n=c.readLine();

System.out.println("Welcome "+n);

58
}

PROGRAM 2:

import java.io.Console;

class ReadPasswordTest{

public static void main(String args[]){

Console c=System.console();

System.out.println("Enter password: ");

char[] ch=c.readPassword();

String pass=String.valueOf(ch);//converting char array into string

System.out.println("Password is: "+pass);

OUTPUT 1:

59
OUTPUT 2:

RESULT:

60
28. COUNT THE NUMBER OF CHARACTERS, WORDS AND
LINES FROM THE FILE USING STREAM I/O

AIM

ALGORITHM

PROGRAM

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class WordCountInFile


{
public static void main(String[] args)
{
BufferedReader reader = null;

//Initializing charCount, wordCount and lineCount to 0

61
int charCount = 0;

int wordCount = 0;

int lineCount = 0;

try
{
//Creating BufferedReader object
reader = new BufferedReader (new FileReader("D:\\p1\\sample.txt"));

//Reading the first line into currentLine

String currentLine = reader.readLine();

while (currentLine != null)


{
//Updating the lineCount

lineCount++;

//Getting number of words in currentLine

String[] words = currentLine.split(" ");

//Updating the wordCount

wordCount = wordCount + words.length;

//Iterating each word

for (String word : words)


{

62
//Updating the charCount

charCount = charCount + word.length();


}

//Reading next line into currentLine

currentLine = reader.readLine();
}

//Printing charCount, wordCount and lineCount

System.out.println("Number Of Chars In A File : "+charCount);

System.out.println("Number Of Words In A File : "+wordCount);

System.out.println("Number Of Lines In A File : "+lineCount);


}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close(); //Closing the reader
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

63
}

OUPUT

D:\javac WordCountInFile.java

D:\java WordCountInFile

Number Of Chars In A File : 49

Number Of Words In A File : 8

Number Of Lines In A File : 2

D:\

RESULT

64
29. JDBC CONNECTIVITY - STUDENT DATABASE
AIM:

To write a java program for JDBC connectivity of student database

ALGORITHM:

 Start
 Create a jdbc class
 Load the driver using class.forName()
 Create connections using DriverManager.getConnection()
 Create the statements using createStatment()
 Execute the query
 Using Resultset object display the details of student
 Close the connections
 Stop

PROGRAM :

import java.sql.*;

class FirstExample

public static void main(String[] args)

Connection conn = null;

Statement stmt = null;

try

Class.forName("com.mysql.jdbc.Driver");

System.out.println("Connecting to database...");

conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Emp","root","manuel28");

System.out.println("Creating statement...");

stmt = conn.createStatement();

String sql;

65
sql = "SELECT id, first, last, age FROM Employees";

ResultSet rs = stmt.executeQuery(sql);

while(rs.next())

int id = rs.getInt("id");

int age = rs.getInt("age");

String first = rs.getString("first");

String last = rs.getString("last");

System.out.print("ID: " + id);

System.out.print(", Age: " + age);

System.out.print(", First: " + first);

System.out.println(", Last: " + last);

rs.close();

stmt.close();

conn.close();

catch(SQLException se)

se.printStackTrace();

catch(Exception e){

e.printStackTrace();

System.out.println("Goodbye!");

66
OUTPUT:

RESULT:

67
30. CREATE DIFFERENT GEOMETRIC SHAPE USING APPLETS
AIM:

ALGORITHM:

PROGRAM :

import java.applet.Applet;
import java.awt.*;
public class Graphics extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString(“welcome”,50,50);
g.drawLine(20,30,50,100);
g.drawRect(70,30,100,30);
g.fillRect(170,100,30,30);
g.drawOval(70,100,30,30);
g.setColor(Color.pink);
g.fillOvel(70,200,30,30);
g.drawArc(90,150,30,50,70,60);
g.fillArc(20,30,40,50,60,70);
}
}

68
OUTPUT:

RESULT:

69
31.CREATE A HOUSE SHAPE BY USING APPLETS
AIM:

ALGORITHM:

PROGRAM:
import java.applet.*;
public class house extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
int xs[]={100,160,220};
int ys[]={100,50,100};
polygon poly=new polygon(xs,ys,3);

g.fillpolygon(poly);
g.setColor(Color.white);
g.fillRect(145,160,30,60);
g.setColor(Color.yellow);
g.setLine(30,50,60,70);
g.setColor(Color.black);
g.fillRect(120,55,10,30);
}

70
OUTPUT:

RESULT:

71
32.EVENT HANDLING - MOUSE

AIM

ALGORITHM

PROGRAM

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Mouse extends Applet
implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)

72
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="NEC";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}
public void mouseDragged(MouseEvent m)
{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)

73
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}

D:\javac Mouse.java

D:\Appletviewer Mouse.java

OUTPUT

RESULT

74
33.SIMPLE APPLET APPLICATION – CREATING BIO DATA
FORM

AIM

ALGORITHM

PROGRAM

//Tes.java

import java.awt.*;

public class Tes extends java.applet.Applet

public void init()

setLayout(new FlowLayout(FlowLayout.LEFT));

add(new Label("Name :"));

add(new TextField(10));

75
add(new Label("Address :"));

add(new TextField(10));

add(new Label("Birthday :"));

add(new TextField(10));

add(new Label("Gender :"));

Choice gender = new Choice();

gender.addItem("Man");

gender.addItem("Woman");

Component add = add(gender);

add(new Label("Job :"));

CheckboxGroup job = new CheckboxGroup();

add(new Checkbox("Student", job, false));

add(new Checkbox("Teacher", job, false));

add(new Button("Register"));

add(new Button("Exit"));

//Tes.html

<html>

<head><title>Register</title></head>

76
<body>

<applet code="Tes.class" width=230 height=300></applet>

</body>

</html>

OUTPUT

D:/ javac Tes.java

D:/Appletviewer Tes.html

RESULT:

77

You might also like