Você está na página 1de 60

qwertyuiopasdfghjklzxcvbnmqwertyui

Java Programming Lab


opasdfghjklzxcvbnmqwertyuiopasdfgh
jklzxcvbnmqwertyuiopasdfghjklzxcvb
nmqwertyuiopasdfghjklzxcvbnmqwer
Java Programming Lab
tyuiopasdfghjklzxcvbnmqwertyuiopas
II YEAR II SEMISTER
dfghjklzxcvbnmqwertyuiopasdfghjklzx
cvbnmqwertyuiopasdfghjklzxcvbnmq
wertyuiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopasdfghj
klzxcvbnmqwertyuiopasdfghjklzxcvbn
mqwertyuiopasdfghjklzxcvbnmqwerty
uiopasdfghjklzxcvbnmqwertyuiopasdf
ghjklzxcvbnmqwertyuiopasdfghjklzxc
vbnmqwertyuiopasdfghjklzxcvbnmrty
uiopasdfghjklzxcvbnmqwertyuiopasdf
ghjklzxcvbnmqwertyuiopasdfghjklzxc
COMPUTER SCIENCE AND ENGINEERING

Java Programming Lab


Table of Contents
Write a JAVA program to display default value of all primitive data types of JAVA ............................... 4
Write a JAVA program that displays the roots of a quadratic equation ax2+bx+c=0. Calculate the
discriminent D and basing on the value of D, describe the nature of roots. .......................................... 5
Write a JAVA program to display the Fibonacci sequence .................................................................... 7
Write a JAVA program give example for command line arguments. ..................................................... 8
Write a JAVA program to sort given list of numbers. ............................................................................ 9
Write a JAVA program to search for an element in a given list of elements (linear search). ................ 11
Write a JAVA program to search for an element in a given list of elements using binary search
mechanism. ....................................................................................................................................... 12
Write a JAVA program to determine the addition of two matrices ..................................................... 14
Write a JAVA program to determine multiplication of two matrices................................................... 16
Write a JAVA program to sort an array of strings ............................................................................... 18
Write a JAVA program to check whether given string is palindrome or not. ....................................... 19
Write a JAVA program for the following ............................................................................................. 20
2-Example for call by reference. ..................................................................................................... 21
Write a JAVA program to demonstrate static variables, methods, and blocks. ................................... 22
Write a JAVA program to give the example for super keyword. ........................................................ 23
Write a JAVA program that illustrates simple inheritance .................................................................. 24
Write a JAVA program that illustrates multi-level inheritance ............................................................ 26
Write a JAVA program demonstrating the difference between method overloading and method
overriding. ......................................................................................................................................... 28
Method overloading ...................................................................................................................... 28
Method overriding ......................................................................................................................... 30
Write a JAVA program demonstrating the difference between method overloading and constructor 31
Method overloading ...................................................................................................................... 31
Constructor overloading ................................................................................................................ 33
Write a JAVA program that describes exception handling mechanism................................................ 34
Write a JAVA program for example of try and catch block. In this check whether the given array size is
negative or not. ................................................................................................................................. 35
Write a JAVA program for creation of user defined exception ............................................................ 37

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to illustrate creation of threads using runnable class.(start method start each of
the newly created thread. Inside the run method there is sleep() for suspend the thread for 500
milliseconds)...................................................................................................................................... 38
Write a JAVA program to create a class MyThread in this class a constructor, call the base class
constructor, using super and starts the thread. The run method of the class starts after this. It can be
observed that both main thread and created child thread are executed concurrently ........................ 40
Write a JAVA program illustrating multiple inheritance using interfaces. ........................................... 42
Write a JAVA program to create a package named pl, and implement this package in ex1 class. ........ 44
Write a JAVA program to create a package named mypack and import it in circle class...................... 45
Write a JAVA program to give a simple example for abstract class. .................................................... 46
Write a JAVA program that describes the life cycle of an applet ......................................................... 47
Write a JAVA program to create a dialogbox and menu. ................................................................ 47
Write a JAVA program to create a grid layout control..................................................................... 51
Write a JAVA program to create a border layout control. ................................................................... 52
Write a JAVA program to create a simple calculator. .......................................................................... 53
Write a JAVA program that displays the x and y position of the cursor movement using Mouse ........ 57
Write a JAVA program that displays number of characters, lines and words in a text file. .................. 59

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to display default value of all primitive data types of
JAVA
Program:
class DefaultValues
{
static byte b;
static short s;
static int i;
static long l;
static float f;
static double d;
static char c;
static boolean bl;
public static void main(String[] args)
{
System.out.println("Byte :"+b);
System.out.println("Short :"+s);
System.out.println("Int :"+i);
System.out.println("Long :"+l);
System.out.println("Float :"+f);
System.out.println("Double :"+d);
System.out.println("Char :"+c);
System.out.println("Boolean :"+bl);
}
}
Output:

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program that displays the roots of a quadratic equation
ax2+bx+c=0. Calculate the discriminent D and basing on the value of D,
describe the nature of roots.
Program:
import java.util.Scanner;
public class CalcAvrgAccel_2_9 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the values of a, b and c");
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
double r1 = 0;
double r2 = 0;
double discriminant = b * b - 4 * a * c;
if (discriminant > 0){
r1 = (-b + Math.sqrt(discriminant)) / (2 * a);
r2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The equation has two real roots " + r1 + " and " + r2);
}
if (discriminant == 0){
System.out.println("The equation has one root " +r1);
r1 = -b / (2 * a);
r2 = -b / (2 * a);
}
if (discriminant < 0){
System.out.println("The equation has no real root");
}
}
}

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Output:

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to display the Fibonacci sequence
Program:
class Fibonacci{
public static void main(String args[]){
int num = Integer.parseInt(args[0]);
System.out.println("*****Fibonacci Series*****");
int f1, f2=0, f3=1;
for(int i=1;i<=num;i++){
System.out.print(" "+f3+" ");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
}
}
Output:

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab

Write a JAVA program give example for command line arguments.


Program:
import java.io.*;
class cli{
public static void main(String args[]){
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("*****Addition*****");
int c=a+b;
System.out.print(" "+c+" ");
}
}

Output:

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to sort given list of numbers.
Program:
class sorting
{
public static void main(String args[])
{
int number[]={55,40,80,65,71};
int n=number.length;
System.out.println("given list");
for(int i=0;i<n;i++)
{
System.out.println(""+number[i]);
}
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(number[i]<number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
System.out.println("sorted list");
for(int i=0;i<n;i++)
{
System.out.println(""+number[i]);
}
System.out.println("");
}
}

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Output:

10

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to search for an element in a given list of elements
(linear search).
Program:
import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}
Output:

11

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to search for an element in a given list of elements
using binary search mechanism.
Program:
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}

12

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Output:

13

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to determine the addition of two matrices
Program:
import java.util.Scanner;
class AddTwoMatrix
{
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 first[][] = new int[m][n];
int second[][] = new int[m][n];
int sum[][] = 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] = in.nextInt();
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
second[c][d] = in.nextInt();
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-' to subtract matrices
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.println();
}
}
}

14

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Output:

15

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to determine multiplication of two matrices.
Program:
import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.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] = in.nextInt();
System.out.println("Enter the number of rows and columns of second matrix");
p = in.nextInt();
q = in.nextInt();
if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied with each other.");
else
{
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] = in.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;
16

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


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

17

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to sort an array of strings
Program:
public class StringSortingTest {
public static void main(String args[])
{
String StringArray[]={"java","fore","cast","for","you"};
int n=StringArray.length;
String temp;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(StringArray[i].compareTo(StringArray[j])>0)
{
temp=StringArray[i];
StringArray[i]=StringArray[j];
StringArray[j]=temp;
}
}
}
for(int i=0;i<n;i++)
{
System.out.println(StringArray[i]);
}
}
}

18

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to check whether given string is palindrome or not.
Program:
import java.util.*;
class palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
Output:

19

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program for the following
- 1. Example for call by value.
Program:
class CallByValue {
public static void main ( String[] args ) {
int x =3;
System.out.println ( "Value of x before calling increment() is "+x);
increment(x);
System.out.println ( "Value of x after calling increment() is "+x);
}
public static void increment ( int a ) {
System.out.println ( "Value of a before incrementing is "+a);
a= a+1;
System.out.println ( "Value of a after incrementing is "+a);
}
}
Output:

20

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab

2-Example for call by reference.

Program:
class Number {
int x;
}
class CallByReference {
public static void main ( String[] args ) {
Number a = new Number();
a.x=3;
System.out.println("Value of a.x before calling increment() is "+a.x);
increment(a);
System.out.println("Value of a.x after calling increment() is "+a.x);
}
public static void increment(Number n) {
System.out.println("Value of n.x before incrementing x is "+n.x);
n.x=n.x+1;
System.out.println("Value of n.x after incrementing x is "+n.x);
}
}
Output:

21

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to demonstrate static variables, methods, and blocks.
Program:
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}

Output:

22

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to give the example for super keyword.
Program:
class Parentclass
{
void display(){
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass
{
void display(){
System.out.println("Child class method");
}
void printMsg(){
display();
super.display();
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printMsg();
}
}
Output:

23

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program that illustrates simple inheritance
Program:
import java.util.*;
import java.lang.*;
import java.io.*;
class Marks{
float age,S1,S2,S3,S4,S5;
String Name,Roll;
void displayMarks() {
Scanner input = new Scanner(System.in);
System.out.println("Enter your name:");
Name=input.nextLine();
System.out.println("Enter your Roll no:");
Roll=input.nextLine();
System.out.println("Enter the marks of first subject:");
S1=input.nextFloat();
System.out.println("Enter the marks of second subject:");
S2=input.nextFloat();
System.out.println("Enter the marks of third subject:");
S3=input.nextFloat();
System.out.println("Enter the marks of fourth subject:");
S4=input.nextFloat();
System.out.println("Enter the marks of fifth subject:");
S5=input.nextFloat();
}
}
class Result extends Marks{
void displayResults(){
float total,average;
total=(S1+S2+S3+S4+S5);
average=(total/5);
System.out.println("Roll no:"+Roll);
System.out.println("Name:"+Name);
System.out.println("Age:"+age);
System.out.println("The marks of the individual subjects are:subject1="+S1+ " ,subject2="+S2+ "
,subject3="+S3+ " ,subject4="+S4+ " ,subject5="+S5);
System.out.println("Total:"+total);
System.out.println("Average:"+average);
24

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


}
}
public class sininhe{
public static void main(String [] args){
Marks m=new Marks();
Result r=new Result();
m.displayMarks();
r.displayResults();
}
}
Output:

25

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab

Write a JAVA program that illustrates multi-level inheritance


Program:
class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{
public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
26

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


obj.brand();
obj.speed();
}
}
Output:

27

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab

Write a JAVA program demonstrating the difference between method


overloading and method overriding.
Method overloading
Program:
class Sum
{
int add(int n1, int n2)
{
return n1+n2;
}
int add(int n1, int n2, int n3)
{
return n1+n2+n3;
}
int add(int n1, int n2, int n3, int n4)
{
return n1+n2+n3+n4;
}
int add(int n1, int n2, int n3, int n4, int n5)
{
return n1+n2+n3+n4+n5;
}
public static void main(String args[])
{
Sum obj = new Sum();
System.out.println("Sum of two numbers: "+obj.add(20, 21));
System.out.println("Sum of three numbers: "+obj.add(20, 21, 22));
System.out.println("Sum of four numbers: "+obj.add(20, 21, 22, 23));
System.out.println("Sum of five numbers: "+obj.add(20, 21, 22, 23, 24));
}
}

28

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab

Output:

29

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Method overriding
class CarClass
{
public int speedLimit()
{
return 100;
}
}
class Ford extends CarClass
{
public int speedLimit()
{
return 150;
}
public static void main(String args[])
{
CarClass obj = new Ford();
int num= obj.speedLimit();
System.out.println("Speed Limit is: "+num);
}
}
Output:

30

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program demonstrating the difference between method
overloading and constructor
Method overloading
Program:
class Sum
{
int add(int n1, int n2)
{
return n1+n2;
}
int add(int n1, int n2, int n3)
{
return n1+n2+n3;
}
int add(int n1, int n2, int n3, int n4)
{
return n1+n2+n3+n4;
}
int add(int n1, int n2, int n3, int n4, int n5)
{
return n1+n2+n3+n4+n5;
}
public static void main(String args[])
{
Sum obj = new Sum();
System.out.println("Sum of two numbers: "+obj.add(20, 21));
System.out.println("Sum of three numbers: "+obj.add(20, 21, 22));
System.out.println("Sum of four numbers: "+obj.add(20, 21, 22, 23));
System.out.println("Sum of five numbers: "+obj.add(20, 21, 22, 23, 24));
}
}

31

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Output:

32

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Constructor overloading
Program:
public class MyOverloading {
public MyOverloading(){
System.out.println("Inside default constructor");
}
public MyOverloading(int i){
System.out.println("Inside single parameter constructor with int value");
}
public MyOverloading(String str){
System.out.println("Inside single parameter constructor with String object");
}
public MyOverloading(int i, int j){
System.out.println("Inside double parameter constructor");
}
public static void main(String a[]){
MyOverloading mco = new MyOverloading();
MyOverloading spmco = new MyOverloading(10);
MyOverloading dpmco = new MyOverloading(10,20);
MyOverloading dpmco1 = new MyOverloading("java2novice");
}
}
Output:

33

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program that describes exception handling mechanism.
Program:
import java.util.Scanner;
class Division {
public static void main(String[] args) {
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
result = a / b;
System.out.println("Result = " + result);
}
}
Output:

34

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program for example of try and catch block. In this check
whether the given array size is negative or not.
Program:
import java.util.*;
class StringAbc{
TreeSet ts;
StringAbc(){
ts=new TreeSet();
}
public void abc() {
Scanner sc=new Scanner(System.in);
int s1=0;
System.out.println("enter number of elemtns ");
//Read the size of array from user and check if it is not negative
s1=sc.nextInt();
if(s1<0) throw new NegativeArraySizeException("Array size cannot be negative.");
int i[]=new int[s1];
int s2 = 0;
for(int i2=0;i2<i.length;i2++) {
System.out.println("Enter element");
s2=sc.nextInt();
//get input from user and dont allow negtive numbers in the array
if(s2<0) throw new IllegalArgumentException("Negative numbers not allowed");
ts.add(s2);
}
System.out.println("first,,,,"+s2);
System.out.println("higest....."+ts.last());
}
public static void main(String[] args)
{
StringAbc s=new StringAbc(); s.abc();
}
}

35

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Output:

36

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program for creation of user defined exception
Program
class MyException extends Exception{
String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("Output String = "+str1) ;
}
}
class CustomException{
public static void main(String args[]){
try{
throw new MyException("Custom");
// I'm throwing user defined custom exception above
}
catch(MyException exp){
System.out.println("Hi this is my catch block") ;
System.out.println(exp) ;
}
}
}
Output:

37

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to illustrate creation of threads using runnable
class.(start method start each of the newly created thread. Inside the run
method there is sleep() for suspend the thread for 500 milliseconds).
Program:
class FirstThread implements Runnable
{
Thread t;
FirstThread(){
t=new Thread(this,"demo thread");
System.out.println("child thread:"+t);
t.start();
}
public void run()
{
for ( int i=1; i<=10; i++)
{
System.out.println( "Messag from:" +t+"is"+i);
try
{
Thread.sleep (500);
}
catch (InterruptedException interruptedException)
{
System.out.println( "First Thread is interrupted when it is sleeping" +interruptedException);
}
}
}
}
public class custthread
{
public static void main(String args[])
{
new FirstThread();
new FirstThread();
}
}

38

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Output:

39

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to create a class MyThread in this class a constructor,
call the base class constructor, using super and starts the thread. The run
method of the class starts after this. It can be observed that both main thread
and created child thread are executed concurrently
Program:
class FirstThread extends Thread
{
FirstThread(){
super("Demo Thread");
System.out.println("child thread:"+this);
start();
}
public void run()
{
for ( int i=1; i<=10; i++)
{
System.out.println( "Main thread:"+i);
try
{
Thread.sleep (500);
}
catch (InterruptedException interruptedException)
{
System.out.println( "First Thread is interrupted when it is sleeping" +interruptedException);
}
}
}
}
public class custthread
{
public static void main(String args[])
{
new FirstThread();
new FirstThread();
}
}

40

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Output:

41

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program illustrating multiple inheritance using interfaces.
Program:
import java.lang.*;
import java.io.*;
interface Exam
{
void percent_cal();
}
class Student
{
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2)
{
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
}
void display()
{
System.out.println ("Name of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2);
}
}
class Result extends Student implements Exam
{
Result(String n, int r, int m1, int m2)
{
super(n,r,m1,m2);
}
public void percent_cal()
{
int total=(mark1+mark2);
float percent=total*100/200;
System.out.println ("Percentage: "+percent+"%");
}
void display()
{
super.display();
}
}
class q10Multiple
{
public static void main(String args[])
42

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


{
Result R = new Result("Ra.one",12,93,84);
R.display();
R.percent_cal();
}
}
Output:

43

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to create a package named pl, and implement this
package in ex1 class.
Program:
package p1;
public class Arithematic
{
public Double add(Double a,Double b)
{
Double c=a+b;
return c;
}
}
import p1.*;
public class pack
{
public static void main(String args[])
{
Arithematic ob=new Arithematic();
System.out.println("addition:"+ob.add(20.0,30.0));
}
}
Output:

44

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to create a package named mypack and import it in
circle class.
Program:
package circle;
public class Circleari
{
public Double circum(Double r)
{
Double c=2.0*(22.0/7.0)*r;
return c;
}
public Double area(Double r)
{
Double c=(22.0/7.0)*r*r;
return c;
}
}
import circle.*;
public class pack
{
public static void main(String args[])
{
Circleari ob=new Circleari();
System.out.println("circumfrance:"+ob.circum(20.0));
System.out.println("circumfrance:"+ob.area(20.0));
}
}
Output:

45

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab

Write a JAVA program to give a simple example for abstract class.


Program:
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output:

46

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program that describes the life cycle of an applet
Write a JAVA program to create a dialogbox and menu.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="DialogDemo" width=250 height=250>
</applet>
*/
// Create a subclass of Dialog.
class SampleDialog extends Dialog implements ActionListener {
SampleDialog(Frame parent, String title) {
super(parent, title, false);
setLayout(new FlowLayout());
setSize(300, 200);
add(new Label("Press this button:"));
Button b;
add(b = new Button("Cancel"));
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
dispose();
}
public void paint(Graphics g) {
g.drawString("This is in the dialog box", 10, 70);
}
}
// Create a subclass of Frame.
class MenuFrame extends Frame {
String msg = "";
CheckboxMenuItem debug, test;
MenuFrame(String title) {
super(title);
// create menu bar and add it to frame
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
// create the menu items
Menu file = new Menu("File");
MenuItem item1, item2, item3, item4;
file.add(item1 = new MenuItem("New..."));
file.add(item2 = new MenuItem("Open..."));
file.add(item3 = new MenuItem("Close"));
file.add(new MenuItem("-"));
file.add(item4 = new MenuItem("Quit..."));
mbar.add(file);
47

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Menu edit = new Menu("Edit");
MenuItem item5, item6, item7;
edit.add(item5 = new MenuItem("Cut"));
edit.add(item6 = new MenuItem("Copy"));
edit.add(item7 = new MenuItem("Paste"));
edit.add(new MenuItem("-"));
Menu sub = new Menu("Special", true);
MenuItem item8, item9, item10;
sub.add(item8 = new MenuItem("First"));
sub.add(item9 = new MenuItem("Second"));
sub.add(item10 = new MenuItem("Third"));
edit.add(sub);
// these are checkable menu items
debug = new CheckboxMenuItem("Debug");
edit.add(debug);
test = new CheckboxMenuItem("Testing");
edit.add(test);
mbar.add(edit);
// create an object to handle action and item events
MyMenuHandler handler = new MyMenuHandler(this);
// register it to receive those events
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);
MyWindowAdapter adapter = new MyWindowAdapter(this);
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);
if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10, 240);
48

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


}
}
class MyWindowAdapter extends WindowAdapter {
MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
public void windowClosing(WindowEvent we) {
menuFrame.dispose();
}
}
class MyMenuHandler implements ActionListener, ItemListener {
MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
// Handle action events.
public void actionPerformed(ActionEvent ae) {
String msg = "You selected ";
String arg = ae.getActionCommand();
// Activate a dialog box when New is selected.
if(arg.equals("New...")) {
msg += "New.";
SampleDialog d = new
SampleDialog(menuFrame, "New Dialog Box");
d.setVisible(true);
}
// Try defining other dialog boxes for these options.
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
49

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}
public void itemStateChanged(ItemEvent ie) {
menuFrame.repaint();
}
}
// Create frame window.
public class DialogDemo extends Applet {
Frame f;
public void init() {
f = new MenuFrame("Menu Demo");
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
setSize(width, height);
f.setSize(width, height);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
}
Output:

50

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab

Write a JAVA program to create a grid layout control.


Program:
import java.awt.*;
import java.applet.*;
public class gridemo extends Applet
{
static final int n=4;
public void init(){
setLayout(new GridLayout(n,n));
setFont(new Font("SansSerif",Font.BOLD,24));
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));
}
}
}
}
}
/*<applet code="gridemo" height=300 width=300></applet>*/
Output:

51

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to create a border layout control.
Program:
import java.applet.*;
import java.awt.*;
public class BorderButtons extends Applet {
public void init() {
this.setLayout(new BorderLayout(20, 10));
this.add(new Button("North"), BorderLayout.NORTH);
this.add(new Button("South"), BorderLayout.SOUTH);
this.add(new Button("Center"), BorderLayout.CENTER);
this.add(new Button("East"), BorderLayout.EAST);
this.add(new Button("West"), BorderLayout.WEST);
}
}
/*<applet code="BorderButtons" height=300 width=300></applet>*/
Output:

52

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program to create a simple calculator.
Program:
import java.io.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class calc extends Applet implements ActionListener
{
TextField t;
Button bp,bm,bmul,bdiv,b[],beql;
Double sum,mus;
String s1;
int v;
int d,f;
public void init()
{
d=0;
f=0;
s1="";
sum=0.0;
mus=0.0;
v=0;
Panel p=new Panel();
Panel p1=new Panel();
setLayout(new BorderLayout());
p1.setLayout(new GridLayout(1,0));
p.setLayout(new GridLayout(3,5));
b=new Button[10];
t=new TextField(15);
Font font1 = new Font("SansSerif", Font.BOLD, 32);
t.setFont(font1);
//Dimension td=t.getPreferredSize();
//p1.setPreferredSize(new Dimension((int)td.getWidth(),(int)td.getHeight()));
p1.add(t);
add(p1,BorderLayout.NORTH);
for(int i=0;i<10;i++){
b[i]=new Button(""+i);
p.add(b[i]);
b[i].addActionListener(this);
}
bp=new Button("+");
bm=new Button("-");
bmul=new Button("*");
bdiv=new Button("/");
beql=new Button("=");
p.add(bp);
p.add(bm);
53

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


p.add(bmul);
p.add(bdiv);
p.add(beql);
t.setText("0");
bp.addActionListener(this);
bm.addActionListener(this);
bmul.addActionListener(this);
bdiv.addActionListener(this);
beql.addActionListener(this);
add(p,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae)
{
String s=ae.getActionCommand();
if(v==1)
{
t.setText("0");
v=0;
}
if(f==1 &&((s.equals("+"))||(s.equals("-"))||(s.equals("*"))||(s.equals("/"))))
{
f=0;
sum=mus;
}
else
f=0;
switch(s)
{
case "1":
t.setText(t.getText()+"1");
break;
case "2":
t.setText(t.getText()+"2");
break;
case "3":
t.setText(t.getText()+"3");
break;
case "4":
t.setText(t.getText()+"4");
break;
case "5":
t.setText(t.getText()+"5");
break;
case "6":
54

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


t.setText(t.getText()+"6");
break;
case "7":
t.setText(t.getText()+"7");
break;
case "8":
t.setText(t.getText()+"8");
break;
case "9":
t.setText(t.getText()+"9");
break;
case "0":
t.setText(t.getText()+"0");
break;
case "+":
sum+=Double.parseDouble(t.getText());
v=1;
s1="+";
t.setText(sum+"");
break;
case "-":
sum-=Double.parseDouble(t.getText());
v=1;
s1="-";
t.setText(sum+"");
break;
case "*":
s1="*";
if(sum==0)
sum=1.0;
sum*=Double.parseDouble(t.getText());
v=1;
t.setText(sum+"");
break;
case "/":
s1="/";
if(d==0){
sum=Double.parseDouble(t.getText());
d++;
break;
}
sum/=Double.parseDouble(t.getText());
55

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


v=1;
t.setText(sum+"");
break;
case "=":
switch(s1)
{
case "+":
sum=sum+Double.parseDouble(t.getText());
break;
case "-":
sum=sum-Double.parseDouble(t.getText());
break;
case "*":
sum=sum*Double.parseDouble(t.getText());
break;
case "/":
sum=sum/Double.parseDouble(t.getText());
break;
case "=":
sum=Double.parseDouble(t.getText());
break;
default:
sum=Double.parseDouble(t.getText());
}
s1="=";
mus=sum;
v=1;
f=1;
t.setText(sum+"");
sum=0.0;
break;
}
}
}
/*<applet code="calc" width=200 height=200></applet>*/
Output:

56

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program that displays the x and y position of the cursor
movement using Mouse
Program:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class mousepos extends Applet implements MouseMotionListener
{
int x,y;
public void init()
{
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent me)
{
x=me.getX();
y=me.getY();
repaint();
}
public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
repaint();
}
public void paint(Graphics g)
{
g.drawString("mouse coorcinates are:("+x+","+y+")",x,y);
}
}
/*<applet code="mousepos" height=300 width=300></applet>*/

57

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Output:

58

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Write a JAVA program that displays number of characters, lines and words in a
text file.
Program:
import java.util.*;
import java.io.*;
public class TextFileInfoPrinter
{
public static void main(String[]args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.println("File to be read: ");
String inputFile = console.next();
File file = new File(inputFile);
Scanner in = new Scanner(file);
int words = 0;
int lines = 0;
int chars = 0;
while(in.hasNextLine()) {
lines++;
String line = in.nextLine();
chars += line.length();
words += new StringTokenizer(line, " ,").countTokens();
}
System.out.println("Number of lines: " + lines);
System.out.println("Number of words: " + words);
System.out.println("Number of characters: " + chars);
}
}

59

| SRI PRAKASH COLLEGE OF ENGINEERING

Java Programming Lab


Output:

60

| SRI PRAKASH COLLEGE OF ENGINEERING

Você também pode gostar