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

Public Class Public Static Void Int New Int If Return For Int

The document contains 7 code examples that demonstrate various Java programming concepts: 1. A program that reads numbers from the command line and calculates their factorials. 2. A program that finds all prime numbers between two given limits. 3. A program that sorts an integer array using bubble sort. 4. A program that implements various string operations like length, concatenation, uppercase/lowercase etc. 5. A program that calculates the area of different geometric shapes like circle, square, rectangle, triangle by defining methods for each shape. 6. A program that demonstrates constructor overloading by creating different constructors that accept varying number and types of parameters. 7. An applet

Uploaded by

shwetha k
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views

Public Class Public Static Void Int New Int If Return For Int

The document contains 7 code examples that demonstrate various Java programming concepts: 1. A program that reads numbers from the command line and calculates their factorials. 2. A program that finds all prime numbers between two given limits. 3. A program that sorts an integer array using bubble sort. 4. A program that implements various string operations like length, concatenation, uppercase/lowercase etc. 5. A program that calculates the area of different geometric shapes like circle, square, rectangle, triangle by defining methods for each shape. 6. A program that demonstrates constructor overloading by creating different constructors that accept varying number and types of parameters. 7. An applet

Uploaded by

shwetha k
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 18

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[])
  {
     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
7

3.
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");

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;

Output:

4.Write a program to implement all string operations.

Solution:
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("first char of "+s2+" is ="+s2.toUpperCase());
// System.out.println("first char of "+s1+" is ="+s1.toLowerCase());
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)
{
System.out.println(" "+s1+" and " +s2+" are not same");

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

Output:
thr string sre javaandprogrammig
length of javais = 4
length of programmigis = 10
the concation of 2 strings javaprogrammig
first char of java is =j
second char of programmig is =p
string first java is =JAVA
second string of programmig is =programmig
v occurs at position 2 in java
substrig ofprogrammigstarting from index 3 and ending at 7 is = gram
replacing 'v' with 'z' in java is = jaza
java and programmig 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)


   {
       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));

      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:

6.Write a program to implement constructor overloading by passing


different number of parameter of different types.
Source code
public class cube {
int length,breadth,height;
public int getvolume()
{
return(length*breadth*height);
}
cube()
{
length=breadth=height=2;
System.out.println("Initialized with different constructor");
}
cube(int l,int b)
{
length=l;
breadth=b;
height=2;
System.out.println("Initialized with parameterized constructor having 2
parameters");
}
cube(int l,int b, int h)
{
length=l;
breadth=b;
height=h;
System.out.println("Initialized with parameterized constructor having 3
parameters");
}
public static void main(String args[])
{
cube cubeobj1=new cube();
System.out.println("Volume of cube1:"+cubeobj1.getvolume());

cube cubeobj2=new cube(10,20);


System.out.println("Volume of cube2:"+cubeobj2.getvolume());

cube cubeobj3=new cube(10,20,30);


System.out.println("Volume of cube3:"+cubeobj3.getvolume());
}
}

Output:
Initialized with different constructor
Volume of cube1:8

Initialized with parameterized constructor having 2 parameters

Volume of cube2:400

Initialized with parameterized constructor having 3 parameters

Volume of cube3: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);
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);

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;


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);
}
}
import java.io.*;
class Area
{
   public static double circleArea(double r)
   {
      return Math.PI*r*r;
   }

   public static double squareArea(double side)


   {
       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));

      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));

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


method overriding.
Source code
abstract class Department {
double salary, bonus, totalsalary;
public void calBonus (double salary) {
}public void displaytotalsalary (String dept){
System.out.println(dept+ "\t" +salary+ "\t\t" +salary+ "\t\t" +bonus+ "\t"
+totalsalary);
}
}
class Accounts extends Department{
public void calBonus(double sal){
salary=sal;
bonus=sal*0.2;
totalsalary=sal+bonus;
}
}
class Sales extends Department{
public void calBonus(double sal){
salary=sal;
bonus=sal*0.3;
totalsalary=sal+bonus;
}
}
class BonusCalculate{
public static void main(String[] args) {
Department acc=new Accounts();
Department sales=new Sales();
acc.calBonus(10000);
sales.calBonus(20000);
System.out.println("Department \t salary \t bonus \t totalsalary");
System.out.println("_ _ _ _ _ _ _ _ _ _ _");
acc.displaytotalsalary("Accounts");
sales.displaytotalsalary("Sales");
System.out.println("_ _ _ _ _ _ _ _ _ _ _");
}
}

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;
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;
}
}

10.AWrite a program to implement mouse events.

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

import java.applet.*;

/* <applet code="Mouse event" width=300 height=300> </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();

public void mouseClicked(MouseEvent me){

str="Mouse Button Clicked";

repaint();

public void mouseReleased(MouseEvent me){

str="Mouse Button Released";

repaint();

public void mouseEntered(MouseEvent me){

str="Mouse Button Entered";

repaint();

public void mouseExited(MouseEvent me){

str="Mouse Button Exited";

repaint();

}
public void mouseMoved(MouseEvent me){

str="Mouse Button Moved";

repaint();

public void mouseDropped(MouseEvent me){

str="Mouse Button Dropped";

repaint();

public void mouseDragged(MouseEvent me){

str="Mouse Button Dragged";

repaint();

Output:

12.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)

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);

You might also like