Core Java Exam Paper 1

T.Y.B.B.A. (C.A.) CA 503: Core Java – Exam Paper (2019 Pattern) (Semester-V)

Q1) Answer any Eight: [Max. Marks: 70 (8×2=16)]

a) What is a Java program structure?

A Java program structure consists of the following components:

  • Class Definition: A Java program is written inside a class.
  • Main Method: The entry point of any Java application is the main method. It has the signature public static void main(String[] args).
  • Statements: Inside the main method, we write statements that will execute when the program runs.
  • Curly Braces: {} are used to define code blocks such as class body, method body, etc.

b) Define this keyword.

The this keyword in Java refers to the current object instance of the class. It is used to differentiate between class variables and parameters or to call one constructor from another within the same class.

c) Explain in detail the data types in Java.

Java has two main types of data types:

  1. Primitive Data Types: These are basic types and hold simple values. Examples include:
    • int: Integer value
    • float: Floating-point value
    • char: A single character
    • boolean: Holds true or false
    • double: Double precision floating-point
    • byte, short, long: Other integer types of varying sizes
  2. Reference Data Types: These include objects, arrays, and interfaces. They refer to objects or memory locations.

d) What is an Interface?

An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors. A class that implements an interface must provide implementations for all of its methods.

e) What is the use of Reader and Writer classes?

The Reader and Writer classes are part of Java’s I/O package and are used to read and write character data, respectively. The Reader class reads character data, and the Writer class writes character data. They support a wider range of character encoding than byte streams like InputStream and OutputStream.

f) Which method is used to specify a container’s layout with syntax?

The method setLayout() is used to specify the layout of a container in Java. The syntax is:

container.setLayout(LayoutManager layout);

For example, to set a FlowLayout:

frame.setLayout(new FlowLayout());

g) What is the default layout for Frame and Panel?

  • Frame: The default layout manager for a Frame is BorderLayout.
  • Panel: The default layout manager for a Panel is FlowLayout.

h) Explain Modifiers and Access Controls used in Java.

In Java, access modifiers control the visibility and accessibility of classes, methods, and variables. There are four types:

  • public: The member is accessible from any other class.
  • private: The member is accessible only within the same class.
  • protected: The member is accessible within the same package and by subclasses.
  • default (no modifier): The member is accessible only within the same package.

i) List and explain any 2 built-in exceptions.

  • ArithmeticException: Thrown when an exceptional arithmetic condition occurs, such as dividing by zero.
  • NullPointerException: Thrown when the JVM attempts to access an object or call a method on a null object.

j) Explain the purpose of getContentPane().

In Java Swing, the getContentPane() method returns the container where components (such as buttons, labels, panels) are placed. This is the primary area where the components are added in a JFrame.


Q2) Attempt any four. [4×4=16]

a) Explain in detail the features of Java.

Java is a high-level, object-oriented, and platform-independent programming language. Some of its key features include:

  • Object-Oriented: Everything in Java is an object, and classes and objects are the fundamental components.
  • Platform Independent: Java programs are compiled into bytecode, which can run on any platform with a Java Virtual Machine (JVM).
  • Automatic Garbage Collection: Java manages memory automatically, removing unused objects to free up memory.
  • Multithreading: Java supports multithreading, allowing concurrent execution of two or more threads.
  • Rich API: Java has a rich API for networking, I/O operations, utilities, etc.
  • Security: Java provides a secure environment through its classloader and bytecode verifier.
  • Distributed Computing: Java supports distributed computing through technologies like RMI (Remote Method Invocation) and EJB (Enterprise Java Beans).

b) What are the rules for method overloading and method overriding? Explain with examples.

  • Method Overloading: Occurs when multiple methods have the same name but differ in the number or type of parameters. It is resolved at compile-time. Example: class MathOperation { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } }
  • Method Overriding: Occurs when a subclass provides its own implementation of a method that is already defined in its superclass. It is resolved at runtime. Example: class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } }

c) Differentiate between interface and abstract class.

FeatureInterfaceAbstract Class
InheritanceCan be implemented by any classCan be inherited by a subclass
MethodsCan have only abstract methods (in Java versions before 8)Can have both abstract and non-abstract methods
ConstructorsNo constructors allowedCan have constructors
Multiple InheritanceA class can implement multiple interfacesA class can inherit only one abstract class
FieldsCan have only static final variablesCan have instance variables

d) Explain the concept of exception and exception handling.

An exception is an event that disrupts the normal flow of a program’s execution. Java provides a robust exception handling mechanism using try, catch, throw, throws, and finally blocks to handle runtime errors. The try block is used to enclose code that might throw an exception. The catch block handles the exception if it occurs.

e) What are the different types of streams? Explain in detail.

Java I/O streams are of two types:

  • Byte Stream: Handles raw binary data. Examples include FileInputStream and FileOutputStream.
  • Character Stream: Handles text data. Examples include FileReader and FileWriter. These streams work with Unicode characters.

Q3) Attempt any four. [4×4=16]

a) Write a Java program to display alternate characters from a given string.

import java.util.Scanner;
public class AlternateChars {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = sc.nextLine();
        for (int i = 0; i < str.length(); i += 2) {
            System.out.print(str.charAt(i));
        }
    }
}

b) Write a Java program to calculate the area of Circle, Triangle, and Rectangle using Method Overloading.

class Area {
    // Method to calculate area of Circle
    double calculateArea(double radius) {
        return Math.PI * radius * radius;
    }

    // Method to calculate area of Rectangle
    double calculateArea(double length, double breadth) {
        return length * breadth;
    }

    // Method to calculate area of Triangle
    double calculateArea(double base, double height) {
        return 0.5 * base * height;
    }
}

public class Main {
    public static void main(String[] args) {
        Area area = new Area();
        System.out.println("Area of Circle: " + area.calculateArea(5.0));
        System.out.println("Area of Rectangle: " + area.calculateArea(10.0, 5.0));
        System.out.println("Area of Triangle: " + area.calculateArea(10.0, 5.0));
    }
}

c) Write a Java program to search a given name in an array.

import java.util.Scanner;

public class NameSearch {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] names = {"John", "Paul", "George", "Ringo"};
        System.out.print("Enter name to search: ");
        String name = sc.nextLine();
        boolean found = false;

        for (int i = 0; i < names.length; i++) {
            if (names[i].equalsIgnoreCase(name)) {
                System.out.println("Name found at index: " + i);
                found = true;
                break;
            }
        }
        if (!found) {
            System.out.println("Name not found!");
        }
    }
}

d) Write a Java program to display ASCII values of the characters from a file.

import java.io.*;

public class ASCIIValuesFromFile {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
            int character;
            while ((character = reader.read()) != -1) {
                System.out.println("Character: " + (char) character + " ASCII Value: " + character);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

e) Write a Java program to display the multiplication table of a given number in a List box by clicking on a button.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MultiplicationTable {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Multiplication Table");
        JButton button = new JButton("Show Table");
        DefaultListModel<String> listModel = new DefaultListModel<>();
        JList<String> list = new JList<>(listModel);
        frame.setLayout(new FlowLayout());
        frame.add(button);
        frame.add(new JScrollPane(list));
        
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number"));
                listModel.clear();
                for (int i = 1; i <= 10; i++) {
                    listModel.addElement(number + " x " + i + " = " + (number * i));
                }
            }
        });
        
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Q4) Attempt any four. [4×4=16]

a) What is a collection? Explain Collection framework in detail.

In Java, a collection is a group of objects stored in a specific way. The Collection framework provides a set of interfaces and classes to handle and manipulate groups of objects. It includes:

  • List: An ordered collection, e.g., ArrayList.
  • Set: A collection that does not allow duplicate elements, e.g., HashSet.
  • Queue: A collection designed for holding elements in a queue-like structure, e.g., LinkedList.
  • Map: A collection of key-value pairs, e.g., HashMap.

b) Difference between Swing and AWT.

FeatureAWTSwing
Component TypesContains basic components like Button, LabelRicher components like JButton, JLabel
Platform DependencyPlatform-dependentPlatform-independent
Lightweight or HeavyweightHeavyweight (uses native OS components)Lightweight (pure Java components)
GraphicsLimitedProvides richer graphics

c) Create a package named Series having three different classes to print series.

package Series;

class Fibonacci {
    void printSeries(int n) {
        int a = 0, b = 1;
        System.out.print(a + " " + b + " ");
        for (int i = 2; i < n; i++) {
            int c = a + b;
            System.out.print(c + " ");
            a = b;
            b = c;
        }
    }
}

class Cube {
    void printSeries(int n) {
        for (int i = 1; i <= n; i++) {
            System.out.print(i * i * i + " ");
        }
    }
}

class Square {
    void printSeries(int n) {
        for (int i = 1; i <= n; i++) {
            System.out.print(i * i + " ");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Fibonacci fib = new Fibonacci();
        fib.printSeries(10);

        Cube cube = new Cube();
        cube.printSeries(10);

        Square square = new Square();
        square.printSeries(10);
    }
}

d) Write a ‘Java’ program to check whether a given number is Armstrong or not. (Use static keyword)

class Armstrong {
    static boolean checkArmstrong(int number) {
        int originalNumber = number;
        int sum = 0;
        while (number > 0) {
            int digit = number % 10;
            sum += digit * digit * digit;
            number /= 10;
        }
        return sum == originalNumber;
    }

    public static void main(String[] args) {
        int number = 153;
        if (checkArmstrong(number)) {
            System.out.println(number + " is an Armstrong number");
        } else {
            System.out.println(number + " is not an Armstrong number");
        }
    }
}

e) Write a ‘Java’ program to copy only non-numeric data from one file to another file.

import java.io.*;

public class CopyNonNumericData {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));
             BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
            int ch;
            while ((ch = br.read()) != -1) {
                if (!Character.isDigit(ch)) {
                    bw.write(ch);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Q5) Write short notes on any two:

a) Define new operator.

The new operator in Java is used to create new objects or instances of classes. It allocates memory for the object and returns a reference to it.

Example:

String str = new String("Hello");

b) Define the finalize() method.

The finalize() method in Java is used to perform cleanup operations before an object is garbage collected. It is a method in the Object class, and it can be overridden to release resources like file handles or database connections.

c) Define package with all the steps for package creation.

A package is a namespace that groups related classes and interfaces together. To create a package:

  1. Use the package keyword at the top of the Java source file.
  2. Create a directory structure that matches the package name.
  3. Compile the class with the javac command, specifying the package path.

Example:

package mypackage;
public class MyClass { }
Scroll to Top