0% found this document useful (0 votes)
134 views64 pages

Java Programs

The document contains 10 code snippets demonstrating various Java programming concepts like: 1. Adding two numbers 2. Swapping two numbers 3. Calculating tiffin items based on amount 4. Creating a Circle class with methods to calculate area and perimeter 5. Checking pass/fail status based on subject marks 6. Reading different data types from input 7. Calculating sum of digits of a number 8. Creating an Account class with deposit/withdrawal methods 9. Overloading a method to calculate area of circle and rectangle 10. Using varargs in a method

Uploaded by

cse D
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
134 views64 pages

Java Programs

The document contains 10 code snippets demonstrating various Java programming concepts like: 1. Adding two numbers 2. Swapping two numbers 3. Calculating tiffin items based on amount 4. Creating a Circle class with methods to calculate area and perimeter 5. Checking pass/fail status based on subject marks 6. Reading different data types from input 7. Calculating sum of digits of a number 8. Creating an Account class with deposit/withdrawal methods 9. Overloading a method to calculate area of circle and rectangle 10. Using varargs in a method

Uploaded by

cse D
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 64

1.

/*Write a java program to print Addition of two numbers

Sample I/O

Enter two values

23

Addition of 2 and 3 is 5

*/

import java.util.Scanner;

class Addition

public static void main(String args[])

int a,b,c;

Scanner sc=new Scanner(System.in);

System.out.println("Enter two values");

a=sc.nextInt();

b=sc.nextInt();

c=a+b;

System.out.println("Addition of "+a+" and "+b+" is "+c);

2./*Write a java program to SWAP two numbers.

Sample I/O:

Enter the first number:

65

Enter the second number:

23

After Swap:

23

65

*/
//write code here

import java.util.Scanner;

class SwapTest{

public static void main(String[]args){

Swap s1=new Swap();

s1.input();

s1.process();

s1.output();

class Swap

int a,b,temp;

void input()

Scanner sc=new Scanner(System.in);

System.out.println("Enter first number:");

a=sc.nextInt();

System.out.println("Enter second number:");

b=sc.nextInt();

void process()

temp=a;

a=b;

b=temp;

void output()
{

System.out.println("After Swap:\n"+a+"\n"+b);

3. /* Program to read amount in rupees. If amount is >=300 print idly, vada, dosa and puri followed by glass of water.

printing of glass of water is mandatory.

sample I/O

sample 1

output:

Enter the amount:

400

Idly

Vada

Dosa

Puri

glass of water

sample 2

Enter the amount:

30

glass of water

*/

//write code here

import java.util.Scanner;

class Tiffin

int amt;

void process()
{

if(amt>=300)

System.out.println("Idly");

System.out.println("Vada");

System.out.println("Dosa");

System.out.println("Puri");

System.out.println("glass of water");

/*DO NOT CHANGE MAIN CLASS*/

class TiffinTest{

public static void main(String args[]){

Tiffin t=new Tiffin();

Scanner s=new Scanner(System.in);

System.out.println("Enter the amount:");

t.amt=s.nextInt();

t.process();

4. /*Java program to create class Circle with

methods to calculate area and perimeter of circle.

Note: use Math.PI

Sample I/O

Enter the radius:

15.50

Area of circle:754.7676350249478

Perimeter of circle:97.38937226128358
*/

//import appropriate package

//declare fields required

//funtction to calculate area

//returns double value - will return calculated area

//funtction to calculate perimeter

//returns double value - will return calculated perimeter

import java.util.Scanner;

//create a class

class Circle{

double r;

double getArea()

return(Math.PI*r*r);

double getPerimeter()

return(Math.PI*2*r);

public static void main(String[]args){

Circle c=new Circle();

//create object of Scanner class

Scanner s=new Scanner(System.in);

System.out.println("Enter the radius: ");

c.r=s.nextDouble();

System.out.println("Area of circle:" + c.getArea());

System.out.println("Perimeter of circle:" + c.getPerimeter());


}

};

5. /*Write a java program to read three subject marks and display pass or fail.

criteria: if all subjects marks >= 40 then pass

other wise fail.

Sample I/O:

case 1:

Enter first subject marks:

60

Enter second subject marks:

20

Enter third subject marks:

50

Fail

case 2:

Enter first subject marks:

70

Enter second subject marks:

802

Enter third subject marks:

90

Pass

*/

//WRITE CODE HERE

/*DO NOT CHANGE MAIN CLASS*/


import java.util.Scanner;

class Result

private int p,q,r;

public Result(int a,int b,int c)

p=a;

q=b;

r=c;

void process()

if(p>=40 && q>=40 && r>=40)

System.out.println("Pass");

else

System.out.println("Fail");

class ResultTest{

public static void main(String[]args){

int m1,m2,m3;

Scanner s=new Scanner(System.in);

System.out.println("Enter first subject marks:");

m1=s.nextInt();

System.out.println("Enter second subject marks:");

m2=s.nextInt();

System.out.println("Enter third subject marks:");

m3=s.nextInt();

Result r1=new Result(m1,m2,m3);

r1.process();
}

6. /*you must read an integer, a double, and a String from stdin,

then print the values according to the instructions

in the Output Format section below.

Sample Input

42

3.1415

true

Sample Output

Boolean: true

Double: 3.1415

Byte: 42

Sample I/O-2:

128

Exception in thread "main" java.util.InputMismatchException: Value out of range.

Value:"128" Radix:10

at java.util.Scanner.nextByte(Unknown Source)

at java.util.Scanner.nextByte(Unknown Source)

at Demo.main(Demo.java:23)

*/

import java.util.Scanner;

class DataType

public static void main(String []args)

byte a;

double b;
boolean c;

Scanner sc=new Scanner(System.in);

a=sc.nextByte();

b=sc.nextDouble();

c=sc.nextBoolean();

System.out.println("Boolean:"+" "+c);

System.out.println("Double:"+" "+b);

System.out.println("Byte:"+" "+a);

7. /*program to find the sum of the individual digits of the given number.

if input is 123, then output should be 6

Sample I/O:

Enter the positive integer number to find sum of digits:

1234

Sum of digits: 10

*/

//WRITE CODE HERE

import java.util.Scanner;

class Demo{

public static void main(String args[]){

SumOfDigits s=new SumOfDigits();

s.input();

s.process();

s.output();

class SumOfDigits

public int n,p,m,sum=0;

void input()
{

System.out.println("Enter the positive integer number to find sum of digits:");

Scanner c=new Scanner(System.in);

n=c.nextInt();

void process()

while(n>=1)

m=n%10;

sum=sum+m;

n=n/10;

void output()

System.out.println("Sum of digits: "+sum);

8. /*Implement a class Account. An account has

the properties customer name,account number & balance and a methods to deposit,

withdraw and inquire the current balance.

Pass values into a constructor to set.

If no value is passed the initial balance should be set to 0.

Charge a 5 penalty if an attempt is made to withdraw more money than available in the account.

Sample Output:

CASE 1(with penalty):

Current Balance: 2000.0

Enter the amount to withdraw

3000

Current Balance after withdraw: 1995.0


Enter the amount to deposit

1000

Current Balance after deposit: 2995.0

CASE 2(without penalty):

Current Balance: 2000.0

Enter the amount to withdraw

1000

Current Balance after withdraw: 1000.0

Enter the amount to deposit

2000

Current Balance after deposit: 3000.0

*/

//WRITE CODE HERE

/*DO NOT CHANGE MAIN CLASS*/

import java.util.Scanner;

class Account

String name;

long num;

double balance;

Scanner sc=new Scanner(System.in);

public Account(String name,long num,double balance)

this.name=name;

this.num=num;

this.balance=balance;

}
public void withdraw(double z)

System.out.println("Enter the amount to withdraw");

z=sc.nextDouble();

if(z>balance)

balance=balance-5;

else

balance=balance-z;

public void deposit(double z)

System.out.println("Enter the amount to deposit");

z=sc.nextDouble();

balance=balance+z;

public double getBalance()

return(balance);

class TestAccount

public static void main(String a[])

double x;

Account b=new Account("Anil",12345L,2000.0);

System.out.println("Current Balance: "+b.getBalance());

b.withdraw(2500);

System.out.println("Current Balance after withdraw: "+b.getBalance());

b.deposit(500);

System.out.println("Current Balance after deposit: "+b.getBalance());

9. /*program to overload find() method to calculate area of circle and rectangle


Sample I/O:

Enter the radius of circle:

Area of Circle: 12.56

Enter the length and breadth of rectangle:

56

Area of Rectangle: 30.0

*/

//write code here

import java.util.Scanner;

class Area

public double find(int a)

return(3.14*a*a);

public double find(int a,int b)

return(a*b);

class Overloading

public static void main(String args[])

int a,b,c;

Scanner s= new Scanner(System.in);

Area a1=new Area();

System.out.println("Enter the radius of circle:");


a=s.nextInt();

System.out.println("Area of Circle: "+a1.find(a));

System.out.println("Enter the length and breadth of rectangle:");

a=s.nextInt();

b=s.nextInt();

System.out.println("Area of Rectangle: "+a1.find(a,b));

10.Varargs Programs

import java.util.Scanner;

class Area

public double find(int a)

return(3.14*a*a);

public double find(int ...a)

return(a[0]*a[1]);

class Overloading

public static void main(String args[])

int a,b,c;

Scanner s= new Scanner(System.in);

Area a1=new Area();

System.out.println("Enter the radius of circle:");

a=s.nextInt();

System.out.println("Area of Circle: "+a1.find(a));

System.out.println("Enter the length and breadth of rectangle:");


a=s.nextInt();

b=s.nextInt();

System.out.println("Area of Rectangle: "+a1.find(a,b));

11. /*Write a Java program that prints the numbers from 1 to 50. But for multiples of three print "Fizz" instead of

the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and

five print "FizzBuzz"

SAMPLE OUTPUT:

Fizz

Buzz

Fizz

Fizz

Buzz

11

Fizz

13

14

FizzBuzz

*/

class FizzBuzzTest

public static void main(String args[])

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

if( (i%3)==0 && (i%5)==0)


{

System.out.println("FizzBuzz");

else if( (i%5)==0)

System.out.println("Buzz");

else if( (i%3)==0)

System.out.println("Fizz");

else

System.out.println(i);

12. /* Write a Java Program To Calculate Sum Of First And Last Digit Of A Number

*/

import java.util.Scanner;

class Sum

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter the number:");

int n=sc.nextInt();

int last=n%10;

int first=0;

while(n>=1)

{
first=n;

n=n/10;

System.out.println("Sum of first and last digits: "+(first+last));

13. /* Write a Java Program To Calculate Perfect Squares Between Two Numbers

Sample I/O:

enter the first number

Enter the second number

perfect squares between 2 and 6 are:

*/

import java.util.*;

class Squares

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

int a,b;

System.out.println("enter the first number");

a=sc.nextInt();

System.out.println("enter the second number");

b=sc.nextInt();

System.out.println("perfect squares between "+a+" and "+b+" are:");

for(int i=a;i<=b;i++)

if(i%Math.sqrt(i)==0)

System.out.println(i);
}

14. /*Java Program To Find All Pairs Of Elements In An Array Whose Sum Is Equal To A Given Number :

Sample Output :

Pairs of elements whose sum is 10 are :

4 + 6 = 10

5 + 5 = 10

-10 + 20 = 10

Pairs of elements whose sum is 50 are :

12 + 38 = 50

23 + 27 = 50

125 + -75 = 50

*/

public class PairsOfElementsInArray

static void findThePairs(int inputArray[],int inputNumber)// start writing the code here

System.out.println("Pairs of elements whose sum is "+inputNumber+" are: ");

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

for(int j=i+1;j<inputArray.length;j++)

if(inputArray[i]+inputArray[j]==inputNumber)

System.out.println(inputArray[i]+" + "+inputArray[j]+" = "+inputNumber);

}
public static void main(String[] args)

findThePairs(new int[] {4, 6, 5, -10, 8, 5, 20}, 10);

findThePairs(new int[] {12, 23, 125, 41, -75, 38, 27, 11}, 50);

15. /*

Write a java program to find the no. of times each charecter repeated in a given String.

Sample Input/Output:

Example 1:

Enter the String

java

The Character j has occurred 1 times

The Character a has occurred 2 times

The Character v has occurred 1 times

Example 2:

Enter the String

hello

The Character h has occurred 1 times

The Character e has occurred 1 times

The Character l has occurred 2 times

The Character o has occurred 1 times

*/

import java.util.*;// start wrinting your code here.

class RepetitionsInString

public static void main(String args[])

String a,temp="";

int i,j,cnt=0;

System.out.println("Enter the String");


Scanner s=new Scanner(System.in);

a=s.nextLine();

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

char c=a.charAt(i);

for(j=i;j<a.length();j++)

char c2=a.charAt(j);

if(c==c2 && temp.indexOf(c)==-1)

cnt++;

if(temp.indexOf(c)==-1)

temp+=c;

System.out.println("The Character "+c+" has occurred "+cnt+" times");

cnt=0;

16. /*Write a java program to count the number of words in a string?

HINT: YOU CAN USE split() FROM String class.

Sample Output:

Enter the string

Hello! How are you?

Number of words in the string = 4

*/

// write code from here

import java.util.*;

class CountTheWords

{
public static void main(String[] args)

String a;

int n;

Scanner s=new Scanner(System.in);

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

a=s.nextLine();

String[] ar=a.split(" ");

n=ar.length;

System.out.println("Number of words in the string = "+n);

17. /* Write a Java Program To Calculate Sum Of First And Last Digit Of A Number

SAMPLE INPUT/OUTPUT:

enter the number

456

sum of first and last digits: 10

*/

import java.util.Scanner;

class Sum

public static void main(String[] args)

int num;

Scanner sc=new Scanner(System.in);

System.out.println("enter the number");

num=sc.nextInt();

int last=num%10;

int first=0;

while(num>=1)

first=num;

num=num/10;
}

System.out.println("sum of first and last digits: "+(first+last));

18. /*Implement a class Address. An address has

a house number,

a street,

an optional apartment number,

a city,

a state and a

postal code.

Supply two constructors:

one with an apartment number

and one without.

Supply a print function that prints the address with the street on one line and the city,

state, and postal code on the next line.

Sample output:

Street: Narayanguda

City: HydState: TelenganaPostal Code: 500021

*/

import java.util.*;

class Address

int hno,oan;

String str;

String city;

String state;

int pc;

Address()

}
Address(int oan)

System.out.println("apartment number: "+oan);

void print(String str,String city,String state,int pc)

str="Narayanguda";

city="Hyd";

state="Telengana";

pc=500021;

System.out.println("Street: "+str);

System.out.println("City: "+city+"State: "+state+"Postal Code: "+pc);

class Test

public static void main(String[] args)

Address add=new Address();

add.print("Narayanguda","Hyd","Telengana",500021);

19. /*Write a Java Program to define a class,define instance methods for setting and Retrieving values of

instance variables and instantiate itsobject.

SAMPLE OUTPUT:

Employee details are:

Name:smith

ID:1234

Address:narayanguda

*/
import java.util.*;

class empdemo

public static void main(String arg[])

Employee e=new Employee();

Scanner sc=new Scanner(System.in);

e.setData("smith",1234,"narayanguda");

e.putData();

class Employee

void setData(String n,int num,String add)

n="smith";

num=1234;

add="narayanguda";

System.out.println("Employee details are:");

void putData()

String nam="smith";

int nu=1234;

String addre="narayanguda";

System.out.println("Name:"+nam);

System.out.println("ID:"+nu);

System.out.println("Address:"+addre);

20. /*Write a Java Program to define a class,

define instance methods and overload them


SAMPLE OUTPUT:

The sum of 10 & 20 is 30

The sum of 10.2 & 20.2 is 30.4

*/

import java.util.*;

class add_demo

public static void main(String arg[])

Scanner sc=new Scanner(System.in);

Sum obj=new Sum();

obj.display(10,20);

obj.display2(10.2,20.2);

class Sum

void display(int i,int j)

i=10;

j=20;

int add=i+j;

System.out.println("The sum of "+i+" & "+j+" is "+add);

void display2(double y,double z)

y=10.2;

z=20.2;

double add=y+z;

System.out.println("The sum of "+y+" & "+z+" is "+add);

}
21. /*Program to read person's age and display eligible to vote or not.

SAMPLE I/O:

CASE 1:

Enter your age:

23

You are eligible to vote

CASE 2:

Enter your age:

16

You are not eligible to vote

*/

//WRITE YOUR CODE HERE

import java.util.Scanner;

class VoteTest{

public static void main(String args[]){

int age;

Scanner s=new Scanner(System.in);

System.out.println("Enter your age:");

age=s.nextInt();

Vote v=new Vote(age);

v.process();

class Vote

int a;

Vote(int i)

a=i;

}
void process()

if(a>=18)

System.out.println("You are eligible to vote");

else

System.out.println("You are not eligible to vote");

22. /*program to create super class as Student with id,

name and three subject marks m1,m2,m3.

create a sub class Result with total and average and result.

create an executable class and instantiate an object for sub class,

invoke respective methods to input the data,

process the data and display the same.

Sample I/O:

Case 1:

Enter id:

Enter name:

abc

Enter subject1 marks:

40

Enter subject2 marks:

50

Enter subject3 marks:

60

Student id:1

Name :abc

Subject1 :40
Subject2 :50

Subject3 :60

Total is :150

Average is:50.0

result is :Second Division

CASE 2:

Student id:2

Name :xyz

Subject1 :70

Subject2 :0

Subject3 :90

Total is :160

Average is:53.0

result is :Fail

CASE 3:

Student id:3

Name :mno

Subject1 :88

Subject2 :99

Subject3 :100

Total is :287

Average is:95.0

result is :Distinction

CASE 4:

Student id:4

Name :pqr

Subject1 :66

Subject2 :59
Subject3 :70

Total is :195

Average is:65.0

result is :First Division

*/

import java.util.*;

class StudentInheritanceTest

public static void main(String args[])

int id,m1,m2,m3;

String name;

Scanner s=new Scanner(System.in);

System.out.println("Enter id:");

id=s.nextInt();

System.out.println("Enter name:");

name=s.next();

System.out.println("Enter subject1 marks:");

m1=s.nextInt();

System.out.println("Enter subject2 marks:");

m2=s.nextInt();

System.out.println("Enter subject3 marks:");

m3=s.nextInt();

Result r=new Result(id,name,m1,m2,m3);

r.process();

r.output();

// write the code here

class Student

int id;

String name;
int m1,m2,m3;

Student(int id,String name,int m1,int m2,int m3)

this.id=id;

this.name=name;

this.m1=m1;

this.m2=m2;

this.m3=m3;

void output()

System.out.println("Student id:"+id);

System.out.println("Name :"+name);

System.out.println("Subject1 :"+m1);

System.out.println("Subject2 :"+m2);

System.out.println("Subject3 :"+m3);

class Result extends Student

int total;

double avg;

String result;

Result(int id,String name,int m1,int m2,int m3)

super(id,name,m1,m2,m3);

void process()

total=m1+m2+m3;

avg=total/3;

if(m1>=40 && m2>=40 && m3>=40)

if(avg>=70)

result="Distinction";
else if(avg>=60 && avg<70)

result="First Division";

else if(avg>=50 && avg<60)

result="Second Division";

else if(avg>=40 && avg<50)

result="Third Division";

else

result="Fail";

void output()

super.output();

System.out.println("Total is :"+total);

System.out.println("Average is:"+avg);

System.out.println("result is :"+result);

23. /*Write a Java Program to create an abstract class named Shapes

that contains an empty method named printArea.

Provide three classes named Rectangle,Triangle and Circle subclass

that each one of the classes extends the Class Shapes.

Each one of the classes contains only the method printArea()

that prints the area of Shape.

Sample I/O:

Area of Rectangle is 200

Area of Triangle is 100.0

Area of Circle is 314.0

*/

//write code here


class Week8

public static void main(String[] args) {

Shapes s[];

s=new Shapes[10];

s[0]=new Rectangle();

s[1]=new Triangle();

s[2]=new Circle();

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

s[i].printArea(10,20);}

abstract class Shapes

int a,b;

abstract public void printArea(int a,int b);

class Rectangle extends Shapes

public void printArea(int a,int b)

System.out.println("Area of Rectangle is "+(a*b));

class Circle extends Shapes

public void printArea(int a,int b)

double c=3.14;

System.out.println("Area of Circle is "+(c*a*a));

}
class Triangle extends Shapes

public void printArea(int a,int b)

System.out.println("Area of Triangle is "+(0.5)*(a*b));

24. /* You are given a class Test with a main method to demonstrate static modifier.

Complete the given code so that it outputs as below:

Sample I/O:

Number of student in the beginning: 0

Number of students (Using class name): 2

Number of students (Using first object): 2

Number of students (Using second object): 2

Number of students (Using static method): 2

*/

//write code here

public class Test {

public static void main(String args[]) {

System.out.println("Number of student in the beginning: " + Student.getNumberOfStudents() );

Student student1 = new Student("Arun", 19, 2010001L);

Student student2 = new Student("Deepak", 16, 2010002L);

System.out.println("Number of students (Using class name): " + Student.getNumberOfStudents() );

System.out.println("Number of students (Using first object): " + Student.getNumberOfStudents() );

System.out.println("Number of students (Using second object): " + Student.getNumberOfStudents() );

System.out.println("Number of students (Using static method): "+Student.getNumberOfStudents ());

}
}

class Student

public static int cnt;

static

cnt=0;

String na;

long b,l;

Student(String a,int b,long l)

na=a;

this.b=b;

this.l=l;

cnt++;

static int getNumberOfStudents()

return cnt;

25. /*Q2) Read the content of the file ex2.txt, count and display number of characters,

words and lines present in the File.

(Contents of the file ex2.txt is :

shiva rama krishna

younus shariff

tejaswitha)

Sample I/O:

Number of characters in the file:46


Number of words in the file:6

Number of lines in the file:3

*/

import java.io.*;

class CountCWL

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

FileInputStream fp=new FileInputStream("ex2.txt");

int i=0,cnt1=0,cnt2=0,cnt=0;

while(true)

i=fp.read();

if(i==-1)

break;

if((char)i==' ' || (char)i=='\n')

cnt1++;

if((char)i=='\n')

cnt2++;

cnt++;

System.out.println("Number of characters in the file:"+cnt);

System.out.println("Number of words in the file:"+(cnt1+1));

System.out.println("Number of lines in the file:"+(cnt2+1));

26. /*(Q)Copy the content of the file ex1.txt to abc.txt a byte at a time.

Display the content of abc.txt file.


contents of the file ex1.txt is:

shivaram

Sample Output:

The content of abc.txt file is:

shivaram

*/

import java.io.*;

class FileCopy1

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

int ch;

// write the code for copying the content of ex1.txt to abc.txt

FileInputStream fis1=new FileInputStream("ex1.txt");

FileOutputStream fos=new FileOutputStream("abc.txt");

while(true)

ch=fis1.read();

if(ch==-1)

break;

fos.write((char)ch);

// code for displaying the content of abc.txt file. is already given below

FileInputStream fis2=new FileInputStream("abc.txt");

System.out.println("The content of abc.txt file is:");

//Read characters from fis2 into ch and write onto the monitor,repeat this till end of the file is reached

while(true)

ch=fis2.read();

if(ch==-1)
break;

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

fis2.close();

27. /*(Q) Write the numbers 11,22,33,44,55 on to the file 'file6.dat'.

Read all the numbers from file6.dat and write all even numbers into the file 'even.dat',

odd numbers into the file 'odd.dat'.

Display the contents of the file 'odd.dat'.

SAMPLE OUTPUT:

Numbers 11,22,33,44,55 written to the file.

the odd numbers from odd.dat file:

11 33 55

*/

import java.io.*;

import java.util.*;

class FileRW

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

int i,x;

// Writing the numbers 11,22,33,44,55 on to the file 'file6.dat' is given below

Scanner s=new Scanner(System.in);

FileOutputStream fos=new FileOutputStream("file6.dat");

DataOutputStream dos=new DataOutputStream(fos);


dos.writeInt(11);

dos.writeInt(22);

dos.writeInt(33);

dos.writeInt(44);

dos.writeInt(55);

dos.close();

System.out.println("Numbers 11,22,33,44,55 written to the file.");

// strat writing the code here

FileInputStream fis=new FileInputStream("file6.dat");

DataInputStream dis=new DataInputStream(fis);

FileOutputStream fos1=new FileOutputStream("even.dat");

DataOutputStream dos1=new DataOutputStream(fos1);

FileOutputStream fos2=new FileOutputStream("odd.dat");

DataOutputStream dos2=new DataOutputStream(fos2);

while(dis.available()>0)

x=dis.readInt();

if(x%2==0)

dos1.writeInt(x);

else

dos2.writeInt(x);

dis.close();

dos1.close();

dos2.close();

// Code For Displaying the contents of the file 'odd.dat' is givenm below.

System.out.println("the odd numbers from odd.dat file:");

FileInputStream fis2=new FileInputStream("odd.dat");


DataInputStream dis2=new DataInputStream(fis2);

while(dis2.available()>0)

x=dis2.readInt();

System.out.print(x+" ");

dis2.close();

}//end of main method

28. /*

(Q)create a class Student is with 2 fields rno(String), name(String).

Write the details of three students on to the file 'student1.dat'.

Display the name of the student for the given roll number.

SAMPLE OUTPUT:

CASE 1:

enter the student roll number:

15BD1A0503

STUDENT NAME=kiran

CASE 2:

enter the student roll number:

15BD1A0508

No such student found

*/

import java.io.*;

import java.util.*;

// creation of class Student


class Student implements Serializable

String rno;

String name;

Student(String rno,String name)

this.rno=rno;

this.name=name;

public String toString()

return "ROLL NO="+rno+" NAME="+name;

class ObjectIO

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

// Writing the details of three students on to the file 'student1.dat' is given below

FileOutputStream fos=new FileOutputStream("student.dat");

ObjectOutputStream oos=new ObjectOutputStream(fos);

Student s1=new Student("15BD1A0501","shiva");

oos.writeObject(s1);

Student s2=new Student("15BD1A0502","Younus");

oos.writeObject(s2);

Student s3=new Student("15BD1A0503","kiran");

oos.writeObject(s3);

oos.close();

// write the code for Displaying the name of the student for the given roll number.

String r;
System.out.println("enter the student roll number:");

Scanner s=new Scanner(System.in);

r=s.next();

if(r.equals(s1.rno))

System.out.println("STUDENT NAME="+s1.name);

else if(r.equals(s2.rno))

System.out.println("STUDENT NAME="+s2.name);

else if(r.equals(s3.rno))

System.out.println("STUDENT NAME="+s3.name);

else

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

29. /*create a thread that prints the multiplication table for number 5

Sample output:

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

*/

//write your code here

class FifthTable extends Thread

int f=5;
public void run()

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

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

class MyThread1

public static void main(String args[])

FifthTable f=new FifthTable();

f.start();

30. /*Write a program that displays 5th and 6th mathematical tables.

child thread should display multiplication table of 5 and

main thread should diplay multiplication table of 6.

main thread should display table 6 only

after the child completes displayig table 5.

SAMPLE I/O:

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

6 *1 = 6

6 *2 = 12

6 *3 = 18

6 *4 = 24

6 *5 = 30

6 *6 = 36

6 *7 = 42

6 *8 = 48

6 *9 = 54

6 *10 = 60

*/

class FifthTable extends Thread

public void run()

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

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

class MultipleTables2

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

FifthTable f=new FifthTable();

f.start();

f.join();

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

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


}

31. /*

Write a Java program that implements a multi-thread application that has three threads.

First thread reads an integer value from keyboard and

if the value is even,second thread computes the square of the number and prints.

If the value is odd, the third thread will print the value of cube of the number.

input/output:

--------------

case 1:

Enter x value :

X=4 SQUARE=16

case 2:

Enter x value :

X=5 CUBE=125

*/

import java.util.*;

class Thread2 extends Thread

int x;

Thread2(int a)
{

x=a;

public void run()

System.out.println("X="+x+" SQUARE="+(x*x));

class Thread3 extends Thread

int x;

Thread3(int a)

x=a;

public void run()

System.out.println("X="+x+" CUBE="+(x*x*x));

class Thread1

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter x value :");

int x=sc.nextInt();

if(x%2==0)

Thread2 t2=new Thread2(x);

t2.start();

else
{

Thread3 t3=new Thread3(x);

t3.start();

32. /**

* This program is used to show the inter thread communication.

Producer is waiting...

Product3 is consumed.

Consumer is waiting...

Product4 is produced.

Producer is waiting...

Product4 is consumed.

Consumer is waiting...

Product5 is produced.

Producer is waiting...

Product5 is consumed.

Consumer is waiting...

Product6 is produced.

Producer is waiting...

Product6 is consumed.

Consumer is waiting...

Product7 is produced.

Producer is waiting...

Product7 is consumed.

Consumer is waiting...

Product8 is produced.

Producer is waiting...

Product8 is consumed.
Consumer is waiting...

Product9 is produced.

Producer is waiting...

Product9 is consumed.

Consumer is waiting...

Product10 is produced.

Product10 is consumed.

*/

class Buffer

int a;

boolean produced = false;

public synchronized void produce(int x)

if(produced)

System.out.println("Producer is waiting...");

try{

wait();

}catch(Exception e){

System.out.println(e);

a=x;

System.out.println("Product" + a + " is produced.");

produced = true;

notify();

public synchronized void consume()

if(!produced)

{
System.out.println("Consumer is waiting...");

try

wait();

catch(Exception e){}

System.out.println("Product" + a + " is consumed.");

produced=false;

notify();

class Producer extends Thread

Buffer b;

public Producer(Buffer b)

this.b = b;

public void run()

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

b.produce(i);

class Consumer extends Thread

Buffer b;

Consumer(Buffer b)

this.b=b;

public void run()


{

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

b.consume();

public class demo12

public static void main(String args[])

//Create Buffer object.

Buffer b = new Buffer();

//creating producer thread.

Producer p = new Producer(b);

//creating consumer thread.

Consumer c = new Consumer(b);

//starting threads.

p.start();

c.start();

33. import javax.swing.JFrame;

class Test

public static void main(String args[])

JFrame f=new JFrame();

f.setVisible(true);

//f.setSize(400,700);

//f.setLocation(100,100);

f.setBounds(500,100,300,400);

f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//DO_NOTHING,EXIT,HIDE
f.setTitle("KMIT");

34. import javax.swing.JFrame;

import java.awt.Container;

import java.awt.Color;

import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.ImageIcon;

class Test extends JFrame

public Test()

setVisible(true);

//setSize(400,700);

//setLocation(100,100);

setBounds(500,100,800,400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setTitle("KMIT");

//setResizable(false);

Container c=getContentPane();

c.setBackground(Color.yellow);

ImageIcon icm=new ImageIcon("img1(2).jpg");

JLabel l=new JLabel("Welcome To Kmit",icm,JLabel.LEFT);

add(l);

setLayout(null);

l.setBounds(100,100,400,300);

l.setForeground(Color.blue);

Font f=new Font("Arial",Font.BOLD,20);

l.setFont(f);

l.setToolTipText("This is label");

}
public static void main(String args[])

new Test();

35. import javax.swing.JFrame;

import javax.swing.JPasswordField;

import javax.swing.JButton;

class Test

public static void main(String arg[])

JFrame f=new JFrame();

f.setSize(300,150);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setLayout(null);

JPasswordField t1=new JPasswordField(10);

t1.setBounds(20,20,120,30);

f.add(t1);

JButton b1=new JButton("CLICK");

b1.setBounds(75,60,80,50);

f.add(b1);

f.setVisible(true);

36. import javax.swing.JFrame;

import javax.swing.JTextField;

import javax.swing.JPasswordField;
import javax.swing.JButton;

import javax.swing.JLabel;

class Test

public static void main(String arg[])

JFrame f=new JFrame();

f.setBounds(500,100,800,400);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setTitle("Demo application");

f.setLayout(null);

JLabel l1=new JLabel("User");

JLabel l2=new JLabel("Password");

l1.setBounds(10,10,80,25);

l2.setBounds(10,30,80,25);

f.add(l1);

f.add(l2);

JTextField t1=new JTextField();

JTextField t2=new JTextField();

t1.setBounds(100,10,160,25);

t2.setBounds(100,10,160,25);

f.add(t1);

f.add(t2);

JPasswordField p1=new JPasswordField();

JPasswordField p2=new JPasswordField();

p1.setBounds(100,40,160,25);

p2.setBounds(100,40,160,25);

f.add(p1);

f.add(p2);

JButton b1=new JButton("login");

JButton b2=new JButton("register");

b1.setBounds(10,80,80,25);

b2.setBounds(180,80,150,25);
f.add(b1);

f.add(b2);

f.setVisible(true);

37. import javax.swing.JFrame;

import javax.swing.JTextField;

import javax.swing.JButton;

import javax.swing.JLabel;

import java.awt.FlowLayout;

class Test

public static void main(String arg[])

JFrame f=new JFrame();

f.setSize(500,150);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setLayout(new FlowLayout());

JLabel l=new JLabel("Find What: ");

JTextField t=new JTextField(20);

JButton b=new JButton("Find");

f.add(l);

f.add(t);

f.add(b);

f.setVisible(true);

38. import javax.swing.JFrame;

import javax.swing.JButton;

import java.awt.FlowLayout;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;

class Test extends JFrame implements ActionListener

Test()

setSize(300,150);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new FlowLayout());

JButton b=new JButton("Clickme");

add(b);

b.addActionListener(this);//registration of the event*

setVisible(true);

@Override

public void actionPerformed(ActionEvent e)

JOptionPane.showMessageDialog(null,"Welcome to eventhandling");//static method

public static void main(String arg[])

new Test();

39. import javax.swing.JFrame;

import javax.swing.JButton;

import java.awt.FlowLayout;

import java.awt.Color;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import javax.swing.JOptionPane;

class Test extends JFrame implements ActionListener

Test()

{
setSize(300,150);

setTitle("Event");

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new FlowLayout());

JButton b1=new JButton("Yellow");

JButton b2=new JButton("Blue");

JButton b3=new JButton("Red");

add(b1);

add(b2);

add(b3);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

setVisible(true);

@Override

public void actionPerformed(ActionEvent e)

setBackground(Color.yellow);

public static void main(String arg[])

new Test();

40. import javax.swing.JFrame;

import javax.swing.JButton;

import javax.swing.JTextField;

import javax.swing.JLabel;

import java.awt.FlowLayout;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import javax.swing.JOptionPane;

class Test extends JFrame implements ActionListener


{

JLabel l1,l2,l3;

JTextField t1,t2,t3;

JButton b;

Test()

setSize(500,150);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new FlowLayout(FlowLayout.LEFT));

l1=new JLabel("Enter first no.");

l2=new JLabel("Enter second no.");

l3=new JLabel("Result");

t1=new JTextField(8);

t2=new JTextField(8);

t3=new JTextField(8);

b=new JButton("Divide");

add(l1);

add(t1);

add(l2);

add(t2);

add(l3);

add(t3);

add(b);

b.addActionListener(this);

setVisible(true);

@Override

public void actionPerformed(ActionEvent e)

try

int a=Integer.parseInt(t1.getText());

int b=Integer.parseInt(t2.getText());

float c=a/b;
t3.setText(""+c);

catch(ArithmeticException e1)

JOptionPane.showMessageDialog(null,e1.getMessage());

catch(NumberFormatException e2)

JOptionPane.showMessageDialog(null,e2.getMessage());

public static void main(String arg[])

new Test();

41. import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JTextField;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import javax.swing.JOptionPane;

import java.awt.Container;

class Test implements ActionListener

JLabel l;

JTextField t;

Container c;

Test()

JFrame f=new JFrame();

f.setSize(700,150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setLayout(new FlowLayout(FlowLayout.LEFT));

l=new JLabel("Enter the background color:");

t=new JTextField(20);

f.add(l);

f.add(t);

c=f.getContentPane();

f.setVisible(true);

t.addActionListener(this);

@Override

public void actionPerformed(ActionEvent e)

String s=e.getActionCommand();

switch(s)

case "red":c.setBackground(Color.red);

break;

case "yellow":c.setBackground(Color.yellow);

break;

case "blue":c.setBackground(Color.blue);

break;

default:JOptionPane.showMessageDialog(null,"Wrong Input");

break;

public static void main(String arg[])

new Test();

42.//PRACTICE LAB

import javax.swing.JFrame;

import javax.swing.JTextField;
import java.awt.FlowLayout;

import java.awt.event.FocusListener;

import java.awt.event.FocusEvent;

import javax.swing.JButton;

class Test implements FocusListener

JButton b;

JTextField t;

Test()

JFrame f=new JFrame();

f.setSize(500,150);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setLayout(new FlowLayout(FlowLayout.LEFT));

t=new JTextField(20);

b=new JButton("Click");

f.add(t);

f.add(b);

f.setVisible(true);

t.addFocusListener(this);

@Override

public void focusGained(FocusEvent e1)

t.setText("Enter some text here");

public void focusLost(FocusEvent e2)

t.setText(" ");

public static void main(String arg[])

new Test();

}
43.//PRACTICE LAB

import javax.swing.JFrame;

import javax.swing.JTextField;

import java.awt.FlowLayout;

import java.awt.event.KeyListener;

import java.awt.event.KeyEvent;

import javax.swing.JLabel;

class Test implements KeyListener

JTextField t;

JLabel l;

Test()

JFrame f=new JFrame();

f.setSize(500,150);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setLayout(new FlowLayout(FlowLayout.LEFT));

t=new JTextField(20);

l=new JLabel();

f.add(t);

f.add(l);

f.setVisible(true);

t.addKeyListener(this);

@Override

public void keyPressed(KeyEvent e1)

public void keyReleased(KeyEvent e2)

public void keyTyped(KeyEvent e3)


{

String ch=t.getText();

String word[]=ch.split("\\s");

l.setText("Words: "+word.length+"Characters: "+ch.length());

public static void main(String arg[])

new Test();

44.//PRACTICE LAB

import javax.swing.JFrame;

import javax.swing.JLabel;

import java.awt.FlowLayout;

import java.awt.Font;

import java.awt.Color;

import java.awt.event.MouseListener;

import java.awt.event.MouseMotionListener;

import java.awt.event.MouseEvent;

class Test implements MouseListener,MouseMotionListener

JLabel l;

Test()

JFrame f=new JFrame();

f.setSize(500,150);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setLayout(new FlowLayout());

l=new JLabel();

f.add(l);

l.setFont(new Font("Arieal",Font.BOLD,25));

//l.setColor(Color.blue);

f.setVisible(true);

f.addMouseListener(this);
f.addMouseMotionListener(this);

@Override

public void mouseEntered(MouseEvent e)

l.setText("Mouse Entered");

public void mouseExited(MouseEvent e)

l.setText("Mouse Exited");

public void mousePressed(MouseEvent e)

l.setText("Mouse Pressed");

public void mouseReleased(MouseEvent e)

l.setText("Mouse Released");

public void mouseClicked(MouseEvent e)

l.setText("Mouse Clicked");

public void mouseDragged(MouseEvent e)

l.setText("Mouse Dragging");

public void mouseMoved(MouseEvent e)

l.setText("Mouse Moving");

public static void main(String arg[])

new Test();

}
}

45. import javax.swing.JFrame;

import javax.swing.JLabel;

import java.awt.FlowLayout;

import java.awt.Font;

import java.awt.Color;

import java.awt.event.MouseListener;

import java.awt.event.MouseAdapter;

//import java.awt.event.MouseMotionListener;

import java.awt.event.MouseEvent;

class Test extends MouseAdapter

JLabel l;

Test()

JFrame f=new JFrame();

f.setSize(500,150);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setLayout(new FlowLayout());

l=new JLabel();

f.add(l);

l.setFont(new Font("Arieal",Font.BOLD,25));

//l.setColor(Color.blue);

f.setVisible(true);

f.addMouseListener(this);

@Override

public void mouseEntered(MouseEvent e)

l.setText("Mouse Entered");

public void mouseReleased(MouseEvent e)

l.setText("Mouse Released");
}

public void mouseClicked(MouseEvent e)

l.setText("Mouse Clicked");

public static void main(String arg[])

new Test();

46.

You might also like