Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
136 views

JAVA Lab Manual

The document contains examples of Java programs for various concepts: 1) A program that takes user input to calculate the roots of a quadratic equation. It uses if/else statements to check for real, equal or complex roots. 2) A program that takes user input and prints the Fibonacci series up to that number. 3) A program that multiplies two matrices together and prints the result.

Uploaded by

JAJULAHARIBABU
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
136 views

JAVA Lab Manual

The document contains examples of Java programs for various concepts: 1) A program that takes user input to calculate the roots of a quadratic equation. It uses if/else statements to check for real, equal or complex roots. 2) A program that takes user input and prints the Fibonacci series up to that number. 3) A program that multiplies two matrices together and prints the result.

Uploaded by

JAJULAHARIBABU
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

1. implement a java program for finding roots of quadratic equations?

import java.util.Scanner; import

java.util.Scanner; public class

QuadraticEquationExample1

public static void main(String[] Strings)

Scanner input = new Scanner(System.in);

System.out.print("Enter the value of a: ");

double a = input.nextDouble();

System.out.print("Enter the value of b: ");

double b = input.nextDouble();

System.out.print("Enter the value of c: ");

double c = input.nextDouble(); double d=

b * b - 4.0 * a * c; if (d> 0.0)

double r1 = (-b + Math.pow(d, 0.5)) / (2.0 * a); double

r2 = (-b - Math.pow(d, 0.5)) / (2.0 * a);

System.out.println("The roots are " + r1 + " and " + r2);

else if (d == 0.0)

double r1 = -b / (2.0 * a);

System.out.println("The root is " + r1);

else

System.out.println("Roots are not real.");

}
Output 1:

Enter the value of a: 1

Enter the value of b: 1

Enter the value of c: 1

Roots are not real

Output 2:

Enter the value of a: 1

Enter the value of b: 5

Enter the value of c: 2

The roots are -0.4384471871911697 and -4.561552812808831


2.Implement a Java program to display the Fibonacci series.

import java. util. *;

Class fibonacci

public static void main (string args[])

Scanner sc = new Scanner (System.in);

System.out.println(''Enter the number to print fibonacci series'');

int n=sc.next Int (); int n1=0,n2=1,n3,i;

System.out.println(n1+''\t''+n3) for(i=2;i<n;i++)

n3=n1+n2;

System.out.println(''\t''+n3);

n1=n2; n2=n3;

Output:

Enter the number to print fibonacci series

5
3.Implement a java program to multiply two given matrices?

public class MatrixMultiplicationExample{

public static void main(String args[]){

//creating two matrices int

a[][]={{1,1,1},{2,2,2},{3,3,3}}; int

b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices int

c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices

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];

}//end of k loop

System.out.print(c[i][j]+" "); //printing matrix element

}//end of j loop

System.out.println();//new line

}}

Output:

666

12 12 12

18 18 18
4.Implement a Java program to check whether the given string is palindrome or not.

import java. util.*; class

palindrome

public static void main (string args[])

String str, rev='' '';

Scanner sc=new Scanner (System.in);

System.out.print/n(''Enter a string'');

Str=sc.next Line(); int Length =

strong. Length(); for(int i=Length-1;

i>=0;i--) rev=rev+str.charAt(i);

if(Str.equals(rev))

System.out.println(str+'' is a

palindrome ''); else

System.out.prinyln(str+'' is not a palindrome '');

Output:

Enter a string

HANNAH

HANNAH is a palindrome
5.Implement a java program for finding the total numbers of objects created of a class.

public class Number_Objects

static int count=0;

Number_Objects()

count++;

public static void main(String[] args)

Number_Objects obj1 = new Number_Objects();

Number_Objects obj2 = new Number_Objects();

Number_Objects obj3 = new Number_Objects();

Number_Objects obj4 = new Number_Objects();

System.out.println("Number of objects created:"+count);

Output:

Number of objects created:4


6.Implement a java program to demonstrate static variables, methods, and blocks.

class StaticDemo

{ static int a = 3; static

int b; static void

display(int x)

System.out.println(&quot;Display is a static method&quot;);

System.out.println(&quot;x = &quot; + x);

System.out.println(&quot;a = &quot; + a);

System.out.println(&quot;b = &quot; + b);

static

System.out.println(&quot;Static block initialized.&quot;);

b = a * 4;

class StaticKeyword

public static void main(String args[])

StaticDemo.display(42);

Output:

Static block initialized.

Display is a static method

x = 42 a = 3 b = 12
7.Implement a java program that illustrates simple inheritance and multi-level inheritance

Simple inheritance:

class A

public void methodA()

System.out.println(&quot;Base class method&quot;);

class B extends A

public void methodB()

System.out.println(&quot;Child class method&quot;);

class SimpleInheritance

public static void main(String args[])

B obj = new B(); obj.methodA(); //calling

super class method obj.methodB(); //calling

local method
}

Output:

Base class method

Child class method

Multi-level inheritance:

class X

public void methodX()

System.out.println(&quot;class X method&quot;);

class Y extends X

public void methodY()

System.out.println(&quot;class Y method&quot;);

class Z extends Y

public void methodZ()

System.out.println(&quot;class Z method&quot;);

class T

public static void main(String args[])


{

Z obj = new Z(); obj.methodX(); //calling grand

parent class method obj.methodY(); //calling

parent class method obj.methodZ(); //calling local

method

Output:

class X method class

Y method class Z

method
9. Implement a java program demonstrating the difference between methodoverloading,
constructor overloading and method overriding.

Method Overloading:

class A

void sum (int a, int b)

System.out.println("sum is"+(a+b)) ;

void sum (float a, float b)

System.out.println("sum is"+(a+b));

public static void main (String[] args)

Calculate cal = new Calculate(); cal.sum (8,5);

//sum(int a, int b) is method is called. cal.sum (4.6f,

3.8f); //sum(float a, float b) is called.

Output: Sum is 13 Sum is 8.4

Example of constructor overloading class

Cricketer

String name;

String team; int age;

Cricketer () //default constructor.

{
name ="";

team =""; age

= 0;

Cricketer(String n, String t, int a) //constructor overloaded

name = n; team =

t; age = a;

Cricketer (Cricketer ckt) //constructor similar to copy constructor of c++

name = ckt.name; team

= ckt.team; age =

ckt.age;

public String toString()

return "this is " + name + " of "+team;

class A

public static void main (String[] args)

Cricketer c1 = new Cricketer();

Cricketer c2 = new Cricketer("sachin", "India", 32);

Cricketer c3 = new Cricketer(c2 );

System.out.println(c2);

System.out.println(c3);

c1.name = "Virat";
c1.team= "India"; c1.age

= 32;

System .out. println (c1);

Output:

this is sachin of india this

is sachin of india this is

virat of india

Example of Method Overriding class

Animal

public void eat()

System.out.println("Generic Animal eating");

class Dog extends Animal

public void eat() //eat() method overriden by Dog class.

System.out.println("Dog eat meat");

class MethodOverriding

public static void main(String args[])

Dog d=new Dog();


d.eat();

Output:

Dog eat meat


10. Implement a java program to give the example for ‘super’ keyword.

class Animal

String color="white";

class Dog extends Animal

String color="black"; void

printColor()

System.out.println(color);//prints color of Dog class

System.out.println(super.color);//prints color of Animal class

class TestSuper

public static void main(String args[])

Dog d=new Dog();

d.printColor();

Output:

black white
11. Implement a java program to give a simple example for abstract class abstract

class Shape

abstract void draw();

//In real scenario, implementation is provided by others i.e. unknown by end user class

Rectangle extends Shape

void draw()

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

class Circle1 extends Shape

void draw()

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

//In real scenario, method is called by programmer or user class

TestAbstraction1

public static void main(String args[])

Shape s=new Circle1();

//In real scenario, object is provided through method e.g. getShape() method s.draw();
}

Output:

drawing circle
12. Implement a java program illustrating multiple inheritance using interfaces.

interface Printable

void print(); final

static int a=10;

interface Showable

void show();

final static int a=20;

class B implements Printable,Showable

public void print()

System.out.println("Hello");

System.out.println("a value from interface Printable is"+Printable.a);

System.out.println("a value from interface Printable is"+Showable.a);

public void show()

System.out.println("Welcome");

System.out.println("a value from interface Printable is"+Printable.a);

System.out.println("a value from interface Printable is"+Showable.a);

class MultipleInher
{

public static void main(String args[])

B obj = new B();

obj.print(); obj.show();

Output: Hello a value from interface

Printable is10 a value from interface

Printable is20 Welcome

a value from interface Printable is10 a

value from interface Printable is20


13 Implement a java program to create a package named mypack and import it in circle class.

Program 1: package mypack; public class A { public void area() { int radius=5; double area=3.14*5*5;
System.out.println("Area of circle is"+area); } }

Save as: A.java

Program 2:

package qis; import mypack.*; class Circle { public static void main(String args[]) { A obj = new A();
obj.area(); } }

Save program as: Circle.java

To Compile: javac -d . *.java To Run: java qis.Circle

Output:

Area of circle is 78.5

14 Implement a java program for example of try, catch and finally block. In this check whether
the given array size is negative or not.

import java.util.*; class

NegArraySize

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter Size of Array");

int n=sc.nextInt(); try

int[] arr=new int[n]; for(int

i=0;i<arr.length;i++)

System.out.println("enter "+i+" th element"); arr[i]=sc.nextInt();

}
System.out.println("Elements of Array"); for(int

i=0;i<arr.length;i++)

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

catch(NegativeArraySizeException e)

System.out.println("Exception Caught: You have Given Negative Array Size");

} finally

System.out.println("Statements of finally block gets executed irrespective of exception");

Output1:

Enter Size of Array

4 enter 0 th

element 2

enter 1 th element

2 enter 2 th

element

1 enter 3 th

element

Elements of Array

3
Statements of finally block gets executed irrespective of exception

Output2:

Enter Size of Array

-4

Exception Caught: You have Given Negative Array Size

Statements of finally block gets executed irrespective of exception


15 Implement a java program for creation of user defined exception.

class JavaException

public static void main(String args[])

try

throw new MyException(2);

// throw is used to create a new exception and throw it.

catch(MyException e)

System.out.println(e) ;

class MyException extends Exception

int a;

MyException(int b)

a=b;

public String toString()

return ("Exception Number = "+a) ;

Output: Exception Number = 2


16.Implement a Java program for creation of multiple threads .

class My Thread1 extends Thread

public void run ()

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

System.out.println(''My Thread1:''+i);

Class My Thread2 extends Thread

public void run()

for(int i=1;i<=4.i++)

System.out.println(''My Thread2:''+i);

Class Multiple Thread Demo

public static void main (string s[])

My Thread1 t1=new My Thread1();

My Thread2 t2=new My Thread2();

t1. start();

t2. start();

}
Output:

Output may be charged from run to run. Because both threads executes simultaneously
17.Implement a Java program correctly implements producer consumer problem using the concept
of inter thread communication.

class Notify Thread extends Thread

int total;

public void run()

System.out.println(''Notify Thread starts updation'');

synchronized(this)

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

total = total+i;

System.out.println(''Notify Thread giving notification '');

this. notify();

class Wait Notify Demo

public static void main (string s[]) throws Interrupted Exception

Notify Thread t1=new Notify Thread ();

t1. start();

synchronized (t1)

System.out.println(''Main thread going to waiting state '');

t1. wait ();

System.out.println(''Main thread receives notification '');


System.out.println(''Total is:''+t1. total1);

Output:

Main thread going to waiting state

Notify Thread starts updation

Notify Thread giving notification

Main thread receives notification

Total is :5050.
18.implement a java program to add and display the group of objects using array?

public class ArrayOfObjects

public static void main(String args[])

//create an array of product object

Product[] obj = new Product[5] ;

//create & initialize actual product objects using constructor

obj[0] = new Product(23907,"Dell Laptop"); obj[1] = new

Product(91240,"HP 630"); obj[2] = new Product(29823,"LG

OLED TV"); obj[3] = new Product(11908,"MI Note Pro Max

9"); obj[4] = new Product(43590,"Kingston USB"); //display

the product object data System.out.println("Product Object

1:"); obj[0].display();

System.out.println("Product Object 2:"); obj[1].display();

System.out.println("Product Object 3:"); obj[2].display();

System.out.println("Product Object 4:"); obj[3].display();

System.out.println("Product Object 5:"); obj[4].display();

//Product class with product Id and product name as attributes class

Product

int pro_Id;

String pro_name;

//Product class constructor


Product(int pid, String n)

pro_Id = pid;

pro_name = n;

public void display()

System.out.print("Product Id = "+pro_Id + " " + " Product Name = "+pro_name);

System.out.println();

Output:

Product Object 1:

Product Id = 23907 Product Name = Dell Laptop Product

Object 2:

Product Id = 91240 Product Name = HP 630 Product

Object 3:

Product Id = 29823 Product Name = LG OLED TV

Product Object 4:

Product Id = 11908 Product Name = MI Note Pro Max 9

Product Object 5:

Product Id = 43590 Product Name = Kingston USB


19. Implement a java program that displays number of characters, lines and words in a
text file.

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

class Wordcount
{
public static void main(String args[]) throws Exception
{
FileInputStream fis=new FileInputStream("Wordcount .java");
LineNumberReader lnr=new LineNumberReader(new InputStreamReader(fis));
String data;
int chars=0,words=0;

while((data=lnr.readLine())!=null)
{
StringTokenizer st =new StringTokenizer(data);
chars=chars+ data.length();
words=words+st.countTokens();
}

System.out.println("Total chars are:"+chars );


System.out.println("Total words are:"+words );
System.out.println("Total lines are:"+lnr.getLineNumber() );

}
}

Output
20. Implement a java program for creation of buttons and labels.
Program 1
/*
Create AWT Button Example
This java example shows how to create a Button using AWT Button class.
*/

import java.applet.Applet;
import java.awt.Button;

/*
<applet code="CreateAWTButtonExample" width=200 height=200>
</applet>
*/

public class CreateAWTButtonExample extends Applet{

public void init(){

/*
* To create a button use
* Button() constructor.
*/

Button button1 = new Button();

/*
* Set button caption or label using
* void setLabel(String text)
* method of AWT Button class.
*/

button1.setLabel("My Button 1");

/*
* To create button with the caption use
* Button(String text) constructor of
* AWT Button class.
*/

Button button2 = new Button("My Button 2");

//add buttons using add method


add(button1);
add(button2);
}

Example Output
Program 2
/*
Create AWT Label Example
This java example shows how to create a label using AWT Label class.
*/
import java.applet.Applet;
import java.awt.Label;
/*
<applet code="CreateLabel" width=200 height=200>
</applet>
*/
public class CreateLabel extends Applet{

public void init(){

/*
* To create a new label use
* Label() constructor of AWT Label class.
*/

Label label1 = new Label();

/*
* To set label text use,
* void setText(String text) method of AWT Label class
*/

label1.setText("My Label 1");

/*
* To create label with the text use
* Label(String text) constructor.
*/

Label label2 = new Label("My Label 2");

/*
* To add label use
* void add(Component c) method.
*/

add(label1);
add(label2);
}
}
Example Output
21 .Implement a java program to create a border layout control and grid layout control.

Border Layout:

import java.awt.*;
public class Border1 extends Frame
{
public Border1()
{
super ("Border Layout 1");
setFont (new Font ("Helvetica", Font. PLAIN, 16 ) );
setLayout (new BorderLayout (5, 5));
add ( new Button ("Button 1"),BorderLayout.WEST);
add ( new Button ("Button 2"),BorderLayout.NORTH);
add ( new Button ("Button 3"),BorderLayout.EAST);
add ( new Button ("Button 4"),BorderLayout.SOUTH);
add ( new Button ("Button 5" ),BorderLayout.CENTER);
setBounds(100, 100, 300, 200);
setVisible(true);
}

public static void main (String arg [ ])


{
new Border1( );
}
}
Output:

Grid Layout:

import java.awt.*;
public class Grid1 extends Frame
{
public Grid1()
{
super(" Grid Layout 1");
setLayout (new GridLayout (3, 3, 30, 5) );
add (new Button ("Button 1") );
add (new Button ("Button 2") );
add (new Button ("Button 3") );
add (new Button ("Button 4") );
add (new Button ("Button 5") );
setBounds(100,100,200,100);
setVisible (true);
}

public static void main(String arg [ ])


{
new Grid1();
}
}
Output:
22. Implement a java program to create a simple calculator.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="Appletdemo.class" height=300 width=300>
</applet>
*/

public class Appletdemo extends Applet


{
Button b[];
TextField t1;
String txt="";
int no1=0,no2=0,no3=0;
String oprt="";

public void init()


{
b = new Button[16];
for(int i =0; i <= 9; i++)
{
b[i] = new Button(i + "");
}

b[10] = new Button("+");


b[11] = new Button("-");
b[12] = new Button("*");
b[13] = new Button("/");
b[14] = new Button("=");
b[15] = new Button("C");
t1 = new TextField(25);
add(t1);

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


{
add(b[i]);
b[i].addActionListener(new Bh());
}
}

class Bh implements ActionListener


{
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") )
{
no1 = Integer.parseInt(t1.getText());
oprt = s;
t1.setText(no1+ "");
txt = "";
}

else if (s.equals("C"))
{
no1 = no2 = 0;
txt = "";
t1.setText("");
}
else if (s.equals("="))
{
no2 = Integer.parseInt(t1.getText());
if (oprt.equals("+"))
t1.setText((no1 + no2) + "");
if (oprt.equals("-"))
t1.setText((no1 - no2) + "");
if (oprt.equals("*"))
t1.setText((no1 * no2) + "");
if (oprt.equals("/"))
t1.setText((no1 / no2) + "");
txt = "";
}
else
{
txt = txt + s;
t1.setText(txt);
}
}
}
}

Output:

You might also like