T.Y.B.B.A. (C.A.) CA 503: CORE JAVA – Exam Paper (2019 Pattern) (Semester-V)
Q1) Attempt any Eight: [8×2 = 16]
i) Define variable in Java? What are the naming rules of variable?
A variable in Java is a container that holds data which can be used and modified during program execution. It is defined with a specific data type and an identifier.
Naming Rules for Variables in Java:
- A variable name must start with a letter, underscore (_), or a dollar sign ($).
- The remaining characters of the variable name can include letters, digits, underscores, and dollar signs.
- Variable names are case-sensitive (e.g.,
myVar
andmyvar
are different). - No spaces or special characters like
@
,#
, or-
are allowed. - The name cannot be a Java keyword (e.g.,
int
,if
,while
).
ii) What is recursion?
Recursion is a programming technique in which a method calls itself to solve a problem. The problem is divided into smaller subproblems, and the method solves the subproblems by calling itself with modified arguments.
Example of recursion:
public class Factorial {
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
System.out.println(factorial(5)); // Output: 120
}
}
iii) Define Inheritance?
Inheritance is an object-oriented programming concept in Java where one class (subclass) acquires the properties and behaviors (fields and methods) of another class (superclass). This allows for code reusability and hierarchical class structures.
Example:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class TestInheritance {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Inherited from Animal
d.bark(); // Defined in Dog
}
}
iv) What is the difference between Array and ArrayList?
Feature | Array | ArrayList |
---|---|---|
Size | Fixed size | Dynamic size (can grow or shrink) |
Type | Can store elements of a single data type | Can store objects of any type (though you can specify a type with generics) |
Performance | Faster access (due to fixed size) | Slower access (due to dynamic resizing) |
Methods | No built-in methods for adding/removing elements | Provides built-in methods like add() , remove() , etc. |
Memory | Fixed memory allocation | Memory is dynamically allocated and resized |
v) What is error? List types of error?
An error in Java refers to a serious problem that the application cannot recover from, typically caused by the JVM. Errors usually indicate issues in the environment rather than the program itself.
Types of Errors:
- Compilation Errors: Occur during the compilation phase, often due to syntax mistakes.
- Runtime Errors: Occur during program execution, such as division by zero or accessing an invalid index.
- Logical Errors: Occur when the program runs without crashing but produces incorrect results.
vi) List any two restrictions for applets.
- No access to local files: Applets cannot access local files on the client machine due to security restrictions.
- Limited network access: Applets are restricted from making network connections to servers other than the one from which they were downloaded.
vii) What is an event?
An event in Java refers to an action or occurrence that a program can respond to. These events are typically triggered by the user or the system, such as a mouse click, key press, or window close event.
viii) What is Object and Class?
- Class: A blueprint or template for creating objects. It defines the properties (fields) and behaviors (methods) that the objects will have.
- Object: An instance of a class. It contains actual values for the properties defined in the class and can invoke methods defined in the class.
Example:
class Car {
String color;
void start() {
System.out.println("Car is starting");
}
}
public class TestClass {
public static void main(String[] args) {
Car myCar = new Car(); // Object creation
myCar.color = "Red";
myCar.start(); // Method invocation
}
}
ix) Write the definition of abstract class?
An abstract class in Java is a class that cannot be instantiated directly and is used as a base for other classes. It may contain abstract methods (methods without a body) that must be implemented by subclasses.
Example:
abstract class Animal {
abstract void sound(); // Abstract method
}
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}
public class TestAbstract {
public static void main(String[] args) {
Animal dog = new Dog();
dog.sound(); // Output: Bark
}
}
x) What is a Container?
In Java, a container is an object that holds and organizes other components or elements such as buttons, labels, text fields, etc. Examples of containers include JFrame
, JPanel
, and Window
.
Q2) Attempt any Four: (Explain in detail) [4×4=16]
i) Write a note on package in Java.
A package in Java is a namespace that groups related classes and interfaces. It is used to avoid name conflicts and to organize code into a structured hierarchy.
Types of Packages:
- Built-in Packages: These are predefined packages like
java.util
,java.io
,java.lang
, etc. - User-defined Packages: These are packages created by the programmer to organize their own classes.
Creating a Package:
package mypackage;
public class MyClass {
public void display() {
System.out.println("This is my package!");
}
}
Importing a Package:
import mypackage.MyClass;
public class TestPackage {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
ii) What is an exception? Explain its keywords with an example.
An exception in Java is an event that disrupts the normal flow of program execution. It can be caught and handled to prevent the program from terminating abruptly.
Keywords for Exception Handling:
try
: Used to enclose code that might throw an exception.catch
: Used to catch and handle exceptions.throw
: Used to throw an exception explicitly.throws
: Used in a method signature to declare that the method can throw an exception.
Example:
class Example {
public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero exception
} catch (ArithmeticException e) {
System.out.println("Exception: " + e);
} finally {
System.out.println("This block will always execute.");
}
}
}
iii) Explain java.util
package.
The java.util
package is part of the Java Standard Library and provides a wide range of utility classes such as collections, date/time utilities, and random number generation. Key classes in java.util
include:
- ArrayList: A dynamic array that can grow as needed.
- HashMap: A collection that stores key-value pairs.
- Date: Represents date and time.
- Collections: Provides utility methods to work with collections.
Example:
import java.util.*;
public class ExampleUtil {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
Collections.sort(list);
System.out.println(list);
}
}
iv) What is a method in Java? Explain method overloading with an example.
A method in Java is a block of code that performs a specific task. It has a name, a return type, and may accept parameters.
Method Overloading: It is the concept of defining multiple methods with the same name but different parameters (either different number or types).
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
public class TestOverloading {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(10, 20)); // Calls int method
System.out.println(calc.add(10.5, 20.5)); // Calls double method
}
}
v) How to handle events in applet? Explain with example.
In Java Applets, events are handled using event listeners. An applet can respond to events such as mouse clicks or key presses using the MouseListener
, KeyListener
, etc.
Example:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements MouseListener {
public void init() {
addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
Graphics g = getGraphics();
g.drawString("Mouse Clicked at: " + e.getX() + ", " + e.getY(), 20, 20);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
Q3) Attempt any Four: (Explain in detail) [4×4=16]
i) 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.*;
public class CustomerDetails extends Frame {
TextField idField, nameField, addrField;
Button submitButton;
public CustomerDetails() {
setLayout(new FlowLayout());
add(new Label("Customer ID:"));
idField = new TextField(20);
add(idField);
add(new Label("Customer Name:"));
nameField = new TextField(20);
add(nameField);
add(new Label("Customer Address:"));
addrField = new TextField(20);
add(addrField);
submitButton = new Button("Submit");
add(submitButton);
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String custId = idField.getText();
String custName = nameField.getText();
String custAddr = addrField.getText();
// Display details in a new frame
Frame detailsFrame = new Frame("Customer Details");
detailsFrame.setLayout(new FlowLayout());
detailsFrame.add(new Label("Customer ID: " + custId));
detailsFrame.add(new Label("Customer Name: " + custName));
detailsFrame.add(new Label("Customer Address: " + custAddr));
detailsFrame.setSize(300, 200);
detailsFrame.setVisible(true);
}
});
setSize(300, 300);
setVisible(true);
}
public static void main(String[] args) {
new CustomerDetails();
}
}
ii) Write a Java program to reverse elements in an array.
import java.util.Scanner;
public class ReverseArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter array size: ");
int size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter array elements:");
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
// Reverse the array
int start = 0, end = size - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
System.out.println("Reversed array:");
for (int i : arr) {
System.out.print(i + " ");
}
}
}
iii) Write a Java program using static method which maintains bank account information about various customers.
class BankAccount {
static int accountCount = 0;
int accountNumber;
double balance;
public BankAccount(double balance) {
accountCount++;
this.accountNumber = accountCount;
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient
balance”); } }
public void displayAccount() {
System.out.println("Account Number: " + accountNumber);
System.out.println("Balance: " + balance);
}
public static void main(String[] args) {
BankAccount acc1 = new BankAccount(1000);
BankAccount acc2 = new BankAccount(2000);
acc1.deposit(500);
acc2.withdraw(1000);
acc1.displayAccount();
acc2.displayAccount();
}
}
---
**iv) Define an abstract class Shape with abstract method `area()` and `volume()`. Write a Java program to calculate the area and volume of cone and cylinder.**
```java
abstract class Shape {
abstract void area();
abstract void volume();
}
class Cone extends Shape {
double radius, height;
public Cone(double radius, double height) {
this.radius = radius;
this.height = height;
}
@Override
void area() {
double area = Math.PI * radius * (radius + Math.sqrt(radius * radius + height * height));
System.out.println("Area of Cone: " + area);
}
@Override
void volume() {
double volume = (1 / 3.0) * Math.PI * radius * radius * height;
System.out.println("Volume of Cone: " + volume);
}
}
class Cylinder extends Shape {
double radius, height;
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
@Override
void area() {
double area = 2 * Math.PI * radius * (radius + height);
System.out.println("Area of Cylinder: " + area);
}
@Override
void volume() {
double volume = Math.PI * radius * radius * height;
System.out.println("Volume of Cylinder: " + volume);
}
}
public class TestShape {
public static void main(String[] args) {
Shape cone = new Cone(5, 10);
cone.area();
cone.volume();
Shape cylinder = new Cylinder(5, 10);
cylinder.area();
cylinder.volume();
}
}