Java (1)

39
1 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

Transcript of Java (1)

Page 1: Java (1)

1

Java ProgrammingQ1 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:");

Page 2: Java (1)

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

}}

Q6. Write a program to write a text line and show it ?import java.*;import java.io.*;class BLine{ public static void main(String arg[]) throws IOException { String str; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter lines of the text."); System.out.println("Enter 'stop' to quit."); do { str=br.readLine(); System.out.println(str); }while(!str.equals("stop")); }}

Q7.Write a program to enter characters and show it on console?import java.*;import java.io.*;class Bread{ public static void main(String arg[]) throws IOException

Page 3: Java (1)

3

{ 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 { BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

int n1=0; String number; System.out.print("Enter number (1 to 7) :");

number=in.readLine(); n1=Integer.parseInt(number);

switch(n1) { case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tuesday"); break; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday"); break;

Page 4: Java (1)

4

case 6: System.out.println("Friday"); break; case 7: System.out.println("Saturday"); break; default: System.out.println("Invalid value Entered"); } }}

Q10.Write a program display reverse number 10 to 1 using for loop ?import java.*;class lpd{public static void main(String args[]){for(int i=10;i>0;i--){System.out.println(i); } }}

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 { BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

int n1=0,t; String number; System.out.print("Enter number :");

number=in.readLine(); n1=Integer.parseInt(number);

for(int i=1;i<=10;i++){

t=i*n1;System.out.println(t); } }}

Q12. Write a program to compute the area of circle?import java.*;class CircleArea{

public static void main(String args[]){

double pi,r,a;r=10.8;

Page 5: Java (1)

5

pi=3.1416;a=pi*r*r;System.out.println("Area of circle is "+a);

}}

Q13.Write a program to print character variable using ASCII code?import java.*;class ch{ public static void main(String args[ ]) { char ch1,ch2;

ch1=88;ch2='y';System.out.println("Ch1 and Ch2 : ");System.out.println(ch1+ " " + ch2);

}}

Q14. Write a program in java using type conversion?import java.*;class Conversion{

public static void main(String args[]){

byte b;int i=257;double d=323.142;System.out.println("\nConversion of int to byte .");b=(byte)i;System.out.println("i and b " +i + " "+b);System.out.println("\nConversion of double to int .");i=(int)d;System.out.println("d and i " + d + " "+i);System.out.println("\nConversion of double to byte .");b=(byte)d;System.out.println("d and b " + d + " "+b);

}}Q15.Write a program to find out average of the array element?import java.*;class Avg{ public static void main(String arg[]) { double num [ ]={5.54,5.25,5.8,5.75}; double res=0;for(int i=0;i<4;i++){res=res+num[i] ;}System.out.println("Average is " + res/4); }}

Page 6: Java (1)

6

Q16. Write a program in java to display 5 Random number( 1 to 100)?import java.*;import java.math.*;class RandomNumber{ public static void main(String args[]) { for(int i=1;i<=5;i++){ System.out.println((int)(Math.random()*100)); } }}Q17 write a program to calculate Factorial number using while loop?import java.*;import java.io.*;class Factorial{ public static void main(String args[]) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

int n1=0,result=1; String number; System.out.print("Enter number (1 to 9) :");

number=in.readLine(); n1=Integer.parseInt(number);

while(n1>0){ result = result * n1; n1--; } System.out.println("Factorial of "+ number +" is : "+result); }}Q18.Write a program input from keyboard and display Reverse Number ?import java.*;import java.io.*;class Reverse{ public static void main(String args[]) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

int n1=0,result=0,remainder; String number; System.out.print("Please input integer number :");

number=in.readLine(); n1=Integer.parseInt(number);

while(n1>0){ remainder = n1%10; result = result * 10 + remainder; n1 = n1/10; } System.out.println("Reverse number is : "+result); }}

Page 7: Java (1)

7

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

Q20.write a program in java to display multiplication table using for loop?import java.*;import java.io.*;class MulTable{ public static void main(String args[]) throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

int n1=0; String number; System.out.print("Please input integer number :");

number=in.readLine(); n1=Integer.parseInt(number);

System.out.println("*****MULTIPLICATION TABLE*****"); for(int i=1;i<=n1;i++) { for(int j=1;j<=10;j++) { System.out.print(" "+ i * j + " "); } System.out.print("\n"); } }}Q21.Write a program in java to find out even or odd number using if condition?import java.*;import java.io.*;class EvenOddNumber{ public static void main(String args[]) throws IOException {

Page 8: Java (1)

8

BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int n1=0; String number; System.out.print("Please input integer number :");

number=in.readLine(); n1=Integer.parseInt(number); if(n1%2==0) System.out.println(number + " is Even Number."); else System.out.println(number + " is Odd Number."); }

}

Q 22.Write a program to calculate the cost of printing Circle?

import java.*;class Circle{

static final float PI=3.1415f;float puCost; //Say cost of painting unit areafloat radius;float area(){

return PI*radius*radius;}float calCost(){

float cost=puCost*area();return cost;

}

public static void main(String args[]){

Circle c=new Circle();c.puCost=100;c.radius=3;float area=c.calCost();System.out.println("Cost of painting Circle is" +area);

}}

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

Page 9: Java (1)

9

static float area(float size)//area of square{ return size * size;}public static void main(String args[]){

double carea=area(3.0);// Circle's area() method is invokedSystem.out.println("Area of Circle is :"+carea);double rarea=area(3.0f,4.0f);// Circle's area() method is invokedSystem.out.println("Area of Rectangle is :"+rarea);double sarea=area(3.0f);// Square's area() method is invokedSystem.out.println("Area of Square is :"+sarea);

}}

Q24.Write a program inherit class a to class b using extends keyword?import java.*;class A{ int i,j;

void show1(){ System.out.println(i);

System.out.println(j);}

}class B extends A{

int k;void show2(){ System.out.println(k); }void sum(){ System.out.println(i+j+k); }}

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

{A a=new A();B b=new B();a.i=10;a.j=20;System.out.println("Contents of a");a.show1();b.i=7;b.j=8;b.k=9;System.out.println("Contents of a and b");b.show1();b.show2();a.show1();System.out.println("Sum of i,j and k is:");b.sum();

}}

Page 10: Java (1)

10

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;

} Box() // constructor used no dimensions specified

{width=-1; //use -1 to indicateheight=-1; //an unintializeddepth=-1; //box

} Box(double len) // constructor used when cube is created {

width=height=depth=len;}

double volume() {

return width*height*depth; }}

class Box1 extends Box { double weight; Box1(double w,double h,double d, double m) // constructor for Box1

{ width=w;

height=h;depth=d;weight=m;

}}class BoxVo{

public static void main(String args[]){

Page 11: Java (1)

11

Box1 box1=new Box1(10,20,15,34.3); Box1 box2=new Box1(2,3,4,0.076); double vol; vol=box1.volume(); System.out.println("Volume of box1 is :"+vol) ; System.out.println("Weight of box1 is :"+box1.weight) ; System.out.println("Volume of box1 is :"+vol) ; vol=box2.volume(); System.out.println("Volume of box2 is :"+vol) ; System.out.println("Weight of box2 is :"+box2.weight) ; }

}Q26. Write a program in java when constructor are called when child class object is created in case of a multi level hierarchy?import java.*;class A{ A() { System.out.println("Inside A's constructor."); }}class B extends A{ B() { System.out.println("Inside B's constructor."); }}class C extends B{ C() { System.out.println("Inside C's constructor."); }}class Super{ public static void main(String args[])

{ C c=new C(); }}

Q27.Write a program in java Test Method Overloading?import java.*;import java.lang.*;class MethodOverload {void test(int a) {System.out.println("a: " + a);}void test(int a, int b) {System.out.println("a and b: " + a + "," + b);}double test(double a)

Page 12: Java (1)

12

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

Q28. Write a program in java add number using Method Overriding?import java.*;import java.lang.*;class A {int i;A(int a, int b) {i = a+b;}void add() {System.out.println("Sum of a and b is: " + i);}}class B extends A {int j;B(int a, int b, int c) {super(a, b);j = a+b+c;}void add() {super.add();System.out.println("Sum of a, b and c is: " + j);} }class MethodOverriding {public static void main(String args[]) {B b = new B(10, 20, 30);b.add(); }}

Q29. Write a program to generate Prime number (1-100) using for loop?

Page 13: Java (1)

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 onefor(int i=1; i < 100; i++){

boolean isPrime = true; //check to see if the number is primefor(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.javapackage p1;import java.*;class Box{

double width;double height;double depth;

}

//Second Program BoxDemo.javapackage p1;import java.*;import java.lang.*;import java.util.*;

class Box{

double w;double h;double d;

}class BoxDemo{

public static void main(String args[]){

Box b= new Box();double vol;

Page 14: Java (1)

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 */

Q31.Wrtie a Program To find out Factorial Number using Recursion?import java.*;class Factorial{ long fact(int n) { if(n==1) return 1; else return n*fact(n-1); } public static void main(String ag[]) { Factorial f=new Factorial(); System.out.println("Factorial of 3 is "+f.fact(4)); System.out.println("Factorial of 4 is "+f.fact(5)); System.out.println("Factorial of 5 is "+f.fact(6)); }}Q32. Write a Program in java to implement in a class a use interface A and interface B?

class A implements IntfA,IntfB{public int a;A(){ this(10);} A(int x){ a=x;} public String MethodofIntfA(){ String s="Method-A";// System.out.println(s); return s;

Page 15: Java (1)

15

}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(); String s1=new String(); String s2=new String(); s1=a1.MethodofIntfA(); s2=a1.MethodofIntfB(); a1.methodofA(); System.out.println(""); System.out.println("Method -IntfA"+s1); System.out.println(""); System.out.println("Method -IntfB"+s2); }} interface IntfA extends IntfB{ //constant can be declare;;;;;;;;;;;;;;;;;;;; how use it'spublic String MethodofIntfA(); //public String MethodofIntfA1();} interface IntfB{ //constant can be declare;;;;;;;;;;;;;;;;;;;; how use it'spublic String MethodofIntfB(); //public String MethodofIntfA1();} Q33 write a program in java pirnt Hello visitor using interface?interface IntExample{ public void sayHello(); } class JavaInterfaceExample implements IntExample

{ /* We have to define the method declared in implemented interface, or else we have to declare the implementing class as abstract class. */

public void sayHello() { System.out.println("Hello Visitor !"); } public static void main(String args[]) { //create object of the class JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();

//invoke sayHello(), declared in IntExample interface.

Page 16: Java (1)

16

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

}

Page 17: Java (1)

17

Q35.Write a program to sort an integer array using java.util.Arrays ?import java.*;import java.util.Arrays;public class SortIntArray { public static void main(String[] args) { //create an int array int[] i1 = new int[]{3,2,5,4,1}; //print original int array System.out.print("Original Array : "); for(int index=0; index < i1.length ; index++) System.out.print(" " + i1[index]);

/*To sort java int array use Arrays.sort() method of java.util package. Sort method sorts int array in ascending order and based on quicksort algorithm.There are two static sort methods available in java.util.Arrays class

to sort an int array. */

//To sort full array use sort(int[] i) method. Arrays.sort(i1); //print sorted int array System.out.print("\nSorted int array : "); for(int index=0; index < i1.length ; index++) System.out.print(" " + i1[index]); } }

Q36.Write a program to sort a char array using java.util.Arrays?import java.*;import java.util.Arrays; public class SortCharArray { public static void main(String[] args) { //create char array char[] c1 = new char[]{'d','a','f','k','e'}; //print original char array System.out.print("Original Array :\t "); for(int index=0; index < c1.length ; index++) System.out.print(" " + c1[index]); Arrays.sort(c1); //print sorted char array System.out.print("\nSorted char array :\t "); for(int index=0; index < c1.length ; index++) System.out.print(" " + c1[index]); } }

Q37.Write a program to change UpperCase to LowerCase in String?import java.*; public class StrLower { public static void main(String[] args) { String str = "STRING TOLOWERCASE EXAMPLE"; /* To change the case of string to lower case use,

Page 18: Java (1)

18

public String toLowerCase() method of String class. */ String strLower = str.toLowerCase(); System.out.println("Original String: " + str); System.out.println("String changed to lower case: " + strLower); } }Q38.Write a program to change LowerCase to UpperCase in String?import java.*; public class StrUpper { public static void main(String[] args) { String str = "india is my country"; /* To change the case of string to lower case use, public String toLowerCase() method of String class. */ String strUpper = str.toUpperCase(); System.out.println("Original String: " + str); System.out.println("String changed to Upper case: " + strUpper); } }

Q39.Write a program to show reverse a given string?public class StrReverse { public static void main(String args[]) { //declare orinial string String strOriginal = "Hello World"; System.out.println("Original String : " + strOriginal); strOriginal = new StringBuffer(strOriginal).reverse().toString(); System.out.println("Reversed String : " + strOriginal); } }Q40. Write a program in java how to swap value of two numbers using java?import java.*; public class SwapExample {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); //swap the valueswap(num1, num2);} private static void swap(int num1, int num2) { int temp = num1;num1 = num2;num2 = temp; System.out.println("After Swapping");System.out.println("Value of num1 is :" + num1);System.out.println("Value of num2 is :" +num2);} }

Page 19: Java (1)

19

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 firstnum1 = 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()); }}

Q44.Write a program to handle run-time error using ArithmeticException?import java.*;class Exc1{

public static void main(String args[])

Page 20: Java (1)

20

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

}

Q45.Write a program in java to use fileException when file is not found.?import java.io.*;public class fileExcep {

public static void main(String[] args) {openFile("test1.bmp");

}public static void openFile(String name) {

try {FileInputStream f = new FileInputStream(name);

}catch (FileNotFoundException e) {

System.out.println("File not found.");}

}}Q46.Write a program to use ArrayIndexOutOfBoundsException in array?import java.*;class excep2 {public static void main(String args[]) { try {

doWork();}

catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Exception: " + e.getMessage());e.printStackTrace();}

}static void doWork() throws ArithmeticException {int array[] = new int[100];array[100] = 100;}

}

Page 21: Java (1)

21

Q47.Wrtie a program in java to create a SimpleThread?import java.*;import java.lang.*;public class SimpleThread extends Thread { private int countDown = 5; private static int threadCount = 0; public SimpleThread() { super("" + ++threadCount); // Store the thread name start(); } public String toString() { return "#" + getName() + ": " + countDown; } public void run() { while(true) { System.out.println(this); if(--countDown == 0) return; } } public static void main(String[] args) { for(int i = 0; i < 5; i++) new SimpleThread(); }}

Q48.Write a program in java uses java.util.Timer to schedule a task to execute once 5 seconds have passed?import java.*;import java.util.Timer;import java.util.TimerTask;/* Simple demo that uses java.util.Timer to schedule a task to execute once 5 seconds have passed. */public class Reminder { Timer timer;

public Reminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds * 1000); }

class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); timer.cancel(); //Terminate the timer thread } }

Page 22: Java (1)

22

public static void main(String args[]) { System.out.println("About to schedule task."); new Reminder(5); System.out.println("Task scheduled."); }}

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

Q50.Write a Program in java to create a joining thread?import java.*;import java.lang.*;import java.util.Timer;class Sleeper extends Thread { private int duration;

Page 23: Java (1)

23

public Sleeper(String name, int sleepTime) { super(name); duration = sleepTime; start(); }

public void run() { try { sleep(duration); } catch (InterruptedException e) { System.out.println(getName() + " was interrupted. " + "isInterrupted(): " + isInterrupted()); return; } System.out.println(getName() + " has awakened"); }}

class Joiner extends Thread { private Sleeper sleeper;

public Joiner(String name, Sleeper sleeper) { super(name); this.sleeper = sleeper; start(); }

public void run() { try { sleeper.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(getName() + " join completed"); }}

public class Joining {

public static void main(String[] args) { Sleeper sleepy = new Sleeper("Sleepy", 1500), grumpy = new Sleeper( "Grumpy", 1500); Joiner dopey = new Joiner("Dopey", sleepy), doc = new Joiner("Doc", grumpy); grumpy.interrupt();

}}Q51.Write a program in java to create TwoSimple Thread?import java.*;import java.lang.*; class TwoThread extends Thread { public void run() {

Page 24: Java (1)

24

for (int i = 0; i < 10; i++) { System.out.println("New thread"); } }

public static void main(String[] args) { TwoThread tt = new TwoThread(); tt.start(); for (int i = 0; i < 10; i++) { System.out.println("Main thread"); } }}Q52.Write a program in java to create a SleepingThread?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(); }}Q53.Write a applet program in java to display Hello from Java! ?import java.applet.Applet;import java.awt.*;/*<APPLET CODE=applet1.class WIDTH=200 HEIGHT=200 > </APPLET> */public class applet1 extends Applet{public void init(){setBackground(Color.white);

Page 25: Java (1)

25

}public void start(){}public void paint(Graphics g){g.drawString("Hello from Java!", 60, 100);}public void stop(){}public void destroy(){ }}

/* we can Compile our applet program through command prompt C:\Program Files\Java\jdk1.5.0_06\bin\javac apple1.java Press EnterRun our applet program to use this commandC:\Program Files\Java\jdk1.5.0_06\bin\appletviewer applet1.java Press Enter*/

Q54.Write an applet Program in java Passing Parameters to Applets?import java.*;import java.awt.*;import java.applet.Applet;/*<APPLET CODE=ParamDemo.class WIDTH=300 HEIGHT=80> <param name=fontName value=Courier> <param name=fontSize value=14> <param name=leading value=2> <param name=accountEnabled value=true> </APPLET> */public class ParamDemo extends Applet{

String fontName;int fontSize;float leading;boolean active;//Initialize the string to be displayed.

public void start(){ String param; fontName=getParameter("fontName"); if(fontName==null) fontName="Not Found"; param=getParameter("fontSize"); try { if(param!=null)//if not found fontSize=Integer.parseInt(param); else fontSize=0; }

Page 26: Java (1)

26

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?

Page 27: Java (1)

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 appletg.drawString(“Show Status Example”,50,50);//this will be displayed in a status bar of an applet windowshowStatus(“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 RedsetForeground(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?

Page 28: Java (1)

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 buttonsButton1.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”))

Page 29: Java (1)

29

actionMessage=”OK Button Pressed”; else if(action.equals(“Cancel”))

actionMessage=”Cancel Button Pressed”; repaint(); }}Q61. Write an applet program to create a checked Checkbox using AWT Checkbox Class?import java.awt.*;import java.applet.Applet;import java.awt.Checkbox;/*<applet code= “CreateCheckedCheckBox” width=200 height=200></applet>*/public class CreateCheckedCheckBox extends Applet {

public void init(){//create checkboxesCheckbox checkBox1=new Checkbox(“My Checkbox1”);/* To create a checkbox, use Checkbox(String label, boolean on)Constructor*/Checkbox checkBox2=new Checkbox(“My Checkbox2”,true);//add checkboxes using add method add(checkBox1); add(checkBox2); }}

Q62. Write an applet program to handle checkbox event .when checkbox is selected and deselected, item event is generated?import java.awt.*;import java.applet.Applet;import java.awt.Checkbox;import java.awt.Graphics;import java.awt.event.ItemEvent;import java.awt.event.ItemListner;/*<applet code= “HandleCheckboxEvent” width=200 height=200></applet>*/public class HandleCheckboxEvent extends Applet implements ItemListener{

Checkbox Java=null;Checkbox VB=null;Checkbox C=null;

//create checkboxesJava=new Checkbox(“Java”);VB=new Checkbox(“Visual Basic”);C=new Checkbox(“C Languages”);add(Java);add(VB);add(C);add(C++);//add item ListenersJava.addItemListener(this)VBaddItemListener(this)C.addItemListener(this)

}

public void paint(Graphics g)

Page 30: Java (1)

30

{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 comboboxadd(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() {

// To create a choice or a combo box Language=new Choice();// add items to the choiceLanguage.add(“Java”);Language.add(“VB”);Language.add(“C++”);Language.add(“Perl”);

//add choice or combobox

Page 31: Java (1)

31

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

// To create a choice or a combo box Language=new Choice();// add items to the choiceLanguage.add(“Java”);Language.add(“VB”);Language.add(“C++”);Language.add(“Perl”);

//add choice or comboboxadd(Language);//add(Language);Language.add(“PHP”,2); }}Q66.Write an applet program to create a AWT Radio Buttons using CheckBox Group?import java.awt.*;import java.applet.Applet;import java.awt.Checkbox;import java.awt.CheckboxGroup;/*<applet code=”CreateRadioButtons” width=200 height=200></applet>*/public class CreateRadioButtons extends Applet { public void init() {

// To create a checkbox group, use CheckboxGroup() constructor of AWT CheckboxGroup classCheckboxGroup IngGrp=new CheckboxGroup();

//if you create a checkboxes and add to group, they become radio buttons

Page 32: Java (1)

32

Checkbox java=new Checkbox(“Java”,IngGrp,true);Checkbox cpp=new Checkbox(“C++”,IngGrp,true);Checkbox vb=new Checkbox(“VB”,IngGrp,true);

//add radio buttonsadd(java);add(cpp);add(vb); }}

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

Q69.Write a program to Create a border in Applet Window using BorderLayout?import java.awt.*;import java.applet.Applet;import java.awt.event.*;/*<applet code=border.class” width=200 height=100></applet>*/class textPanel extends Panel{ TextField Text1; textPanel() { Text1=new TextField(30); add(Text1); }}public class border extends Applet implements ActionListner{ Button button1,button2,button3,button4;textpanel Panel1;public void init()

Page 33: Java (1)

33

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