07 August 2014

Java Programs




1.            Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c=0.Read in a,b,c and use the quadratic formula.If the discriminant b2-4ac is negative,display a message stating that there are no real roots .





import java.util.Scanner;


class Solutions

{

public static void main(String args[])

{

int a,b,c;

double x,y;

Scanner s=new Scanner(System.in);

System.out.println("Enter the values of a,b, and c");

a=s.nextInt();

b=s.nextInt();

c=s.nextInt();

double f=(b*b)-4*a*c;

System.out.println("F value="+f);

if(f<0)

{

System.out.println("No real roots");

}

else

{

double l=Math.sqrt(f);

System.out.println("Math.sqrt(f)="+l);

x=((-b-l)/(2*a));

y=((-b+l)/(2*a));

System.out.println("Roots of given equation:"+x+"\t"+y);

}

}

}





Output:






Enter the values of a,b,c


2

5

2

Roots of given equation:-0.5   -2.0

































2.            Write a Java program that uses both recursive and non-recursive functions to print nth value in the Fibonacci sequence .



/*Without recursion*/





import java.util.Scanner;


class Fibonacci

{

public static void main(String[] input)

{

int x,y;

x=Integer.parseInt(input[0]);

y=Integer.parseInt(input[1]);

Scanner s=new Scanner(System.in);

System.out.println(“Enter the value of n:”);

int n=s.nextInt();

int z[]=new int[n];

z[0]=x;

z[1]=y;

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

{

z[i]=z[i-1]+z[i-2];

}

System.out.println("<------------Fibonacii series------------>");

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

{

System.out.println(z[i]);

}

}

}





Output:


>java Fibonacci  0  1

Enter the value of n:

8

<------------Fibonacii series------------>

0

1

1

2

3

5

8

13























/*With recursion*/






import java.util.Scanner;


class Fibwithrec

{

public static void main(String[] args)

{

Scanner s=new Scanner(System.in);

System.out.println("Enter the value of n:");

int n=s.nextInt();

System.out.println("Fibonacci series using recursion");

Fiboni f1=new Fiboni();

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

System.out.println(f1.fibon(i));

}

}

class Fiboni

{

public int fibon(int n)

{

if(n==0 || n==1)

return 1;

else

return fibon(n-1)+fibon(n-2);

}

}











Output:






Enter the value of n:


10

Fibonacci series using recursion

1

1

2

3

5

8

13

21

34

55























3.            Write a java program to calculate Factorial of a given number using “Recursion”  concept .






import java.io.*;


import java.util.*;

class Factorial

{

int fact(int n)

{

int r;

if(n==1)

return 1;

else

r=fact(n-1)*n;

return r;

}

}

class Recursion

{

public static void main(String args[])throws IOException

{

Factorial f=new Factorial();

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

System.out.println("Enter num to find factorial");

int x=Integer.parseInt(br.readLine());

int k=f.fact(x);

System.out.println("The fatorial of"+x+"is="+k);

}

}





Output:






Enter num to find factorial


5

The fatorial of5is=120













































































4.            Write a java program to check whether given number is prime or not.






import java.util.*;


import java.lang.*;

class PrimeNum

{

public static void main(String args[ ])throws IOException

{

Scanner s=new Scanner(System.in);

System.out.println("Enter the value of n:");

int n=s.nextInt();

int count=0;

for(int i=1;i<=n;i++)

{

if((n%i)==0)

{

count++;

}

}

if(count==2)

{

System.out.println("the num is prime"+n);

}

else

{

System.out.println("the num is  not a prime"+n);

}

}

}





Output:






Enter  n value


11

the num is prime11





Enter  n value


22

the num is not prime22















































5.            Write a Java program that prompts the user for an integer and then prints out all prime numbers upto that integer .






import java.util.Scanner;


class Prime

{

public static void main(String[] args)

{

int n,p;

Scanner s=new Scanner(System.in);

System.out.println("Enter upto which number prime numbers are needed");

n=s.nextInt();

System.out.println("<------------Prime numbers------------->");

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

{

p=0;

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

{

if(i%j==0)

p=1;

}

if(p==0)

System.out.println(i);

}

}

}





Output:






Enter upto which number prime numbers are needed


20

<------------Prime numbers------------->

2

3

5

7

11

13

17

19















































6.   Write a Java program to print prime numbers in a given range.






import java.util.*;


class PrimeRange

{

public static void main(String args[])

{

int i,j;

Scanner br =new Scanner(System.in);

System.out.println("Enter the starting range");

int s=br.nextInt();

System.out.println("Enter the end range");

int e=br.nextInt();

for(i=s;i<=e;i++)

{

int count=0;

for(j=1;j<=e;j++)

{

if((i%j)==0)

count++;

}

if(count==2)

{

System.out.println(i);

}

}

}

}





Output:












Enter the starting  range


10

Enter the end range

30

…Prime series…

11

13

17

19

23

29





























7.    Write a java program to check whether given number is perfect  or  not.






import java.util.*;


public class PerfectNumber

{

public static void main(String[] args)

{

System.out.println("Enter any number");

Scanner input = new Scanner(System.in);

int num = input.nextInt();

int perfectNo = 0;

int i;

System.out.println("Factors are:");

for (i = 1; i < num; i++)

{

if (num % i == 0) {

perfectNo += i;

System.out.println(i);

}

}

if (perfectNo == num)

{

System.out.println("number is a perfect number");

} else {

System.out.println("number is not a perfect number");

}

}





Output:






Enter any number


28

Factors are:

1

2

7

14

number is a perfect number

































































8.    Write a Java program to find the total and average of a student marks.






import java.io.*;


class DemoArray

{

public static void main (String args[]) throws IOException

{

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

System.out.println("Enter how many sub");

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

int marks[]=new int[n];

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

{

System.out.println("Enter subject"+(i+1)+"marks");

marks[i]=Integer.parseInt(br.readLine());

}

int tot=0;

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

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

{

System.out.println(marks[i]);

tot=tot+marks[i];

}

System.out.println("Total marks="+tot);

float avg=(float)tot/n;

System.out.print("Avarage marks ="+avg);

}

}





Output:






Enter how many subjects


3

Enter subject1 marks

67

Enter subject2 marks

53

Enter subject3 marks

70

The Marks are

67

53

70

total marks=190

Avarage marks=63.333332























9.            Write a Java program to display multiplication table.




import java.io.*;

class Multiplication

{

public static void main(String args[])throws IOException

{

Scanner s=new Scanner(System.in);

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

int n=s.nextInt();

System.out.println("...Multiplication Table...");

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

System.out.println(n+"*"+i+"="+(n*i));

}

}





Output :






Enter n value


5

Multiplication table:

5*1=5

5*2=10

5*3=15

5*4=20

5*5=25

5*6=30

5*7=35

5*8=40

5*9=45

5*10=50





































































































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






class Palindrome


{

public static void main(String[] args)

{

StringBuffer s1=new StringBuffer(args[0]);

StringBuffer s2=new StringBuffer(s1);

s1.reverse();

System.out.println(“Given String is:”+s2);

System.out.println(“Reverse String is”+s1);

if(String.valueOf(s1).compareTo(String.valueOf(s2))==0)

System.out.println(“Palindrome”);

else

System.out.println(“Not Palindrome”);

}

}











Output:






Java palindrome madam


Given String is:madam

Reverse String is madam

Palindrome











Java palindrome 121


Given String is:121

Reverse String is 121

Palindrome











11.    Write a Java program to sort a given list of names in ascending order.






class Sorting


{

public static void main(String[] input)

{

int k=input.length;

String temp=new String();

String names[]=new String[k+1];

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

{

names[i]=input[i];

}

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

for(int j=i+1;j<k;j++)

{

if(names[i].compareTo(names[j])<0)

{

temp=names[i];

names[i]=names[j];

names[j]=temp;

}

}

System.out.println(“Sorted order is”);

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

{

System.out.println(names[i]);

}

}

}











Output:






Java sorting Harish  Ramesh  Mahesh  Rakesh


Sorted order is

Ramesh

Rakesh

Mahesh

Harish





12.    Write a Java Program to multiply two matrices.




import java.util.Scanner;

class Matmul

{

public static void main(String args[])

{

Scanner input=new Scanner(System.in);

System.out.println("Enter size of first matrix:");

int m=input.nextInt();

int n=input.nextInt();

System.out.println("Enter size of second matrix:");

int p=input.nextInt();

int q=input.nextInt();





int a[][]=new int[m][n];


int b[][]=new int[p][q];

int c[][]=new int[m][q];





System.out.println("Enter the first matrix:");


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

for(int j=0;j<n;j++)

a[i][j]=input.nextInt();





System.out.println("Enter the second matrix:");


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

for(int j=0;j<q;j++)

b[i][j]=input.nextInt();





System.out.println("Matrix multiplication is as follows:\n");


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

{

for(int j=0;j<q;j++)

{

c[i][j]=0;

for(int k=0;k<n;k++)

{

c[i][j]+=a[i][k]*b[k][j];

}

}

}





System.out.println("First matrix:\n");


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

{

for(int j=0;j<n;j++)

{

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

}

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

}





System.out.println("Second matrix:");


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

{

for(int j=0;j<q;j++)

{

System.out.print(b[i][j]+"\t");

}

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

}





System.out.println("Multiplcation:");


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

{

for(int j=0;j<q;j++)

{

System.out.print(c[i][j]+"\t");

}

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

}

}

}





Output:






Enter size of first matrix:


2

2

Enter size of second matrix:

2

2

Enter the first matrix:

1       2

3       4

Enter the second matrix:

1       2

3       4





Matrix multiplication is as follows:






First matrix:






1       2






3       4






Second matrix:


1       2





3       4






Multiplcation:


7       10





15      22






13.    Write a java program for array copying method.






import java.io.*;


public class CopyArray

{

public static void main(String[] args)throws IOException

{

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

System.out.println("Enter array length ");

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

String array1[]=new String[n];

String  array2[]=new String[n];

System.out.println("Enter strings into array1: ");

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

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

{

System.out.println("Enter the string"+(i+1));

array1[i]=br.readLine();

}

System.out.println("Enter strings into array2: ");

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

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

{

System.out.println("Enter the string"+(i+1));

array2[i]=br.readLine();

}

System.out.println("Array1:");

System.out.print("[");

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

{

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

}

System.out.print("]");

System.out.println("\nArray2:");

System.out.print("[");

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

{

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

}

System.out.print("]");

System.out.println("\nAfterCopying:");

System.out.print("[");

System.arraycopy(array1,0,array2,0,2);

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

{

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

}

System.out.print("]");

}

}





Output:






Enter array length


5





Enter strings into array1:


...................................

Enter the string1

q

Enter the string2

w

Enter the string3

e

Enter the string4

r

Enter the string5

t

Enter strings into array2:

...................................

Enter the string1

a

Enter the string2

s

Enter the string3

d

Enter the string4

f

Enter the string5

g

Array1:

[ q w e r t]

Array2:

[ a s d f g]

AfterCopying:

[ q w d f g]





14.    Write  a program  on “Static” method.






import java.io.*;


class StaticMethod

{

static int sum(int a,int b)

{

int c=a+b;

return c;

}

}

class Demo

{

public static void main(String args[])

{

int x=StaticMethod.sum(10,50);

System.out.println(x);

}

}





Output:






sum=60






15.    Write a java application on “Static” variable.






import java.io.*;


class Test

{

static int  x;

int y;

void inc()

{

x=x+1;

y=y+1;

}

void show()

{

System.out.println("x value is:"+x);

System.out.println("y value is:"+y);

}

}

class Static

{

public static void main(String args[])throws IOException

{

Test t1=new Test();

Test t2=new Test();

System.out.println("First obj values:");

t1.inc();

t1.show();

System.out.println("Second obj values:");

t2.inc();

t2.show();

}

}





Output:






First obj values:


x value is:1

y value is:1

Second obj values:

x value is:2

y value is:1

16.     Write a program on “Constructor”.





class Rectangle


{

int l,w;

void getData(int x,int y)

{

l=x;

w=y;

}

int rectArea()

{

return(l*w);

}

}

class RectArea

{

public static void main(String args[ ])

{

Rectangle r1=new Rectangle( );

r1.getData(10,15);

int k=r1.rectArea( );

System.out.print("Area is:"+k);

}

}





Output :






Area is:150






17.     Write a java program for  “ This ”  keyword .






import java.io.*;


class Test

{

int a,b;

void getData()

{

this.a=10;

this.b=20;

}

void show()

{

System.out.println("a value is:"+a);

System.out.println("b value  is:"+b);

}

}

class This

{

public static void main(String args[])throws IOException

{

Test t=new Test();

t.getData();

t.show();

}

}





Output:






a value is:10


b value  is:20





18.     Write a java program on Command Line Arguments.






public class GetCommandLine


{

public static void main(String args[])

{

System.out.println("----->>Getting command line arguments --");

for(int i=0;i<args.length;i++)

{

System.out.println("Argument ["+(i+1)+"] is = "+args[i]);

}

}

}

















Output:






>javac GetCommandLine.java






>java GetCommandLine 10 20 30 40 50






----->>Getting command line arguments --


Argument [1] is = 10

Argument [2] is = 20

Argument [3] is = 30

Argument [4] is = 40

Argument [5] is = 50











19.     Write a program to find sum of  given Command Line Arguments.






import java.io.*;


import java.lang.*;

public class Cmd

{

public static void main(String args[])throws IOException

{

int sum=0;

for(int i=0;i<args.length;i++)

{

int x=Integer.parseInt(args[i]);

sum+=x;

}

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

}

}





Output:






>javac Cmd.java






>java Cmd 10 15 20 25 30






sum is=100






20.     Write a program on Method Overloding.






import java.io.*;


class MethodOverLoad

{

void calValue()

{

int x=20;

x=x*x;

System.out.println("Sqrt of x is:"+x);

}

void calValue(int y)

{

y=y*y*y;

System.out.println("Cube of y is:"+y);

}

void calValue(int m,int n)

{

int z=m*n;

System.out.println("Product of m and n  is:"+z);

}

}

class MOV

{

public static void main(String args[])throws IOException

{

MethodOverLoad m=new MethodOverLoad();

m.calValue();

m.calValue(10,20);

m.calValue(10);

}

}





Output:






Sqrt of x is:400


Product of m and n  is:200

Cube of y is:1000





21.    Write a program on Method Overriding.






import java.io.*;


class One

{

int calculate(int n)

{

return n;

}

}

class Two extends One

{

int calculate(int n)

{

return(n*n);

}

}

class MOR

{

public static void main(String args[])throws IOException

{

Two t=new Two();

int m=t.calculate(3);

System.out.println("Multiplication is:"+m);

}

}





Output:






Multiplication is:9






22.    Write  a program on Constructor Overloding.






class Test


{

int a,b;

Test()

{

a=1;

b=2;

}

Test(int x)

{

a=b=x;

}

Test(int a, int b)

{

this.a=a;

this.b=b;

}

void show()

{

System.out.println("a value is:"+a);

System.out.println("b value is:"+b);

}

}

class COL

{

public static void main(String args[])

{

Test t1=new Test();

t1.show();

Test t2=new Test(10);

t2.show();

Test t3=new Test(15,25);

t3.show();

}

}

Output:

a value is:1

b value is:2

a value is:10

b value is:10

a value is:15

b value is:25





23.    Write  a program on InnerClass concept.


class Outer

{

Inner in=new Inner();

class Inner

{

public void sayHello()

{

System.out.println("Hello");

}

}

}

class DemoInner

{

public static void main(String args[])

{

Outer o=new Outer();

o.in.sayHello();

}

}





Output:






Hello


















24.    Write a Java programme that reads a line of integers and displays each integer and sum of all integers using StringTokenizer class.






import java.util.StringTokenizer;


import java.util.Scanner;

class Tokens

{

public static void main(String[] args)

{

Scanner input=new Scanner(System.in);

System.out.println("Enter no. of tokens u want to add ");

String sentence=input.nextLine();

String temp;

int k,total=0;

StringTokenizer s1=new StringTokenizer(sentence);

System.out.println("Total Number of tokens:"+s1.countTokens());

System.out.println("Tokens are:");

while(s1.hasMoreTokens())

{

temp=s1.nextToken();

k=Integer.parseInt(temp);

total+=k;

System.out.print(k+"\t");

}

System.out.println("\nSum of tokens :"+total);

}

}





Output:






Enter no. of tokens u want to add


5 4 6 1 8 2

Total Number of tokens:6

Tokens are:

5       4       6       1       8       2

Sum of tokens :26











25.    Write a java program on “StringTokenizer” class.






import  java.util.*;


import java.lang.*;

import java.io.*;

class StringToken

{

public static void main(String args[])throws IOException

{

String str=new String("welcome to java lab");

StringTokenizer stz=new StringTokenizer(str);

System.out.println("No.of words are:");

System.out.println(stz.countTokens());

System.out.println("Tokens are:");

while(stz.hasMoreTokens())

{

System.out.println(stz.nextToken());

}

int count=0;

for(int i=0;i<str.length();i++)

if(str.charAt(i)!=' ')

count++;

System.out.println("Total no of characters:"+count);

}

}





Output:






No.of words are:


4

Tokens are:

welcome

to

java

lab

Total no of characters:16











26.    Write a java program on “Inheritence” concept.






interface Father


{

int PROP1=500000;

}

interface Mother

{

int PROP2=800000;

}

class Child implements Father,Mother

{

void property()

{

System.out.println("child property="+(PROP1+PROP2));

}

}

class MultiInher

{

public static void main(String args[])

{

Child ch=new Child();

ch.property();

}





Output:






child property=1300000






27.    Write an example using “StringTokenizer” class.






import java.io.*;


import java.util.*;

class DiffData

{

public static void main(String args[])throws IOException

{

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

System.out.println("enter name,age,salary");

String s=br.readLine();

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

String s1=str.nextToken();

String s2=str.nextToken();

String s3=str.nextToken();

s1=s1.trim();

s2=s2.trim();

s3=s3.trim();

String name=s1;

int age=Integer.parseInt(s2);

float salary=Float.parseFloat(s3);

System.out.println("name="+name);

System.out.println("Age="+age);

System.out.println("Salary="+salary);

}

}





Output:






enter name,age,salary


puja,24,15000

name=puja

Age=24

Salary=15000.0











28.     Write a java program to make frequency count of words in a given text.






import java.util.*;


import java.lang.*;

import java.io.*;

class Freq

{

public static void main(String[ ] args) throws IOException

{

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter number of words");

String str=dis.readLine();

String temp;

StringTokenizer st=new StringTokenizer(str);

int n=st.countTokens( );

String a[ ]=new String[n];

int i=0,count=0;

while(st.hasMoreTokens())

{

a[i]=st.nextToken();

i++;

}

for(int x=1;x<n;x++)

{

for(int y=0;y<n-x;y++)

{

if(a[y].compareTo(a[y+1])>0)

{

temp=a[y];

a[y]=a[y+1];

a[y+1]=temp;

}

}

}

System.out.println("the sorted string are:");

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

{

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

}

System.out.println();

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

{

count=1;





if(i<n-1)


{

while(a[i].compareTo(a[i+1])==0)

{

count++;

i++;

if(i>=n-1)

{

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

System.exit(0);

}

}

}

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

}

}

}





Output:






Enter number of words


anu puja rani anu vani rani

the sorted string are:

anu

anu

puja

rani

rani

vani





anu 2


puja 1

rani 2

vani 1





29.     Write a java program to display Employee data.






import java.io.*;


class Employee

{

int id;

String name;

Employee(int i,String n)

{

id=i;

name=n;

}

void displayData()

{

System.out.println(id+"\t"+name);

}

}

class Group

{

public static void main(String args[])throws IOException

{

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

Employee arr[]=new Employee[5];

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

{

System.out.println("enter id");

int id=Integer.parseInt(br.readLine());

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

String name=br.readLine();

arr[i]=new Employee(id,name);

}

System.out.println("Employee data");

for(int i=0;i<arr.length;i++)

{

arr[i].displayData();

}

}

}





Output:






1


enter name

rani

enter id

2

enter name

bhavya

enter id

3

enter name

madhu

enter id

4

enter name

peethi

enter id

5

enter name

sonu





Employee data


1       rani

2       bhavya

3       madhu

4       peethi

5       sonu











30.    Write a java program using “Super” keyword.






import java.io.*;


class A

{

int a;

A(int a)

{

this.a=a;

}

void showA()

{

System.out.println("The value of a is  "+a);

}

}

class B extends A

{

int b;

B(int a,int b)

{

super(a);

this.b=b;

}

void showB()

{

System.out.println("The value of b is  "+b);

}

}

class SuperKey

{

public static void main(String args[])

{

B o=new B(100,200);

o.showA();

o.showB();

}

}





Output:






The value of a is  100


The value of b is  200











31.     Write a java program using “Abstract class”.






abstract class A


{

abstract void call();

void callMethod()

{

System.out.println("This is concreate method");

}

}

class B extends A

{

void call()

{

System.out.println("This is implementation of class ");

}

}

class AbstractDemo

{

public static void main(String args[])

{

B b=new B();

b.call();

b.callMethod();

}

}





Output:












This is implementation of class


This is concreate method











32.     Write a java program on creating and implementation of package.






//creating own package.






package pack;


public class Add

{

public int i,j;

public Add(int i,int j)

{

this.i=i;

this.j=j;

}

public void add()

{

System.out.println("Details");

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

System.out.println("Additon is: "+(i+j));

}

}

//implementation of a package.





import pack.Add;


class PackExe

{

public static void main(String args[])

{

Add a=new Add(20,45);

a.add();

}

}





Output:






>javac -d . Add.java


>javac PackExe.java

>java PackExe





Details


.................

Additon is: 65





33.    Write a java program on “Interface” concept.






interface MyInterface


{

public void sayHello();

}

class Subclass implements MyInterface

{

public void sayHello()

{

System.out.println("hello");

}

}

class DemoInterface

{

public static void main(String args[ ])

{

Subclass i=new Subclass();

i.sayHello();

}

}





Output:






hello












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






import java.util.Scanner;


import java.io.File;

class FileDemo

{

public static void main(String[] args)

{

Scanner input=new Scanner(System.in);

String s=input.nextLine();

File f1=new File(s);

System.out.println("File Name:"+f1.getName());

System.out.println("Path:"+f1.getPath());

System.out.println("Abs Path:"+f1.getAbsolutePath());

System.out.println("Parent:"+f1.getParent());

System.out.println("This file is:"+(f1.exists()?"Exists":"Does not exists"));

System.out.println("Is file:"+f1.isFile());

System.out.println("Is Directory:"+f1.isDirectory());

System.out.println("Is Readable:"+f1.canRead());

System.out.println("IS Writable:"+f1.canWrite());

System.out.println("Is Absolute:"+f1.isAbsolute());

System.out.println("File Last Modified:"+f1.lastModified());

System.out.println("File Size:"+f1.length()+"bytes");

System.out.println("Is Hidden:"+f1.isHidden());

}}



Output:





Fibonacci.java


File Name:Fibonacci.java

Path: Fibonacci.java

Abs Path: c:\sameer\Fibonacci.java

Parent: Null

This file is:Exists

Is file:true

Is Directory:false

Is Readable:true

Is Writable:true

Is Absolute:false

File Last Modified:1206324301937

File Size: 406 bytes

Is Hidden:false











35.    Wtire a Java program that reads a file and displays a file and displays the file on the screen,with a line number before each line.






import java.io.*;


class Linenum

{

public static void main(String[] args)throws IOException

{

FileInputStream fil;

LineNumberInputStream line;

int i;

try

{

fil=new FileInputStream(args[0]);

line=new LineNumberInputStream(fil);

}

catch(FileNotFoundException e)

{

System.out.println("No such file found");

return;

}

do

{

i=line.read();

if(i=='\n')

{

System.out.println();

System.out.print(line.getLineNumber()+" ");

}

else

System.out.print((char)i);

}while(i!=-1);

fil.close();

line.close();

}

}



Output:





Demo.java






class Demo


1 {

2   public static void main(java Demo beta gamma delta)

3               {

4                         int n = 1 ;

5             System.out.println("The word is " + args[ n ] );

6              }

7 }

8?

















36.    Write a Java program that displays the number of characters,lines and words in a given text file.






import java.io.*;


class Wordcount

{

public static int words=0;

public static int lines=0;

public static int chars=0;

public static void wc(InputStreamReader isr)throws IOException

{

int c=0;

boolean lastwhite=true;

while((c=isr.read())!=-1)

{

++chars;

if(c=='\n')

lines++;

if(c=='\t' || c==' ' || c=='\n')

++words;

if(chars!=0)

++chars;

}

}

public static void main(String[] args)

{

FileReader fr;

try

{

if(args.length==0)

{

wc(new InputStreamReader(System.in));

}

else

{

for(int i=0;i<args.length;i++)

{

fr=new FileReader(args[i]);

wc(fr);

}

}

}

catch(IOException ie)

{

return;

}

System.out.println("No. of Lines"+lines+"\nNo. of Words"+words+"\nNo. of chars"+chars);

}

}





Output:






This is cse


^Z





No. of Lines1


No. of Words3

No. of chars13























37.    Write a   java program on “try,catch,finally” blocks.




class DemoEx

{

public static void main(String args[])

{

try

{

int a,b,c;

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

b=Integer.parseInt(args[1]);

c=a/b;

System.out.println("Result is ="+c);

}

catch (ArithmeticException ae)

{

System.out.println("not enter zeros");

}

catch (ArrayIndexOutOfBoundsException e)

{

System.out.println("enter at least 2 no's");

}

catch (NumberFormatException ne)

{

System.out.println("enter int values");

}

finally

{

System.out.println("This is final");

}

}

}





Output:












>java DemoEx 4 0


not enter zeros

This is final





>java DemoEx 4


enter at least 2 no's

This is final





>java DemoEx 4.2 3.4


enter int values

This is final





>java DemoEx 4 2


Result is =2

This is final











38.    Write a java program on creating own exception.






class VException extends Exception


{

VException(String s)

{

super(s);

}

}

class Voting

{

static void displayvote(int age)throws VException

{

if(age<19)

throw new VException("Invalid age");

System.out.println("Candidate is eligible to vote");

}

}

class UserExe

{

public static void main(String args[])

{

int age = Integer.parseInt(args[0]);

try

{

Voting.displayvote(age);

}

catch(VException e)

{

System.out.println(e.getMessage());

}

}

}





Output:






>java UserExe 23






Candidate is eligible to vote






>java UserExe 16






Invalid age












39.             Write a java program using “HashSet” method..






import java.util.*;


class HS

{

public static void main(String args[])

{

HashSet<String> hs=new HashSet<String>();

hs.add("india");

hs.add("us");

hs.add("uk");

hs.add("japan");

System.out.println("HashSet ="+hs);

Iterator it=hs.iterator();

System.out.println("elements using iterator");

while(it.hasNext())

{

String s=(String)it.next();

System.out.println(s);

}

}

}





Output:






HashSet =[

uk, japan, us, india]

elements using iterator



uk




japan

us



india








40 .    Write a Java program that implements stack ADT.












import java.lang.*;


import java.io.*;

import java.util.*;

interface Mystack

{

int n=10;

public void pop();

public void push();

public void display();

}

class Stackimp implements Mystack

{

int stack[]=new int[n];

int top=-1;

public void push()

{

try

{

DataInputStream dis=new DataInputStream(System.in);

if(top==(n-1))

{

System.out.println("overflow");

return;

}

else

{

System.out.println("enter element");

int ele=Integer.parseInt(dis.readLine());

stack[++top]=ele;

}

}

catch(Exception e)

{

System.out.println("e");

}

}

public void pop()

{

if(top<0)

{

System.out.println("underflow");

return;

}

else

{

int popper=stack[top];

top--;

System.out.println("popped element" +popper);

}

}

public void display()

{

if(top<0)

{

System.out.println("empty");

return;

}

else

{

String str=" ";

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

str=str+" "+stack[i];

System.out.println("elements are"+str);

}

}

}

class StackAdt

{

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

{

DataInputStream dis=new DataInputStream(System.in);

Stackimp stk=new Stackimp();

int ch=0;

do{

System.out.println("\nMenu is as follows:\n1.push\t2.pop\t3.display\t4.exit");

System.out.println("\nEnter ur choice");

ch=Integer.parseInt(dis.readLine());

switch(ch)

{

case 1:stk.push();

break;

case 2:stk.pop();

break;

case 3:stk.display();

break;

case 4:System.exit(0);

}

}while(ch<=5);

}

}





Output:


Menu is as follows:

1.Push

2.Pop

3.Display

4.Exit

Enter ur choice:1

Enter element to push :12

Menu is as follows:

1.Push

2.Pop

3.Display

4.Exit

Enter ur choice:1

Enter element to push:13

Menu is as follows:

1.Push

2.Pop

3.Display

4.Exit

Enter ur choice:3

12

13

Menu is as follows:

1.Push

2.Pop

3.Display

4.Exit

Enter ur choice:2

Popped item:13

Menu is as follows:

1.Push

2.Pop

3.Display

4.Exit

Enter ur choice:2

Popped item:12

Menu is as follows:

1.Push

2.Pop

3.Display

4.Exit

Enter ur choice:3

Stack is empty





41.    Write a Java program that converts infix expression into postfix form.






import java.io.*;


class stack

{

char stack1[]=new char[20];

int top;

void push(char ch)

{

top++;

stack1[top]=ch;

}

char pop()

{

char ch;

ch=stack1[top];

top--;

return ch;

}

int pre(char ch)

{

switch(ch)

{

case '-':return 1;

case '+':return 1;

case '*':return 2;

case '/':return 2;

}

return 0;

}

boolean operator(char ch)

{

if(ch=='/'||ch=='*'||ch=='+'||ch=='-')

return true;

else

return false;

}

boolean isAlpha(char ch)

{

if(ch>='a'&&ch<='z'||ch>='0'&&ch=='9')

return true;

else

return false;

}

void postfix(String str)

{

char output[]=new char[str.length()];

char ch;

int p=0,i;

for(i=0;i<str.length();i++)

{

ch=str.charAt(i);

if(ch=='(')

{

push(ch);

}

else if(isAlpha(ch))

{

output[p++]=ch;

}

else if(operator(ch))

{

if(stack1[top]==0||(pre(ch)>pre(stack1[top]))||stack1[top]=='(')

{

push(ch);

}

}

else if(pre(ch)<=pre(stack1[top]))

{

output[p++]=pop();

push(ch);

}

else if(ch=='(')

{

while((ch=pop())!='(')

{

output[p++]=ch;

}

}

}

while(top!=0)

{

output[p++]=pop();

}

for(int j=0;j<str.length();j++)

{

System.out.print(output[j]);

}

}

}

class intopost

{

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

{

String s;

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

stack b=new stack();

System.out.println("Enter input string");

s=br.readLine();

System.out.println("Input String:"+s);

System.out.print("Output String:");

b.postfix(s);

}

}





Output:






Enter input string


a+b*c

Input String:a+b*c

Output String:abc*+























Enter input string


a+(b*c)/d

Input String:a+(b*c)/d

Output String:abc*d/)(+





42.    Write an applet that displays a simple message.






import java.io.*;


import java.awt.*;

import java.applet.Applet;

/*<applet code="AppletTest.class" height=100 width=500></applet>*/

public class AppletTest extends Applet

{

public void paint(Graphics g)

{

g.drawString("This is CSE IInd Year IInd sem",50,60);

setBackground(Color.yellow);

setForeground(Color.red);

}

}





Output:



>javac AppletTest.java





>appletviewer AppletTest.java





















43.     Develop an applet that receives an integer in one text field, and computes as factorial value and returns it in another text field,when the button named “Compute” is clicked.




import java.awt.*;

import java.awt.event.*;

import java.applet.Applet;

/*<applet code="AddEvent.class" height=100 width=500></applet>*/

public class AddEvent extends Applet implements ActionListener

{

TextField tf1;

TextField tf2;

Button b;

Label l;

public void init()

{

setBackground(Color.cyan);

setForeground(Color.blue);

l=new Label("Enter the number & press the button");

tf1=new TextField("",5);

tf2=new TextField("",10);

b=new Button("press me");

add(l);

add(tf1);

add(tf2);

add(b);

b.addActionListener(this);

}

public void actionPerformed(ActionEvent ae)

{

String str=ae.getActionCommand();

String str1;

int fact=1;

if(str=="press me")

{

int n=Integer.parseInt(tf1.getText());

for(int i=1;i<=n;i++)

fact=fact*i;

str1=""+fact;

tf2.setText(str1);

}

}

}











Output:




>javac  AddEvent.java





>appletviewer  AddEvent.java



































































44.    Write a Java program that works as a simple calculator.Use a grid layout to arrange buttons for the digits and for the + - * % operations.Add a text field to display the result.






import java.awt.*;


import java.applet.*;

import java.awt.event.*;

/*<applet code="Calculator.class" width=200 height=200></applet>*/

public class Calculator extends Applet implements ActionListener

{

TextField t1;

String a="",b;

String oper="",s="",p="";

int first=0,second=0,result=0;

Panel p1;

Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9;

Button add,sub,mul,div,mod,res,space;

public void init()

{

setBackground(Color.cyan);

setForeground(Color.blue);

Panel p2,p3;

p1=new Panel();

p2=new Panel();

p3=new Panel();

t1=new TextField(a,20);

p1.setLayout(new BorderLayout());

p2.add(t1);

b0=new Button("0");

b1=new Button("1");

b2=new Button("2");

b3=new Button("3");

b4=new Button("4");

b5=new Button("5");

b6=new Button("6");

b7=new Button("7");

b8=new Button("8");

b9=new Button("9");

add=new Button("+");

sub=new Button("-");

mul=new Button("*");

div=new Button("/");

mod=new Button("%");

res=new Button("=");

space=new Button("c");

p3.setLayout(new GridLayout(4,4));

b0.addActionListener(this);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

b5.addActionListener(this);

b6.addActionListener(this);

b7.addActionListener(this);

b8.addActionListener(this);

b9.addActionListener(this);

add.addActionListener(this);

sub.addActionListener(this);

mul.addActionListener(this);

div.addActionListener(this);

mod.addActionListener(this);

res.addActionListener(this);

space.addActionListener(this);

p3.add(b0);

p3.add(b1);

p3.add(b2);

p3.add(b3);

p3.add(b4);

p3.add(b5);

p3.add(b6);

p3.add(b7);

p3.add(b8);

p3.add(b9);

p3.add(add);

p3.add(sub);

p3.add(mul);

p3.add(div);

p3.add(mod);

p3.add(res);

p3.add(space);

p1.add(p2,BorderLayout.NORTH);

p1.add(p3,BorderLayout.CENTER);

add(p1);

}

public void actionPerformed(ActionEvent ae)

{

a=ae.getActionCommand();

if(a=="0"||a=="1"||a=="2"||a=="3"||a=="4"||a=="5"||a=="6"||a=="7"||a=="8"||

a=="9")

{

t1.setText(t1.getText()+a);

}

if(a=="+"||a=="-"||a=="*"||a=="/"||a=="%")

{

first=Integer.parseInt(t1.getText());

oper=a;

t1.setText("");

}

if(a=="=")

{

if(oper=="+")

result=first+Integer.parseInt(t1.getText());

if(oper=="-")

result=first-Integer.parseInt(t1.getText());

if(oper=="*")

result=first*Integer.parseInt(t1.getText());

if(oper=="/")

result=first/Integer.parseInt(t1.getText());

if(oper=="%")

result=first%Integer.parseInt(t1.getText());

t1.setText(result+"");

}

if(a=="c")

t1.setText("");

}

}





Output:




>javac  Calculator.java





>appletviewer  Calculator.java



































































45.    Write a Java program for handling mouse events.






import java.awt.*;


import java.awt.event.*;

import java.applet.*;

/*

<applet code="Mouse" width=500 height=500>

</applet>

*/

public class Mouse extends Applet

implements MouseListener,MouseMotionListener

{

int X=0,Y=20;

String msg="MouseEvents";

public void init()

{

addMouseListener(this);

addMouseMotionListener(this);

setBackground(Color.black);





setForeground(Color.red);


}

public void mouseEntered(MouseEvent m)

{

setBackground(Color.magenta);

showStatus("Mouse Entered");

repaint();

}

public void mouseExited(MouseEvent m)

{

setBackground(Color.red);

showStatus("Mouse Exited");

repaint();

}

public void mousePressed(MouseEvent m)

{

X=10;

Y=20;

msg="NEC";

setBackground(Color.green);

repaint();

}

public void mouseReleased(MouseEvent m)

{

X=10;

Y=20;

msg="Engineering";

setBackground(Color.blue);

repaint();}

public void mouseMoved(MouseEvent m)

{

X=m.getX();

Y=m.getY();

msg="College";

setBackground(Color.cyan);

showStatus("Mouse Moved");

repaint();

}

public void mouseDragged(MouseEvent m)

{

msg="CSE";

setBackground(Color.yellow);

showStatus("Mouse Moved"+m.getX()+" "+m.getY());

repaint();

}

public void mouseClicked(MouseEvent m)

{

msg="Students";

setBackground(Color.pink);

showStatus("Mouse Clicked");

repaint();

}

public void paint(Graphics g)

{

g.drawString(msg,X,Y);

}}





Output:






>javac Mouse.java


>appletviewer Mouse.java






















46.    Write a program for handling KeyBoard events.





import java.awt.*;


import java.awt.event.*;

import java.applet.*;

/*

<applet code="Key" width=300 height=400>

</applet>

*/

public class Key extends Applet

implements KeyListener

{

int X=20,Y=30;

String msg="KeyEvents--->";

public void init()

{

addKeyListener(this);

requestFocus();

setBackground(Color.green);

setForeground(Color.blue);

}

public void keyPressed(KeyEvent k)

{

showStatus("KeyDown");

int key=k.getKeyCode();

switch(key)

{

case KeyEvent.VK_UP:

showStatus("Move to Up");

break;

case KeyEvent.VK_DOWN:

showStatus("Move to Down");

break;

case KeyEvent.VK_LEFT:

showStatus("Move to Left");

break;

case KeyEvent.VK_RIGHT:

showStatus("Move to Right");

break;

}

repaint();

}

public void keyReleased(KeyEvent k)

{

showStatus("Key Up");

}

public void keyTyped(KeyEvent k)

{

msg+=k.getKeyChar();

repaint();

}

public void paint(Graphics g)

{

g.drawString(msg,X,Y);

}

}

Output:


































47.    Write a java program that creates three threads.First thread displays”Good Morning”every one second,the second thread displays “Hello” every two seconds and the third threaddisplays “Welcome” every three seconds.






class Frst implements Runnable


{

Thread t;

Frst()

{

t=new Thread(this);

System.out.println("Good Morning");

t.start();

}

public void run()

{

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

{

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

try

{

t.sleep(1000);

}

catch(Exception e)

{

System.out.println(e);

}

}

}

}

class sec implements Runnable

{

Thread t;

sec()

{

t=new Thread(this);

System.out.println("hello");

t.start();

}

public void run()

{

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

{

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

Try

{

t.sleep(2000);

}





catch(Exception e)


{

System.out.println(e);

}

}

}

}

class third implements Runnable

{

Thread t;

third()

{

t=new Thread(this);

System.out.println("welcome");

t.start();

}

public void run()

{

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

{

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

try{

t.sleep(3000);

}

catch(Exception e)

{

System.out.println(e);

}

}

}

}

public class Multithread

{

public static void main(String arg[])

{

new Frst();

new sec();

new third();

}

}

Output:





Good Morning


hello

welcome

Good Morning0

hello0

welcome0

Good Morning1

hello1

welcome1

Good Morning2

hello2

welcome2

Good Morning3

hello3

welcome3

Good Morning4

hello4

welcome4

Good Morning5

hello5

welcome5

Good Morning6

hello6

welcome6

Good Morning7

hello7

welcome7

Good Morning8

hello8

welcome8

Good Morning9

hello9

welcome9





48.     Write a java program on “ThreadGroup”.






class ThreadGroupPro


{

public static void main(String args[])

{

ThreadGroup tg=new ThreadGroup("subgroup1");

Thread t1=new Thread(tg,"Thread1");

Thread t2=new Thread(tg,"Thread2");

Thread t3=new Thread(tg,"Thread3");

tg=new ThreadGroup("subgroup2");

Thread t4=new Thread(tg,"Thread4");

Thread t5=new Thread(tg,"Thread5");

tg=Thread.currentThread().getThreadGroup();

int age=tg.activeGroupCount();

System.out.println("No.of sub groups="+age);

System.out.println("Groups are");

tg.list();

}

}





Output:






No.of sub groups=2


Groups are

java.lang.ThreadGroup[name=main,maxpri=10]

Thread[main,5,main]

java.lang.ThreadGroup[name=subgroup1,maxpri=10]

java.lang.ThreadGroup[name=subgroup2,maxpri=10]





49.     Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication.






class Q


{

int n;

boolean valueSet=false;

synchronized int get()

{

if(!valueSet)

try

{

wait();

}

catch(InterruptedException e)

{

System.out.println("Interrupted Exception caught");

}

System.out.println("Got:"+n);

valueSet=false;

notify();

return n;

}

synchronized void put(int n)

{

if(valueSet)

try

{

wait();

}

catch(InterruptedException e)

{

System.out.println("Interrupted Exception caught");

}

this.n=n;

valueSet=true;

System.out.println("Put:"+n);

notify();

}

}

class Producer implements Runnable

{

Q q;

Producer(Q q)

{

this.q=q;

new Thread(this,"Producer").start();

}

public void run()

{

int i=0;

while(true)

{

q.put(i++);

}

}

}

class Consumer implements Runnable

{

Q q;

Consumer(Q q)

{

this.q=q;

new Thread(this,"Consumer").start();

}

public void run()

{

while(true)

{

q.get();

}

}

}

class ProdCons

{

public static void main(String[] args)

{

Q q=new Q();

new Producer(q);

new Consumer(q);

System.out.println("Press Control-c to stop");

}

}











Output:






Put:0


Press Control-c to stop

Got:0

Put:1

Got:1

Put:2

Got:2

Put:3

Got:3

Put:4

Got:4

Put:5

Got:5

Put:6

Got:6

Put:7

Got:7

Put:8

Got:8

Put:9

Got:9

Put:10

Got:10

Put:11

Got:11

Put:12

Got:12

Put:13

Got:13

Put:14

Got:14

Put:15

Got:15





50.     Write a program that creates a user interface to perform integer divisions.The user enters two numbers int the textfields,Num1 and Num2.The divison 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 program would throw a NumberFormatException.If Num2 were Zero,the programwould throw an ArithmeticException Display the exception in a message dialog box.

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
/*<applet code="Divide.class" height=100 width=500></applet>*/
public class Divide extends Applet implements ActionListener
{
TextField tf1;
TextField tf2;
Button b;
TextField tf3;
Label l;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.blue);
l=new Label("enter the numbers and press divide button");
tf1=new TextField("",5);
tf2=new TextField("",5);
tf3=new TextField("",5);
b=new Button("Divide");
add(l);
add(tf1);
add(tf2);
add(b);
add(tf3);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand()=="Divide")
{
try{
int n1=Integer.parseInt(tf1.getText());
int n2=Integer.parseInt(tf2.getText());
int n=n1/n2;
tf3.setText(""+n);
}
catch(ArithmeticException e1)
{
JOptionPane.showMessageDialog(null,"Arthimetic Exception");
}
catch(NumberFormatException e2)
{
JOptionPane.showMessageDialog(null,"NumberFormatException");
}
}
}
}


Output:
>javac Divide.java


>appletviewer Divide.java








51.     Write a java program that stimulates 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.*;
import java.applet.*;
/*<applet code="CBGroup" width=250 height=200></applet>*/
public class CBGroup extends Applet implements ItemListener
{
String msg="";
Checkbox Red,Green,Yellow;
CheckboxGroup cbg;
public void init()
{
setBackground(Color.cyan);
cbg=new CheckboxGroup();
Red=new Checkbox("RED",cbg,false);
Green=new Checkbox("GREEN",cbg,false);
Yellow=new Checkbox("YELLOW",cbg,false);
add(Red);
add(Yellow);
add(Green);
Red.addItemListener(this);
Green.addItemListener(this);
Yellow.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
//g.drawOval(10,10,50,50);
if(cbg.getSelectedCheckbox().getLabel()=="RED")
{
g.setColor(Color.red);
g.fillOval(10,10,50,50);
}
if(cbg.getSelectedCheckbox().getLabel()=="YELLOW")
{
g.setColor(Color.yellow);
g.fillOval(10,10,50,50);
}
if(cbg.getSelectedCheckbox().getLabel()=="GREEN")
{
g.setColor(Color.green);
g.fillOval(10,10,50,50);
}
}
}


Output:


>javac CBGroup.java


>appletviewer CBGroup.java








52.    Write a Java program that allows the user to draw lines, rectangles and ovals






import java.awt.*;


import java.applet.*;

/*<applet code="Draw.class" width=200 height=200>

</applet>*/

public class Draw extends Applet

{

public void paint(Graphics g)

{

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

{

Color c1=new Color(35-i,55-i,110-i);

g.setColor(c1);

g.drawRect(250+i,250+i,100+i,100+i);

g.drawOval(100+i,100+i,50+i,50+i);

g.drawLine(50+i,20+i,10+i,10+i);

}

}

}























Output:                     >appletviewer  Draw.java













53.    Write a java program to create an abstract class named Shape that contains an empty
method name numberOfSides().Provide three classes named Trapezoid,Traingle and Hexagon
such that each 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.

import java.lang.*;
abstract class Shape
{
abstract void numberOfSides();
}
class Traingle extends Shape
{
public void numberOfSides()
{
System.out.println("three");
}}
class Trapezoid extends Shape
{
public void numberOfSides()
{
System.out.println("four");
}}
class Hexagon extends Shape
{
public void numberOfSides()
{
System.out.println("six");
}}
public class Sides
{
public static void main(String arg[])
{
Traingle T=new Traingle();
Trapezoid Ta=new Trapezoid();
Hexagon H=new Hexagon();
T.numberOfSides();
Ta.numberOfSides();
H.numberOfSides();
}}
Output:
three
four
six




54.      Write a java program for FlowLayout.


import java.awt.*;

class DemoFlowLayout extends Frame

{

public DemoFlowLayout()

{

setLayout(new FlowLayout());

for(int i=1;i<=20;i++)

{

Button b=new Button(String.valueOf(i));

add(b);

}

setBackground(Color.cyan);

setForeground(Color.blue);

setSize(100,200);

setVisible(true);

}

public static void main(String args[])

{

DemoFlowLayout df=new DemoFlowLayout();

}

}



Output:









55.                Write a java program for GridLayout.



import java.awt.*;

import java.applet.*;

class DemoGridLayout extends Frame

{

public DemoGridLayout()

{

setLayout(new GridLayout(5,4));

for(int i=1;i<=20;i++)

{

Button b=new Button(String.valueOf(i));

add(b);

}

setBackground(Color.cyan);

setForeground(Color.blue);

setSize(100,200);

setVisible(true);

}

public static void main(String args[])

{

DemoGridLayout dg=new DemoGridLayout();

}

}

































Output:









56.     Write a java program for BorderLayout.



import java.awt.*;

import java.applet.*;

import java.awt.event.*;

class DemoBoarder extends Frame

{

Button b1,b2,b3,b4,b5;

public DemoBoarder()

{

setForeground(Color.blue);

setLayout(new BorderLayout());

b1=new Button("one");

b2=new Button("two");

b3=new Button("three");

b4=new Button("four");

b5=new Button("five");

add(b1,"East");

add(b2,"West");

add(b3,"North");

add(b4,"South");

add(b5,"Center");

setSize(300,300);

setVisible(true);

}

public static void main(String args[])

{

DemoBoarder db=new DemoBoarder();

}

}



Output:

















57.     Write a java program for CardLayout.




import java.awt.*;

import java.applet.*;

import java.awt.event.*;

/*<APPLET

CODE=CardLayoutDemo.class

WIDTH=400

HEIGHT=200>

</APPLET>

*/

public class CardLayoutDemo extends Applet implements ActionListener

{

CardLayout cl;

Panel p;

public void init()

{

setBackground(Color.cyan);

setForeground(Color.blue);

p=new Panel();

add(p);

cl=new CardLayout();

p.setLayout(cl);

initialisation();

}

void initialisation()

{

Button b1=new Button("Button1");

Button b2=new Button("Button2");

Button b3=new Button("Button3");

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

p.add(b1,"Button1");

p.add(b2,"Button2");

p.add(b3,"Button3");

}

public void actionPerformed(ActionEvent e)

{

cl.next(p);

}

}











Output:




>javac CardLayoutDemo.java





>appletviewer CardLayoutDemo.java



























58.     Write a java program on “Server and Client”.




/*Server.java*/



import java.io.*;

import java.net.*;

class Server

{

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

{

ServerSocket ss=new ServerSocket(777);

Socket s=ss.accept();

System.out.println("connection establisted");

OutputStream obj=s.getOutputStream();

PrintStream ps=new PrintStream(obj);

String str="Hello client";

ps.println(str);

ps.println("Good Bye");

ps.close();

ss.close();

s.close();

}

}



/*Client.java*/



import java.io.*;

import java.net.*;

class Client

{

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

{

Socket s=new Socket("localhost",777);

InputStream obj=s.getInputStream();

BufferedReader br=new BufferedReader(new InputStreamReader(obj));

String str;

while((str=br.readLine())!=null)

System.out.println("from Server1:"+str);

br.close();

s.close();

}

}











Output:




From Server:





>javac Server1.java






>java Server1






connection establisted






From Client:






>javac Client1.java






>java Client1






from Server1:Hello client


from Server1:Good Bye





59.     Write a java program on “Canvas”.






import java .awt.*;


import java.applet.*;

/*<APPLET CODE=CanvasDemo.class WIDTH=300 HEIGHT=300>

</APPLET>*/

public  class CanvasDemo extends Applet

{

public void  init()

{

setBackground(Color.red);

CanvasExe ce=new CanvasExe();

ce.setSize(200,200);

ce.setBackground(Color.blue);

ce.setVisible(true);

add(ce);

}

class CanvasExe extends Canvas

{

public void paint(Graphics g)

{

setForeground(Color.green);

g.fillOval(30,0,80,80);

g.drawString("Hello",50,100);

}}}





Output:

03 July 2014

Youtube Video Downloader For Google Chrome


Youtube Video Downloader For Google Chrome

>>Here first we need to install the script plugin.

  1. Open Google Chrome Browser and click on setting.
  2. Click on "Extensions" (Left side top corner)
  3. Click on "Get more extensions" (Left side bottom of the page).
  4. Search for "tampermonkey"  and select it.
  5. Here you can find the tampermonkey picture and Click on "+ FREE" buttor (Green color button)
  6. Click on "Add"
  7. Script plugin successfully installed. So now we can import any type of script in your google chrome through tampermonkey extensions.

>>Here second we need to import the script to download the youtube videos.

  1. Click Here to install/import the script.
  2. Click on "Install"
  3. Please close and re-open you google chrome.
  4. Enjoy!!!


Popular Posts



www.Java2Hari.blogspot.com. Powered by Blogger.

 
Design by Java2Hari | Bloggerized by Free Blogger Templates | Free Downloads