0% found this document useful (0 votes)
79 views58 pages

Final Oops Lab Manual

Uploaded by

Ranga Swamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views58 pages

Final Oops Lab Manual

Uploaded by

Ranga Swamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

1.

Prime Numbers from 1 to n


Program
import java.util.Scanner;
class Prime
{
public static void main (String args[])
{
Scanner Scanner=new Scanner(System.in);
int i=0;
int num=0;
String PrimeNumbers=" ";
System.out.println("Enter the value of n:");
int n=Scanner.nextInt();
Scanner.close();
for(i=1;i<=n;i++)
{
int counter=0;
for (num=i; num>=1;num--)
{
if(i%num==0)
{
counter=counter+1;
}
}
if(counter==2)
{
PrimeNumbers=PrimeNumbers+i+" ";
}
}
System.out.println("PrimeNumbers from 1to n Are:");
System.out.println(PrimeNumbers);
}
}
COMPILATION & EXECUTION

To save: Prime.java
To compile: javac Prime.java
To run: java Prime

***********OUTPUT***********
Enter the value of n: 10
Prime Numbers from 1 to n Are:
2 3 5 7
2. Roots of Quadratic Equation
Program
import static java.lang.Math.*;
public class EQR
{
static void calculateRoots(int a, int b, int c)
{
if (a == 0)
{
System.out.println("The value of a cannot be 0.");
return;
}

int d = b * b - 4 * a * c;
double sqrtval = sqrt(abs(d));
if (d > 0)
{
System.out.println("The roots of the equation are real and different. \n");
System.out.println((double)(-b + sqrtval) / (2 * a) + "\n"+ (double)(-b - sqrtval) / (2 * a));
}
else if (d == 0)
{
System.out.println("The roots of the equation are real and same. \n");
System.out.println(-(double)b / (2 * a) + "\n"+ -(double)b / (2 * a));
}
else
{
System.out.println("The roots of the equation are complex and different. \n");
System.out.println(-(double)b / (2 * a) + " + i"+ sqrtval + "\n"+ -(double)b / (2 * a)+ " - i" +
sqrtval);
}
}
public static void main(String args[])
{
int a = 1, b = -2, c = 1;
calculateRoots(a, b, c);

}
}
COMPILATION & EXECUTION

To save: EQR.java
To compile: javac EQR.java
To run: java EQR

***********OUTPUT***********

The roots of the equation are real and same.


1.0
1.0
3. Electricity Bill
Program

import java.util.*;
class EBill
{
public static void main(String args[])
{
int units=280;

double billpay=0;

if(units<100)
{
billpay=units*1.20;
}
else if(units<300)
{
billpay=100*1.20+(units-100)*2;
}
else if(units>300)
{
billpay=100*1.20+200*2+(units-300)*3;
}

System.out.println("Bill to pay : " + billpay);


}
}

COMPILATION & EXECUTION

To save: EBill.java
To compile: javac EBill.java
To run: java EBill

***********OUTPUT***********

Bill to pay: 480.0


4. Matrix multiplication
Program
public class Matrix{
public static void main(String args[]){
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+"");
}
System.out.println();
}
}
}
COMPILATION & EXECUTION

To save: Matrix.java
To compile: javac Matrix.java
To run: java Matrix

***********OUTPUT***********
6 12 18
6 12 18
6 12 18
5. Dynamic Binding
Program
public class DynamicBinding

public static class superclass{

void print() {

System.out.println("this is super class ");

public static class subclass extends superclass

//@Override

void print(){

System.out.println("this is sub class");

public static void main(String[] args){

superclass sup=new superclass();

subclass sub=new subclass();

sup.print();

sub.print();

}}
COMPILATION & EXECUTION

To save : DynamicBinding.java

To compile : javac DynamicBinding.java

To run : java DynamicBinding

***********OUTPUT***********

This is super class

This is sub class


6. Use of Inheritance Preventing Inheritance using
Final Abstract Class
Program

Class Calculation

int z;

public void addition (int x,int y)

z=x+y;

System.out.println("the sum of the given number"+z);

public void subtraction(int x,int y)

z=x-y;

System.out.println("the difference between the given numbers"+ z);

class My_Calculation extends Calculation

public void multiplication(int x,int y)

z=x*y;

System.out.println("the product of the given numbers"+ z);

public static void main(String args[])


{

int a=20,b=10;

My_Calculation demo= new My_Calculation();

demo.addition(a,b);

demo.subtraction(a,b);

demo.multiplication(a,b);

COMPILATION & EXECUTION

To save: My_Calculation.java

To compile : javac My_Calculation.java

To run: java My Calculation

***********OUTPUT***********

The sum of the given Numbers: 30

The difference between the given numbers is: 10

The product of the given number is: 200


7. Define a class Define Instance Method for getting
and retrieving of instance variable and initiate
object
Program
import java.lang.*;

class Emp

String name;

int id;

String address;

void getdata(String name,int id,String address)

this.name=name;

this.id=id;

this.address=address;

void putdata()

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

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

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

System.out.println("address:"+address);

class Empdemo{

public static void main(String arg[])

{
Emp e=new Emp();

e.getdata("smith",2084,"anathapur");

e.putdata();

COMPILATION & EXECUTION

To save : Empdemo.java

To compile : javac Empdemo.java

To run : java Empdemo.java

***********OUTPUT***********
Employee Details are

Name : smith

Id : 2048

Address : ananthapur
8. Define a class Define instance method for getting
and instance of object
Program
class Sum

void add(int a,int b)

System.out.println("sum of two:"+(a+b));

void add(int a,int b,int c)

System.out.println("sum of three:"+(a+b+c));

class polymorphism

public static void main(String args[])

Sum s=new Sum();

s.add(10,15);

s.add(10,20,30);

}
COMPILATION & EXECUTION

To save : Polymorphism.java

To compile :javac Polymorphism.java

To run : java Polymorphism

***********OUTPUT***********
Sum of two : 25

Sum of three: 30
9. Preventing Inheritance using Final
Program

final class DataOne

void Display()

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

class DataTwo extends DataOne

void Display()

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

public class JavaApp

public static void main(String[] args)

DataTwo obj=new DataTwo();

obj.Display();

}
COMPILATION & EXECUTION

To save : Javaapp.java

To compile : javac Javaapp.java

To run : java Javaapp

***********OUTPUT***********

Cannot inherit from final dataone


10. Program Using Abstract Class
Program

abstract class one

abstract void callme();

void callmetoo()

System.out.println("this is a concerete method");

class two extends one

void callme()

System.out.println("b is implementation of callme");

class AbstractDemo

public static void main(String args[])

two b=new two();

b.callme();

b.callmetoo();

}
COMPILATION & EXECUTION

To save : AbstractDemo.java

To compile : javac AbstractDemo.java

To run : java AbstractDemo

**************** output ******************


b is implementation of callme

this is a concrete method


11. Implementing Interface
Program

import java.lang.*;

interface Area{

final static float pi=3.14f;

float compute(float x,float y);

class rectangle implements Area{

public float compute(float x,float y){

return(pi*x*y);

class Circle implements Area{

public float compute(float x,float y){

return(pi*x*x);

class InterfaceDemo{

public static void main(String args[])

rectangle rect=new rectangle();

Circle cir=new Circle();

Area A;

A=rect;

System.out.println("Area of rectangle="+A.compute(10,20));
A=cir;

System.out.println("Area of circle="+A.compute(30,0));

COMPILATION & EXECUTION

To save : InterfaceDemo.java

To compile : javac InterfaceDemo.java

To run : java InterfaceDemo

********************* OUTPUT *******************

Area of rectangle = 628.0

Area of circle = 2826.0002


12. Method Overloading
Program

import java.lang.*;

class A

void cal(double x)

System.out.println("square value="+(x*x));

class B extends A

void cal(double x)

System.out.println("square root="+Math.sqrt(x));

class Polymorphism

public static void main(String args[])

A a=new A();

B b=new B();

b.cal(15);

a.cal(15);
}

COMPILATION & EXECUTION

To save : Polymorphism.java

To complie : javac Polymorphism.java

To run : java Polymorphism

********************* OUTPUT ****************************

Square root :3.87298334

Square value : 225.0


13. Program ways on the Implement Interface
Program

import java.lang.*;

interface Area

final static float pi=3.14f;

double compute(double x,double y);

interface display extends area{

void display.result(double result);

class rectangle implements display{

public double compute(double x,double y){

return(pi*x*y);

public void display-result(double result){

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

class InterfaceDemo{

public static void main(string args[]){

rectangle rect=new rectangle();

double rect.compute(10,2,12,3);

rect.display_result(result);

}
COMPILATION & EXECUTION

To save : InterfaceDemo.java

To compile : javac InterfaceDemo,java

To run : java InterfaceDemo

******************** OUTPUT*************
Area of Rectangle : 628.0

Area of circle : 2826.0002


14. Program to display content of a fail along with the number
Program

import java.util.*;

import java.io.*;

class Rfile

public static void main(String args[])throws

IOException{

int j=1;

char ch;

Scanner scr=new Scanner(System.in);

System.out.println("\n enter File name:");

String str=scr.next();

FileInputStream f=new FileInputStream(str);

System.out.println("\n Contents of file are");

int n=f.available();

System.out.print(j+":");

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

ch=(char)f.read();

System.out.print(ch);

if(ch=='\n')

System.out.println(++j+":");

}}}}
COMPILATION & EXECUTION

To save : Rfile.java

To compile : javac Rfile.java

To run : java Rfile.java

***************** OUTPUT **************

1:Import java.io.*;

2:Class Demo

3:{

4: Public static void main(String args[])

5:{

6:System.out.println(“This is demo”);

7:}

8:}

*/
15.Program for implementing Traffic Signals

Program

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="Signals" width=400 height=250></applet>*/
public class Signals extends Applet implements ItemListener
{
String msg="";
Checkbox stop,ready,go;
CheckboxGroup cbg;
public void init()
{
cbg = new CheckboxGroup();
stop = new Checkbox("Stop", cbg, false);
ready = new Checkbox("Ready", cbg, false);
go= new Checkbox("Go", cbg, false);
add(stop);
add(ready);
add(go);
stop.addItemListener(this);
ready.addItemListener(this);
go.addItemListener(this);

public void itemStateChanged(ItemEvent ie)


{
repaint();
}

public void paint(Graphics g)


{

msg=cbg.getSelectedCheckbox().getLabel();
g.drawOval(165,40,50,50);
g.drawOval(165,100,50,50);
g.drawOval(165,160,50,50);
if(msg.equals("Stop"))
{
g.setColor(Color.red);
g.fillOval(165,40,50,50);
}
else if(msg.equals("Ready"))
{
g.setColor(Color.yellow);
g.fillOval(165,100,50,50);
}
else
{
g.setColor(Color.green);
g.fillOval(165,160,50,50);
}

}
}

COMPILATION & EXECUTION

To save : Signals.java

To compile : javac Signals.java

To run : appletviewer.java
***************** OUTPUT **************
16. Java program to implement solution of producer
consumer problem.
Program

import java.util.LinkedList;
public class ThreadExample {
public static void main(String[] args) throws InterruptedException
{

final PC pc = new PC();

Thread t1 = new Thread(new Runnable() {

public void run()


{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});

Thread t2 = new Thread(new Runnable() {


@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});

t1.start();
t2.start();
t1.join();
t2.join();
}

public static class PC {

LinkedList<Integer> list = new LinkedLis();


int capacity = 2;

public void produce() throws InterruptedException


{
int value = 0;
while (true) {
synchronized (this)
{

while (list.size() == capacity)


wait();

System.out.println("Producer produced-"+ value);

list.add(value++);

notify();

Thread.sleep(1000);
}
}
}

public void consume() throws InterruptedException


{
while (true) {
synchronized (this)
{

while (list.size() == 0)
wait();

int val = list.removeFirst();

System.out.println("Consumeconsumed-+ val);
notify();

Thread.sleep(1000);
}
}
}
}
}

COMPILATION & EXECUTION

To save : ThreadExample java

To compile : javac ThreadExample.java

To run : ThreadExample java

*************/OUTPUT***********

Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2
17. Program for using “this” keyword
Program
import java.io.*;

class Si{

float p,t,r;

void getdata(float p,float t,float r){

this.p=p;

this.t=t;

this.r=r;

void rate()

System.out.println("rate is" + (p*t*r));

class This

public static void main(String args[]){

Si s=new Si();

s.getdata(10.0f,11.2f,29.8f);

s.rate();

}
Compilation & Execution

To Save: Si.java

Compilation: javac Si.java

Execution: java Si

*************OUTPUT***********

Rate is 3337.5999
18. program to print student details
Program

import java.io.*;

class Student

String SName;

String Htn;

float per;

void getData(String s,String h,float p)

SName=s;

Htn=h;

per=p;

void disp()

System.out.println("Name="+SName);

System.out.println("Hall ticket no="+Htn);

System.out.println("Percentage="+per);

class StudentDetails

public static void main(String[] args)

Student ob=new Student();


ob.getData("saranyadevi","111111",99.9f);

ob.disp();

Compilation & Execution

To Save: StudentDetails.java

Compilation: javac StudentDetails.java

Execution: java StudentDetails

*************OUTPUT***********

Name=saranyadevi

Hall ticket no=111111

Percentage=99.9
19.Establishing JDBC Connection in Java
Program

import java.sql.*;
import java.util.*;

class Main
{
public static void main(String a[])
{
//Creating the connection

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String user = "system";
String pass = "12345";

//Entering the data

Scanner k = new Scanner(System.in);


System.out.println("enter name");
String name = k.next();
System.out.println("enter roll no");
int roll = k.nextInt();

System.out.println("enter class");
String cls = k.next();

//Inserting data using SQL query


String sql = "insert into student1 values('"+name+"',"+roll+",'"+cls+"')";
Connection con=null;

try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
//Reference to connection interface
con = DriverManager.getConnection(url,user,pass);

Statement st = con.createStatement();
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
con.close();
}
catch(Exception ex)

{
System.err.println(ex);
}
}
}

Compilation & Execution

To Save: Main.java

Compilation: javac Main.java

Execution: java Main


*************OUTPUT***********
20. To calculate difference between two time periods
Program
public class Time {

int seconds;

int minutes;

int hours;

public Time(int hours, int minutes, int seconds) {

this.hours = hours;

this.minutes = minutes;

this.seconds = seconds;

public static void main(String[] args) {

Time start = new Time(12, 34, 55),

stop = new Time(8, 12, 15),

diff;

diff = difference(start, stop);

System.out.printf("TIME DIFFERENCE: %d:%d:%d - ", start.hours,

start.minutes, start.seconds);

System.out.printf("%d:%d:%d ", stop.hours, stop.minutes,

stop.seconds);

System.out.printf("= %d:%d:%d\n", diff.hours, diff.minutes,

diff.seconds);

public static Time difference(Time start, Time stop)

{
Time diff = new Time(0, 0, 0);

if(stop.seconds > start.seconds){

--start.minutes;

start.seconds += 60;

diff.seconds = start.seconds - stop.seconds;

if(stop.minutes > start.minutes){

--start.hours;

start.minutes += 60;

diff.minutes = start.minutes - stop.minutes;

diff.hours = start.hours - stop.hours;

return(diff);

Compilation & Execution


To save: Time.java

To compile:javac Time.java

To run: java Time

*************OUTPUT***********

Time Difference: 12:34:55- 8:12:15= 4:22:40


21.Program for finding maximum value in Generics
Program

public class MainClass {

public static <T extends Comparable<T>> T maximum(T x, T y, T z) {

T max = x;

if (y.compareTo(max) > 0)

max = y;

if (z.compareTo(max) > 0)

max = z;

return max;

public static void main(String args[]) {

System.out.printf("Maximum of %d, %d and %d is %d\n\n", 3, 4, 5, maximum(3, 4, 5));

System.out.printf("Maximum of %.1f, %.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum(6.6,

8.8, 7.7));

System.out.printf("Maximum of %s, %s and %s is %s\n", "pear", "apple", "orange", maximum(


"pear""apple","orange"));

}
Compilation & Execution

To save: MainClass.java

To compile: javac MainClass.java

To execute: java MainClass

*************OUTPUT***********

Maximum of 3, 4 and 5 is 5

Maximum of 6.6, 8.8 and 7.7 is 8.8

Maximum of pear, apple and orange is pear


22. Create the following Java program using Swing
with JTextField
Program
import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class SwingControlDemo {

private JFrame mainFrame;

private JLabel headerLabel;

private JLabel statusLabel;

private JPanel controlPanel;

public SwingControlDemo(){

prepareGUI();

public static void main(String[] args){

SwingControlDemo swingControlDemo = new SwingControlDemo();

swingControlDemo.showTextFieldDemo();

private void prepareGUI(){

mainFrame = new JFrame("Java Swing Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

headerLabel = new JLabel("", JLabel.CENTER);

statusLabel = new JLabel("",JLabel.CENTER);

statusLabel.setSize(350,100);

controlPanel = new JPanel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showTextFieldDemo(){

headerLabel.setText("Control in action: JTextField");

JLabel namelabel= new JLabel("User ID: ", JLabel.RIGHT);

JLabel passwordLabel = new JLabel("Password: ", JLabel.CENTER);

final JTextField userText = new JTextField(6);

final JPasswordField passwordText = new JPasswordField(6);

JButton loginButton = new JButton("Login");

loginButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


String data = "Username " + userText.getText();

data += ", Password: " + new String(passwordText.getPassword());

statusLabel.setText(data);

});

controlPanel.add(namelabel);

controlPanel.add(userText);

controlPanel.add(passwordLabel);

controlPanel.add(passwordText);

controlPanel.add(loginButton);

mainFrame.setVisible(true);

Compilation & Execution

To Save: SwingControlDemo.java

Compilation: javac SwingControlDemo.java

Execution: java SwingControlDemo


*************OUTPUT***********
23.Develop a java application for stack operation
using buttons and JOptionpane input and message
dialogue box
Program

import javax.swing.JOptionPane;

public class MessageDialogDemo


{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "Welcome");
}
}

/* ***************** output **************


24.finding area of rectangle using JOptionPane with
swing
Program
import javax.swing.JOptionPane;
public class RectangleTest
{
public static void main(String[] args)
{
String input;
int length;
int width;
int area;
input = JOptionPane.showInputDialog("Enter Length");

length = Integer.parseInt(input);

input = JOptionPane.showInputDialog("Enter Width");

width = Integer.parseInt(input);

area = length * width;

JOptionPane.showMessageDialog(null,"Area of rectangle is " + area);


}
}

Compilation & Execution

To Save: RectangleTest.java

Compilation: javac RectangleTest.java

Execution: java RectangleTest


*************OUTPUT***********
25.Program for
ArithmeticOperationJOptionPane using swing
Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ArithmeticOperationJOptionPane extends JFrame {
private JButton buttons[];
private String operation[] = {"Addition [+]","Subtraction [-]","Multiplication [x]","Division
[/]"};
public arithmeticOperationJOptionPane() {
super

("Arithmetic Operation using JOptionPane");


setSize(320,120);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttons = new JButton[4];

Container pane = getContentPane();


setContentPane(pane);
GridLayout grid = new GridLayout(2,2);
pane.setLayout(grid);

for(int count=0; count<buttons.length; count++) {


buttons[count] = new JButton(operation[count]);
pane.add(buttons[count]);

buttons[0].addActionListener(

new ActionListener() {
public void actionPerformed(ActionEvent event) {

try {

String input1, input2;


int num1, num2, result;
input1 = JOptionPane.showInputDialog("Please Input First Number: ");

input2 = JOptionPane.showInputDialog("Please Input Second Number: ");


num1 = Integer.parseInt(input1);
num2 = Integer.parseInt(input2);
result = num1 + num2;

JOptionPane.showMessageDialog(null,result,"Result:",JOptionPane.INFORMATION_MES
SAGE);
} catch(NumberFormatException e)

{
JOptionPane.showMessageDialog(null, "Please Input a
Integer","Error",JOptionPane.ERROR_MESSAGE);

);

buttons[1].addActionListener(
new ActionListener() {

public void actionPerformed(ActionEvent event) {


try {

String input1, input2;


int num1, num2, result;
input1 = JOptionPane.showInputDialog("Please Input First Number: ");
input2 = JOptionPane.showInputDialog("Please Input Second Number: ");
num1 = Integer.parseInt(input1);
num2 = Integer.parseInt(input2);
result = num1 - num2;
JOptionPane.showMessageDialog(null,result,"Result:",JOptionPane.INFORMATION_MES
SAGE);

catch(NumberFormatException e)

JOptionPane.showMessageDialog(null, "Please Input a


Integer","Error",JOptionPane.ERROR_MESSAGE);
}

}
}

);

buttons[2].addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {

try {
String input1, input2;
int num1, num2, result;
input1 = JOptionPane.showInputDialog("Please Input First Number: ");
input2 = JOptionPane.showInputDialog("Please Input Second Number: ");
num1 = Integer.parseInt(input1);
num2 = Integer.parseInt(input2);
result = num1 * num2;
JOptionPane.showMessageDialog(null,result,"Result:",JOptionPane.INFORMATION_MES
SAGE);
} catch (NumberFormatException e){
JOptionPane.showMessageDialog(null, "Please Input a
Integer","Error",JOptionPane.ERROR_MESSAGE);
}

}
}

);
buttons[3].addActionListener(
new ActionListener() {

public void actionPerformed(ActionEvent event) {

try {
String input1, input2;
int num1, num2, result;
input1 = JOptionPane.showInputDialog("Please Input First Number: ");
input2 = JOptionPane.showInputDialog("Please Input Second Number: ");
num1 = Integer.parseInt(input1);
num2 = Integer.parseInt(input2);

result = num1 / num2;


JOptionPane.showMessageDialog(null,result,"Result:",JOptionPane.INFORMATION_MES
SAGE);
} catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Please Input a
Integer","Error",JOptionPane.ERROR_MESSAGE);
}

);
buttons[0].setMnemonic('A');
buttons[1].setMnemonic('S');
buttons[2].setMnemonic('M');
buttons[3].setMnemonic('D');
setVisible(true);setResizable(false);
}
public static void main (String[] args) {

arithmeticOperationJOptionPane pjtf = new arithmeticOperationJOptionPane();

Compilation and Exicution:


To save: ArithmeticOperationJOptionPane

To Compile: javac ArithmeticOperationJOptionPane.java

To Run: java ArithmeticOperationJOptionPane

*************OUTPUT***********
26.Program to find the number of words in the given
text file
Program
import java.io.BufferedReader;
import java.io.FileReader;
public class CountWordFile
{
public static void main(String[] args) throws Exception
{
String line;
int count = 0;
FileReader file = new FileReader("data.txt");
BufferedReader br = new BufferedReader(file);
while((line = br.readLine()) != null) {
String words[] = line.split(" ");
count = count + words.length;
}

System.out.println("Number of words present in given file: " + count);


br.close();
}
}
Compilation & Execution

To Save: CountWordFile.java

Compilation: javac CountWordFile.java

Execution: java CountWordFile

*************OUTPUT***********

Number of words present in given file: 63


27.Program for Exception Handling
Program

import java.lang.Exception;

import java.lang.*;

import java.lang.Exception;

import java.io.DataInputStream;

class MyException extends Exception

MyException(String Message)

super(Message);

class User

public static void main(String args[])

int age;

DataInputStream ds=new DataInputStream(System.in);

try

System.out.println("enter the age(above(15 and below 20):");

age=Integer.parseInt(ds.readLine());

if(age<15||age>25)

{
throw new MyException("number not in range");

System.out.println("the number is:"+age);

catch(MyException e)

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

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

catch(Exception e)

System.out.println(e);

Compilation & Execution

To save: User.java

To compile: javac User.java

To run: java User

*************OUTPUT***********

Enter the age<above 15 and below 20>:

16

The number is:16 *\

You might also like