Frequently asked Java Programs

 1. Write a Java program that prints all real solutions to the quadratic equation ax^2+bx+c=0.

import java.io.*;

public class Quad

{

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

 {

  int a,b,c,d;

  double res1=0,res2=0;

  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

  a=Integer.parseInt(br.readLine());

  b=Integer.parseInt(br.readLine());

  c=Integer.parseInt(br.readLine());

  d=b*b-4*a*c;

  if(d<0)

  {

    System.out.println("no real solutions");

   }

  else

   {

    res1=((-b)+Math.sqrt(d))/(2*a);

    res2=((-b)-Math.sqrt(d))/(2*a);

   }

    System.out.println("The real roots are");

     System.out.println(res1);

      System.out.println(res2);

  }

}

2.Write a JAVAPROGRAM that uses nonrecursive functions to print the Fibonacci sequence below a value n

import java.io.*;

public class Fibonacci

{

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

 {

  int a=1,b=1,c,n;

  System.out.println("Enter n value");

  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

  n=Integer.parseInt(br.readLine());

    System.out.println(a+ "  " +b);

    c=a+b;

    while(c<n)

     { 

      System.out.println(c);

      a=b;

      b=c;

       c=a+b;

      }

  }

}

3.Write a java program that prompts the user for an integer and then prints out all prime numbers up to that number.

import java.io.*;

public class Prime 

{

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

 {

  int n,count,i,j;

  System.out.println("Enter n value");

  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

  n=Integer.parseInt(br.readLine());

  for(i=2;i<=n;i++)

  {

   count=1;

   for(j=2;j<i;j++)

    {

      if(i%j==0)

       {

           count=0;

           break;

        }     

     } 

    System.out.println("The primenumbers are");   

    if(count==1)

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

  }  

}

}

4.Write a Java program that checks whether a given string is a palindrome or not.

import java.io.*;

public class Palindrome 

{

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

 {

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

  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

  String string=br.readLine();

  StringBuffer str=new StringBuffer(string);

  StringBuffer str1=str.reverse();

  if(str.equals(str1))

      System.out.println("The given String "+ str+" is a palindrome");   

   else

      System.out.println("The given String" + str+" is not a palindrome");   

  }  

}

5.Write a java program that reads a line of integers and then displays each integer and find the sum of the integers (using StringTokenizer)

import java.io.*;

import java.util.*;

public class Sum

{

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

 {

  String str;

   int a,sum=0;

  System.out.println("enter the integers seperated by comma");

  BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));

  str=bf.readLine();

  StringTokenizer str1=new StringTokenizer (str,",");

   System.out.println("the integers are");

  while (str1.hasMoreTokens ())

  {

   a=Integer.parseInt(str1.nextToken());

   sum=sum+a;

   System.out.println(a); 

  }

 System.out.println("The sum is "+ sum);   

}

}

6.Write a java program that reads a file name from the user then displays information about whether that file exists, file is readable, file is writable, the type of file and length of the file in bytes.

import java.io.*;

import java.util.*;

public class Fileprop

{

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

 {

  String str;

   System.out.println("enter the file name");

  BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));

  str=bf.readLine();

  File f=new File(str);

  if(f.exists())

    System.out.println("the file exists");

   long l=f.length();

  System.out.println("The length of the file is"+ l);

    if(f.canWrite())

   { 

    System.out.println("The file "+  str  +  "  is writable");

   }

  if(f.canRead())

      {

    System.out.println("The file "+  str  +  "  is readable");

   }

 }

}

7.Write a java program that reads a file and displays the file on the screen with a line number before each line.
import java.io.*;
import java.util.*;
public class Linecount
{
 public static void main(String arg[])throws Exception
 {
  String str, str1;
  int count=0;
   System.out.println("enter the file name");
  BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
  str=bf.readLine();
  BufferedReader bf1=new BufferedReader(new FileReader(str));
  while((str1=bf1.readLine())!=null)
 {
  System.out.println(++count   +  str1);
 }
 }
}
8.Write a java program that reads a file and displays the no of lines and words in that file
import java.io.*;
import java.util.*;
public class Count
{
 public static void main(String arg[])throws Exception
 {
  String str,str1;
  int lcount=0,wcount=0,ccount=0;
   System.out.println("enter the file name");
  BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
  str=bf.readLine();
  BufferedReader bf1=new BufferedReader(new FileReader(str));
  while((str1=bf1.readLine())!=null)
  {
   ++lcount;
  StringTokenizer str2=new StringTokenizer(str1," ");
  while(str2.hasMoreTokens())
  {
    String s1=str2.nextToken();
    ++wcount;
  }
 }
  System.out.println("the no of lines are"+  lcount);
  System.out.println("the no of words are"+  wcount);
 }
}

9.Write an applet that displays a simple message?

import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet.class" width=40 height=50>
</applet>
*/
public class Simpleapplet extends Applet
{
 public void paint(Graphics g)
  {
   g.drawString("This is  a simpleapplet",20,30);
   System.out.println("helloworld");
  }
}

10.Write a program that creates a user interface to  perform integer divisions . The user enters two numbers in the text fields , Num1 and Num2 .The divisin of Num1 and Num2 is displayed in the Result field when the Divide button is clicked.If Num1 or Num2 were not an integer.,the pogram would throw a NumberFormatException.If Nub2 were Zero, the program whould throw an ArithmeticException .Display the exception  in a message dialog box.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DivideWindow extends Frame implements ActionListener
{
    Label l1,l2,l3;
    TextField t1,t2,t3;
    Button b1;
    DivideWindow()
   {
     //setting the size of the window
     setSize(250,400);
     l1=new Label("First Number :");
     l2=new Label("Second Number:");
     l3=new Label("RESULT       :");
     t1=new TextField(10);
    t2=new TextField(10);
    t3=new TextField(10);
    b1=new Button("Divide");
    //setting the layout of the container window
    setLayout(new FlowLayout());
   //adding the controls to the container window
    add(l1);
    add(t1);
    add(l2);
    add(t2);
    add(l3);
    add(t3);
    add(b1);
    b1.addActionListener(this);
    setVisible(true);
}

public void actionPerformed(ActionEvent ae)
{
    try
   {
 int n1=Integer.parseInt(t1.getText());
 int n2=Integer.parseInt(t2.getText());
 if(ae.getSource()==b1)
 {
 int div=n1/n2;
 t3.setText(div+"");
 }
    
  }catch(NumberFormatException nfe)
   {
            JOptionPane.showMessageDialog(null,"NumberFormatException");
   }
   catch(ArithmeticException e)
   {
  JOptionPane.showMessageDialog(null,"ArithmeticExceptin");
   }

}//actionPerformed method

public static void main(String args[])
{
  new DivideWindow();
}//main method

}//class

11.Write a java program that implants a client / server application. The client / server application. The client displays the result, and then sends result back to the client. The client displays the result on the console. 
For Ex. the data sent form the client is the radius of the circle, and the result produce by the server is the area of the circle.

Server side program:

import java.io.*;
import java.net.*;
class server
{
public static void main(String args[ ]) throws Exception
{
ServerSocket ss=new ServerSocket(8080);
System.out.println(“wait for client request”);
Socket s=ss.accept( );
BufferReader br;
PrintStream ps;
String str;
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
str=br.readLine();
System.out.println(“received radius”);
double r=Double.parseDouble(str);
double area=3.14*r*r;
ps=new PrintStream(s.getOutputStream());
ps.println(String.valueOf(area));
ps.close();
br.close( );
s.close();
ss.close( );
}
}

Client side program:

import java.io.*;
import java.net.*;
class client
{
public static void main(String[ ] args) throws Exception
{
Socket s=new Socket(“localhost”,8080);
BufferedReader br;
PrintStream ps;
String str;
System.out.println(“enter the radius to send the server.”);
br=new BufferedReader(new InputStreamReader(System.in));
ps=new PrintStream(s.getOutputStream());
ps.println(br.readLine());
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
str=br.readLine();
System.out.println(“area of the circle:” +str);
br.close();
ps.close();
}
}

12.Write a java program that simulates a traffic light. The program lets the user select one of three lights: red ,yellow ,or green .When  a radio button is selected , the light is turned on  and only one light can be on at a time .No light is on when the program starts.

import java.awt.*;
import java.awt.event.*;
class TrafficLights extends Frame implements ItemListener
{
  Checkbox b1,b2,b3;
  CheckboxGroup cbg;
  String msg="";
  
  TrafficLights()
  {
    setSize(400,400);
    //creating button group
    cbg = new CheckboxGroup();

    //creating radio buttons
    b1=new Checkbox("red",false,cbg);
    b2=new Checkbox("yellow",false,cbg);
    b3=new Checkbox("green",false,cbg);
    setLayout(new FlowLayout());
    add(b1);
    add(b2);
    add(b3);
    
    b1.addItemListener(this);
    b2.addItemListener(this);
    b3.addItemListener(this);
    setVisible(true);
  }
  public void itemStateChanged(ItemEvent ae)
  {
    msg=cbg.getSelectedCheckbox().getLabel();
    repaint();
  }
 
 public void paint(Graphics g)
  {
    g.drawOval(150,100,20,20);
    g.drawOval(150,130,20,20);
    g.drawOval(150,160,20,20);
    if(msg.equals("red"))
    {
      g.setColor(Color.red);
      g.fillOval(150,100,20,20);
    }
    else
      if(msg.equals("yellow"))
      {
          g.setColor(Color.yellow);
          g.fillOval(150,130,20,20);
      }
      else if(msg.equals("green"))
            {
             g.setColor(Color.green);
             g.fillOval(150,160,20,20);
            }
   }

  public static void main(String args[])
  {
   new TrafficLights();
  }

13.program to draw a line , rectangle on the window 

   import java.awt.*;
   class DrawingWindow extends Frame
   {
      DrawingWindow()
      {
        setSize(400,400);
        setVisible(true);
      }//constructor
      
     public void paint(Graphics g)
     {
       g.drawLine(30,30,120,80);
       g.setColor(new Color(0,0,255));
       g.drawRect(70,70,60,60);
       g.drawOval(200,200,100,100);
     }//paint
     
     public static void main(String args[])
     {
        new DrawingWindow();
     }//main
  }//DrawingWindow

14.Write a program to create an abstract class named Shape that contains an empty method named numberOfSides() . 
Provide three classes named TrapeZoid, Triangle and Hexagon such that each 
one of the classes extends the class Shape. Each one of the classes contains only the method numberOfSides() that shows the number of sides in the given geometrical figures.

abstract class Shape
{
  abstract void numberOfSides();
}//class

class TrapeZoid extends Shape
{
 void numberOfSides()
 {
   System.out.println("Four sides");
 }
}//class

class Triangle extends Shape
{
  void numberOfSides()
  {
    System.out.println("Three sides");
  }
}//class
class Hexagon extends Shape
{
  void numberOfSides()
  {
    System.out.println("Six sides");
  }
}//class
class ShapeDemo
{
  public static void main(String args[])
  {
    Shape s;
    s=new TrapeZoid();
    s.numberOfSides();
    s=new Triangle();
    s.numberOfSides();
    s=new Hexagon();
    s.numberOfSides();
  }//main
}//class

          
Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

No comments:

Post a Comment