Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

LAB MANUAL

1151CS302-JAVA PROGRAMMING LABORATORY


-LIST OF EXPERIMENTS:

1. Simple Java applications

- for understanding reference to an instance of a class (object), methods


- Handling Strings in Java
2. Constructors

-Implement constructor overloading.

3. Inheritance

- To Implement Method Overloading and Method Overriding.

4. Package creation.

- Developing user defined packages in Java


5. Interfaces

- Developing user-defined interfaces and implementation


- Use of predefined interfaces
6. Threading

- Creation of thread in Java applications


- Multithreading
7. Exception Handling Mechanism in Java

- Handling pre-defined exceptions


- Handling user-defined exceptions
8. AWT-To Create Different Layout Managers.

9. JDBC-To connect Oracle/MS Access for Table creation and Data Manipulation.

G. Learning Resources

i. Text Books

1.E. Balaguruswamy,Programming in java , Fourth Edition,TMH,2010.

2. PatricNaughton , Herbert Schildt, The Complete Reference “Java 2 “, Ninth edition


Tata McGraw Hills ,2014.

ii. Reference Books

1. H.M.Deitel and P.J.Deitel –“Java How to Program” Pearson Prentice Hall 6th Edition, 2011.

2. Sachinmalhotra, ”Programming in JAVA”, Oxford University Press, 2011.


3. Maydene Fisher, Jonathan Ellis, Jonathan Bruce,”JDBC Database access with java”
Addison-Wesley, Third Edition 2003

4. Bruce Eckel – “Thinking in Java” Pearson Prentice Hall Third Edition-2006

iii. Online Resources

1. docs.oracle.com/javaee/6/tutorial/doc/girgm.html
2. www.webreference.com/programming/java.html
3. www.apl.jhu.edu/~hall/java/Documentation.html
INDEX

EX.NO NAME OF THE EXPERIMENT

1(a) Employ Details – Class and Methods

1(b) Handling String Function

2 Constructors

3 Inheritance – Method overloading and Method overriding

4 Package creation

5
Interfaces

6 Threading
a) Creation of thread in Java applications
b) Multithreading

7 Exception Handling Mechanism in Java


a) Handling pre-defined exceptions
b) Handling user-defined exceptions
AWT-To Create Different Layout Managers.
8

9 JDBC-To connect Oracle/MS Access for Table creation and Data


Manipulation.
Exp_No: 1(a) Employee Details – Class and Methods

Aim:
To write a simple java application program for employee details for understanding reference to
an instance of a class (object), methods.

Algorithm
Step1: Start the program.
Step2: Declare all data members in employee class.
Step3: Define all member functions in employee class.
Step4: Create object for employee class.
Step5: call all the member functions and data members using object.
Step6: Display the result.
Step7: Stop the program.

Program

importjava.lang.*;

classemp

String name;

int id;

String address;

voidgetdata(String name,intid,String address)

this.name=name;

this.id=id;

this.address=address;

voidputdata()
{

System.out.println("Employee details are :");

System.out.println("Name :" +name);

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

System.out.println("Address :" +address);

classempdemo

public static void main(String arg[])

emp e=new emp();

e.getdata("smith",76859,"gulbarga");

e.putdata();

OUTPUT

Employee details are :

Name :smith

ID :76859

Address :Gulbarga

Conclusion
Thus the java program was successfully complied and executed and result also verified.
Exp_No: 1(b) Handling String Function

Aim:
To write a simple java application program for student details for handling String functions.
Algorithm
Step1: Start the program.
Step2. Import the lang package.
Step3. Get input string.
Step4. And do the String manipulation operation such as modification, search and etc., using
appropriate methods.
Step5. Display the results.
Step6. Stop the program.
Program
importjava.lang.String;

classstringdemo

public static void main(String arg[])

String s1=new String("gptgulbarga");

String s2="GPT GULBARGA";

System.out.println(" The string s1 is : " +s1);

System.out.println(" The string s1 is : " +s2);

System.out.println(" Length of the string s1 is : " +s1.length());

System.out.println(" The first accurence of r is at the position : " +s1.indexOf('r'));

System.out.println(" The String in Upper Case : " +s1.toUpperCase());

System.out.println(" The String in Lower Case : " +s1.toLowerCase());

System.out.println(" s1 equals to s2 : " +s1.equals(s2));

System.out.println(" s1 equals ignore case to s2 : " +s1.equalsIgnoreCase(s2));

int result=s1.compareTo(s2);

System.out.println("After compareTo()");

if(result==0)
System.out.println( s1 + " is equal to "+s2);

else if(result>0)

System.out.println( s1 + " is greather than to "+s2);

else

System.out.println( s1 + " is smaller than to "+s2);

System.out.println(" Character at an index of 6 is :" +s1.charAt(6));

String s3=s1.substring(4,12);

System.out.println(" Extracted substring is :"+s3);

System.out.println(" After Replacing g with a in s1 : " + s1.replace('g','a'));

String s4=" This is a book ";

System.out.println(" The string s4 is :"+s4);

System.out.println(" After trim() :"+s4.trim());

OUTPUT

The string s1 is :gptgulbarga

The string s1 is : GPT GULBARGA

Length of the string s1 is : 12

The first accurence of r is at the position : 9

The String in Upper Case : GPT GULBARGA

Conclusion
Thus the java program was successfully complied and executed and result also verified.
Exp_No: 2 Constructor

Aim:
To write a simple java application program for the following concept in Constructor over Loading.

Procedure
Step1: Open the notepad.
Step2. Then type the program in the notepad and save in our own folder <mainclassname>.java
Step3. Set the path: set path=” C:\Program Files\Java\jdk1.6.0_20\bin”;
Step4. Set the classpath: set classpath=”C:\Program Files\Java\jdk1.6.0_20\lib”;
Step4. Compile the source progam using javac <mainclassname.java>
Step5. Run the program using java <mainclassname>

Program

importjava.lang.*;

class student

String name;

intregno;

int marks1,marks2,marks3;

// null constructor

student()

name="raju";

regno=12345;

marks1=56;

marks2=47;

marks3=78;

// parameterized constructor
student(String n,intr,int m1,int m2,int m3)

name=n;

regno=r;

marks1=m1;

marks2=m2;

marks3=m3;

// copy constructor

student(student s)

name=s.name;

regno=s.regno;

marks1=s.marks1;

marks2=s.marks2;

marks3=s.marks3;

void display()

System.out.println(name + "\t" +regno+ "\t" +marks1+ "\t" +marks2+ "\t" + marks3);

}}

classstudentdemo

public static void main(String arg[])

{
student s1=new student();

student s2=new student("john",34266,58,96,84);

student s3=new student(s1);

s1.display();

s2.display();

s3.display();

OUTPUT

raju 12345 56 47 78

john 34266 58 96 84

raju 12345 56 47 78

Conclusion
Thus the java program was successfully complied and executed and result also verified.
Exp_No: 3 Inheritance

Aim:
To write a simple java application program for the following concept in Inheritance with overloading and
overriding methods.

Procedure
Step1: Open the notepad.
Step2. Then type the program in the notepad and save in our own folder <mainclassname>.java
Step3. Set the path: set path=” C:\Program Files\Java\jdk1.6.0_20\bin”;
Step4. Set the classpath: set classpath=”C:\Program Files\Java\jdk1.6.0_20\lib”;
Step4. Compile the source progam using javac <mainclassname.java>
Step5. Run the program using java <mainclassname>

Program

Method overriding

importjava.lang.*;
class A
{
void display()
{
System.out.println("This is from class A ");
}
}
class B extends A
{
void display()
{
System.out.println("This is from class B ");
}
}
class AB
{
public static void main(String arg[])
{
B obj=new B();
obj.display();
}
}
OUTPUT

This is from class B

Method Overloading

classDisplayOverloading

public void disp(char c)

System.out.println(c);

public void disp(char c, intnum)

System.out.println(c + " "+num);

class Sample

public static void main(String args[])

DisplayOverloadingobj = new DisplayOverloading();

obj.disp('a');

obj.disp('a',10);

}
Output

a 10

Conclusion
Thus the java program was successfully complied and executed and result also verified.
Exp-No: 4 Package Creation

Aim
To write a simple java application program for Create User Defined Packages in Java.

Procedure
Step1. Create new folder as a calculator in existing folder
Step2: Open the notepad.
Step3. Type the package program in notepad and save <classname>.java
Step4. Then type the main program in the notepad and save <mainclassname>.java
Step5. Compile the package program : javac foldername/classname.java
Step6. Compile the source progam using javac <mainclassname.java>
Step7. Run the program using java <mainclassname>

Program

package forest;
import java.util.*;
public class Tiger
{
public void getDetails(String nickName, int weight)
{
System.out.println("Tiger nick name is " + nickName);
System.out.println("Tiger weight is " + weight);
}
}

Target directory

import forest.Tiger;

public class Animal


{
public static void main(String args[])
{
Tiger t1 = new Tiger ();
t1.getDetails("Everest", 50);
}
}
OUTPUT

Tiger nick name is :Everest);


Tiger weight is : 50

Conclusion
Thus the java program was successfully complied and executed and result also verified.
Exp-No: 5 Interfaces

Aim:
To write java program for developing user-defined interfaces and implementation.

Procedure
Step1: Open the notepad.
Step2. Then type the program in the notepad and save in our own folder <mainclassname>.java
Step3. Set the path: set path=” C:\Program Files\Java\jdk1.6.0_20\bin”;
Step4. Set the classpath: set classpath=”C:\Program Files\Java\jdk1.6.0_20\lib”;
Step4. Compile the source progam using javac <mainclassname.java>
Step5. Run the program using java <mainclassname>

Program

import java.util.*;
interface Fly
{
void goForward();
void goDown();
}
class Duck implements Fly
{
public void goForward()

{
System.out.println("Duck going forward");
}

public void goDown()


{
System.out.println("Duck going down");
}

}
public class Finch implements Fly {

public void goForward() {


System.out.println("Finch is going forward");

public void goDown() {

System.out.println("Finch is going down");


}
}
public class Bird {

public static void main(String[] args) {

Duck duck = new Duck();


duck.goForward();
duck.goDown();

Finch finch = new Finch();


finch.goForward();
finch.goDown();

OUTPUT

Duck going forward


Duck going down
Finch is going forward
Finch is going down

Conclusion
Thus the java program was successfully complied and executed and result also verified.
Exp-No: 6 Threading
a.) Creation of thread in Java applications

Aim:
To write a java program for developing a chatting application(Client and Server) using Thread.

Procedure
Step1: Open the notepad.
Step2. Then type the program in the notepad and save in our own folder <mainclassname>.java
Step3. Set the path: set path=” C:\Program Files\Java\jdk1.6.0_20\bin”;
Step4. Set the classpath: set classpath=”C:\Program Files\Java\jdk1.6.0_20\lib”;
Step4. Compile the source progam using javac <mainclassname.java>
Step5. Run the program using java <mainclassname>

Program

import java.util.*;
class MyThread implements Runnable {
String name;
Thread t;
MyThread String thread){
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThread {
public static void main(String args[]) {
new MyThread("One");
new MyThread("Two");
new NewThread("Three");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

OUTPUT

New thread: Thread[One,5,main]


New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.

b. Multithreading

program

import java.util.*;
class Count extends Thread
{
Count()
{
super("my extending thread");
System.out.println("my thread created" + this);
start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("My thread run is over" );
}
}
class ExtendingExample
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread's run is over" );
}
}

OUTPUT

my thread createdThread[my runnable thread,5,main]


Main thread will be alive till the child thread is live
Printing the count 0
Printing the count 1
Main thread will be alive till the child thread is live
Printing the count 2
Main thread will be alive till the child thread is live
Printing the count 3
Printing the count 4
Main thread will be alive till the child thread is live
Printing the count 5
Main thread will be alive till the child thread is live
Printing the count 6
Printing the count 7
Main thread will be alive till the child thread is live
Printing the count 8
Main thread will be alive till the child thread is live
Printing the count 9
mythread run is over
Main thread run is over

Conclusion
Thus the java program was successfully complied and executed and result also verified.
Exp-No: 7 Exception Handling Mechanism in Java

Aim
To write java program for Handling pre-defined exceptions and User-defined Exception.

Procedure
Step1: Open the notepad.
Step2. Then type the program in the notepad and save in our own folder <mainclassname>.java
Step3. Set the path: set path=” C:\Program Files\Java\jdk1.6.0_20\bin”;
Step4. Set the classpath: set classpath=”C:\Program Files\Java\jdk1.6.0_20\lib”;
Step4. Compile the source progam using javac <mainclassname.java>
Step5. Run the program using java <mainclassname>

Program

Pre-defined exception
class PrefinedException
{
public static void main(String arg[])
{
try{
int a1[]=new int[5];
int a,b,i,N;
double c;
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter the value of N");
N=Integer.parseInt(d.readLine());
System.out.println("Enter the array elements");
for(i=0;i<N;i++)
a1[i]=Integer.parseInt(d.readLine());
a=a1[0];
b=a1[1];
c=a/b;
System.out.println("c="+c);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error is "+e);
}
catch(ArithmeticException e)
{
System.out.println("Error is "+e);
}
catch(NumberFormatException e)
{
System.out.println("Error is "+e);
}
catch(IOException e)
{
System.out.println("Error is "+e);
}
}
}

OUTPUT

D:\raj>javac PrefinedException.java
Note: PrefinedException.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

D:\raj>java PrefinedException
Enter the value of N
3
Enter the array elements
10
11
12
Sum of N elements=33
c=0.9090909090909091
D:\raj>
D:\raj>java PrefinedException
Enter the value of N
6
Enter the array elements
1
2
3
4
5
6
Error is java.lang.ArrayIndexOutOfBoundsException: 5
D:\raj>java PrefinedException
Enter the value of N
3
Enter the array elements
11
0
13
Sum of N elements=24
Error is java.lang.ArithmeticException: Divide by zero

User defined exception

class MyException extends Exception


{
//store account information
private static int accno[] = {1001, 1002, 1003, 1004};

private static String name[] =


{"Nish", "Shubh", "Sush", "Abhi", "Akash"};

private static double bal[] =


{10000.00, 12000.00, 5600.0, 999.00, 1100.55};

// default constructor
MyException() { }

// parametrized constructor
MyException(String str) { super(str); }

// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");

// display the actual account information


for (int i = 0; i < 5 ; i++)
{
System.out.println(accno[i] + "\t" + name[i] +
"\t" + bal[i]);

// display own exception if balance < 1000


if (bal[i] < 1000)
{
MyException me =
new MyException("Balance is less than 1000");
throw me;
}
}
} //end of try

catch (MyException e) {
e.printStackTrace();
}
}
}

OUTPUT

ACCNO CUSTOMER BALANCE


1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0

Conclusion
Thus the java program was successfully complied and executed and result also verified.
Exp-No: 8 AWT Components

Aim

To write a calculator program codes using Java Swing component.

Procedure
Step1: Open the notepad.
Step2. Then type the program in the notepad and save in our own folder <mainclassname>.java
Step3. Set the path: set path=” C:\Program Files\Java\jdk1.6.0_20\bin”;
Step4. Set the classpath: set classpath=”C:\Program Files\Java\jdk1.6.0_20\lib”;
Step4. Compile the source progam using javac <mainclassname.java>
Step5. Run the program using applet viewer or Internet Explorer <mainclassname>

Program

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Border extends JFrame


implements ActionListener {
private JButton b[];
private String names[] =
{ "Hide North Border", "Hide South Border", "Hide East Border",
"Hide West Border", "Hide Center Border" };
private BorderLayout layout;

public Border()
{
super( "BorderLayout" );

layout = new BorderLayout( 5, 5 );

Container c = getContentPane();
c.setLayout( layout );

// instantiate button objects


b = new JButton[ names.length ];

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


b[ i ] = new JButton( names[ i ] );
b[ i ].addActionListener( this );
}
// order is not important
c.add( b[ 0 ], BorderLayout.NORTH ); // North position
c.add( b[ 1 ], BorderLayout.SOUTH ); // South position
c.add( b[ 2 ], BorderLayout.EAST ); // East position
c.add( b[ 3 ], BorderLayout.WEST ); // West position
c.add( b[ 4 ], BorderLayout.CENTER ); // Center position

setSize( 400, 300 );


show(); //Show the border layout
}

public void actionPerformed( ActionEvent e )


{
for ( int i = 0; i < b.length; i++ )
if ( e.getSource() == b[ i ] )
b[ i ].setVisible( false );
else
b[ i ].setVisible( true );

// re-layout the content pane


layout.layoutContainer( getContentPane() );
}

public static void main( String args[] )


{
Border bord = new Border();

bord.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
OUTPUT

Conclusion
Thus the java program was successfully complied and executed and result also verified.
Exno: 9 JDBC

Aim :
Write a simple for connect Oracle for Data Manipulation.

Procedure
Step1: Open the notepad.
Step2. Then type the program in the notepad and save in our own folder <mainclassname>.java
Step3. Set the path: set path=” C:\Program Files\Java\jdk1.6.0_20\bin”;
Step4. Set the classpath: set classpath=”C:\Program Files\Java\jdk1.6.0_20\lib”;
Step4. Compile the source progam using javac <mainclassname.java>
Step5. Run the program using applet viewer or Internet Explorer <mainclassname>

Program

import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class addcus extends JFrame implements ActionListener
{
JTextField id;
JTextField name;
JTextField addr;
JTextField pno;
JTextField job;
JButton next;
JButton addnew;
JPanel p;
static Result res;
static Connection conn;
static Statement stat;
public addcus()
{
Super("our application");
Container c=getContentPane();
c.setLayout(new GridLayout(8,1));
id=new JTextField(20);
name=new JTextField(20);
addr=new JTextField(25);
pno=new JTextField(10);
job=new JTextField(15);
next=new JButton("Next");
p=new JPanel();
c.add(new JLabel("customer id",JLabel.CENTER));
c.add(id);
c.add(new JLabel("Customer name",JLabel.CENTER));
c.add(name);
c.add(new JLabel("Customer address",JLabel.CENTER));
c.add(addr);
c.add(new JLabel(" phone num",JLabel.CENTER));
c.add(pno);
c.add(new JLabel("Job",JLabel.CENTER));
c.add(job);
c.add(p);
p.add(next);
next.addActionListener(this);
setSize(500,500);
setVisible(true);
addWindowListener(new WIN());
}
public static void mian(string args[])
{
addcus c=new addcus();
try
{
Class.forName("sun.jdbc.odbc.jdbcodbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:data1");
stat=conn.CreateStatement();
res=stat.executeQuery("select *from customer");
res.next();

}
catch(Exception e)
{
System.out.println("Error"+e);
}
c.showRecord(res);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==next)
{
try
{
res.next();
}
catch(Exception ee)
{}
showRecord(res0;
}
}
public void showRecord(ResultSet res)
{
try
{
id.setText(res.getString(1));
name.setText(res.getString(2));
addr.setText(res.getString(3));
pno.setText(res.getString(4));
job.setText(res.getString(5));
}
catch(Exception e)
{}
}
class WIN extends WindowAdapter
{
public void windowClosing(windowEvent w)
{
JOptionPane jop=new JOptionPane();
jop.showMessageDialog(null,"Database","thanks",JOptionPane.QUESTION_MESSAGE);
}
}
}
OUTPUT

Conclusion
Thus the java program was successfully complied and executed and result also verified.

You might also like