Solved T.Y. B.B.A. (Computer Application) CA-503: Core Java (2019 Pattern) Exam Paper
Q1) Attempt any Eight:
a) What is JDK? How to build and run a Java program?
JDK (Java Development Kit): JDK is a software development kit used to develop Java applications. It includes the Java Runtime Environment (JRE) and development tools like the Java compiler (javac), Java debugger (jdb), and other utilities.
Steps to build and run a Java program:
- Write your Java code in a text editor (e.g., Notepad) and save it with a
.java
extension (e.g.,HelloWorld.java
). - Open a command prompt and navigate to the directory where the file is saved.
- Compile the Java code using the Java compiler:
javac HelloWorld.java
- Run the compiled program using the Java interpreter:
java HelloWorld
b) Explain Static keyword.
Static keyword in Java: The static
keyword is used to create class-level members (variables and methods) that are shared among all instances of the class. A static variable is initialized only once when the class is loaded into memory. Static methods can be called without creating an instance of the class.
Example:
class MyClass {
static int count = 0;
static void increment() {
count++;
}
}
c) What is use of classpath?
Classpath: Classpath is an environment variable used by the Java runtime system to locate classes and libraries. It is a path to the directory or jar file containing Java classes that are needed for running a Java application.
d) What is collection? Explain collection framework in detail.
Collection in Java: A collection is a group of objects. The collection framework in Java provides classes and interfaces that handle different types of collections such as lists, sets, and maps.
Collection Framework:
- List: Ordered collection (e.g., ArrayList, LinkedList).
- Set: Unordered collection that does not allow duplicate elements (e.g., HashSet, TreeSet).
- Map: Collection of key-value pairs (e.g., HashMap, TreeMap).
e) What is the use of Reader and Writer class?
Reader and Writer classes:
- Reader: These are used to read data in the form of characters (e.g., FileReader, BufferedReader).
- Writer: These are used to write data in the form of characters (e.g., FileWriter, BufferedWriter).
f) What is the use of layout manager?
Layout Manager: A layout manager is used in Java to organize components (like buttons, text fields, etc.) within a container (like JFrame or JPanel) in a particular layout. Examples include FlowLayout
, BorderLayout
, GridLayout
.
g) What is the difference between paint() and repaint()?
- paint(): It is a method used to paint components on the screen. It is automatically called when the component needs to be redrawn.
- repaint(): It is a method used to request the system to call the
paint()
method to refresh the component.
h) Explain Access modifiers used in Java.
Access Modifiers in Java:
- public: The member is accessible from any other class.
- protected: The member is accessible within its package and by subclasses.
- default: The member is accessible only within the same package.
- private: The member is accessible only within its own class.
i) Define keyword throw.
throw: The throw
keyword is used to explicitly throw an exception in Java. It is followed by an instance of the Throwable
class (or its subclasses). Example:
throw new Exception("An error occurred");
j) Define polymorphism.
Polymorphism: Polymorphism is the ability of an object to take on many forms. It allows one interface to be used for a general class of actions. The two types are:
- Compile-time polymorphism (Method Overloading).
- Run-time polymorphism (Method Overriding).
Q2) Attempt any Four (Explain in detail):
(Each question carries 4 marks)
a) Explain features of Java.
Features of Java:
- Platform Independence: Java programs can run on any device that has a Java Virtual Machine (JVM).
- Object-Oriented: Java is based on objects and classes, following the principles of OOP (Encapsulation, Inheritance, Polymorphism, and Abstraction).
- Distributed Computing: Java has built-in support for networking and remote method invocation (RMI).
- Multithreading: Java provides support for multithreaded programming, allowing multiple threads to run concurrently.
- Security: Java provides a secure execution environment, including bytecode verification, sandboxing, and encryption.
- Automatic Garbage Collection: Java handles memory management automatically, eliminating the need for manual memory management.
b) What is the difference between constructor and method? Explain types of constructors.
Constructor vs. Method:
- Constructor: It is a special type of method used to initialize objects. It has the same name as the class and no return type.
- Method: A method is a block of code that performs a specific task and has a return type.
Types of Constructors:
- Default Constructor: Automatically provided by Java if no constructor is explicitly defined.
- Parameterized Constructor: A constructor that accepts parameters to initialize the object with specific values.
c) Differentiate between interface and abstract class.
Interface vs. Abstract Class:
Aspect | Interface | Abstract Class |
---|---|---|
Inheritance | A class can implement multiple interfaces | A class can inherit only one abstract class |
Methods | Can have only abstract methods (until Java 8) | Can have both abstract and concrete methods |
Constructors | Cannot have constructors | Can have constructors |
Multiple Inheritance | Supports multiple inheritance | Does not support multiple inheritance |
Implementation | Provides no implementation | Can provide partial implementation |
d) Explain the concept of exception and exception handling.
Exception Handling in Java: An exception is an event that disrupts the normal flow of a program. Java provides a robust mechanism to handle exceptions using try
, catch
, finally
, throw
, and throws
.
- try block: Contains code that may throw an exception.
- catch block: Handles exceptions thrown by the try block.
- finally block: Executes code regardless of whether an exception is thrown or not.
e) Explain try and catch with example.
Example of try-catch:
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("This block always executes");
}
Q3) Attempt any Four:
(Each question carries 4 marks)
a) Write a Java program to display all the perfect numbers between 1 to n.
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the range: ");
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
int sum = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum += j;
}
}
if (sum == i) {
System.out.println(i + " is a perfect number.");
}
}
}
}
b) Write a Java program to calculate the area of circle, triangle, and rectangle (Use Method Overloading).
public class ShapeArea {
public double calculateArea(double radius) {
return Math.PI * radius * radius; // Circle
}
public double calculateArea(double base, double height) {
return 0.5 * base * height; // Triangle
}
public double calculateArea(double length, double width) {
return length * width; // Rectangle
}
public static void main(String[] args) {
ShapeArea shape = new ShapeArea();
System.out.println("Area of Circle: " + shape.calculateArea(5));
System.out.println("Area of Triangle: " + shape.calculateArea(5, 10));
System.out.println("Area of Rectangle: " + shape.calculateArea(5, 8));
}
}
c) Write a Java program to accept n integers from the user and store them in an ArrayList collection. Display elements in reverse order.
import java.util.*;
public class ReverseArrayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of integers: ");
int n = sc.nextInt();
ArrayList<Integer> list = new ArrayList<>();
System.out.println("Enter the integers:");
for (int i = 0; i < n; i++) {
list.add(sc.nextInt());
}
Collections.reverse(list); // Reverse the list
System.out.println("Elements in reverse order: " + list);
}
}
d) Write a Java program to count number of digits, spaces, and characters from a file.
import java.io.*;
public class FileCharacterCount {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
int digits = 0, spaces = 0, characters = 0;
int ch;
while ((ch = br.read()) != -1) {
if (Character.isDigit(ch)) {
digits++;
} else if (Character.isSpaceChar(ch)) {
spaces++;
} else {
characters++;
}
}
System.out.println("Digits: " + digits);
System.out.println("Spaces: " + spaces);
System.out.println("Characters: " + characters);
br.close();
}
}
e) Create an applet that displays x and y position of the cursor movement using mouse and keyboard.
import java.awt.*;
import java.awt.event.*;
public class MousePositionApplet extends Applet implements MouseMotionListener, KeyListener {
String msg = "";
public void init() {
addMouseMotionListener(this);
addKeyListener(this);
}
public void mouseMoved(MouseEvent e) {
msg = "Mouse Position: " + e.getX() + ", " + e.getY();
repaint();
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void paint(Graphics g) {
g.drawString(msg, 20, 20);
}
}
Q4) Attempt any Four:
(Each question carries 4 marks)
a) How a Java program is structured? Explain data types.
Java Program Structure: A basic Java program consists of:
- Class: The class is the blueprint for objects.
- Main Method: The entry point of the program where the execution starts.
Data Types in Java:
- Primitive types: byte, short, int, long, float, double, char, boolean.
- Reference types: Arrays, classes, interfaces.
b) What is an applet? Explain its types.
Applet: An applet is a small Java program designed to be run within a web browser.
Types of Applets:
- Local Applets: These run on the local machine.
- Remote Applets: These run on a remote server.
c) Write a Java program to count the number of lines, words, and characters from a given file.
import java.io.*;
public class FileWordCount {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line;
int lines = 0, words = 0, characters = 0;
while ((line = br.readLine()) != null) {
lines++;
String[] wordArray = line.split("\\s+");
words += wordArray.length;
characters += line.length();
}
System.out.println("Lines: " + lines);
System.out.println("Words: " + words);
System.out.println("Characters: " + characters);
br.close();
}
}
d) Write a Java program to design an email registration form. (Use Swing components)
import javax.swing.*;
import java.awt.*;
public class EmailRegistrationForm {
public static void main(String[] args) {
JFrame frame = new JFrame("Email Registration");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel emailLabel = new JLabel("Email:");
emailLabel.setBounds(10, 20, 80, 25);
panel.add(emailLabel);
JTextField emailField = new JTextField(20);
emailField.setBounds(100, 20, 165, 25);
panel.add(emailField);
JButton submitButton = new JButton("Register");
submitButton.setBounds(10, 80, 100, 25);
panel.add(submitButton);
}
}
e) 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 objects).
import java.util.Scanner;
class Teacher {
int Tid;
String Tname, Designation, Subject;
double Salary;
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;
}
}
public class TeacherDetails {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of teachers: ");
int n = sc.nextInt();
Teacher[] teachers = new Teacher[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter details for teacher " + (i + 1));
System.out.print("ID: ");
int Tid = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Name: ");
String Tname = sc.nextLine();
System.out.print("Designation: ");
String Designation = sc.nextLine();
System.out.print("Salary: ");
double Salary = sc.nextDouble();
sc.nextLine(); // Consume newline
System.out.print("Subject: ");
String Subject = sc.nextLine();
teachers[i] = new Teacher(Tid, Tname, Designation, Salary, Subject);
}
System.out.println("\nTeachers who teach Java:");
for (Teacher teacher : teachers) {
if (teacher.Subject.equalsIgnoreCase("Java")) {
System.out.println(teacher.Tname);
}
}
}
}
Q5) Write short note on any two:
(Each question carries 3 marks)
a) Define object.
Object: An object is an instance of a class. It represents a real-world entity with specific attributes and behaviors. It is created using the new
keyword and can access the members (fields and methods) of the class.
b) Define term finally block.
finally block: The finally
block is used to execute code that must run after a try
block, regardless of whether an exception is thrown or not. It is typically used for resource cleanup (e.g., closing files or database connections).
c) What is package? Write down all the steps for package creation.
Package: A package in Java is a namespace that organizes classes and interfaces. It provides a way to group related classes, making code easier to manage.
Steps to create a package:
- Create a Java file with a
package
statement at the top:package mypackage;
- Save the file in a directory corresponding to the package name.
- Compile the class:
javac mypackage/MyClass.java
- Use the package in another program by importing it:
import mypackage.MyClass;