0% found this document useful (0 votes)
4 views19 pages

Java Assignment for Students

The document contains a list of Java programming tasks along with their respective code implementations. It covers a variety of topics including factorial calculation, Fibonacci series, word counting, palindrome checking, prime number generation, employee details display, abstract classes, interfaces, multi-threading, file properties, applets, and JDBC database connections. Each task includes a brief description and a sample output.

Uploaded by

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

Java Assignment for Students

The document contains a list of Java programming tasks along with their respective code implementations. It covers a variety of topics including factorial calculation, Fibonacci series, word counting, palindrome checking, prime number generation, employee details display, abstract classes, interfaces, multi-threading, file properties, applets, and JDBC database connections. Each task includes a brief description and a sample output.

Uploaded by

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

[ INDEX

S No Name of the program


1 Write a java program to find the factorial of a number

2 Write a java program to display Fibonacci series

3
Write a java program to count number of words in a given text
4
Write a java program to check the given string is palindrome or not
5 Write a java program to print the prime numbers upto nth number Program:

6
Write a java program to display the employee details using Scanner class.

7
Write a java program to represent Abstract class with example.

8
Write a java program to implement Interface using extends keyword.

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

10
Write a java program to display File class properties.

11
Write an applet program that displays a simple message.

12
Write a Java program compute factorial value using Applet.

13
Write a program for passing parameters using Applet.

14
Write a java program that connects to a database using JDBC

15
Write a java program to connect to database using JDBC & insert values into table

16 Write a java program to connect to a database using JDBC and delete values from table
1. Write a java program to find the factorial of the number

class Fact
{
public static void main(String[] args)
{
int number = 5;
int factorial = number;
for(int i =(number - 1); i > 1; i--)
{
factorial = factorial * i;
}
System.out.println("Factorial of a number is:" + factorial);
}
}

Output:
Factorial of a number is:120
2. Write a java program to display Fibonacci series

import java.util.Scanner;
class Fib
{
public static void main(String args[ ])
{
Scanner input=new Scanner(System.in);
int i,a=0,b=1,c=0,t;
System.out.println("Enter value of t:");
t=input.nextInt();
System.out.print(a);
System.out.print(" "+b);
for(i=0;i<t-2;i++)
{
c=a+b;
a=b; b=c;
System.out.print(" "+c);
}
System.out.println();
System.out.print(t+"th value of the series is: "+c);
}
}

Output –

Enter value of t: 8
0 1 1 2 3 5 8 13
3. Write a java program to count number of words in a given text

import java.util.*;
class CountWords
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string : ");
String str=sc.readLine(); int count=0; if(str.length()==0)
{
System.out.println("No.of words in given text:" + count);
}
else
{
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==' ')
{
count++;
}
}
System.out.println("No.of words in given text:" + (count+1));
}
}
}

Output:
Enter a string: hi this is siva
No. of words in given text: 4
4. Write a java program to check the given string is palindrome or not.

import java.util.*;
public class Palindrome
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter String:");
String str=sc.readLine();
char ch[]=new char[str.length()];
for(int i=str.length()-1,j=0;i>=0;i--,j+
+)
ch[j]=str.charAt(i);
String restr=new String(ch);
System.out.println("Reverse of String "+str+" is "+restr);
if(str.compareTo(restr)==0)
System.out.println(str+" "+"is a Palindrome");
else
System.out.println(str+" "+"is not a Palindrome");
}
}

Output:
Enter String: madam
Reverse of String madam is madam madam is a Palindrome
5. Write a java program to print the prime numbers upto nth number

import java.util.*;
class Primenos
{
public static void main(String args[])
{

int i,t,flag,n;
Scanner sc = new Scanner(System.in);
System.out.println("ENTER n VALUE:");
n=Integer.parseInt(sc.readLine());
System.out.println("PRIME NUMBERS UP TO"+" "+n+":");
for(i=2;i<=n;i++)
{
flag=1; for(t=2;t<i;t+
+)
{
if(i%t==0)
{
flag=0;
break;
}
}
if(flag==1)
System.out.println(i);
}
}
}

Output:
ENTER n VALUE:
5
PRIME NUMBERS UP TO 5:
2
3
5
6. Write a java program to display the employee details using Scanner class.

import java.util.Scanner;
class Employee
{
int Id;
String Name; int Age;
long Salary;
void GetData()
{
Scanner sc = new Scanner(System.in);
System.out.print("\n\tEnter Employee Id : ");
Id = Integer.parseInt(sc.nextLine());
System.out.print("\n\tEnter Employee Name : ");
Name = sc.nextLine();
System.out.print("\n\tEnter Employee Age : ");
Age = Integer.parseInt(sc.nextLine());
System.out.print("\n\tEnter Employee Salary : ");
Salary = Integer.parseInt(sc.nextLine());
}
void PutData()// Defining PutData()
{
System.out.print("\n\t" + Id + "\t" +Name + "\t" +Age + "\t" +Salary);
}

public static void main(String args[])


{
Employee[] Emp = new Employee[3]; int i;
for(i=0;i<3;i++)
Emp[i] = new Employee(); // Allocating memory to each object

for(i=0;i<3;i++)
{
System.out.print("\nEnter details of "+ (i+1) +" Employee\n");
Emp[i].GetData();
}
System.out.print("\nDetails of Employees\n");
for(i=0;i<3;i++)
Emp[i].PutData();
}
}
7 Write a java program to represent Abstract class with example.
abstract class Shape
{
abstract void numberOfSides();
}

class Trapezoid extends Shape


{
void numberOfSides()
{
System.out.println("The no. of side's in trapezoidal are6");
}
}

class Triangle extends Shape


{
void numberOfSides()
{
System.out.println("The no. of side's in triangle are:3 ");
}
}

class Hexagon extends Shape


{
void numberOfSides()
{
System.out.println("The no. of side's in hexagon are:6 ");
}
}

class ShapeDemo
{
public static void main(String args[])
{
Trapezoid obj1 = new Trapezoid();
Triangle obj2 = new Triangle();
Hexagon obj3 = new Hexagon();
obj1.numberOfSides();
obj2.numberOfSides();
obj3.numberOfSides();
}
}
8. Write a java program to implement Interface using extends keyword.

interface Inf1
{
public void method1();
}

interface Inf2 extends Inf1


{
public void method2();
}

public class Demo implements Inf2


{
public void method1()
{
System.out.println("method1");
}
public void method2()
{
System.out.println("method2");
}
public static void main(String args[])
{
Inf2 obj = new Demo();
obj.method2();
}
}
9. Write a Java program that implements a multi-thread application that has three threads.

/* The first thread displays "Good Morning" for every one second, the second thread
displays "Hello" for every two seconds and third thread displays "Welcome" for every three
seconds */

class GoodMorning extends Thread


{
synchronized public void run()
{
try
{
int i=0;
while (i<5)
{
sleep(1000); System.out.println("Good morning "); i++;
}
} catch (Exception e) {}
}
}

class Hello extends Thread


{
synchronized public void run()
{
try {
int i=0;
while (i<5)
{
sleep(2000);
System.out.println("hello"); i++;
}
} catch (Exception e) {}
}
}

class Welcome extends Thread


{
synchronized public void run()
{
try {
int i=0;
while (i<5)
{
sleep(3000);
System.out.println("welcome"); i++;
}
} catch (Exception e) {}
}
}

class MultithreadDemo
{
public static void main(String args[])
{
GoodMorning t1 = new GoodMorning();
Hello t2 = new Hello();

}
Welcome t3 = new Welcome();

t1.start();
t2.start();
t3.start();

}
}
10. Write a java program to display File class properties.

import java.io.File;

property class fileProperty


{
public static void main(String[] args)
{
//accept file name or directory name through command line args
String fname =args[0];
//pass the filename or directory name to File
object File f = new File(fname);
//apply File class methods on File object
System.out.println("File name :"+f.getName());
System.out.println("Path: "+f.getPath());
System.out.println("Absolute path:" +f.getAbsolutePath());
System.out.println("Parent:"+f.getParent());
System.out.println("Exists :"+f.exists());
if(f.exists())
{
System.out.println("Is writeable:"+f.canWrite());
System.out.println("Is readable"+f.canRead());
System.out.println("Is a directory:"+f.isDirectory());
System.out.println("File Size in bytes "+f.length());
}

}
}
11. Write an applet program that displays a simple message

Applet1.java:

// Import the packages to access the classes and methods in awt and applet

classes. import java.awt.*;


import java.applet.*;

public class Applet1 extends Applet


{
// Paint method to display the message.
public void paint(Graphics g)
{
g.drawString("HELLO WORLD",20,20);
}

Applet1.html:
/* <applet code="Applet1" width=200 height=300>
</applet>*/
12. Write a Java program to compute factorial value using Applet

. import java.applet.*;
import java.awt.event.*;
import java.awt.*;

/*<applet code="Factorial" width=500 height=500></applet> */

public class FactorialApplet extends Applet implements ActionListener


{
Label l1,l2;
TextField
t1,t2; Button
b1,b2;

public void init()


{
l1=new Label("Enter a value:
"); l2=new Label("Result:");
t1=new TextField(10);
t2=new TextField(10);
b1=new
Button("Calculate");
b2=new Button("Clear");
add(l1);
add(t1);
add(b1);
add(b2);
add(l2);
add(t2);
b1.addActionListener(this);
b2.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
int
n=Integer.parseInt(t1.getText());
int fact=1;
if(ae.getSource()==b1)
{
if(n==0||n==1)
{
fact=1;
t2.setText(String.valueOf(fact))
;
}
else

{for(int i=1;i<=n;i++) fact=fact*i; }


t2.setText(String.valueOf(fact));
}
else if(ae.getSource()==b2)
{
t1.setText("");
t2.setText("");
}
}
}
13. Write a program for passing parameters using Applet.

import java.awt.*;
import java.applet.*;

public class MyApplet extends Applet


{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}

public void paint(Graphics g)


{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}

/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
14. Write a java program that connects to a database using JDBC program:

import java.sql.Connection;
import java.sql.DriverManager;

public class PostgreSQLJDBC


{
public static void main(String args[])
{
Connection c = null;

try

Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb",
"postgres", "123");

} catch (Exception e)

{ e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);

System.out.println("Opened database successfully");


}
}
15. Write a java program to connect to database using JDBC & insert values
into table

import java.sql.*;

public class insert1


{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String fullname = "MRCET";
String email = "[email protected]";

try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();

// Inserting data in database


String q1 = "insert into userid values('" +id+ "', '" +pwd+
"', '" +fullname+ "', '" +email+ "')";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed");

con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
16. Write a java program to connect to a database using JDBC and delete values from table.

import java.sql.*;
public class delete
{
public static void main(String args[])
{
String id = "id2";
String pwd = "pwd2";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();

// Deleting from database


String q1 = "DELETE from userid WHERE id = '" +
id + "' AND pwd = '" + pwd + "'";

int x = stmt.executeUpdate(q1);

if (x > 0)
System.out.println("One User Successfully Deleted");
else
System.out.println("ERROR OCCURED :(");

con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

You might also like