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

Core Java Exam Paper Solutions

Uploaded by

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

Core Java Exam Paper Solutions

Uploaded by

anymanyviral
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 [Link];
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 ([Link]);
[Link]("enter the value for n");
int n = [Link]();
for(int i=1; i<=n; i++)
{
if(perfect(i))
[Link](i);
}
}
}

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


(Use Method over loading)

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

void area(float x, float y)


{
[Link]("the area of the rectangle is "+x*y+" sq units");
}
void area(double x)
{
double z = 3.14 * x * x;
[Link]("the area of the circle is "+z+" sq units");
}
}

class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
[Link](5);
[Link](11,12);
[Link](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 [Link];
import [Link];
import [Link];

public class arrayList


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

for(int i=0;i<num;i++)
{
[Link]("Enter "+i+" Element of ArrayList :");
String elmt=[Link]();
[Link](elmt);
}
[Link]();
[Link]("Orignal list :"+alist);
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

[Link](alist);
[Link]("Reverse of a ArrayList is :"+alist);
}
}

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


from a file.

import [Link];
import [Link];
import [Link];
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 = [Link]()) != -1) {
char ch = (char) c;
if ([Link](ch)) {
digitCount++;
} else if ([Link](ch)) {
spaceCount++;
}
characterCount++;
}
}
catch (IOException e) {
[Link]("An error occurred while reading the file.");
[Link]();
}
[Link]("Digits: " + digitCount);
[Link]("Spaces: " + spaceCount);
[Link]("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;
[Link](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;
[Link](" "+n3);
n1=n2;
n2=n3;
}

}
}

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

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

}
[Link]();
}
}

Write a Java Program using Applet to create login form

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

add(b1);
add(b2);
[Link](70,90,90,60);
[Link](70,130,90,60);
[Link](280,100,90,20);
[Link](200,140,90,20);
[Link](100,260,70,40);
[Link](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);
[Link]("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 [Link].*;
class FileCopyPro
{
public static void main(String args[ ])
{
try
{
FileInputStream fin=new FileInputStream("[Link]");
FileOutputStream fout=new FileOutputStream("[Link]");
int i;
while((i=[Link]())!=-1)
{
[Link](i);
}
[Link]("File Copied Successfully");
[Link]();
[Link]();
}
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 [Link].*;
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([Link]));
String s;
[Link]("Enter Name");
s=[Link]();
try
{
if([Link]()<6)
throw new MyNameException("Name is Invalid Exception");
else
[Link]("Name is Valid "+[Link]());
}
catch(Exception e)
{
[Link]("Error = "+e);
}
}
}

Program for defining Student package


package MCA;
import [Link].*;
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([Link]));
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()
{
[Link]("<========RESULT========>");
[Link]("Roll No :"+rn);
[Link]("Name :"+name);
[Link]("Marks 1: "+m1);
[Link]("Marks 2: "+m2);
[Link]("Marks 3: "+m3);
[Link]("Total Marks: "+total);
[Link]("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);
[Link]();
[Link]();
Student s2=new Student(2,”XYZ”,85,48,99);
[Link]();
[Link]();
}
}

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 [Link].*;
import [Link].*;
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:");
[Link](50, 50, 100, 30);
t1 = new TextField();
[Link](200, 50, 150, 30);

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


[Link](50, 100, 100, 30);
t2 = new TextField();
[Link](200, 100, 150, 30);

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


[Link](50, 150, 100, 30);
t3 = new TextField();
[Link](200, 150, 150, 30);

b = new Button("Submit");
[Link](200, 200, 80, 30);
[Link](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 = [Link]();
String name = [Link]();
String address = [Link]();

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


[Link]();
}
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);
[Link](50, 50, 200, 30);
l2 = new Label("Customer Name: " + name);
[Link](50, 100, 200, 30);
l3 = new Label("Customer Address: " + address);
[Link](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};
[Link]("Original array: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}
[Link]();
[Link]("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = [Link]-1; i >= 0; i--)
{
[Link](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;
[Link]("Modified Rate of Interest : " + rate);
}
void show()
{
[Link]("Account Number : " + accountNo);
[Link]("Rate of Interest : " +rate);
[Link]("Balance : "+ balance);
}
}
public class StaticMethod
{
public static void main(String[] args)
{
Account acc1 = new Account();
Account acc2 = new Account();
[Link](0.01);
[Link]("Customel Information......");
[Link](201,1000);
[Link](); //Calculate interest
[Link](); //display account interest
[Link]("Customer2 Information......");
[Link](202,1000);
[Link](); //Calcuate interest
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

[Link](); //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 [Link].*;
import [Link].*;
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;
[Link]("Area of Cone-"+a);
}
void volume()
{
float v=pi*red*red*(height/3);
[Link]("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;
[Link]("Area of Cylinder-"+a1);
}
void volume()
{
float v1=pi*red*red*height;
[Link]("Volume of Cylinder-"+v1);
}
}
class ShapeDemo1
{
public static void main(String arg[])
{
int r,s,h;
DataInputStream din=new DataInputStream([Link]);
try
{
[Link]("Enter the values of Redius, Side , height-");
r=[Link]([Link]());
s=[Link]([Link]());
h=[Link]([Link]());
Cone c1=new Cone(r,s,h);
[Link]();
[Link]();
Cylinder c2=new Cylinder(r,h);
[Link]();
[Link]();
}
catch(Exception e)
{
[Link]([Link]());
}
}
}

Java program to Draw a Smiley using Java Applet


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

import [Link].*;
import [Link].*;
/*<applet code ="Smiley" width=600 height=600>
</applet>*/

public class Smiley extends Applet


{
public void paint(Graphics g)
{
setBackground([Link]);
[Link]([Link]);
// Oval for face outline
[Link](80, 70, 150, 150);

[Link]([Link]); //Oval for eyes


[Link](120, 120, 15, 15);
[Link](170, 120, 15, 15);

// Arc for the smile


[Link](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 [Link].*;
import [Link].*;

class StudentDetails extends Frame


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

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

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

[Link](200, 50, 100, 30);


t2 = new TextField();
[Link](200, 100, 100, 30);
t3 = new TextField();
[Link](200, 150, 100, 30);

b = new Button("Submit");
[Link](100, 200, 100, 30);
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
new DisplayFrame([Link](), [Link](), [Link]());
}
});

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);
[Link](50, 50, 100, 30);
Label l2 = new Label("Sname: " + sname);
[Link](50, 100, 100, 30);
Label l3 = new Label("Saddr: " + saddr);
[Link](50, 150, 100, 30);

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

[Link](l3);

[Link](400, 400);
[Link](null);
[Link](true);
}
}

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


characters from a given file.

import [Link];
import [Link];
import [Link];

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("[Link]"));
String currentLine = [Link]();
while (currentLine != null)
{
lineCount++;
String[] words = [Link](" ");
wordCount = wordCount + [Link];

for (String word : words)


{
charCount = charCount + [Link]();
}
currentLine = [Link]();
}
[Link]("Number of character in file : "+charCount);
[Link]("Number of words in a file : "+wordCount);
[Link]("Number of lines in file : "+lineCount);
}
Saaish Academy, Canada Corner, Nashik. 97 3051 3051
Exam-Paper Core Java Programs

catch (IOException e)
{
[Link]();
}
finally
{
try
{
[Link]();
}
catch (IOException e)
{
[Link]();
}
}
}
}

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 [Link];

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

// Constructor
Teacher(int tid, String tname, String designation, double salary, String subject) {
[Link] = tid;
[Link] = tname;
[Link] = designation;
[Link] = salary;
[Link] = subject;
}

// Method to display teacher details


void display() {
[Link]("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([Link]);

[Link]("Enter the number of teachers: ");


int n = [Link]();
[Link](); // 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++)
{
[Link]("Enter details for Teacher " + (i + 1) + ":");
[Link]("Enter ID: ");
int tid = [Link]();
[Link](); // Consume the newline
[Link]("Enter Name: ");
String tname = [Link]();
[Link]("Enter Designation: ");
String designation = [Link]();
[Link]("Enter Salary: ");
double salary = [Link]();
[Link](); // Consume the newline
[Link]("Enter Subject: ");
String subject = [Link]();

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


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

// Display teachers who teach Java


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

}
if (!found) {
[Link]("No teachers found who teach Java.");
}
[Link]();
}
}

Common questions

Powered by AI

Java's file I/O operations allow programs to read from and write to files, providing essential data management capabilities. The source includes examples of reversing file contents and copying one file's data to another. Reversing contents involves reading file data into an array and outputting it in reverse order, showcasing direct manipulation of file data. Copying entails reading and writing byte streams from one file to another, illustrating basic I/O operations' practicality in data handling tasks. The I/O capabilities in Java are powerful for developing applications that require persistent storage or data transfer functionalities .

Java Applets are small Java programs that run within a web browser environment, as opposed to standalone Java applications that run directly on the Java Virtual Machine (JVM). The source provides an example of a Java Applet used to create a login form, highlighting graphical component use and event handling typical in applets. Applets are often used for interactive features in web applications but have become less common due to security concerns and the advancement of other technologies like JavaScript and HTML5 .

Recursion allows a function to call itself, enabling solutions to problems that can be broken into similar sub-problems. This concept is effectively utilized in the source's example of calculating a factorial, where the function `multiplyNumbers` calls itself with decremented values until reaching the base case. Recursive solutions can simplify coding and enhance readability, although they can also lead to performance inefficiencies due to function call overhead and stack use .

Encapsulation is a fundamental object-oriented programming principle that involves bundling the data (variables) and methods that operate on the data into a single unit, or class, and restricting access to some of the object's components. The class `Teacher` from the source encapsulates its attributes such as `tid`, `tname`, and methods that operate on these attributes. By controlling access through methods, encapsulation protects the integrity of the data, restricts direct access which prevents accidental interference and provides a clear modular structure, enhancing maintainability and flexibility .

Method overloading in Java occurs when multiple methods have the same name but different parameters (different type or number of parameters). An example from the source is from the class `OverloadDemo` where the method `area` is overloaded. There are three versions of `area`: one takes a single float parameter for square area calculation, another takes two float parameters for rectangle area calculation, and a third takes a single double parameter for circle area calculation .

AWT, or Abstract Window Toolkit, provides a platform-independent way to create graphical user interfaces in Java. The application of AWT in the source is demonstrated by managing customer details such as ID, name, and address. This involves creating input fields and a submit button using AWT components, allowing interaction through graphical elements which are displayed in a frame window. AWT is essential for GUI-based applications but has largely been replaced by more advanced frameworks like Swing .

An abstract class in Java, like `Shape` from the source, is used to define a template for other classes. It cannot be instantiated on its own but provides a base set of methods that derived classes must implement, enforcing a uniform interface. The `Shape` class defines abstract methods `area` and `volume` that are implemented by subclasses `Cone` and `Cylinder` to perform specific calculations based on their geometrical formulas. This approach allows for polymorphic behavior where different shapes can be managed through the common superclass `Shape` .

Exception handling in Java is vital for managing errors and ensuring program stability. The source includes a custom exception `MyNameException` which is thrown if a user-input string is less than five characters long. Custom exceptions provide the advantage of specialized error handling by allowing specific conditions to trigger exceptions, making debugging easier and more intuitive. Moreover, it illustrates encapsulating common error handling logic and allowing for cleaner program code by separating error management from main logic .

In Java, the `ArrayList` is a resizable array that is part of the Collections framework. The source demonstrates using an `ArrayList` to store integers input by the user, then using the `Collections.reverse` method to reverse the order of elements in the list. This flexibility of `ArrayList` and the utility methods provided by `Collections` make it easy to manipulate data within lists without explicitly coding tedious operations .

Multithreading in Java refers to concurrent execution of multiple threads (smaller units of a process). It improves applications by maximizing CPU utilization, enabling simultaneous execution of tasks, and enhancing performance and responsiveness. For instance, in a server application handling multiple client requests, each request can be handled by a separate thread, allowing parallel processing. This ensures that even while waiting for network operations, other threads can proceed with independent tasks, thus optimizing resource usage and improving throughput.

You might also like