Lab Manual: "Programming in Java Lab"

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

Lab Manual

For

“PROGRAMMING IN JAVA LAB”


[BCA504P]

V Semester BCA

MRS. SHWETHA S KULLOLI, Assitant Professor

K. L. E. Society’s Degree College


(Affiliated to Bangalore University)

Department of Computer Applications


II Stage, III Block, Nagarbhavi, Bengaluru-560072
1 Write a program to find the factorial of list of number reading input as command
line argument.

2 Write a program to display all prime numbers between two limits.

3 Write a program to sort the elements in ascending and descending order and show
the exception handling.

4 Write a program to implement all string operations.

5 Write a program to find the area of geometrical figures using method.

6 6. Write a program to implement constructor overloading by passing different number


of parameter of different types.

7 Write a program to create student report using applet, read the input using text
boxes and display the o/p using buttons.

8 Write a program to calculate bonus for different departments using method


overriding.

9 Write a program to implement thread, applets and graphics by implementing


animation of ball moving.

10 A. Write a program to implement Mouse events.


B. Write a program to implement Keyboard events.

PART-A PROGRAMS

KLE SOCIETY’S, B.C.A., DEPARTMENT 2


SOLUTIONS

1.  Write a program to find factorial of list of number reading input as command


line argument.

Source Code

public class factorial


{
public static void main(String args[]){

int[] num=new int[10];


if(args.length==0){
System.out.println("no command line argument passed");
return;
}
for(int i=0;i<args.length;i++)

num[i]=Integer.parseInt(args[i]);
for(int i=0;i<args.length;i++)
{
int fact=1;
for(int j=1;j<=num[i];j++)
fact *=j;
System.out.println("the factorial of"+args[i]+" is : " +fact);
}
}
}

Output:
The factorial of 6 is:120

2. Write a program to display all prime numbers between two limits.

Source Code

class Prime
{
  public static void main(String args[])

KLE SOCIETY’S, B.C.A., DEPARTMENT 3


  {
     int i,j;
     if(args.length<2)
      {
           System.out.println("No command line Argruments ");
           return;
      }
 
      int num1=Integer.parseInt(args[0]);
      int num2=Integer.parseInt(args[1]);

      System.out.println("Prime number between"+num1+"and" +num2+" are:");


      for(i=num1;i<=num2;i++)
      {
           for(j=2;j<i;j++)
           {

              int n=i%j;
              if(n==0)
              {

                 break;
              }
           }
          
           if(i==j)
           {

               System.out.println(" "+i);
           }
      } 
 }

Output:
Prime number between1and10 are:
2
3
5

KLE SOCIETY’S, B.C.A., DEPARTMENT 4


7

3. Write a program to sort the elements in ascending and descending order


and show the exception handling.

Source code:
class Sorting
{

public static void main(String args[]){

int a[] = new int[5];

try

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

a[i]=Integer.parseInt(args[i]);

System.out.println("Before Sorting\n");

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

System.out.println(" " + a[i]);

bubbleSort(a,5);

System.out.println("\n\n After Sorting\n");

System.out.println("\n\nAscending order \n");

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

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

System.out.println("\n\nDescending order \n");

KLE SOCIETY’S, B.C.A., DEPARTMENT 5


for(int i=4;i>=0;i--)

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

catch(NumberFormatException e)

System.out.println("Enter only integers");

catch(ArrayIndexOutOfBoundsException e)

System.out.println("Enter only 5 integers");

private static void bubbleSort(int [] arr, int length){

int temp,i,j;

for(i=0;i<length-1;i++)

for(j=0;j<length-1-i;j++)

if(arr[j]>arr[j+1])

temp=arr[j];

arr[j]=arr[j+1];

arr[j+1]=temp;

KLE SOCIETY’S, B.C.A., DEPARTMENT 6


}

Output:

Before Sorting 45 6 32 5 64

After Sorting

Ascending order 5 6 32 45 64

Descending order 64 45 32 6 5

4.Write a program to implement all string operations.

Source code:
public class string1 {
public static void main(String args[])
{
String s1="java";
String s2="programmig";
System.out.println("thr string sre "+s1+"and"+s2);
int len1=s1.length();
int len2=s2.length();
System.out.println("length of "+s1+"is = "+len1);
System.out.println("length of "+s2+"is = "+len2);
System.out.println("the concation of 2 strings "+s1.concat(s2));
System.out.println("first char of "+s1+" is ="+s1.charAt(0));
System.out.println("second char of "+s2+" is ="+s2.charAt(0));
System.out.println("string first "+s1+" is ="+s1.toUpperCase());
System.out.println("second string of "+s2+" is ="+s2.toLowerCase());
System.out.println(" v occurs at position "+s1.indexOf("v")+" in "+s1);
System.out.println("substrig of"+s2+"starting from index 3 and ending at 7 is =
"+s2.substring(3,7));
System.out.println("replacing 'v' with 'z' in "+s1+" is = "+s1.replace('v','z'));
boolean check=s1.equals(s2);
if(check==false)

KLE SOCIETY’S, B.C.A., DEPARTMENT 7


{
System.out.println(" "+s1+" and " +s2+" are not same");

}
else
{
System.out.println(" "+s1+" and " +s2+" are same");
}
}
}

Output:
The string are java and programming
Length of java is = 4
Length of programming is = 10
The concatenation of 2 strings javaprogramming
First char of java is =j
Second char of programming is =p
String first java is =JAVA
Second string of programming is =programming
v occurs at position 2 in java
substring of programming starting from index 3 and ending at 7 is = gram
replacing 'v' with 'z' in java is = jaza
java and programming are not same

5.     Write a program to find area of geometrical figures using method.

Source code:

import java.io.*;
class Area
{
   public static double circleArea(double r)
   {
      return Math.PI*r*r;
   }

   public static double squareArea(double side)

KLE SOCIETY’S, B.C.A., DEPARTMENT 8


   {
       return side*side;
   }
   public static double rectArea(double width, double height)
   {
      return width*height;
  }

  public static double triArea(double base, double height1)


  {
      return 0.5*base*height1;
  }

  public static String readLine()


  {
     String input=" ";
     BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
     try
     {
          input = in.readLine();
     }catch(Exception e)
     {
        System.out.println("Error" + e);
     }

     return input;
  }

   public static void main(String args[])


   {
      System.out.println("Enter the radius");
      Double radius=Double.parseDouble(readLine());
      System.out.println("Area of circle = " + circleArea(radius));

      System.out.println("Enter the side");


      Double side=Double.parseDouble(readLine());
      System.out.println("Area of square = "+squareArea(side));

KLE SOCIETY’S, B.C.A., DEPARTMENT 9


      System.out.println("Enter the Width");
      Double width=Double.parseDouble(readLine());
      System.out.println("Enter the height");
      Double height=Double.parseDouble(readLine());
      System.out.println("Area of Rectangle = " + rectArea(width,height));

      System.out.println("Enter the Base");


      Double base=Double.parseDouble(readLine());
      System.out.println("Enter the Height");
      Double height1=Double.parseDouble(readLine());
      System.out.println("Area of traingle ="+triArea(base,height1));

   }

Output:
Enter the radius: 5
Area of Circle =78.53981633974483
Enter the side:3
Area of square=9.0
Enter the width:4
Enter the height:8
Area of rectangle:32.0
Enter the base:2
Enter the Heigh9t:
Area of Triangle:9.0

6.     Write a program to implement constructor overloading by passing different


number of parameter of different types.
Source code
public class Box
{
  int length,breadth,height;
 
  Box()
  {
     length=breadth=height=2;
     System.out.println("Intialized with default constructor");

KLE SOCIETY’S, B.C.A., DEPARTMENT 10


  }

  Box(int l, int b)
   {
      length=l;
      breadth=b;
      height=2;
System.out.println("Initialized with parameterized  constructor having 2 params");
   
 
   }

   Box(int l, int b, int h)


   {
        length=l;
        breadth=b;
        height=h;
        System.out.println("Initialized with parameterized constructor having 3 params");

   }

   public int getVolume()


   {
       return length*breadth*height;
  
   }

   public static void main(String args[])


   {
      Box box1 = new Box();
      System.out.println("The volume of Box 1 is :"+ box1.getVolume());

      Box box2 = new Box(10,20);


      System.out.println("Volume of Box 2 is :" + box2.getVolume());

      Box box3 = new Box(10,20,30);


      System.out.println("Volume of Box 3 is :" + box3.getVolume());

KLE SOCIETY’S, B.C.A., DEPARTMENT 11


   }
}

Output:
Initialized with default constructor
Volume of cube1 is:8
Initialized with parameterized construcror having 2 params
Volume of cube2 is:400
Initialized with parameterized construcror having 3 params
Volume of cube3 is:6000

7.     Write a program to create student report using applet, read the input using
text boxes and display the o/p using buttons.

Source code
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/* <applet code="StudentReport.class",width=500 height=500>


</applet>*/
public class StudentReport extends Applet implements ActionListener
{
Label lblTitle,lblRegno,lblCourse,lblSemester,lblSub1, lblSub2;

TextField txtRegno,txtCourse,txtSemester,txtSub1,txtSub2;
Button cmdReport;

String rno="", course="", sem="",sub1="",sub2="",avg="",heading="";

public void init()


{
GridBagLayout gbag= new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);

lblTitle = new Label("Enter Student Details");


lblRegno= new Label("Register Number");
txtRegno=new TextField(25);

KLE SOCIETY’S, B.C.A., DEPARTMENT 12


lblCourse=new Label("Course Name");
txtCourse=new TextField(25);
lblSemester=new Label("Semester ");
txtSemester=new TextField(25);
lblSub1=new Label("Marks of Subject1");
txtSub1=new TextField(25);
lblSub2=new Label("Marks of Subject2");
txtSub2=new TextField(25);

cmdReport = new Button("View Report");

// Define the grid bag


gbc.weighty=2.0;
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbc.anchor=GridBagConstraints.NORTH;
gbag.setConstraints(lblTitle,gbc);

//Anchor most components to the right


gbc.anchor=GridBagConstraints.EAST;

gbc.gridwidth=GridBagConstraints.RELATIVE;
gbag.setConstraints(lblRegno,gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbag.setConstraints(txtRegno,gbc);

gbc.gridwidth=GridBagConstraints.RELATIVE;
gbag.setConstraints(lblCourse,gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbag.setConstraints(txtCourse,gbc);

gbc.gridwidth=GridBagConstraints.RELATIVE;
gbag.setConstraints(lblSemester,gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbag.setConstraints(txtSemester,gbc);

gbc.gridwidth=GridBagConstraints.RELATIVE;
gbag.setConstraints(lblSub1,gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbag.setConstraints(txtSub1,gbc);

KLE SOCIETY’S, B.C.A., DEPARTMENT 13


gbc.gridwidth=GridBagConstraints.RELATIVE;
gbag.setConstraints(lblSub2,gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbag.setConstraints(txtSub2,gbc);

gbc.anchor=GridBagConstraints.CENTER;
gbag.setConstraints(cmdReport,gbc);

add(lblTitle);
add(lblRegno);
add(txtRegno);
add(lblCourse);
add(txtCourse);
add(lblSemester);
add(txtSemester);
add(lblSub1);
add(txtSub1);
add(lblSub2);
add(txtSub2);
add(cmdReport);
cmdReport.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
try{
if(ae.getSource() == cmdReport)
{

rno=txtRegno.getText().trim();
course=txtCourse.getText().trim();
sem=txtSemester.getText().trim();
sub1=txtSub1.getText().trim();
sub2=txtSub2.getText().trim();
avg="Avg Marks:" + ((Integer.parseInt(sub1) + Integer.parseInt(sub2))/2);

rno="Register No:" + rno;

KLE SOCIETY’S, B.C.A., DEPARTMENT 14


course="Course :"+ course;
sem="Semester :"+sem;
sub1="Subject1 :"+sub1;
sub2="Subject2 :"+sub2;

heading="Student Report";
removeAll();
showStatus("");
repaint();
}

}catch(NumberFormatException e)
{

showStatus("Invalid Data");
}

}
public void paint(Graphics g)
{
g.drawString(heading,30,30);
g.drawString(rno,30,80);
g.drawString(course,30,100);
g.drawString(sem,30,120);
g.drawString(sub1,30,140);
g.drawString(sub2,30,160);
g.drawString(avg,30,180);
}
}

Output:

KLE SOCIETY’S, B.C.A., DEPARTMENT 15


8.     Write a program to calculate bonus for different departments using method

KLE SOCIETY’S, B.C.A., DEPARTMENT 16


overriding.

Source code
abstract class Department
{
  double salary,bonus,totalsalary;
  public abstract void calBonus(double salary);

 public void displayTotalSalary(String dept)


 {
  System.out.println(dept+"\t"+salary+"\t\t"+bonus+"\t"+totalsalary);
 }
}

class Accounts extends Department


{
    public void calBonus(double sal)
    {
       salary = sal;
       bonus = sal * 0.2;
       totalsalary=salary+bonus;
    }
}

class Sales extends Department


{
   public void calBonus(double sal)
   {
      salary = sal;
      bonus = sal * 0.3;
     totalsalary=salary+bonus;

   }
}

public class BonusCalculate


{
    public static void main(String args[])
    {
        Department acc = new Accounts();

KLE SOCIETY’S, B.C.A., DEPARTMENT 17


        Department sales = new Sales();
       
        acc.calBonus(10000);
        sales.calBonus(20000);

       System.out.println("Department \t Basic Salary \t Bonus \t Total Salary");

       System.out.println("--------------------------------------------------------------");
       acc.displayTotalSalary("Accounts Dept");
       sales.displayTotalSalary("Sales Dept");
       System.out.println("---------------------------------------------------------------");
    }
}

Output:
Department BasicSalary Bonus TotalSalary

Accounts 10000.0 2000.0 12000.0


SalesDep 20000.0 6000.0 26000.0

9.Write a program to implement thread, applets and graphics by implementing


animation of ball moving.

Source code :
import java.awt.*;
import java.applet.*;
/* <applet code="MovingBall.class" height=300 width=300></applet> */
public class MovingBall extends Applet implements Runnable
{
    int x,y,dx,dy,w,h;
    Thread t;
    boolean flag;
    public void init()
    {
        w=getWidth();
        h=getHeight();
        setBackground(Color.yellow);
        x=100;
        y=10;

KLE SOCIETY’S, B.C.A., DEPARTMENT 18


        dx=10;
        dy=10;
    }
    public void start()
    {
        flag=true;
        t=new Thread(this);
        t.start();
    }
    public void paint(Graphics g)
    {
        g.setColor(Color.blue);
        g.fillOval(x,y,50,50);
    }
    public void run()
    {
        while(flag)
        {
           
            if((x+dx<=0)||(x+dx>=w))
                dx=-dx;
            if((y+dy<=0)||(y+dy>=h))
                dy=-dy;
            x+=dx;
            y+=dy;
            repaint();
            try
            {
                Thread.sleep(300);
            }
            catch(InterruptedException e)
            {}
        }
    }   
    public void stop()
    {
        t=null;
        flag=false;
    }
}

KLE SOCIETY’S, B.C.A., DEPARTMENT 19


Output:

10. A. Write a program to implement mouse events.

KLE SOCIETY’S, B.C.A., DEPARTMENT 20


Source code
import java.awt.*;
import java.awt.Graphics;
import java.awt.event.*;
import java.applet.*;

public class MouseEvents extends Applet implements MouseListener,MouseMotionListener {

String str= "";


public void init(){
addMouseListener(this);
addMouseMotionListener(this);
}

public void paint(Graphics g){


g.drawString(str, 20, 20);
}

public void mousePressed(MouseEvent me) {


str="Mouse Button Pressed";
repaint(0);
}
public void mouseClicked(MouseEvent me) {
str="Mouse Button Clicked";
repaint(0);
}
public void mouseReleased(MouseEvent me) {
str="Mouse Button Released";
repaint(0);
}
public void mouseEntered(MouseEvent me) {
str="Mouse Button Entered";
repaint(0);
}
public void mouseExited(MouseEvent me) {
str="Mouse Button Exited";
repaint(0);
}
public void mouseMoved(MouseEvent me) {

KLE SOCIETY’S, B.C.A., DEPARTMENT 21


str="Mouse Button Moved";
repaint(0);
}
public void mouseDropped(MouseEvent me) {
str="Mouse Button Dropped";
repaint(0);
}
public void mouseDragged(MouseEvent me) {
str="Mouse Button Dragged";
repaint(0);
}
}
Output:

KLE SOCIETY’S, B.C.A., DEPARTMENT 22


10.B    Write a program to implement keyboard events.
Source code:
import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class KeyBoardEvents extends Applet implements KeyListener {

String str=" ";

public void init()

addKeyListener(this);

requestFocus();

public void keyTyped(KeyEvent e){

KLE SOCIETY’S, B.C.A., DEPARTMENT 23


str +=e.getKeyChar();

repaint(0);

public void keyPressed(KeyEvent e){

showStatus("KEY PRESSED");

public void keyReleased(KeyEvent e){

showStatus("KEY RELEASED");

public void paint(Graphics g)

g.drawString(str,15,15);

Output:

KLE SOCIETY’S, B.C.A., DEPARTMENT 24


KLE SOCIETY’S, B.C.A., DEPARTMENT 25
KLE SOCIETY’S, B.C.A., DEPARTMENT 26
PART- B PROGRAMS

1 Write a java program to add two numbers.

2 Write a program to calculate the simple interest

3 Write a Program to demonstrate the parameterized constructor

4 Program to demonstrate the method overriding


5 Program to illustrate the concept of vectors.

6 Program to demonstrate the concept of wrapper class & methods.

7 Program to create the threads using runnable interface.

8 Write a java program to implement Graphics Program to Draw CIRCLE.

9 Write a java program to implement Graphics Program to Draw RECTANGLE.

10 Write a java program to implement Graphics Program to Draw Barchat.

KLE SOCIETY’S, B.C.A., DEPARTMENT 27


SOLUTIONS

1. Write a java program to add two numbers.

Source code:
import java.util.Scanner;
public class AddTwoNumbers2 {

public static void main(String[] args) {

int num1, num2, sum;


Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();

System.out.println("Enter Second Number: ");


num2 = sc.nextInt();

sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}

Output:
Enter First Number:
121
Enter Second Number:
19
Sum of these numbers: 140

2.Write a Java program to calculate the simple interest


Source code:
import java.util.Scanner;
public class JavaExample
{
public static void main(String args[])
{

KLE SOCIETY’S, B.C.A., DEPARTMENT 28


float p, r, t, sinterest;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Principal : ");
p = scan.nextFloat();
System.out.print("Enter the Rate of interest : ");
r = scan.nextFloat();
System.out.print("Enter the Time period : ");
t = scan.nextFloat();
scan.close();
sinterest = (p * r * t) / 100;
System.out.print("Simple Interest is: " +sinterest);
}
}

Output:

Enter the Principal : 2000


Enter the Rate of interest : 6
Enter the Time period : 3
Simple Interest is: 360.0

3.Program to demonstrate the parameterized constructor


class contpara

contpara(int a,int b)

System.out.println("The constructor parameters are : " + a +" and " +b);

public class java_7

public static void main(String args[])

KLE SOCIETY’S, B.C.A., DEPARTMENT 29


contpara c= new contpara(10,5);

Output:

The constructor parameters are: 10 and 5

4.Program to demonstrate the method overriding


Source code:
class Base
{
void type()
{
System.out.println("This is base Class");
}
}
class B1 extends Base
{
void type()
{
System.out.println("This is Class B1");
}
}
class B2 extends Base
{
void type()
{
System.out.println("This is Class B2");
}
}
class java13
{
public static void main(String args[])
{
B1 b1 = new B1();
B2 b2 = new B2();

KLE SOCIETY’S, B.C.A., DEPARTMENT 30


b1.type();
b2.type();
}
}

Output:

This is Class B1
This is Class B2

5. Program to illustrate the concept of vectors.

Source code:

import java.util.Vector;

public class VectorDemo {


public static void main(String args[])
{
Vector v = new Vector();
v.add("C");
v.add("C++");
v.add("JAVA");
v.add("J2EE");
System.out.println("initially the vector contents:" +v.toString());
System.out.println("the last element:" +v.lastElement());
System.out.println("the element at 2nd position:" +v.elementAt(2));
v.insertElementAt("VB",1);
v.insertElementAt("#c",0);
System.out.println("after inserting the vector contents:" +v.toString());
v.removeElementAt(3);
System.out.println("after removing the element(3)- the contents:" +v.toString());
v.setElementAt("C++", 1);
v.remove("VB");
System.out.println("after remove (VB) -the vector contents:" +v.toString());

KLE SOCIETY’S, B.C.A., DEPARTMENT 31


}

Output:

initially the vector contents:[C, C++, JAVA, J2EE]


the last element:J2EE
the element at 2nd position:JAVA
after inserting the vector contents:[#c, C, VB, C++, JAVA, J2EE]
after removing the element(3)- the contents:[#c, C, VB, JAVA, J2EE]
after remove (VB) -the vector contents:[#c, C++, JAVA, J2EE]

6. Program to demonstrate the concept of wrapper class & methods.


public class WrapperObjectsDemo {

public static void main(String[] args) {


int i=100;
Integer i1=new Integer(i);
Integer i2=Integer.valueOf("200");
System.out.println("The primitive value of i1=" +i1.intValue());
System.out.println("The primitive value of i2=" +i2.intValue());
String str1="12345";
int num2=Integer.parseInt(str1);
System.out.println(" the value of num 2="+num2);
System.out.println(" the string value of i1="+i1.toString());
System.out.println(" the string value of i2="+i2.toString());
}
}

Output:

The primitive value of i1=100


The primitive value of i2=200
the value of num 2=12345
the string value of i1=100
the string value of i2=200

KLE SOCIETY’S, B.C.A., DEPARTMENT 32


7.Program to create the threads using runnable interface.

Source code:

class demo1 implements Runnable

public void run()

System.out.println("Thread is running");

public class pgm20

public static void main(String args[])

demo1 d=new demo1();

Thread t=new Thread(d);

t.start();

Output:

Thread is running

KLE SOCIETY’S, B.C.A., DEPARTMENT 33


8. Write a java program to implement Graphics Program to Draw CIRCLE.
Source code:

import java.awt.*;

import java.applet.*;

public class test extends Applet

public void paint(Graphics g)

g.setColor(Color.red);

g.drawOval(40, 40, 50, 50);

g.fillOval(40, 40, 50, 50);

Output:

9. Write a java program to implement Graphics Program to Draw RECTANGLE.

Source code:

import java.awt.*;

import java.applet.*;

public class test extends Applet

KLE SOCIETY’S, B.C.A., DEPARTMENT 34


{

public void paint(Graphics g)

g.drawRect(40, 40, 80, 50);

Output:

10. Write a java program to implement Graphics Program to Draw Barchart.

Source code:

import java.awt.Graphics;
public class Barchart extends java.applet.Applet {
public void paint(Graphics g){
String year[]={"2006", "2007", "2008", "2009", "2010"};
int amount[]={120,140,135,150,170};
for(int i=0;i<5;i++){
g.drawString(year[i], 20, i*50+30);
g.fillRect(50, i*50+10, amount[i], 40);

KLE SOCIETY’S, B.C.A., DEPARTMENT 35


Output:

KLE SOCIETY’S, B.C.A., DEPARTMENT 36

You might also like