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

Exam Paper Java Programs

Uploaded by

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

Exam Paper Java Programs

Uploaded by

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

Saaish Academy, Canada Corner, Nashik.

97 3051 3051
Exam-Paper Core Java Programs

Write a Java program to display all the perfect numbers between 1 to n


import java.util.Scanner;
public class Perfect
{
static boolean perfect(int num)
{
int sum = 0;
for(int i=1; i<num; i++)
{
if(num%i==0)
{
sum = sum+i;
}
}
if(sum==num)
return true;
else
return false;
}
public static void main(String[] args)
{
Scanner obj = new Scanner (System.in);
System.out.println("enter the value for n");
int n = obj.nextInt();
for(int i=1; i<=n; i++)
{
if(perfect(i))
System.out.println(i);
}
}
}

Write a Java program to calculate area of circle, Triangle and Rectangle


(Use Method over loading)

class OverloadDemo
{
void area(float x)
{
System.out.println("the area of the square is "+Math.pow(x, 2)+" sq units");
}
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

void area(float x, float y)


{
System.out.println("the area of the rectangle is "+x*y+" sq units");
}
void area(double x)
{
double z = 3.14 * x * x;
System.out.println("the area of the circle is "+z+" sq units");
}
}

class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
ob.area(5);
ob.area(11,12);
ob.area(2.5);
}
}

Write a java program to accept n integers from the user and store them
in on Arraylist collection. Display elements in reverse order
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class arrayList


{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.print("enter limit of array : ");
int num=sc.nextInt();
ArrayList<String> alist=new ArrayList<>(num);

for(int i=0;i<num;i++)
{
System.out.println("Enter "+i+" Element of ArrayList :");
String elmt=sc.next();
alist.add(elmt);
}
sc.close();
System.out.println("Orignal list :"+alist);
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

Collections.reverse(alist);
System.out.println("Reverse of a ArrayList is :"+alist);
}
}

Write a Java program to count number of digits, spaces and characters


from a file.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileCharacterCount
{
public static void main(String[] args)
{
String fileName = "your_file.txt"; // Replace with the actual file path
int digitCount = 0;
int spaceCount = 0;
int characterCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))
{
int c;
while ((c = reader.read()) != -1) {
char ch = (char) c;
if (Character.isDigit(ch)) {
digitCount++;
} else if (Character.isWhitespace(ch)) {
spaceCount++;
}
characterCount++;
}
}
catch (IOException e) {
System.err.println("An error occurred while reading the file.");
e.printStackTrace();
}
System.out.println("Digits: " + digitCount);
System.out.println("Spaces: " + spaceCount);
System.out.println("Characters: " + characterCount);
}
}
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

Write a Java program to Fibonacci series

class FibonacciExample1
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1

for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed


{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}

}
}

Write a Java program to display contents of file in reverse order.

import java.io.*;
class FileRev
{
public static void main(String[] args)throws Exception
{
int ch,n=0,i=0,b;
FileInputStream fin=new FileInputStream("abc.txt");
while((ch=fin.read())!=-1)
{
n=n+1;
//System.out.println((char)ch);
}
char str[]=new char[n];
fin.close();
FileInputStream fin1=new FileInputStream("abc.txt");
while((b=fin1.read())!=-1)
{
str[i]=(char)b;
i++;
}
for(i=n-1;i>=0;i--)
{
System.out.print(str[i]);
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

}
fin.close();
}
}

Write a Java Program using Applet to create login form

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MyApp extends Applet
{
TextField name,pass;
Button b1,b2;
public void init()
{
Label n=new Label("Name:",Label.CENTER);
Label p=new Label("password:",Label.CENTER);
name=new TextField(20);
pass=new TextField(20);
pass.setEchoChar('$');
b1=new Button("submit");
b2=new Button("cancel");
add(n);
add(name);
add(p);
add(pass);

add(b1);
add(b2);
n.setBounds(70,90,90,60);
p.setBounds(70,130,90,60);
name.setBounds(280,100,90,20);
pass.setBounds(200,140,90,20);
b1.setBounds(100,260,70,40);
b2.setBounds(180,260,70,40);
}

public void paint(Graphics g)


{
repaint();

}
}
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

What is recursion is Java? Write a Java Program to final factorial of a


given number using recursion.

public class Factorial


{

public static void main(String[] args) {


int num = 6;
long factorial = multiplyNumbers(num);
System.out.println("Factorial of " + num + " = " + factorial);
}
public static long multiplyNumbers(int num)
{
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}

Write a java program to copy the data from one file into another file.

import java.io.*;
class FileCopyPro
{
public static void main(String args[ ])
{
try
{
FileInputStream fin=new FileInputStream("abc.txt");
FileOutputStream fout=new FileOutputStream("pqr.txt");
int i;
while((i=fin.read())!=-1)
{
fout.write(i);
}
System.out.println("File Copied Successfully");
fin.close();
fout.close();
}
catch(Exception e)
{
}
}
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

Write Java program which accepts string from user, if its length is less than five,
then throw user defined exception “Invalid String” otherwise display string in
uppercase.
import java.io.*;
class MyNameException extends Exception
{
MyNameException(String msg)
{
super(msg);
}
}

class UserExcp1
{
public static void main(String args[ ])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
System.out.println("Enter Name");
s=br.readLine();
try
{
if(s.length()<6)
throw new MyNameException("Name is Invalid Exception");
else
System.out.println("Name is Valid "+s.toUpperCase());
}
catch(Exception e)
{
System.out.println("Error = "+e);
}
}
}

Program for defining Student package


package MCA;
import java.io.*;
public class Student
{
int rn,m1,m2,m3,total;
double per;
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

String name;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Student (int r,String n,int t1,int t2,int t3)
{
rn=r;
name =n;
m1=t1;
m2=t2;
m3=t3;
total=m1+m2+m3;
per=total/3;
}
}
public void display()
{
System.out.println("<========RESULT========>");
System.out.println("Roll No :"+rn);
System.out.println("Name :"+name);
System.out.println("Marks 1: "+m1);
System.out.println("Marks 2: "+m2);
System.out.println("Marks 3: "+m3);
System.out.println("Total Marks: "+total);
System.out.println("Percentage "+per+"%");
}
}

Program to implement MCA package


import MCA.*;
class StudentPkgMCA //exe class
{
public static void main(String args[])
{
Student s1=new Student(1,”ABC”,89,57,79);
s1.getdata();
s1.display();
Student s2=new Student(2,”XYZ”,85,48,99);
s2.getdata();
s2.display();
}
}

Write a Java program using AWT to display details of Customer (cust_id,


cust_name, cust_addr) from user and display it on the next frame.
import java.awt.*;
import java.awt.event.*;
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

class CustomerDetails extends Frame implements ActionListener {


Label l1, l2, l3;
TextField t1, t2, t3;
Button b;

CustomerDetails() {
l1 = new Label("Customer ID:");
l1.setBounds(50, 50, 100, 30);
t1 = new TextField();
t1.setBounds(200, 50, 150, 30);

l2 = new Label("Customer Name:");


l2.setBounds(50, 100, 100, 30);
t2 = new TextField();
t2.setBounds(200, 100, 150, 30);

l3 = new Label("Customer Address:");


l3.setBounds(50, 150, 100, 30);
t3 = new TextField();
t3.setBounds(200, 150, 150, 30);

b = new Button("Submit");
b.setBounds(200, 200, 80, 30);
b.addActionListener(this);

add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b);

setSize(400, 300);
setLayout(null);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String id = t1.getText();
String name = t2.getText();
String address = t3.getText();

DisplayCustomerDetails d = new DisplayCustomerDetails(id, name, address);


this.dispose();
}
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

public static void main(String[] args) {


new CustomerDetails();
}
}

class DisplayCustomerDetails extends Frame {


Label l1, l2, l3;

DisplayCustomerDetails(String id, String name, String address) {


l1 = new Label("Customer ID: " + id);
l1.setBounds(50, 50, 200, 30);
l2 = new Label("Customer Name: " + name);
l2.setBounds(50, 100, 200, 30);
l3 = new Label("Customer Address: " + address);
l3.setBounds(50, 150, 200, 30);

add(l1);
add(l2);
add(l3);

setSize(400, 300);
setLayout(null);
setVisible(true);
}
}

Write a Java program to reverse elements in array


class ReverseArray
{
public static void main(String[] args)
{
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--)
{
System.out.print(arr[i] + " ");
}
}
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

Write a Java program using static method which maintain bank


account information about various customers.
class Account
{
int accountNo; //account ID
double balance ;
static double rate = 0.05;
void setData(int n,double bai)
{
accountNo = n ;
balance = bai ;
}
void quarterRatecal()
{
double interest = balance * rate * 0.25 ;
balance += interest ;
}
static void modifyRate(double incr)
{
rate += incr;
System.out.println("Modified Rate of Interest : " + rate);
}
void show()
{
System.out.println("Account Number : " + accountNo);
System.out.println("Rate of Interest : " +rate);
System.out.println("Balance : "+ balance);
}
}
public class StaticMethod
{
public static void main(String[] args)
{
Account acc1 = new Account();
Account acc2 = new Account();
Account.modifyRate(0.01);
System.out.println("Customel Information......");
acc1.setData(201,1000);
acc1.quarterRatecal(); //Calculate interest
acc1.show(); //display account interest
System.out.println("Customer2 Information......");
acc1.setData(202,1000);
acc2.quarterRatecal(); //Calcuate interest
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

acc2.show(); //display account information


}
}

Define an abstract class Shape with abstract method area() and


volume().
Write a Java program to calculate area and volume of cone and
cylinder
import java.io.*;
import java.lang.*;
abstract class Shape
{
float pi=3.14f;
abstract void area();
abstract void volume();
}
class Cone extends Shape
{
int red,side,height;
Cone(int r,int s,int h)
{
red=r;
side=s;
height=h;
}
void area()
{
float a=pi*red*side;
System.out.println("Area of Cone-"+a);
}
void volume()
{
float v=pi*red*red*(height/3);
System.out.println("Volume of Cone-"+v);
}
}
class Cylinder extends Shape
{
int red ,height;
Cylinder(int r,int h)
{
red=r;
height=h;
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

}
void area()
{
float a1=2*pi*red*height+2*pi*red*red;
System.out.println("Area of Cylinder-"+a1);
}
void volume()
{
float v1=pi*red*red*height;
System.out.println("Volume of Cylinder-"+v1);
}
}
class ShapeDemo1
{
public static void main(String arg[])
{
int r,s,h;
DataInputStream din=new DataInputStream(System.in);
try
{
System.out.println("Enter the values of Redius, Side , height-");
r=Integer.parseInt(din.readLine());
s=Integer.parseInt(din.readLine());
h=Integer.parseInt(din.readLine());
Cone c1=new Cone(r,s,h);
c1.area();
c1.volume();
Cylinder c2=new Cylinder(r,h);
c2.area();
c2.volume();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

Java program to Draw a Smiley using Java Applet


Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

import java.applet.*;
import java.awt.*;
/*<applet code ="Smiley" width=600 height=600>
</applet>*/

public class Smiley extends Applet


{
public void paint(Graphics g)
{
setBackground(Color.white);
g.setColor(Color.yellow);
// Oval for face outline
g.drawOval(80, 70, 150, 150);

g.setColor(Color.BLACK); //Oval for eyes


g.fillOval(120, 120, 15, 15);
g.fillOval(170, 120, 15, 15);

// Arc for the smile


g.drawArc(130, 180, 50, 20, 180, 180);// Arc for the smile
}
}

Write a java program which accepts student details (Sid, Sname, Saddr)
from user and display it on next frame. (Use AWT).

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

class StudentDetails extends Frame


{
Label l1, l2, l3;
TextField t1, t2, t3;
Button b;

StudentDetails() {
l1 = new Label("Stud_Id");
l1.setBounds(50, 50, 100, 30);
l2 = new Label("Stud_Name");
l2.setBounds(50, 100, 100, 30);
l3 = new Label("Address");
l3.setBounds(50, 150, 100, 30);

t1 = new TextField();
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

t1.setBounds(200, 50, 100, 30);


t2 = new TextField();
t2.setBounds(200, 100, 100, 30);
t3 = new TextField();
t3.setBounds(200, 150, 100, 30);

b = new Button("Submit");
b.setBounds(100, 200, 100, 30);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
new DisplayFrame(t1.getText(), t2.getText(), t3.getText());
}
});

add(l1);
add(l2);
add(l3);
add(t1);
add(t2);
add(t3);
add(b);

setSize(400, 400);
setLayout(null);
setVisible(true);
}

public static void main(String[] args)


{
new StudentDetails();
}
}

class DisplayFrame {
DisplayFrame(String sid, String sname, String saddr) {
Frame f = new Frame();
Label l1 = new Label("Sid: " + sid);
l1.setBounds(50, 50, 100, 30);
Label l2 = new Label("Sname: " + sname);
l2.setBounds(50, 100, 100, 30);
Label l3 = new Label("Saddr: " + saddr);
l3.setBounds(50, 150, 100, 30);

f.add(l1);
f.add(l2);
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

f.add(l3);

f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
}

Write a java program to count number of Lines, words and


characters from a given file.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class WordCharLineCountInFile


{
public static void main(String[] args)
{
BufferedReader reader = null;
int charCount = 0;
int wordCount = 0;
int lineCount = 0;

try
{
reader = new BufferedReader(new FileReader("test.txt"));
String currentLine = reader.readLine();
while (currentLine != null)
{
lineCount++;
String[] words = currentLine.split(" ");
wordCount = wordCount + words.length;

for (String word : words)


{
charCount = charCount + word.length();
}
currentLine = reader.readLine();
}
System.out.println("Number of character in file : "+charCount);
System.out.println("Number of words in a file : "+wordCount);
System.out.println("Number of lines in file : "+lineCount);
}
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}

Create a class Teacher (Tid, Tname, Designation, Salary, Subject).


Write a java program to accept 'n' teachers and display who teach
Java subject (Use Array of object)
 Code from chat GPT
import java.util.Scanner;

class Teacher
{
int tid;
String tname;
String designation;
double salary;
String subject;

// Constructor
Teacher(int tid, String tname, String designation, double salary, String subject) {
this.tid = tid;
this.tname = tname;
this.designation = designation;
this.salary = salary;
this.subject = subject;
}

// Method to display teacher details


void display() {
System.out.println("ID: " + tid + ", Name: " + tname + ", Designation: " + designation
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

+ ", Salary: " + salary + ", Subject: " + subject);


}
}

public class MainPro


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of teachers: ");


int n = sc.nextInt();
sc.nextLine(); // Consume the newline

// Create an array to store Teacher objects


Teacher[] teachers = new Teacher[n];

// Accept details for each teacher


for (int i = 0; i < n; i++)
{
System.out.println("Enter details for Teacher " + (i + 1) + ":");
System.out.print("Enter ID: ");
int tid = sc.nextInt();
sc.nextLine(); // Consume the newline
System.out.print("Enter Name: ");
String tname = sc.nextLine();
System.out.print("Enter Designation: ");
String designation = sc.nextLine();
System.out.print("Enter Salary: ");
double salary = sc.nextDouble();
sc.nextLine(); // Consume the newline
System.out.print("Enter Subject: ");
String subject = sc.nextLine();

// Create a Teacher object and add it to the array


teachers[i] = new Teacher(tid, tname, designation, salary, subject);
}

// Display teachers who teach Java


System.out.println("\nTeachers who teach Java:");
boolean found = false;
for (Teacher teacher : teachers)
{
if (teacher.subject.equalsIgnoreCase("Java")) {
teacher.display();
found = true;
}
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

}
if (!found) {
System.out.println("No teachers found who teach Java.");
}
sc.close();
}
}

You might also like