Java
Java
Java Programming
Q1 Write a program in java to display Hello World?
import java.*;
class hello
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Q2.Write a program to find out the length of arry?
import java.*;
class ary
{
public static void main(String args[])
{
int a[]=new int[10];
int a1[]={3,5,7,1,8,99,44};
int a2[]={4,3,2,1};
System.out.println("Length of a1 is"+a1.length);
System.out.println("Length of a2 is"+a2.length);
}
}
Q3.Write a program to find out SquareRoot number?
import java.*;
import java.math.*;
class SquareRoot
{
public static void main(String args[])
{
double number,root=1;
number=25;
root=Math.sqrt(number);
System.out.println(root);
}
}
Q4.Write a program to add two number using BufferedReader class give (input from keyboard)?
import java.io.*;
class SumTwo
{
public static void main(String args[]) throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n1=0,n2=0,sum=0,len;
String number;
System.out.print("Enter the First number:");
2
number=in.readLine();
n1=Integer.parseInt(number);
System.out.print("Enter the Second number:");
number=in.readLine();
n2=Integer.parseInt(number);
sum=n1+n2;
System.out.println("Sum = "+sum);
}
}
Q5.Write a program to add two number using DataInputStream class give (input from keyboard)?
import java.io.*;
class AddTwo
{
public static void main(String args[]) throws IOException
{
DataInputStream in=new DataInputStream(System.in);
int n1=0,n2=0,sum=0,len;
String number;
System.out.print("Enter the First number:");
number=in.readLine();
n1=Integer.parseInt(number);
System.out.print("Enter the Second number:");
number=in.readLine();
n2=Integer.parseInt(number);
sum=n1+n2;
System.out.println("Sum = "+sum);
}
}
{
char c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters to Quit.");
do
{
c=(char)br.read();
System.out.print(c);
}while(c!='Q');
}
}
Q 8. Write a program to find out max value using if condition?
import java.*;
class Maxof2{
public static void main(String args[])
{
int i = 10;
int j = 15;
if(i > j)
System.out.println(i+" is greater than "+j);
else
System.out.println(j+" is greater than "+i);
}
}
Q9. Write a program in java display Day of the week using Switch case?
import java.*;
import java.io.*;
class SwitchWeek{
public static void main(String args[]) throws IOException
{
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Invalid value Entered");
}
}
}
Q11. Write a program to create a table give input number from keyboard?
import java.*;
import java.io.*;
class table
{
public static void main(String args[]) throws IOException
{
pi=3.1416;
a=pi*r*r;
System.out.println("Area of circle is "+a);
}
}
Q19. Write a program to generate Fibonacci series give input from keyboard?
import java.*;
import java.io.*;
class Fibonacci
{
public static void main(String args[]) throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n1=0,f1, f2=0, f3=1;
String number;
System.out.print("Please input integer number :");
number=in.readLine();
n1=Integer.parseInt(number);
System.out.println("*****Fibonacci Series*****");
for(int i=1;i<=n1;i++){
System.out.println(" "+f3+" ");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
}
}
import java.*;
class Circle
{
static final float PI=3.1415f;
float puCost; //Say cost of painting unit area
float radius;
float area()
{
return PI*radius*radius;
}
float calCost()
{
float cost=puCost*area();
return cost;
}
Q23. Write a program to calculate the area of Circle, Rectangle, Square using Method overloading?
import java.*;
class CircleArOverload
{
static final double PI=3.1415;
static double area(double radius)//area of circle
{
return PI*radius*radius;
}
static float area(float length,float width)//area of rectangle
{
return length*width;
}
9
Q25. Write a program to find out the volume of box and weight of box using inheritance?
import java.*;
import java.lang.*;
class Box
{
double width;
double height;
double depth;
Box(Box ob) //pass object of an constructor
{
width=ob.width;
height=ob.height;
depth=ob.depth;
}
Box(double w,double h,double d) // constructor used when all dimensions specified
{
width=w;
height=h;
depth=d;
}
}
}
}
}
class BoxVo
{
public static void main(String args[])
{
11
{
System.out.println("double a: " + a);
return a*a;
}
}
class Overload
{
public static void main(String args[])
{
MethodOverload overload = new MethodOverload();
double result;
overload.test(10);
overload.test(10, 20);
result = overload.test(5.5);
System.out.println("Result : " + result);
}
}
Q29. Write a program to generate Prime number (1-100) using for loop?
13
import java.*;
class PrimeNumber
{
public static void main(String[] args)
{ //define limit
int limit = 100;
System.out.println("Prime numbers between 1 and " + limit);
//loop through the numbers one by one
for(int i=1; i < 100; i++)
{
boolean isPrime = true;
//check to see if the number is prime
for(int j=2; j < i ; j++)
{
if(i % j == 0)
{
isPrime = false;
break;
}
} // print the number
if(isPrime)
System.out.print(i + " ");
}
}
}
Q30. Write a program to calculate volume of Box using the Box.java and BoxDemo.Java belong to the
package p1?
// First Program Box.java
package p1;
import java.*;
class Box
{
double width;
double height;
double depth;
}
class Box
{
double w;
double h;
double d;
}
class BoxDemo
{
public static void main(String args[])
{
Box b= new Box();
double vol;
14
b.w=10;
b.h=20;
b.d=15;
vol=b.w*b.h*b.d;
System.out.println("Vol.ume is :"+vol);
}
}
/*Note: If you want to run your program in command prompt then use this command
The folder p1 will be created automatically (if it does not exit),in the working folder if you compile
the above java files using this command :
Javac –d Box.java
Javac -d BoxDemo.java
To run the above program you should put both class in the folder p1 in the working folder and then
give the following Command from the Working folder(parent of p1)
Java p1.Box.demo */
A(int x)
{ a=x;
}
}
public void methodofA()
{
System.out.println(" Method Of A " +a);
}
public String MethodofIntfB()
{
String s2="Method-B";
return s2;
}
public static void main(String args[])
{
A a1=new A();
javaInterfaceExample.sayHello();
}
}
Q34. write a program in java to findout given number is palindrome or not ,using IO or
ExceptionHandling?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PalindromeNum
{
public static void main(String[] args)
{
System.out.println("Enter the number to check..");
int number = 0;
try
{
//take input from console
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//parse the line into int
number = Integer.parseInt(br.readLine());
}
catch(NumberFormatException ne)
{
System.out.println("Invalid input: " + ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println("I/O Error: " + ioe);
System.exit(0);
}
System.out.println("Number is " + number);
int n = number;
int reversedNumber = 0;
int temp=0; //reverse the number
while(n > 0)
{
temp = n % 10;
n = n / 10;
reversedNumber = reversedNumber * 10 + temp;
}
/ * if the number and it's reversed number are same, the number is a palindrome number or not */
if(number == reversedNumber)
System.out.println(number + " is a palindrome number");
else
System.out.println(number + " is not a palindrome number");
}
}
17
Q41.Write a program in java how to swap value of two numbers without using third variable using
java?
import java.*;
class SwapWithoutUsingThird {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
//add both the numbers and assign it to first
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("After Swapping");
System.out.println("Value of num1 is :" + num1);
System.out.println("Value of num2 is :" +num2);
}
}
Q42.Write a program to find a power using pow method of Java Math class.?
import java.*;
import java.io.*;
public class FindPower
{
public static void main(String[] args)
{
/* To find a value raised to power of another value, use
static double pow(double d1, double d2) method of Java Math class. */
//returns 2 raised to 2, i.e. 4
System.out.println(Math.pow(2,2));
//returns -3 raised to 2, i.e. 9
System.out.println(Math.pow(-3,2));
}
}
Q43.Write a program to use Java Calendar class to display current date and time.?
import java.*;
import java.util.Calendar;
public class TodayDate
{
public static void main(String[] args)
{
//use getInstance() method to get object of java Calendar class
Calendar cal = Calendar.getInstance();
//use getTime() method of Calendar class to get date and time
System.out.println("Today is : " + cal.getTime());
}
}
{
int d,a;
try
{//monitor a block of code.
d=0;
a=42/d;
System.out.println("This will not be printed");
}
catch(ArithmeticException e)
{//catch divide by zero error
System.out.println("Division by Zero.");
}
System.out.println("After catch Statement");
}
}
Q49.Wrtie a program in java to create Thread Calling sleep() to wait for a while?
import java.*;
import java.lang.*;
public class SleepingThread extends Thread
{
private int countDown = 5;
private static int threadCount = 0;
public SleepingThread() {
super("" + ++threadCount);
start();
}
public String toString()
{
return "#" + getName() + ": " + countDown;
}
public void run()
{
while (true)
{
System.out.println(this);
if (--countDown == 0)
return;
try
{
sleep(100);
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws InterruptedException
{
for (int i = 0; i < 5; i++)
new SleepingThread().join();
}
}
}
}
Q51.Write a program in java to create TwoSimple Thread?
import java.*;
import java.lang.*;
class TwoThread extends Thread
{
public void run()
{
24
}
public void start()
{
}
public void paint(Graphics g)
{
g.drawString("Hello from Java!", 60, 100);
}
public void stop()
{
}
public void destroy()
{
}
}
catch(NumberFormatException e)
{
fontSize=-1;
}
param=getParameter("leading");
try
{
if(param!=null)//if not found
leading=Float.valueOf(param).floatValue();
else
leading=0;
}
catch(NumberFormatException e)
{
leading=-1;
}
param=getParameter("accountEnabled");
if(param!=null)
active = Boolean.valueOf(param).booleanValue();
}
public void paint(Graphics g)
{
g.drawString("Font Name :"+fontName, 0, 10);
g.drawString("Font Size :"+fontSize, 0, 26);
g.drawString("Font Name :"+leading , 0, 42);
g.drawString("Font Name :"+active, 0, 58);
}
}
Q55.Write a applet program in java to type a text in textbox and press on button to show display
message ?
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*
<APPLET CODE=applet2.class WIDTH=200 HEIGHT=200 > </APPLET> */
public class applet2 extends Applet implements ActionListener
{
TextField text1;
Button button1;
public void init()
{
text1 = new TextField(20);
add(text1);
button1 = new Button("Click Here!");
add(button1);
button1.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
String msg = new String ("Hello from Java!");
if(event.getSource() == button1){
text1.setText(msg);
}
} }
Q56. Write an applet Program to show Set Status Message in Applet Window Example?
27
import java.awt.*;
import java.applet.Applet;
import java.awt.Graphics;
/*<applet code=SetStatusMessage” width=200 height=200></applet>*/
public class SetStatusMessage extends Applet
{
public void paint(Graphics g)
{
/* Show status message in an Applet window using
Void showStatus(String msg) method of an applet of an applet class. */
//This will be displayed inside an applet
g.drawString(“Show Status Example”,50,50);
//this will be displayed in a status bar of an applet window
showStatus(“This is a Status message of an applet window”);
}
}
Q57. Write an applet program to Draw Rectangle & Square in Applet Window?
import java.awt.*;
import java.applet.Applet;
import java.awt.Graphics;
/*<applet code=DrawRectangle” width=200 height=200></applet>*/
public class DrawRectangle extends Applet
{
public void paint(Graphics g)
{
/*To draw rectangle in an applet window use,
void drawRect(int x1, int y1, int width, int height)method.
This method draws a rectangle of width 50 & height 100 at(10,10). */
g.drawRect(10,10,50,100);
// If you Specify same width & height, the drawRect method will be draw a square!
g.drawRect(100,100,50,50);
}
}
Q58. Write an applet program to Draw Oval & Circle in Applet Window?
import java.awt.*;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
/*<applet code=DrawOvals” width=500 height=500></applet>*/
public class DrawOvals extends Applet
{
public void paint(Graphics g)
{
//Set Color to Red
setForeground(Color.red)
/* To draw an oval in an applet window use, void drawOval(int x1, int y1,int width, int height)
method . This method draws a oval of specified width and height at(x1,y1). This will draw a Oval of
height at(x1,y1)*/
g.drawOval(10,10,50,100);
g.fillOval(100,20,50,100);
}
}
Q59. Write an applet program to create a Button using AWT Button class?
28
import java.awt.*;
import java.applet.Applet;
import java.awt.Button;
/*<applet code=CreateAWTButton” width=200 height=200></applet>*/
public class CreateAWTButton extends Applet
{
public void init()
{
//To create a button use Button() constructor.
Button button1=new Button();
/*Set button caption or label using void setLabel(String text)
Method of AWT Button class.*/
button1.setLabel(“My Button1”);
/*To create button with the caption use Button(String text) constructor of
AWT Button class.*/
Button button2=new Button(“My Button 2”);
// add buttons using add method
add(button1);
add(button2);
}
}
Q60. Write an applet program to handle action event of AWT Button by implementing ActionListener
interface?
import java.awt.*;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*<applet code= “HandleActionEvent” width=200 height=200></applet>*/
public class HandleActionEvent extends Applet implements ActionListener
{
String actionMessage=””;
public void init()
{
//create button
Button Button1=new Button(“Ok”);
Button Button2=new Button(“Cancel”);
// add buttons using add method
add(Button1);
add(Button2);
//set action Listener for buttons
Button1.addActionListener(this);
Button2.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString(actionMessage,10,50);
}
public void actionPerformed(ActionEvent ae)
{
//Get the action command using String getActionCommand() method.
String action=ae.getActionCommand();
if(action.equals(“Ok”))
29
//create checkboxes
Java=new Checkbox(“Java”);
VB=new Checkbox(“Visual Basic”);
C=new Checkbox(“C Languages”);
add(Java);
add(VB);
add(C);
add(C++);
//add item Listeners
Java.addItemListener(this)
VBaddItemListener(this)
C.addItemListener(this)
}
{
g.drawString(“Java:”+java.getState(),10,80);
g.drawString(“VB:”+VB.getState(),10,100);
g.drawString(“C:”+C.getState(),10,120);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
}
Q63. Write an applet program to create a choice or combobox using Java AWT Choice class?
import java.awt.*;
import java.applet.Applet;
import java.awt.Choice;
/*<applet code= “CreateChoiceExmaple” width=200 height=200></applet>*/
public class CreateChoiceExmaple extends Applet
{
public void init()
{
/* To create a AWT choice control or a combo box, Use Choice() constructor of AWT Choice
Class.*/
Choice Language=new Choice();
/* To add items in a choice control or a combobox, use void add(string item)
Method of AWT Choice class.*/
Language.add(“Java”);
Language.add(“VB”);
Language.add(“Perl”);
//add choice or combobox
add(Language);
}
}
Q64. Write an applet program to show on applet window get selected item of a choice or combobox?
import java.awt.*;
import java.applet.Applet;
import java.awt.Choice;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListner;
/*<applet code= “GetSelectedItem” width=200 height=200></applet>*/
public class GetSelectedItem extends Applet implements ItemListener
{
Choice Language=null;
public void init()
{
add(Language);
//add itemListener(this);
}
public void paint(Graphics g)
{
// to get Selected item, use String getSelectedItem() method of AWT() Choice class.
g.drawString(Language.getSelectedItem(),10,70);
}
public void itemStateChanged(ItemEvent arg0)
{
repaint();
}
}
Q65. Write an applet program to insert Item in Combo Box Using AWT Choice Classes?
import java.awt.*;
import java.applet.Applet;
import java.awt.Choice;
/*<applet code= “InsertItem” width=200 height=200></applet>*/
public class InsertItem extends Applet
{
Choice Language=null;
public void init()
{
//if you create a checkboxes and add to group, they become radio buttons
32
Q68.Write an applet program to draw Line,Rectangle and fill color using AWT Graphics?
import java.awt.*;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
/*<applet code=SetGraphicsColor” width=200 height=100></applet>*/
public class SetGraphicsColor extends Applet
{
public void paint(Graphics g)
{
/Graphics objects like Lines and rectangles uses current foreground color.
To Change the Current graphics color use void setColor(color c) method of Graphics class*/
//This will create light blue color
Color customColor=new Color(10,10,255);
g.setColor(customColor);
g.drawLine(10,10,30,30);
g.setColor(Color.red);
g.fillRect(40,40,40,40);
g.setColor(Color.green);
g.fillRect(80,80,40,40);
g.draw3DRect(81,81,40,40,true);
}
}
{
setLayout(new BorderLayout());
button1=new ButtonLayout(“1”);
add(“North”,button1);
button1.addActionListener(this);
button2=new ButtonLayout(“2”);
add(“West”,button2);
button2.addActionListener(this);
button3=new ButtonLayout(“3”);
add(“South”,button3);
button3.addActionListener(this);
button4=new ButtonLayout(“4”);
add(“East”,button4);
button4.addActionListener(this);
Panel1=new textPanel();
add(“Center”,Panel1)
Panel1.Text1.setLocation(0,0);
}
public void actionPerformed(ActionEvent e)
{
Panel1.Text1.setText(“Button”+((Button)e.getSource()).getLabel()+ ”Clicked.”);
}
}
Q70.Write an applet program to create a textarea for type a text and display message when button
pressed?
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code=textarea.class” width=200 height=200></applet>*/
public class textarea extends Applet implements ActionListner
{
TextArea textarea1;
Button button1;
public void init()
{
textarea1=new TextArea(“”,10,20,TextArea.SCROLLBARS_BOTH);
add(textarea1);
button1=new Button(“Click Me”);
add(button1);
button1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String msg=”Hello from Java!”;
if(e.getSource()==button1)
{
Textarea1.insert(msg,0);
}
}
}