5 Multiple Choices of Java

1. The Adder Class

There are different kinds of calculators which are available in the market for different purposes. Sam wants to make a calculator which can return the sum of two integers.

Implement the Adder class which should follow the following:

  • It should inherit from the Calculator class .
  • It should implement the method add(int a, int b) which should calculate and return the sum of two integer parameters, a and b.

The locked stub code in the editor consists of the following:

  • An abstract class named Calculator which contains an abstract method, add(int a, int b).
  • A solution class which
    • creates an object of the Adder class. 
    • reads the inputs and passes them in a method called by the object of the Adder class.

Constraints

  • 0 < a, b < 105
Input Format For Custom Testing

The only line contains two space-separated integers, a and b.

Sample Case 0

Sample Input For Custom Testing

1 1

Sample Output

The sum is: 2

Explanation

When the add method is called with the arguments a = 1 and b = 1, it calculates and returns their sum as 1 + 1 = 2, which is then printed.

Sample Case 1

Sample Input For Custom Testing

2 3

Sample Output

5

Explanation

When the add method is called with the arguments a = 2 and b = 3, it calculates and returns their sum as 2 + 3 = 5, which is then printed.

SOLUTION:

				
					import java.util.Scanner;

abstract class Calculator {
    abstract int add(int a, int b);
}

class Adder extends Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

public class Solution {
    public static void main(String[] args) {
        int a, b;
        try (Scanner scan = new Scanner(System.in)) {
            a = scan.nextInt();
            b = scan.nextInt();
        }

        Calculator adderObject = new Adder();
        System.out.println("The sum is: " + adderObject.add(a, b));
    }
}
				
			

2. Java: Encryption Decryption

Decrypt a message that was encrypted using the following logic:

  • First the words in the sentence are reversed. For example, “welcome to hackerrank” becomes “hackerrank to welcome”.
  • For each word, adjacent repeated letters are compressed in the format <character><frequency>.  For example, “mississippi” becomes “mis2is2ip2i” or “baaa” becomes “ba3”. Note the format is not applied for characters with frequency 1. Also, the frequency will be no greater than 9.

Return the decrypted string.

Example

encryptedMessage = ‘world hel2o’

Expand each word to get ‘world hello’. Now reverse the words to get ‘hello world’, the return value.

Function Description

Complete the function decrypt in the editor below.

decrypt has the following parameter(s):

    string encryptedMessage:  an encrypted string

Returns

    string:  the decrypted message

Constraints

  • 1 ≤ length of encryptedMessage ≤ 105

  • Character frequency counts in the encrypted string will be 9 or less.

  • encryptedMessage consists of words and spaces. Words consist of lower case English letters and digits from 0 to 9.

Input Format For Custom Testing

A single line of input consists of a string, encryptedMessage.

Sample Case 0

Sample Input For Custom Testing

seaside the to sent be to ne2ds army ten of team a

Sample Output

a team of ten army needs to be sent to the seaside
Sample Case 1

Sample Input For Custom Testing

a3b4q2i abcd2 abc

Sample Output

abc abcdd aaabbbbqqi

3. Java Program Flow

What is the output of the following program:

interface BaseI { void method(); }

class BaseC
{
   public void method()
   {
      System.out.println("Inside BaseC::method");
   }
}

class ImplC extends BaseC implements BaseI
{
   public static void main(String []s)
   {
      (new ImplC()).method();
   }
}
Pick ONE option
null
Compilation fails
Inside BaseC::method
None of the above

The output of the given program will be:

Inside BaseC::method

Explanation:
The program defines an interface BaseI with a single method method(). It also defines a class BaseC that implements the BaseI interface and provides an implementation for the method() method. Lastly, it defines a class ImplC that extends BaseC and also implements the BaseI interface.

In the main() method of ImplC, an instance of ImplC is created using the new keyword, and its method() method is invoked.

Since ImplC extends BaseC, it inherits the method() implementation from BaseC. Thus, when method() is called on the instance of ImplC, it will execute the implementation of method() in BaseC, which prints “Inside BaseC::method” to the console.

Therefore, the output of the program will be “Inside BaseC::method”. The correct option is:

Inside BaseC::method

4. Java : Threads – Static Analysis

What is the output of the following Java snippet?

class SampleDemo implements Runnable {

   private Thread t;
   private String threadName;
   
   SampleDemo (String threadName){
       this.threadName = threadName;
   }

   public void run() 
   {
       while (true)
            System.out.print(threadName);
   }

   public void start ()
   {
      if (t == null)
      {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThread {

   public static void main(String args[]) {

      SampleDemo A = new SampleDemo( "A");
      SampleDemo B = new SampleDemo( "B");

      B.start();
      A.start();
   }
}
Pick ONE option
ABABABAB…(pattern repeats).
BABABABA…(pattern repeats).
AABAABAA…(pattern repeats).
A pattern cannot be predicted and can vary each time the program is run.

I tried to run in on several problems. I couldn’t find the patterns. So maybe it was the last option. I went with it. If you find a pattern, let me know

5. Return Type

What is a covariant return type?

Pick ONE option
The overriding method can have derived type as the return type instead of the base type
The overriding method can have base type as the return type instead of the derived type
The return type is of the class type Covariant
The return type is void

The correct option is:

The overriding method can have derived type as the return type instead of the base type.

Covariant return type refers to the ability of an overriding method in a subclass to have a return type that is a subclass of the return type of the overridden method in the superclass. In other words, the return type of the overriding method can be a more specific (derived) type than the return type of the overridden method.

This feature was introduced in Java 5 to enhance the flexibility and expressiveness of method overriding. It allows for more precise method signatures and enables the use of polymorphism in a more intuitive way.

For example, consider a class hierarchy with a base class Animal and a subclass Cat:

				
					class Animal {
    public Animal reproduce() {
        // ...
    }
}

class Cat extends Animal {
    @Override
    public Cat reproduce() {
        // ...
    }
}
				
			

In this example, the reproduce() method in the Cat class overrides the reproduce() method in the Animal class and has a covariant return type. Instead of returning an Animal, it returns a Cat, which is a more specific type.

Therefore, the correct option is:

The overriding method can have derived type as the return type instead of the base type.