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

Department of Information Technology Department of Information Technology

This document outlines the syllabus for a Java Programming lab course. It includes 10 programming assignments that cover topics like classes and objects, inheritance, interfaces, threads, exceptions, applets, and graphics. The assignments involve writing programs to display student details using classes, demonstrate String and StringBuffer methods, create classes that inherit from each other, implement runnable interfaces and threads, handle exceptions, and create a basic calculator applet. Sample programs are provided for the first two assignments.

Uploaded by

Padma Pradhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views

Department of Information Technology Department of Information Technology

This document outlines the syllabus for a Java Programming lab course. It includes 10 programming assignments that cover topics like classes and objects, inheritance, interfaces, threads, exceptions, applets, and graphics. The assignments involve writing programs to display student details using classes, demonstrate String and StringBuffer methods, create classes that inherit from each other, implement runnable interfaces and threads, handle exceptions, and create a basic calculator applet. Sample programs are provided for the first two assignments.

Uploaded by

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

Tulsiramji Gaikwad-Patil College of Engineering and Technology

Wardha Road, Nagpur-441 108


NAAC Accredited

Department of Information Technology

Second Year B.E. (Fifth Semester)


BEIT505T: JAVA PROGRAMMING – LAB (EXPERMENTS)
by Dr PL Pradhan Subject Teacher

Teaching Scheme Examination Scheme


Lectures 4 Hrs/week Theory
Tutorial 1 Hrs/week Internal 20
Total 100
Theory Credits: 5 Duration of Exam: 03 Hours
Course Outcomes
BEIT505T.1 To understand basic Programming Language in JAVA.
To understand various Method, Mechanisms & Data Handling.
BEIT505T.2
BEIT505T.3 To understand the class, object & Interface in JAVA Programming.
BEIT505T.4 To understand the threading & Synchronization in JAVA.
BEIT505T.5 To develop, test and debug the file handling system.
BEIT505T.6 To Design and build Swing & AWT in JAVA.
Course Contents
1 Write an application program which display total marks of 5 students using student class
with following attributes: Regd No, Name Mark & Total.
2 A.Write an application program to demonstrate various methods in String class.
B.Write an application program to demonstrate various methods in StringBuffer class.
3 Write an application program to create a player class & inherit three classes
Cricket_player.
Football_player
Hocker_player.
4 Write a manu based java that accepts a shoping list of 4 items from command line and store in
vector and perform operations.

5 Write an application program to show how a class implements two interfaces using departmental
data of college.
6 Write an application program to implement the concept of threading by extending thread class.
Write an application program to implement the concept of threading by implementing Runnable
Interface.
7 Write a Java Program to display the date of before and after days for given dates.
8 Write an application program to implement the concept of Exception Handling by creating user
defined exceptions.

9 Write an applet program for creating a simple calculator to perform addition, subtraction,
multiplication and division using Button, Lebel, and Textfield components.

10 Write an application program on applet using Graphics Class 1. To display basic shape and fill
them. 2. Draw different items using basic shapes. 3.Set the background & foreground color.
1. Write an application program which display total marks of 5 students using student class
with following attributes: Regd No, Name Mark & Total.
Sample Program
class PrintStudentDetailsUsingClasses
{
public static void main(String s[])
{
Student students[] = new Student[5];

students[0] = new Student();


students[0].name = "Rajesh";
students[0].marks = 45;
students[0].section = 'A';

students[1] = new Student();


students[1].name = "Suresh";
students[1].marks = 78;
students[1].section = 'B';

students[2] = new Student();


students[2].name = "Ramesh";
students[2].marks = 83;
students[2].section = 'A';

students[3] = new Student();


students[3].name = "Kamlesh";
students[3].marks = 77;
students[3].section = 'A';

students[4] = new Student();


students[4].name = "Vignesh";
students[4].marks = 93;
students[4].section = 'B';

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


{
System.out.println( students[i].name + " in section " + students[i].section + " got " +
students[i].marks + " marks." );
}
}

}
class Student
{
String name;
int marks;
char section;
String address;
String mobile;
}
OR
Sample Program

import java.util.Scanner;

public class GetStudentDetails


{
public static void main(String args[])
{
String name;
int roll, math, phy, eng;

Scanner SC=new Scanner(System.in);

System.out.print("Enter Name: ");


name=SC.nextLine();
System.out.print("Enter Roll Number: ");
roll=SC.nextInt();
System.out.print("Enter marks in Maths, Physics and English: ");
math=SC.nextInt();
phy=SC.nextInt();
eng=SC.nextInt();

int total=math+eng+phy;
float perc=(float)total/300*100;

System.out.println("Roll Number:" + roll +"\tName: "+name);


System.out.println("Marks (Maths, Physics, English): " +math+","+phy+","+eng);
System.out.println("Total: "+total +"\tPercentage: "+perc);

Outputter Name: Mikenter umber: 101

Enter marks in Maths, Physics and English: 88 77 99


Roll Number:101 Name: Mike
Marks (Maths, Physics, English): 88,77,99
Total: 264 Percentage: 88.0
2. A.Write an application program to demonstrate various methods in
String class.

Java String Example Sample Program


public class Example{
public static void main(String args[]){
//creating a string by java string literal
String str = "Beginnersbook";
char arrch[]={'h','e','l','l','o'};
//converting char array arrch[] to string str2
String str2 = new String(arrch);

//creating another java string str3 by using new keyword


String str3 = new String("Java String Example");

//Displaying all the three strings


System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
Output:

Beginnersbook

hello
Java String Example

2.B.Write an application program to demonstrate various methods in StringBuffer


class.
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}

1) StringBuilder append() method


The StringBuilder append() method concatenates the given argument with this string.

class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

2) StringBuilder insert() method


The StringBuilder insert() method inserts the given string with this string at the given
position.

class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}

3) StringBuilder replace() method


The StringBuilder replace() method replaces the given string from the specified beginIndex
and endIndex.

class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified beginIndex
to endIndex.

class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}

5) StringBuilder reverse() method


The reverse() method of StringBuilder class reverses the current string.

class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
6) StringBuilder capacity() method
The capacity() method of StringBuilder class returns the current capacity of the Builder. The
default capacity of the Builder is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.

class StringBuilderExample6{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

7) StringBuilder ensureCapacity() method


The ensureCapacity() method of StringBuilder class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.

class StringBuilderExample7{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
3. Write a program in Java to create a Player class. Inherit the classes
Cricket _Player, Football _Player and Hockey_ Player from Player
class.

Sample Program
class player
{
String name;
int age;
player(String n,int a)
{ name=n; age=a; }
void show()
{
System.out.println("\n");
System.out.println("Player name : "+name);
System.out.println("Age : "+age);
}
}
class criket_player extends player
{
String type;
criket_player(String n,String t,int a)
{
super(n,a);
type=t;
}
public void show()
{
super.show();
System.out.println("Player type : "+type);
}
}
class football_player extends player
{
String type;
football_player(String n,String t,int a)
{
super(n,a);
type=t;
}
public void show()
{
super.show();
System.out.println("Player type : "+type);
}
}
class hockey_player extends player
{
String type;
hockey_player(String n,String t,int a)
{
super(n,a);
type=t;
}
public void show()
{
super.show();
System.out.println("Player type : "+type);
}
}
//--------- main -----------
class s04_02
{
public static void main(String args[])
{
criket_player c=new criket_player("Ameer","criket",25);
football_player f=new football_player("arun","foot ball",25);
hockey_player h=new hockey_player("Ram","hockey",25);
c.show();
f.show();
h.show();
}
}
4.Write a manu based java that accepts a shoping list of 4 items from command line and store in vector
and perform operations.

Sample Program
import java.util.*;
import java.io.*;

class MenuDriven
{
publicstaticvoid main(String args[])
{
Vector itemList = new Vector();
String str,item;
int i,j,len,choice,pos;

len=args.length;
for(i=0;i<len;i++)
itemList.addElement(args[i]);

while(true)
{
System.out.println("\n\nChoose your choice ...");
System.out.println("1) Delete Item");
System.out.println("2) Add Item at Specified Location ");
System.out.println("3) Add Item at the End of the list");
System.out.println("4) Print Vector List ");
System.out.println("5) Exit");
System.out.print("Enter your choice : ");
System.out.flush();
try{
BufferedReader obj = new BufferedReader(new
InputStreamReader(System.in));
str=obj.readLine();
choice=Integer.parseInt(str);
switch(choice)
{
case 1 : System.out.print("Enter Item you want to delete :
");
str=obj.readLine();
itemList.removeElement(str); //string is not
needed to convert object type as it

//is already object of class String


break;
case 2 : System.out.print("Enter Item to be Insert : ");
System.out.flush();
item=obj.readLine();
System.out.print("Enter Position to insert
item : ");
str=obj.readLine();
pos=Integer.parseInt(str);
itemList.insertElementAt(item,pos-1);
break;
case 3 : System.out.print("Enter Item to be Insert : ");
System.out.flush();
item=obj.readLine();
itemList.addElement(item);
break;
case 4 : len=itemList.size();
System.out.println("\nItem Display ");
for(i=0;i<len;i++)
{
System.out.println((i+1)+")
"+itemList.elementAt(i));
}
break;
case 5 : System.out.println("\n\nThank You for using this
software.....");
System.exit(1);
break;
default : System.out.println("\nEntered Choice is
Invalid\nTry Again\n");
}
}
catch(Exception e) {}
}
}
}
5. Write an application program to show how a class implements two interfaces using departmental data
of college.
Sample Program
interface MyInterface
{
/* compiler will treat them as:
* public abstract void method1();
* public abstract void method2();
*/
public void method1();
public void method2();
}
class Demo implements MyInterface
{
/* This class must have to implement both the abstract methods
* else you will get compilation error
*/
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}
Output:

implementation of method1
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
A class can implement any number of interfaces. If there are two or
more same methods in two interfaces and a class implements both
interfaces, implementation of the method once is enough.

Sample Program Dept A & Dept B Central = college


interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String args[])
{
//Statements
}
}
A class cannot implement two interfaces that have methods with same name
but different return type.

 interface A
 {
 public void aaa();
 }
 interface B
 {
 public int aaa();
 }

 class Central implements A,B
 {

 public void aaa() // error
 {
 }
 public int aaa() // error
 {
 }
 public static void main(String args[])
 {

 }
 }
Variable names conflicts can be resolved by interface name.

 interface A
 {
 int x=10;
 }
 interface B
 {
 int x=100;
 }
 class Hello implements A,B
 {
 public static void Main(String args[])
 {
 /* reference to x is ambiguous both variables are x
 * so we are using interface name to resolve the
 * variable
 */
 System.out.println(x);
 System.out.println(A.x);
 System.out.println(B.x);
 }
 }
6. a.Write an application program to implement the concept of threading by extending thread class.

class Lab751{
public static void main(String as[]){
Mythread th=new Mythread();
Mythread th1=new Mythread();
th.start();
th1.start();
Thread t= Thread.currentThread();/****now control is transfered Here
from the run method without evaluting the rest code**/
for(int i=100;i<=110;i++){
System.out.println(t.getName()+" -value is"+i);
try{
Thread.sleep(500);

}catch(Exception e){
e.printStackTrace();
}
}
}
}
class Mythread extends Thread{
public void run(){

Thread th=Thread.currentThread();/**control jumps from here to there


above*****/
for(int i=1;i<=10;i++){
System.out.println(th.getName()+"+Value is"+i);
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}

}
}
6.b Write an application program to implement the concept of threading by implementing Runnable
Interface.
public class FirstThread implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(i);
try
{
Thread.sleep(50);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}

public static void main(String s[])


{
Thread t=new Thread(new FirstThread(),"My Thread");
t.start();
}
OR

package com.myjava.threads;

class MyRunnableThread implements Runnable{

public static int myCount = 0;


public MyRunnableThread(){

}
public void run() {
while(MyRunnableThread.myCount <= 10){
try{
System.out.println("Expl Thread:
"+(++MyRunnableThread.myCount));
Thread.sleep(100);
} catch (InterruptedException iex) {
System.out.println("Exception in thread: "+iex.getMessage());
}
}
}
}
public class RunMyThread {
public static void main(String a[]){
System.out.println("Starting Main Thread...");
MyRunnableThread mrt = new MyRunnableThread();
Thread t = new Thread(mrt);
t.start();
while(MyRunnableThread.myCount <= 10){
try{
System.out.println("Main Thread:
"+(++MyRunnableThread.myCount));
Thread.sleep(100);
} catch (InterruptedException iex){
System.out.println("Exception in main thread:
"+iex.getMessage());
}
}
System.out.println("End of Main Thread...");
}
}

7 Write a Java Program to display the date of before and after days for given dates.
Sample Program
import java.time.*;
public class Exercise22 {
public static void main(String[] args)
{
LocalDate today = LocalDate.now();
System.out.println("\nCurrent Date: "+today);
System.out.println("10 days before today will be
"+today.plusDays(-10));
System.out.println("10 days after today will be
"+today.plusDays(10)+"\n");
}
}
8. Write an application program to implement the concept of Exception Handling by creating user
defined exceptions
To created a User-Defined Exception Class
Sample Program
class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception and throw it.
}
catch(MyException e){
System.out.println(e) ;
}
}
}
class MyException extends Exception{
int a;
MyException(int b) {
a=b;
}
public String toString(){
return ("Exception Number = "+a) ;
}
}
9. Write an applet program for creating a simple calculator to perform addition, subtraction,
multiplication and division using Button, Lebel, and Textfield components.

Sample program
import java.awt.*;
import java.awt.event.*;
public class TwoNumbers extends Applet implements ActionListener
{
TextField firstNum, secondNum, resultNum;
public TwoNumbers()
{
setLayout(new GridLayout(3, 2, 10, 15));
setBackground(Color.cyan);

firstNum = new TextField(15);


secondNum = new TextField(15);
resultNum = new TextField(15);

secondNum.addActionListener(this);

add(new Label("Enter First Number")); add(firstNum);


add(new Label("Enter Second Number")); add(secondNum);
add(new Label("S U M")); add(resultNum);
}
public void actionPerformed(ActionEvent e)
{
String str1 = firstNum.getText();
double fn = Double.parseDouble(str1);
double sn = Double.parseDouble(secondNum.getText());

resultNum.setText("Sum is " + (fn+sn));


}
}
10 Write an application program on applet using Graphics Class 1. To display basic shape and fill
them.
import java.applet.*;
public class RectanglesDrawing extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawRect(50, 80, 150, 100);
g.setColor(Color.magenta);
g.fillRect(230, 80, 150, 100);
}
}

import java.awt.Graphics;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class Main extends JPanel {

public static void main(String[] a) {

JFrame f = new JFrame();

f.setSize(400, 400);

f.add(new Main());

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

public void paint(Graphics g) {

g.fillRect (5, 15, 50, 75);

Draw different items using basic shapes

import java.awt.Color;
import java.awt.Graphics;

import java.awt.Graphics2D;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class Panel extends JPanel {

public void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(new Color(31, 21, 1));

g2d.fillRect(250, 195, 90, 60);

public static void main(String[] args) {

Panel rects = new Panel();

JFrame frame = new JFrame("Rectangles");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(rects);

frame.setSize(360, 300);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

Draw different items using basic shapes


import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class SetBackColor extends Applet {

public void init()


{
setBackground(Color.cyan);
setForeground(Color.red);
}

public void paint(Graphics g)


{
g.drawString("Hello Java",50,50);
}
}

/*
<applet code="SetBackColor" width=200 height=200>
</applet>
*/
Write an application program on applet using Graphics Class 1. To display basic shape and fill them.
2. Draw different items using basic shapes. 3.Set the background & foreground color.
3.Set the background & foreground color.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class SetForegroundColorExample extends Applet{

public void paint(Graphics g){


/*
* Set foreground color of an applet using
* void setForeground(Color c) method.
*/

setForeground(Color.red);
g.drawString("Foreground color set to red", 50, 50);
}
}

OR
import java.applet.Applet;
import java.awt.*; //Color and Graphics belongs to java.awt,
import java.awt.event.*;
public class ColorApplet extends Applet
{
public static void main(String[] args)
{
Frame ForegroundBackgroundColor = new Frame("Change Background and
Foreground Color of Applet");
ForegroundBackgroundColor.setSize(420, 180);
Applet ColorApplet = new ColorApplet();
ForegroundBackgroundColor.add(ColorApplet);
ForegroundBackgroundColor.setVisible(true);
ForegroundBackgroundColor.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0); }
});
}
public void paint(Graphics g)
{
Color c = getForeground();
setBackground(Color.yellow); /*There are many predefined colors, or you can
create your own predefined colors to Change are
black,blue,cyan,darkGray,gray,green,lightGray,magenta,orange,pink,red,white,ye
llow */
setForeground(Color.red); /*There are many predefined colors, or you can
create your own predefined colors to Change are
black,blue,cyan,darkGray,gray,green,lightGray,magenta,orange,pink,red,white,ye
llow */
g.drawString("Foreground color set to red", 100, 50); // Drawing texts on the
graphics screen:
g.drawString(c.toString(), 100, 80); /*The drawString() method, takes
parameters as instance of String containing where the text to be drawn, and two
integer values specifying
the coordinates where the text should place.*/
g.drawString("Change Background and Foreground Color of Applet", 50, 100);
}
}

You might also like