Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

1.

Program: Write a java program that prints all real solutions to the quadratic equation
ax2+bx+c=0. Read in a, b, c and use the quadratic formula.

import java.util.Scanner;
public class Exercise2 {

public static void main(String[] Strings) {

Scanner input = new Scanner(System.in);

System.out.print("Input a: ");
double a = input.nextDouble();
System.out.print("Input b: ");
double b = input.nextDouble();
System.out.print("Input c: ");
double c = input.nextDouble();

double result = b * b - 4.0 * a * c;

if (result > 0.0) {


double r1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
double r2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
System.out.println("The roots are " + r1 + " and " + r2);
} else if (result == 0.0) {
double r1 = -b / (2.0 * a);
System.out.println("The root is " + r1);
} else {
System.out.println("The equation has no real roots.");
}

}
}

Sample Output:
Input a: 1
Input b: 5
Input c: 2
The roots are -0.4384471871911697 and -4.561552812808831

2. Create a Java class called Student with the following details as variables within it.
USN ,Name ,Branch , Phone.
Write a Java program to create n Student objects and print the USN, Name, Branch, and
Phone of these objects with suitable headings.

import java.util.Scanner; 
public class student
 {
            String USN;
            String Name;
            String branch;
            int phone;
void insertRecord(String reg,String name, String brnch,int ph) {
USN=reg;
Name=name;
branch=brnch; 
phone=ph;
}

void displayRecord()
{
System.out.println(USN+" "+Name+" "+branch+" "+phone);
}

public static void main(String args[])

student s[]=new student [100]; 
Scanner sc=new Scanner(System.in);
System.out.println("enter the number of students");
int n=sc.nextInt();
for(int i=0;i<n;i++)  
      s[i]=new student();
for(int j=0;j<n;j++)
{       System.out.println("enter the usn,name,branch,phone")
         String USN=sc.next();    
         String Name=sc.next();    
        String branch=sc.next();     
         int phone=sc.nextInt();
    s[j].insertRecord(USN,Name,branch,phone);

for( int m=0;m<n;m++)
{
  s[m].displayRecord();
}

}
}

Output :
enter the number of students 
2
enter the usn,name,branch,phone 
1
monika 
cse
93411
enter the usn,name,branch,phone 
12 
gowda
cse 9785
students details are
 1 monika cse 93411
12 gowda cse 9785

3. Program:
A. Write a program to check prime number
import java.util.Scanner;
public class PrimeNumber
{
                public static void main(String args[])
             {
                  int num,b,c;
                  Scanner s=new Scanner(System.in);
                  System.out.println("Enter A Number");
                  num =s.nextInt();
                  b=1;
                  c=0;
                   while(b<= num)
                      {
                          if((num%b)==0)
                             c=c+1;
                             b++;
                      }
                       if(c==2)
                       System.out.println(num +" is a prime number");
                       else
                       System.out.println(num +" is not a prime number");
             }
}
B.Write a program for Arithmetic calculator using switch case menu.

import java.util.Scanner;

class Main {
public static void main(String[] args) {

char operator;
Double number1, number2, result;

// create an object of Scanner class


Scanner input = new Scanner(System.in);

// ask users to enter operator


System.out.println("Choose an operator: +, -, *, or /");
operator = input.next().charAt(0);

// ask users to enter numbers


System.out.println("Enter first number");
number1 = input.nextDouble();

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


number2 = input.nextDouble();

switch (operator) {

// performs addition between numbers


case '+':
result = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + result);
break;

// performs subtraction between numbers


case '-':
result = number1 - number2;
System.out.println(number1 + " - " + number2 + " = " + result);
break;

// performs multiplication between numbers


case '*':
result = number1 * number2;
System.out.println(number1 + " * " + number2 + " = " + result);
break;

// performs division between numbers


case '/':
result = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + result);
break;

default:
System.out.println("Invalid operator!");
break;
}

input.close();
}
}

Output:
Choose an operator: +, -, *, or /
/
Enter first number
24
Enter second number
8
24.0 / 8.0 = 3.0

4. Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this class
by writing three subclasses namely Teaching (domain, publications), Technical (skills), and
Contract (period). Write a Java program to read and display at least 3 staff objects of all three
categories.
import java.io.*;
class Staff
{
private int staffid;
private String name;
private long phone;
private int salary;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

void Read_Staff() throws Exception


{
System.out.println("Enter Staff ID");
staffid = Integer.parseInt(br.readLine());
System.out.println("Enter Staff Name");
name = br.readLine();
System.out.println("Enter Staff Phone number");
phone = Long.parseLong(br.readLine());
System.out.println("Enter Staff Salary");
salary = Integer.parseInt(br.readLine());
}
void Display_Staff()
{
System.out.print(staffid + "\t" + name + "\t" + phone + "\t" + salary + "\t");
}
}
class Teaching extends Staff
{
private String domain;
private String pub;

void Read_Teaching() throws Exception


{
super.Read_Staff();
System.out.println("Enter Domain");
domain = br.readLine();
System.out.println("Enter Publications");
pub = br.readLine();
}

void Display_Teaching()
{
super.Display_Staff();
System.out.println(domain + "\t" + pub);
}
}
class Technical extends Staff
{
private String skills;

void Read_Technical() throws Exception


{
super.Read_Staff();
System.out.println("Enter skills");
skills = br.readLine();
}

void Display_Technical()
{
super.Display_Staff();
System.out.println(skills);
}
}
class Contract extends Staff
{
private float period;

void Read_Contract() throws Exception


{
super.Read_Staff();
System.out.println("Enter Experience in years");
period = Float.parseFloat(br.readLine());
}

void Display_Contract()
{
super.Display_Staff();
System.out.println(period);
}
}
class LAB2A
{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter your choice");


System.out.println("1. Teaching \n 2. Technical \n 3. Contract ");
int ch = Integer.parseInt(br.readLine());

System.out.println("Enter number of records");


int no = Integer.parseInt(br.readLine());

switch(ch)
{
case 1: Teaching[] t = new Teaching[no];
for(int i = 0; i < t.length; i++ )
{
System.out.println("Enter " + (i + 1) + " details");
t[i] = new Teaching();
t[i].Read_Teaching();
}
System.out.println("Teaching Staff details are as follows:");
System.out.println("StaffID" + "\t" + "Name" + "\t" + "Phone" + "\t\t" + "Salary" + "\t"
+ "Domain" + "\t" + "Publications");
for(int i = 0; i < t.length; i++ )
{
t[i].Display_Teaching();
}
break;
case 2: Technical[] tech = new Technical[no];
for(int i = 0; i < tech.length; i++ )
{
System.out.println("Enter " + (i + 1) + " details");
tech[i] = new Technical();
tech[i].Read_Technical();
}
System.out.println("Technical Staff details are as follows:");
System.out.println("StaffID" + "\t" + "Name" + "\t" + "Phone" + "\t\t" + "Salary" + "\t"
+ "Skills" );
for(int i = 0; i < tech.length; i++ )
{
tech[i].Display_Technical();
}
break;
case 3: Contract[] c = new Contract[no];
for(int i = 0; i < c.length; i++ )
{
System.out.println("Enter " + (i + 1) + " details");
c[i] = new Contract();
c[i].Read_Contract();
}
System.out.println("Technical Staff details are as follows:");
System.out.println("StaffID" + "\t" + "Name" + "\t" + "Phone" + "\t\t" + "Salary" + "\t" +
"Period" );
for(int i = 0; i < c.length; i++ )
{
c[i].Display_Contract();
}
break;
default:System.out.println("Wrong Choice");
break;
}
}
}

5. Program: Write a java program demonstrating Method overloading and Constructor


overloading
class Main {

String language;

// constructor with no parameter


Main() {
this.language = "Java";
}

// constructor with a single parameter


Main(String language) {
this.language = language;
}

public void getName() {


System.out.println("Programming Langauage: " + this.language);
}

public static void main(String[] args) {

// call constructor with no parameter


Main obj1 = new Main();

// call constructor with a single parameter


Main obj2 = new Main("Python");

obj1.getName();
obj2.getName();
}
}
Sample Output:
Programming Language: Java
Programming Language: Python

class MethodOverloading {

// this method accepts int


private static void display(int a){
System.out.println("Got Integer data.");
}

// this method accepts String object


private static void display(String a){
System.out.println("Got String object.");
}

public static void main(String[] args) {


display(1);
display("Hello");
}
}
Sample Output:
Got Integer data.
Got String object.
6. Program: Develop a java application to implement currency converter (Dollar to
INR, EURO to INR, Yen to INR and vice versa), distance converter (meter to KM,
miles to KM and vice versa), time converter (hours to minutes, seconds and vice
versa) using packages.
Algorithm:
1.Create a package with a class file
2.Set the “classpath” from the directory from which you would like to access. It may be in
adifferent drive and directory. Let us call it as a target directory.
3.Write a program and use the file from the package.

Let us create a package called forest and place a class called Tiger in it. Access the package
from a different drive and directory.
Program:
Step 1:Create a package (converter) and place Dollar.class in it.(Package Creation)
Let us assume C:\myjava is the current directory where we would like to create the
package.C:\myjava > notepad Dollar.java//Dollar.javapackage converter;
import java.util.*;
public class Dollar
{
public void Convert()
{
double inr,usd,doll;
System.out.println("\nDollar to INR");
Scanner in=new Scanner(System.in);
System.out.print("Enter INR to convert into USD : ");
inr=in.nextDouble();
System.out.print("Enter Current USD reate : ");
doll=in.nextDouble();
usd=inr/doll;
System.out.println("\n INR="+inr+"\n USD="+usd);
}
}

While create User Defined Packages Java, the order of statements is very important. The
order must belike this, else, compilation error.
1.Package statement
2.Import statement
3.Class declarationStep
2: Compiling the package (converter):C:\jdk1.7\bin>set path="C:\jdk1.7\bin”
C:\jdk1.7>cd converter
C:\jdk1.7\converter>javac Dollar.java
The –d compiler option creates a new folder called converter and places the Dollarr.class in it. The
dot(.) is an operating system's environment variable that indicates the current directory. It is an
instruction to the OS to create a directory called converter and place the Dollar.class in it.
Step 3: Now finally, write a program from the target directory D:/myjava and access the package as
below: D:\myjava> notepad Compute.java// Compute.javaimport converter.Dollar;
public class Compute
{
public static void main(String s[])
{
Dollar d=new Dollar();
d.Convert();
}
}
Step 4:Compilation and execution of Compute.java as below:
C:\jdk1.7\bin>javac Dollar.java
C:\jdk1.7\bin>java Dollar

Output :
Dollar to INR Enter INr to convert into USD:500
Enter Current USD reate:71
INR=500.0
USD=7.042253521126761

7. Write a program to generate the resume. Create 2 Java classes Teacher (data: personal
information, qualification, experience, achievements) and Student (data: personal
information, result, discipline) which implements the java interface Resume with the method
biodata().
8. Write a Java program that implements a multi-thread application that has three threads. First
thread generates a random integer for every 1 second; second thread computes the square of
the number and prints; third thread will print the value of cube of the number.

import java.util.*;
// class for Even Number
class EvenNum implements Runnable {
public int a;
public EvenNum(int a) {
this.a = a;
}
public void run() {
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);
}
} // class for Odd Number
class OddNum implements Runnable {
public int a;
public OddNum(int a) {
this.a = a;
}
public void run() {
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);
}
}
// class to generate random number
class RandomNumGenerator extends Thread {
public void run() {
int n = 0;
Random rand = new Random();
try {
for (int i = 0; i < 10; i++) {
n = rand.nextInt(20);
System.out.println("Generated Number is " + n);
// check if random number is even or odd
if (n % 2 == 0) {
Thread thread1 = new Thread(new EvenNum(n));
thread1.start();
}
else {
Thread thread2 = new Thread(new OddNum(n));
thread2.start();
}
// thread wait for 1 second
Thread.sleep(1000);
System.out.println("------------------------------------");
}
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
// Driver class
public class MultiThreadRandOddEven {
public static void main(String[] args) {
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}
9. Program: Write a program to perform string operations using ArrayList. Write functions for
the following
a. Append - add at end b. Insert – add at particular index
c. Search d. List all string starts with given letter.

Procedure:

1. 1.Create the class arraylistexample. Create the object for the arraylist class.
2. Display the options to the user for performing string handling .
3. Use the function add() to append the string at the end and to insert the string at the
particular index.
4. The function sort () is used to sort the elements in the array list.
5. The function indexof() is used to search whether the element is in the array list or not.
6. The function startsWith () is used to find whether the element starts with the specified
character.
7. The function remove() is used to remove the element from the arraylist.
8. The function size() is used to determine the number of elements in the array list.

import java.util.*;
import java.io.*;
public class arraylistexample
{
public static void main(String args[])throws IOException
{
ArrayList<String> obj = new ArrayList<String>();
DataInputStream in=new DataInputStream(System.in);
int c,ch;
int i,j;
String str,str1;
do
{
System.out.println("STRING MANIPULATION");
System.out.println("******************************");
System.out.println(" 1. Append at end \t 2.Insert at particular index \t 3.Search \t");
System.out.println( "4.List string that starting with letter \t");
System.out.println("5.Size \t 6.Remove \t 7.Sort\t 8.Display\t" );
System.out.println("Enter the choice ");
c=Integer.parseInt(in.readLine());
switch(c)
{
case 1:
{
System.out.println("Enter the string ");
str=in.readLine();
obj.add(str);
break;
}
case 2:
{
System.out.println("Enter the string ");
str=in.readLine();
System.out.println("Specify the index/position to insert");
i=Integer.parseInt(in.readLine());
obj.add(i-1,str);
System.out.println("The array list has following elements:"+obj);
break;
}
case 3:
{
System.out.println("Enter the string to search ");
str=in.readLine();
j=obj.indexOf(str);
if(j==-1)
System.out.println("Element not found");
else
System.out.println("Index of:"+str+"is"+j);
break;
}
case 4:
{
System.out.println("Enter the character to List string that starts with specified
character");
str=in.readLine();
for(i=0;i<(obj.size()-1);i++)
{
str1=obj.get(i);
if(str1.startsWith(str))
{
System.out.println(str1);
}
}
break;
}
case 5:
{
System.out.println("Size of the list "+obj.size());
break;
}
case 6:
{
System.out.println("Enter the element to remove");
str=in.readLine();
if(obj.remove(str))
{
System.out.println("Element Removed"+str);
}
else
{
System.out.println("Element not present");
}
break;
}
case 7:
{
Collections.sort(obj);
System.out.println("The array list has following elements:"+obj);
break;
}
case 8:
{
System.out.println("The array list has following elements:"+obj);
break;
}
}
System.out.println("enter 0 to break and 1 to continue");
ch=Integer.parseInt(in.readLine());
}while(ch==1);
}
}

10. Program: Write a Java program to read two integers a and b. Compute a/b and print, when b
is not zero. Raise an exception when b is equal to zero.
import java.util.Scanner;
public class Exception {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a,b,c;
System.out.print("Enter the Two Interger Values\nA :");
a=scan.nextInt();
System.out.print("B :");
b=scan.nextInt();
scan.close();
try {
if(b==0)
throw new ArithmeticException("Divide By Zero");
c=a/b;
System.out.println("\nThe Value of "+a+" / "+b+" is "+c);
}catch(ArithmeticException e)
{
e.printStackTrace();
}
}
}

11. Write a java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length
of the file in bytes.
Algorithm:

1. import java.io.*; package

create class Filedemo{


2.
3. Create function: public static void p(String str){
1. Print String: System.out.println(str);
4. Againg create another function: public static void
analyze(String s){
1. File f = new File(s)’
5. if( f.exists()){
1. p(f.getName()+” is a file”);
2.  p(f.canRead()?” is readable”:” is not readable”);

3. p(f.canWrite()?” is writable”:” is not writable”);

4. p(“Filesize:”+f.length()+” bytes”);

5. p(“File last mdified:”+f.lastModified());

6.    if(f.isDirectory()) then

1. p(f.getName()+” is directory”);
2. p(“List of files”);

3. String dir[]=f.list();

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

5. p(dir[i])

7. Create main function: public static void main(String rr[])throws


IOException{
1. filedemo fd=new filedemo();
2. BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
3. System.out.println(“Enter the file name:”);
4. String s=br.readLine();
5. fd.analyze(s);

import java.io.*;
class filedemo
{
public static void p(String str)
{
System.out.println(str);
}
public static void analyze(String s)
File f=new File(s);
if(f.exists())
{
p(f.getName()+" is a file");
p(f.canRead()?" is readable":" is not readable");
p(f.canWrite()?" is writable":" is not writable");
p("Filesize:"+f.length()+" bytes");
p("File last mdified:"+f.lastModified());
}
if(f.isDirectory())
{
p(f.getName()+" is directory");
p("List of files");
String dir[]=f.list();
for(int i=0;i<dir.length;i++)
p(dir[i]);
}
}

}
public class FileDetails
{
public static void main(String rr[])throws IOException
{
filedemo fd=new filedemo();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the file name:");
String s=br.readLine();
fd.analyze(s);
}
}

12. Develop an applet that displays a simple message in center of the screen. Develop a simple
calculator using Swings.
/* Program to create a Simple Calculator */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements ActionListener {
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init() {
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
}
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
}
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("=")) {
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e) {
result=num2;
JOptionPane.showMessageDialog(this,"Divided by zero");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
}
}

Program 4:- Design a super class called Staff with details as StaffId, Name, Phone, Salary.
Extend this class by writing three subclasses namely Teaching (domain, publications),
Technical (skills), and Contract (period). Write a Java program to read and display at least 3
staff objects of all three categories.

class Staff
{
private int StaffId;
private String Name;
private String Phone;
private long Salary;

public Staff(int staffId,String name,String phone,long salary)


{
StaffId = staffId;
Name = name;
Phone = phone;
Salary = salary;
}
public void Display()
{
System.out.print("\t"+StaffId+"\t"+Name+"\t\t"+Phone+"\t\t"+Salary);
}
}

class Teaching extends Staff


{
private String Domain;
private int Publications;

public Teaching(int staffId, String name, String phone,long salary, String domain, int
publications)
{
super(staffId, name, phone, salary);
Domain = domain;
Publications = publications;
}
public void Display()
{
super.Display();
System.out.print("\t\t"+Domain+"\t\t"+Publications+"\t\t"+"--"+"\t"+"--");
}
}

class Technical extends Staff


{
private String Skills;
public Technical(int staffId, String name, String phone,long salary, String skills)
{
super(staffId, name, phone, salary);
Skills = skills;
}
public void Display()
{
super.Display();
System.out.print("\t\t--"+"\t\t"+"--"+"\t"+Skills+"\t"+"--");
}
}

class Contract extends Staff


{
private int Period;
public Contract(int staffId, String name, String phone, long salary, int period)
{
super(staffId, name, phone, salary);
this.Period = period;
}
public void Display()
{
super.Display();
System.out.print("\t\t--"+"\t\t"+"--"+"\t\t"+"--"+"\t"+Period);
}
}

public class lab2a


{
public static void main(String[] args)
{
Staff staff[]=new Staff[3];
staff[0]=new Teaching(0001,"Narendr","271173",90000,"CSE",3);
staff[1]=new Technical(0002,"Ara","271172",2000,"Server Admin");
staff[2]=new Contract(0003,"Rahul","271174",9000,3);
System.out.println("Staff ID\tName\t\tPhone\t\tSalary\t\tDomain\tPublication\tSkills\t\
tPeriod");
for(int i=0;i<3;i++)
{
staff[i].Display();
System.out.println();
}
}
}

You might also like