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

Q1: Write a program to display all prime numbers from 1 to N.

Program:
package college;

import java.util.Scanner;

public class Prime {


public static void main(String[] args) {
int i, n, counter,j;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the n value: ");
n = scanner.nextInt();
System.out.print("Prime numbers between 1 to N are :");
for(j=2; j<=n ; j++) {
counter = 0;
for(i=1;i<=j;i++) {
if(j % i <= 0) {
counter++;
}
}
if(counter == 2) {
System.out.print(j+" ");
}
}
}

Output:
Enter the n value: 135
Prime numbers between 1 to N are :2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59
61 67 71 73 79 83 89 97 101 103 107 109 113 127 131

//

//

Q2: Write a program to check leap year.


Program:
package college;

import java.util.Scanner;

public class leapyear {

public static void main(String[] args) {

int year;
System.out.println("Enter an year: ");
Scanner scanner = new Scanner(System.in);
year = scanner.nextInt();

if(((year % 4 == 0) && (year % 100 !=0 )) || (year % 400 == 0)) {


System.out.print("Specified year is a leap year ");
}else {
System.out.print("Specified year is a not leap year ");
}

Output:
Enter an year:
2035
Specified year is a not leap year

//

//

Q3: Write a program to create simple interest and input by the user.
Program:
package college;

import java.util.Scanner;

public class simpleinterest {

public static void main(String[] args) {


float p,r,t,sinterest;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the principal: ");
p = scan.nextInt();
System.out.print("Enter the Rate of Interest: ");
r = scan.nextInt();
System.out.print("Enter the Time Period: ");
t = scan.nextInt();
sinterest = (p*r*t)/100;
System.out.print("Simple Interest is = " +sinterest);
}
}

Output:
Enter the principal: 2500
Enter the Rate of Interest: 4
Enter the Time Period: 2
Simple Interest is = 200.0
Q4: Write a program to create simple class to find out the area and
perimeter of rectangle and box using this and super keyword.
Program:
package college;

import java.util.Scanner;

public class rect {


int l = 20, b = 40;
}

class area_rect extends rect {


int l=50, b = 60, p,a ;
void add()
{
p = 2 * (super.l + super.b);
System.out.println("Perimeter of rectangle :" +p);

a =this.l * this.b;
System.out.println("Area of rectangle :" +a);

}
public static void main(String[] args)
{
area_rect a = new area_rect();
a.add();
}

Output:
Perimeter of rectangle :120
Area of rectangle :3000

Q5: Write a program for Binary to Octal Conversion.-


Program:
package college;

public class binary {


public static void main(String[] args) {
long binary = 110001;
int octal = convertBinarytoOctal(binary);
System.out.println(binary + " in binary = " + octal + " in
octal");
}

public static int convertBinarytoOctal(long binaryNumber) {


int octalNumber = 0, decimalNumber = 0, i = 0;
while (binaryNumber != 0) {
decimalNumber += (binaryNumber % 10) * Math.pow(2, i);
++i;
binaryNumber /= 10;
}

i = 1;

while (decimalNumber != 0) {
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}

return octalNumber;
}

Output:
110001 in binary = 61 in octal

Q6: Write a program for Octal to Decimal Conversion.


Program:
package college;

public class octal {

public static void main(String[] args) {


int decimal = 98;
int octal = convertDecimalToOctal(decimal);
System.out.printf("%d in decimal = %d in octal", decimal, octal);
}

public static int convertDecimalToOctal(int decimal)


{
int octalNumber = 0, i = 1;

while (decimal != 0)
{
octalNumber += (decimal % 8) * i;
decimal /= 8;
i *= 10;
}

return octalNumber;
}
}
Output:
98 in decimal = 142 in octal
Q7: Write a program to print pyramid star pattern.
Program:
package college;

public class star {


public static void main(String[] args) {

for (int i=0; i<5; i++) {


for (int j=0; j<5-i ; j++) {
System.out.print(" ");
}
for (int k=0; k<=i; k++) {
System.out.print("*");
}
System.out.println();
}

}
}

Output:
*
* *
* * *
* * * *
* * * * *

Q8: Write a program to print reverse pyramid star pattern.


Program:
package college;

public class star_rev {


public static void main(String[] args) {

for (int i=0; i<=5; i++) {


for (int k=0; k<=i ; k++) {
System.out.print(" ");
}
for (int j=5 ; j>i ; j--) {
System.out.print("*");
}
System.out.println();
}

}
}

Output:
* * * * *
* * * *
* * *
* *
*

Q9: Write a program to design a class account using the inheritance


and static that show all functions of bank.
Program:
package college;

public class bank {

String name;
float bal;
String account_type;
bank( String name,float bal,String account_type){
this.name=name;
this.bal=bal;
this.account_type=account_type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getBal() {
return bal;
}
public void setBal(float bal) {
this.bal = bal;
}
public String getAccount_type() {
return account_type;
}
public void setAccount_type(String account_type) {
this.account_type = account_type;
}
}
class Account extends bank{
Account(String name, float bal, String account_type) {
super(account_type, bal, account_type);
}
public void witdraw(int amt) {
if(super.bal>=amt) {
float withdraw=super.bal-amt;
super.setBal(withdraw);
System.out.println("amout reaming after withdraw " +getBal());
}else {
System.out.println("low balance");
}
}
public void deposite(int amt) {
float deposite= super.bal+amt;
super.setBal(deposite);
System.out.println(getBal());
}
public static void main(String[] args) {
Account obj= new Account("RAM", 5000, "saving");
obj.witdraw(500);
obj.deposite(5000);
}

Output:
amout reaming after withdraw 4500.0
9500.0

Q10: Write a program to find the factorial of a given number using


recursion.

Program:
package college;

import java.util.Scanner;

public class factorial {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number: ");
int n = sc.nextInt();
int Fact = 1;
for(int i=1;i<=n;i++)
{
Fact = Fact *i;
}
System.out.print("The factorial is: " +Fact);

}
}

Output:
Enter the number: 8
The factorial is: 40320

//
Q11: Write a program to design a class using abstract methods and
classes.
Program:
package college;

abstract class abstract_method


{
abstract int display(int b, String a);
}
public class abstract_mainf extends abstract_method {
int display(int b, String a) {
System.out.println("WELCOME " +a+ " " +b);
return b;
}
public static void main(String[] args) {
abstract_mainf ab = new abstract_mainf();
ab.display(0, "World");
}
}

Output:
WELCOME World 0

Q12: Write a program to design a string class that perform string


method. (Equal, Reverse, Change Case)
Program:
package college;

public class String_method {


String first = "Hello";
String first1 = "Welcome";
String second = "world";
public void equal() {
if (first.endsWith(first)) {
System.out.println("Equal");
}
}
public void reverse() {
StringBuilder sb = new StringBuilder(first);
System.out.println(sb.reverse());
}
public void uppercase() {
System.out.println(first.toUpperCase());
System.out.println(second.toUpperCase());
}
public void lowercase() {
System.out.println(first.toLowerCase());
System.out.println(second.toLowerCase());
}
public static void main(String[] args) {
String_method obj = new String_method();
obj.equal();
obj.reverse();
obj.uppercase();
obj.lowercase();
}

Output:
Equal
olleH
HELLO
WORLD
hello
world

Q13: Write a program to check if two arrays are equal or not.


Program:
package college;

import java.util.Arrays;

public class array_equalf {

public static void main (String[] args)


{
int a[] = {30,31,32,33,34,35};
int b[] = {29,30,32,33,34,43};
boolean result = Arrays.equals(a,b);
if (result == true) {
System.out.println("Arrays are equal.");
}else {
System.out.println("Arrays are not equal.");
}
}

Output:
Arrays are not equal.

Q14: Write a program to remove all occurrences of an element in an


array.
Program:
package college;
public class occ {
public static void main(String[] args) {
int a[] = {5,15,25,35,45,55,65,75,85};
int val = 5;
int count = 0;
int copy[] = new int [a.length];
for (int i =0; i<a.length; i++ ) {
if (val != a[i]) {
copy[i] = a[i];
}
}
for (int k =0; k<a.length; k++) {
System.out.print(copy[k] +" ");
}
}
}

Output:
0 15 25 35 45 55 65 75 85

Q15: Write a program to find common array element.


Program:
package college;

public class common {

public static void main(String[] args) {


int[] arr1 = {3, 10, 1, 0, 9};
int[] arr2 = {32, 5, 10, 6, 9, 1};
for(int i = 0; i < arr1.length; i++){
for(int j = 0; j < arr2.length; j++){
if(arr1[i] == arr2[j]){
System.out.print(arr1[i] + " ");
break;
}
}
}
}
}

Output:
10 1 9

Q16: Write a program to copy all the elements of one array to another
array.
Program:
package college;
public class copy_array {

public static void main(String args[]){


int a[]={10,20,30,40,50,60,70};
int b[]=new int[a.length];
//copying one array to another
for(int i=0;i<a.length;++i){
b[i]=a[i];
}

for(int j=0;j<b.length;j++){
System.out.print(b[j]+" ");
}
}

}
Output:
10 20 30 40 50 60 70

Q17: Write a program to handle the exception using try and multiple
catch block.
Program:
package college;

public class multiple_catch {

public static void main(String[] args) {


try{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception
occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
Q18: Write a program that implement the nested try statements.
Program:
package college;

public class nestedtry {


public static void main(String[] args) {
try{
int a[]= {15,25,35,45,55};
System.out.println(a[5]);
try{
int x = a[2]/0;
}catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
System.out.println("Element at such index does not exists");
}
}

}
Output:
ArrayIndexOutOfBounds Exception occurs
Element at such index does not exists

Q19: Write a program to create a package that access the member of


external class as well as same package
Program:
package demo;
public class Hello {
protected String name="hello world";
protected void display() {
System.out.println("demo package");
System.out.println(name);
}
}
package practical1.java;
public class Test {
void m1() {
System.out.println("same package");
}
}
package practical1.java;
import demo.*;
public class Q19 extends Hello{
public static void main(String[] args) {
Q19 obj=new Q19();
obj.display();
Test t1=new Test();
t1.m1();
}
}

Q20: Write a program to handle divide by zero and multiple


exceptions.
Program:
package college;

public class divide {


public static void main(String[] args) {
int a = 13;
try {
int sum = a/0;
System.out.println(sum);
}
catch(Exception e)
{

e.printStackTrace();
System.out.println("Divide by zero");
}
}
}
Output:
Divide by zero

Q21: Thread Life-Cycle Methods


a. Start() method
b. Run() method.
Program:
package college;

public class practical_thread extends Thread{


public void run() {
for (int i=0;i<=5;i++)
{
System.out.println(i+": hello World");
}
}
public static void main(String[] args) {
practical_thread a = new practical_thread();
a.start();
for (int j=0;j<=5;j++)
{
System.out.println(j+": New World");
}
}
}

Output:
0: New World
1: New World
2: New World
3: New World
4: New World
5: New World
0: hello World
1: hello World
2: hello World
3: hello World
4: hello World
5: hello World

Q22: Write a program that import the user define Package and access
the member variable of classes that combined by Package.
Program:
Combine1.java
package college;

public class combine1 {


protected String name="hello world";
protected void display() {
System.out.println("college package");
System.out.println(name);
}
}
Combine2.java
package college;

public class combine2 extends combine1{


public static void main(String[] args) {
combine2 obj=new combine2();
obj.display();
}
}

Output: (Run Combine2.java)


college package
hello world

Q23: Write a program to handle the user defined exception using


throw keyword.
Program:
package college;

import java.util.Scanner;

public class practical_throw {

void age(int age) throws InvalidAgeException{


if(age<=17) {
throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}
public static void main(String[] args) {
practical_throw obj=new practical_throw();
try {
obj.age(18);
} catch (InvalidAgeException e) {
e.printStackTrace();
}
}

}
Output:
welcome to vote
Q24: Write a program to create a thread that implement the runnable
interface.
package college;

public class prac_runnableint implements Runnable {


public void run() {
System.out.println("Implements Runnable");
}
public static void main(String[] args) {
prac_runnableint obj=new prac_runnableint();
Thread t1=new Thread(obj);
t1.start();
}

Output:
Implements Runnable

Q25: Write a program to implement interthread communication.


Program:
package college;

public class interthread {


int amount = 10000;
synchronized void withdraw(int amount) {
System.out.println("Going to withdraw");
if (this.amount<amount) {
System.out.println("Less balance; Waiting for Deposit");
try {
wait();
}catch(Exception e){}
}

this.amount -= amount;
System.out.println("Withdraw Completed");
}
synchronized void deposit(int amount) {
System.out.println("Going to Deposit");
this.amount += amount;
System.out.println("Deposit Completed");
notify();
}
}
class interthread1
{
public static void main(String[] args) {
final interthread c = new interthread();
new Thread()
{
- public void run() {
c.withdraw(15000);
}
}.start();
new Thread() {
public void run() {
c.deposit(15000);
}
}.start();
}
}

Output:
Going to withdraw
Less balance; Waiting for Deposit
Going to Deposit
Deposit Completed
Withdraw Completed

Internal Practical Program:


Q: Write a java program to join threads.
Program:
package college;

import java.io.*;

class ThreadJoining extends Thread


{
@Override
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
Thread.sleep(500);
System.out.println("Current Thread: "
+ Thread.currentThread().getName());
}
catch(Exception ex)
{
System.out.println("Exception has" +
" been caught" + ex);
}
System.out.println(i);
}
}
}
class practical
{
public static void main (String[] args)
{

// creating two threads


ThreadJoining t1 = new ThreadJoining();
ThreadJoining t2 = new ThreadJoining();
ThreadJoining t3 = new ThreadJoining();

// thread t1 starts
t1.start();

// starts second thread after when


// first thread t1 has died.
try
{
System.out.println("Current Thread: "
+ Thread.currentThread().getName());
t1.join();
}

catch(Exception ex)
{
System.out.println("Exception has " +
"been caught" + ex);
}

// t2 starts
t2.start();

// starts t3 after when thread t2 has died.


try
{
System.out.println("Current Thread: "
+ Thread.currentThread().getName());
t2.join();
}

catch(Exception ex)
{
System.out.println("Exception has been" +
" caught" + ex);
}

t3.start();
}
}

Output:
Current Thread: main
Current Thread: Thread-0
0
Current Thread: Thread-0
1
Current Thread: main
Current Thread: Thread-1
0
Current Thread: Thread-1
1
Current Thread: Thread-2
0
Current Thread: Thread-2
1
Q: Write a program of database connectivity using JDBC & ODBC
Drivers.
Program:
package college;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class jdbcodbcexample {

public static void main(String args[])


{
Connection con = null;
PreparedStatement stmt = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:swing");
String sql ="INSERT INTO employee (name, rollNo, course, subject,
marks) VALUES" + "('RAM', 10, 'MCA', 'Computer Science', 85)";
stmt = con.prepareStatement(sql);
int i = stmt.executeUpdate();
if(i > 0 )
{
System.out.println("Record Added Into Table Successfully.");
}
} catch (SQLException sqle) {
System.out.println(sqle.getNextException());
} catch (ClassNotFoundException e) {
System.out.println(e.getException());
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
System.out.println(e);
}
}
}
}
Q: Using AWT, write a program to create two buttons labelled ‘A’
and ‘B’. When button ‘A’ is pressed, it displays your personal
information (Name, Course, Roll No, College) and when button ‘B’ is
pressed, it displays your CGPA in previous semester.
Program:

/**** Main.java ****/


import java.awt.*;
import java.awt.event.*;
public class Main extends Frame implements ActionListener {
Button btnInfo, btnCGPA;
Main() {
super("Student Details");
btnInfo = new Button("A");
btnInfo.setBounds(25, 125, 450, 100);
btnInfo.addActionListener(this);
this.add(btnInfo);
btnCGPA = new Button("B");
btnCGPA.setBounds(25, 300, 450, 100);
btnCGPA.addActionListener(this);
this.add(btnCGPA);
this.setSize(500, 500);
this.setLayout(null);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public static void main(String[] args) {
new Main();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnInfo) {
new Information(
"SUDIPTO GHOSH",
"BSc (Hons) Computer Science",
"19/78003",
"ARSD College"
);
} else if (e.getSource() == btnCGPA) {
new CGPA("9.73");
}
}
}

//
/**** Information.java ****/
import java.awt.*;
import java.awt.event.*;
class Information extends Frame {
Button btnClose;
Panel panelForm;
Label labelName, labelCourse, labelRollNo, labelCollege;
TextField fieldName, fieldCourse, fieldRollNo, fieldCollege;
Information(String name, String course, String rollNo, String college) {
super("Personal Information");
labelName = new Label("Name:");
labelName.setBounds(20, 20, 80, 30);
labelCourse = new Label("Course:");
labelCourse.setBounds(20, 50, 80, 30);
labelRollNo = new Label("Roll No.:");
labelRollNo.setBounds(20, 80, 80, 30);
labelCollege = new Label("College:");
labelCollege.setBounds(20, 110, 80, 30);
fieldName = new TextField(name);
fieldName.setBounds(100, 22, 200, 24);
fieldName.setEditable(false);
fieldCourse = new TextField(course);
fieldCourse.setBounds(100, 52, 200, 24);
fieldCourse.setEditable(false);
fieldRollNo = new TextField(rollNo);
fieldRollNo.setBounds(100, 82, 200, 24);
fieldRollNo.setEditable(false);
fieldCollege = new TextField(college);
fieldCollege.setBounds(100, 112, 200, 24);
fieldCollege.setEditable(false);
btnClose = new Button("Close");
btnClose.setBounds(100, 150, 125, 30);
btnClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
panelForm = new Panel();
panelForm.setLayout(null);
panelForm.add(labelName);
panelForm.add(fieldName);
panelForm.add(labelCourse);
panelForm.add(fieldCourse);
panelForm.add(labelRollNo);
panelForm.add(fieldRollNo);
panelForm.add(labelCollege);
panelForm.add(fieldCollege);
panelForm.add(btnClose);
this.add(panelForm);
this.setSize(350, 250);
this.setVisible(true);
this.setLayout(null);
this.setLocationRelativeTo(null);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
}

//
//

/**** CGPA.java ****/


import java.awt.*;
import java.awt.event.*;
class CGPA extends Frame {
Label l;
Button btnClose;
CGPA(String cgpa) {
super("Previous Year CGPA");
l = new Label("Your CGPA was: " + cgpa);
l.setBounds(10, 50, 280, 30);
l.setAlignment(Label.CENTER);
btnClose = new Button("Close");
btnClose.setBounds(20, 85, 260, 30);
btnClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
this.add(l);
this.add(btnClose);
this.setSize(300, 150);
this.setLayout(null);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
}

Q: jsp program to validate username and password


Program:
Login.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>User Details</h1>
<%-- The form data will be passed to acceptuser.jsp
for validation on clicking submit
--%>
<form method ="get" action="acceptuser.jsp">
Enter Username : <input type="text" name="user"><br/><br/>
Enter Password : <input type="password" name ="pass"><br/>
<input type ="submit" value="SUBMIT">
</form>
</body>
</html>

acceptuser.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Accept User Page</title>

</head>

<body>

<h1>Verifying Details</h1>

<%-- Include the ValidateUser.java class whose method

boolean validate(String, String) we will be using

--%>

<%-- Create and instantiate a bean and assign an id to

uniquely identify the action element throughout the jsp

--%>

<jsp:useBean id="snr" class="saagnik.ValidateUser"/>

<%-- Set the value of the created bean using form data --%>

<jsp:setProperty name="snr" property="user"/>

<jsp:setProperty name="snr" property="pass"/>

<%-- Display the form data --%>

The Details Entered Are as Under<br/>

<p>Username : <jsp:getProperty name="snr" property="user"/></p>

<p>Password : <jsp:getProperty name="snr" property="pass"/></p>

<%-- Validate the user using the validate() of

ValidateUser.java class

--%>
<%if(snr.validate("GeeksforGeeks", "GfG")){%>

Welcome! You are a VALID USER<br/>

<%}else{%>

Error! You are an INVALID USER<br/>

<%}%>

</body>

</html>

The ValidateUser.java class


package saagnik;

import java.io.Serializable;

public class ValidateUser implements Serializable {

private String user, pass;

// Methods to set username and password

// according to form data

public void setUser(String u1) { this.user = u1; }

public void setPass(String p1) { this.pass = p1; }

// Methods to obtain back the values set

// by setter methods

public String getUser() { return user; }

public String getPass() { return pass; }

// Method to validate a user

public boolean validate(String u1, String p1)

if (u1.equals(user) && p1.equals(pass))

return true;

else

return false;

You might also like