Bca Java Lab

You might also like

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

Practical -1 : Write a Java program that prints all roots of quadratic equation ax2 +bx + c = 0.

import java.util.Scanner;

public classRootsOfQuadraticEquation{

public static void main(String args[]){

double secondRoot =0, firstRoot =0;

Scanner sc =newScanner(System.in);

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

double a = sc.nextDouble();

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

double b = sc.nextDouble();

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

double c = sc.nextDouble();

double determinant =(b*b)-(4*a*c);

double sqrt =Math.sqrt(determinant);

if(determinant>0){

firstRoot =(-b + sqrt)/(2*a);

secondRoot =(-b - sqrt)/(2*a);

System.out.println("Roots are :: "+ firstRoot +" and "+secondRoot);

}elseif(determinant ==0){

System.out.println("Root is :: "+(-b + sqrt)/(2*a));

OUTPUT:
Practical 2: Write a Java program that prompts the user for an integer and then prints out all prime
numbers up to that integer.
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int i,j,n,c;
System.out.println("Enter the number till which you want prime numbers");
n=sc.nextInt();
System.out.println("Prime numbers are :-");
for(i=2;i<=n;i++)
{
c=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
{
c++;
}
}
if(c==2)
{
System.out.print(i+" ");
}
}
}
}
Output:
Practical-3: Write a Java program to create a Student class with following fields
i. Hall ticket number ii. Student Name iii. Department
Create „n‟ number of Student objects where „n‟ value is passed as input to constructor

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Student[] arr;
int Hallticketnumber;
String StudentName;
String Department;
Scanner sc=new Scanner(System.in);
System.out.println("enter n value");
int n=sc.nextInt();
arr=new Student[n+1];
for(int i=1;i<=n;i++)
{
System.out.println("enter student"+i+"details");
Hallticketnumber=sc.nextInt();
StudentName=sc.next();
Department=sc.next();
arr[i]=new Student(Hallticketnumber,StudentName,Department);
}
for(int i=1;i<=n;i++)
{
arr[i].display();
}
}
}
class Student
{
int Hallticketnumber;
String StudentName;
String Department;
Student(int x,String y,String z)
{
Hallticketnumber=x;
StudentName=y;
Department=z;
}
public void display()
{
System.out.println("Hallticketnumber is "+Hallticketnumber+" StudentName is
"+StudentName+" Department is "+Department);
}
}
Output :
Practical-4 : Write Java program to implement Hierarchical Inheritance
class A
{
public void dispA()
{
System.out.println("Displaying method A");
}
}
class B extends A
{
public void dispB()
{
System.out.println("Displaying method B");
}
}
class C extends A
{
public void dispC()
{
System.out.println("Displaying method C");
}
}
public class Student
{
public static void main(String args[])
{
C x=new C();
x.dispC();
x.dispA();
B y=new B();
y.dispB();
y.dispA();
}
}
OUTPUT:
Practical-5 : Write Java program to implement multiple inheritance through interface .
interface AnimalEat {

void eat();

interface AnimalTravel {

void travel();

class Animal implements AnimalEat, AnimalTravel {

public void eat() {

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

public void travel() {

System.out.println("Animal is travelling");

public class Student {

public static void main(String args[]) {

Animal a = new Animal();

a.eat();

a.travel();

OUTPUT:
Practicl-6 : Write a Java program to demonstrate String comparison using == and equals method.
Program 6:

public class Student {


public static void main(String[] args)
{
String s1 = "HELLO";
String s2 = "HELLO";
String s3 = "Hellow";
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // true
}
}
OUTPUT:

Practical-7 Write a Java program that creates three threads. First thread displays “Good Morning”
everyone second, the second thread displays “Hello” every two seconds and the third thread displays
“Welcome” every three seconds
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Good Morning");
try {
sleep(1000);
} catch(Exception e) {
}
}
}
}
class B extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Hello");
try {
sleep(2000);
} catch(Exception e) {
}
}
}
}
class C extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Welcome");
try {
sleep(3000);
} catch(Exception e) {
}
}
}
}
public class Student
{
public static void main(String[] args)
{
A x=new A();
B y=new B();
C z=new C();
x.start();
y.start();
z.start();
}
}
OUTPUT:

Practical-8. Write a Java program to demonstrate Exception Handling


class Student
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try {
x=a/(b-c);

}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
finally
{
System.out.println("This is a finally block");
}
y=a/(b+c);
System.out.println("y="+y);
}
}
OUTPUT:

Practical 9: Write a Java program that displays the number of characters, lines and words in a
text file
import java.util.*;
import java.io.*;
class Student
{
public static void main(String args[])throws IOException
{
int nl=1,nw=0;
char ch;
Scanner scr=new Scanner(System.in);
System.out.print("\nEnter File name: ");
String str=scr.nextLine();
FileInputStream f=new FileInputStream(str);
int n=f.available();
for(int i=0;i<n;i++)
{
ch=(char)f.read();
if(ch=='\n')
nl++;
else if(ch==' ')
nw++;

}
System.out.println("\nNumber of lines : "+nl);
System.out.println("\nNumber of words : "+(nl+nw));
System.out.println("\nNumber of characters : "+n);

}
}
OUTPUT:
Practical 10: Write a Java Program to create Applet for timer
import java.applet.Applet;
import java.awt.*;
import java.util.*;
import java.text.*;
public class DigitalClock extends Applet implements Runnable {
Thread t;
String Time="";

public void init()


{ setSize(400,200);
setBackground(Color.CYAN);
t=new Thread(this);
t.start();
}

public void run()


{
try
{
while(true)
{
Calendar c=Calendar.getInstance();
SimpleDateFormat f=new SimpleDateFormat("hh:mm:ss "+" dd/MM/yyyy");
Date d=c.getTime();
Time=f.format(d);
repaint();
t.sleep(1000);
}
}catch(Exception e)
{
System.out.println("Error Occured");
}
}
public void paint(Graphics g)
{
g.setColor(Color.RED);
g.setFont(new Font("Dialog",Font.BOLD,50));
g.drawString(Time, 100,100);
}
}
Output:
Practical 11:. Write a Java program to connect to Database using JDBC
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");

System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
Output:

When you run FirstExample, it produces the following result −


C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
Practical 12: Write a Java Program to demonstrate Servelet life Cycle.
HTML FILE:
<html>
<head>
<title>Servlet Lifecycle Example</title>
</head>
<body>
<form action="ServletLifecycle" method="post">
<input type="submit" value="Make request" />
</form>
</body>
</html>
XML File:
<web-app>
<servlet>
<servlet-name>ServletLifecycle</servlet-name>
<servlet-class>ServletLifecycleExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletLifecycle</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Servlet File:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class ServletLifecycleExample extends GenericServlet {
@Override
public void init() {
// initialize the servlet, and print something in the console.
System.out.println("Servlet Initialized!");
}
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
// the service method will
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Servlet called from jsp page!");
}
@Override
public void destroy() {
// close connections etc.
}
}
Output:

// Java Program to Establish Connection in JDBC

// Importing database
importjava.sql.*;
// Importing required classes
importjava.util.*;
// Main class
class Main {

// Main driver method


public static void main(String a[])
{

// Creating the connection using Oracle DB


// Note: url syntax is standard, so do grasp
String url = "jdbc:oracle:thin:@localhost:1521:xe";

// Usernamer and password to access DB


// Custom initialization
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 class object


Connection con = null;

// Try block to check for exceptions


try {

// Registering drivers
DriverManager.registerDriver(
new oracle.jdbc.OracleDriver());

// Reference to connection interface


con = DriverManager.getConnection(url, user,
pass);

// Creating a statement
Statement st = con.createStatement();

// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println(
"inserted successfully : " + sql);
else
System.out.println("insertion failed");
// Closing the connections
con.close();
}
// Catch block to handle exceptions
catch (Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
}
}

You might also like