Anda di halaman 1dari 86

PROGRAMMING

IN JAVA
INDEX

SESSION

2015 - 16

PROGRAMMING IN JAVA
S.N
O.
1

ASSIGNMENT QUESTION
Write a program to separate the fraction and integer part of the given real number.

Write a program to demonstrate the type casting

Write a program to find the largest number between three numbers using conditional
operator.

Write a program to check whether the number is palindrome or not.

Write a program to convert the integer and real number to equivalent binary number.

Write a program to create 2D array having different variable row size and sum the value
of each row.

Write a program to display the number in words.

Write a program for bubble sort.

Write a program for insertion Sort.

10

Write a program for selection sort.

11

Write a program to create invalid range exception and throws this exception when the
given number is not in the range.

12

Write a program to create negative number exception class and throw this exception when
the given number is negative.

13

Write a program to sort characters of the given string.

14
15

Write a program to check the given string contains the given substring or not if contains
then throws string match exception and display appropriate message, if not throw string
not match exception with proper message.
Write a program to check whether string is palindrome or not without using reverse
method.

16

Write a program to implement methods of string buffer class.

17

Write a program for matrix multiplication.

18

Write a program for Matrix inverse

19

Write a program for matrix transpose

20

Write a program to sort array of string using bubble sort.

21

Write a program for producer consumer using Wait() and notify().

22

Write a program to create an stack interface and create 2 classes FixedStack and
DynamicStack that implements Stack interface.

23

Write a program to generate random numbers and store only 1 to 15 numbers on the list.

PAGE | 1

PAG
E
NO.

PROGRAMMING IN JAVA

24

Write a program for moving string. (animation banner)

25

Write a program for image extraction .(Image show).

26

Write a program for audio clip.

27

28

SESSION

2015 - 16

Write a program to generate the following output ,in all the following cases , accept N
1
-4 9
-16 25 -36
.
.
N rows
1
2
6 24 120
.
.N rows
*
* *
***
****

29

.
N rows
*
30

31

32

*
*

* *
* * *
* ** * *

*
* *
.
.
N rows
Write some code that is capable to generating exception like Arithmetic Exception,
NumberFormatException, ArrayIndexOutOfBoundsException etc.
Write an exception handler that is enclose these line of code in try block and write
appropriate catch block to catch different exception types.
Write a program to demonstrate the working of access specifier in all cases(same class
,same package sub class, same package other class, other package sub class, other package
other class).

33

Write a program to create bar chart in applet using parameter (param tag).

34

Write a program to implement FlowLayout .

35

Write a program to add menubar, menu and menuItem into the frame.

36

Write a program to impelement GridLayout.

37

Write a program to implement border layout.

38

Write a program to implement thread priority use all constant and methods related to
priority.

PAGE | 2

39

PROGRAMMING
IN JAVA
SESSION
2015 - 16
Write a program to search a file,
when file is found
display its path
otherwise display
appropriate message.

40

Write a program to copy the context of the one file to the another file.

41

Write a program to add buttons into frame and handle the event generated by buttons.

42

Write a program to implement the serialization concept.

PAGE | 3

IN JAVA
SESSION
2015 - 16
1. Write a program to separate PROGRAMMING
the fraction and integer
part of the given
real number.

class Sepfrac
{
public static void main (String args[])
{
float f=3.142F;
float n;
System.out.println("the real Value of f="+f);
int m=(int)f;
n=f-m;
System.out.println("the integer value ="+m);
System.out.println("the fraction value="+n);
}
}

Output :-

PAGE | 4

PROGRAMMING IN JAVA

2. Write a program to demonstrate the type casting.

public class TypeCast


{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l;

//explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);

Output :-

PAGE | 5

SESSION

2015 - 16

PROGRAMMING IN JAVA

SESSION

2015 - 16

3. Write a program to find the largest number between three numbers using conditional
operator.

import java.util.Scanner;
class LargestOfThreeNumbers
{
public static void main(String args[])
{
int x, y, z;
System.out.println("Enter three integers ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
if ( x > y && x > z )
System.out.println("First number is largest.");
else if ( y > x && y > z )
System.out.println("Second number is largest.");
else if ( z > x && z > y )
System.out.println("Third number is largest.");
else
System.out.println("Entered numbers are not distinct.");
}
}
Output:-

PAGE | 6

PROGRAMMING IN JAVA

SESSION

4. Write a program to check whether the number is palindrome or not.

class Palindrom
{
public static void main(String args[])
{
int a=152;
int b,res=0,rem=0;
b=a;
while(b!=0)
{
rem=b%10;
res=res*10+rem
;
b=b/10;
}
System.out.println("Inserted number is=:"+a);

if(a==res)
{
System.out.println("Number is Palindrom");
}
else
{
System.out.println("Number is not Palindrom");
}
}
}

Output :PAGE | 7

2015 - 16

PROGRAMMING IN JAVA

SESSION

2015 - 16

5. Write a program to convert the integer and real number to equivalent binary number.
PAGE | 8

PROGRAMMING IN JAVA

SESSION

import java.util.Scanner;

class Binary
{
public static void main(String args[])
{
int j,i;
int n;
int count=0;
int a[]=new int[16];
Scanner obj =new Scanner(System.in);
System.out.println("Enter an integer value to find its equivalent binary");
n=obj.nextInt();
i=0;
while(n!=0)
{
j= n%2;
n=n/2;
a[i]=j;
i=i+1;
count=i;

}
for(i=count-1;i>=0;i--)
{
System.out.print(""+a[i]);

PAGE | 9

2015 - 16

PROGRAMMING IN JAVA

Output :-

7. Write a program to display the number in words.

PAGE | 10

SESSION

2015 - 16

PROGRAMMING IN JAVA

import java.util.Scanner;

public class NumberToWord

{
private static final String[] specialNames = {
"",
" thousand",
" million",
" billion",
" trillion",
" quadrillion",
" quintillion"
};

private static final String[] tensNames = {


"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};

private static final String[] numNames = {


"",

PAGE | 11

SESSION

2015 - 16

" one",

PROGRAMMING IN JAVA

" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};

private String convertLessThanOneThousand(int number) {


String current;

if (number % 100 < 20){


current = numNames[number % 100];
number /= 100;
}
else {
current = numNames[number % 10];
number /= 10;

PAGE | 12

SESSION

2015 - 16

PROGRAMMING IN JAVA

current = tensNames[number % 10] + current;


number /= 10;
}
if (number == 0) return current;
return numNames[number] + " hundred" + current;
}

public String convert(int number) {

if (number == 0) { return "zero"; }

String prefix = "";

if (number < 0) {
number = -number;
prefix = "negative";
}

String current = "";


int place = 0;

do {
int n = number % 1000;
if (n != 0){
String s = convertLessThanOneThousand(n);
current = s + specialNames[place] + current;
}
place++;
number /= 1000;
} while (number > 0);

PAGE | 13

SESSION

2015 - 16

PROGRAMMING IN JAVA

return (prefix + current).trim();


}

public static void main(String[] args) {


NumberToWord obj = new NumberToWord();
Scanner obj1 =new Scanner(System.in);
int n;
System.out.println("Enter the number");
n=obj1.nextInt();
System.out.println(""+obj.convert(n));
}
}

Output :_

PAGE | 14

SESSION

2015 - 16

PROGRAMMING IN JAVA
8. Write a program for Bubble sort.

class Bubble
{
public static void main(String args[])
{
int a[]={5,6,2,3,4,9,11,7,25,12};
int i,j,k;
System.out.println("Element of array");
for(i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
for(i=0;i<a.length;i++)
{
for(j=i+1;j<a.length;j++)
{
if (a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("After Sorting Element of array");
for(i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
PAGE | 15

SESSION

2015 - 16

PROGRAMMING IN JAVA

Output :-

PAGE | 16

SESSION

2015 - 16

PROGRAMMING
IN JAVA
9. Write a program for Insertion
sort.

import java.util.Scanner;

class InsertionSort
{
public static void main(String args[]) {
int n, i, key,tmp;
Scanner obj = new Scanner(System.in);

System.out.println("Enter the number of integers");


n = obj.nextInt();

int array[] = new int[n];

System.out.println("Enter " + n + " integers");

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


array[i] = obj.nextInt();

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


{
key = i;
while (key > 0 && array[key - 1] > array[key])
{
tmp = array[key];
array[key] = array[key - 1];
array[key- 1] = tmp;
key--;
}

PAGE | 17

SESSION

2015 - 16

PROGRAMMING IN JAVA

System.out.println("Sorted list of numbers");

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


System.out.println(array[i]);
}
}

Output :-

PAGE | 18

SESSION

2015 - 16

PROGRAMMING IN JAVA

10. Write a program for selection sort.

import java.util.Scanner;

class SelectionSort {
public static void main(String []args) {
int n, i, j,index, smaller ;
Scanner obj = new Scanner(System.in);

System.out.println("Enter the number of integers");


n = obj.nextInt();

int array[] = new int[n];

System.out.println("Enter " + n + " integers");

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


array[i] = obj.nextInt();

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


{
index = i;
for ( j = i + 1; j <n; j++)
{
if (array[j] < array[index])

{
index = j;
}
}

PAGE | 19

SESSION

2015 - 16

PROGRAMMING IN JAVA

SESSION

2015 - 16

smaller = array[index];
array[index] = array[i];
array[i] = smaller;
}

System.out.println("Sorted list of numbers");

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


System.out.println(array[i]);
}
}

Output :-

11. Write a program to create InvalidRangeException and throws this exception when the
given number is not in the range.

PAGE | 20

PROGRAMMING IN JAVA

SESSION

2015 - 16

import java.util.Scanner;
class InvalidNumberException
{
public static void main(String args[])
{
Scanner obj = new Scanner(System.in);
boolean tryAgain = true;
do {
try {
System.out.println("Please enter an integer between 1 to 100 : ");

int init = obj.nextInt();

if (init >= 1 && init <= 100){


System.out.println("Thank you, valid number");
tryAgain = false;
}
else if (init < 1 || init > 100){
throw new NumberFormatException("Integer is out of range.");
}

}
catch (NumberFormatException e1)
{
System.out.println(" The number you entered is not between 1 and 100. pls Try again.");
System.out.println();
obj.nextLine();
}

PAGE | 21

PROGRAMMING IN JAVA

while(tryAgain);
}
}

Output :-

PAGE | 22

SESSION

2015 - 16

IN JAVA class and


SESSION
2015
- 16
12. Write a program to createPROGRAMMING
negative number exception
throw this
exception
when the given number is negative.

import java.util.Scanner;
class NegativeNumberException
{
public static void main(String args[])
{
Scanner obj = new Scanner(System.in);
boolean tryAgain = true;
do {
try {
System.out.println("Please input a positive integer");

int init = obj.nextInt();

if (init >= 1)
{
System.out.println("Positive integer , accepted request");
tryAgain = false;
}
else if (init < 1)
{
throw new NumberFormatException("Integer is Negative");
}

}
catch (NumberFormatException e1)
{
System.out.println(" The entered number is not a positive integer");
System.out.println();

PAGE | 23

obj.nextLine();

PROGRAMMING IN JAVA

while(tryAgain);
}
}

Output :-

PAGE | 24

SESSION

2015 - 16

PROGRAMMING
JAVA
13. Write a program to sort characters
of the givenIN
string.

import java.io.* ;
import java.util.Scanner;

class CharBubbleSort1

public static void main (String args[])


{
//String str="Computer"

Scanner obj=new Scanner(System.in);


System.out.println("Enter the string");
String str=obj.nextLine();
int i, j;
i=j=0;
char temp ;
int arrlen = 0 ;
int strlen = str.length() ;
char strarray[] = new char[50] ;

System.out.println("Str array: " + str) ;


for (int a = 0 ; a < strlen ; a++)
{
strarray[a] = str.charAt(a) ;
arrlen++ ;
}

PAGE | 25

SESSION

2015 - 16

PROGRAMMING IN JAVA

for(i=0; i< (arrlen - 1); ++i)


{

for(j = i + 1; j > 0; --j)


{
if(strarray[j] < strarray[j-1])
{
//Swaps the values
temp = strarray[j];
strarray[j] = strarray[j - 1];
strarray[j - 1] = temp;
}
}
}
System.out.print("Sorted String :" ) ;
for (int b = 0 ; b < strlen ; b++)

{
System.out.print(strarray[b]) ;
}
}
}
Output :-

PAGE | 26

SESSION

2015 - 16

PROGRAMMING
IN JAVA
SESSION
- 16
14. Write a program to check the
given string contains
the given substring
or not2015
if contains
then throws string match exception and display appropriate message , if not throw string
not match exception with proper message.

import java.util.Scanner;
class StringMatch extends Exception
{
String str;
StringMatch(String str)
{
this.str=str;
}
public String toString()
{
return str;
}
}
class StringNotMatch extends Exception
{
String str;
StringNotMatch(String str)
{
this.str=str;
}
public String toString()
{
return str;
}
}
class SubStringDemo
{
public static void main(String args[])
{
String string, sub,substr;
int i, c, length,flag=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to find its substring");
string = in.nextLine();
length = string.length();
System.out.println("Enter a substring");
substr = in.nextLine();
System.out.println();
try{
for( c = 0 ; c < length ; c++ )
{
for( i = 1 ; i <= length - c ; i++ )
{
sub=string.substring(c,c+i);
if(substr.equals(sub))
PAGE | 27

PROGRAMMING IN JAVA
{
flag=1;
throw new StringMatch("SubString is Matched");
}
}
}
if(flag==0)
throw new StringNotMatch("Substring not found");
}
catch(StringMatch sm)
{
System.out.println(sm.toString());
}
catch(StringNotMatch snm)
{
System.out.println(snm.toString());

}
}
}
Output :-

PAGE | 28

SESSION

2015 - 16

PROGRAMMING
IN JAVAor not without
SESSION
15. Write a program to check whether
string is palindrome
using 2015
reverse- 16
method.

import java.util.*;
import java.lang.*;
import java.util.Scanner;

class Palindrome
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the string");

String chr=obj.nextLine();

String reverse="";
int len=chr.length();

for(int i=len-1;i>-1;i--)
{
reverse=reverse+chr.charAt(i);
}
System.out.println("Reversed String is: "+reverse);

if(chr.equals(reverse))
{
System.out.println("The Given String is Palindrome");
}else{

PAGE | 29

PROGRAMMING
JAVA
SESSION 2015 - 16
System.out.println("The
Given String is notIN
a Palindrome");

}
}
}

Output :-

PAGE | 30

PROGRAMMING
INbuffer
JAVA class.
16. Write a program to implement
methods of string

SESSION

2015 - 16

class StringBufferDemo
{

public static void main(String[] args)


{

StringBuffer sb = new StringBuffer("Hello world");

System.out.println("original: " + sb);

System.out.println("length():\n " + sb.length() + ",\n capacity(): \n" + sb.capacity());

System.out.println("charAt(10): \n" + sb.charAt(10));

System.out.println("append():\n " + sb.append(" This is java program "));

System.out.println("insert(): \n" + sb.insert(12, "I am chandresh & "));

System.out.println("indexOf()\n" + sb.indexOf("chandresh"));

System.out.println("delete(): \n" + sb.delete(7, "chandresh ".length()));

PAGE | 31

PROGRAMMING
IN JAVA
System.out.println("substing(5,15):\n
" + sb.substring(5,15));

System.out.println("reverse():\n " + sb.reverse());

}
}

Output :-

PAGE | 32

SESSION

2015 - 16

PROGRAMMING
17. Write a program to Multiplication
of Matrix. IN JAVA

SESSION

2015 - 16

import java.util.Scanner;

class MulMatrix
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;

Scanner obj = new Scanner(System.in);


System.out.println("Enter the number of rows and columns of first matrix");
m = obj.nextInt();
n = obj.nextInt();

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

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

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
first[c][d] = obj.nextInt();

System.out.println("Enter the number of rows and columns of second matrix");


p = obj.nextInt();
q = obj.nextInt();

if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied with each other.");
else
{

PAGE | 33

PROGRAMMING IN JAVA
int second[][] = new int[p][q];

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

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

for ( c = 0 ; c < p ; c++ )


for ( d = 0 ; d < q ; d++ )
second[c][d] = obj.nextInt();

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

System.out.println("Product of entered matrices:");

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < q ; d++ )
System.out.print(multiply[c][d]+"\t");

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

PAGE | 34

SESSION

2015 - 16

PROGRAMMING IN JAVA

}
}
}

Output :-

PAGE | 35

SESSION

2015 - 16

PROGRAMMING
IN JAVA
18. Write a program to Addition
of matrix.

SESSION

import java.util.Scanner;

class SumMatrix
{
public static void main(String args[])
{
int m, n, p, q, s = 0, c, d;

Scanner obj = new Scanner(System.in);


System.out.println("Enter the number of rows and columns of matrices");
m = obj.nextInt();
n = obj.nextInt();

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

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

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
first[c][d] = obj.nextInt();

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


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

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n; d++ )
second[c][d] = obj.nextInt();

PAGE | 36

2015 - 16

PROGRAMMING IN JAVA

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

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < n ; d++ )
{

sum[c][d]= first[c][d] + second[c][d];

}
}

System.out.println("sum of entered matrices:");

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < n ; d++ )

System.out.print(sum[c][d]+"\t");

System.out.print("\n");
}
}
}

PAGE | 37

SESSION

2015 - 16

Output :-

PROGRAMMING IN JAVA

PAGE | 38

SESSION

2015 - 16

IN JAVA
19. Write a program for InversePROGRAMMING
of Matrix.

import java.util.Scanner;

public class InverseMatrix


{
public static void main(String argv[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the dimension of square matrix: ");
int n = input.nextInt();
double a[][]= new double[n][n];
System.out.println("Enter the elements of matrix: ");
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
a[i][j] = input.nextDouble();

double d[][] = invert(a);

System.out.println("The inverse is: ");


for (int i=0; i<n; ++i)
{
for (int j=0; j<n; ++j)
{
System.out.print(d[i][j]+" ");
}
System.out.println();
}
input.close();
}

PAGE | 39

SESSION

2015 - 16

PROGRAMMING
IN JAVA
public static double[][] invert(double
a[][])

{
int n = a.length;
double x[][] = new double[n][n];
double b[][] = new double[n][n];
int index[] = new int[n];
for (int i=0; i<n; ++i)
b[i][i] = 1;

// Transform the matrix into an upper triangle


gaussian(a, index);

// Update the matrix b[i][j] with the ratios stored


for (int i=0; i<n-1; ++i)
for (int j=i+1; j<n; ++j)
for (int k=0; k<n; ++k)
b[index[j]][k]
-= a[index[j]][i]*b[index[i]][k];

// Perform backward substitutions


for (int i=0; i<n; ++i)
{
x[n-1][i] = b[index[n-1]][i]/a[index[n-1]][n-1];
for (int j=n-2; j>=0; --j)
{
x[j][i] = b[index[j]][i];
for (int k=j+1; k<n; ++k)
{
x[j][i] -= a[index[j]][k]*x[k][i];
}
x[j][i] /= a[index[j]][j];

PAGE | 40

SESSION

2015 - 16

PROGRAMMING IN JAVA

}
}
return x;
}

// Method to carry out the partial-pivoting Gaussian


// elimination. Here index[] stores pivoting order.

public static void gaussian(double a[][], int index[])


{
int n = index.length;
double c[] = new double[n];

// Initialize the index


for (int i=0; i<n; ++i)
index[i] = i;

// Find the rescaling factors, one from each row


for (int i=0; i<n; ++i)
{
double c1 = 0;
for (int j=0; j<n; ++j)
{
double c0 = Math.abs(a[i][j]);
if (c0 > c1) c1 = c0;
}
c[i] = c1;
}

// Search the pivoting element from each column


int k = 0;

PAGE | 41

SESSION

2015 - 16

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

PROGRAMMING IN JAVA

{
double pi1 = 0;
for (int i=j; i<n; ++i)
{
double pi0 = Math.abs(a[index[i]][j]);
pi0 /= c[index[i]];
if (pi0 > pi1)
{
pi1 = pi0;
k = i;
}
}

// Interchange rows according to the pivoting order


int itmp = index[j];
index[j] = index[k];
index[k] = itmp;
for (int i=j+1; i<n; ++i)
{
double pj = a[index[i]][j]/a[index[j]][j];

// Record pivoting ratios below the diagonal


a[index[i]][j] = pj;

// Modify other elements accordingly


for (int l=j+1; l<n; ++l)
a[index[i]][l] -= pj*a[index[j]][l];
}
}
}

PAGE | 42

SESSION

2015 - 16

PROGRAMMING IN JAVA

SESSION

Assignment 20. Wap for transpose of a matrix.


import java.util.Scanner;

class TransposeMatrix
{
public static void main(String args[])
{
int m, n, c, d;

Scanner in = new Scanner(System.in);


System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();

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

System.out.println("Enter the elements of matrix");

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
matrix[c][d] = in.nextInt();

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

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];
}

PAGE | 43

2015 - 16

PROGRAMMING IN JAVA

System.out.println("Transpose of entered matrix:-");

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


{
for ( d = 0 ; d < m ; d++ )
System.out.print(transpose[c][d]+"\t");

System.out.print("\n");
}
}
}
Output :-

PAGE | 44

SESSION

2015 - 16

PROGRAMMING
IN JAVA
20. Write a program for transpose
of a matrix.

import java.util.Scanner;
class TranspMatrix
{
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();
int matrix[][] = new int[m][n];
System.out.println("Enter the elements of matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
matrix[c][d] = in.nextInt();
int transpose[][] = new int[n][m];
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];
}
System.out.println("Transpose of entered matrix:-");
for ( c = 0 ; c < n ; c++ )
{
for ( d = 0 ; d < m ; d++ )
System.out.print(transpose[c][d]+"\t");
System.out.print("\n");
}
}
PAGE | 45

SESSION

2015 - 16

PROGRAMMING IN JAVA

OUTPUT :-

PAGE | 46

SESSION

2015 - 16

PROGRAMMING
IN JAVA
21. Write a program to sort array
of string using bubble
sort.

class stringordering
{
static String name[]={"Ram","Mitesh","Akash","Bhupendra"};
public static void main(String arg[])
{
int size=name.length;
String temp=null;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(name[i].compareTo(name[j])>0)
{
//swap the string
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}

PAGE | 47

SESSION

2015 - 16

OUTPUT :-

PROGRAMMING IN JAVA

PAGE | 48

SESSION

2015 - 16

PROGRAMMING
IN JAVA
SESSION 2015 - 16
22. Write a program for producer
consumer using Wait()
and notify().

class Q
{
int n;
boolean value=false;
synchronized void put(int n)
{
try {
if(!value)
{
wait();
}
}
catch(InterruptedException ae)
{
System.out.println(ae);
}
this.n=n;
System.out.println("put value ="+n);
value=false;
notify();
}
synchronized int get()
{
try
{
if(value)
{
wait();
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("get value ="+n);
value=true;
notify();
return n;
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread (this,"Producer").start();
}

PAGE | 49

PROGRAMMING IN JAVA
public void run()
{
int i=0;
while(i<=50)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q1;
Consumer(Q q1)
{
this.q1=q1;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q1.get();
}
}
}
class Interprocess
{
public static void main(String args[])
{
Q q=new Q();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
}
}

Output :-

PAGE | 50

SESSION

2015 - 16

PROGRAMMING
IN and
JAVAcreate 2 SESSION
2015 - and
16
23. Write a program to create
an stack interface
classes FixedStack
DynamicStack that implements Stack interface.

import java.util.*;
interface Stack
{
void push(int item);
int pop();
}

class DynamicStack implements Stack


{
int stack[];
int top;

DynamicStack(int size)
{
stack = new int[size];
top=-1;
}

public void push(int node)


{
if(top==(stack.length-1))
{
int temp[] = new int[stack.length*2];
int i;
for(i=0;i<stack.length;i++)
{
temp[i]=stack[i];
}
PAGE | 51

stack=temp;

PROGRAMMING IN JAVA

stack[++top]=node;
}
else
stack[++top]=node;
}
public int pop()
{
if(top==-1)
{
System.out.println("Stack is now empty");
return 0;
}
else
return (stack[top--]);
}

void display()
{
for(int i:stack)
{
System.out.println(i);
}
}
}

class FixedStack implements Stack


{
int stack[];
int top;

PAGE | 52

SESSION

2015 - 16

PROGRAMMING IN JAVA

FixedStack(int size)
{
stack = new int[size];
top=-1;
}

public void push(int node)


{
if(top==(stack.length-1))
{

stack[++top]=node;
}
else
stack[++top]=node;
}
public int pop()
{
if(top==-1)
{
System.out.println("Stack is now empty");
return 0;
}
else
return (stack[top--]);
}

void display()
{
for(int i:stack)

PAGE | 53

SESSION

2015 - 16

PROGRAMMING IN JAVA

System.out.println(i);
}
}

class StackDemo
{
public static void main(String args[])
{
DynamicStack f = new DynamicStack(3);

int i;
for(i=0;i<3;i++)
{
f.push(i);
}
System.out.println("Displaying contents of Stack");
f.display();
System.out.println("Now popping elements off the stack");
for(i=0;i<2;i++)
{
System.out.println("Popped element is " + f.pop());

FixedStack fs=new FixedStack(3);


System.out.println("again pushed elements are:");

PAGE | 54

SESSION

2015 - 16

fs.push(4);

PROGRAMMING IN JAVA

fs.display();
fs.push(5);
fs.display();
System.out.println("");
System.out.println("\nPopped element is " + fs.pop());
System.out.println("Popped element is " + fs.pop());

}
}

Output :-

PAGE | 55

SESSION

2015 - 16

SESSION
2015
- 16
24. Write a program to generatePROGRAMMING
random numbers IN
andJAVA
store only 1 to
15 numbers
on the
list.

import java.util.*;
public class Random
{

public static void main(String[] args)


{
int n;
LinkedList ll=new LinkedList();

System.out.println("Random numbers between 0.0 and 1.0 are,");


for(int i=0; i < 15 ; i++)
System.out.println("Random Number ["+ (i+1) + "] : " + Math.random());

System.out.println("Random numbers between 1 and 15 are,");


for(int i=0; i < 15 ; i++)
{
n=(int)(Math.random()*15);
ll.add(n);

}
System.out.println("The contents of the linked list are:"+ll);

}
}

PAGE | 56

Output :-

PROGRAMMING IN JAVA

PAGE | 57

SESSION

2015 - 16

JAVA
25. Write a program for movingPROGRAMMING
string. (animation IN
banner)

import java.applet.*;
import java.awt.*;
/*<applet code="TextMove.class" width=450 height=400>
</applet>*/

public class TextMove extends Applet implements Runnable


{
Thread t;
int x,y;
boolean stopflag;
public void init()
{
setBackground(Color.blue);
setForeground(Color.red);

x=120;y=130;

public void start()


{
stopflag=false;
t=new Thread(this,"one");
t.start();

public void paint(Graphics g)


{showStatus("name of college");
PAGE | 58

SESSION

2015 - 16

PROGRAMMING
IN JAVA
g.drawString("Progamming in JAVA
",x,y);

public void stop()


{
stopflag=true;
t=null;
}

public void run()


{ char ch;
for(; ;)
{
try
{
y++;x++;
repaint();
Thread.sleep(50);
if(stopflag) break;
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}

Output :PAGE | 59

SESSION

2015 - 16

PROGRAMMING IN JAVA

26. Write a program for image extraction. (Image show).

PAGE | 60

SESSION

2015 - 16

PROGRAMMING IN JAVA

SESSION

import java.awt.*;
import java.applet.*;
/* <applet code=AppletImage.class width= 400 height =400> <param name=imgsrc
value="images.jpg"> </applet> */
public class AppletImage extends Applet
{
Image img;
String imgSource;
public void start()
{
imgSource=getParameter("imgSrc");
img=getImage(getCodeBase(),imgSource);
}
public void paint(Graphics g)
{
g.drawImage(img,10,10,this);
}

PAGE | 61

2015 - 16

}OUTPUT :-

PROGRAMMING IN JAVA

PAGE | 62

SESSION

2015 - 16

PROGRAMMING IN JAVA
27. Write a program for audio clip.

SESSION

import java.awt.event.*;
import java.applet.*;
import java.awt.*;
/* <applet code="AppletAudio.class" width=400 Height=500>
<param name="audioname" value="bc.au\\">
</applet> */
public class AppletAudio extends Applet implements ActionListener
{
AudioClip audioclip;
Button play,stop;
public void init()
{
play=new Button("play");
stop=new Button("stop");
add(play);
add(stop);
play.addActionListener(this); //resister ActionListener to play button
stop.addActionListener(this);
String audio=getParameter("audioname"); // blue eyes is assign to audio
audioclip =getAudioClip(getCodeBase(),audio);
audioclip.play();
System.out.println(audioclip);

}
public void actionPerformed(ActionEvent ae)
{

PAGE | 63

2015 - 16

PROGRAMMING IN JAVA
if(ae.getActionCommand()=="play")

{
System.out.println("start");
audioclip.play();
}
else if(ae.getActionCommand()=="stop")
{ System.out.println("stop");
audioclip.stop();
}
}
}

OUTPUT :-

PAGE | 64

SESSION

2015 - 16

IN ,in
JAVA
SESSION
2015 -N16
28. Write a program to generatePROGRAMMING
the following output
all the following
cases , accept
row.

1
-4 9
-16 25 -36
.
.
N rows
import java.util.*;
import java.io.*;
class Pattern2
{
public static void main(String args[])
{
int i,j,r;
int k=1;
Scanner obj=new Scanner(System.in);
System.out.println("Enter the no. of rows");
r=obj.nextInt();
System.out.println("");
for(i=0;i<r;i++)
{
for(j=0;j<=i;j++)
{
if(k%2==0)
{
System.out.print("-"+(k*k)+" \t");
}
else
{
System.out.print((k*k)+" \t");
}
k++;
}
System.out.println(" ");
}
}
}

Output :-

PAGE | 65

PROGRAMMING IN JAVA

PAGE | 66

SESSION

2015 - 16

IN ,in
JAVA
SESSION
2015 -N16
29. Write a program to generatePROGRAMMING
the following output
all the following
cases , accept
row.

1
2
6
.

24 120

.
N rows
import java.util.*;
import java.io.*;
class Pattern1
{
public static void main(String args[])
{
Pattern1 ob =new Pattern1();
int n;
int i,j,r;
int k=0;
Scanner obj=new Scanner(System.in);
System.out.println("Enter the no. of rows");
r=obj.nextInt();
for(i=0;i<r;i++)
{
for(j=0;j<=i;j++)
{

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

System.out.println(" ");
}

PAGE | 67

PROGRAMMING IN JAVA

}
static int fact(int n)
{

if(n<=1)
{
return 1;
}
else
{

return n* fact(n-1);
}

Output :-

PAGE | 68

SESSION

2015 - 16

PROGRAMMING
IN JAVA
30. Write a program to print the
Pattern.

*
* *
* * *
* * * *
* * * * *
import java.util.*;
import java.io.*;
class Pattern3
{
public static void main(String args[])
{

int i,j,r;
Scanner obj=new Scanner(System.in);
System.out.println("Enter the no. of rows");
r=obj.nextInt();
for(i=0;i<=r;i++)
{
for(j=r;j>i;j--)
{
System.out.print(" ");

}
for(int k=i;k>0;k--)
{
System.out.print(" *");
}
System.out.println(" ");

PAGE | 69

SESSION

2015 - 16

PROGRAMMING IN JAVA

}
}

Output :-

PAGE | 70

SESSION

2015 - 16

PROGRAMMING
IN JAVA
31. Write a program to print the
Pattern.

*
* * *
* * * * *
* * * * * * *
import java.util.*;
import java.io.*;
class Pattern4
{
public static void main(String args[])
{

int i,j,r;
Scanner obj=new Scanner(System.in);
System.out.println("Enter the no. of rows");
r=obj.nextInt();
for(i=0;i<r;i++)
{
for(j=r;j>i;j--)
{
System.out.print(" ");

}
for(int k=2*i ;k>=0;k--)
{
System.out.print("* ");
}
System.out.println(" ");

PAGE | 71

SESSION

2015 - 16

PROGRAMMING IN JAVA

}
}

Output :-

PAGE | 72

SESSION

2015 - 16

PROGRAMMING
35. Write a Program to implement
FlowLayout. IN JAVA

SESSION

2015 - 16

import java.awt.*;
import javax.swing.*;
public class MyFlowLayout{
JFrame f;
MyFlowLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}

PAGE | 73

//setting flow layout of right alignment

OUTPUT :-

PROGRAMMING IN JAVA

PAGE | 74

SESSION

2015 - 16

PROGRAMMING
IN JAVAinto the SESSION
2015 - 16
36. Write a Program to add menubar,
menu and menuItem
frame .

import java.awt.*;
class AWTMenu extends Frame
{
MenuBar mbar;
Menu menu,submenu;
MenuItem m1,m2,m3,m4,m5;
public AWTMenu()
{

// Set frame properties

setTitle("AWT Menu");

// Set the title

setSize(400,400);

// Set size to the frame

setLayout(new FlowLayout());

// Set the layout

setVisible(true);

// Make the frame visible

setLocationRelativeTo(null);

// Center the frame

mbar=new MenuBar();

// Create the menu bar

menu=new Menu("Menu");

// Create the menu

submenu=new Menu("Page");

// Create the submenu

m1=new MenuItem("New");

// Create MenuItems

m2=new MenuItem("Open");
m3=new MenuItem("Save");
m4=new MenuItem("Print");
m5=new MenuItem("Print Preview");
menu.add(m1);

// Attach menu items to menu

menu.add(m2);
menu.add(m3);
submenu.add(m4);

// Attach menu items to submenu

submenu.add(m5);

PAGE | 75

menu.add(submenu);

PROGRAMMING// IN
JAVA
SESSION
Attach
submenu to
menu

mbar.add(menu);

// Attach menu to menu bar

setMenuBar(mbar);

// Set menu bar to the frame

}
public static void main(String args[])
{
new AWTMenu();
}
}
OUTPUT :-

PAGE | 76

2015 - 16

PROGRAMMING IN JAVA

37. Write a Program to implement GridLayout.

import java.awt.*;
import java.applet.*;
/* <applet code ="GridLayout" width =300 height =200> </applet>*/
public class GridLayout extends Applet
{
static final int n =3;
public void init()
{
setLayout (new GridLayout (n, n));
setFont (new Font ("Times New Roman", Font.BOLD, 12));
for(int i =0; i<n; i++)
{
for (int j=0; j<n; j++)
{
int k=i *n+j;
if(k>0)
add(new Button (" " +k));
}
}
}
}

PAGE | 77

SESSION

2015 - 16

PROGRAMMING IN JAVA

OUTPUT :-

PAGE | 78

SESSION

2015 - 16

PROGRAMMING IN JAVA

38. Write a Program to implement border layout.

import java.awt.*;
import java.awt.event.*;
class BorderDemo extends Frame
{
public BorderDemo()
{
Label lbl1 = new Label("NORTH");
Label lbl2=new Label("SOUTH");
Button btn1 = new Button("EAST");
Button btn2=new Button("WEST");
TextArea ta = new TextArea(5,5);
ta.append("CENTER");
setLayout(new BorderLayout());
add(lbl1,BorderLayout.NORTH);
add(lbl2,BorderLayout.SOUTH);
add(btn1,BorderLayout.EAST);
add(btn2,BorderLayout.WEST);
add(ta,BorderLayout.CENTER);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}

PAGE | 79

SESSION

2015 - 16

} );

PROGRAMMING IN JAVA

}
public static void main(String args[])
{
BorderDemo bd = new BorderDemo();
bd.setTitle("BorderLayout");
bd.setSize(300,200);
bd.setVisible(true);
}
}

OUTPUT :-

PAGE | 80

SESSION

2015 - 16

PROGRAMMING IN JAVA

SESSION

Assignment 32 . Wap to create Bar chart using param tag.

Assignment 41. Wap to copy the context of the one file to the another file.
import java.io.*;

public class CopyFile {


public static void main(String[] args)
throws Exception {
BufferedWriter out1 = new BufferedWriter
(new FileWriter("srcfile"));
out1.write("string to be copied\n");
out1.close();
InputStream in = new FileInputStream
(new File("srcfile"));
OutputStream out = new FileOutputStream
(new File("destnfile"));
byte[] buf = new byte[1024];
int len;

PAGE | 81

2015 - 16

PROGRAMMING
IN JAVA
while ((len = in.read(buf)) > 0)
{

out.write(buf, 0, len);
}
in.close();
out.close();
BufferedReader in1 = new BufferedReader
(new FileReader("destnfile"));
String str;
while ((str = in1.readLine()) != null) {
System.out.println(str);
}
in.close();
}
}

PAGE | 82

SESSION

2015 - 16

PROGRAMMING
INdisplay
JAVA its path SESSION
2015 - 16
Assignment 42. Wap to search a file,
when file is found
otherwise display
appropriate message.

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/*
* Here we will learn to search files in Folder
*/
class FileSearch {

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


System.out.println("Enter the path to folder to search for files");

Scanner scanner = new Scanner(System.in);

String folderPath = scanner.next();

File folder = new File(folderPath);

if (folder.isDirectory()) {
File[] listOfFiles = folder.listFiles();
if (listOfFiles.length < 1)
System.out.println("There is no File inside Folder");
else
System.out.println("List of Files & Folder");

for (File file : listOfFiles) {

PAGE | 83

PROGRAMMING IN JAVA
if(!file.isDirectory())

System.out.println(file.getCanonicalPath().toString());
}
}

else
System.out
.println("There is no Folder @ given path :" + folderPath);
}
}

PAGE | 84

SESSION

2015 - 16

IN JAVA
2015
- 16
Assignment 6. Wap to create 2DPROGRAMMING
array having different
variable rowSESSION
size and sum
the value
of each row.

class AnonymousArray
{
public static void main(String args[])
{
System.out.println("First sum of numbers"+sum(new int[] {1,2,3,4,5,6}));
System.out.println("Second sum of the numbers"+sum(new int [] {3,5,6,7,9,10}));
}

public static int sum(int[] num)


{
int total=0;
for(int i : num)

// for each loop

same as for(i=0;i<=num.length;i++)

total=total+i;
return total;
}

PAGE | 85

PROGRAMMING IN JAVA

PAGE | 86

SESSION

2015 - 16

Anda mungkin juga menyukai