Java Question Bank with Answers

Answers for Core Java Question Bank.

Chapter 1: Introduction to Core Java.

Difficult Level Questions

14. "Java is purely object-oriented, whereas C++ supports both procedural and object-oriented paradigms." Evaluate this statement critically. Elaborate on the core differences that justify this classification, providing specific features or characteristics of both languages that support this distinction (e.g., primitive types vs. objects, global functions, inheritance models).

Answer:
The statement that "Java is purely object-oriented, whereas C++ supports both procedural and object-oriented paradigms" holds significant truth, though the "purely" aspect of Java can be debated due to its inclusion of primitive data types. Critically evaluating this statement reveals fundamental design philosophies:

C++: A Hybrid Language
C++ evolved from C, inheriting its procedural capabilities. This means C++ allows developers to write code using:

  • Global Functions: Functions can exist outside of any class, acting as standalone entities.
  • Structs: C++ retains C-style structs, which are essentially classes where members are public by default, often used for data aggregation without methods or complex OOP behavior.
  • Pointers and Direct Memory Access: As a systems programming language, C++ provides low-level control, including explicit pointers and manual memory management (malloc/free or new/delete), which are characteristics of procedural programming.
  • Primitive Data Types: C++ has primitive types (int, char, float) that are not objects.
  • No Universal Base Class: There isn’t a single root class from which all other classes implicitly derive.

This hybrid nature makes C++ highly flexible, suitable for both low-level system programming (where procedural control is often needed) and high-level application development using OOP.

Java: Predominantly Object-Oriented (with a minor compromise for primitives)
Java was designed from the ground up with OOP as its central paradigm. Its object-oriented nature is evident in:

  • Everything is (almost) an Object: Except for its primitive data types (like int, double, boolean), almost everything in Java is an object, including arrays. All classes (except Object itself) implicitly inherit from the java.lang.Object class, providing a common root and consistent behavior (e.g., equals(), toString()).
  • No Global Functions: All code (except primitive type variables and operators) must reside within a class. There are no standalone functions or variables that exist outside of a class context. Even the main method is a static method within a class.
  • No Pointers: Java replaces C++’s explicit pointers with references, which are safer and managed by the JVM. This eliminates direct memory manipulation, a hallmark of procedural languages.
  • Encapsulation and Information Hiding: Java strongly promotes encapsulation by default, encouraging the bundling of data and methods within classes and controlling access via access specifiers.
  • Strict Inheritance Model: While it supports inheritance, Java does not allow multiple inheritance of classes (to avoid complexity like the "Diamond Problem"), instead advocating multiple inheritance of type through interfaces, which aligns with its clean OOP design.

Justification for Classification:
The classification is justified by the fundamental design philosophy and language constructs:

  • C++’s Backward Compatibility: C++ maintains backward compatibility with C, retaining features that enable a procedural style of programming. Its design allows developers to choose how object-oriented their code needs to be.
  • Java’s Forward-Looking OOP Design: Java was created to be inherently object-oriented, aiming for simplicity, robustness, and platform independence by imposing an OOP structure. The inclusion of primitive types in Java is primarily for performance reasons, as dealing with objects for basic arithmetic can introduce overhead. However, wrapper classes exist (Integer, Double) to treat primitives as objects when needed, and autoboxing/unboxing bridge this gap.

In conclusion, Java is indeed predominantly object-oriented in its design and enforcement, making OOP the default and most natural way to program. C++, while fully capable of object-oriented programming, provides the flexibility to also write procedural code, thus making it a hybrid language.

15. Design and implement a complete Java program that:

Takes three integer command-line arguments: principal, rate, and time_years.

Declares a final variable COMPOUNDING_FREQUENCY initialized to 4 (for quarterly compounding).

Calculates and prints the interest.

Includes appropriate comments and uses a 1D array to store the input arguments.

 // CompoundInterestCalculator.java

public class CompoundInterestCalculator {

 

    // Declare a final variable for quarterly compounding frequency

    public static final int COMPOUNDING_FREQUENCY = 4; // n in the formula

 

    public static void main(String[] args) {

        // Step 1: Check if exactly three command-line arguments are provided

        if (args.length != 3) {

            System.out.println("Usage: java CompoundInterestCalculator <principal> <rate> <time_years>");

            System.out.println("Example: java CompoundInterestCalculator 10000 5 2");

            return; // Exit the program if arguments are incorrect

        }

 

        // Step 2: Parse command-line arguments to appropriate numeric types

        double principal;

        double rate;      // Annual interest rate (e.g., 5 for 5%)

        int timeYears;    // Time in years

 

        try {

            principal = Double.parseDouble(args[0]);

            rate = Double.parseDouble(args[1]);

            timeYears = Integer.parseInt(args[2]);

 

            // Validate inputs (optional, but good practice)

            if (principal <= 0 || rate < 0 || timeYears < 0) {

                System.out.println("Principal must be positive. Rate and Time must be non-negative.");

                return;

            }

 

        } catch (NumberFormatException e) {

            System.out.println("Error: Invalid number format for principal, rate, or time.");

            System.out.println("Please ensure all arguments are valid numbers.");

            return;

        }

 

        // Convert annual rate percentage to decimal (e.g., 5% -> 0.05)

        double decimalRate = rate / 100.0;

 

        // Calculate Compound Amount using the formula: A = P(1 + r/n)^(nt)

        double base = 1 + (decimalRate / COMPOUNDING_FREQUENCY);

        double exponent = COMPOUNDING_FREQUENCY * timeYears;

        double compoundAmount = principal * Math.pow(base, exponent);

 

        // Calculate the Compound Interest

        double compoundInterest = compoundAmount – principal;

 

        // Print the results, formatted for clarity

        System.out.println("\n— Compound Interest Calculation —");

        System.out.printf("Principal Amount:      $%,.2f%n", principal);

        System.out.printf("Annual Interest Rate:  %.2f%%%n", rate);

        System.out.printf("Time Period:           %d years%n", timeYears);

        System.out.printf("Compounding Frequency: %d (quarterly)%n", COMPOUNDING_FREQUENCY);

        System.out.println("————————————-");

        System.out.printf("Compound Amount (A):   $%,.2f%n", compoundAmount);

        System.out.printf("Compound Interest:     $%,.2f%n", compoundInterest);

        System.out.println("————————————-");

    }

}

How to compile and run from the command line:

1.     Save the code as CompoundInterestCalculator.java.

2.     Compile: javac CompoundInterestCalculator.java

3.     Run: java CompoundInterestCalculator 10000 5 2 (for Principal=10000, Rate=5%, Time=2 years)

 

16. Analyze the following Java code segments. For each, determine if it will compile successfully. If not, identify the exact compilation error and explain the underlying Java type conversion rules (implicit promotion, explicit casting, or lack thereof) that lead to the error. Propose a correction for each faulty segment.

Answer:

Scenario A: Byte Arithmetic

byte b1 = 70;

byte b2 = 80;

byte sumResult = b1 + b2; // Will this compile?

  • Will it compile? No.
  • Compilation Error: incompatible types: possible lossy conversion from int to byte
  • Explanation: In Java, arithmetic operations on byte, short, and char types automatically promote the operands to int before performing the calculation. So, b1 + b2 results in an int value (70 + 80 = 150). Attempting to assign this int result back to a byte variable (sumResult) requires an explicit cast because int has a larger range than byte, and the compiler detects a potential "lossy conversion" (data loss).
  • Correction: Explicitly cast the result of the addition back to byte.

·         byte b1 = 70;

·         byte b2 = 80;

byte sumResult = (byte) (b1 + b2); // Corrected line

Scenario B: Mixed Type Calculation

int intVal = 10;

long longVal = 50L;

float floatVal = 2.5f;

int finalResult = intVal * longVal / floatVal; // Will this compile?

  • Will it compile? No.
  • Compilation Error: incompatible types: possible lossy conversion from float to int
  • Explanation: Java follows binary numeric promotion rules for mixed-type operations.

1.     intVal * longVal: int is promoted to long, so the result is long (10 * 50 = 500L).

2.     long_result / floatVal: long is promoted to float (since float is larger than long in terms of data storage for floating point values, despite long being 64-bit for integers). The division 500L / 2.5f results in a float value (200.0f).

3.     Attempting to assign this float result to an int variable (finalResult) is a potential lossy conversion because float can hold decimal values, and int cannot. Therefore, an explicit cast is required.

  • Correction: Explicitly cast the final result to int. Note that casting from float to int truncates the decimal part.

·         int intVal = 10;

·         long longVal = 50L;

·         float floatVal = 2.5f;

int finalResult = (int) (intVal * longVal / floatVal); // Corrected line. Result will be 200.

Scenario C: Character to Integer Conversion

char ch = ‘K’;

int charSum = ch + 2; // What is the value of charSum? Will it compile?

  • Will it compile? Yes.
  • What is the value of charSum? charSum will be 77.
  • Explanation: When a char type is used in an arithmetic expression with an int (or larger integer types), the char is implicitly promoted to its corresponding Unicode integer value. The Unicode value for ‘K’ is 75. Therefore, the operation becomes 75 + 2, which equals 77. Since 77 is an int, and charSum is an int, the assignment is compatible and no explicit cast is needed.
  • Correction: No correction needed; the code compiles successfully and produces the expected result based on implicit type promotion rules.