ICSE Class 10 Computer Applications — All Questions

357 solved questions from 18 papers. Filter by year, section or marks, or search the full bank.

Year
Section
Marks
Insight
1(i)1 Mark · 2026 · Section A · 2026 PaperFull page

The full form of JVM is:

Show SolutionHide Solution↓

Java Virtual Machine

Reason — JVM stands for Java Virtual Machine, which is responsible for executing Java bytecode and enables Java programs to run on any platform (platform independence).

1(ii)1 Mark · 2026 · Section A · 2026 PaperFull page

Which of the following occupies 2 bytes of storage?

Show SolutionHide Solution↓

\\

Reason —

  1. 25 is an integer literal. In Java, an int occupies 4 bytes, hence it is not correct.
  2. AM represents a string consisting of two characters. Each character occupies 2 bytes, so total memory required is 4 bytes, hence it is not correct.
  3. 35.2 is a double literal. In Java, a double occupies 8 bytes, hence it is not correct.
  4. \\ represents a single character (backslash) using an escape sequence ('\\'). In Java, a char occupies 2 bytes, hence it is correct.
1(iii)1 Mark · 2026 · Section A · 2026 PaperFull page

In a statement c = c + (x * d + e); which variable is an accumulator?

Show SolutionHide Solution↓

c

Reason — In the statement c = c + (x * d + e);, the variable c appears on both sides of the assignment and continuously stores the updated result by adding new values to its previous value, which is the defining property of an accumulator. The variables x, d, and e are only used to compute the expression once and do not store cumulative results, hence they are not accumulators.

1(iv)1 Mark · 2026 · Section A · 2026 PaperFull page

Which of the following is NOT an access specifier?

Show SolutionHide Solution↓

package

Reason — In Java, the valid access specifiers are private, protected, and public.

1(v)1 Mark · 2026 · Section A · 2026 PaperFull page

What is the output of the statement Math.pow(36, 6/5); ?

Show SolutionHide Solution↓

36.0

Reason — In the expression Math.pow(36, 6/5), the division 6/5 is performed first using integer division, which results in 1 (not 1.2). Therefore, the expression becomes Math.pow(36, 1), which evaluates to 36.0 since the pow() method returns a double value.

1(vi)1 Mark · 2026 · Section A · 2026 PaperFull page

Read the if program segment given below:

if(a > b)
z = 25;
else
z = 35;

Which one of the following is the correct conversion of the if program segment to ternary?

Show SolutionHide Solution↓

z = a > b ? 25 : 35;

Reason — The ternary operator follows the format condition ? value_if_true : value_if_false. In the given if-else statement, when a > b is true, z is assigned 25, otherwise it is assigned 35. Hence, the correct equivalent ternary expression is z = a > b ? 25 : 35;.

1(vii)1 Mark · 2026 · Section A · 2026 PaperFull page

The output of the statement:

System.out.println(Character.toUpperCase('b') + 2); is:

Show SolutionHide Solution↓

68

Reason — The method Character.toUpperCase('b') converts 'b' to 'B'. In Java, when a character is used in an arithmetic expression, it is converted to its ASCII (Unicode) value. The ASCII value of 'B' is 66, and adding 2 gives 66 + 2 = 68. Hence, the output is 68.

1(viii)1 Mark · 2026 · Section A · 2026 PaperFull page

Consider the following statements:

Computer desktop = new Computer();
Computer Mainframe = new Computer();

Name the objects of the class given above:

Show SolutionHide Solution↓

desktop, Mainframe

Reason — In the given statements, Computer is the class name, while desktop and Mainframe are the object names (variables that store object references). Therefore, the objects of the class are desktop and Mainframe.

1(ix)1 Mark · 2026 · Section A · 2026 PaperFull page

The earth spins on its axis completing one rotation in a day. The earth revolves around the sun in 365 days to complete one revolution. What is the Java concept depicted in the given picture?

The earth spins on its axis completing one rotation in a day. The earth revolves around the sun in 365 days to complete one revolution. What is the Java concept depicted in the given picture. ICSE 2025 Computer Applications Solved Question Paper.
Show SolutionHide Solution↓

Nested loop

Reason — The Earth performs two repeated motions:

  • it rotates on its axis once every day, and
  • it revolves around the Sun in 365 days.

This means that for one complete revolution, the rotation is repeated many times. One activity is taking place repeatedly within another activity.

In Java, such a situation is represented by a nested loop, where:

  • the outer loop represents the revolution of the Earth around the Sun, and
  • the inner loop represents the daily rotation of the Earth on its axis.

Hence, the Java concept illustrated in this scenario is nested loop.

1(x)1 Mark · 2026 · Section A · 2026 PaperFull page

In the following method prototype to accept a character, an integer and return YES or NO, fill in the blank to complete the method prototype.

public ............... someMethod(char ch, int n)

Show SolutionHide Solution↓

String

Reason — The method is required to return "YES" or "NO", which are textual values. In Java, such values are represented using the String data type. Hence, the return type of the method should be String, not boolean, int, or double.

The complete method prototype:

public String someMethod(char ch, int n)

1(xi)1 Mark · 2026 · Section A · 2026 PaperFull page

In a calculator which Java feature allows multiple methods named calculate() for the different operations?

Show SolutionHide Solution↓

polymorphism

Reason — Polymorphism in Java allows multiple methods with the same name but different parameters (method overloading). In a calculator, different operations like addition, subtraction, etc., can be implemented using methods with the same name calculate() but with different parameter lists, which is a feature of polymorphism.

1(xii)1 Mark · 2026 · Section A · 2026 PaperFull page

Assertion (A): The result of the Java expression 3 + 7/2 is 6.

Reason (R): According to the hierarchy of operators in Java, addition is done first followed by division.

Show SolutionHide Solution↓

(A) is true and (R) is false.

Reason — In the expression 3 + 7/2, division has higher precedence than addition, so 7/2 is evaluated first using integer division, giving 3, and then added to 3 → 3 + 3 = 6, so Assertion (A) is true. However, the Reason (R) is incorrect because it wrongly states that addition is performed before division, which is not true in Java operator precedence.

1(xiii)1 Mark · 2026 · Section A · 2026 PaperFull page

What is the type of parameter to be given for the method parseInt()?

Show SolutionHide Solution↓

String

Reason — The method Integer.parseInt() is used to convert a numeric value given in String form into an integer. Therefore, it requires a String parameter as input, not double, char, or int.

1(xiv)1 Mark · 2026 · Section A · 2026 PaperFull page

To extract the word NOW from the word "ACKNOWLEDGEMENT", the Java statement "ACKNOWLEDGEMENT".substring(3, ...............) is used.

Choose the correct number to fill in the blank.

Show SolutionHide Solution↓

6

Reason — The method substring(beginIndex, endIndex) extracts characters from the starting index up to (but not including) the ending index. In "ACKNOWLEDGEMENT", the word "NOW" starts at index 3 (N) and ends at index 5 (W). Since the ending index is exclusive, we use 5 + 1 = 6 to include index 5. Hence, substring(3, 6) correctly extracts "NOW".

1(xv)1 Mark · 2026 · Section A · 2026 PaperFull page

The output of the below statement is:

String a[] = {"Atasi", "Aditi", "Anant", "Amit", "Ahana"};
System.out.println(a[1].charAt(1) + "*" + a[2].charAt(2));
Show SolutionHide Solution↓

d*a

Reason — In the array, a[1] is "Aditi", so a[1].charAt(1) gives 'd'. Similarly, a[2] is "Anant", so a[2].charAt(2) gives 'a'. The expression uses "*" as a String, so the + operator performs concatenation, resulting in "d*a".

1(xvi)1 Mark · 2026 · Section A · 2026 PaperFull page

Which of the following String methods returns a negative value?

Show SolutionHide Solution↓

compareTo()

Reason — The compareTo() method compares two strings lexicographically and returns an integer value which can be positive, zero, or negative depending on the comparison. The methods length() returns the length (non-negative), equals() returns a boolean, and charAt() returns a character, so none of them can return a negative value.

1(xvii)1 Mark · 2026 · Section A · 2026 PaperFull page

An array with 3 elements is arranged in a ascending order as follows:

An array with 3 elements is arranged in a ascending order as follows. ICSE 2025 Computer Applications Solved Question Paper.

Name the technique used:

Show SolutionHide Solution↓

Bubble sort

Reason — The array is arranged in ascending order by repeatedly comparing and swapping adjacent elements. First, 4 and 1 are swapped to get 1 4 3, and then 4 and 3 are swapped to get 1 3 4. This step-by-step swapping of adjacent elements is the characteristic feature of Bubble Sort.

1(xviii)1 Mark · 2026 · Section A · 2026 PaperFull page

The sales made by 5 salesmen selling 5 products is stored in a two-dimensional array of integer data type. How many bytes does the array occupy?

Show SolutionHide Solution↓

100

Reason — The data is stored in a two-dimensional array for 5 salesmen and 5 products, so total elements = 5 × 5 = 25. Each element is of type int, and in Java an int occupies 4 bytes. Therefore, total memory required = 25 × 4 = 100 bytes.

1(xix)1 Mark · 2026 · Section A · 2026 PaperFull page

Assertion (A): The substring() method modifies the original String.

Reason (R): The substring() method can extract part of a String starting from a specific index.

Show SolutionHide Solution↓

(A) is false and (R) is true.

Reason — In Java, Strings are immutable, so the substring() method does not modify the original String, it returns a new String, making Assertion (A) false. However, the method does extract a part of the String starting from a specific index, which makes Reason (R) true.

1(xx)1 Mark · 2026 · Section A · 2026 PaperFull page

In constructor overloading, all constructors should have the the same name as of the class but with a different set of ............... .

Show SolutionHide Solution↓

Parameters

Reason — In constructor overloading, all constructors must have the same name as the class but differ in their parameter list (number, type, or order of parameters).

2(i)1 Mark · 2026 · Section A · 2026 PaperFull page

Rewrite the following program segment using a for loop.

int a = 5, b = 10;
while (b > 0)
{ b -= 2;
}
System.out.println(a * b);
Show SolutionHide Solution↓
int a = 5, b = 10;
for( ; b > 0; b -= 2)
{
}
System.out.println(a * b);
2(ii)1 Mark · 2026 · Section A · 2026 PaperFull page

Evaluate the Java expression:

x = a * b % (++c) + (++a) + (--b);

if a = 7, b = 8, c = 2

Show SolutionHide Solution↓

x = a * b % (++c) + (++a) + (--b)
x = 7 * 8 % (++c) + (++a) + (--b)
x = 7 * 8 % 3 + 8 + 7 (c becomes 3, a becomes 8, b becomes 7)
x = 56 % 3 + 8 + 7
x = 2 + 8 + 7
x = 17

2(iii)1 Mark · 2026 · Section A · 2026 PaperFull page

Write the Java expression to find the sum of cube root of x and the absolute value of y.

Show SolutionHide Solution↓

Math.cbrt(x) + Math.abs(y)

2(iv)1 Mark · 2026 · Section A · 2026 PaperFull page

Users must be above 10 years to open a self-operated bank account. Write this logic using a ternary operator and store the result (the eligibility message) in a String variable named idStatus and print it.

Show SolutionHide Solution↓
String idStatus = (age > 10) ? "Eligible" : "Not Eligible";
System.out.println(idStatus);
2(v)1 Mark · 2026 · Section A · 2026 PaperFull page

Give the output of the following program segment:

String S = "GRACIOUS".substring(4);
System.out.println(S);
System.out.println("GLAMOROUS".endsWith(S));
Show SolutionHide Solution↓
IOUS
false
  • The substring() method is used to extract a part of a string starting from a specified index. In the given statement, "GRACIOUS".substring(4) extracts characters from index 4 to the end, resulting in "IOUS".

  • The endsWith() method checks whether a string ends with a specified sequence of characters and returns a boolean value. Here, "GLAMOROUS".endsWith("IOUS") checks if the string ends with "IOUS", which is false, so it prints false.

2(vi)1 Mark · 2026 · Section A · 2026 PaperFull page

Give the output of the following program segment and mention how many times the loop is executed.

int K = 1;
do
{K += 2;
System.out.println(K);
} while (K <= 6);
Show SolutionHide Solution↓

Number of times the loop is executed: 3 times

3
5
7
  • The do-while loop executes the block first and then checks the condition.
  • Initial value: K = 1
    • 1st iteration: K = 1 + 2 = 3 → printed
    • Condition: 3 <= 6 → true
  • 2nd iteration: K = 3 + 2 = 5 → printed
    • Condition: 5 <= 6 → true
  • 3rd iteration: K = 5 + 2 = 7 → printed
    • Condition: 7 <= 6 → false → loop stops

Hence, the loop executes 3 times.

2(vii)1 Mark · 2026 · Section A · 2026 PaperFull page

The following program segment calculates and displays the factorial of a number. [Example : Factorial of 5 is 1 x 2 x 3 x 4 x 5 = 120]

int p, n = 5, f = 0;
for(p = n; p > 0; p--)
f *= p;
System.out.println(f);

Name the type of error if any; correct the statement to get the desired output.

Show SolutionHide Solution↓

The logical error occurs because the factorial variable f is initialized to 0. Since multiplication with 0 always results in 0, the loop will never produce the correct factorial value.

The corrected code is as follows:

int p, n = 5, f = 1;
for(p = n; p > 0; p--)
f *= p;
System.out.println(f);
2(viii)1 Mark · 2026 · Section A · 2026 PaperFull page

int X[][] = {{4, 5}, {7, 2}, {19, 4}, {7, 4}};

Write the index of the maximum element and the index of the minimum element of the array.

Show SolutionHide Solution↓

Maximum element index: X[2][0]
Minimum element index: X[1][1]

This is a 2D array (matrix) with 4 rows and 2 columns. Each element is accessed using X[row][column].

RowColumn 0Column 1
045
172
2194
374

To find the maximum element, all values in the array are compared. The largest value is 19, which is located in row 2 and column 0. Hence, its index is X[2][0].

To find the minimum element, all values are compared again. The smallest value is 2, which is located in row 1 and column 1. Hence, its index is X[1][1].

2(ix)1 Mark · 2026 · Section A · 2026 PaperFull page

The following program segment swaps the first element and the second element of the given array without using the third variable, fill in the blanks with appropriate java statements:

void swap()
{ int x[] = {4, 8, 19, 24, 15};
(1) ............... ;
(2) ............... ;
x[0] = x[0] / x[1];
System.out.println(x[0] + " " + x[1]); }
Show SolutionHide Solution↓
void swap()
{ int x[] = {4, 8, 19, 24, 15};
x[0] = x[0] * x[1];
x[1] = x[0] / x[1];
x[0] = x[0] / x[1];
System.out.println(x[0] + " " + x[1]); }

Explanation

The first two elements of the array are:

  • x[0] = 4
  • x[1] = 8

The swapping is done without using a third variable by using multiplication and division.

Step 1

x[0] = x[0] * x[1];

So,

x[0] = 4 * 8 = 32

Now:

  • x[0] = 32
  • x[1] = 8

Step 2

x[1] = x[0] / x[1];

So,

x[1] = 32 / 8 = 4

Now:

  • x[0] = 32
  • x[1] = 4

Step 3

x[0] = x[0] / x[1];

So,

x[0] = 32 / 4 = 8

Now:

  • x[0] = 8
  • x[1] = 4

Thus, the values of the first and second elements are interchanged.

Output

8 4
2(x)1 Mark · 2026 · Section A · 2026 PaperFull page

Name the following:

(a) The return data type of the method equals().

(b) The String method which has no parameter and returns a String.

Show SolutionHide Solution↓

(a) boolean

(b) toUpperCase()

3Written · 2026 · Section B · 2026 PaperFull page

Define a class named StepTracker with the following specifications:

Member Variables:

  • String name – stores the user's name
  • int sw – stores the total number of steps walked by the user.
  • double cb – stores the estimated calories burned by the user.
  • double km – stores the estimated distance walked in kilometers.

Member Methods:

  • void accept() – to input the name and the steps walked using Scanner class methods only.
  • void calculate() – calculates calories burned and distance in km based on steps walked using the following estimation table:
MetricCalculation Formula
Calories Burnedsteps walked x 0.04 (e.g., 1 step burns 0.04 calories)
Distance (Km)steps walked / 1300 (e.g., 1300 steps is approx. 1 km)
  • void display() – Display the calories burned, distance in km and the user's name.

Write a main method to create an object of the class and invoke the methods.

Show SolutionHide Solution↓
import java.util.Scanner;

class StepTracker
{
    String name;
    int sw;
    double cb, km;

    public void accept()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter name: ");
        name = sc.nextLine();
        System.out.print("Enter steps walked: ");
        sw = sc.nextInt();
    }

    public void calculate()
    {
        cb = sw * 0.04;
        km = sw / 1300.0;
    }

    public void display()
    {
        System.out.println("Name: " + name);
        System.out.println("Calories Burned: " + cb);
        System.out.println("Distance (km): " + km);
    }

    public static void main(String args[])
    {
        StepTracker obj = new StepTracker();
        obj.accept();
        obj.calculate();
        obj.display();
    }
}
BlueJ output of StepTracker.java
4Written · 2026 · Section B · 2026 PaperFull page

Write a program to accept the designations of 100 employees in a single dimensional array. Accept the designation from the user and print the total number of employees with the designation given by the user as input.

Example:

TraineeManagerChefManagerDirectorManager

Input: Manager Output: 3

Show SolutionHide Solution↓
import java.util.Scanner;

class EmployeeDesignation
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        String desig[] = new String[100];
        int i, count = 0;
        String search;

        for(i = 0; i < 100; i++)
        {
            System.out.print("Enter designation: ");
            desig[i] = sc.nextLine();
        }

        System.out.print("Enter designation to search: ");
        search = sc.nextLine();

        for(i = 0; i < 100; i++)
        {
            if(desig[i].equalsIgnoreCase(search))
            count++;
        }

        System.out.println("Total employees with designation " + search + ": " + count);
    }
}
BlueJ output of EmployeeDesignation.java
5Written · 2026 · Section B · 2026 PaperFull page

Write a program to accept a two-dimensional integer array of order 4 x 5 as input from the user. Check if it is a Sparse Matrix or not. A matrix is considered to be a sparse, if the total number of zero elements is greater than the total number of non-zero elements. Print appropriate messages.

Example:

43010
10020
10100
03200

Number of zero elements = 11
Number of non zero elements = 9
Matrix is a Sparse Matrix

Show SolutionHide Solution↓
import java.util.Scanner;

class SparseMatrix
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        int a[][] = new int[4][5];
        int i, j, zero = 0, nonzero = 0;

        for(i = 0; i < 4; i++)
        {
            for(j = 0; j < 5; j++)
            {
                System.out.print("Enter element: ");
                a[i][j] = sc.nextInt();
            }
        }

        for(i = 0; i < 4; i++)
        {
            for(j = 0; j < 5; j++)
            {
                if(a[i][j] == 0)
                    zero++;
                else
                    nonzero++;
            }
        }

        System.out.println("Number of zero elements = " + zero);
        System.out.println("Number of non zero elements = " + nonzero);

        if(zero > nonzero)
            System.out.println("Matrix is a Sparse Matrix");
        else
            System.out.println("Matrix is not a Sparse Matrix");
    }
}
BlueJ output of SparseMatrix.java
6Written · 2026 · Section B · 2026 PaperFull page

Write a program to accept a number and check if it is a Mark number or not. A number is said to be Mark when sum of the squares of each digit is an even number as well as the last digit of the sum and the last digit of the number given is same.

Example: n = 246
sum = 2 x 2 + 4 x 4 + 6 x 6 = 56
56 is an even number as well as last digit is 6 for both sum as well as the number.

Show SolutionHide Solution↓
import java.util.Scanner;

class MarkNumber
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        int n, d, sum = 0, temp;

        System.out.print("Enter number: ");
        n = sc.nextInt();

        temp = n;

        while(n > 0)
        {
            d = n % 10;
            sum += d * d;
            n = n / 10;
        }

        if(sum % 2 == 0 && (sum % 10 == temp % 10))
            System.out.println("It is a Mark Number");
        else
            System.out.println("It is not a Mark Number");
    }
}
BlueJ output of MarkNumber.java BlueJ output of MarkNumber.java
7Written · 2026 · Section B · 2026 PaperFull page

Define a class to overload the method format as follows:

void format(): To print the following pattern using Nested for loops only.

Show SolutionHide Solution↓
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5

int format(String s): To calculate and return the sum of ASCII codes of each character of the String.

Example: CAB
Output: 67 + 65 + 66
198

void format(int n): To calculate and display the sum of natural numbers up to n given by the formula.

$\frac{n(n+1)}{2}$

import java.util.Scanner;

class OverloadFormat
{
    public void format()
    {
        int i, j;
        for(i = 1; i <= 5; i++)
        {
            for(j = i; j <= 5; j++)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }

    public int format(String s)
    {
        int i, sum = 0;
        for(i = 0; i < s.length(); i++)
        {
            sum += (int)s.charAt(i);
        }
        return sum;
    }

    public void format(int n)
    {
        int sum;
        sum = n * (n + 1) / 2;
        System.out.println("Sum = " + sum);
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        OverloadFormat obj = new OverloadFormat();

        obj.format();

        System.out.print("Enter a string: ");
        String str = sc.nextLine();
        int result = obj.format(str);
        System.out.println("Sum of ASCII = " + result);

        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        obj.format(num);
    }
}
BlueJ output of OverloadFormat.java
8Written · 2026 · Section B · 2026 PaperFull page

Write a program to accept a word and print the Symbolic of the accepted word.

Symbolic word is formed by extracting the characters from the first consonant, then add characters before the first consonant of the accepted word and end with "TR".

Example:
AIRWAYS Symbolic word is RWAYSAITR
BEAUTY Symbolic word is BEAUTYTR

Show SolutionHide Solution↓
import java.util.Scanner;

class SymbolicWord
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        String w, res;
        int i, pos = -1;

        System.out.print("Enter a word: ");
        w = sc.nextLine();
        int l = w.length();

        for(i = 0; i < l; i++)
        {
            char ch = Character.toUpperCase(w.charAt(i));
            if(!(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U'))
            {
                pos = i;
                break;
            }
        }

        if(pos != -1)
            res = w.substring(pos) + w.substring(0, pos) + "TR";
        else
            res = w + "TR";

        System.out.println("Symbolic word: " + res);
    }
}
BlueJ output of SymbolicWord.java
1(i)1 Mark · 2025 · Section A · 2025 PaperFull page

Character class methods are found in the package called:

Show SolutionHide Solution↓

java.lang

Reason — The Character class methods are found in the java.lang package because this package contains fundamental classes that are automatically available in every Java program. The Character class provides methods to work with characters, such as checking whether a character is a letter, digit, uppercase, or lowercase.

1(ii)1 Mark · 2025 · Section A · 2025 PaperFull page

System.out.println('Z' + 32); will display:

Show SolutionHide Solution↓

122

Reason — In the statement System.out.println('Z' + 32);, the character 'Z' is converted to its ASCII value 90, and then 32 is added to it, giving the result 122. Since the + operator with a character and an integer results in an integer, the output displayed will be 122.

1(iii)1 Mark · 2025 · Section A · 2025 PaperFull page

double x[] = {2.5, 4.5, 5.5, 6.4}; occupies ............... bytes.

Show SolutionHide Solution↓

32

Reason — The double data type in Java occupies 8 bytes of memory. In the array double x[] = {2.5, 4.5, 5.5, 6.4};, there are 4 elements, and each element takes 8 bytes. So, the total memory occupied is 4 × 8 = 32 bytes.

1(iv)1 Mark · 2025 · Section A · 2025 PaperFull page

The output of 42 / 6 % 2 is:

Show SolutionHide Solution↓

1

Reason — According to operator precedence in Java, division (/) and modulus (%) have the same priority and are evaluated from left to right.

42 / 6 % 2

= 7 % 2

= 1

1(v)2 Marks · 2025 · Section A · 2025 PaperFull page

Consider the two-dimensional array P[2][3], of peripherals (input/output devices) given below, state the index of the device Barcode Scanner.

Consider the two-dimensional array P[2][3], of peripherals (input/output devices) given below, state the index of the device Barcode Scanner. ICSE 2025 Computer Applications Solved Question Paper.
Show SolutionHide Solution↓

P[1][1]

Reason — In a two-dimensional array P[2][3], the first index represents the row and the second index represents the column. The device "barcode scanner" is located in the second row (index 1) and the second column (index 1), so its index is P[1][1].

1(vi)1 Mark · 2025 · Section A · 2025 PaperFull page

Which of the following is user-defined data type?

Which of the following is user-defined data type. ICSE 2025 Computer Applications Solved Question Paper.
Show SolutionHide Solution↓

1 and 3

Reason — A user-defined data type is a data type defined by the user. In the given options, array and class are user-defined data types because they are created by the user to store multiple values or define their own structure. double and boolean are predefined (primitive) data types.

1(vii)1 Mark · 2025 · Section A · 2025 PaperFull page

Select the infinite loop:

Show SolutionHide Solution↓

for(int i = 2; i != 0; i -= 3)

Reason — The loop for(int i = 2; i != 0; i -= 3) is an infinite loop because the value of i starts at 2 and decreases by 3 in every iteration. Since i will never become 0 (it will take values like 2, -1, -4, -7, etc.), the condition i != 0 will always be true. Therefore, the loop will continue to run forever.

1(viii)1 Mark · 2025 · Section A · 2025 PaperFull page

The output of Math.max(-7, Math.min(-5, -4)) is:

Show SolutionHide Solution↓

-5

Reason — The method Math.min(-5, -4) returns the smaller of the two values, which is -5. Then, Math.max(-7, -5) returns the greater of the two values, which is -5. Hence, the final output of Math.max(-7, Math.min(-5, -4)) is -5.

1(ix)1 Mark · 2025 · Section A · 2025 PaperFull page

Which of the following is true for the given object creation statement?

Game cricket = new Game();

Show SolutionHide Solution↓

Game is a class and cricket is an object

Reason — In the statement Game cricket = new Game();, Game is the name of the class, and cricket is the object (or instance) created from that class. The new keyword is used to create a new object of the class. Therefore, Game is the class, and cricket is the object.

1(x)1 Mark · 2025 · Section A · 2025 PaperFull page

Post Office is an example for ............... access specifier.

Show SolutionHide Solution↓

public

Reason — A Post Office is accessible to everyone in a community, just like a public access specifier in programming, which allows members of a class to be accessible from any other class or part of the program. Hence, a Post Office is an example of public access specifier.

1(xi)1 Mark · 2025 · Section A · 2025 PaperFull page

Assertion (A): In switch case, break statement avoids fall through.

Reason (R): break statement helps to execute only one case at a time.

Show SolutionHide Solution↓

Both (A) and (R) are true and (R) is a correct explanation of (A).

Reason — In a switch case, the break statement stops the program from executing the next cases after a match is found. Without the break, the program would continue to run all the cases below the matched one (called fall through). Therefore, the break statement helps to execute only one case at a time.

1(xii)1 Mark · 2025 · Section A · 2025 PaperFull page

A physical education teacher asks the students to do the side stretch as shown below, 10 times. Which programming construct the teacher uses?

A physical education teacher asks the students to do the side stretch as shown below, 10 times. Which programming construct the teacher uses? ICSE 2025 Computer Applications Solved Question Paper.
Show SolutionHide Solution↓

for

Reason — The teacher asks the students to do the side stretch 10 times, which means repeating the same action multiple times. In programming, the for loop is used to repeat a block of code a specific number of times. Hence, the teacher is using the concept similar to a for loop to instruct repetition.

1(xiii)1 Mark · 2025 · Section A · 2025 PaperFull page

The index(subscript) of the last element of an array ar[] is:

Show SolutionHide Solution↓

ar.length – 1

Reason — In Java, the length of an array ar is given by ar.length (without parentheses). Since array indexing starts from 0, the last element's index is always one less than the total length of the array. Therefore, the index of the last element is ar.length – 1.

1(xiv)1 Mark · 2025 · Section A · 2025 PaperFull page

Assertion (A): A clock is a real-life example of nested loops.

Reason (R): The hour hand moves through 12 positions, while the minute hand moves through 60 positions within each hour.

Show SolutionHide Solution↓

Both (A) and (R) are true and (R) is a correct explanation of (A).

Reason — A clock is a real-life example of nested loops because the hour hand moves through 12 positions, and within each hour, the minute hand moves through 60 positions. This shows that one loop (minute hand) runs inside another loop (hour hand), which is similar to the concept of nested loops in programming.

1(xv)1 Mark · 2025 · Section A · 2025 PaperFull page

Which of the following pairs of methods will cause a compile-time error due to incorrect method overloading?

Show SolutionHide Solution↓

void test(int a) and int test(int a)

Reason — In Java, method overloading depends on the method's name and its parameter list (number or type of parameters). The return type alone is not considered for method overloading. So, void test(int a) and int test(int a) have the same name and same parameter list, which causes a compile-time error because they differ only in return type, not in parameters.

1(xvi)1 Mark · 2025 · Section A · 2025 PaperFull page

Which of the following converts "25" to 25.0?

Show SolutionHide Solution↓

Double.parseDouble("25")

Reason — In Java, the method Double.parseDouble("25") is used to convert a string containing a numeric value into a double data type. It belongs to the Double class and takes a string as an argument, returning its equivalent double value.

1(xvii)1 Mark · 2025 · Section A · 2025 PaperFull page

Consider the program segment:

int p = 0;
for(p = 4; p > 0; p -= 2);
System.out.print(p);
System.out.println(p);

The above statement will display:

Show SolutionHide Solution↓

00

Reason

1. Initialization: int p = 0;

  • This line declares an integer variable p and initializes it to 0.

2. For Loop: for(p = 4; p > 0; p -= 2);

  • p = 4 → loop starts with p assigned the value 4.
  • Condition: p > 0 is true (since 4 > 0).
  • The semicolon (;) at the end means the loop body is empty and does nothing.
  • Update: p -= 2 decreases p by 2.
  • Next value of p = 2 → still > 0, so the loop continues.
  • Decrease again: p -= 2 → p = 0 → now the condition p > 0 is false, loop stops.

3. After the Loop: p is now 0.

4. Output Statements:

  • System.out.print(p); prints 0 without moving to the next line.
  • System.out.println(p); prints 0 and moves to the next line.
1(xviii)1 Mark · 2025 · Section A · 2025 PaperFull page

The output of the below statement is:

System.out.println("I said, \"It\'s wise to obey elders.\"");

Show SolutionHide Solution↓

I said, "It's wise to obey elders."

Reason — In Java, the backslash \ is used as an escape character. The statement uses escape sequences:

  • \" to include double quotes inside a string.
  • \' to include a single quote inside a string.

So the output preserves both the double quotes around "It's wise to obey elders." and the apostrophe in It's.

Hence, the output is: I said, "It's wise to obey elders."

1(xix)1 Mark · 2025 · Section A · 2025 PaperFull page

What is the output of the statement given below?

"ANGER".compareTo("ANGEL")

Show SolutionHide Solution↓

6

Reason — The compareTo() method compares two strings lexicographically by comparing their characters one by one. It returns the difference between the first pair of characters that differ in the two strings.

Here, comparing "ANGER" and "ANGEL":

  • Characters 'A', 'N', 'G', and 'E' are the same in both strings at positions 0 to 3.
  • At position 4, 'R' (ASCII value 82) in "ANGER" is compared with 'L' (ASCII value 76) in "ANGEL".
  • The difference is 82 - 76 = 6.

Thus, the output is 6.

1(xx)1 Mark · 2025 · Section A · 2025 PaperFull page

Consider the following program segment in which the statements are jumbled.
Choose the correct order of statements to calculate and return the factorial of 4.

for(k = 1; k <= 4; k++) → 1
return fa; → 2
long fa = 1, k; → 3
fa *= k; → 4
Show SolutionHide Solution↓

3, 1, 4, 2

Reason — To calculate and return the factorial of 4 using a loop, we must follow the proper sequence of statements:

  1. long fa = 1, k; – This is the declaration and initialization of variables fa and k.
  2. for(k = 1; k <= 4; k++) – This sets up a loop to run from 1 to 4.
  3. fa *= k; – This multiplies the current value of fa by k during each iteration.
  4. return fa; – This returns the final calculated factorial value.

So, the correct order is: 3, 1, 4, 2, which correctly calculates and returns the factorial.

2(i)1 Mark · 2025 · Section A · 2025 PaperFull page

Write the Java expression to find the product of square root of P and the square root of Q using the methods of Math class.

Show SolutionHide Solution↓

Math.sqrt(P) * Math.sqrt(Q)

2(ii)1 Mark · 2025 · Section A · 2025 PaperFull page

Write the output of the following String method:

String x = "talent";
String y = "matrix";
System.out.println(x.substring(3).concat(y.substring(3)));
Show SolutionHide Solution↓
entrix
  • x.substring(3) returns the substring of "talent" from index 3 onwards, i.e., "ent".
  • y.substring(3) returns the substring of "matrix" from index 3 onwards, i.e., "rix".
  • The concat() method joins both substrings: "ent" + "rix" = "entrix".
2(iii)1 Mark · 2025 · Section A · 2025 PaperFull page

Write the Java statement for creating an object named 'sifra' of the class 'Robot', which takes three double parameters.

Show SolutionHide Solution↓

Robot sifra = new Robot(2.5, 3.5, 4.5);

2(iv)1 Mark · 2025 · Section A · 2025 PaperFull page

Convert the given loop into exit-controlled loop.

int a, b;
for(a = 10, b = 1; a >= 1; a -= 2){
b += a;
b++;
}
System.out.print(b);
Show SolutionHide Solution↓
int a = 10, b = 1;
do {
    b += a;
    b++;
    a -= 2;
} while(a >= 1);
System.out.print(b);
2(v)1 Mark · 2025 · Section A · 2025 PaperFull page

Consider and give the output of the following program:

class report{
    int a, b;
    report(){
        a = 10;
        b = 15;
    }
    report(int x, int y){
        a = x;
        b = y;
    }
    void print(){
        System.out.println(a * b);
    }
    static void main(){
        report r = new report();
        r.print();
        report p = new report(4, 5);
        p.print();
    }
}
Show SolutionHide Solution↓
150
20

1. Class Definition:

  • The class report is defined with two integer variables: a and b.

2. Constructors:

  • Default constructor: report()
    This constructor sets the values of a and b to 10 and 15, respectively, when an object is created without any parameters.

  • Parameterized constructor: report(int x, int y)
    This constructor accepts two integer values x and y and assigns them to a and b.

3. Method print():

  • This method prints the product of the two variables a and b.

4. Static method main():
Inside the main() method:

  • First, an object r of class report is created using the default constructor.
  • Then, the print() method is called on r which prints the product 10 * 15 = 150.
  • Next, an object p is created using the parameterized constructor with values 4 and 5.
  • The print() method is called on p which prints the product 4 * 5 = 20.
2(vi)1 Mark · 2025 · Section A · 2025 PaperFull page

(a) Name one String method which results in positive integer only.

(b) Name one String method which results in a character.

Show SolutionHide Solution↓

(a) length()

(b) charAt()

2(vii)1 Mark · 2025 · Section A · 2025 PaperFull page

John was asked to write a Java code to calculate the surface area of a cone. The following code was written by him: Surface area of cone is A = πrl

l = $\sqrt{r^2 + h^2}$

class area{
    double area(double r, double h){
        double l, a;
        a = 22.0 / 7 * r * l;
        l = Math.sqrt(r * r + h * h);
        return a;
    }
}

Specify the type of the error in the above program, correct and write the program to be error free.

Show SolutionHide Solution↓

The compile-time error occurs because the variable l is used before it is initialized.

The corrected code is as follows:

class area{
    double area(double r, double h){
        double l, a;
        l = Math.sqrt(r * r + h * h);
        a = 22.0 / 7 * r * l;
        return a;
    }
}
2(viii)1 Mark · 2025 · Section A · 2025 PaperFull page

Consider the following array and answer the questions given below:

int a[] = {12, 10, 8, 4, 6, 2, 3, 5, 7};

(a) What is the output of System.out.print(a[0] + a[5]);?

(b) What is the index (subscript) of the largest element of the array a[]?

Show SolutionHide Solution↓

(a) 14

(b) The largest element in the array is 12, which is at index 0.

  • a[0] is 12.
  • a[5] is 2.
  • Sum = 12 + 2 = 14.
2(ix)1 Mark · 2025 · Section A · 2025 PaperFull page

(a) Write the Java statement to initialize the first 6 odd numbers in a 3 × 2 array.

(b) What is the result of x[0][1] + x[2][1] of the above array?

Show SolutionHide Solution↓

(a) x[3][2] = {{1, 3}, {5, 7}, {9, 11}};

(b) 14

  • x[0][1] = 3.
  • x[2][1] = 11.
  • Sum = 3 + 11 = 14.
2(x)1 Mark · 2025 · Section A · 2025 PaperFull page

Give the output of the following program segment and specify how many times the loop is executed.

String s = "JAVA";
for(i = 0; i < s.length(); i += 2)
    System.out.println(s.substring(i));
Show SolutionHide Solution↓
JAVA
VA

The loop executes 2 times.

  • The string x contains the value "JAVA", which has a length of 4.
  • The for loop initializes i to 0 and increments it by 2 in each iteration (i = 0, 2).
  • In the first iteration, when i is 0, x.substring(0) extracts the substring from index 0 to the end, which is "JAVA". This is printed.
  • In the second iteration, when i is 2, x.substring(2) extracts the substring from index 2 to the end, which is "VA". This is printed.
  • When i becomes 4, the condition i < x.length() (i.e., 4 < 4) becomes false, so the loop terminates.
  • Therefore, the loop executes exactly 2 times, printing the substrings "JAVA" and "VA".
3Written · 2025 · Section B · 2025 PaperFull page

Define a class named CloudStorage with the following specifications:
Member Variables:
int acno – stores the user’s account number
int space – stores the amount of storage space in GB purchased by the user
double bill – stores the total price to be paid by the user
Member Methods:
void accept() – prompts the user to input their account number and storage space using Scanner class methods only.
void calculate() – calculates the bill total price based on the storage space purchased using the pricing table provided:

Storage rangePrice per GB (Rs)
First 15 GB15
Next 15 GB13
Above 30 GB11

void display() – displays the account number, storage space and bill to be paid.

Write a main method to create an object of the class and invoke the methods of the class with respect to the object.

Show SolutionHide Solution↓
import java.util.Scanner;
class CloudStorage{
    int acno;
    int space;
    double bill;
    public void accept(){
        Scanner in = new Scanner(System.in);
        System.out.print("Account number: ");
        acno = in.nextInt();
        System.out.print("Space: ");
        space = in.nextInt();
    }
    public void calculate(){
        if(space <= 15)
            bill = space * 15;
        else if(space <= 30)
            bill = 225 + (space - 15) * 13;
        else
            bill = 420 + (space - 30) * 11;
    }
    public void display(){
        System.out.println("Account No. " + acno);
        System.out.println("Storage space: " + space);
        System.out.println("Bill: " + bill);
    }
    public static void main(String[] args){
        CloudStorage obj = new CloudStorage();
        obj.accept();
        obj.calculate();
        obj.display();
    }
}
BlueJ output of CloudStorage.java BlueJ output of CloudStorage.java BlueJ output of CloudStorage.java
4Written · 2025 · Section B · 2025 PaperFull page

Define a class to accept values into a 4 × 4 integer array. Calculate and print the NORM of the array.
NORM is the square root of sum of squares of all elements.

Show SolutionHide Solution↓
1	2	1	3
5	2	1	6
3	6	1	2
3	4	6	3

Sum of squares of elements = 1 + 4 + 1 + 9 + 25 + 4 + 1 + 36 + 9 + 36 + 1 + 4 + 9 + 16 + 36 + 9 = 201
NORM = Square root of 201 = 14.177446878757825

import java.util.Scanner;
class Norm{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int a[][] = new int[4][4];
        int sum = 0;
        System.out.println("Enter array elements:");
        for(int i = 0; i < 4; i++){
            for(int j = 0; j < 4; j++){
                a[i][j] = in.nextInt();
            }
        }
        
        for(int i = 0; i < 4; i++){
            for(int j = 0; j < 4; j++){
                sum += a[i][j] * a[i][j];
            }
        }
        
        double root = Math.sqrt(sum);
        System.out.println("NORM = " + root);
    }
}
BlueJ output of Norm.java
5Written · 2025 · Section B · 2025 PaperFull page

Define a class to accept a String and print if it is a Super String or not. A String is Super if the number of uppercase letters are equal to the number of lowercase letters. [Use Character and String methods only]
Example: “COmmITmeNt”
Number of uppercase letters = 5
Number of lowercase letters = 5
String is a Super String

Show SolutionHide Solution↓
import java.util.Scanner;
class SuperString{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the string: ");
        String s = in.nextLine();
        int upper = 0;
        int lower = 0;
        int l = s.length();
        for(int i = 0; i < l; i++){
            char ch = s.charAt(i);
            if(Character.isUpperCase(ch))
                upper++;
            else if(Character.isLowerCase(ch))
                lower++;
        }
        if(upper == lower)
            System.out.println("String is a Super String");
        else
            System.out.println("String is not a Super String");
    }
}
BlueJ output of SuperString.java
6Written · 2025 · Section B · 2025 PaperFull page

Define a class to initialize the following data in an array.
Search for a given character input by the user, using the Binary Search technique.
Print “Search successful” if the character is found otherwise print “Search is not successful”.
‘A’, ‘H’, ‘N’, ‘P’, ‘S’, ‘U’, ‘W’, ‘Y’, ‘Z’, ‘b’, ‘d’

Show SolutionHide Solution↓
import java.util.Scanner;
class Search{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        char a[] = {'A', 'H', 'N', 'P', 'S', 'U', 'W', 'Y', 'Z', 'b', 'd'};
        System.out.print("Character to be searched: ");
        char key = in.next().charAt(0);
        int low = 0;
        int high = a.length - 1;
        int mid = 0;
        while(low <= high){
            mid = (low + high) / 2;
            if(key == a[mid])
                break;
            else if(key < a[mid])
                high = mid - 1;
            else
                low = mid + 1;
        }
        if(low > high)
            System.out.println("Search is not successful");
        else
            System.out.println("Search is successful");
    }
}
BlueJ output of Search.java BlueJ output of Search.java
7Written · 2025 · Section B · 2025 PaperFull page

Define a class to overload the method print() as follows:
void print() – To print the given format using nested loops.

Show SolutionHide Solution↓
@#@#@
@#@#@
@#@#@
@#@#@

double print(double a, double b) – To display the sum of numbers between a and b with difference of 0.5.
e.g. if a = 1.0, b = 4.0
Output is: 1.0 + 1.5 + 2.0 + 2.5 + … + 4.0
int print(char ch1, char ch2) – Compare the two characters and return the ASCII code of the largest character.

import java.util.Scanner;

class Overload {
    public void print() {
        for(int i = 0; i < 4; i++) {
            for(int j = 0; j < 5; j++) {
                if (j % 2 == 0) {
                    System.out.print('@');
                }
                else {
                    System.out.print('#');
                }
            }
            System.out.println();
        }
    }

    public double print(double a, double b) {
        double sum = 0.0;
        for(double i = a; i <= b; i += 0.5)
            sum += i;
        System.out.println("Sum = " + sum);
        return sum;
    }

    public int print(char ch1, char ch2) {
        int maxAscii = (ch1 > ch2) ? (int)ch1 : (int)ch2;
        System.out.println("Larger ASCII code = " + maxAscii);
        return maxAscii;
    }

    public static void main(String[] args) {
        Overload obj = new Overload();
        Scanner sc = new Scanner(System.in);
        System.out.println("Pattern:");
        obj.print();
        System.out.print("\nEnter two decimal values (a and b): ");
        double a = sc.nextDouble();
        double b = sc.nextDouble();
        obj.print(a, b);
        System.out.print("\nEnter two characters: ");
        char ch1 = sc.next().charAt(0);
        char ch2 = sc.next().charAt(0);
        obj.print(ch1, ch2);
    }
}
BlueJ output of Overload.java
8Written · 2025 · Section B · 2025 PaperFull page

Define a class to accept a number. Check if the sum of the largest digit and the smallest digit is an even number or an odd number. Print appropriate messages.

Sample Input:64253748
Largest digit:68
Smallest digit:23
Sample Output:Sum is evenSum is odd
Show SolutionHide Solution↓
import java.util.Scanner;

class Find{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        
        int num = in.nextInt();
        int sum = 0;
        int s = 10;
        int l = -1;
        
        while (num != 0) {
            int d = num % 10;
            
            if (d < s)
                s = d;
                
            if (d > l)
                l = d;
                
            num /= 10;
        }
        
        sum = s + l;
        
        if(sum % 2 == 0)
            System.out.println("Sum is even");
        else
            System.out.println("Sum is odd");
    }
}
BlueJ output of Find.java BlueJ output of Find.java
1(i)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Which of the following String methods results into boolean data type?

Show SolutionHide Solution↓

equals()

Reason — In Java, the equals() method compares the contents of two strings and returns a boolean value (true or false), whereas trim(), replace(), and concat() return new strings, not boolean values.

1(ii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Which construct can be used to get only one of the required ice creams?

which construct can be used to get only one of the required ice creams. ICSE 2025 Computer Applications Solved Question Paper.
Show SolutionHide Solution↓

switch construct

Reason — The switch construct can be used to select and execute only the case that matches the required ice cream choice, skipping all other cases, which makes it suitable when only one specific ice cream needs to be selected from several options.

1(iii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Which statement is correct for the method prototype given below:

int check(char ch, String s)

Show SolutionHide Solution↓

check() has return type int

Reason — In the method prototype int check(char ch, String s), the keyword int before the method name specifies that the method returns an integer value. The parameters char ch and String s are formal parameters, and the method is not a constructor as it has a return type.

1(iv)1 Mark · 2025 · Section A · 2025 ImprovementFull page

The Math method which returns int value is:

Show SolutionHide Solution↓

round()

Reason — The round() method returns an int. Other methods like cbrt() and ceil() return double, while random() returns a double value between 0.0 and 1.0.

1(v)1 Mark · 2025 · Section A · 2025 ImprovementFull page

What is the output of the following statement:

“MONOPOLY”.lastIndexOf(‘O’);

Show SolutionHide Solution↓

5

Reason — In the string "MONOPOLY", the character 'O' occurs at indexes 1, 3, and 5 (indexing starts from 0). The lastIndexOf('O') method returns the last occurrence of 'O', which is at index 5.

1(vi)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Typecasting is often necessary when dealing with financial data. Identify the correct syntax to typecast a double to an int using the variables:

int amount; double valueINR

Show SolutionHide Solution↓

int amount = (int) valueINR;

Reason — The correct syntax to typecast a double to an int in Java is by placing (int) before the double variable, which converts it to an integer by removing its decimal part.

1(vii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

What is the output of the code snippet given below?

int lives = 5;
System.out.print(lives--);
System.out.print(lives);
Show SolutionHide Solution↓

5 4

Reason — In System.out.print(lives--), the post-decrement operator (lives--) prints the current value of lives (which is 5) first, then decreases it to 4. The next System.out.print(lives) prints the updated value 4.

1(viii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

What will be the output of the following statement?

String s = "JavaProgramming";
System.out.println(s.substring(4, 11).toUpperCase());
Show SolutionHide Solution↓

PROGRAM

Reason — In the string "JavaProgramming", indexing starts at 0. substring(4, 11) extracts characters from index 4 to 10, which is "Program". Calling .toUpperCase() converts it to "PROGRAM".

1(ix)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Which of the following access specifiers will make a member accessible only within its own class?

Show SolutionHide Solution↓

private

Reason — In Java, the private access specifier restricts a member’s visibility so it can be accessed only within the same class where it is declared.

1(x)1 Mark · 2025 · Section A · 2025 ImprovementFull page

What will be the output of the following Java method?

Character.isLetterOrDigit('\n')
Show SolutionHide Solution↓

false

Reason — The method Character.isLetterOrDigit('\n') checks whether the given character is a letter or a digit. The character '\n' represents a newline, which is neither a letter nor a digit, so the method returns false.

1(xi)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Which of the following is not a type of token in Java?

1. Method3. Literal
2. Identifier4. Keyword
Show SolutionHide Solution↓

only 1

Reason — In Java, the main types of tokens are keywords, identifiers, literals, operators, and separators. A method is not considered a token; it is a block of code that performs a task.

1(xii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

The statement given below is termed as:

public void Accept(int a)

Show SolutionHide Solution↓

Method prototype

Reason — In Java, a method prototype specifies the method’s access specifier, return type, name, and parameter list without including its body. The statement public void Accept(int a) shows these elements but does not contain a method body, so it is a method prototype.

1(xiii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

What is the output of the following Java code?

boolean flag = false; 
if (flag) { 
System.out.println("True"); 
} else { 
System.out.println("False"); 
}
Show SolutionHide Solution↓

False

Reason — The code declares a boolean variable flag with the value false, checks it in the if condition, and since it evaluates to false, the if block is skipped and the else block executes, printing False to the output.

1(xiv)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Identify the static method from the list given below:

Show SolutionHide Solution↓

isLetter(char)

Reason — The method isLetter(char) belongs to the Character class and is a static method, meaning it can be called using the class name without creating an object. The other methods (length(), nextLine(), substring(int)) are instance methods that require an object to be invoked.

1(xv)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Which one of the following will be the output of the below statements?

String a[]={"Rohini", "Rajarshi", "Rajeev", "Rehan", "Rebecca"}; 
System.out.println(a[2].substring(2));
Show SolutionHide Solution↓

jeev

Reason — In the array, the element at position 2 is "Rajeev". In Java, string indexing starts from 0, so index 0 = R, index 1 = a, and index 2 = j. Using substring(2) means we take all characters from index 2 to the end, giving "jeev".

1(xvi)1 Mark · 2025 · Section A · 2025 ImprovementFull page

System.out.println(Math.round(Math.ceil(-8.8))); will result in:

Show SolutionHide Solution↓

-8

Reason — First, Math.ceil(-8.8) returns -8.0 because ceil() rounds a number up to the nearest integer (for negative numbers, “up” means closer to zero). Then, Math.round(-8.0) returns the integer -8, as round() converts a floating-point number to the nearest whole number.

1(xvii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Which one of the following Java statements assign 100 to the last element of a 3 × 3 array?

Show SolutionHide Solution↓

x[2][2]=100;

Reason — In Java, array indexing starts from 0, so a 3 × 3 array has valid row and column indices 0, 1, and 2. The last element is at row index 2 and column index 2, so x[2][2] = 100; correctly assigns the value 100 to that element.

1(xviii)3 Marks · 2025 · Section A · 2025 ImprovementFull page

Consider the Two dimensional array S[2], of storage devices given below, state the index of the Hard disk.

Consider the Two dimensional array S[2][3], of storage devices given below, state the index of the Hard disk? ICSE 2025 Computer Applications Solved Question Paper.
Show SolutionHide Solution↓

S[1][0]

Reason — In a two-dimensional array S[2][3], the first index represents the row and the second index represents the column, both starting from 0. Based on the given arrangement of storage devices, the element "Hard disk" is located in the second row (index 1) and first column (index 0), so its index is S[1][0].

1(xix)1 Mark · 2025 · Section A · 2025 ImprovementFull page

How many times the for statement given below is executed?

for(k = 10; k >= 0; k--)

Show SolutionHide Solution↓

11

Reason — The loop starts with k = 10 and runs while k >= 0. This includes both k = 10 and k = 0, so the values of k will be: 10, 9, 8, ..., 1, 0 — a total of 11 iterations.

1(xx)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Consider the following program segment in which the statements are jumbled. Choose the correct order of the statements to return the sum of first 10 natural numbers.

for(i=1; i<=10; i++)  → 1
return sum;           → 2
int sum = 0, i;       → 3
sum+=i;               → 4
Show SolutionHide Solution↓

3 1 4 2

Reason — To return the sum of first 10 natural numbers, we must follow the proper sequence of statements:

  1. int sum = 0, i; – Declare the variables sum and i, and initialize sum to 0.
  2. for(i=1; i<=10; i++) – Start the loop to go through numbers 1 to 10.
  3. sum+=i; – Add the current number i to sum during each loop iteration.
  4. return sum; – After the loop completes, return the total sum.
2(i)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Write Java expression for the following:

$x^{10} + y^{10}$

Show SolutionHide Solution↓

Math.pow(x, 10) + Math.pow(y, 10)

2(ii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Evaluate the given expression when x = 4.

x *= --x + x-- + x;

Show SolutionHide Solution↓

x *= --x + x-- + x
x = x * (--x + x-- + x)
x = 4 * (--x + x-- + x)
x = 4 * (3 + x-- + x)
x = 4 * (3 + 3 + x)
x = 4 * (3 + 3 + 2)
x = 4 * 8
x = 32

2(iii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Convert the following switch case into if else if:

switch(x) 
{ 
case 'T' : 
case  't'  : System.out.print("Teacher");  break; 
default  :  System.out.print("Student");   
}
Show SolutionHide Solution↓
if (x == 'T' || x == 't') {
    System.out.print("Teacher");
} else {
    System.out.print("Student");
}
2(iv)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Write the output of the following program segment:

for(int a = 1; a <= 10; a++) 
{ 
if(a % 2 == 0) 
continue; 
System.out.print(a + "  "); 
}
Show SolutionHide Solution↓
1  3  5  7  9
  1. The loop control variable a is initialized to 1 and is incremented by 1 after each iteration until it attains the value 10.
  2. The condition if (a % 2 == 0) tests whether a is an even number. If the condition is true, the continue statement transfers control to the next iteration of the loop, thereby skipping the print statement.
  3. Consequently, only the odd values 1, 3, 5, 7, and 9 are displayed by the statement System.out.print(a + " ");.
2(v)1 Mark · 2025 · Section A · 2025 ImprovementFull page

In the example given below of class Cat, identify the variable and the methods:

Cat
Name
meow()
eat()
play()
Show SolutionHide Solution↓

Variable: Name

Methods: meow(), eat(), play()

2(vi)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Give the output of the following program segment and mention how many times the loop is executed.

int k = 100; 
while (k>=10) 
{
    System.out.println(k); 
    k-=40; 
}
Show SolutionHide Solution↓
100
60
20

The loop is executed 3 times.

  • Initial value: k = 100 → printed, then reduced to 60.
  • Second iteration: k = 60 → printed, then reduced to 20.
  • Third iteration: k = 20 → printed, then reduced to -20.
  • Loop stops when k < 10.
2(vii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Consider the given array and answer the questions given below:

int z[ ] [ ] = { {2, 3, 4}, {5, 1, 2}, {7, 9, 3}};

(a) What is the order of the array z[ ][ ]?

(b) What is the value in z[2][0]?

Show SolutionHide Solution↓

(a) The order of the array z[ ][ ] is 3 × 3.

(b) The value in z[2][0] is 7.

2(viii)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Give the output of the following:

(a) "ROSE".compareTo("ROJA")

(b) "DEDICATE".replace('D', 'L')

Show SolutionHide Solution↓

(a)

9

The method compareTo() compares two strings lexicographically by evaluating the Unicode value of each character from left to right until a mismatch is found.

  1. 'R' (82) vs 'R' (82) → same.
  2. 'O' (79) vs 'O' (79) → same.
  3. 'S' (83) vs 'J' (74) → difference = 83 - 74 = 9.

Since a mismatch occurs at the third character, the comparison stops; therefore, the characters 'E' and 'A' are not compared.

Hence, the method returns 9.

(b)

LELICATE

The replace('D', 'L') method substitutes every occurrence of the character 'D' in the string "DEDICATE" with 'L', resulting in "LELICATE".

2(ix)1 Mark · 2025 · Section A · 2025 ImprovementFull page

Consider the following array and answer the questions given below:

char ch [ ] = { ‘A’, ‘%’, ‘y’, ‘@’, ‘7’, ‘p’};

(a) How many bytes does the array occupy?

(b) What is the output of the statement Character.isDigit(ch[4])?

Show SolutionHide Solution↓

(a) In Java, each element of type char occupies 2 bytes of memory. The given array has 6 elements, therefore:

Total memory = 6 × 2 = 12 bytes.

(b)

true
  • The element ch[4] contains the character '7'.
  • The method Character.isDigit('7') returns true because '7' is a numeric digit.
2(x)1 Mark · 2025 · Section A · 2025 ImprovementFull page
class perform 
{ 
int  m;  String name; 
perform(int x, String y) 
{ 
m=x; 
name=y; 
} 
void print()  
{ 
System.out.print(name + "     " + m); 
}      
public static void main() 
{ 
perform ob1=new perform(95 , "Xavier"); 
ob1.print();
} 
}

(a) Give the output of the code given above.

(b) Name the type of the constructor used.

Show SolutionHide Solution↓

(a)

Xavier     95
  • A perform object ob1 is created using new perform(95, "Xavier").
  • The constructor assigns m = 95 and name = "Xavier".
  • The print() method outputs the name followed by spaces and then m.

(b) The constructor perform(int x, String y) accepts arguments, hence it is a parameterized constructor.

3Written · 2025 · Section B · 2025 ImprovementFull page

Define a class with following specifications.
class name: Hotel
Member variables:
String name – stores name of customer name
long mobno – stores mobile number
int days – stores number of days customer stayed in hotel
int bill – stores customer bill

Member method:
void input() – input values using Scanner class methods only
void charge() – calculate bill as per the following criteria

dayscharge/day
first 3 days1000 Rs/ day
next 4 days900 Rs/day
> 7 days800 Rs/day

bill = bill + gst (18% of bill)

void print() - Display customer name, mobile number and bill.

Invoke all the above methods in main method with the help of an object.

Show SolutionHide Solution↓
import java.util.Scanner;

class Hotel {
    String name;
    long mobno;
    int days;
    int bill;

    void input() {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter customer name: ");
        name = sc.nextLine();
        System.out.print("Enter mobile number: ");
        mobno = sc.nextLong();
        System.out.print("Enter number of days stayed: ");
        days = sc.nextInt();
    }

    void charge() {
        if (days <= 3) {
            bill = days * 1000;
        } else if (days <= 7) {
            bill = (3 * 1000) + (days - 3) * 900;
        } else {
            bill = (3 * 1000) + (4 * 900) + (days - 7) * 800;
        }
        bill += bill * 0.18;
    }

    void print() {
        System.out.println("Customer Name : " + name);
        System.out.println("Mobile Number : " + mobno);
        System.out.println("Total Bill    : Rs " + bill);
    }

    public static void main(String[] args) {
        Hotel h = new Hotel();
        h.input();
        h.charge();
        h.print();
    }
}
BlueJ output of Hotel.java
4Written · 2025 · Section B · 2025 ImprovementFull page

Define a class to accept values into a 3x3 integer array and print the product of each row elements.

Example:

312
421
512

Output:

Row 0 – 6
Row 1 – 8
Row 2 – 10

Show SolutionHide Solution↓
import java.util.Scanner;

public class RowProduct {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[][] arr = new int[3][3];

        System.out.println("Enter 9 integers for the 3x3 array:");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                arr[i][j] = sc.nextInt();
            }
        }

        for (int i = 0; i < 3; i++) {
            int product = 1;
            for (int j = 0; j < 3; j++) {
                product *= arr[i][j];
            }
            System.out.println("Row " + i + " – " + product);
        }
    }
}
BlueJ output of RowProduct.java
5Written · 2025 · Section B · 2025 ImprovementFull page

Define a class to overload the method transform as follows:

int transform(int n) – to return the sum of the digits of the given number

Example: n = 458
output : 17

void transform(String s) – to convert the given String to upper case and print

Example: if S = “Blue”
Output : BLUE

void transform (char ch) – to print the character ch in 3 rows and 3 columns using nested loops.

Example: if ch = ‘@’
Output :

Show SolutionHide Solution↓
@@@  
@@@
@@@
import java.util.Scanner;

public class OverloadTransform {

    int transform(int n) {
        int sum = 0;
        while (n > 0) {
            int d = n % 10;
            sum += d;
            n /= 10;
        }
        return sum;
    }

    void transform(String s) {
        String str = s.toUpperCase();
        System.out.println(str);
    }

    void transform(char ch) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(ch);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        OverloadTransform obj = new OverloadTransform();

        System.out.print("Enter an integer: ");
        int num = sc.nextInt();
        System.out.println("Sum of digits: " + obj.transform(num));

        sc.nextLine();
        System.out.print("Enter a string: ");
        String str = sc.nextLine();
        obj.transform(str);

        System.out.print("Enter a character: ");
        char ch = sc.next().charAt(0);
        obj.transform(ch);
    }
}
BlueJ output of OverloadTransform.java
6Written · 2025 · Section B · 2025 ImprovementFull page

Define a class to accept a string. Check if it is a Special String or not.
A String is Special if the number of vowels equals to the number of consonants.
Example: MINE
Number of vowels = 2
Number of Consonants = 2

Show SolutionHide Solution↓
import java.util.Scanner;

public class SpecialString {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = sc.nextLine().toUpperCase();

        int vowels = 0, consonants = 0;
        int len = str.length();

        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
            if (ch >= 'A' && ch <= 'Z') {
                if (ch == 'A' 
                    || ch == 'E' 
                    || ch == 'I' 
                    || ch == 'O' 
                    || ch == 'U')
                    vowels++;
                else
                    consonants++;
            }
        }

        System.out.println("Number of vowels = " + vowels);
        System.out.println("Number of consonants = " + consonants);

        if (vowels == consonants)
            System.out.println("It is a Special String");
        else
            System.out.println("It is not a Special String");
    }
}
BlueJ output of SpecialString.java BlueJ output of SpecialString.java
7Written · 2025 · Section B · 2025 ImprovementFull page

Define a class to accept a number and check if the sum of the first digit and the last digit is an even number or an odd number.

Example:

Show SolutionHide Solution↓
            N = 2396    N = 9316
First digit:   2         9
Last digit:    6         6
Sum:           8         15
Output: Sum is even  Sum is odd
import java.util.Scanner;

public class FirstLastSum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int n = sc.nextInt();

        int lastDigit = n % 10;
        int firstDigit = n;
        while (firstDigit >= 10) {
            firstDigit /= 10;
        }

        int sum = firstDigit + lastDigit;

        System.out.println("First digit: " + firstDigit);
        System.out.println("Last digit: " + lastDigit);
        System.out.println("Sum: " + sum);

        if (sum % 2 == 0)
            System.out.println("Sum is even");
        else
            System.out.println("Sum is odd");
    }
}
BlueJ output of FirstLastSum.java BlueJ output of FirstLastSum.java
8Written · 2025 · Section B · 2025 ImprovementFull page

Define a class to accept 10 integers in an array, search for the given value using the Linear Search technique and print appropriate messages.

Show SolutionHide Solution↓
import java.util.Scanner;
public class LinearSearchArray {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = new int[10];

        System.out.println("Enter 10 integers:");
        for (int i = 0; i < 10; i++) {
            arr[i] = sc.nextInt();
        }
        System.out.print("Enter the value to search: ");
        int key = sc.nextInt();
        int i = 0;

        for (i = 0; i < 10; i++) {
            if (arr[i] == key) {
                break;
            }
        }
        
        if (i < 10)
            System.out.println("Value found at position: " + (i + 1));
        else
            System.out.println("Value not found in the array");
    }
}
BlueJ output of LinearSearchArray.java BlueJ output of LinearSearchArray.java
1(i)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Name the below structure:

Name the structure. One dimensional array, Two Dimensional array with 4 rows and 5 columns. ICSE 2025 Specimen Computer Applications Solved Question Paper.
Show SolutionHide Solution↓

Two Dimensional array with 4 rows and 5 columns

Reason — A two-dimensional array is like a grid or table with rows and columns. The image shows a table with 4 rows and 5 columns.

1(ii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

"Java compiled code (byte code) can run on all operating systems"
— Name the feature.

Show SolutionHide Solution↓

Platform Independent

Reason — The feature of "Platform Independence" allows Java compiled code (bytecode) to run on any operating system. This is achieved through the Java Virtual Machine (JVM), which interprets the bytecode and executes it on the specific platform.

1(iii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

The size of '\n' is:

Show SolutionHide Solution↓

2 bytes

Reason — In Java, \n (newline character) is a character literal. All character literals in Java, including escape sequences like \n, are stored as char data type, which occupies 2 bytes (16 bits) in memory.

1(iv)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Identify the operator that gets the highest precedence while evaluating the given expression:

a + b % c * d - e

Show SolutionHide Solution↓

%

Reason — % and * have the highest precedence. Since % appears first in the expression, it takes precedence during evaluation.

1(v)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Which of the following is a valid java keyword?

Show SolutionHide Solution↓

static

Reason — In Java, keywords are reserved words that have a specific meaning and purpose in the language. Keywords must always be written in lowercase. Analysing the given options:

  1. If: Incorrect because Java keywords are case-sensitive, and the correct keyword is if (in lowercase).
  2. BOOLEAN: Incorrect because the keyword in Java is boolean (in lowercase).
  3. static: Correct. static is a valid Java keyword used to declare static methods, variables, or blocks.
  4. Switch: Incorrect because the correct keyword is switch (in lowercase).
1(vi)1 Mark · 2025 · Section A · 2025 SpecimenFull page

The output of the following code is:

System.out.println(Math.ceil(6.4) + Math.floor(-1-2));
Show SolutionHide Solution↓

4.0

Reason — Let's evaluate the expression step by step:

System.out.println(Math.ceil(6.4) + Math.floor(-1 - 2));

Step 1: Evaluate Math.ceil(6.4)

  • The ceil method rounds a number up to the nearest integer.
  • Math.ceil(6.4) → 7.0 (as ceil returns a double).

Step 2: Evaluate -1 - 2

  • -1 - 2 = -3

Step 3: Evaluate Math.floor(-3)

  • Math.floor(-3): The floor method rounds a number down to the nearest integer.
  • Math.floor(-3) → -3.0 (as floor also returns a double).

Step 4: Add the Results

  • Math.ceil(6.4) + Math.floor(-3) → 7.0 + (-3.0)
  • Result = 4.0
1(vii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Which of the following returns a String?

Show SolutionHide Solution↓

replace(char, char)

Reason — The given methods return:

MethodReturn
Type
length()int
charAt(int)char
replace(char, char)String
indexOf(String)int
1(viii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Which of the following is not true with regards to a switch statement?

Show SolutionHide Solution↓

supports floating point constants

Reason — The switch statement does not support float or double constants as case labels. It supports byte, short, int, char, String and enum.

1(ix)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Consider the array given below:

char ch[] = {'A','E','I','O', 'U'};

Write the output of the following statements:

System.out.println(ch[0]*2);:
Show SolutionHide Solution↓

130

Reason — The given array is:

char ch[] = {'A', 'E', 'I', 'O', 'U'};

Step-by-Step Execution:

1. ch[0]:

  • The element at index 0 of the array is 'A'.

2. Character Multiplication in Java:

  • In Java, a char is treated as a numeric value based on its ASCII code when used in arithmetic operations.
  • The ASCII value of 'A' is 65.

3. ch[0] * 2:

  • Substituting ch[0] with its ASCII value:
65 * 2 = 130

4. Output:

  • System.out.println(ch[0] * 2); will print 130.
1(x)1 Mark · 2025 · Section A · 2025 SpecimenFull page

To execute a loop 10 times, which of the following is correct?

Show SolutionHide Solution↓

for (int i=11;i<=30;i+=2)

Reason — To execute a loop 10 times, the total number of iterations should match 10, based on the condition and increment values. Let's analyse each option:

1. for (int i = 11; i <= 30; i += 2)

  • The loop starts at 11 and increments by 2.
  • The sequence is: 11, 13, 15, 17, 19, 21, 23, 25, 27, 29.
  • This loop executes 10 times.

2. for (int i = 11; i <= 30; i += 3)

  • The loop starts at 11 and increments by 3.
  • The sequence is: 11, 14, 17, 20, 23, 26, 29.
  • This loop executes only 7 times, so it is incorrect.

3. for (int i = 11; i < 20; i++)

  • The loop starts at 11 and increments by 1.
  • The sequence is: 11, 12, 13, 14, 15, 16, 17, 18, 19.
  • This loop executes only 9 times, so it is incorrect.

4. for (int i = 11; i <= 21; i++)

  • The loop starts at 11 and increments by 1.
  • The sequence is: 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21.
  • This loop executes 11 times, so it is incorrect.
1(xi)1 Mark · 2025 · Section A · 2025 SpecimenFull page

A single dimensional array has 50 elements, which of the following is the correct statement to initialize the last element to 100.

Show SolutionHide Solution↓

x[49]=100

Reason — In Java, arrays use zero-based indexing, meaning the first element of the array is at index 0. For an array with n elements, the last element is at index n - 1.
Given a single-dimensional array with 50 elements, the indices range from 0 to 49. Thus, the correct index for the last element is 49.

1(xii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Method prototype for the method compute which accepts two integer arguments and returns true/false.

Show SolutionHide Solution↓

boolean compute (int a, int b)

Reason — Let's analyse the given options:

  1. void compute (int a, int b) — Incorrect because void means the method does not return any value, but the question requires the method to return true/false.

  2. boolean compute (int a, int b) — Correct because it returns a boolean value (true or false) and accepts two integer arguments.

  3. Boolean compute (int a, b) — Incorrect due to syntax error (int b is not fully declared). Also, Boolean is a wrapper class, not a primitive boolean.

  4. int compute (int a, int b) — Incorrect because the return type is int, not boolean.

1(xiii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

The statement that brings the control back to the calling method is:

Show SolutionHide Solution↓

return

Reason — The return statement in Java is used to bring the control back to the calling method. If the method has a return type other than void, the return statement also passes back a value to the calling method.

1(xiv)1 Mark · 2025 · Section A · 2025 SpecimenFull page

The default value of a boolean variable is:

Show SolutionHide Solution↓

false

Reason — In Java, the default value of a variable depends on its data type. For a boolean variable, the default value is false (in lowercase). This is because Java uses the primitive boolean type, which has only two possible values: true or false.

1(xv)1 Mark · 2025 · Section A · 2025 SpecimenFull page

The method to convert a lowercase character to uppercase is:

Show SolutionHide Solution↓

Character.toUpperCase( char )

Reason — The method Character.toUpperCase(char) is used to convert a single lowercase character to its uppercase equivalent. It belongs to the Character class in Java.

1(xvi)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Assertion (A): Integer class can be used in the program without calling a package.

Reason (R): It belongs to the default package java.lang.

Show SolutionHide Solution↓

Both Assertion (A) and Reason (R) are true and Reason (R) is a correct explanation of Assertion (A)

Reason — The Integer class can indeed be used in a program without explicitly importing any package. This is because it is part of the java.lang package, which is automatically imported in every Java program by default.

1(xvii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

A student executes the following code to increase the value of a variable ‘x’ by 2.

He has written the following statement, which is incorrect.

x = +2;

What will be the correct statement?

A. x +=2;
B. x =2;
C. x = x +2;

Show SolutionHide Solution↓

Both A and C

Reason — The student's code x = +2; is incorrect because it doesn't actually increment x by 2. Instead, it simply assigns the value +2 to x.

The correct way to increment the value of x by 2 is:

  1. Option A: x += 2;
    This is shorthand for x = x + 2; and correctly increments x by 2.

  2. Option C: x = x + 2;
    This is the full, explicit version of incrementing x by 2. It is also correct.

Option B: x = 2;
This assigns 2 to x, which is not incrementing its value. Hence, this is incorrect.

1(xviii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

The statement used to find the total number of Strings present in the string array String s[] is:

Show SolutionHide Solution↓

s.length

Reason — In Java, arrays have a property called length, which gives the total number of elements in the array. This applies to any type of array, including arrays of Strings.

For a string array String s[], the correct way to get the number of elements is:

s.length

Analysing other options:

  1. s.length():

    • Incorrect. The length() method is used for String objects to get the number of characters in a String, not for arrays.
  2. length(s):

    • Incorrect. This is not a valid syntax in Java.
  3. len(s):

    • Incorrect. Java does not have a function called len() for arrays or strings.
1(xix)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Consider the following program segment in which the statements are jumbled, choose the correct order of statements to swap two variables using the third variable.

void swap(int a, int b)
{	
  a = b;      → (1)
  b = t;      → (2)
  int t = 0;  → (3)
  t = a;      → (4)
}
Show SolutionHide Solution↓

(3) (4) (1) (2)

Reason — To swap two variables a and b using a third variable t, the correct sequence of statements is:

Step 1: Declare and initialize the third variable t.

int t = 0;  // (3)

Step 2: Assign the value of a to t.

t = a;  // (4)

Step 3: Assign the value of b to a.

a = b;  // (1)

Step 4: Assign the value of t (original value of a) to b.

b = t;  // (2)

Correct Order:

int t = 0;  // (3)
t = a;      // (4)
a = b;      // (1)
b = t;      // (2)
1(xx)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Assertion (A): An argument is a value that is passed to a method when it is called.

Reason (R): Variables which are declared in a method prototype to receive values are called actual parameters

Show SolutionHide Solution↓

Assertion (A) is true and Reason (R) is false

Explanation — Arguments are the actual values passed to a method when it is invoked. For example:

void exampleMethod(int x) { ... }  
exampleMethod(5);  // Here, 5 is the argument.

Hence, Assertion (A) is true.

The variables declared in a method prototype (or header) to receive values are called formal parameters, not actual parameters. For example:

void exampleMethod(int x) {  // x is the formal parameter
    System.out.println(x);
}
exampleMethod(5);  // 5 is the actual parameter

Hence, Reason (R) is false.

2(i)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Rewrite the following code using single if statement.

if(code=='g')
System.out.println("GREEN"); 
else if(code=='G') 
System.out.println("GREEN");
Show SolutionHide Solution↓

The code can be rewritten using a single if statement as follows:

if(code == 'g' || code == 'G')
    System.out.println("GREEN");

Explanation:

  • The logical OR operator (||) is used to check if code is either 'g' or 'G'.
  • If either condition is true, the statement System.out.println("GREEN"); will execute. This simplifies the multiple if-else blocks into a single if statement.
2(ii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Evaluate the given expression when the value of a=2 and b=3

b*=a++ - ++b + ++a;
System.out.println("a= "+a); 
System.out.println("b= "+b);
Show SolutionHide Solution↓

a = 4, b = 6

Explanation:

The given expression is evaluated as follows:

b*=a++ - ++b + ++a
b = b * (a++ - ++b + ++a) [a=2, b=3]
b = 3 * (2 - 4 + 4) [a=4, b=4]
b = 3 * 2
b = 6

2(iii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

A student executes the following program segment and gets an error. Identify the statement which has an error, correct the same to get the output as WIN.

boolean x = true; 
switch(x)
{ 
  case 1: System.out.println("WIN"); break;
  case 2: System.out.println("LOOSE");
}
Show SolutionHide Solution↓

Statement having the error is:

boolean x = true;

Corrected code:

int x = 1; // Change boolean to int
switch(x)
{ 
  case 1: System.out.println("WIN"); break;
  case 2: System.out.println("LOOSE");
}

Explanation:

The error occurs because the switch statement in Java does not support the boolean data type. A switch expression must be one of the following types:

  • int, byte, short, char, String, or an enum.

Replacing boolean x = true; with int x = 1; ensures that the switch statement now uses a valid data type (int). Assigning x = 1 makes the case 1 to execute printing WIN as the output.

2(iv)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Write the Java expression for $\sqrt[3]{x}+ \sqrt{y}$

Show SolutionHide Solution↓

The Java expression for the given mathematical expression can be written as:

Math.cbrt(x) + Math.sqrt(y);
2(v)1 Mark · 2025 · Section A · 2025 SpecimenFull page

How many times will the following loop execute? Write the output of the code:

int x=10; 
while (true){
System.out.println(x++ * 2);
if(x%3==0)
break;
} 
Show SolutionHide Solution↓

The loop executes two times.

Output

20
22

Explanation:

Step-by-Step Execution of the Code

Initial Value of x:
x = 10

Iteration 1:
System.out.println(x++ * 2);

  • x++ → Use the current value of x (10), then increment x to 11.
  • Output: 10 * 2 = 20

if (x % 3 == 0):

  • x = 11, so 11 % 3 = 2 → Condition is false.

Iteration 2:
System.out.println(x++ * 2);

  • x++ → Use the current value of x (11), then increment x to 12.
  • Output: 11 * 2 = 22

if (x % 3 == 0):

  • x = 12, so 12 % 3 = 0 → Condition is true.

break;

  • The break statement exits the loop.
2(vi)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Write the output of the following String methods:

String x= "Galaxy", y= "Games";

(a) System.out.println(x.charAt(0)==y.charAt(0));

(b) System.out.println(x.compareTo(y));

Show SolutionHide Solution↓

The outputs are:

(a) true

(b) -1

Explanation:

Given Strings:

String x = "Galaxy";
String y = "Games";

(a) System.out.println(x.charAt(0) == y.charAt(0));

  1. x.charAt(0): Retrieves the character at index 0 of x → 'G'.

  2. y.charAt(0): Retrieves the character at index 0 of y → 'G'.

  3. Comparison: 'G' == 'G' → true.

(b) System.out.println(x.compareTo(y));

  1. x.compareTo(y): Compares x ("Galaxy") with y ("Games") lexicographically (character by character based on Unicode values). The comparison is based on the first differing character:

    • 'G' == 'G' → Equal, move to the next characters.
    • 'a' == 'a' → Equal, move to the next characters.
    • 'l' == 'm' → 'l' (Unicode 108) is less than 'm' (Unicode 109).
  2. Result:

    • x.compareTo(y) → 108 - 109 = -1.
2(vii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Predict the output of the following code snippet:

char ch='B',
char chr=Character.toLowerCase(ch); 
int n=(int)chr-10; 
System.out.println((char)n+"\t"+chr);
Show SolutionHide Solution↓
X	b

Step-by-Step Execution:

char ch = 'B';

  • ch is assigned the character 'B'.

char chr = Character.toLowerCase(ch);

  • Character.toLowerCase(ch) converts 'B' to its lowercase equivalent 'b'.
  • chr = 'b'.

int n = (int) chr - 10;

  • (int) chr converts the character 'b' to its ASCII value.
  • ASCII value of 'b' is 98.
  • n = 98 - 10 = 88.

System.out.println((char) n + "\t" + chr);

  • (char) n: Converts the integer 88 back to a character.
    • ASCII value 88 corresponds to the character 'X'.
  • + "\t" + adds a tab space between the characters.
  • chr: The value of chr is 'b'.
2(viii)1 Mark · 2025 · Section A · 2025 SpecimenFull page

A student is trying to convert the string present in x to a numerical value, so that he can find the square root of the converted value. However the code has an error. Name the error (syntax / logical / runtime). Correct the code so that it compiles and runs correctly.

String x= "25";
int y=Double.parseDouble(x); 
double r=Math.sqrt(y); 
System.out.println(r);
Show SolutionHide Solution↓

Syntax error in the line:
int y=Double.parseDouble(x);

Corrected code:

String x= "25";
double y=Double.parseDouble(x); //int changed to double
double r=Math.sqrt(y); 
System.out.println(r);

Explanation:

The error is a syntax error because the method Double.parseDouble(x) returns a double, but the code is trying to assign it to an int variable without proper casting, which is not allowed in Java.

2(ix)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Consider the following program segment and answer the questions below:

class calculate

{
  int a; double b; 
  calculate()

  {

  a=0; 
  b=0.0;

  }

  calculate(int x, double y)

  {

  a=x;
  b=y;

  }

void sum()

{

  System.out.println(a*b);

}}

Name the type of constructors used in the above program segment?

Show SolutionHide Solution↓

The type of constructors used in the above program segment are:

  1. Default constructor
  2. Parameterized constructor

Explanation:

The types of constructors used in the given program are:

1. Default Constructor:

calculate() {
    a = 0;
    b = 0.0;
}
  • A default constructor is a constructor that does not take any parameters.
  • It initializes the instance variables a and b with default values (0 and 0.0 respectively).

2. Parameterized Constructor:

calculate(int x, double y) {
    a = x;
    b = y;
}
  • A parameterized constructor is a constructor that takes arguments (int x and double y in this case).
  • It allows for initializing the instance variables a and b with specific values provided during object creation.
2(x)1 Mark · 2025 · Section A · 2025 SpecimenFull page

Consider the following program segment and answer the questions given below:

int x[][] = { {2,4,5,6}, {5,7,8,1}, {34, 1, 10, 9}};

(a) What is the position of 34?

(b) What is the result of x[2][3] + x[1][2]?

Show SolutionHide Solution↓

(a) The position of 34 is x[2][0]

(b) x[2][3] + x[1][2] = 9 + 8 = 17

Explanation:

(a) Position of 34

  • The array x is a 2D array, where elements are accessed using row and column indices.
  • The element 34 is located in the 3rd row and 1st column.
  • In zero-based indexing:
    • Row index: 2
    • Column index: 0

Position: x[2][0]

(b) Result of x[2][3] + x[1][2]

Step 1: Locate x[2][3]

  • x[2][3] refers to the element in the 3rd row and 4th column.
  • Value at x[2][3] = 9.
  • x[1][2] refers to the element in the 2nd row and 3rd column.
  • Value at x[1][2] = 8.
  • x[2][3] + x[1][2] = 9 + 8 = 17.
3Written · 2025 · Section B · 2025 SpecimenFull page

Define a class with the following specifications:

Class name: Bank

Member variables:
double p — stores the principal amount
double n — stores the time period in years
double r — stores the rate of interest
double a — stores the amount

Member methods:
void accept () — input values for p and n using Scanner class methods only.
void calculate () — calculate the amount based on the following conditions:

Time in (Years)Rate %
Upto 1⁄29
> 1⁄2 to 1 year10
> 1 to 3 years11
> 3 years12

$a = p\Big(1+\frac{r}{100}\Big)^n$

void display () — display the details in the given format.

Show SolutionHide Solution↓
Principal	Time	Rate	Amount

XXX	        XXX	    XXX	    XXX

Write the main method to create an object and call the above methods.

import java.util.Scanner;

public class Bank
{
    private double p;
    private double n;
    private double r;
    private double a;

    void accept() {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter principal amount: ");
        p = in.nextDouble();

        System.out.print("Enter time period in years: ");
        n = in.nextDouble();
    }
    
    void calculate() {
        if (n <= 0.5) {
            r = 9;
        } else if (n <= 1) {
            r = 10;
        } else if (n <= 3) {
            r = 11;
        } else {
            r = 12;
        }

        a = p * Math.pow(1 + (r / 100), n);
    }
    
    void display() {
        System.out.println("Principal\tTime\tRate\tAmount");
        System.out.println(p + "\t" + n + "\t" + r + "\t" + a);
    }
    
    public static void main(String args[]) {
        Bank b = new Bank();
        b.accept();
        b.calculate();
        b.display();
    }
}
BlueJ output of Bank.java
4Written · 2025 · Section B · 2025 SpecimenFull page

Define a class to search for a value input by the user from the list of values given below. If it is found display the message "Search successful", otherwise display the message "Search element not found" using Binary search technique.

5.6, 11.5, 20.8, 35.4, 43.1, 52.4, 66.6, 78.9, 80.0, 95.5.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatBinarySearch
{
    void search(double[] arr, double key) {
        int low = 0;
        int high = arr.length - 1;
        boolean found = false;

        while (low <= high) {
            int mid = (low + high) / 2;

            if (arr[mid] == key) {
                found = true;
                break;
            } else if (arr[mid] < key) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        if (found) {
            System.out.println("Search successful");
        } else {
            System.out.println("Search element not found");
        }
    }
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        double[] values = {5.6, 11.5, 20.8, 35.4, 43.1, 52.4, 66.6, 78.9, 80.0, 95.5};

        System.out.print("Enter the value to search: ");
        double key = in.nextDouble();

        KboatBinarySearch obj = new KboatBinarySearch();
        obj.search(values, key);
    }
}
BlueJ output of KboatBinarySearch.java BlueJ output of KboatBinarySearch.java
5Written · 2025 · Section B · 2025 SpecimenFull page

Define a class to accept a string and convert the same to uppercase, create and display the new string by replacing each vowel by immediate next character and every consonant by the previous character. The other characters remain the same.

Example:
Input : #IMAGINATION@2024
Output : #JLBFJMBSJPM@2024

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatStringConvert
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String str = in.nextLine();
        str = str.toUpperCase();
        int l = str.length();
        
        String res = "";
        
        for (int i = 0; i < l; i++) {
            char ch = str.charAt(i);
            if ("AEIOU".indexOf(ch) != -1) {
                res += (char)(ch + 1);
            }
            else if (Character.isLetter(ch)) {
                res += (char)(ch - 1);
            }
            else {
                res += ch;
            }
        }
        
        System.out.println("Output String:");
        System.out.println(res);
    }
}
BlueJ output of KboatStringConvert.java
6Written · 2025 · Section B · 2025 SpecimenFull page

Define a class to accept values into 4x4 array and find and display the sum of each row.

Example:

A[][]={{1,2,3,4},{5,6,7,8},{1,3,5,7},{2,5,3,1}}

Output:

Show SolutionHide Solution↓
sum of row 1 = 10 (1+2+3+4)
sum of row 2 = 26 (5+6+7+8)
sum of row 3 = 16 (1+3+5+7)
sum of row 4 = 11 (2+5+3+1)
import java.util.Scanner;

public class KboatDDARowSum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int arr[][] = new int[4][4];

        System.out.println("Enter 4x4 DDA elements:");
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                arr[i][j] = in.nextInt();
            }
        }

        for (int i = 0; i < 4; i++) {
            int rowSum = 0;
            for (int j = 0; j < 4; j++) {
                rowSum += arr[i][j];
            }
            System.out.println("Sum of Row" + (i+1) 
                                + " = " + rowSum);
        }
    }
}
BlueJ output of KboatDDARowSum.java
7Written · 2025 · Section B · 2025 SpecimenFull page

Define a class to accept a number and check whether it is a SUPERSPY number or not. A number is called SUPERSPY if the sum of the digits equals the number of the digits.

Example1:

Show SolutionHide Solution↓
Input: 1021
output: SUPERSPY number [SUM OF THE DIGITS = 1+0+2+1 = 4,
NUMBER OF DIGITS = 4 ]

Example2:

Input: 125
output: Not an SUPERSPY number [1+2+5 is not equal to 3]
import java.util.Scanner;

public class KboatSuperSpy
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = in.nextInt();
        
        int sum = 0;
        int dc = 0;
        int orgNum = num;
        
        while (num > 0) {
            int d = num % 10;
            sum += d;
            dc++;
            num /= 10;
        }
        
        if (sum == dc) {
            System.out.println(orgNum + " is a SUPERSPY number");
        }
        else {
            System.out.println(orgNum + " is not a SUPERSPY number");
        }
    }
}
BlueJ output of KboatSuperSpy.java BlueJ output of KboatSuperSpy.java
8Written · 2025 · Section B · 2025 SpecimenFull page

Define a class to overload the method display() as follows:

void display(): To print the following format using nested loop.

1 2 1 2 1
1 2 1 2 1
1 2 1 2 1

void display (int n, int m) : To print the quotient of the division of m and n if m is greater than n otherwise print the sum of twice n and thrice m.

double display (double a, double b, double c) — to print the value of z where

$z = p \times q$

$p = \frac{a + b}{c}$

$q = a + b + c$

Show SolutionHide Solution↓
public class KboatOverloadDisplay
{
    void display() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 5; j++) {
                if (j % 2 == 0) {
                    System.out.print("1  ");
                } else {
                    System.out.print("2  ");
                }
            }
            System.out.println();
        }
    }
    
    void display(int n, int m) {
        if (m > n) {
            double q = m / n;
            System.out.println("Quotient: " + q);
        } else {
            int sum = 2 * n + 3 * m;
            System.out.println("Sum: " + sum);
        }
    }
    
    double display(double a, double b, double c) {
        double p = (a + b) / c;
        double q = a + b + c;
        double z = p * q;
        System.out.println("Z = " + z);
        return z;
    }
}
BlueJ output of KboatOverloadDisplay.java BlueJ output of KboatOverloadDisplay.java BlueJ output of KboatOverloadDisplay.java BlueJ output of KboatOverloadDisplay.java BlueJ output of KboatOverloadDisplay.java BlueJ output of KboatOverloadDisplay.java BlueJ output of KboatOverloadDisplay.java
1(i)1 Mark · 2024 · Section A · 2024 PaperFull page

Consider the below picture and choose the correct statement from the following:

Consider the below picture and choose the correct statement. Polygon is the object and the pictures are classes. Both polygon and the pictures are classes. ICSE 2024 Computer Applications Solved Question Paper.
Show SolutionHide Solution↓

Polygon is the class and the pictures are objects

Reason — In object-oriented programming (OOP), a class is a blueprint or template that defines the properties and behaviours (methods) of objects. An object is an instance of a class that holds specific data defined by the class.

In this case:

  • Polygon represents the class because it defines the general structure, properties, and methods common to all polygons (e.g., sides, vertices, perimeter calculation).
  • The pictures are specific examples or instances of polygons, such as triangles, parallelogram, or pentagons, making them objects created from the Polygon class.
1(ii)1 Mark · 2024 · Section A · 2024 PaperFull page

int x = 98; char ch = (char)x; what is the value in ch?

Show SolutionHide Solution↓

b

Reason — In Java, when an int value is cast to char, it is converted based on the ASCII code. Since, 98 is the ASCII code of the letter b, hence value of ch is 'b'.

1(iii)1 Mark · 2024 · Section A · 2024 PaperFull page

The output of the statement "CONCENTRATION".indexOf('T') is:

Show SolutionHide Solution↓

6

Reason — The method indexOf(char ch) in Java returns the index of the first occurrence of the specified character ch in the string. If the character is not found, it returns -1.

Consider the string:
"CONCENTRATION"

Let’s count the characters by their index (Java uses zero-based indexing):

CONCENTRATION
0123456789101112

The first occurrence of the character 'T' is at index 6.

Thus, the output of the statement "CONCENTRATION".indexOf('T') is 6.

1(iv)1 Mark · 2024 · Section A · 2024 PaperFull page

The access specifier that gives least accessibility is:

Show SolutionHide Solution↓

private

Reason — In Java, access specifiers determine the visibility or accessibility of classes, methods, and variables. The three main access specifiers are:

  1. public: Accessible from anywhere in the program.
  2. protected: Accessible within the same package and by subclasses even if they are in different packages.
  3. private: Accessible only within the same class.

private gives least accessibility as it provides the most restricted access.

1(v)1 Mark · 2024 · Section A · 2024 PaperFull page

The output of the statement "talent".compareTo("genius") is:

Show SolutionHide Solution↓

13

Reason — The method compareTo(String str) in Java compares two strings lexicographically based on the ASCII values of characters. It returns:

0 if both strings are equal.
A positive value if the calling string comes after the argument string.
A negative value if the calling string comes before the argument string.

How It Works:
We compare "talent" and "genius" using their first differing characters:

  • The ASCII value of 't' = 116
  • The ASCII value of 'g' = 103

The difference is:
116 - 103 = 13

Since 't' comes after 'g', the result is 13.

1(vi)1 Mark · 2024 · Section A · 2024 PaperFull page

Which of the following is an escape sequence character in Java?

Show SolutionHide Solution↓

\t

Reason — In Java, an escape sequence is a combination of characters starting with a backslash (\) followed by a specific character that performs a special operation.

Analysing the given options:

  1. /n – Incorrect, should be \n (Backslash is required).
  2. \t – Correct, it represents a tab.
  3. /t – Incorrect, should be \t.
  4. //n – Incorrect, this is not an escape sequence; // is used for comments in Java.
1(vii)1 Mark · 2024 · Section A · 2024 PaperFull page

if (a>b&&b>c) then largest number is:

Show SolutionHide Solution↓

a

Reason — The && (Logical AND) operator in Java is used to combine two boolean expressions. It returns true only if both expressions are true. If either of the expressions is false, the entire condition becomes false.

The condition if (a > b && b > c) checks two expressions:

  1. a > b – Checks if a is greater than b.
  2. b > c – Checks if b is greater than c.

Since both conditions must be true (due to the && operator), the logical sequence becomes:
a > b > c

In this sequence:
a is the largest number because it is greater than both b and c.

1(viii)1 Mark · 2024 · Section A · 2024 PaperFull page

What is the output of Math.ceil(5.4)+Math.ceil(4.5)?

Show SolutionHide Solution↓

11.0

Reason — The method Math.ceil(double value) in Java rounds up a decimal number to the next highest integer, regardless of the fractional part.

Breakdown of the Expression:

  1. Math.ceil(5.4):
    5.4 is rounded up to 6.0.

  2. Math.ceil(4.5):
    4.5 is rounded up to 5.0.

Adding the Results:
6.0 + 5.0 = 11.0

1(ix)1 Mark · 2024 · Section A · 2024 PaperFull page

What is the method to check whether a character is a letter or digit?

Show SolutionHide Solution↓

isLetterOrDigit(char)

Reason — In Java, the method Character.isLetterOrDigit(char ch) is used to check whether a given character ch is either a letter (A-Z or a-z) or a digit (0-9).

Analysing Other Options:

  1. isDigit(char) – This method only checks if the character is a digit, not a letter.
  2. isLetterOrDigit() – Incorrect because this method requires a character parameter.
  3. isLETTERorDIGIT(char) – Java methods are case-sensitive, and method names follow camelCase. This method name does not exist.
1(x)1 Mark · 2024 · Section A · 2024 PaperFull page

The extension of a Java source code file is:

Show SolutionHide Solution↓

java

Reason — In Java, source code files are saved with the .java extension. These files contain the Java program's source code, written in human-readable text format.

1(xi)1 Mark · 2024 · Section A · 2024 PaperFull page

The number of bytes occupied by a character array of four rows and three columns are:

Show SolutionHide Solution↓

24

Reason — In Java, a character (char) takes 2 bytes because Java uses Unicode encoding.

Given:
Character Array: 4 rows and 3 columns
Total Elements = 4 × 3 = 12 characters

Memory Calculation:
Each character = 2 bytes
Total Memory = 12 × 2 = 24 bytes

1(xii)1 Mark · 2024 · Section A · 2024 PaperFull page

Which of the following data type cannot be used with switch case construct?

Show SolutionHide Solution↓

double

Reason — The switch statement in Java supports specific data types for the case labels. However, double and float data types cannot be used.

Data Types supported in switch statement are:

  1. int
  2. char
  3. String
1(xiii)1 Mark · 2024 · Section A · 2024 PaperFull page

Which of the following are entry controlled loops?

(a) for

(b) while

(c) do..while

(d) switch

Show SolutionHide Solution↓

a and b

Reason — An entry-controlled loop checks the loop condition before executing the loop's body. If the condition is false at the start, the loop's body will not execute even once.
for and while loops check the condition before running the loop's body. If the condition is false, the loop won't run. Therefore, they are entry controlled loops.
The body of the do-while loop executes at least once before checking the condition. Hence, it is an exit controlled loop.

1(xiv)1 Mark · 2024 · Section A · 2024 PaperFull page

Method which reverses a given number is:

Show SolutionHide Solution↓

Pure method

Reason — A pure method in Java is a method that:

  1. Returns a value based only on its input arguments.
  2. Does not modify any external variables or system state.
  3. Does not change any class fields or input values.

In the context of reversing a number, a pure method accepts the number as input and returns its reversed form without altering any external state.

1(xv)1 Mark · 2024 · Section A · 2024 PaperFull page

If the name of the class is "Yellow", what can be the possible name for its constructors?

Show SolutionHide Solution↓

Yellow

Reason — In Java, a constructor must have the same name as the class. It initializes an object when it is created. Since the class name is Yellow, the constructor's name must be exactly Yellow, matching the class name including capitalization.

1(xvi)1 Mark · 2024 · Section A · 2024 PaperFull page

Invoking a method by passing the objects of a class is termed as:

Show SolutionHide Solution↓

Call by reference

Reason — When an object is passed to a method:

  1. The method receives a reference (memory address) to the original object.
  2. Any changes made inside the method affect the original object.
1(xvii)1 Mark · 2024 · Section A · 2024 PaperFull page

The correct statement to create an object named mango of class fruit:

Show SolutionHide Solution↓

fruit mango = new fruit();

Reason — In Java, creating an object follows the syntax:

ClassName objectName = new ClassName();

Where:

  • ClassName: The name of the class.
  • objectName: The name of the object.
  • new: Allocates memory for the object.
  • ClassName(): Calls the class's constructor.

Thus, fruit mango = new fruit(); correctly creates mango named object of fruit class.

1(xviii)1 Mark · 2024 · Section A · 2024 PaperFull page

Assertion (A): Static method can access static and instance variables.

Reason (R): Static variable can be accessed only by static method.

Show SolutionHide Solution↓

Assertion and Reason both are false.

Reason — A static method can only access static variables and static methods directly because it belongs to the class, not any specific object. Hence, Assertion is false.
Both instance and static methods can access static variables. Hence, Reason is false.

1(xix)1 Mark · 2024 · Section A · 2024 PaperFull page

What is the output of the Java code given below?

String color[] = {"Blue", "Red", "Violet"};
System.out.println(color[2].length());
Show SolutionHide Solution↓

6

Reason — The given Java code declares and initializes a String array color with three elements. The array elements are:

  • color[0] = "Blue"
  • color[1] = "Red"
  • color[2] = "Violet"

The method length() returns the number of characters in the string "Violet".

1(xx)1 Mark · 2024 · Section A · 2024 PaperFull page

Which of the following mathematical methods returns only an integer?

Show SolutionHide Solution↓

Math.round(n)

Reason — In Java, Math.round(n) is the only method in the list that returns an integer when called with a floating-point number (float or double).

2(i)1 Mark · 2024 · Section A · 2024 PaperFull page

Write Java expression for:

$\frac{|𝑎 + 𝑏|}{\sqrt{a^2 + b^2}}$

Show SolutionHide Solution↓

The Java expression for the given mathematical expression can be written as:

double result = Math.abs(a + b) / Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
2(ii)1 Mark · 2024 · Section A · 2024 PaperFull page

Evaluate the expression when x is 4:

x += x++ * ++x % 2;

Show SolutionHide Solution↓

The given expression is evaluated as follows:

x += x++ * ++x % 2
x = x + (x++ * ++x % 2) (x = 4)
x = 4 + (4 * ++x % 2) (x = 5)
x = 4 + (4 * 6 % 2) (x = 6)
x = 4 + (24 % 2) (x = 6)
x = 4 + 0 (x = 6)
x = 4

2(iii)1 Mark · 2024 · Section A · 2024 PaperFull page

Rewrite the following do while program segment using for:

x = 10; y = 20;
do
{
    x++;
    y++;
} while (x<=20);
System.out.println(x * y );
Show SolutionHide Solution↓

Below is the for loop version of the provided do-while segment:

public class Main {
    public static void main(String[] args) {
        int x = 10, y = 20;

        for (; x <= 20; x++, y++) {
            // Body is empty because the increments are in the for loop header
        }

        System.out.println(x * y);
    }
}
2(iv)1 Mark · 2024 · Section A · 2024 PaperFull page

Give the output of the following program segment. How many times is the loop executed?

for(x=10; x>20;x++)

System.out.println(x);

System.out.println(x*2);
Show SolutionHide Solution↓
20

The loop executes 0 times because the loop condition x>20 is false as value of x is 10.

2(v)1 Mark · 2024 · Section A · 2024 PaperFull page
String s1 = "45.50"; String s2 = "54.50";
double d1=Double.parseDouble(s1);
double d2=Double.parseDouble(s2);
int x= (int)(d1+d2);

What is value of x?

Show SolutionHide Solution↓

100

Reason — The code converts the strings "45.50" and "54.50" into doubles using Double.parseDouble(), resulting in d1 = 45.5 and d2 = 54.5. Their sum is 100.0.
Casting 100.0 to an integer using (int) removes the decimal part, leaving x = 100.

2(vi)1 Mark · 2024 · Section A · 2024 PaperFull page

Consider the following two-dimensional array and answer the questions given below:

int x[ ][ ] = {{4,3,2}, {7,8,2}, {8, 3,10}, {1, 2, 9}};

(a) What is the order of the array?

(b) What is the value of x[0][0]+x[2][2]?

Show SolutionHide Solution↓

(a) The order of the array is 4 x 3 as it has 4 rows and 3 columns.

(b) The value is evaluated as follows:

x[0][0] = 4
x[2][2] = 10

x[0][0]+x[2][2] = 4 + 10 = 14

2(vii)1 Mark · 2024 · Section A · 2024 PaperFull page

Differentiate between boxing and unboxing.

Show SolutionHide Solution↓

Differences between boxing and unboxing are:

BoxingUnboxing
It is the process of converting a primitive type to its corresponding wrapper class object.It is the process of converting a wrapper class object back to its corresponding primitive type.
It occurs when assigning a primitive value to a wrapper object.It occurs when assigning a wrapper object to a primitive variable.
Example:
int num = 10;
Integer obj = num;
Example:
Integer obj = 20;
int num = obj;
2(viii)1 Mark · 2024 · Section A · 2024 PaperFull page

The following code to compare two strings is compiled, the following syntax error was displayed – incompatible types – int cannot be converted to boolean.

Identify the statement which has the error and write the correct statement. Give the output of the program segment.

void calculate()
{
String a = "KING", b = "KINGDOM";
boolean x = a.compareTo(b);
System.out.println(x);
}
Show SolutionHide Solution↓

boolean x = a.compareTo(b); has the error.

Corrected statement is:

boolean x = (a.compareTo(b) == 0);

false

Explanation

The error occurs in this line:

boolean x = a.compareTo(b);
  • The compareTo() method of the String class returns an int, not a boolean.
  • The method compares two strings lexicographically and returns:
    • 0 if the strings are equal.
    • A positive value if the calling string is lexicographically greater.
    • A negative value if the calling string is lexicographically smaller.

Since an int cannot be assigned to a boolean variable, this causes a "incompatible types" error.

To fix the error, we can use a comparison to convert the int result into a boolean:

boolean x = (a.compareTo(b) == 0);  // True if strings are equal

This assigns true or false based on whether the two strings are equal.

Corrected Program:

void calculate() {
    String a = "KING", b = "KINGDOM";
    boolean x = (a.compareTo(b) == 0);  // Check if strings are equal
    System.out.println(x);
}

Output of the Program:

  • "KING".compareTo("KINGDOM") compares the strings lexicographically.
  • "KING" is lexicographically smaller than "KINGDOM".
  • The result of compareTo() will be -3 (difference between the lengths of the two strings ⇒ 4 - 7 = -3).

Since a.compareTo(b) == 0 is false, the output will be:

false
2(ix)1 Mark · 2024 · Section A · 2024 PaperFull page

Consider the given program and answer the questions given below:

class temp
{
 int a;
 temp()
 {
 a=10;
 }
 temp(int z)
 {
 a=z;
 }
 void print()
 {
 System.out.println(a);
 }
 void main()
 {
 temp t = new temp();
 temp x = new temp(30);
 t.print();
 x.print();
}
}

(a) What concept of OOPs is depicted in the above program with two constructors?

(b) What is the output of the method main()?

Show SolutionHide Solution↓

(a) The concept of Constructor Overloading (Polymorphism) is depicted in the program.

(b) Output of the main() method:

10
30

Explanation:

Output of the program is explained below:

  1. temp t = new temp();
    Calls the default constructor temp() → a = 10

  2. temp x = new temp(30);
    Calls the parameterized constructor temp(int z) → a = 30

  3. t.print();
    Prints value of a for t → 10

  4. x.print();
    Prints value of a for x → 30

2(x)1 Mark · 2024 · Section A · 2024 PaperFull page

Primitive data types are built in data types which are a part of the wrapper classes. These wrapper classes are encapsulated in the java.lang package. Non primitive datatypes like Scanner class are a part of the utility package for which an object needs to be created.

(a) To which package the Character and Boolean classes belong?

(b) Write the statement to access the Scanner class in the program.

Show SolutionHide Solution↓

(a) java.lang

(b) import java.util.Scanner

3Written · 2024 · Section B · 2024 PaperFull page

DTDC a courier company charges for the courier based on the weight of the parcel. Define a class with the following specifications:

Class name: courier

Member variables:

name – name of the customer

weight – weight of the parcel in kilograms

address – address of the recipient

bill – amount to be paid

type – 'D'- domestic, 'I'- international

Member methods:

void accept ( ) — to accept the details using the methods of the Scanner class only.

void calculate ( ) — to calculate the bill as per the following criteria:

Weight in KgsRate per Kg
First 5 KgsRs.800
Next 5 KgsRs.700
Above 10 KgsRs.500

An additional amount of Rs.1500 is charged if the type of the courier is I (International)

void print ( ) — To print the details

void main ( ) — to create an object of the class and invoke the methods

Show SolutionHide Solution↓
import java.util.Scanner;

public class courier
{
    private String name;
    private double weight;
    private String address;
    private double bill;
    private char type;
    
    public void accept() {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter customer's name: ");
        name = in.nextLine();
        
        System.out.print("Enter recipient's address: ");
        address = in.nextLine();

        System.out.print("Enter parcel weight (in Kgs): ");
        weight = in.nextDouble();

        System.out.println("Enter courier type");
        System.out.print("D (Domestic), I (International): ");
        type = in.next().charAt(0);
    }
    
    public void calculate() {
        if (weight <= 5) {
            bill = weight * 800;
        } else if (weight <= 10) {
            bill = (5 * 800) + ((weight - 5) * 700);
        } else {
            bill = (5 * 800) + (5 * 700) + ((weight - 10) * 500);
        }

        if (type == 'I') {
            bill += 1500;
        }
    }
    
    public void print() {
        System.out.println("Customer's Name: " + name);
        System.out.println("Parcel Weight: " + weight + " Kgs");
        System.out.println("Recipient's Address: " + address);
        System.out.println("Type of Courier: " + type);
        System.out.println("Bill Amount: Rs." + bill);
    }

    public static void main(String[] args) {
        courier obj = new courier();
        obj.accept();
        obj.calculate();
        obj.print();
    }
}
BlueJ output of courier.java
4Written · 2024 · Section B · 2024 PaperFull page

Define a class to overload the method perform as follows:

double perform (double r, double h) — to calculate and return the value of curved surface area of cone

$CSA = \pi rl \quad l = \sqrt{r^2 + h^2}$

void perform (int r, int c) — Use NESTED FOR LOOP to generate the following format

r = 4, c = 5

output
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

void perform (int m, int n, char ch) — to print the quotient of the division of m and n if ch is Q else print the remainder of the division of m and n if ch is R

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatOverloadPerform
{
    double perform(double r, double h) {
        double l = Math.sqrt((r * r) + (h * h));
        double csa = Math.PI * r * l;
        return csa;
    }
    
    void perform(int r, int c) {
        for (int i = 1; i <= r; i++) {
            for (int j = 1; j <= c; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
    
    void perform(int m, int n, char ch) {
        if (ch == 'Q') {
            int q = m / n;
            System.out.println("Quotient: " + q);
        } else if (ch == 'R') {
            int r = m % n;
            System.out.println("Remainder: " + r);
        } else {
            System.out.println("Invalid Character!");
        }
    }
    
    public static void main(String[] args) {
        KboatOverloadPerform mo = new KboatOverloadPerform();

        // Calculating CSA of a cone
        double csa = mo.perform(3.0, 4.0);
        System.out.println("Curved Surface Area of Cone: " + csa);

        // Generating pattern
        mo.perform(4, 5);

        // Printing quotient or remainder
        mo.perform(20, 6, 'Q');
        mo.perform(20, 6, 'R');
    }
}
BlueJ output of KboatOverloadPerform.java
5Written · 2024 · Section B · 2024 PaperFull page

Define a class to accept a number from user and check if it is an EvenPal number or not.

(The number is said to be EvenPal number when number is palindrome number (a number is palindrome if it is equal to its reverse) and sum of its digits is an even number.)

Example: 121 – is a palindrome number
Sum of the digits – 1+2+1 = 4 which is an even number

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatEvenPal
{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int num = in.nextInt();
        int org = num;
        int rev = 0;
        int sum = 0;
        
        while (num > 0) {
            int d = num % 10;
            rev = rev * 10 + d;
            sum += d;
            num /= 10;
        }
        

        if (org == rev && sum % 2 == 0) {
            System.out.println(org + " is an EvenPal number.");
        } else {
            System.out.println(org + " is not an EvenPal number.");
        }
    }
}
BlueJ output of KboatEvenPal.java BlueJ output of KboatEvenPal.java BlueJ output of KboatEvenPal.java
6Written · 2024 · Section B · 2024 PaperFull page

Define a class to accept values into an integer array of order 4 x 4 and check whether it is a DIAGONAL array or not. An array is DIAGONAL if the sum of the left diagonal elements equals the sum of the right diagonal elements. Print the appropriate message.

Example:

3 4 2 5
2 5 2 3
5 3 2 7
1 3 7 1

Sum of the left diagonal element = 3 + 5 + 2 + 1 = 11

Sum of the right diagonal element = 5 + 2 + 3 + 1 = 11

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatDiagonalDDA
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int[][] arr = new int[4][4];
        
        System.out.println("Enter elements for 4x4 DDA:");
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                arr[i][j] = in.nextInt();
            }
        }
        
        int lSum = 0;
        int rSum = 0;
        
        for (int i = 0; i < 4; i++) {
            lSum += arr[i][i];
            rSum += arr[i][3 - i];
        }
        
        if (lSum == rSum) {
            System.out.println("The array is a DIAGONAL array.");
        } else {
            System.out.println("The array is NOT a DIAGONAL array.");
        }
    }
}
BlueJ output of KboatDiagonalDDA.java
7Written · 2024 · Section B · 2024 PaperFull page

Define a class pin code and store the given pin codes in a single dimensional array. Sort these pin codes in ascending order using the Selection Sort technique only. Display the sorted array.

110061, 110001, 110029, 110023, 110055, 110006, 110019, 110033

Show SolutionHide Solution↓
public class Pincode
{
    public static void main(String args[]) {
        int[] arr = {110061, 110001, 
                     110029, 110023, 
                     110055, 110006, 
                     110019, 110033};
                          
        for (int i = 0; i < 7; i++) 
        {
            int idx = i;
            for (int j = i + 1; j < 8; j++) 
            {
                if (arr[j] < arr[idx])
                    idx = j;
            }
            
            int t = arr[i];
            arr[i] = arr[idx];
            arr[idx] = t; 
        }
        
        System.out.println("Sorted Array:");
        for (int i = 0; i < 8; i++) 
        {
            System.out.print(arr[i] + " ");
        }

    }
}
BlueJ output of Pincode.java
8Written · 2024 · Section B · 2024 PaperFull page

Define a class to accept the gmail id and check for its validity.

A gmail id is valid only if it has:

→ @

→ .(dot)

→ gmail

→ com

Example: [email protected] is a valid gmail id

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatValidateGmail
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a Gmail ID: ");
        String gmailId = in.nextLine();
        int len = gmailId.length(); 

        if (gmailId.endsWith("@gmail.com")
        && gmailId.indexOf('@') == len - 10)
        {
            System.out.println(gmailId + " is a valid Gmail ID.");
        }
        else
        {
            System.out.println(gmailId + " is NOT a valid Gmail ID.");
        }
    }
}
BlueJ output of KboatValidateGmail.java BlueJ output of KboatValidateGmail.java BlueJ output of KboatValidateGmail.java
1(ii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

The expression which uses >= operator is known as:

Show SolutionHide Solution↓

relational

Reason — Relational expressions are constructed using relational operators — equal to ( == ), not equal to ( != ), less than ( < ), less than equal to ( <= ), greater than ( > ), greater than equal to ( >= )

1(iii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Ternary operator is a:

Show SolutionHide Solution↓

conditional operator

Reason — Ternary operator is a conditional operator as it evaluates the given condition. Its syntax is as follows:

condition? expression 1 : expression 2

If the condition is true then result of ternary operator is the value of expression 1. Otherwise the result is the value of expression 2.

1(iv)1 Mark · 2024 · Section A · 2024 SpecimenFull page

When primitive data type is converted to a corresponding object of its class, it is called:

Show SolutionHide Solution↓

Boxing

Reason — Boxing is the conversion of primitive data type into an object of its corresponding wrapper class.

1(v)1 Mark · 2024 · Section A · 2024 SpecimenFull page

The number of bytes occupied by a character array of 10 elements.

Show SolutionHide Solution↓

20 bytes

Reason — A char data type occupies '2' bytes in the memory. Thus, 10 char type elements occupy (10 x 2) = 20 bytes in memory.

1(vi)1 Mark · 2024 · Section A · 2024 SpecimenFull page

The method of Scanner class used to accept a double value is:

Show SolutionHide Solution↓

nextDouble()

Reason — The nextDouble() function reads the next token entered by the user as a double value.

1(vii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Among the following which is a keyword:

Show SolutionHide Solution↓

case

Reason — case is a keyword. It is used to define switch case construct.

1(viii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

The output of Math.round(6.6) + Math.ceil(3.4) is:

Show SolutionHide Solution↓

11.0

Reason — The given expression is evaluated as follows:
Math.round(6.6) + Math.ceil(3.4)
⇒ 7 + 4.0
⇒ 11.0

Math.round() rounds off its argument to the nearest mathematical integer and returns its value as an int or long type. Math.ceil method returns the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer. In the addition operation, the type of result is promoted to a double as one operand is double. Hence, the result is 11.0.

1(ix)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Name the type of error, if any in the following statement:

System.out.print("HELLO")

Show SolutionHide Solution↓

syntax

Reason — The given statement is missing a terminator ( ; ) at the end. Thus, it has a syntax error.

1(x)5 Marks · 2024 · Section A · 2024 SpecimenFull page

Java statement to access the 5th element of an array is:

Show SolutionHide Solution↓

X[4]

Reason — Array indexes start from 0. So, X[4] refers to the 5th element of the array.

1(xi)1 Mark · 2024 · Section A · 2024 SpecimenFull page

The output of "Remarkable".substring(6) is:

Show SolutionHide Solution↓

able

Reason — "Remarkable".substring(6) will extract a substring starting from the character at index 6 (i.e., 7th character of the string) which is 'a' till the end of the string. Hence the output is able.

1(xii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Which of the following is the wrapper class for the data type char?

Show SolutionHide Solution↓

Character

Reason — Character is the wrapper class for the data type char.

1(xiii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Name the package that contains wrapper classes:

Show SolutionHide Solution↓

java.lang

Reason — Wrapper classes are present in java.lang package.

1(xiv)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Constructor overloading follows which principle of Object Oriented programming?

Show SolutionHide Solution↓

Polymorphism

Reason — In object-oriented programming, Polymorphism provides the means to perform a single action in multiple different ways and constructor overloading follows Polymorphism principle of Object Oriented programming wherein a constructor having the same name behaves differently with different arguments.

1(xv)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Which of the following is a valid Integer constant:
i. 4
ii. 4.0
iii. 4.3f
iv. "four"

Show SolutionHide Solution↓

Only i

Reason — Integer constants represent whole number values only. Thus, 4 is an integer constant. 4.0 is a double constant, 4.3f is a float constant while "four" is a String constant.

1(xvi)1 Mark · 2024 · Section A · 2024 SpecimenFull page

The method compareTo() returns ............... when two strings are equal and in lowercase :

Show SolutionHide Solution↓

0

Reason — compareTo() method compares two strings lexicographically and returns the difference between the ASCII values of the first differing characters in the strings. Here, the strings are equal so the difference is 0.

1(xvii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Assertion (A): In Java, statements written in lower case letter or upper case letter are treated as the same.

Reason (R): Java is a case sensitive language.

Show SolutionHide Solution↓

Assertion (A) is false and Reason (R) is true

Reason — In Java, statements written in lower case letter or upper case letter are treated differently as Java is a case sensitive language.

1(xviii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Read the following text, and choose the correct answer:

A class encapsulate Data Members that contains the information necessary to represent the class and Member methods that perform operations on the data member.

What does a class encapsulate?

Show SolutionHide Solution↓

Data members and Member methods

Reason — A class encapsulates state and behavior by combining data and functions into a single unit. The state of an object is represented by its member variables and behaviour is represented by member methods.

1(xix)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Assertion (A): Call by value is known as pure method.

Reason (R): The original value of variable does not change as operation is performed on copied values.

Show SolutionHide Solution↓

Both Assertion (A) and Reason (R) are true and Reason (R) is a correct explanation of Assertion (A)

Reason — Call by value is known as pure method as it does not modify the value of original variables. The original value of variable does not change as operation is performed on copied values.

1(xx)1 Mark · 2024 · Section A · 2024 SpecimenFull page

What will be the output for:

System.out.print(Character.toLowerCase('1'));
Show SolutionHide Solution↓

1

Reason — In Java, the Character.toLowerCase(char ch) method is used to convert a given character to its lowercase equivalent, if one exists. If the character is already in lowercase or there is no lowercase equivalent, it will return the original character.

2(i)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Write the Java expression for (p + q)2.

Show SolutionHide Solution↓

Math.pow((p + q) , 2)

2(ii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Evaluate the expression when the value of x = 2:

x = x++ + ++x + x

Show SolutionHide Solution↓
10

Initially, x = 2. The expression is calculated as follows:

x = x++ + ++x + x
x = 2 + ++x + x          (x = 3)
x = 2 + 4 + x               (x = 4)
x = 2 + 4 + 4               (x = 4)
x = 10

2(iii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

The following code segment should print "You can go out" if you have done your homework (dh) and cleaned your room (cr). However, the code has errors. Fix the code so that it compiles and runs correctly.

boolean dh = True; 
boolean cr= true; 
if (dh && cr)
System.out.println("You cannot go out"); 
else
System.out.println("You can go out");	
Show SolutionHide Solution↓

The corrected code is as follows:

boolean dh = true; 
boolean cr= true; 
if (dh && cr)
System.out.println("You can go out"); 
else
System.out.println("You cannot go out");	
  1. boolean dh = True; — Here, True should be in lowercase as true.
  2. println statements of if-else should be interchanged because if both dh (done homework) and cr (cleaned room) are true then the person can go out.
2(iv)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Sam executes the following program segment and the answer displayed is zero irrespective of any non zero values are given. Name the error. How the program can be modified to get the correct answer?

void triangle(double b, double h)
{	
    double a; 
    a = 1/2 * b * h;
    System.out.println("Area=" + a);	
}	
Show SolutionHide Solution↓

Logical error.

Modified program:

void triangle(double b, double h)
{	
    double a; 
    a = 1.0/2 * b * h;
    System.out.println("Area=" + a);	
}	

The statement is evaluated as follows:

a = 1/2 * b * h;
a = 0 * b * h; (1/2 being integer division gives the result as 0)
a = 0 (Since anything multiplied by 0 will be 0)

To avoid this error, we can replace '1/2' with '1.0/2'. Now the expression will be evaluated as follows:

a = 1.0/2 * b * h;
a = 0.5 * b * h; (The floating-point division will result in result as as 0.5)

This will give the correct result for the given code.

2(v)1 Mark · 2024 · Section A · 2024 SpecimenFull page

How many times will the following loop execute? What value will be returned?

int x = 2;
int y = 50;
do{
++x;
y -= x++;
}
while(x <= 10);
return y;
Show SolutionHide Solution↓

The loop will execute 5 times and the value returned is 15.

IterationXYRemark
 250Initial values
1347x = 4 (3 + 1), y = 47 (50 - 3)
2542x = 6 (5 + 1), y = 42 (47 - 5)
3735x = 8 (7 + 1), y = 35 (42 - 7)
4926x = 10 (8 + 1), y = 26 (35 - 9)
51115x = 12 (11 + 1), y = 15 (26 - 11)
 1115Condition becomes false. Loop terminates.
2(vi)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Write the output of the following String methods:

(a) "ARTIFICIAL".indexOf('I')

(b) "DOG and PUPPY".trim().length()

Show SolutionHide Solution↓

(a)

3

indexOf() returns the index of the first occurrence of the specified character within the string or -1 if the character is not present. First occurrence of 'I' in "ARTIFICIAL" is at index 3 (a string begins at index 0).

(b)

13

trim() removes all leading and trailing space from the string and length() returns the length of the string i.e., the number of characters present in the string. Thus, the output is 13.

2(vii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Name any two jump statements.

Show SolutionHide Solution↓

Two jump statements are:

  1. break statement
  2. continue statement
2(viii)1 Mark · 2024 · Section A · 2024 SpecimenFull page

Predict the output of the following code snippet:

String a = "20";
String b = "23";
int p = Integer.parseInt(a); 
int q = Integer.parseInt(b); 
System.out.print(a + "*" + b);
Show SolutionHide Solution↓
20*23

Integer.parseInt() method will convert the strings a and b to their corresponding numerical integers — 20 and 23. In the statement, System.out.print(a + "*" + b); a, b, and "*" are strings so + operator concatenates them and prints 20*23 as the output.

2(ix)1 Mark · 2024 · Section A · 2024 SpecimenFull page

When there is no explicit initialization, what are the default values set for variables in the following cases?

(a) Integer variable

(b) String variable

Show SolutionHide Solution↓

(a) 0

(b) null

2(x)1 Mark · 2024 · Section A · 2024 SpecimenFull page

int P[ ] = {12, 14, 16, 18};
int Q[ ] = {20, 22, 24};

Place all elements of P array and Q array in the array R one after the other.

(a) What will be the size of array R[ ] ?

(b) Write index position of first and last element?

Show SolutionHide Solution↓

int R[ ] = {12, 14, 16, 18, 20, 22, 24};

(a) Size of array P[ ] = 4
     Size of array Q[ ] = 3
     Size of array R[ ] = 7 (4 + 3).

(b) Index position of first element is 0.
     Index position of last element is 6.

3Written · 2024 · Section B · 2024 SpecimenFull page

Define a class called with the following specifications:

Class name: Eshop

Member variables:
String name: name of the item purchased
double price: Price of the item purchased

Member methods:
void accept(): Accept the name and the price of the item using the methods of Scanner class.
void calculate(): To calculate the net amount to be paid by a customer, based on the following criteria:

PriceDiscount
1000 – 250005.0%
25001 – 570007.5 %
57001 – 10000010.0%
More than 10000015.0 %

void display(): To display the name of the item and the net amount to be paid.

Write the main method to create an object and call the above methods.

Show SolutionHide Solution↓
import java.util.Scanner;
public class Eshop
{
    private String name;
    private double price;
    private double disc;
    private double amount;

    public void accept() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter item name: ");
        name = in.nextLine();
        System.out.print("Enter price of item: ");
        price = in.nextDouble();
    }
    
    public void calculate() {
        double d = 0.0;
        
        if (price < 1000)
            d = 0.0;
        else if (price <= 25000)
            d = 5.0;
        else if (price <= 57000)
            d = 7.5;
        else if (price <= 100000)
            d = 10.0;
        else
            d = 15.0;
        
        disc = price * d / 100.0;
        amount = price - disc;
        
    }
    
    public void display() {
        System.out.println("Item Name: " + name);
        System.out.println("Net Amount: " + amount);
    }
    
    public static void main(String args[]) {
        Eshop obj = new Eshop();
        obj.accept();
        obj.calculate();
        obj.display();
    }
}
BlueJ output of Eshop.java
4Written · 2024 · Section B · 2024 SpecimenFull page

Define a class to accept values in integer array of size 10. Sort them in an ascending order using selection sort technique. Display the sorted array.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSelectionSort
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        int arr[] = new int[10];
        System.out.println("Enter 10 integers: ");
        for (int i = 0; i < 10; i++) 
        {
            arr[i] = in.nextInt();
        }
        
        for (int i = 0; i < 9; i++) 
        {
            int idx = i;
            for (int j = i + 1; j < 10; j++) 
            {
                if (arr[j] < arr[idx])
                    idx = j;
            }
            
            int t = arr[i];
            arr[i] = arr[idx];
            arr[idx] = t; 
        }
        
        System.out.println("Sorted Array:");
        for (int i = 0; i < 10; i++) 
        {
            System.out.print(arr[i] + " ");
        }
    }
}
BlueJ output of KboatSelectionSort.java
5Written · 2024 · Section B · 2024 SpecimenFull page

Define a class to accept a string and convert it into uppercase. Count and display the number of vowels in it.

Input: robotics
Output: ROBOTICS
Number of vowels: 3

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatCountVowels
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the string: ");
        String str = in.nextLine();
        str = str.toUpperCase();
        str += " ";
        int count = 0;
        int len = str.length();
        
        for (int i = 0; i < len - 1; i++) 
        {
            char ch = str.charAt(i);
            if(ch == 'A' 
                || ch == 'E' 
                || ch == 'I'
                || ch == 'O'
                || ch == 'U')
                count++;
        }
        
        System.out.println("String : " + str);
        System.out.println("Number of vowels : " + count);
    }
}
BlueJ output of KboatCountVowels.java
6Written · 2024 · Section B · 2024 SpecimenFull page

Define a class to accept values into a 3 × 3 array and check if it is a special array. An array is a special array if the sum of the even elements = sum of the odd elements.

Example:
A[ ][ ]={{ 4 ,5, 6}, { 5 ,3, 2}, { 4, 2, 5}};
Sum of even elements = 4 + 6 + 2 + 4 + 2 = 18
Sum of odd elements = 5 + 5 + 3 + 5 = 18

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatDDASpArr
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        int arr[][] = new int[3][3];
        long evenSum = 0, oddSum = 0;
        System.out.println("Enter the elements of 3 x 3 DDA: ");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                arr[i][j] = in.nextInt();
            }
        }
        
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (arr[i][j] % 2 == 0)
                    evenSum += arr[i][j];
                else
                    oddSum += arr[i][j];
            }
        }
        
        System.out.println("Sum of even elements = " + evenSum);
        System.out.println("Sum of odd elements = " + oddSum);
        if (evenSum == oddSum)
            System.out.println("Special Array");
        else
            System.out.println("Not a Special Array");
    }
}
BlueJ output of KboatDDASpArr.java
7Written · 2024 · Section B · 2024 SpecimenFull page

Define a class to accept a 3 digit number and check whether it is a duck number or not.
Note: A number is a duck number if it has zero in it.

Example 1:
Input: 2083
Output: Invalid

Example 2:
Input: 103
Output: Duck number

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatDuckNumber
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = in.nextInt();
        int n = num;
        int count = 0;
        
        while (n != 0)    {
            count++;
            n = n / 10;
        }
        
        if (count == 3)
        {
            n = num;
            boolean isDuck = false;
            while(n != 0) 
            {
                if(n % 10 == 0)  
                {  
                    isDuck = true;
                    break;
                }
                n = n / 10;  
            }
            
            if (isDuck) {
                System.out.println("Duck Number");
            }
            else {
                System.out.println("Not a Duck Number");
            }
        }
        else {
            System.out.println("Invalid");
        }
    }
}
BlueJ output of KboatDuckNumber.java BlueJ output of KboatDuckNumber.java BlueJ output of KboatDuckNumber.java
8Written · 2024 · Section B · 2024 SpecimenFull page

Define a class to overload the method display as follows:

void display( ): To print the following format using nested loop

Show SolutionHide Solution↓
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

void display(int n): To print the square root of each digit of the given number.

Example:
n = 4329
Output – 3.0
1.414213562
1.732050808
2.0

import java.util.Scanner;

public class KboatMethodOverload
{
    public void display()
    {
        for(int i = 1; i <= 5; i++) 
        {
            for(int j = 1; j <= i; j++)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
    
    public void display(int n)
    {
        while( n != 0)
        {
            int d = n % 10;
            System.out.println(Math.sqrt(d));
            n = n / 10;
        }
    }
    
    public static void main(String args[]) 
    {
        KboatMethodOverload obj = new KboatMethodOverload();
        Scanner in = new Scanner(System.in);
        
        System.out.println("Pattern: ");
        obj.display();
        
        System.out.print("Enter a number: ");
        int num = in.nextInt();
        obj.display(num);
        
    }
}
BlueJ output of KboatMethodOverload.java
1(i)1 Mark · 2023 · Section A · 2023 PaperFull page

A mechanism where one class acquires the properties of another class:

Show SolutionHide Solution↓

Inheritance

Reason — Inheritance enables new classes to receive or inherit the properties and methods of existing classes.

1(ii)1 Mark · 2023 · Section A · 2023 PaperFull page

Identify the type of operator &&:

Show SolutionHide Solution↓

logical

Reason — Logical operators operate only on boolean operands and are used to construct complex decision-making expressions. Logical AND && operator evaluates to true only if both of its operands are true.

1(iii)1 Mark · 2023 · Section A · 2023 PaperFull page

The Scanner class method used to accept words with space:

Show SolutionHide Solution↓

nextLine()

Reason — nextLine() reads the input till the end of line so it can read a full sentence including spaces.

1(iv)1 Mark · 2023 · Section A · 2023 PaperFull page

The keyword used to call package in the program:

Show SolutionHide Solution↓

import

Reason — import keyword is used to import built-in and user-defined packages into our Java program.

1(v)1 Mark · 2023 · Section A · 2023 PaperFull page

What value will Math.sqrt(Math.ceil(15.3)) return?

Show SolutionHide Solution↓

4.0

Reason — Math.ceil method returns the smallest double value that is greater than or equal to the argument and Math.sqrt method returns the square root of its argument as a double value. Thus the given expression is evaluated as follows:

Math.sqrt(Math.ceil (15.3))
= Math.sqrt(16.0)
= 4.0

1(vi)1 Mark · 2023 · Section A · 2023 PaperFull page

The absence of which statement leads to fall through situation in switch case statement?

Show SolutionHide Solution↓

break

Reason — The absence of break statement leads to fall through situation in switch case statement.

1(vii)1 Mark · 2023 · Section A · 2023 PaperFull page

State the type of loop in the given program segment:

for (int i = 5; i != 0; i -= 2)
    System.out.println(i);
Show SolutionHide Solution↓

infinite

Reason — The given loop is an example of infinite loop as for each consecutive iteration of for loop, the value of i will be updates as follows:

IterationValue of iRemark
15Initial value of i = 5
23i = 5 - 2 = 3
31i = 3 - 2 = 1
4-1i = 1 - 2 = -1
5-3i = -1 - 2 = -3 and so on...

Since i will never be '0', the loop will execute infinitely.

1(viii)1 Mark · 2023 · Section A · 2023 PaperFull page

Write a method prototype name check() which takes an integer argument and returns a char:

Show SolutionHide Solution↓

char check (int x)

Reason — The prototype of a function is written in the given syntax:

return_type method_name(arguments)

Thus, the method has the prototype given below:

char check (int x)

1(ix)1 Mark · 2023 · Section A · 2023 PaperFull page

The number of values that a method can return is:

Show SolutionHide Solution↓

1

Reason — A method can return only one value.

1(x)1 Mark · 2023 · Section A · 2023 PaperFull page

Predict the output of the following code snippet:

String P = "20", Q ="22"; 
int a = Integer.parseInt(P);
int b = Integer.valueOf(Q);
System.out.println(a + " " + b);
Show SolutionHide Solution↓

20 22

Reason — The values of strings P and Q are converted into integers using the Integer.parseInt() method and stored in int variables a and b, respectively.
When the statement System.out.println(a + " " + b) is executed, first the operation a + " " is performed. Here, int variable a is converted to a string and a space is concatenated to it resulting in "20 ".
After this, the operation "20 " + b is performed resulting in 20 22 which is printed as the output.

1(xi)1 Mark · 2023 · Section A · 2023 PaperFull page

The String class method to join two strings is:

Show SolutionHide Solution↓

concat(String)

Reason — concat() method is used to join two strings. Its syntax is as follows:

String1.concat(String2)

1(xii)1 Mark · 2023 · Section A · 2023 PaperFull page

The output of the function "COMPOSITION".substring(3, 6):

Show SolutionHide Solution↓

POS

Reason — The substring() method returns a substring beginning from the startindex and extending to the character at endIndex - 1. Since a string index begins at 0, the character at index 3 is 'P' and the character at index 5 (6-1 = 5) is 'S'. Thus, "POS" is extracted.

1(xiii)1 Mark · 2023 · Section A · 2023 PaperFull page

int x = (int)32.8; is an example of ............... typecasting.

Show SolutionHide Solution↓

explicit

Reason — In explicit type conversion, the data gets converted to a type as specified by the programmer. Here, the float value 32.8 is being converted to int type by the programmer, explicitly.

1(xiv)1 Mark · 2023 · Section A · 2023 PaperFull page

The code obtained after compilation is known as:

Show SolutionHide Solution↓

java byte code

Reason — Java compiler converts Java source code into an intermediate binary code called Bytecode after compilation.

1(xv)1 Mark · 2023 · Section A · 2023 PaperFull page

Missing a semicolon in a statement is what type of error?

Show SolutionHide Solution↓

Syntax

Reason — Syntax Errors occur when we violate the rules of writing the statements of the programming language. Missing a semicolon in a statement is a syntax error.

1(xvi)1 Mark · 2023 · Section A · 2023 PaperFull page

Consider the following program segment and select the output of the same when n = 10 :

switch(n)
{
    case 10 : System.out.println(n*2); 
    case 4 : System.out.println(n*4); break; 
    default : System.out.println(n);
}
Show SolutionHide Solution↓
20
40

Reason — Since n = 10, case 10 will be executed. It prints 20 (10 * 2) on the screen. Since break statement is missing, the execution falls through to the next case. Case 4 prints 40 (10 * 4) on the screen. Now the control finds the break statement and the control comes out of the switch statement.

1(xvii)1 Mark · 2023 · Section A · 2023 PaperFull page

A method which does not modify the value of variables is termed as:

Show SolutionHide Solution↓

Pure method

Reason — A method which does not modify the value of variables is termed as a pure method.

1(xviii)1 Mark · 2023 · Section A · 2023 PaperFull page

When an object of a Wrapper class is converted to its corresponding primitive data type, it is called as ............... .

Show SolutionHide Solution↓

Unboxing

Reason — When an object of a Wrapper class is converted to its corresponding primitive data type, it is called as unboxing.

1(xix)1 Mark · 2023 · Section A · 2023 PaperFull page

The number of bits occupied by the value ‘a’ are:

Show SolutionHide Solution↓

16 bits

Reason — A char data type occupies 2 bytes in the memory.

1 byte = 8 bits
2 bytes = 8 * 2 = 16 bits

1(xx)1 Mark · 2023 · Section A · 2023 PaperFull page

Method which is a part of a class rather than an instance of the class is termed as:

Show SolutionHide Solution↓

Static method

Reason — Method which is a part of a class rather than an instance of the class is termed as Static method.

2(i)1 Mark · 2023 · Section A · 2023 PaperFull page

Write the Java expression for (a + b)x.

Show SolutionHide Solution↓
Math.pow(a + b, x)
2(ii)1 Mark · 2023 · Section A · 2023 PaperFull page

Evaluate the expression when the value of x = 4:

x *= --x + x++ + x

Show SolutionHide Solution↓

The given expression is evaluated as follows:

x *= --x + x++ + x (x = 4)
x *= 3 + x++ + x (x = 3)
x *= 3 + 3 + x (x = 4)
x *= 3 + 3 + 4 (x = 4)
x *= 10 (x = 4)
x = x * 10 (x = 4)
x = 4 * 10
x = 40

2(iii)1 Mark · 2023 · Section A · 2023 PaperFull page

Convert the following do…while loop to for loop:

int x = 10;
do
{
x––;
System.out.print(x);
}while (x>=1);	
Show SolutionHide Solution↓
for(int x = 9; x >= 0; x--)
{
    System.out.print(x);
}
2(iv)1 Mark · 2023 · Section A · 2023 PaperFull page

Give the output of the following Character class methods:

(a) Character.toUpperCase ('a')

(b) Character.isLetterOrDigit('#')

Show SolutionHide Solution↓

(a) Character.toUpperCase ('a')

A

In Java, the Character.toUpperCase(char ch) method is used to convert a given character to its uppercase equivalent, if one exists. So, the output is uppercase 'A'.

(b) Character.isLetterOrDigit('#')

false

Character.isLetterOrDigit() method returns true if the given character is a letter or digit, else returns false. Since, hash (#) is neither letter nor digit, the method returns false.

2(v)1 Mark · 2023 · Section A · 2023 PaperFull page

Rewrite the following code using the if-else statement:

int m = 400;
double ch = (m>300) ? (m / 10.0) * 2 : (m / 20.0) - 2;
Show SolutionHide Solution↓
int m = 400;
double ch = 0.0;
if(m > 300)
    ch = (m / 10.0) * 2;
else
    ch = (m / 20.0) - 2;
2(vi)1 Mark · 2023 · Section A · 2023 PaperFull page

Give the output of the following program segment:

int n = 4279; int d;
while(n > 0)
{ d = n % 10;
System.out.println(d); 
n = n / 100;
}
Show SolutionHide Solution↓
9
2

Step by step explanation of the code:

  1. int n = 4279; — Initializes the integer n with the value 4279.
  2. int d; — Declares an integer variable d without initializing it. It will be used to store the individual digits.

Now, let's go through the loop:

The while loop continues as long as n is greater than 0:

  • d = n % 10; — This line calculates the remainder when n is divided by 10 and stores it in d. In the first iteration, d will be 9 because the remainder of 4279 divided by 10 is 9.
  • System.out.println(d); — This line prints the value of d. In the first iteration, it will print 9.
  • n = n / 100; — This line performs integer division of n by 100. In the first iteration, n becomes 42. (Remember, it is integer division so only quotient is taken and fractional part is discarded.)

The loop continues, and in the second iteration:

  • d = n % 10; — d will now be 2 because the remainder of 42 divided by 10 is 2.
  • System.out.println(d); — It prints 2.
  • n = n / 100; — n becomes 0 because 42 divided by 100 is 0. Since n is no longer greater than 0, the loop terminates.
2(vii)1 Mark · 2023 · Section A · 2023 PaperFull page

Give the output of the following String class methods:

(a) "COMMENCEMENT".lastIndexOf('M')

(b) "devote".compareTo("DEVOTE")

Show SolutionHide Solution↓

(a) "COMMENCEMENT".lastIndexOf('M')

8
2(viii)1 Mark · 2023 · Section A · 2023 PaperFull page

Consider the given array and answer the questions given below:

int x[ ] = {4, 7, 9, 66, 72, 0, 16};

(a) What is the length of the array?

(b) What is the value in x[4]?

Show SolutionHide Solution↓

(a) 7

(b) 72

2(ix)1 Mark · 2023 · Section A · 2023 PaperFull page

Name the following:

(a) What is an instance of the class called?

(b) The method which has same name as that of the class name.

Show SolutionHide Solution↓

(a) Object.

(b) Constructor.

2(x)1 Mark · 2023 · Section A · 2023 PaperFull page

Write the value of n after execution:

char ch ='d';
int n = ch + 5;	
Show SolutionHide Solution↓

The value of n is 105.

3Written · 2023 · Section B · 2023 PaperFull page

Design a class with the following specifications:

Class name: Student

Member variables:
name — name of student
age — age of student
mks — marks obtained
stream — stream allocated

(Declare the variables using appropriate data types)

Member methods:
void accept() — Accept name, age and marks using methods of Scanner class.
void allocation() — Allocate the stream as per following criteria:

mksstream
>= 300Science and Computer
>= 200 and < 300Commerce and Computer
>= 75 and < 200Arts and Animation
< 75Try Again

void print() – Display student name, age, mks and stream allocated.

Call all the above methods in main method using an object.

Show SolutionHide Solution↓
import java.util.Scanner;

public class Student
{
    private String name;
    private int age;
    private double mks;
    private String stream;
    
    public void accept() 
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter student name: ");
        name = in.nextLine();
        System.out.print("Enter age: ");
        age = in.nextInt();
        System.out.print("Enter marks: ");
        mks = in.nextDouble();
    }
    
    public void allocation() 
    {
        if (mks < 75)
            stream = "Try again";
        else if (mks < 200)
            stream = "Arts and Animation";
        else if (mks < 300)
            stream = "Commerce and Computer";
        else
            stream = "Science and Computer";
    }
    
    public void print() 
    {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Marks: " + mks);
        System.out.println("Stream allocated: " + stream);
    }
    
    public static void main(String args[]) {
        Student obj = new Student();
        obj.accept();
        obj.allocation();
        obj.print();
    }
}
BlueJ output of Student.java
4Written · 2023 · Section B · 2023 PaperFull page

Define a class to accept 10 characters from a user. Using bubble sort technique arrange them in ascending order. Display the sorted array and original array.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatCharBubbleSort
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        char ch[] = new char[10];
        System.out.println("Enter 10 characters:");
        for (int i = 0;  i < ch.length; i++) {
            ch[i] = in.nextLine().charAt(0);
        }

        System.out.println("Original Array");
        for (int i = 0;  i < ch.length; i++) {
            System.out.print(ch[i] + " ");
        }
        
        //Bubble Sort
        for (int i = 0; i < ch.length - 1; i++) {
            for (int j = 0; j < ch.length - 1 - i; j++) {
                if (ch[j] > (ch[j + 1])) {
                    char t = ch[j];
                    ch[j] = ch[j + 1];
                    ch[j + 1] = t;
                }
            }
        }
        
        System.out.println("\nSorted Array");
        for (int i = 0;  i < ch.length; i++) {
            System.out.print(ch[i] + " ");
        }
    }
}
BlueJ output of KboatCharBubbleSort.java
5Written · 2023 · Section B · 2023 PaperFull page

Define a class to overload the function print as follows:

void print() - to print the following format

Show SolutionHide Solution↓
1  1  1  1
2  2  2  2
3  3  3  3
4  4  4  4
5  5  5  5

void print(int n) - To check whether the number is a lead number. A lead number is the one whose sum of even digits are equal to sum of odd digits.

e.g. 3669
odd digits sum = 3 + 9 = 12
even digits sum = 6 + 6 = 12
3669 is a lead number.

import java.util.Scanner;

public class KboatMethodOverload
{
    public void print()
    {
        for(int i = 1; i <= 5; i++) 
        {
            for(int j = 1; j <= 4; j++)
            {
                System.out.print(i + " ");
            }
        System.out.println();
        }
    }
    
    public void print(int n)
    {
        int d = 0;
        int evenSum = 0;
        int oddSum = 0;
        while( n != 0)
        {
            d = n % 10;
            if (d % 2 == 0)
                    evenSum += d;
                else
                    oddSum += d;
            n = n / 10;
        }
        
        if(evenSum == oddSum)
            System.out.println("Lead number");
        else
            System.out.println("Not a lead number");
    }
    
    public static void main(String args[]) 
    {
        KboatMethodOverload obj = new KboatMethodOverload();
        Scanner in = new Scanner(System.in);
        
        System.out.println("Pattern: ");
        obj.print();
        
        System.out.print("Enter a number: ");
        int num = in.nextInt();
        obj.print(num);
    }
}
BlueJ output of KboatMethodOverload.java
6Written · 2023 · Section B · 2023 PaperFull page

Define a class to accept a String and print the number of digits, alphabets and special characters in the string.

Example:
S = "KAPILDEV@83"
Output:
Number of digits – 2
Number of Alphabets – 8
Number of Special characters – 1

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatCount
{
   public static void main(String args[]) 
   {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = in.nextLine();
             
        int len = str.length();

        int ac = 0;
        int sc = 0;
        int dc = 0;
        char ch;

        for (int i = 0; i < len; i++) {
            ch = str.charAt(i);
            if (Character.isLetter(ch))  
                ac++;    
            else if (Character.isDigit(ch))
                dc++;
            else if (!Character.isWhitespace(ch))
                sc++;
        }
        
        System.out.println("No. of Digits = " + dc);
        System.out.println("No. of Alphabets = " + ac);
        System.out.println("No. of Special Characters = " + sc);
        
    }
}
BlueJ output of KboatCount.java
7Written · 2023 · Section B · 2023 PaperFull page

Define a class to accept values into an array of double data type of size 20. Accept a double value from user and search in the array using linear search method. If value is found display message "Found" with its position where it is present in the array. Otherwise display message "not found".

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatLinearSearch
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        
        double arr[] = new double[20];
        int l = arr.length;
        int i = 0;
        
        System.out.println("Enter array elements: ");
        for (i = 0; i < l; i++) 
        {
            arr[i] = in.nextDouble();    
        }
        
        System.out.print("Enter the number to search: ");
        double n = in.nextDouble();
        
        for (i = 0; i < l; i++) 
        {
            if (arr[i] == n) 
            {
                break;
            }
        }
        
        if (i == l) 
        {
            System.out.println("Not found");
        }
        else 
        {
            System.out.println(n + " found at index " + i);
        }
    }
}
BlueJ output of KboatLinearSearch.java
8Written · 2023 · Section B · 2023 PaperFull page

Define a class to accept values in integer array of size 10. Find sum of one digit number and sum of two digit numbers entered. Display them separately.

Example:
Input: a[ ] = {2, 12, 4, 9, 18, 25, 3, 32, 20, 1}
Output:
Sum of one digit numbers : 2 + 4 + 9 + 3 + 1 = 19
Sum of two digit numbers : 12 + 18 + 25 + 32 + 20 = 107

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatDigitSum
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        int oneSum = 0, twoSum = 0, d = 0;
        int arr[] = new int[10];
        System.out.println("Enter 10 numbers");
        int l = arr.length;
        
        for (int i = 0; i < l; i++) 
        {
            arr[i] = in.nextInt();
        }
        
        for (int i = 0; i < l; i++) 
        {
            if(arr[i] >= 0 && arr[i] < 10 )
                oneSum += arr[i];
            else if(arr[i] >= 10 && arr[i] < 100 )
                twoSum += arr[i];
        }
        
        System.out.println("Sum of 1 digit numbers = "+ oneSum);
        System.out.println("Sum of 2 digit numbers = "+ twoSum);
        
    }
}
BlueJ output of KboatDigitSum.java
1(i)1 Mark · 2022 · Section A · 2022 Semester 2Full page

Return data type of isLetter(char) is ............... .

Show SolutionHide Solution↓

boolean

Reason — isLetter() method returns true if the specified character is a letter else, it returns false. Thus, the return data type of isLetter(char) is boolean.

1(ii)1 Mark · 2022 · Section A · 2022 Semester 2Full page

Method that converts a character to uppercase is ............... .

Show SolutionHide Solution↓

toUpperCase(char)

Reason — Method that converts a character to uppercase is toUpperCase(char) method.

1(iii)1 Mark · 2022 · Section A · 2022 Semester 2Full page

Give output of the following String methods:

"SUCESS".indexOf('S') + "SUCCESS".lastIndexOf('S')

Show SolutionHide Solution↓

6

Reason — indexOf() returns the index of the first occurrence of the specified character within the string and lastIndexOf() returns the index of the last occurrence of the specified character within the string. Since a string begins with index 0, the given methods are evaluated as follows:

"SUCESS".indexOf('S') + "SUCCESS".lastIndexOf('S')
⇒ 0 + 6
⇒ 6

1(iv)1 Mark · 2022 · Section A · 2022 Semester 2Full page

Corresponding wrapper class of float data type is ............... .

Show SolutionHide Solution↓

Float

Reason — Corresponding wrapper class of float data type is Float.

1(v)1 Mark · 2022 · Section A · 2022 Semester 2Full page

............... class is used to convert a primitive data type to its corresponding object.

Show SolutionHide Solution↓

Wrapper

Reason — Wrapper class is used to convert a primitive data type to its corresponding object.

1(vi)1 Mark · 2022 · Section A · 2022 Semester 2Full page

Give the output of the following code:

System.out.println("Good".concat("Day"));

Show SolutionHide Solution↓

GoodDay

Reason — concat() method is used to join two strings. Thus, "Good" and "Day" are joined together and printed as "GoodDay".

1(vii)1 Mark · 2022 · Section A · 2022 Semester 2Full page

A single dimensional array contains N elements. What will be the last subscript?

Show SolutionHide Solution↓

N - 1

Reason — The index of an array begins from 0 and continues till Size - 1. Thus, if an array has N elements, the last subscript/index will be N - 1.

1(viii)1 Mark · 2022 · Section A · 2022 Semester 2Full page

The access modifier that gives least accessibility is:

Show SolutionHide Solution↓

private

Reason — A data member or member method declared as private is only accessible inside the class in which it is declared. Thus, it gives the least accessibility.

1(ix)1 Mark · 2022 · Section A · 2022 Semester 2Full page

Give the output of the following code :

String A = "56.0", B = "94.0";
double C = Double.parseDouble(A); 
double D = Double.parseDouble(B); 
System.out.println((C+D));
Show SolutionHide Solution↓

150.0

Reason — parseDouble() method returns a double value represented by the specified string. Thus, double values 56.0 and 94.0 are stored in C and D, respectively. Both C and D are added and 150.0 (56.0 + 94.0) is printed on the screen.

1(x)1 Mark · 2022 · Section A · 2022 Semester 2Full page

What will be the output of the following code?

System.out.println("Lucknow".substring(0,4));

Show SolutionHide Solution↓

Luck

Reason — The substring() method returns a substring beginning from the startindex and extending to the character at index endIndex - 1. Since a string index begins at 0, the character at startindex (0) is 'L' and the character at the endIndex (4-1 = 3) is 'k'. Thus, "Luck" is extracted and printed on the screen.

2Written · 2022 · Section B · 2022 Semester 2Full page

Define a class to perform binary search on a list of integers given below, to search for an element input by the user, if it is found display the element along with its position, otherwise display the message "Search element not found".

2, 5, 7, 10, 15, 20, 29, 30, 46, 50

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatBinarySearch
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        int arr[] = {2, 5, 7, 10, 15, 20, 29, 30, 46, 50};
        
        System.out.print("Enter number to search: ");
        int n = in.nextInt();
        
        int l = 0, h = arr.length - 1, index = -1;
        while (l <= h) {
            int m = (l + h) / 2;
            if (arr[m] < n)
                l = m + 1;
            else if (arr[m] > n)
                h = m - 1;
            else {
                index = m;
                break;
            }
                
        }
        
        if (index == -1) {
            System.out.println("Search element not found");
        }
        else {
            System.out.println(n + " found at position " + index);
        }
    }
}
BlueJ output of KboatBinarySearch.java BlueJ output of KboatBinarySearch.java
3Written · 2022 · Section B · 2022 Semester 2Full page

Define a class to declare a character array of size ten. Accept the characters into the array and display the characters with highest and lowest ASCII (American Standard Code for Information Interchange) value.
EXAMPLE :
INPUT:
'R', 'z', 'q', 'A', 'N', 'p', 'm', 'U', 'Q', 'F'
OUTPUT :
Character with highest ASCII value = z
Character with lowest ASCII value = A

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatASCIIVal
{

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        char ch[] = new char[10];
        int len = ch.length;
        
        System.out.println("Enter 10 characters:");
        for (int i = 0; i < len; i++)
        {
            ch[i] = in.nextLine().charAt(0);
        }
        
        char h = ch[0];
        char l = ch[0];
        
        for (int i = 1; i < len; i++)
        {
            if (ch[i] > h)
            {
                h = ch[i];
            }
            
            if (ch[i] < l)
            {
                l = ch[i];
            }
        }

        System.out.println("Character with highest ASCII value: " + h);
        System.out.println("Character with lowest ASCII value: " + l);
    }

}
BlueJ output of KboatASCIIVal.java
4Written · 2022 · Section B · 2022 Semester 2Full page

Define a class to declare an array of size twenty of double datatype, accept the elements into the array and perform the following :

Calculate and print the product of all the elements.
Print the square of each element of the array.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSDADouble
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        double  arr[] = new double[20];
        int l = arr.length;
        double p = 1.0;
        
        System.out.println("Enter 20 numbers:");
        for (int i = 0; i < l; i++)
        {
            arr[i] = in.nextDouble();
        }
        
        for (int i = 0; i < l; i++)
        {
            p *= arr[i];
        }        
        System.out.println("Product = " + p);
        
        System.out.println("Square of array elements :");
        for (int i = 0; i < l; i++)
        {
            double sq = Math.pow(arr[i], 2);
            System.out.println(sq + " ");
        }  
    }
}
BlueJ output of KboatSDADouble.java
5Written · 2022 · Section B · 2022 Semester 2Full page

Define a class to accept a string, and print the characters with the uppercase and lowercase reversed, but all the other characters should remain the same as before.

EXAMPLE:
INPUT : WelCoMe_2022
OUTPUT : wELcOmE_2022

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatChangeCase
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = in.nextLine();
        int len = str.length();
        String rev = "";

        for (int i = 0; i < len; i++) 
        {
            char ch = str.charAt(i);
            if (Character.isLetter(ch))
            {
                if(Character.isUpperCase(ch))
                {
                    rev += Character.toLowerCase(ch);
                }
                else
                {
                     rev += Character.toUpperCase(ch);
                }
            }
            else
            {
                rev += ch;
            }
        }
        
        System.out.println(rev);

    }
}
BlueJ output of KboatChangeCase.java
6Written · 2022 · Section B · 2022 Semester 2Full page

Define a class to declare an array to accept and store ten words. Display only those words which begin with the letter 'A' or 'a' and also end with the letter 'A' or 'a'.
EXAMPLE :
Input : Hari, Anita, Akash, Amrita, Alina, Devi Rishab, John, Farha, AMITHA
Output: Anita
Amrita
Alina
AMITHA

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatWords
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        String names[] = new String[10];
        int l = names.length;
        System.out.println("Enter 10 names : ");
        
        for (int i = 0; i < l; i++) 
        {
            names[i] = in.nextLine();
        }
        
        System.out.println("Names that begin and end with letter A are:");

        for(int i = 0; i < l; i++)
        {
            String str = names[i];
            int len = str.length();
            char begin = Character.toUpperCase(str.charAt(0));
            char end = Character.toUpperCase(str.charAt(len - 1));
            if (begin == 'A' && end == 'A') {
                System.out.println(str);
            }
        }
    }
}
BlueJ output of KboatWords.java
7Written · 2022 · Section B · 2022 Semester 2Full page

Define a class to accept two strings of same length and form a new word in such a way that, the first character of the first word is followed by the first character of the second word and so on.
Example :
Input string 1 – BALL
Input string 2 – WORD

OUTPUT : BWAOLRLD

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatStringMerge
{
    public static void main(String args[]) 
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter String 1: ");
        String s1 = in.nextLine();
        System.out.println("Enter String 2: ");
        String s2 = in.nextLine();
        String str = "";
        int len = s1.length();
        
        if(s2.length() == len)
        { 
            for (int i = 0; i < len; i++) 
            {
                char ch1 = s1.charAt(i);
                char ch2 = s2.charAt(i);
                str = str + ch1 + ch2;
            }
            System.out.println(str);
        }
        else
        {
             System.out.println("Strings should be of same length");
        }
    }
}
BlueJ output of KboatStringMerge.java BlueJ output of KboatStringMerge.java
11 Mark · 2019 · Section A · 2019 PaperFull page

(a) Name any two basic principles of Object-oriented Programming.

Show SolutionHide Solution↓
  1. Encapsulation
  2. Inheritance

(b) Write a difference between unary and binary operator.

unary operators operate on a single operand whereas binary operators operate on two operands.

(c) Name the keyword which:

  1. indicates that a method has no return type.
  2. makes the variable as a class variable
  1. void
  2. static

(d) Write the memory capacity (storage size) of short and float data type in bytes.

  1. short — 2 bytes
  2. float — 4 bytes

(e) Identify and name the following tokens:

  1. public
  2. 'a'
  3. ==
  4. { }
  1. Keyword
  2. Literal
  3. Operator
  4. Separator
21 Mark · 2019 · Section A · 2019 PaperFull page

(a) Differentiate between if else if and switch-case statements

Show SolutionHide Solution↓
if else ifswitch-case
if else if can test for any Boolean expression like less than, greater than, equal to, not equal to, etc.switch-case can only test if the expression is equal to any of its case constants.
if else if can use different expression involving unrelated variables in its different condition expressions.switch-case statement tests the same expression against a set of constant values.

(b) Give the output of the following code:

String P = "20", Q ="19";
int a = Integer.parseInt(P);
int b = Integer.valueOf(Q);
System.out.println(a+""+b);

Output of the above code is:

2019

Both Integer.parseInt() and Integer.valueOf() methods convert a string into integer. Integer.parseInt() returns an int value that gets assigned to a. Integer.valueOf() returns an Integer object (i.e. the wrapper class of int). Due to auto-boxing, Integer object is converted to int and gets assigned to b. So a becomes 20 and b becomes 19. 2019 is printed as the output.

(c) What are the various types of errors in Java?

There are 3 types of errors in Java:

  1. Syntax Error
  2. Runtime Error
  3. Logical Error

(d) State the data type and value of res after the following is executed:

char ch = '9';
res= Character.isDigit(ch);

Data type of res is boolean as return type of method Character.isDigit() is boolean. Its value is true as '9' is a digit.

(e) What is the difference between the linear search and the binary search technique?

Linear searchBinary search
Linear search works on sorted and unsorted arrays.Binary search works on only sorted arrays.
In Linear search, each element of the array is checked against the target value until the element is found or end of the array is reached.In Binary search, array is successively divided into 2 halves and the target element is searched either in the first half or in the second half.
Linear Search is slower.Binary Search is faster.
31 Mark · 2019 · Section A · 2019 PaperFull page

(a) Write a Java expression for the following:
       |x2 + 2xy|

Show SolutionHide Solution↓

Math.abs(x * x + 2 * x * y)

(b) Write the return data type of the following functions:

  1. startsWith()
  2. random()
  1. boolean
  2. double

(c) If the value of basic=1500, what will be the value of tax after the following statement is executed?

tax = basic > 1200 ? 200 :100;

Value of tax will be 200. As basic is 1500, the condition of ternary operator — basic > 1200 is true. 200 is returned as the result of ternary operator and it gets assigned to tax.

(d) Give the output of following code and mention how many times the loop will execute?

int i;
for( i=5; i>=1; i--)
{
    if(i%2 == 1)
        continue;
    System.out.print(i+" ");
}

Output of the above code is:

4 2

Loop executes 5 times. The below table shows the dry run of the loop:

iOutputRemark
51st Iteration — As i % 2 gives 1 so condition is true and continue statement is executed. Nothing is printed in this iteration.
442nd Iteration — i % 2 is 0 so condition is false. Print statement prints 4 (current value of i) in this iteration.
343rd Iteration — i % 2 is 1 so continue statement is executed and nothing is printed in this iteration.
24 24th Iteration — i % 2 is 0. Print statement prints 2 (current value of i) in this iteration.
14 25th Iteration — i % 2 is 1 so continue statement is executed and nothing is printed in this iteration.
04 2As condition of loop (i >= 1) becomes false so loops exits and 6th iteration does not happen.

(e) State a difference between call by value and call by reference.

In call by value, actual parameters are copied to formal parameters. Any changes to formal parameters are not reflected onto the actual parameters. In call by reference, formal parameters refer to actual parameters. The changes to formal parameters are reflected onto the actual parameters.

(f) Give the output of the following:
       Math.sqrt(Math.max(9,16))

The output is 4.0.
First Math.max(9,16) is evaluated. It returns 16, the greater of its arguments. Math.sqrt(Math.max(9,16)) becomes Math.sqrt(16). It returns the square root of 16 which is 4.0.

(g) Write the output for the following:

String s1 = "phoenix"; String s2 ="island";
System.out.println(s1.substring(0).concat(s2.substring(2)));
System.out.println(s2.toUpperCase());

The output of above code is:

phoenixland
ISLAND

s1.substring(0) results in phoenix. s2.substring(2) results in land. concat method joins both of them resulting in phoenixland. s2.toUpperCase() converts island to uppercase.

(h) Evaluate the following expression if the value of x=2, y=3 and z=1.

  v=x + --z + y++ + y

    v = x + --z + y++ + y
⇒ v = 2 + 0 + 3 + 4
⇒ v = 9

(i) String x[] = {"Artificial intelligence", "IOT", "Machine learning", "Big data"};

Give the output of the following statements:

  1. System.out.println(x[3]);
  2. System.out.println(x.length);
  1. Big data
  2. 4

(j) What is meant by a package? Give an example.

A package is a named collection of Java classes that are grouped on the basis of their functionality. For example, java.util.

4Written · 2019 · Section B · 2019 PaperFull page

Design a class name ShowRoom with the following description:

Instance variables / Data members:
String name — To store the name of the customer
long mobno — To store the mobile number of the customer
double cost — To store the cost of the items purchased
double dis — To store the discount amount
double amount — To store the amount to be paid after discount

Member methods:
ShowRoom() — default constructor to initialize data members
void input() — To input customer name, mobile number, cost
void calculate() — To calculate discount on the cost of purchased items, based on following criteria

CostDiscount (in percentage)
Less than or equal to ₹100005%
More than ₹10000 and less than or equal to ₹2000010%
More than ₹20000 and less than or equal to ₹3500015%
More than ₹3500020%

void display() — To display customer name, mobile number, amount to be paid after discount.

Write a main method to create an object of the class and call the above member methods.

Show SolutionHide Solution↓
import java.util.Scanner;

public class ShowRoom
{
    private String name;
    private long mobno;
    private double cost;
    private double dis;
    private double amount;

    public ShowRoom()
    {
        name = "";
        mobno = 0;
        cost = 0.0;
        dis = 0.0;
        amount = 0.0;
    }

    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter customer name: ");
        name = in.nextLine();
        System.out.print("Enter customer mobile no: ");
        mobno = in.nextLong();
        System.out.print("Enter cost: ");
        cost = in.nextDouble();
    }
    
    public void calculate() {
        int disPercent = 0;
        if (cost <= 10000)
            disPercent = 5;
        else if (cost <= 20000)
            disPercent = 10;
        else if (cost <= 35000)
            disPercent = 15;
        else
            disPercent = 20;
        
        dis = cost * disPercent / 100.0;
        amount = cost - dis;
    }
    
    public void display() {
        System.out.println("Customer Name: " + name);
        System.out.println("Mobile Number: " + mobno);
        System.out.println("Amout after discount: " + amount);
    }
    
    public static void main(String args[]) {
        ShowRoom obj = new ShowRoom();
        obj.input();
        obj.calculate();
        obj.display();
    }
}
BlueJ output of ShowRoom.java
5Written · 2019 · Section B · 2019 PaperFull page

Using the switch-case statement, write a menu driven program to do the following:

(a) To generate and print Letters from A to Z and their Unicode

LettersUnicode
A65
B66
..
..
..
Z90

(b) Display the following pattern using iteration (looping) statement:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Show SolutionHide Solution↓
import java.util.Scanner;

public class KnowledgeBoat
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter 1 for letters and Unicode");
        System.out.println("Enter 2 to display the pattern");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();
        switch(ch) {
            case 1:
            System.out.println("Letters\tUnicode");
            for (int i = 65; i <= 90; i++)
                System.out.println((char)i + "\t" + i);
            break;
            
            case 2:
            for (int i = 1; i <= 5; i++) {
                for (int j = 1; j <= i; j++)
                    System.out.print(j + " ");
                System.out.println();
            }
            break;
            
            default:
            System.out.println("Wrong choice");
            break;
        }
    }
}
BlueJ output of KnowledgeBoat.java BlueJ output of KnowledgeBoat.java
6Written · 2019 · Section B · 2019 PaperFull page

Write a program to input 15 integer elements in an array and sort them in ascending order using the bubble sort technique.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatBubbleSort
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int n = 15;
        int arr[] = new int[n];
        
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        
        //Bubble Sort
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int t = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = t;
                }
            } 
        }
        
        System.out.println("Sorted Array:");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
BlueJ output of KboatBubbleSort.java
7Written · 2019 · Section B · 2019 PaperFull page

Design a class to overload a function series( ) as follows:

(a) void series (int x, int n) – To display the sum of the series given below:

x1 + x2 + x3 + .......... xn terms

(b) void series (int p) – To display the following series:

0, 7, 26, 63 .......... p terms

(c) void series () – To display the sum of the series given below:

1/2 + 1/3 + 1/4 + .......... 1/10

Show SolutionHide Solution↓
public class KboatOverloadSeries
{
    void series(int x, int n) {
        long sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += Math.pow(x, i);
        }
        System.out.println("Sum = " + sum);
    }

    void series(int p) {
        for (int i = 1; i <= p; i++) {
            int term = (int)(Math.pow(i, 3) - 1);
            System.out.print(term + " ");
        }
        System.out.println();
    }

    void series() {
        double sum = 0.0;
        for (int i = 2; i <= 10; i++) {
            sum += 1.0 / i;
        }
        System.out.println("Sum = " + sum);
    }
}
BlueJ output of KboatOverloadSeries.java BlueJ output of KboatOverloadSeries.java BlueJ output of KboatOverloadSeries.java
8Written · 2019 · Section B · 2019 PaperFull page

Write a program to input a sentence and convert it into uppercase and count and display the total number of words starting with a letter 'A'.

Example:

Sample Input: ADVANCEMENT AND APPLICATION OF INFORMATION TECHNOLOGY ARE EVER CHANGING.

Sample Output: Total number of words starting with letter 'A' = 4

Show SolutionHide Solution↓
import java.util.Scanner;

public class WordsWithLetterA
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String str = in.nextLine();
        str = " " + str; //Add space in the begining of str
        int c = 0;
        int len = str.length();
        str = str.toUpperCase();
        for (int i = 0; i < len - 1; i++) {
            if (str.charAt(i) == ' ' && str.charAt(i + 1) == 'A')
                c++;
        }
        System.out.println("Total number of words starting with letter 'A' = " + c);
    }
}
BlueJ output of WordsWithLetterA.java
9Written · 2019 · Section B · 2019 PaperFull page

A tech number has even number of digits. If the number is split in two equal halves, then the square of sum of these halves is equal to the number itself. Write a program to generate and print all four digits tech numbers.

Example:

Consider the number 3025

Square of sum of the halves of 3025 = (30 + 25)2
= (55)2
= 3025 is a tech number.

Show SolutionHide Solution↓
public class TechNumbers
{
    public static void main(String args[]) {
        for (int i = 1000; i <= 9999; i++) {
            int secondHalf = i % 100;
            int firstHalf = i / 100;
            int sum = firstHalf + secondHalf;
            if (i == sum * sum)
                System.out.println(i);
        }
    }
}
BlueJ output of TechNumbers.java
11 Mark · 2018 · Section A · 2018 PaperFull page

(a) Define abstraction.

Show SolutionHide Solution↓

Abstraction refers to the act of representing essential features without including the background details or explanation.

(b) Differentiate between searching and sorting.

SearchingSorting
Searching means to search for a term or value in an array.Sorting means to arrange the elements of the array in ascending or descending order.
Linear search and Binary search are examples of search techniques.Bubble sort and Selection sort are examples of sorting techniques.

(c) Write a difference between the functions isUpperCase( ) and toUpperCase( ).

isUpperCase( )toUpperCase( )
isUpperCase( ) function checks if a given character is in uppercase or not.toUpperCase( ) function converts a given character to uppercase.
Its return type is boolean.Its return type is char.

(d) How are private members of a class different from public members?

private members of a class can only be accessed by other member methods of the same class whereas public members of a class can be accessed by methods of other classes as well.

(e) Classify the following as primitive or non-primitive datatypes:

  1. char
  2. arrays
  3. int
  4. classes
  1. Primitive
  2. Non-Primitive
  3. Primitive
  4. Non-Primitive
21 Mark · 2018 · Section A · 2018 PaperFull page

(a) (i) int res = 'A';
What is the value of res?

Show SolutionHide Solution↓

Value of res is 65 which is the ASCII code of A. As res is an int variable and we are trying to assign it the character A so through implicit type conversion the ASCII code of A is assigned to res.

(ii) Name the package that contains wrapper classes.

java.lang

(b) State the difference between while and do while loop.

whiledo-while
It is an entry-controlled loop.It is an exit-controlled loop.
It is helpful in situations where numbers of iterations are not known.It is suitable when we need to display a menu to the user.

(c) System.out.print("BEST ");
     System.out.println("OF LUCK");

Choose the correct option for the output of the above statements

  1. BEST OF LUCK
  2. BEST
    OF LUCK

Option 1 — BEST OF LUCK is the correct option.
System.out.print does not print a newline at the end of its output so the println statement begins printing on the same line. So the output is BEST OF LUCK printed on a single line.

(d) Write the prototype of a function check which takes an integer as an argument and returns a character.

char check(int a)

(e) Write the return data type of the following function.

  1. endsWith()
  2. log()
  1. boolean
  2. double
31 Mark · 2018 · Section A · 2018 PaperFull page

(a) Write a Java expression for the following:

$\bold{\frac{\sqrt{3x+x^2}}{a + b}}$

Show SolutionHide Solution↓

Math.sqrt(3 * x + x * x) / (a + b)

(b) What is the value of y after evaluating the expression given below?

y+= ++y + y-- + --y; when int y=8

    y+= ++y + y-- + --y
⇒ y = y + (++y + y-- + --y)
⇒ y = 8 + (9 + 9 + 7)
⇒ y = 8 + 25
⇒ y = 33

(c) Give the output of the following:

  1. Math.floor (-4.7)
  2. Math.ceil(3.4) + Math.pow(2, 3)
  1. -5.0
  2. 12.0

(d) Write two characteristics of a constructor.

Two characteristics of a constructor are:

  1. A constructor has the same name as its class.
  2. A constructor does not have a return type.

(e) Write the output for the following:

System.out.println("Incredible"+"\n"+"world");

Output of the above code is:

Incredible
world

\n is the escape sequence for newline so Incredible and world are printed on two different lines.

(f) Convert the following if else if construct into switch case

if( var==1)
    System.out.println("good");
else if(var==2)
    System.out.println("better");
else if(var==3)
    System.out.println("best");
else
    System.out.println("invalid");
switch (var) {
    case 1:
        System.out.println("good");
        break;

    case 2:
        System.out.println("better");
        break;

    case 3:
        System.out.println("best");
        break;

    default:
        System.out.println("invalid");
}

(g) Give the output of the following string functions:

  1. "ACHIEVEMENT".replace('E', 'A')
  2. "DEDICATE".compareTo("DEVOTE")
  1. ACHIAVAMANT
  2. -18
  1. "ACHIEVEMENT".replace('E', 'A') will replace all the E's in ACHIEVEMENT with A's.
  2. The first letters that are different in DEDICATE and DEVOTE are D and V respectively. So the output will be:
        ASCII code of D - ASCII code of V
    ⇒ 68 - 86
    ⇒ -18

(h) Consider the following String array and give the output

String arr[]= {"DELHI", "CHENNAI", "MUMBAI", "LUCKNOW", "JAIPUR"};
System.out.println(arr[0].length() > arr[3].length());
System.out.print(arr[4].substring(0,3));

Output of the above code is:

false
JAI
  1. arr[0] is DELHI and arr[3] is LUCKNOW. Length of DELHI is 5 and LUCKNOW is 7. As 5 > 7 is false so the output is false.
  2. arr[4] is JAIPUR. arr[4].substring(0,3) extracts the characters from index 0 till index 2 of JAIPUR so JAI is the output.

(i) Rewrite the following using ternary operator:

if (bill > 10000 )
discount = bill * 10.0/100;
else
discount = bill * 5.0/100;
discount = bill > 10000 ? bill * 10.0/100 : bill * 5.0/100;

(j) Give the output of the following program segment and also mention how many times the loop is executed:

int i;
for ( i = 5 ; i > 10; i ++ )
System.out.println( i );
System.out.println( i * 4 );

Output of the above code is:

20

Loop executes 0 times.

In the loop, i is initialized to 5 but the condition of the loop is i > 10. As 5 is less than 10 so the condition of the loop is false and it is not executed. There are no curly braces after the loop which means that the statement System.out.println( i ); is inside the loop and the statement System.out.println( i * 4 ); is outside the loop. Loop is not executed so System.out.println( i ); is not executed but System.out.println( i * 4 ); being outside the loop is executed and prints the output as 20 (i * 4 ⇒ 5 * 4 ⇒ 20).

4Written · 2018 · Section B · 2018 PaperFull page

Design a class RailwayTicket with following description:

Instance variables/data members:
String name — To store the name of the customer
String coach — To store the type of coach customer wants to travel
long mobno — To store customer’s mobile number
int amt — To store basic amount of ticket
int totalamt — To store the amount to be paid after updating the original amount

Member methods:
void accept() — To take input for name, coach, mobile number and amount.
void update() — To update the amount as per the coach selected (extra amount to be added in the amount as follows)

Type of CoachesAmount
First_AC700
Second_AC500
Third_AC250
sleeperNone

void display() — To display all details of a customer such as name, coach, total amount and mobile number.

Write a main method to create an object of the class and call the above member methods.

Show SolutionHide Solution↓
import java.util.Scanner;

public class RailwayTicket
{
    private String name;
    private String coach;
    private long mobno;
    private int amt;
    private int totalamt;
    
    private void accept() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter name: ");
        name = in.nextLine();
        System.out.print("Enter coach: ");
        coach = in.nextLine();
        System.out.print("Enter mobile no: ");
        mobno = in.nextLong();
        System.out.print("Enter amount: ");
        amt = in.nextInt();
    }
    
    private void update() {
        if(coach.equalsIgnoreCase("First_AC"))
            totalamt = amt + 700;
        else if(coach.equalsIgnoreCase("Second_AC"))
            totalamt = amt + 500;
        else if(coach.equalsIgnoreCase("Third_AC"))
            totalamt = amt + 250;
        else if(coach.equalsIgnoreCase("Sleeper"))
            totalamt = amt;
    }
    
    private void display() {
        System.out.println("Name: " + name);
        System.out.println("Coach: " + coach);
        System.out.println("Total Amount: " + totalamt);
        System.out.println("Mobile number: " + mobno);
    }
    
    public static void main(String args[]) {
        RailwayTicket obj = new RailwayTicket();
        obj.accept();
        obj.update();
        obj.display();
    }
}
BlueJ output of RailwayTicket.java
5Written · 2018 · Section B · 2018 PaperFull page

Write a program to input a number and check and print whether it is a Pronic number or not. (Pronic number is the number which is the product of two consecutive integers)

Examples:
12 = 3 x 4
20 = 4 x 5
42 = 6 x 7

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatPronicNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number to check: ");
        int num = in.nextInt();
        
        boolean isPronic = false;
        
        for (int i = 1; i <= num - 1; i++) {
            if (i * (i + 1) == num) {
                isPronic = true;
                break;
            }
        }
        
        if (isPronic)
            System.out.println(num + " is a pronic number");
        else
            System.out.println(num + " is not a pronic number");
    }
}
BlueJ output of KboatPronicNumber.java
6Written · 2018 · Section B · 2018 PaperFull page

Write a program in Java to accept a string in lower case and change the first letter of every word to upper case. Display the new string.

Sample input: we are in cyber world
Sample output: We Are In Cyber World

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatString
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String str = in.nextLine();
        String word = "";

        for (int i = 0; i < str.length(); i++) {
            if (i == 0 || str.charAt(i - 1) == ' ') {
                word += Character.toUpperCase(str.charAt(i));
            }
            else {
                word += str.charAt(i);
            }
        }

        System.out.println(word);
    }
}
BlueJ output of KboatString.java
7Written · 2018 · Section B · 2018 PaperFull page

Design a class to overload a function volume() as follows:

Show SolutionHide Solution↓
public class KboatVolume
{
    double volume(double r) {
        return (4 / 3.0) * (22 / 7.0) * r * r * r;
    }
    
    double volume(double h, double r) {
        return (22 / 7.0) * r * r * h;
    }
    
    double volume(double l, double b, double h) {
        return l * b * h;
    }
    
    public static void main(String args[]) {
        KboatVolume obj = new KboatVolume();
        System.out.println("Sphere Volume = " + 
            obj.volume(6));
        System.out.println("Cylinder Volume = " + 
            obj.volume(5, 3.5));
        System.out.println("Cuboid Volume = " + 
            obj.volume(7.5, 3.5, 2));
    }
}
BlueJ output of KboatVolume.java
8Written · 2018 · Section B · 2018 PaperFull page

Write a menu driven program to display the pattern as per user’s choice.

Pattern 1

ABCDE
ABCD
ABC
AB
A

Pattern 2

B
LL
UUU
EEEE

For an incorrect option, an appropriate error message should be displayed.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatMenuPattern
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter 1 for pattern 1");
        System.out.println("Enter 2 for Pattern 2");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        switch (choice) {
            case 1:
            for (int i = 69; i >= 65; i--) {
                for (int j = 65; j <= i; j++) {
                    System.out.print((char)j);
                }
                System.out.println();
            }
            break;

            case 2:
            String word = "BLUE";
            int len = word.length();
            for(int i = 0; i < len; i++) {
                for(int j = 0; j <= i; j++) {
                    System.out.print(word.charAt(i));
                }
                System.out.println();
            }
            break;

            default:
            System.out.println("Incorrect choice");
            break;

        }
    }
}
BlueJ output of KboatMenuPattern.java BlueJ output of KboatMenuPattern.java
9Written · 2018 · Section B · 2018 PaperFull page

Write a program to accept name and total marks of N number of students in two single subscript array name[] and totalmarks[].

Calculate and print:

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSDAMarks
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number of students: ");
        int n = in.nextInt();
        
        String name[] = new String[n];
        int totalmarks[] = new int[n];
        int grandTotal = 0;
        
        for (int i = 0; i < n; i++) {
            in.nextLine();
            System.out.print("Enter name of student " + (i+1) + ": ");
            name[i] = in.nextLine();
            System.out.print("Enter total marks of student " + (i+1) + ": ");
            totalmarks[i] = in.nextInt();
            grandTotal += totalmarks[i];
        }
        
        double avg = grandTotal / (double)n;
        System.out.println("Average = " + avg);
        
        for (int i = 0; i < n; i++) {
            System.out.println("Deviation for " + name[i] + " = " 
            + (totalmarks[i] - avg));
        }
    }
}
BlueJ output of KboatSDAMarks.java
11 Mark · 2017 · Section A · 2017 PaperFull page

(a) What is inheritance?

Show SolutionHide Solution↓

Inheritance is the mechanism by which a class acquires the properties and methods of another class.

(b) Name the operators listed below:

  1. <
  2. ++
  3. &&
  4. ? :
  1. Less than operator. (It is a relational operator)
  2. Increment operator. (It is an arithmetic operator)
  3. Logical AND operator. (It is a logical operator)
  4. Ternary operator. (It is a conditional operator)

(c) State the number of bytes occupied by char and int data types.

char occupies 2 bytes and int occupies 4 bytes.

(d) Write one difference between / and % operator.

/ operator computes the quotient whereas % operator computes the remainder.

(e) String x[] = {"SAMSUNG", "NOKIA", "SONY", "MICROMAX", "BLACKBERRY"};

Give the output of the following statements:

  1. System.out.println(x[1]);
  2. System.out.println(x[3].length());
  1. The output of System.out.println(x[1]); is NOKIA. x[1] gives the second element of the array x which is "NOKIA"

  2. The output of System.out.println(x[3].length()); is 8. x[3].length() gives the number of characters in the fourth element of the array x which is MICROMAX.

21 Mark · 2017 · Section A · 2017 PaperFull page

(a) Name the following:

Show SolutionHide Solution↓
  1. import
  2. Array

(b) What are the two ways of invoking functions?

Call by value and call by reference.

(c) State the data type and value of res after the following is executed:

char ch='t';
res= Character.toUpperCase(ch);

Data type of res is char and its value is T.

(d) Give the output of the following program segment and also mention the number of times the loop is executed:

int a,b;
for (a = 6, b = 4; a <= 24; a = a + 6)
{
    if (a%b == 0)
    break;
}
System.out.println(a);

Output of the above code is 12 and loop executes 2 times.

This dry run explains the working of the loop.

abRemarks
641st Iteration
1242nd Iteration

In 2nd iteration, as a%b becomes 0 so break statement is executed and the loop exits. Program control comes to the println statement which prints the output as current value of a which is 12.

(e) Write the output:

char ch = 'F';
int m = ch;
m=m+5;
System.out.println(m + " " + ch);

Output of the above code is:

75 F

The statement int m = ch; assigns the ASCII value of F (which is 70) to variable m. Adding 5 to m makes it 75. In the println statement, the current value of m which is 75 is printed followed by space and then value of ch which is F.

31 Mark · 2017 · Section A · 2017 PaperFull page

(a) Write a Java expression for the following:
ax5 + bx3 + c

Show SolutionHide Solution↓

a * Math.pow(x, 5) + b * Math.pow(x, 3) + c

(b) What is the value of x1 if x=5?
x1= ++x – x++ + --x

    x1 = ++x – x++ + --x
⇒ x1 = 6 - 6 + 6
⇒ x1 = 0 + 6
⇒ x1 = 6

(c) Why is an object called an instance of a class?

A class can create objects of itself with different characteristics and common behaviour. So, we can say that an Object represents a specific state of the class. For these reasons, an Object is called an Instance of a Class.

(d) Convert following do-while loop into for loop.

int i = 1;
int d = 5;
do {
    d=d*2;
    System.out.println(d);
    i++ ; } while ( i<=5);
int i = 1;
int d = 5;
for (i = 1; i <= 5; i++) {
    d=d*2;
    System.out.println(d);
}

(e) Differentiate between constructor and function.

ConstructorFunction
Constructor is a block of code that initializes a newly created object.Function is a group of statements that can be called at any point in the program using its name to perform a specific task.
Constructor has the same name as class name.Function should have a different name than class name.
Constructor has no return type not even void.Function requires a valid return type.

(f) Write the output for the following:

String s="Today is Test";
System.out.println(s.indexOf('T'));
System.out.println(s.substring(0,7) + " " +"Holiday");

Output of the above code is:

0
Today i Holiday

As the first T is present at index 0 in string s so s.indexOf('T') returns 0. s.substring(0,7) extracts the characters from index 0 to index 6 of string s. So its result is Today i. After that println statement prints Today i followed by a space and Holiday.

(g) What are the values stored in variables r1 and r2:

  1. double r1 = Math.abs(Math.min(-2.83, -5.83));
  2. double r2 = Math.sqrt(Math.floor(16.3));
  1. r1 has 5.83
  2. r2 has 4.0
  1. Math.min(-2.83, -5.83) returns -5.83 as -5.83 is less than -2.83. (Note that these are negative numbers). Math.abs(-5.83) returns 5.83.
  2. Math.floor(16.3) returns 16.0. Math.sqrt(16.0) gives square root of 16.0 which is 4.0.

(h) Give the output of the following code:

String A ="26", B="100";
String D=A+B+"200";
int x= Integer.parseInt(A);
int y = Integer.parseInt(B);
int d = x+y;
System.out.println("Result 1 = " + D);
System.out.println("Result 2 = " + d);

Output of the above code is:

Result 1 = 26100200
Result 2 = 126
  1. As A and B are strings so String D=A+B+"200"; joins A, B and "200" storing the string "26100200" in D.
  2. Integer.parseInt() converts strings A and B into their respective numeric values. Thus, x becomes 26 and y becomes 100.
  3. As Java is case-sensitive so D and d are treated as two different variables.
  4. Sum of x and y is assigned to d. Thus, d gets a value of 126.

(i) Analyze the given program segment and answer the following questions:

for(int i=3;i<=4;i++ ) {
for(int j=2;j<i;j++ ) {
System.out.print("" ); }
System.out.println("WIN" ); }
  1. How many times does the inner loop execute?
  2. Write the output of the program segment.
  1. Inner loop executes 3 times.
    (For 1st iteration of outer loop, inner loop executes once. For 2nd iteration of outer loop, inner loop executes two times.)

  2. Output:
    WIN
    WIN

(j) What is the difference between the Scanner class functions next() and nextLine()?

next()nextLine()
It reads the input only till space so it can read only a single word.It reads the input till the end of line so it can read a full sentence including spaces.
It places the cursor in the same line after reading the input.It places the cursor in the next line after reading the input.
4Written · 2017 · Section B · 2017 PaperFull page

Define a class ElectricBill with the following specifications:

class : ElectricBill

Instance variables / data member:
String n — to store the name of the customer
int units — to store the number of units consumed
double bill — to store the amount to be paid

Member methods:
void accept( ) — to accept the name of the customer and number of units consumed
void calculate( ) — to calculate the bill as per the following tariff:

Number of unitsRate per unit
First 100 unitsRs.2.00
Next 200 unitsRs.3.00
Above 300 unitsRs.5.00

A surcharge of 2.5% charged if the number of units consumed is above 300 units.

void print( ) — To print the details as follows:
Name of the customer: ………………………
Number of units consumed: ………………………
Bill amount: ………………………

Write a main method to create an object of the class and call the above member methods.

Show SolutionHide Solution↓
import java.util.Scanner;

public class ElectricBill
{
    private String n;
    private int units;
    private double bill;
    
    public void accept() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter customer name: ");
        n = in.nextLine();
        System.out.print("Enter units consumed: ");
        units = in.nextInt();
    }
    
    public void calculate() {
        if (units <= 100)
            bill = units * 2;
        else if (units <= 300)
            bill = 200 + (units - 100) * 3;
        else {
            double amt = 200 + 600 + (units - 300) * 5;
            double surcharge = (amt * 2.5) / 100.0;
            bill = amt + surcharge;
        }
    }
    
    public void print() {
        System.out.println("Name of the customer\t\t: " + n);
        System.out.println("Number of units consumed\t: " + units);
        System.out.println("Bill amount\t\t\t: " + bill);
    }
    
    public static void main(String args[]) {
        ElectricBill obj = new ElectricBill();
        obj.accept();
        obj.calculate();
        obj.print();
    }
}
BlueJ output of ElectricBill.java
5Written · 2017 · Section B · 2017 PaperFull page

Write a program to accept a number and check and display whether it is a spy number or not. (A number is spy if the sum of its digits equals the product of its digits.)

Example: consider the number 1124.
Sum of the digits = 1 + 1 + 2 + 4 = 8
Product of the digits = 1 x 1 x 2 x 4 = 8

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSpyNumber
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter Number: ");
        int num = in.nextInt();
        
        int digit, sum = 0;
        int orgNum = num;
        int prod = 1;
        
        while (num > 0) {
            digit = num % 10;
            
            sum += digit;
            prod *= digit;
            num /= 10;
        }
        
        if (sum == prod)
            System.out.println(orgNum + " is Spy Number");
        else
            System.out.println(orgNum + " is not Spy Number");
        
    }
}
BlueJ output of KboatSpyNumber.java
6Written · 2017 · Section B · 2017 PaperFull page

Using switch statement, write a menu driven program for the following:

For an incorrect option, an appropriate error message should be displayed.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSeriesMenu
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Sum of the series");
        System.out.println("2. Display series");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();

        switch (choice) {
            case 1:
            int sum = 0;
            for (int i = 1; i <= 20; i++) {
                int x = 2;
                int term = (int)Math.pow(x, i);
                if (i % 2 == 0)
                    sum -= term;
                else
                    sum += term;
            }
            System.out.println("Sum=" + sum);
            break;
            
            case 2:
            int term = 1;
            for (int i = 1; i <= 5; i++) {
                System.out.print(term + " ");
                term = term * 10 + 1;
            }
            break;
            
            default:
            System.out.println("Incorrect Choice");
            break;
        }
    }
}
BlueJ output of KboatSeriesMenu.java BlueJ output of KboatSeriesMenu.java
7Written · 2017 · Section B · 2017 PaperFull page

Write a program to input integer elements into an array of size 20 and perform the following operations:

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSDAMinMaxSum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int arr[] = new int[20];
        System.out.println("Enter 20 numbers:");
        for (int i = 0; i < 20; i++) {
            arr[i] = in.nextInt();
        }
        int min = arr[0], max = arr[0], sum = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] < min)
                min = arr[i];
                
            if (arr[i] > max)
                max = arr[i];
                
            sum += arr[i];
        }
        
        System.out.println("Largest Number = " + max);
        System.out.println("Smallest Number = " + min);
        System.out.println("Sum = " + sum);
    }
}
BlueJ output of KboatSDAMinMaxSum.java
8Written · 2017 · Section B · 2017 PaperFull page

Design a class to overload a function check( ) as follows:

Show SolutionHide Solution↓
public class KboatOverload
{
    void check (String str , char ch ) {
        int count = 0;
        int len = str.length();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (ch == c) {
                count++;
            }
        }
        System.out.println("Frequency of " + ch + " = " + count);
    }
    
    void check(String s1) {
        String s2 = s1.toLowerCase();
        int len = s2.length();
        System.out.println("Vowels:");
        for (int i = 0; i < len; i++) {
            char ch = s2.charAt(i);
            if (ch == 'a' ||
                ch == 'e' ||
                ch == 'i' ||
                ch == 'o' ||
                ch == 'u')
                System.out.print(ch + " ");
        }
    }
}
BlueJ output of KboatOverload.java BlueJ output of KboatOverload.java
9Written · 2017 · Section B · 2017 PaperFull page

Write a program to input forty words in an array. Arrange these words in descending order of alphabets, using selection sort technique. Print the sorted array.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSelectionSort
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String a[] = new String[40];
        int n = a.length;
        
        System.out.println("Enter 40 Names: ");
        for (int i = 0; i < n; i++) {
            a[i] = in.nextLine();
        }
        
        for (int i = 0; i < n - 1; i++) {
            int idx = i;
            for (int j = i + 1; j < n; j++) {
                if (a[j].compareToIgnoreCase(a[idx]) < 0) {
                    idx = j;
                }
            }
            String t = a[idx];
            a[idx] = a[i];
            a[i] = t;
        }
        
        System.out.println("Sorted Names");
        for (int i = 0; i < n; i++) {
            System.out.println(a[i]);
        }
    }
}
BlueJ output of KboatSelectionSort.java
11 Mark · 2016 · Section A · 2016 PaperFull page

(a) Define Encapsulation.

Show SolutionHide Solution↓

Encapsulation is a mechanism that binds together code and the data it manipulates. It keeps them both safe from the outside world, preventing any unauthorised access or misuse. Only member methods, which are wrapped inside the class, can access the data and other methods.

(b) What are keywords ? Give an example.

Keywords are reserved words that have a special meaning to the Java compiler. Example: class, public, int, etc.

(c) Name any two library packages.

Two library packages are:

  1. java.io
  2. java.util

(d) Name the type of error ( syntax, runtime or logical error) in each case given below:

  1. Math.sqrt (36 – 45)
  2. int a;b;c;
  1. Runtime Error
  2. Syntax Error

(e) If int x[] = { 4, 3, 7, 8, 9, 10}; what are the values of p and q ?

  1. p = x.length
  2. q = x[2] + x[5] * x[1]
  1. 6
  2. q = x[2] + x[5] * x[1]
    q = 7 + 10 * 3
    q = 7 + 30
    q = 37
21 Mark · 2016 · Section A · 2016 PaperFull page

(a) State the difference between == operator and equals() method.

Show SolutionHide Solution↓
equals()==
It is a methodIt is a relational operator
It is used to check if the contents of two strings are same or notIt is used to check if two variables refer to the same object in memory
Example:
String s1 = new String("hello");
String s2 = new String("hello");
boolean res = s1.equals(s2);
System.out.println(res);
The output of this code snippet is true as contents of s1 and s2 are the same.
Example:
String s1 = new String("hello");
String s2 = new String("hello");
boolean res = s1 == s2;
System.out.println(res);
The output of this code snippet is false as s1 and s2 point to different String objects.

(b) What are the types of casting shown by the following examples:

  1. char c = (char) 120;
  2. int x = ‘t’;
  1. Explicit Cast.
  2. Implicit Cast.

(c) Differentiate between formal parameter and actual parameter.

Formal parameterActual parameter
Formal parameters appear in function definition.Actual parameters appear in function call statement.
They represent the values received by the called function.They represent the values passed to the called function.

(d) Write a function prototype of the following:
A function PosChar which takes a string argument and a character argument and returns an integer value.

int PosChar(String s, char ch)

(e) Name any two types of access specifiers.

  1. public
  2. private
31 Mark · 2016 · Section A · 2016 PaperFull page

(a) Give the output of the following string functions:

Show SolutionHide Solution↓
  1. 2 + 10 = 12
  2. ASCII Code of B - ASCII Code of D
    ⇒ 66 - 68
    ⇒ -2

(b) Give the output of the following Math functions:

  1. Math.ceil(4.2)
  2. Math.abs(-4)
  1. 5.0
  2. 4

(c) What is a parameterized constructor ?

A Parameterised constructor receives parameters at the time of creating an object and initializes the object with the received values.

(d) Write down java expression for:

$T = \sqrt{A^2 + B^2 + C^2}$

T = Math.sqrt(a*a + b*b + c*c)

(e) Rewrite the following using ternary operator:

if (x%2 == 0)
System.out.print("EVEN");
else
System.out.print("ODD");
System.out.print(x%2 == 0 ? "EVEN" : "ODD");

(f) Convert the following while loop to the corresponding for loop:

int m = 5, n = 10;
while (n>=1)
{
    System.out.println(m*n);
    n--;
}
int m = 5;
for (int n = 10; n >= 1; n--) {
    System.out.println(m*n);
}

(g) Write one difference between primitive data types and composite data types.

Primitive Data Types are built-in data types defined by Java language specification whereas Composite Data Types are defined by the programmer.

(h) Analyze the given program segment and answer the following questions:

  1. Write the output of the program segment.
  2. How many times does the body of the loop gets executed ?
for(int m = 5; m <= 20; m += 5)
{    if(m % 3 == 0)
        break;
    else
        if(m % 5 == 0)
            System.out.println(m);
    continue;
}
5
10

Loop executes 3 times.

Below dry run of the loop explains its working.

mOutputRemarks
551st Iteration
105
10
2nd Iteration
155
10
3rd Iteration — As m % 3 becomes true, break statement exists the loop.

(i) Give the output of the following expression:

a+= a++ + ++a + --a + a-- ; when a = 7

    a+= a++ + ++a + --a + a--
⇒ a = a + (a++ + ++a + --a + a--)
⇒ a = 7 + (7 + 9 + 8 + 8)
⇒ a = 7 + 32
⇒ a = 39

(j) Write the return type of the following library functions:

  1. isLetterOrDigit(char)
  2. replace(char, char)
  1. boolean
  2. String
4Written · 2016 · Section B · 2016 PaperFull page

Define a class named BookFair with the following description:

Instance variables/Data members:
String Bname — stores the name of the book
double price — stores the price of the book

Member methods:
(i) BookFair() — Default constructor to initialize data members
(ii) void Input() — To input and store the name and the price of the book.
(iii) void calculate() — To calculate the price after discount. Discount is calculated based on the following criteria.

PriceDiscount
Less than or equal to ₹10002% of price
More than ₹1000 and less than or equal to ₹300010% of price
More than ₹300015% of price

(iv) void display() — To display the name and price of the book after discount.

Write a main method to create an object of the class and call the above member methods.

Show SolutionHide Solution↓
import java.util.Scanner;

public class BookFair
{
    private String bname;
    private double price;
    
    public BookFair() {
        bname = "";
        price = 0.0;
    }
    
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter name of the book: ");
        bname = in.nextLine();
        System.out.print("Enter price of the book: ");
        price = in.nextDouble();
    }
    
    public void calculate() {
        double disc;
        if (price <= 1000)
            disc = price * 0.02;
        else if (price <= 3000)
            disc = price * 0.1;
        else
            disc = price * 0.15;
            
        price -= disc;
    }
    
    public void display() {
        System.out.println("Book Name: " + bname);
        System.out.println("Price after discount: " + price);
    }
    
    public static void main(String args[]) {
        BookFair obj = new BookFair();
        obj.input();
        obj.calculate();
        obj.display();
    }
}
BlueJ output of BookFair.java
5Written · 2016 · Section B · 2016 PaperFull page

Using the switch statement, write a menu driven program for the following:

(i) To print the Floyd’s triangle [Given below]

1
2   3
4   5   6
7   8   9  10
11 12 13 14 15

(b) To display the following pattern:
I
I C
I C S
I C S E

For an incorrect option, an appropriate error message should be displayed.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatPattern
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Type 1 for Floyd's triangle");
        System.out.println("Type 2 for an ICSE pattern");
        
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();
        
        switch (ch) {
            case 1:
            int a = 1;
            for (int i = 1; i <= 5; i++) {
                for (int j = 1; j <= i; j++) {
                    System.out.print(a++ + "\t");
                }
                System.out.println();
            }
            break;
            
            case 2:
            String s = "ICSE";
            for (int i = 0; i < s.length(); i++) {
                for (int j = 0; j <= i; j++) {
                    System.out.print(s.charAt(j) + " ");
                }
                System.out.println();
            }
            break;
            
            default:
            System.out.println("Incorrect Choice");
        }
    }
}
BlueJ output of KboatPattern.java BlueJ output of KboatPattern.java
6Written · 2016 · Section B · 2016 PaperFull page

Special words are those words which start and end with the same letter.
Example: EXISTENCE, COMIC, WINDOW
Palindrome words are those words which read the same from left to right and vice-versa.
Example: MALYALAM, MADAM, LEVEL, ROTATOR, CIVIC
All palindromes are special words but all special words are not palindromes.

Write a program to accept a word. Check and display whether the word is a palindrome or only a special word or none of them.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSpecialPalindrome
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String str = in.next();
        str = str.toUpperCase();
        int len = str.length();
        
        if (str.charAt(0) == str.charAt(len - 1)) {
            boolean isPalin = true;
            for (int i = 1; i < len / 2; i++) {
                if (str.charAt(i) != str.charAt(len - 1 - i)) {
                    isPalin = false;
                    break;
                }
            }
            
            if (isPalin) {
                System.out.println("Palindrome");
            }
            else {
                System.out.println("Special");
            }
        }
        else {
            System.out.println("Neither Special nor Palindrome");
        }
        
    }
}
BlueJ output of KboatSpecialPalindrome.java BlueJ output of KboatSpecialPalindrome.java BlueJ output of KboatSpecialPalindrome.java
7Written · 2016 · Section B · 2016 PaperFull page

Design a class to overload a function sumSeries() as follows:

(i) void sumSeries(int n, double x): with one integer argument and one double argument to find and display the sum of the series given below:

$s = \frac{x}{1} - \frac{x}{2} + \frac{x}{3} - \frac{x}{4} + \frac{x}{5} ...\space ...\space ...\space to \space n \space terms$

(ii) void sumSeries(): to find and display the sum of the following series:

$s = 1 + (1 \times 2) + (1 \times 2 \times 3) + ...\space ...\space ...\space + (1 \times 2 \times 3 \times 4 ...\space ...\space ...\space \times 20)$

Show SolutionHide Solution↓
public class KboatOverload
{
    void sumSeries(int n, double x) {
        double sum = 0;
        for (int i = 1; i <= n; i++) {
            double t = x / i;
            if (i % 2 == 0)
                sum -= t;
            else
                sum += t;
        }
        System.out.println("Sum = " + sum);
    }
    
    void sumSeries() {
        long sum = 0, term = 1;
        for (int i = 1; i <= 20; i++) {
            term *= i;
            sum += term;
        }
        System.out.println("Sum=" + sum);
    }
}
BlueJ output of KboatOverload.java BlueJ output of KboatOverload.java
8Written · 2016 · Section B · 2016 PaperFull page

Write a program to accept a number and check and display whether it is a Niven number or not.
(Niven number is that number which is divisible by its sum of digits.).

Example:
Consider the number 126. Sum of its digits is 1 + 2 + 6 = 9 and 126 is divisible by 9.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatNivenNumber
{
    public void checkNiven() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = in.nextInt();
        int orgNum = num;
        
        int digitSum = 0;
        
        while (num != 0) {
            int digit = num % 10;
            num /= 10;
            digitSum += digit;
        }
        
        /*
         * digitSum != 0 check prevents
         * division by zero error for the
         * case when users gives the number
         * 0 as input
         */
        if (digitSum != 0 && orgNum % digitSum == 0)
            System.out.println(orgNum + " is a Niven number");
        else
            System.out.println(orgNum + " is not a Niven number");
    }
}
BlueJ output of KboatNivenNumber.java
9Written · 2016 · Section B · 2016 PaperFull page

Write a program to initialize the seven Wonders of the World along with their locations in two different arrays. Search for a name of the country input by the user. If found, display the name of the country along with its Wonder, otherwise display "Sorry not found!".

Seven Wonders:
CHICHEN ITZA, CHRIST THE REDEEMER, TAJ MAHAL, GREAT WALL OF CHINA, MACHU PICCHU, PETRA, COLOSSEUM

Locations:
MEXICO, BRAZIL, INDIA, CHINA, PERU, JORDAN, ITALY

Examples:
Country name: INDIA
Output: TAJ MAHAL

Country name: USA
Output: Sorry Not found!

Show SolutionHide Solution↓
import java.util.Scanner;

public class Kboat7Wonders
{
    public static void main(String args[]) {
        
        String wonders[] = {"CHICHEN ITZA", "CHRIST THE REDEEMER", "TAJMAHAL", 
            "GREAT WALL OF CHINA", "MACHU PICCHU", "PETRA", "COLOSSEUM"};
        
        String locations[] = {"MEXICO", "BRAZIL", "INDIA", "CHINA", "PERU", "JORDAN",
        "ITALY"};
        
        Scanner in = new Scanner(System.in);
        System.out.print("Enter country: ");
        String c = in.nextLine();
        int i;
        
        for (i = 0; i < locations.length; i++) {
            if (locations[i].equals(c)) {
                System.out.println(locations[i] + " - " + wonders[i]);
                break;
            }
        }
        
        if (i == locations.length)
            System.out.println("Sorry Not Found!");
    }
}
BlueJ output of Kboat7Wonders.java BlueJ output of Kboat7Wonders.java
11 Mark · 2015 · Section A · 2015 PaperFull page

(a) What are the default values of the primitive data type int and float?

Show SolutionHide Solution↓

Default value of int is 0 and float is 0.0f.

(b) Name any two OOP’s principles.

  1. Encapsulation
  2. Inheritance

(c) What are identifiers ?

Identifiers are symbolic names given to different parts of a program such as variables, methods, classes, objects, etc.

(d) Identify the literals listed below:

(i) 0.5 (ii) 'A' (iii) false (iv) "a"

  1. Real Literal
  2. Character Literal
  3. Boolean Literal
  4. String Literal

(e) Name the wrapper classes of char type and boolean type.

Wrapper class of char type is Character and boolean type is Boolean.

21 Mark · 2015 · Section A · 2015 PaperFull page

(a) Evaluate the value of n if value of p = 5, q = 19

int n = (q – p) > (p – q) ? (q – p) : (p – q);

Show SolutionHide Solution↓

    int n = (q – p) > (p – q) ? (q – p) : (p – q)
⇒ int n = (19 - 5) > (5 - 19) ? (19 - 5) : (5 - 19)
⇒ int n = 14 > -14 ? 14 : -14
⇒ int n = 14 [∵ 14 > -14 is true so ? : returns 14]

Final value of n is 14

(b) Arrange the following primitive data types in an ascending order of their size:

(i) char (ii) byte (iii) double (iv) int

byte, char, int, double

(c) What is the value stored in variable res given below:

double res = Math.pow ("345".indexOf('5'), 3);

Value of res is 8.0
Index of '5' in "345" is 2. Math.pow(2, 3) means 23 which is equal to 8

(d) Name the two types of constructors

Parameterized constructors and Non-Parameterized constructors.

(e) What are the values of a and b after the following function is executed, if the values passed are 30 and 50:

void paws(int a, int b)
{
    a=a+b;
    b=a–b;
    a=a–b;
    System.out.println(a+ "," +b);
}

Value of a is 50 and b is 30.
Output of the code is:

50,30
31 Mark · 2015 · Section A · 2015 PaperFull page

(a) State the data type and value of y after the following is executed:

char x='7';
y=Character.isLetter(x);
Show SolutionHide Solution↓

Data type of y is boolean and value is false. Character.isLetter() method checks if its argument is a letter or not and as 7 is a number not a letter hence it returns false.

(b) What is the function of catch block in exception handling ? Where does it appear in a program ?

Catch block contains statements that we want to execute in case an exception is thrown in the try block. Catch block appears immediately after the try block in a program.

(c) State the output when the following program segment is executed:

String a ="Smartphone", b="Graphic Art";
String h=a.substring(2, 5);
String k=b.substring(8).toUpperCase();
System.out.println(h);
System.out.println(k.equalsIgnoreCase(h));

The output of the above code is:

art
true

a.substring(2, 5) extracts the characters of string a starting from index 2 till index 4. So h contains the string "art". b.substring(8) extracts characters of b from index 8 till the end so it returns "Art". toUpperCase() converts it into uppercase. Thus string "ART" gets assigned to k. Values of h and k are "art" and "ART", respectively. As both h and k differ in case only hence equalsIgnoreCase returns true.

(d) The access specifier that gives the most accessibility is ________ and the least accessibility is ________.

The access specifier that gives the most accessibility is public and the least accessibility is private.

(e) (i) Name the mathematical function which is used to find sine of an angle given in radians.
(ii) Name a string function which removes the blank spaces provided in the prefix and suffix of a string.

(i) Math.sin() (ii) trim()

(f) (i) What will this code print ?

int arr[]=new int[5];
System.out.println(arr);
  1. 0
  2. value stored in arr[0]
  3. 0000
  4. garbage value

This code will print garbage value

(ii) Name the keyword which is used- to resolve the conflict between method parameter and instance variables/fields.

this keyword

(g) State the package that contains the class:

  1. BufferedReader
  2. Scanner
  1. java.io
  2. java.util

(h) Write the output of the following program code:

char ch ;
int x=97;
do
{
    ch=(char)x;
    System.out.print(ch + " " );
    if(x%10 == 0)
    break;
    ++x;
} while(x<=100);

Answer
The output of the above code is:

a b c d

The below table shows the dry run of the program:

xchOutputRemarks
97aa1st Iteration
98ba b2nd Iteration
99ca b c3rd Iteration
100da b c d4th Iteration — As x%10 becomes true, break statement is executed and exists the loop.

(i) Write the Java expressions for:

$\frac{a^2+b^2}{2ab}$

(a * a + b * b) / (2 * a * b)

(j) If int y = 10 then find int z = (++y * (y++ + 5));

    z = (++y * (y++ + 5))
⇒ z = (11 * (11 + 5))
⇒ z = (11 * 16)
⇒ z = 176

4Written · 2015 · Section B · 2015 PaperFull page

Define a class called ParkingLot with the following description:

Instance variables/data members:
int vno — To store the vehicle number.
int hours — To store the number of hours the vehicle is parked in the parking lot.
double bill — To store the bill amount.

Member Methods:
void input() — To input and store the vno and hours.
void calculate() — To compute the parking charge at the rate of ₹3 for the first hour or part thereof, and ₹1.50 for each additional hour or part thereof.
void display() — To display the detail.

Write a main() method to create an object of the class and call the above methods.

Show SolutionHide Solution↓
import java.util.Scanner;

public class ParkingLot
{
    private int vno;
    private int hours;
    private double bill;
    
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter vehicle number: ");
        vno = in.nextInt();
        System.out.print("Enter hours: ");
        hours = in.nextInt();
    }
    
    public void calculate() {
        if (hours <= 1)
            bill = 3;
        else
            bill = 3 + (hours - 1) * 1.5;
    }
    
    public void display() {
        System.out.println("Vehicle number: " + vno);
        System.out.println("Hours: " + hours);
        System.out.println("Bill: " + bill);
    }
    
    public static void main(String args[]) {
        ParkingLot obj = new ParkingLot();
        obj.input();
        obj.calculate();
        obj.display();
    }
}
BlueJ output of ParkingLot.java
5Written · 2015 · Section B · 2015 PaperFull page

Write two separate programs to generate the following patterns using iteration (loop) statements:

(a)

*
*  #
*  #  *
*  #  *  #
*  #  *  #  *

(b)

5 4 3 2 1
5 4 3 2
5 4 3
5 4
5

Show SolutionHide Solution↓
public class KboatPattern
{
    public static void main(String args[]) {
        for (int i = 1; i <=5; i++) {
            for (int j = 1; j <= i; j++) {
                if (j % 2 == 0)
                    System.out.print("# ");
                else
                    System.out.print("* ");
            }
            System.out.println();
        }
    }
}
BlueJ output of KboatPattern.java
public class KboatPattern
{
    public static void main(String args[]) {
        for (int i = 1; i <=5; i++) {
            for (int j = 5; j >= i; j--) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}
BlueJ output of KboatPattern.java
6Written · 2015 · Section B · 2015 PaperFull page

Write a program to input and store roll numbers, names and marks in 3 subjects of n number of students in five single dimensional arrays and display the remark based on average marks as given below:

Average MarksRemark
85 — 100Excellent
75 — 84Distinction
60 — 74First Class
40 — 59Pass
Less than 40Poor
Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatAvgMarks
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number of students: ");
        int n = in.nextInt();
        
        int rollNo[] = new int[n];
        String name[] = new String[n];
        int s1[] = new int[n];
        int s2[] = new int[n];
        int s3[] = new int[n];
        double avg[] = new double[n];
        
        for (int i = 0; i < n; i++) {
            System.out.println("Enter student " + (i+1) + " details:");
            System.out.print("Roll No: ");
            rollNo[i] = in.nextInt();
            in.nextLine();
            System.out.print("Name: ");
            name[i] = in.nextLine();
            System.out.print("Subject 1 Marks: ");
            s1[i] = in.nextInt();
            System.out.print("Subject 2 Marks: ");
            s2[i] = in.nextInt();
            System.out.print("Subject 3 Marks: ");
            s3[i] = in.nextInt();
            avg[i] = (s1[i] + s2[i] + s3[i]) / 3.0;
        }
        
        System.out.println("Roll No\tName\tRemark");
        for (int i = 0; i < n; i++) {
            String remark;
            if (avg[i] < 40) 
                remark = "Poor";
            else if (avg[i] < 60)
                remark = "Pass";
            else if (avg[i] < 75)
                remark = "First Class";
            else if (avg[i] < 85)
                remark = "Distinction";
            else
                remark = "Excellent";
            System.out.println(rollNo[i] + "\t" 
                + name[i] + "\t" 
                + remark);
        }
    }
}
BlueJ output of KboatAvgMarks.java BlueJ output of KboatAvgMarks.java
7Written · 2015 · Section B · 2015 PaperFull page

Design a class to overload a function Joystring( ) as follows:

  1. void Joystring(String s, char ch1, char ch2) with one string argument and two character arguments that replaces the character argument ch1 with the character argument ch2 in the given String s and prints the new string.
    Example:
    Input value of s = "TECHNALAGY"
    ch1 = 'A'
    ch2 = 'O'
    Output: "TECHNOLOGY"
  2. void Joystring(String s) with one string argument that prints the position of the first space and the last space of the given String s.
    Example:
    Input value of s = "Cloud computing means Internet based computing"
    Output:
    First index: 5
    Last Index: 36
  3. void Joystring(String s1, String s2) with two string arguments that combines the two strings with a space between them and prints the resultant string.
    Example:
    Input value of s1 = "COMMON WEALTH"
    Input value of s2 = "GAMES"
    Output: COMMON WEALTH GAMES

(Use library functions)

Show SolutionHide Solution↓
public class KboatStringOverload
{
    public void joystring(String s, char ch1, char ch2) {
        String newStr = s.replace(ch1, ch2);
        System.out.println(newStr);
    }
    
    public void joystring(String s) {
        int f = s.indexOf(' ');
        int l = s.lastIndexOf(' ');
        System.out.println("First index:  " + f);
        System.out.println("Last index:  " + l);
    }
    
    public void joystring(String s1, String s2) {
        String newStr = s1.concat(" ").concat(s2);
        System.out.println(newStr);
    }
    
    public static void main(String args[]) {
        KboatStringOverload obj = new KboatStringOverload();
        obj.joystring("TECHNALAGY", 'A', 'O');
        obj.joystring("Cloud computing means Internet based computing");
        obj.joystring("COMMON WEALTH", "GAMES");
    }
}
BlueJ output of KboatStringOverload.java
8Written · 2015 · Section B · 2015 PaperFull page

Write a program to input twenty names in an array. Arrange these names in descending order of letters, using the bubble sort technique.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatArrangeNames
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String names[] = new String[20];
        System.out.println("Enter 20 names:");
        for (int i = 0;  i < names.length; i++) {
            names[i] = in.nextLine();
        }

        //Bubble Sort
        for (int i = 0; i < names.length - 1; i++) {
            for (int j = 0; j < names.length - 1 - i; j++) {
                if (names[j].compareToIgnoreCase(names[j + 1]) < 0) {
                    String temp = names[j + 1];
                    names[j + 1] = names[j];
                    names[j] = temp;
                }
            }
        }
        
        System.out.println("\nSorted Names");
        for (int i = 0;  i < names.length; i++) {
            System.out.println(names[i]);
        }
    }
}
BlueJ output of KboatArrangeNames.java
9Written · 2015 · Section B · 2015 PaperFull page

Using switch statement, write a menu driven program to:
(i) To find and display all the factors of a number input by the user ( including 1 and the excluding the number itself).
Example:
Sample Input : n = 15
Sample Output : 1, 3, 5

(ii) To find and display the factorial of a number input by the user (the factorial of a non-negative integer n, denoted by n!, is the product of all integers less than or equal to n.)
Example:
Sample Input : n = 5
Sample Output : 5! = 1*2*3*4*5 = 120

For an incorrect choice, an appropriate error message should be displayed.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatMenu
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Factors of number");
        System.out.println("2. Factorial of number");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        int num;

        switch (choice) {
            case 1:
            System.out.print("Enter number: ");
            num = in.nextInt();
            for (int i = 1; i < num; i++) {
                if (num % i == 0) {
                    System.out.print(i + " ");
                }
            }
            System.out.println();
            break;

            case 2:
            System.out.print("Enter number: ");
            num = in.nextInt();
            int f = 1;
            for (int i = 1; i <= num; i++)
                f *= i;
            System.out.println("Factorial = " + f);
            break;
            
            default:
            System.out.println("Incorrect Choice");
            break;
        }
    }
}
BlueJ output of KboatMenu.java BlueJ output of KboatMenu.java
11 Mark · 2014 · Section A · 2014 PaperFull page

(a) Which of the following are valid comments ?

Show SolutionHide Solution↓

The valid comments are:

Option 1 — /*comment*/
Option 3 — //comment

(b) What is meant by a package ? Name any two java Application Programming Interface packages.

A package is a named collection of Java classes that are grouped on the basis of their functionality. Two java Application Programming Interface packages are:

  1. java.util
  2. java.io

(c) Name the primitive data type in Java that is:

  1. a 64-bit integer and is used when you need a range of values wider than those provided by int.
  2. a single 16-bit Unicode character whose default value is '\u0000'.
  1. long
  2. char

(d) State one difference between the floating point literals float and double.

float literalsdouble literals
float literals have a size of 32 bits so they can store a fractional number with around 6-7 total digits of precision.double literals have a size of 64 bits so they can store a fractional number with 15-16 total digits of precision.

(e) Find the errors in the given program segment and re-write the statements correctly to assign values to an integer array.

int a = new int (5);
for (int i=0; i<=5; i++) a[i]=i;

Corrected Code:

int a[] = new int[5];
for (int i = 0; i < 5; i++)
    a[i] = i;
21 Mark · 2014 · Section A · 2014 PaperFull page

(a) Operators with higher precedence are evaluated before operators with relatively lower precedence. Arrange the operators given below in order of higher precedence to lower precedence:

Show SolutionHide Solution↓

++
%
>=
&&

(b) Identify the statements listed below as assignment, increment, method invocation or object creation statements.

  1. System.out.println("Java");
  2. costPrice = 457.50;
  3. Car hybrid = new Car();
  4. petrolPrice++;
  1. Method Invocation
  2. Assignment
  3. Object Creation
  4. Increment

(c) Give two differences between the switch statement and the if-else statement

switchif-else
switch can only test if the expression is equal to any of its case constantsif-else can test for any boolean expression like less than, greater than, equal to, not equal to, etc.
It is a multiple branching flow of control statementIt is a bi-directional flow of control statement

(d) What is an infinite loop? Write an infinite loop statement.

A loop which continues iterating indefinitely and never stops is termed as infinite loop. Below is an example of infinite loop:

for (;;)
    System.out.println("Infinite Loop");

(e) What is constructor? When is it invoked?

A constructor is a member method that is written with the same name as the class name and is used to initialize the data members or instance variables. A constructor does not have a return type. It is invoked at the time of creating any object of the class.

31 Mark · 2014 · Section A · 2014 PaperFull page

(a) List the variables from those given below that are composite data types:

Show SolutionHide Solution↓

The composite data types are:

  • arr[i]=10;
  • obj.display();
  • String str;

(b) State the output of the following program segment:

String str1 = "great"; String str2 = "minds";
System.out.println(str1.substring(0,2).concat(str2.substring(1)));
System.out.println(("WH" + (str1.substring(2).toUpperCase())));

The output of the above code is:

grinds
WHEAT

Explanation:

  1. str1.substring(0,2) returns "gr". str2.substring(1) returns "inds". Due to concat both are joined together to give the output as "grinds".
  2. str1.substring(2) returns "eat". It is converted to uppercase and joined to "WH" to give the output as "WHEAT".

(c) What are the final values stored in variable x and y below?

double a = -6.35;
double b = 14.74;
double x = Math.abs(Math.ceil(a));
double y = Math.rint(Math.max(a,b)); 

The final value stored in variable x is 6.0 and y is 15.0.

Explanation:

  1. Math.ceil(a) gives -6.0 and Math.abs(-6.0) is 6.0.
  2. Math.max(a,b) gives 14.74 and Math.rint(14.74) gives 15.0.

(d) Rewrite the following program segment using if-else statements instead of the ternary operator:

String grade = (marks>=90)?"A": (marks>=80)? "B": "C";

String grade;
if (marks >= 90)
    grade = "A";
else if (marks >= 80)
    grade = "B";
else
    grade = "C";

(e) Give the output of the following method:

public static void main (String [] args){
int a = 5;
a++;
System.out.println(a);
a -= (a--) - (--a);
System.out.println(a);} 
6
4
  1. a++ increments value of a by 1 so a becomes 6.
  2. a -= (a--) - (--a)
    ⇒ a = a - ((a--) - (--a))
    ⇒ a = 6 - (6 - 4)
    ⇒ a = 6 - 2
    ⇒ a = 4

(f) What is the data type returned by the library functions :

  1. compareTo()
  2. equals()
  1. int
  2. boolean

(g) State the value of characteristic and mantissa when the following code is executed:

String s = "4.3756";
int n = s.indexOf('.');
int characteristic=Integer.parseInt(s.substring(0,n));
int mantissa=Integer.valueOf(s.substring(n+1));

The value of characteristic is 4 and mantissa is 3756.

Index of . in String s is 1 so variable n is initialized to 1. s.substring(0,n) gives 4. Integer.parseInt() converts string "4" into integer 4 and this 4 is assigned to the variable characteristic.

s.substring(n+1) gives 3756 i.e. the string starting at index 2 till the end of s. Integer.valueOf() converts string "3756" into integer 3756 and this value is assigned to the variable mantissa.

(h) Study the method and answer the given questions.

public void sampleMethod()
{   for (int i=0; i < 3; i++)
    {   for (int j = 0; j<2; j++)
        {int number = (int)(Math.random() * 10);
        System.out.println(number); }}}
  1. How many times does the loop execute?
  2. What is the range of possible values stored in the variable number?
  1. The loops execute 6 times.
  2. The range is from 0 to 9.

(i) Consider the following class:

public class myClass {
public static int x=3, y=4;
public int a=2, b=3;}
  1. Name the variables for which each object of the class will have its own distinct copy.
  2. Name the variables that are common to all objects of the class.
  1. a, b
  2. x, y

(j) What will be the output when the following code segments are executed?

(i)

String s = "1001";
int x = Integer.valueOf(s);
double y = Double.valueOf(s);
System.out.println("x="+x);
System.out.println("y="+y);

(ii)

System.out.println("The king said \"Begin at the beginning!\" to me.");

(i) The output of the code is:

x=1001
y=1001.0

(ii) The output of the code is:

The king said "Begin at the beginning!" to me.
4Written · 2014 · Section B · 2014 PaperFull page

Define a class named movieMagic with the following description:

Data MembersPurpose
int yearTo store the year of release of a movie
String titleTo store the title of the movie
float ratingTo store the popularity rating of the movie
(minimum rating=0.0 and maximum rating=5.0)
Member MethodsPurpose
movieMagic()Default constructor to initialize numeric data members to 0 and String data member to "".
void accept()To input and store year, title and rating
void display()To display the title of the movie and a message based on the rating as per the table given below
RatingMessage to be displayed
0.0 to 2.0Flop
2.1 to 3.4Semi-Hit
3.5 to 4.4Hit
4.5 to 5.0Super-Hit

Write a main method to create an object of the class and call the above member methods.

Show SolutionHide Solution↓
import java.util.Scanner;

public class movieMagic
{
    private int year;
    private String title;
    private float rating;
    
    public movieMagic() {
        year = 0;
        title = "";
        rating = 0.0f;
    }
    
    public void accept() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Title of Movie: ");
        title = in.nextLine();
        System.out.print("Enter Year of Movie: ");
        year = in.nextInt();
        System.out.print("Enter Rating of Movie: ");
        rating = in.nextFloat();
    }
    
    public void display() {
        String message = "Invalid Rating";
        if (rating <= 2.0f)
            message = "Flop";
        else if (rating <= 3.4f)
            message = "Semi-Hit";
        else if (rating <= 4.4f)
            message = "Hit";
        else if (rating <= 5.0f)
            message = "Super-Hit";
            
        System.out.println(title);
        System.out.println(message);
    }
    
    public static void main(String args[]) {
        movieMagic obj = new movieMagic();
        obj.accept();
        obj.display();
    }
}
BlueJ output of movieMagic.java
5Written · 2014 · Section B · 2014 PaperFull page

A special two-digit number is such that when the sum of its digits is added to the product of its digits, the result is equal to the original two-digit number.

Example: Consider the number 59.
Sum of digits = 5 + 9 = 14
Product of digits = 5 * 9 = 45
Sum of the sum of digits and product of digits = 14 + 45 = 59

Write a program to accept a two-digit number. Add the sum of its digits to the product of its digits. If the value is equal to the number input, then display the message "Special two—digit number" otherwise, display the message "Not a special two-digit number".

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSpecialNumber
{
    public void checkNumber() {
        
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter a 2 digit number: ");
        int orgNum = in.nextInt();
        
        int num = orgNum;
        int count = 0, digitSum = 0, digitProduct = 1;
        
        while (num != 0) {
            int digit = num % 10;
            num /= 10;
            digitSum += digit;
            digitProduct *= digit;
            count++;
        }
        
        if (count != 2)
            System.out.println("Invalid input, please enter a 2-digit number");
        else if ((digitSum + digitProduct) == orgNum)
            System.out.println("Special 2-digit number");
        else
            System.out.println("Not a special 2-digit number");
            
    }
}
BlueJ output of KboatSpecialNumber.java
6Written · 2014 · Section B · 2014 PaperFull page

Write a program to assign a full path and file name as given below. Using library functions, extract and output the file path, file name and file extension separately as shown.

Input
C:\Users\admin\Pictures\flower.jpg

Output
Path: C:\Users\admin\Pictures\
File name: flower
Extension: jpg

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatFilepathSplit
{
    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter full path: ");
        String filepath = in.next();
        
        char pathSep = '\\';
        char dotSep = '.';

        int pathSepIdx = filepath.lastIndexOf(pathSep);
        System.out.println("Path:\t\t" + filepath.substring(0, pathSepIdx));

        int dotIdx = filepath.lastIndexOf(dotSep);
        System.out.println("File Name:\t" + filepath.substring(pathSepIdx + 1, dotIdx));
        
        System.out.println("Extension:\t" + filepath.substring(dotIdx + 1));
    }
}
BlueJ output of KboatFilepathSplit.java
7Written · 2014 · Section B · 2014 PaperFull page

Design a class to overload a function area( ) as follows:

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatOverload
{
    double area(double a, double b, double c) {
        double s = (a + b + c) / 2;
        double x = s * (s-a) * (s-b) * (s-c);
        double result = Math.sqrt(x);
        return result;
    }
    
    double area (int a, int b, int height) {
        double result = (1.0 / 2.0) * height * (a + b);
        return result;
    }
    
    double area (double diagonal1, double diagonal2) {
        double result = 1.0 / 2.0 * diagonal1 * diagonal2;
        return result;
    }
}
8Written · 2014 · Section B · 2014 PaperFull page

Using the switch statement, write a menu driven program to calculate the maturity amount of a Bank Deposit.
The user is given the following options:

For option 1, accept principal (P), rate of interest(r) and time period in years(n). Calculate and output the maturity amount(A) receivable using the formula:

A = P[1 + r / 100]n

For option 2, accept Monthly Installment (P), rate of interest (r) and time period in months (n). Calculate and output the maturity amount (A) receivable using the formula:

A = P x n + P x (n(n+1) / 2) x r / 100 x 1 / 12

For an incorrect option, an appropriate error message should be displayed.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatBankDeposit
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Type 1 for Term Deposit");
        System.out.println("Type 2 for Recurring Deposit");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();
        double p = 0.0, r = 0.0, a = 0.0;
        int n = 0;
        
        switch (ch) {
            case 1:
            System.out.print("Enter Principal: ");
            p = in.nextDouble();
            System.out.print("Enter Interest Rate: ");
            r = in.nextDouble();
            System.out.print("Enter time in years: ");
            n = in.nextInt();
            a = p * Math.pow(1 + r / 100, n);
            System.out.println("Maturity amount = " + a);
            break;
            
            case 2:
            System.out.print("Enter Monthly Installment: ");
            p = in.nextDouble();
            System.out.print("Enter Interest Rate: ");
            r = in.nextDouble();
            System.out.print("Enter time in months: ");
            n = in.nextInt();
            a = p * n + p * ((n * (n + 1)) / 2) * (r / 100) * (1 / 12.0);
            System.out.println("Maturity amount = " + a);
            break;
            
            default:
            System.out.println("Invalid choice");
        }
    }
}
BlueJ output of KboatBankDeposit.java BlueJ output of KboatBankDeposit.java BlueJ output of KboatBankDeposit.java
99 Marks · 2014 · Section B · 2014 PaperFull page

Write a program to accept the year of graduation from school as an integer value from the user. Using the binary search technique on the sorted array of integers given below, output the message "Record exists" if the value input is located in the array. If not, output the message "Record does not exist".
Sample Input:

n[0]nnnnnnnnn
1982198719931996199920032006200720092010
Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatGraduationYear
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int n[] = {1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010};
        
        System.out.print("Enter graduation year to search: ");
        int year = in.nextInt();
        
        int l = 0, h = n.length - 1, idx = -1;
        while (l <= h) {
            int m = (l + h) / 2;
            if (n[m] == year) {
                idx = m;
                break;
            }
            else if (n[m] < year) {
                l = m + 1;
            }
            else {
                h = m - 1;
            }
        }
        
        if (idx == -1)
            System.out.println("Record does not exist");
        else
            System.out.println("Record exists");
    }
}
BlueJ output of KboatGraduationYear.java
11 Mark · 2013 · Section A · 2013 PaperFull page

(a) What is meant by precedence of operators?

Show SolutionHide Solution↓

Precedence of operators refers to the order in which the operators are applied to the operands in an expression.

(b) What is a literal?

Literals are data items that are fixed data values. Java provides different types of literals like:

  1. Integer Literals
  2. Floating-Point Literals
  3. Boolean Literals
  4. Character Literals
  5. String Literals
  6. null Literal

(c) State the Java concept that is implemented through:

  1. a superclass and a subclass.
  2. the act of representing essential features without including background details.
  1. Inheritance
  2. Abstraction

(d) Give a difference between a constructor and a method.

Constructor has the same name as class name whereas function should have a different name than class name.

(e) What are the types of casting shown by the following examples?

  1. double x = 15.2;
    int y = (int) x;

  2. int x = 12;
    long y = x;

  1. Explicit Type Casting
  2. Implicit Type Casting
21 Mark · 2013 · Section A · 2013 PaperFull page

(a) Name any two wrapper classes.

Show SolutionHide Solution↓

Two wrapper classes are:

  1. Integer
  2. Character

(b) What is the difference between a break statement and a continue statement when they occur in a loop?

When the break statement gets executed, it terminates its loop completely and control reaches to the statement immediately following the loop. The continue statement terminates only the current iteration of the loop by skipping rest of the statements in the body of the loop.

(c) Write statements to show how finding the length of a character array char[] differs from finding the length of a String object str.

Java code snippet to find length of character array:

char ch[] = {'x', 'y', 'z'};
int len = ch.length

Java code snippet to find length of String object str:

String str = "Test";
int len = str.length();

(d) Name the Java keyword that:

  1. indicates that a method has no return type.
  2. stores the address of the currently-calling object.
  1. void
  2. this

(e) What is an exception?

An exception is an abnormal condition that arises in a code sequence at run time. Exceptions indicate to a calling method that an abnormal condition has occurred.

31 Mark · 2013 · Section A · 2013 PaperFull page

(a) Write a Java statement to create an object mp4 of class Digital.

Show SolutionHide Solution↓
Digital MP4 = new Digital();

(b) State the values stored in the variables str1 and str2:

String s1 = "good";
String s2 = "world matters";
String str1 = s2.substring(5).replace('t', 'n');
String str2 = s1.concat(str1);

Value stored in str1 is " manners" and str2 is "good manners". (Note that str1 begins with a space.)

s2.substring(5) gives a substring from index 5 till the end of the string which is " matters". The replace method replaces all 't' in " matters" with 'n' giving " manners". s1.concat(str1) joins together "good" and " manners" so "good manners" is stored in str2.

(c) What does a class encapsulate?

A class encapsulates data and behavior.

(d) Rewrite the following program segment using the if..else statement:

comm = (sale > 15000)? sale * 5 / 100 : 0;
if(sale > 15000)
    comm = sale * 5 / 100;
else
    comm = 0;

(e) How many times will the following loop execute? What value will be returned?

int x = 2, y = 50;
do{
    ++x;
    y -= x++;
}while(x <= 10);
return y;

The loop will run 5 times and the value returned is 15.

(f) What is the data type that the following library functions return?

  1. isWhitespace(char ch)
  2. Math.random()
  1. boolean
  2. double

(g) Write a Java expression for:

$ut + \frac{1}{2}ft^2$

u * t + 1 / 2.0 * f * t * t

(h) If int n[] = {1, 2, 3, 5, 7, 9, 13, 16}, what are the values of x and y?

      x = Math.pow(n[4], n[2]);
      y = Math.sqrt(n[5] + n[7]);

    x = Math.pow(n[4], n[2]);
⇒ x = Math.pow(7, 3);
⇒ x = 343.0;

    y = Math.sqrt(n[5] + n[7]);
⇒ y = Math.sqrt(9 + 16);
⇒ y = Math.sqrt(25);
⇒ y = 5.0;

(i) What is the final value of ctr when the iteration process given below, executes?

int ctr = 0;
for(int i = 1; i <= 5; i++)
    for(int j = 1; j <= 5; j += 2)
        ++ctr;

The final value of ctr is 15.

The outer loop executes 5 times. For each iteration of outer loop, the inner loop executes 3 times. So the statement ++ctr; is executed a total of 5 x 3 = 15 times.

(j) Name the method of Scanner class that:

  1. is used to input an integer data from the standard input stream.
  2. is used to input a String data from the standard input stream.
  1. nextInt()
  2. nextLine()
4Written · 2013 · Section B · 2013 PaperFull page

Define a class named FruitJuice with the following description:

Data MembersPurpose
int product_codestores the product code number
String flavourstores the flavour of the juice (e.g., orange, apple, etc.)
String pack_typestores the type of packaging (e.g., tera-pack, PET bottle, etc.)
int pack_sizestores package size (e.g., 200 mL, 400 mL, etc.)
int product_pricestores the price of the product
Member MethodsPurpose
FruitJuice()constructor to initialize integer data members to 0 and string data members to ""
void input()to input and store the product code, flavour, pack type, pack size and product price
void discount()to reduce the product price by 10
void display()to display the product code, flavour, pack type, pack size and product price
Show SolutionHide Solution↓
import java.util.Scanner;

public class FruitJuice
{
    private int product_code;
    private String flavour;
    private String pack_type;
    private int pack_size;
    private int product_price;
    
    public FruitJuice() {
        product_code = 0;
        flavour = "";
        pack_type = "";
        pack_size = 0;
        product_price = 0;
    }
    
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Flavour: ");
        flavour = in.nextLine();
        System.out.print("Enter Pack Type: ");
        pack_type = in.nextLine();
        System.out.print("Enter Product Code: ");
        product_code = in.nextInt();
        System.out.print("Enter Pack Size: ");
        pack_size = in.nextInt();
        System.out.print("Enter Product Price: ");
        product_price = in.nextInt();
    }
    
    public void discount() {
        product_price -= 10;
    }
    
    public void display() {
        System.out.println("Product Code: " + product_code);
        System.out.println("Flavour: " + flavour);
        System.out.println("Pack Type: " + pack_type);
        System.out.println("Pack Size: " + pack_size);
        System.out.println("Product Price: " + product_price);
    }
    
    public static void main(String args[]) {
        FruitJuice obj = new FruitJuice();
        obj.input();
        obj.discount();
        obj.display();
    }
}
BlueJ output of FruitJuice.java
5Written · 2013 · Section B · 2013 PaperFull page

The International Standard Book Number (ISBN) is a unique numeric book identifier which is printed on every book. The ISBN is based upon a 10-digit code.

The ISBN is legal if:
1 × digit1 + 2 × digit2 + 3 × digit3 + 4 × digit4 + 5 × digit5 + 6 × digit6 + 7 × digit7 + 8 × digit8 + 9 × digit9 + 10 × digit10 is divisible by 11.

Example:
For an ISBN 1401601499
Sum = 1 × 1 + 2 × 4 + 3 × 0 + 4 × 1 + 5 × 6 + 6 × 0 + 7 × 1 + 8 × 4 + 9 × 9 + 10 × 9 = 253 which is divisible by 11.

Write a program to:

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatISBNCheck
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the ISBN: ");
        long isbn = in.nextLong();
        
        int sum = 0, count = 0, m = 10;
        while (isbn != 0) {
            int d = (int)(isbn % 10);
            count++;
            sum += d * m;
            m--;
            isbn /= 10;
        }
        
        if (count != 10) {
            System.out.println("Illegal ISBN");
        }
        else if (sum % 11 == 0) {
            System.out.println("Legal ISBN");
        }
        else {
            System.out.println("Illegal ISBN");
        }
    }
}
BlueJ output of KboatISBNCheck.java BlueJ output of KboatISBNCheck.java
6Written · 2013 · Section B · 2013 PaperFull page

Write a program that encodes a word into Piglatin. To translate word into Piglatin word, convert the word into uppercase and then place the first vowel of the original word as the start of the new word along with the remaining alphabets. The alphabets present before the vowel being shifted towards the end followed by "AY".

Sample Input 1: London
Output: ONDONLAY

Sample Input 2: Olympics
Output: OLYMPICSAY

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatPigLatin
{
    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);
        System.out.print("Enter word: ");
        String word = in.next();
        int len = word.length();

        word=word.toUpperCase();
        String piglatin="";
        int flag=0;
        
        for(int i = 0; i < len; i++)
        {
            char x = word.charAt(i);
            if(x=='A' || x=='E' || x=='I' || x=='O' || x=='U')
            {
                piglatin=word.substring(i) + word.substring(0,i) + "AY";
                flag=1;
                break;
            }
        }
        
        if(flag == 0)
        {
            piglatin = word + "AY";
        }
        System.out.println(word + " in Piglatin format is " + piglatin);
    }
}
BlueJ output of KboatPigLatin.java BlueJ output of KboatPigLatin.java
7Written · 2013 · Section B · 2013 PaperFull page

Write a program to input 10 integer elements in an array and sort them in descending order using bubble sort technique.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatBubbleSortDsc
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int n = 10;
        int arr[] = new int[n];
        
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        
        //Bubble Sort
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] < arr[j + 1]) {
                    int t = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = t;
                }
            } 
        }
        
        System.out.println("Sorted Array:");
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
BlueJ output of KboatBubbleSortDsc.java
8Written · 2013 · Section B · 2013 PaperFull page

Design a class to overload a function series( ) as follows:

Show SolutionHide Solution↓
public class KboatSeries
{
    double series(double n) {
        double sum = 0;
        for (int i = 1; i <= n; i++) {
            double term = 1.0 / i;
            sum += term;
        }
        return sum;
    }
    
    double series(double a, double n) {
        double sum = 0;
        int x = 1;
        for (int i = 1; i <= n; i++) {
            int e = x + 1;
            double term = x / Math.pow(a, e);
            sum += term;
            x += 3;
        }
        return sum;
    }
    
    public static void main(String args[]) {
        KboatSeries obj = new KboatSeries();
        System.out.println("First series sum = " + obj.series(5));
        System.out.println("Second series sum = " + obj.series(3, 8));
    }
}
BlueJ output of KboatSeries.java
9Written · 2013 · Section B · 2013 PaperFull page

Using the switch statement, write a menu driven program:

For an incorrect choice, an appropriate error message should be displayed.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Type 1 for Composite Number");
        System.out.println("Type 2 for Smallest Digit");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();
        
        switch (ch) {
            case 1:
            System.out.print("Enter Number: ");
            int n = in.nextInt();
            int c = 0;
            for (int i = 1; i <= n; i++) {
                if (n % i == 0)
                    c++;
            }
            
            if (c > 2)
                System.out.println("Composite Number");
            else
                System.out.println("Not a Composite Number");
            break;
            
            case 2:
            System.out.print("Enter Number: ");
            int num = in.nextInt();
            int s = 10;
            while (num != 0) {
                int d = num % 10;
                if (d < s)
                    s = d;
                num /= 10;
            }
            System.out.println("Smallest digit is " + s);
            break;
            
            default:
            System.out.println("Wrong choice");
        }
    }
}
BlueJ output of KboatNumber.java BlueJ output of KboatNumber.java
11 Mark · 2012 · Section A · 2012 PaperFull page

(a) Give one example each of a primitive data type and a composite data type.

Show SolutionHide Solution↓
  1. int
  2. array

(b) Give one point of difference between unary and binary operators.

unary operators operate on a single operand whereas binary operators operate on two operands.

(c) Differentiate between call by value or pass by value and call by reference or pass by reference.

Call by valueCall by reference
Values of actual parameters are copied to formal parameters.Reference of actual parameters is passed to formal parameters.
Changes made to formal parameters are not reflected back to actual parameters.Changes made to formal parameters are reflected back to actual parameters.

(d) Write a Java expression for:

$\sqrt{2as + u^2}$

Math.sqrt(2 * a * s + u * u)

(e) Name the type of error (syntax, runtime or logical error) in each case given below:

  1. Division by a variable that contains a value of zero.
  2. Multiplication operator used when the operation should be division.
  3. Missing semicolon.
  1. Runtime error
  2. Logical error
  3. syntax error
21 Mark · 2012 · Section A · 2012 PaperFull page

(a) Create a class with one integer instance variable. Initialize the variable using:

Show SolutionHide Solution↓
class Number {
    int a;

    public Number() {
        a = 0;
    }

    public Number(int x) {
        a = x;
    }
}

(b) Complete the code below to create an object of Scanner class:

    Scanner sc = ____ Scanner(__________);

Scanner sc = new Scanner(System.in);

(c) What is an array? Write a statement to declare an integer array of 10 elements.

An array is a structure to store a number of values of the same data type in contiguous memory locations. The following statement declares an integer array of 10 elements:

int arr[] = new int[10];

(d) Name the search or sort algorithm that:

  1. Makes several passes through the array, selecting the next smallest item in the array each time and placing it where it belongs in the array.
  2. At each stage, compares the sought key value with the key value of the middle element of the array.
  1. Selection Sort
  2. Binary Search

(e) Differentiate between public and private modifiers for members of a class.

public modifier makes the class members accessible both within and outside their class whereas private modifier makes the class members accessible only within the class in which they are declared.

31 Mark · 2012 · Section A · 2012 PaperFull page

(a) What are the values of x and y when the following statements are executed?

int a = 63, b = 36;
boolean x = (a > b)? true : false;
int y = (a < b)? a : b;
Show SolutionHide Solution↓
x = true
y = 36

The ternary operator (a > b)? true : false returns true as its condition a > b is true so it returns its first expression that is true.

The ternary operator (a < b)? a : b returns b as its condition a < b is false so it returns its second expression that is b. Value of b is 36 so y also becomes 36.

(b) State the values of n and ch.

char c = 'A';
int n = c + 1;
char ch = (char)n;

Value of n is 66 and ch is B.

int n = c + 1, here due to implicit conversion, 'A' will be converted to its ASCII value 65. 1 is added to it making the value of n 66.

char ch = (char)n, here through explicit conversion 66 is converted to its corresponding character that is 'B' so value of ch becomes B.

(c) What will be the result stored in x after evaluating the following expression?

int x = 4;
x += (x++) + (++x) + x;

    x += (x++) + (++x) + x
⇒ x = x + ((x++) + (++x) + x)
⇒ x = 4 + (4 + 6 + 6)
⇒ x = 4 + 16
⇒ x = 20

(d) Give output of the following program segment:

double x = 2.9, y = 2.5;
System.out.println(Math.min(Math.floor(x), y));
System.out.println(Math.max(Math.ceil(x), y));
2.0
3.0

Math.floor(2.9) gives 2.0. Math.min(2.0, 2.5) gives 2.0.

Math.ceil(2.9) gives 3.0. Math.max(3.0, 2.5) gives 3.0.

(e) State the output of the following program segment:

String s = "Examination";
int n = s.length();
System.out.println(s.startsWith(s.substring(5, n)));
System.out.println(s.charAt(2) == s.charAt(6));
false
true

Putting the value of n in s.substring(5, n), it becomes s.substring(5, 11). This gives "nation". As s does not start with "nation" so s.startsWith(s.substring(5, n)) returns false.

s.charAt(2) is a and s.charAt(6) is also a so both are equal

(f) State the method that:

  1. Converts a string to a primitive float data type.
  2. Determines if the specified character is an uppercase character.
  1. Float.parseFloat()
  2. Character.isUpperCase()

(g) State the data type and values of a and b after the following segment is executed:

String s1 = "Computer", s2 = "Applications"
a = (s1.compareTo(s2));
b = (s1.equals(s2));

Data type of a is int and value is 2. Data type of b is boolean and value is false.

(h) What will the following code output:

String s = "malayalam";
System.out.println(s.indexOf('m'));
System.out.println(s.lastIndexOf('m'));
0
8

The first m appears at index 0 and the last m appears at index 8.

(i) Rewrite the following program segment using while instead of for statement.

int f = 1, i;
for(i = 1; i <= 5; i++){
    f *= i;
    System.out.println(f);
}
int f = 1, i;
while (i <= 5) {
    f *= i;
    System.out.println(f);
    i++;
}

(j) In the program given below, state the name and the value of the:

  1. method argument or argument variable
  2. class variable
  3. local variable
  4. instance variable
class MyClass{
    static int x = 7;
    int y = 2;
    public static void main(String args[]){
        MyClass obj = new MyClass();
        System.out.println(x);
        obj.sampleMethod(5);
        int a = 6;
        System.out.println(a);
    }
    void sampleMethod(int n){
        System.out.println(n);
        System.out.println(y);
    }
}
  1. Method argument/Argument variable is n
  2. Class variable is x
  3. Local variable is a
  4. Instance variable is y
4Written · 2012 · Section B · 2012 PaperFull page

Define a class called Library with the following description:

Instance Variables/Data Members:
int accNum — stores the accession number of the book.
String title — stores the title of the book.
String author — stores the name of the author.

Member methods:

Accession Number    Title   Author

Write a main method to create an object of the class and call the above member methods.

Show SolutionHide Solution↓
import java.util.Scanner;

public class Library
{
    private int accNum;
    private String title;
    private String author;
    
    void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter book title: ");
        title = in.nextLine();
        System.out.print("Enter author: ");
        author = in.nextLine();
        System.out.print("Enter accession number: ");
        accNum = in.nextInt();
    }
    
    void compute() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number of days late: ");
        int days = in.nextInt();
        int fine = days * 2;
        System.out.println("Fine = Rs." + fine);
    }
    
    void display() {
        System.out.println("Accession Number\tTitle\tAuthor");
        System.out.println(accNum + "\t\t" + title + "\t" + author);
    }
    
    public static void main(String args[]) {
        Library obj = new Library();
        obj.input();
        obj.display();
        obj.compute();
    }
}
BlueJ output of Library.java
5Written · 2012 · Section B · 2012 PaperFull page

Given below is a hypothetical table showing rates of income tax for male citizens below the age of 65 years:

Taxable income (TI) in ₹Income Tax in ₹
Does not exceed Rs. 1,60,000Nil
Is greater than Rs. 1,60,000 and less than or equal to Rs. 5,00,000.(TI - 1,60,000) x 10%
Is greater than Rs. 5,00,000 and less than or equal to Rs. 8,00,000[(TI - 5,00,000) x 20%] + 34,000
Is greater than Rs. 8,00,000[(TI - 8,00,000) x 30%] + 94,000

Write a program to input the age, gender (male or female) and Taxable Income of a person.

If the age is more than 65 years or the gender is female, display “wrong category”. If the age is less than or equal to 65 years and the gender is male, compute and display the income tax payable as per the table given above.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatIncomeTax
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Gender(male/female): ");
        String gender = in.nextLine();
        System.out.print("Enter Age: ");
        int age = in.nextInt();
        System.out.print("Enter Taxable Income: ");
        double ti = in.nextDouble();
        double tax = 0.0;

        if (age > 65 || gender.equalsIgnoreCase("female")) {
            System.out.print("Wrong Category");
        }
        else {
            if (ti <= 160000)
                tax = 0;
            else if (ti <= 500000)
                tax = (ti - 160000) * 10 / 100;
            else if (ti <= 800000)
                tax = 34000 + ((ti - 500000) * 20 / 100);
            else
                tax = 94000 + ((ti - 800000) * 30 / 100);
                
            System.out.println("Tax Payable: " + tax);
        }      
    }
}
BlueJ output of KboatIncomeTax.java BlueJ output of KboatIncomeTax.java
6Written · 2012 · Section B · 2012 PaperFull page

Write a program to accept a string. Convert the string into upper case letters. Count and output the number of double letter sequences that exist in the string.
Sample Input: "SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE"
Sample Output: 4

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatLetterSeq
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter string: ");
        String s = in.nextLine();
        String str = s.toUpperCase();
        int count = 0;
        int len = str.length();
        
        for (int i = 0; i < len - 1; i++) {
            if (str.charAt(i) == str.charAt(i + 1))
                count++;
        }
        
        System.out.println("Double Letter Sequence Count = " + count);
        
    }
}
BlueJ output of KboatLetterSeq.java
7Written · 2012 · Section B · 2012 PaperFull page

Design a class to overload a function polygon() as follows:

  1. void polygon(int n, char ch) — with one integer and one character type argument to draw a filled square of side n using the character stored in ch.
  2. void polygon(int x, int y) — with two integer arguments that draws a filled rectangle of length x and breadth y, using the symbol '@'.
  3. void polygon() — with no argument that draws a filled triangle shown below:

Example:

Show SolutionHide Solution↓
public class KboatPolygon
{
    public void polygon(int n, char ch) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                System.out.print(ch);
            }
            System.out.println();
        }
    }
    
    public void polygon(int x, int y) {
        for (int i = 1; i <= x; i++) {
            for (int j = 1; j <= y; j++) {
                System.out.print('@');
            }
            System.out.println();
        }
    }
    
    public void polygon() {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print('*');
            }
            System.out.println();
        }
    }
    
    public static void main(String args[]) {
        KboatPolygon obj = new KboatPolygon();
        obj.polygon(2, 'o');
        System.out.println();
        obj.polygon(2, 5);
        System.out.println();
        obj.polygon();
    }
}
BlueJ output of KboatPolygon.java
8Written · 2012 · Section B · 2012 PaperFull page

Using a switch statement, write a menu driven program to:
(a) Generate and display the first 10 terms of the Fibonacci series
0, 1, 1, 2, 3, 5
The first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two.
(b) Find the sum of the digits of an integer that is input.
Sample Input: 15390
Sample Output: Sum of the digits = 18
For an incorrect choice, an appropriate error message should be displayed.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatFibonacciNDigitSum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Fibonacci Series");
        System.out.println("2. Sum of digits");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();

        switch (ch) {
            case 1:
            int a = 0, b = 1;
            System.out.print(a + " " + b);
            for (int i = 3; i <= 10; i++) {
                int term = a + b;
                System.out.print(" " + term);
                a = b;
                b = term;
            }
            break;

            case 2:
            System.out.print("Enter number: ");
            int num = in.nextInt();
            int sum = 0;
            while (num != 0) {
                sum += num % 10;
                num /= 10;
            }
            System.out.println("Sum of Digits " + " = " + sum);
            break;

            default:
            System.out.println("Incorrect choice");
            break;
        }
    }
}
BlueJ output of KboatFibonacciNDigitSum.java BlueJ output of KboatFibonacciNDigitSum.java
9Written · 2012 · Section B · 2012 PaperFull page

Write a program to accept the names of 10 cities in a single dimensional string array and their STD (Subscribers Trunk Dialling) codes in another single dimension integer array. Search for the name of a city input by the user in the list. If found, display "Search Successful" and print the name of the city along with its STD code, or else display the message "Search unsuccessful, no such city in the list".

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatStdCodes
{
    public static void main(String args[]) {
        final int SIZE = 10;
        Scanner in = new Scanner(System.in);
        String cities[] = new String[SIZE];
        String stdCodes[] = new String[SIZE];
        System.out.println("Enter " + SIZE + 
                 " cities and their STD codes:");
        
        for (int i = 0;  i < SIZE; i++) {
            System.out.print("Enter City Name: ");
            cities[i] = in.nextLine();
            System.out.print("Enter its STD Code: ");
            stdCodes[i] = in.nextLine();
        }
        
        System.out.print("Enter name of city to search: ");
        String city = in.nextLine();
        
        int idx;
        for (idx = 0;  idx < SIZE; idx++) {
            if (city.compareToIgnoreCase(cities[idx]) == 0) {
                break;
            }
        }
        
        if (idx < SIZE) {
            System.out.println("Search Successful");
            System.out.println("City: " + cities[idx]);
            System.out.println("STD Code: " + stdCodes[idx]);
        }
        else {
            System.out.println("Search Unsuccessful");
        }
    }
}
BlueJ output of KboatStdCodes.java
11 Mark · 2011 · Section A · 2011 PaperFull page

(a) What is the difference between an object and a class?

Show SolutionHide Solution↓

A class is a blue print that represents a set of objects that share common characteristics and behaviour whereas an object is a specific instance of a class having a specific identity, specific characteristics and specific behaviour.

(b) What does the token 'keyword' refer to in the context of Java? Give an example for keyword.

Keywords are reserved words that have a special meaning for the Java compiler. Java compiler reserves these words for its own use so Keywords cannot be used as identifiers. An example of keyword is class.

(c) State the difference between entry controlled loop and exit controlled loop.

Entry controlled loopExit controlled loop
It checks the condition at the time of entry. Only if the condition is true, the program control enters the body of the loop.It checks the condition after executing its body. If the condition is true, loop will perform the next iteration otherwise program control will move out of the loop.
Loop does not execute at all if the condition is false.The loop executes at least once even if the condition is false.
Example: for and while loopsExample: do-while loop

(d) What are the two ways of invoking functions?

Two ways of invoking functions are:

  1. Pass by value.
  2. Pass by reference.

(e) What is the difference between / and % operators?

/%
Division operatorModulus operator
Returns the quotient of division operationReturns the remainder of division operation
Example: int a = 5 / 2; Here a will get the value of 2 which is the quotient of this division operationExample: int b = 5 % 2; Here b will get the value of 1 which is the remainder of this division operation
21 Mark · 2011 · Section A · 2011 PaperFull page

(a) State the total size in bytes, of the arrays a[4] of char data type and p[4] of float data type.

Show SolutionHide Solution↓

Size of char a[4] is 4 × 2 = 8 Bytes.
Size of float p[4] is 4 × 4 = 16 Bytes.

(b) (i) Name the package that contains Scanner class.
     (ii) Which unit of the class gets called, when the object of the class is created?

(i) java.util
(ii) Constructor

(c) Give the output of the following:

String n = "Computer Knowledge";
String m = "Computer Applications";
System.out.println(n.substring(0, 8).concat(m.substring(9)));
System.out.println(n.endsWith("e"));
ComputerApplications
true

n.substring(0,8) returns the substring of n starting at index 0 till 7 (i.e. 8 - 1 = 7) which is "Computer". m.substring(9) returns the substring of m starting at index 9 till the end of the string which is "Applications". concat() method joins "Computer" and "Applications" together to give the output as ComputerApplications.

(d) Write the output of the following:

  1. System.out.println(Character.isUpperCase('R'));
  2. System.out.println(Character.toUpperCase('j'));
  1. true
  2. J

(e) What is the role of keyword void in declaring functions?

The keyword 'void' signifies that the function doesn't return a value to the calling function.

31 Mark · 2011 · Section A · 2011 PaperFull page

(a) Analyze the following program segment and determine how many times the loop will be executed and what will be the output of the program segment?

int p = 200;
while(true){
    if(p < 100)
        break;
    p = p - 20;
}
System.out.println(p);
Show SolutionHide Solution↓
80

The loop executes 7 times

pRemarks
2001st Iteration
1802nd Iteration
1603rd Iteration
1404th Iteration
1205th Iteration
1006th Iteration.
807th Iteration. Now p < 100 becomes true so break statement is executed terminating the loop.

(b) What will be the output of the following code?

(i)

int k = 5, j = 9;
k += k++ - ++j + k;
System.out.println("k = " + k);
System.out.println("j = " + j);

(ii)

double b = -15.6;
double a = Math.rint(Math.abs(b));
System.out.println("a = " + a);

(i)

k = 6
j = 10

    k += k++ - ++j + k
⇒ k = 5 + (5 - 10 + 6)
⇒ k = 5 + 1
⇒ k = 6

++j increments j to 10

(ii)

16.0

Math.abs(-15.6) gives 15.6. Math.rint(15.6) gives 16.0.

(c) Explain the concept of constructor overloading with an example.

Constructor overloading is a technique in Java through which a class can have more than one constructor with different parameter lists. The different constructors of the class are differentiated by the compiler using the number of parameters in the list and their types. For example, the Rectangle class below has two constructors:

class Rectangle {
    int length;
    int breadth;

    //Constructor 1
    public Rectangle() {
        length = 0;
        breadth = 0;
    }

    //Constructor 2
    public Rectangle(int l, int b) {
        length = l;
        breadth = b;
    }

    public static void main(String[] args) {
        //Constructor 1 called
        Rectangle obj1 = new Rectangle();

        //Constructor 2 called
        Rectangle obj2 = new Rectangle(10, 15);
    }
}

(d) Give the prototype of a function search which receives a sentence 'sent' and word 'w' and returns 1 or 0.

int search(String sent, String w)

(e) Write an expression in Java for:

$z = \frac{5x^3 + 2y}{x + y}$

z = (5 * x * x * x + 2 * y) / (x + y)

(f) Write a statement each to perform the following tasks on a string:

  1. Find and display the position of the last space in a string s.
  2. Convert a number stored in a string variable x to double data type.
  1. System.out.println(s.lastIndexOf(" "));
  2. double num = Double.parseDouble(x);

(g) Name the keyword that:

  1. informs that an error has occurred in an input/output operation.
  2. distinguishes between instance variable and class variable.
  1. throws IOException
  2. static

(h) What are library classes? Give an example.

Java Library classes are a set of predefined classes in the form of packages that are provided to the programmer as part of Java installation. Library classes simplify the job of programmers by providing built-in methods for common and non-trivial tasks like taking input from user, displaying output to user, etc. For example, System class in java.lang package of Java Library classes provides the print() and println() methods for displaying output to user.

(i) Write one difference between Linear Search and Binary Search.

Linear search works on unsorted as well as sorted arrays whereas Binary search works on only sorted arrays.

4Written · 2011 · Section B · 2011 PaperFull page

Define a class called 'Mobike' with the following specifications:

Data MembersPurpose
int bnoTo store the bike number
int phnoTo store the phone number of the customer
String nameTo store the name of the customer
int daysTo store the number of days the bike is taken on rent
int chargeTo calculate and store the rental charge
Member MethodsPurpose
void input()To input and store the details of the customer
void compute()To compute the rental charge
void display()To display the details in the given format

The rent for a mobike is charged on the following basis:

DaysCharge
For first five days₹500 per day
For next five days₹400 per day
Rest of the days₹200 per day

Output:

Bike No.    Phone No.   Name    No. of days     Charge       
xxxxxxx     xxxxxxxx    xxxx        xxx         xxxxxx       
Show SolutionHide Solution↓
import java.util.Scanner;

public class Mobike
{
    private int bno;
    private int phno;
    private int days;
    private int charge;
    private String name;
    
    public void input() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Customer Name: ");
        name = in.nextLine();
        System.out.print("Enter Customer Phone Number: ");
        phno = in.nextInt();
        System.out.print("Enter Bike Number: ");
        bno = in.nextInt();
        System.out.print("Enter Number of Days: ");
        days = in.nextInt();
    }
    
    public void compute() {
        if (days <= 5)
            charge = days * 500;
        else if (days <= 10)
            charge = (5 * 500) + ((days - 5) * 400);
        else
            charge = (5 * 500) + (5 * 400) + ((days - 10) * 200);
    }
    
    public void display() {
        System.out.println("Bike No.\tPhone No.\tName\tNo. of days \tCharge");
        System.out.println(bno + "\t" + phno + "\t" + name + "\t" + days 
            + "\t" + charge);
    }
    
    public static void main(String args[]) {
        Mobike obj = new Mobike();
        obj.input();
        obj.compute();
        obj.display();
    }
}
BlueJ output of Mobike.java
5Written · 2011 · Section B · 2011 PaperFull page

Write a program to input and sort the weight of ten people. Sort and display them in descending order using the selection sort technique.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSelectionSort
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        double weightArr[] = new double[10];
        System.out.println("Enter weights of 10 people: ");
        for (int i = 0; i < 10; i++) {
            weightArr[i] = in.nextDouble();
        }
        
        for (int i = 0; i < 9; i++) {
            int idx = i;
            for (int j = i + 1; j < 10; j++) {
                if (weightArr[j] > weightArr[idx])
                    idx = j;
            }
            
            double t = weightArr[i];
            weightArr[i] = weightArr[idx];
            weightArr[idx] = t; 
        }
        
        System.out.println("Sorted Weights Array:");
        for (int i = 0; i < 10; i++) {
            System.out.print(weightArr[i] + " ");
        }
    }
}
BlueJ output of KboatSelectionSort.java
6Written · 2011 · Section B · 2011 PaperFull page

Write a program to input a number and print whether the number is a special number or not.

(A number is said to be a special number, if the sum of the factorial of the digits of the number is same as the original number).

Example:
145 is a special number, because 1! + 4! + 5! = 1 + 24 + 120 = 145.
(Where ! stands for factorial of the number and the factorial value of a number is the product of all integers from 1 to that number, example 5! = 1 * 2 * 3 * 4 * 5 = 120)

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSpecialNum
{
    public static int fact(int y) {
        int f = 1;
        for (int i = 1; i <= y; i++) {
            f *= i;
        }
        return f;
    }

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = in.nextInt();

        int t = num;
        int sum = 0;
        while (t != 0) {
            int d = t % 10;
            sum += fact(d);
            t /= 10;
        }

        if (sum == num)
            System.out.println(num + " is a special number");
        else
            System.out.println(num + " is not a special number");

    }
}
BlueJ output of KboatSpecialNum.java
7Written · 2011 · Section B · 2011 PaperFull page

Write a program to accept a word and convert it into lower case, if it is in upper case. Display the new word by replacing only the vowels with the letter following it.
Sample Input: computer
Sample Output: cpmpvtfr

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatVowelReplace
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a word: ");
        String str = in.nextLine();
        str = str.toLowerCase();
        String newStr = "";
        int len = str.length();

        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);

            if (str.charAt(i) == 'a' ||
            str.charAt(i) == 'e' ||
            str.charAt(i) == 'i' ||
            str.charAt(i) == 'o' ||
            str.charAt(i) == 'u') {

                char nextChar = (char)(ch + 1);
                newStr = newStr +  nextChar; 

            }
            else {
                newStr = newStr + ch;
            }
        }

        System.out.println(newStr);
    }
}
BlueJ output of KboatVowelReplace.java
8Written · 2011 · Section B · 2011 PaperFull page

Design a class to overload a function compare( ) as follows:

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatCompare
{
    public void compare(int a, int b) {
        
        if (a > b) {
            System.out.println(a);
        }
        else {
            System.out.println(b);
        }
        
    }
    
    public void compare(char a, char b) {
        int x = (int)a;
        int y = (int)b;
        
        if (x > y) {
            System.out.println(a);
        }
        else {
            System.out.println(b);
        }
        
    }
    
    public void compare(String a, String b) {
        
        int l1 = a.length();
        int l2 = b.length();
        
        if (l1 > l2) {
            System.out.println(a);
        }
        else {
            System.out.println(b);
        }

    }
    
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        KboatCompare obj = new KboatCompare();
        
        System.out.print("Enter first integer: ");
        int n1 = in.nextInt();
        System.out.print("Enter second integer: ");
        int n2 = in.nextInt();
        obj.compare(n1, n2);
        
        System.out.print("Enter first character: ");
        char c1 = in.next().charAt(0);
        System.out.print("Enter second character: ");
        char c2 = in.next().charAt(0);
        in.nextLine();
        obj.compare(c1, c2);
        
        System.out.print("Enter first string: ");
        String s1 = in.nextLine();
        System.out.print("Enter second string: ");
        String s2 = in.nextLine();
        obj.compare(s1, s2);
    }
}
BlueJ output of KboatCompare.java
9Written · 2011 · Section B · 2011 PaperFull page

Write a menu driven program to perform the following tasks by using Switch case statement:

(a) To print the series:
0, 3, 8, 15, 24, ............ to n terms. (value of 'n' is to be an input by the user)

(b) To find the sum of the series:
S = (1/2) + (3/4) + (5/6) + (7/8) + ........... + (19/20)

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatSeriesMenu
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Type 1 to print series");
        System.out.println("0, 3, 8, 15, 24,....to n terms");
        System.out.println();
        System.out.println("Type 2 to find sum of series");
        System.out.println("(1/2) + (3/4) + (5/6) + (7/8) +....+ (19/20)");
        System.out.println();
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();

        switch (choice) {
            case 1:
                System.out.print("Enter n: ");
                int n = in.nextInt();
                for (int i = 1; i <= n; i++)
                    System.out.print(((i * i) - 1) + " ");
                System.out.println();
                break;
                
            case 2:
                double sum = 0;
                for (int i = 1; i <= 19; i = i + 2)
                    sum += i / (double)(i + 1);
                System.out.println("Sum = " + sum);
                break;
                
            default:
                System.out.println("Incorrect Choice");
                break;
        }
    }
}
BlueJ output of KboatSeriesMenu.java BlueJ output of KboatSeriesMenu.java
11 Mark · 2010 · Section A · 2010 PaperFull page

(a) Define the term Bytecode.

Show SolutionHide Solution↓

Java compiler converts Java source code into an intermediate binary code called Bytecode. Bytecode can't be executed directly on the processor. It needs to be converted into Machine Code first.

(b) What do you understand by type conversion? How is implicit conversion different from explicit conversion?

The process of converting one predefined type into another is called type conversion. In an implicit conversion, the result of a mixed mode expression is obtained in the higher most data type of the variables without any intervention by the user. For example:

int a = 10;
float b = 25.5f, c;
c = a + b;

In case of explicit type conversion, the data gets converted to a type as specified by the programmer. For example:

int a = 10;
double b = 25.5;
float c = (float)(a + b);

(c) Name two jump statements and their use.

break statement, it is used to jump out of a switch statement or a loop. continue statement, it is used to skip the current iteration of the loop and start the next iteration.

(d) What is Exception? Name two exception handling blocks.

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Two exception handling blocks are try and catch.

(e) Write two advantages of using functions in a program.

  1. Methods help to manage the complexity of the program by dividing a bigger complex task into smaller, easily understood tasks.
  2. Methods help with code reusability.
21 Mark · 2010 · Section A · 2010 PaperFull page

(a) State the purpose and return data type of the following String functions:

Show SolutionHide Solution↓
  1. indexOf() returns the index within the string of the first occurrence of the specified character or -1 if the character is not present. Its return type is int.
  2. compareTo() compares two strings lexicographically. Its return type is int.

(b) What is the result stored in x, after evaluating the following expression?

int x = 5;
x = x++ * 2 + 3 * --x;

    x = x++ * 2 + 3 * --x
⇒ x = 5 * 2 + 3 * 5
⇒ x = 10 + 15
⇒ x = 25

(c) Differentiate between static and non-static data members.

Static Data MembersNon-Static Data Members
They are declared using keyword 'static'.They are declared without using keyword 'static'.
All objects of a class share the same copy of Static data members.Each object of the class gets its own copy of Non-Static data members.
They can be accessed using the class name or object.They can be accessed only through an object of the class.

(d) Write the difference between length and length().

lengthlength()
length is an attribute i.e. a data member of array.length() is a member method of String class.
It gives the length of an array i.e. the number of elements stored in an array.It gives the number of characters present in a string.

(e) Differentiate between private and protected visibility modifiers.

Private members are only accessible inside the class in which they are defined and they cannot be inherited by derived classes. Protected members are also only accessible inside the class in which they are defined but they can be inherited by derived classes.

31 Mark · 2010 · Section A · 2010 PaperFull page

(a) What do you understand by the term data abstraction? Explain with an example.

Show SolutionHide Solution↓

Data Abstraction refers to the act of representing essential features without including the background details or explanations. A Switchboard is an example of Data Abstraction. It hides all the details of the circuitry and current flow and provides a very simple way to switch ON or OFF electrical appliances.

(b)(i) What will be the output of the following code?

int m = 2;
int n = 15;
for(int i = 1; i < 5; i++);
m++;
--n;
System.out.println("m = " + m);
System.out.println("n = " + n);
m=6
n=14

As there are no curly braces after the for loop so only the statement m++; is inside the loop. Loop executes 4 times so m becomes 6. The next statement --n; is outside the loop so it is executed only once and n becomes 14.

(b)(ii) What will be the output of the following code?

char x = 'A';
int m;
m = (x == 'a')? 'A' : 'a';
System.out.println("m = " + m);
m = 97

The condition x == 'a' is false as X has the value of 'A'. So, the ternary operator returns 'a' that is assigned to m. But m is an int variable not a char variable. So, through implicit conversion Java converts 'a' to its numeric ASCII value 97 and that gets assigned to m.

(c) Analyze the following program segment and determine how many times the loop will be executed and what will be the output of the program segment.

int k = 1, i = 2;
while(++i < 6)
    k *= i;
System.out.println(k);
60

This table shows the change in values of i and k as while loop iterates:

ikRemarks
21Initial values
331st Iteration
4122nd Iteration
5603rd Iteration
660Once i becomes 6, condition is false and loop stops iterating.

Notice that System.out.println(k); is not inside while loop. As there are no curly braces so only the statement k *= i; is inside the loop. The statement System.out.println(k); is outside the while loop, it is executed once and prints value of k which is 60 to the console.

(d) Give the prototype of a function check which receives a character ch and an integer n and returns true or false.

boolean check(char ch, int n)

(e) State two features of a constructor.

  1. A constructor has the same name as that of the class.
  2. A constructor has no return type, not even void.

(f) Write a statement each to perform the following task on a string:

  1. Extract the second-last character of a word stored in the variable wd.
  2. Check if the second character of a string str is in uppercase.
  1. char ch = wd.charAt(wd.length() - 2);
  2. boolean res = Character.isUpperCase(str.charAt(1));

(g) What will the following function return when executed?

  1. Math.max(-17, -19)
  2. Math.ceil(7.8)
  1. -17
  2. 8.0

(h)(i) Why is an object called an instance of a class?

A class can create objects of itself with different characteristics and common behaviour. So, we can say that an Object represents a specific state of the class. For these reasons, an Object is called an Instance of a Class.

(h)(ii) What is the use of the keyword import?

import keyword is used to import built-in and user-defined packages into our Java program.

4Written · 2010 · Section B · 2010 PaperFull page

Write a program to perform binary search on a list of integers given below, to search for an element input by the user. If it is found display the element along with its position, otherwise display the message "Search element not found".

5, 7, 9, 11, 15, 20, 30, 45, 89, 97

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatBinarySearch
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        int arr[] = {5, 7, 9, 11, 15, 20, 30, 45, 89, 97};
        
        System.out.print("Enter number to search: ");
        int n = in.nextInt();
        
        int l = 0, h = arr.length - 1, index = -1;
        while (l <= h) {
            int m = (l + h) / 2;
            if (arr[m] < n)
                l = m + 1;
            else if (arr[m] > n)
                h = m - 1;
            else {
                index = m;
                break;
            }
                
        }
        
        if (index == -1) {
            System.out.println("Search element not found");
        }
        else {
            System.out.println(n + " found at position " + index);
        }
    }
}
BlueJ output of KboatBinarySearch.java BlueJ output of KboatBinarySearch.java
5Written · 2010 · Section B · 2010 PaperFull page

Define a class Student as given below:

Data members/instance variables:
name, age, m1, m2, m3 (marks in 3 subjects), maximum, average

Member methods:

Write a main method to create an object of a class and call the above member methods.

Show SolutionHide Solution↓
import java.util.Scanner;

public class Student
{
    private String name;
    private int age;
    private int m1;
    private int m2;
    private int m3;
    private int maximum;
    private double average;

    public Student(String n, int a, int s1, 
    int s2, int s3) {
        name = n;
        age = a;
        m1 = s1;
        m2 = s2;
        m3 = s3;
    }

    public Student() {
        name = "";
        age = 0;
        m1 = 0;
        m2 = 0;
        m3 = 0;
        maximum = 0;
        average = 0;
    }

    public void accept() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter name: ");
        name = in.nextLine();
        System.out.print("Enter age: ");
        age = in.nextInt();
        System.out.print("Enter Subject 1 Marks: ");
        m1 = in.nextInt();
        System.out.print("Enter Subject 2 Marks: ");
        m2 = in.nextInt();
        System.out.print("Enter Subject 3 Marks: ");
        m3 = in.nextInt();
    }

    public void compute() {
        if (m1 > m2 && m1 > m3)
            maximum = m1;
        else if (m2 > m1 && m2 > m3)
            maximum = m2;
        else
            maximum = m3;

        average = (m1 + m2 + m3) / 3.0;
    }

    public void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Subject 1 Marks: " + m1);
        System.out.println("Subject 2 Marks: " + m2);
        System.out.println("Subject 3 Marks: " + m3);
        System.out.println("Maximum Marks: " + maximum);
        System.out.println("Average Marks: " + average);
    }

    public static void main(String args[]) {
        Student obj = new Student();
        obj.accept();
        obj.compute();
        obj.display();
    }
}
BlueJ output of Student.java
6Written · 2010 · Section B · 2010 PaperFull page

Shasha Travels Pvt. Ltd. gives the following discount to its customers:

Ticket AmountDiscount
Above Rs. 7000018%
Rs. 55001 to Rs. 7000016%
Rs. 35001 to Rs. 5500012%
Rs. 25001 to Rs. 3500010%
Less than Rs. 250012%

Write a program to input the name and ticket amount for the customer and calculate the discount amount and net amount to be paid. Display the output in the following format for each customer:

Sl. No.     Name    Ticket Charges     Discount      Net Amount

(Assume that there are 15 customers, first customer is given the serial no (SI. No.) 1, next customer 2 …….. and so on)

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatShashaTravels
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String names[] = new String[15];
        int amounts[] = new int[15];

        for (int i = 0; i < 15; i++) {
            System.out.print("Enter " + "Customer " + (i+1) + " Name: ");
            names[i] = in.nextLine();
            System.out.print("Enter " + "Customer " + (i+1) + " Ticket Charges: ");
            amounts[i] = in.nextInt();
            in.nextLine();
        }

        System.out.println("Sl. No.\tName\t\tTicket Charges\tDiscount\t\tNet Amount");

        for (int i = 0; i < 15; i++) {
            int dp = 0;
            int amt = amounts[i];
            if (amt > 70000)
                dp = 18;
            else if (amt >= 55001)
                dp = 16;
            else if (amt >= 35001)
                dp = 12;
            else if (amt >= 25001)
                dp = 10;
            else
                dp = 2;

            double disc = amt * dp / 100.0;
            double net = amt - disc;

            System.out.println((i+1) + "\t" + names[i] 
                + "\t" + amounts[i] + "\t\t" 
                + disc + "\t\t" + net);
        }
    }
}
BlueJ output of KboatShashaTravels.java
7Written · 2010 · Section B · 2010 PaperFull page

Write a menu driven program to accept a number from the user and check whether it is a Prime number or an Automorphic number.

(a) Prime number: (A number is said to be prime, if it is only divisible by 1 and itself)

Example: 3,5,7,11

(b) Automorphic number: (Automorphic number is the number which is contained in the last digit(s) of its square.)

Example: 25 is an Automorphic number as its square is 625 and 25 is present as the last two digits.

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatPrimeAutomorphic
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("1. Prime number");
        System.out.println("2. Automorphic number");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        System.out.print("Enter number: ");
        int num = in.nextInt();

        switch (choice) {
            case 1:
            int c = 0;
            for (int i = 1; i <= num; i++) {
                if (num % i == 0) {
                    c++;
                }
            }
            if (c == 2) 
                System.out.println(num + " is Prime");
            else
                System.out.println(num + " is not Prime");
            break;

            case 2:
            int numCopy = num;
            int sq = num * num;
            int d = 0;

            /*
             * Count the number of 
             * digits in num
             */
            while(num > 0) {
                d++;
                num /= 10;
            }

            /*
             * Extract the last d digits
             * from square of num
             */
            int ld = (int)(sq % Math.pow(10, d));

            if (ld == numCopy)
                System.out.println(numCopy + " is automorphic");
            else
                System.out.println(numCopy + " is not automorphic");
            break;

            default:
            System.out.println("Incorrect Choice");
            break;
        }
    }
}
BlueJ output of KboatPrimeAutomorphic.java BlueJ output of KboatPrimeAutomorphic.java
8Written · 2010 · Section B · 2010 PaperFull page

Write a program to store 6 elements in an array P and 4 elements in an array Q. Now, produce a third array R, containing all the elements of array P and Q. Display the resultant array.

InputInputOutput
P[ ]Q[ ]R[ ]
4194
6236
171
282
3 3
10 10
  19
  23
  7
  8
Show SolutionHide Solution↓
import java.util.Scanner;

public class Kboat3Arrays
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        
        int P[] = new int[6];
        int Q[] = new int[4];
        int R[] = new int[10];
        int i = 0;
        
        System.out.println("Enter 6 elements of array P:");
        for (i = 0; i < P.length; i++) {
            P[i] = in.nextInt();
        }
        
        System.out.println("Enter 4 elements of array Q:");
        for (i = 0; i < Q.length; i++) {
            Q[i] = in.nextInt();
        }
        
        i = 0;
        while(i < P.length) {
            R[i] = P[i];
            i++;
        }
        
        int j = 0;
        while(j < Q.length) {
            R[i++] = Q[j++];
        }
        
        System.out.println("Elements of Array R:");
        for (i = 0; i < R.length; i++) {
            System.out.print(R[i] + " ");
        }
    }
}
BlueJ output of Kboat3Arrays.java
9Written · 2010 · Section B · 2010 PaperFull page

Write a program to input a sentence. Count and display the frequency of each letter of the sentence in alphabetical order.
Sample Input: COMPUTER APPLICATIONS
Sample Output:

CharacterFrequencyCharacterFrequency
A2O2
C2P3
I1R1
L2S1
M1T2
N1U1
Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatLetterFreq
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String str = in.nextLine();
        str = str.toUpperCase();
        int freqMap[] = new int[26];
        int len = str.length();
        
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
            if (Character.isLetter(ch)) {
                int chIdx = ch - 65;
                freqMap[chIdx]++;
            }
        }
        
        System.out.println("Character\tFrequency");
        for (int i = 0; i < freqMap.length; i++) {
            if (freqMap[i] > 0) {
                System.out.println((char)(i + 65) 
                            + "\t\t" + freqMap[i]);
            }
        }
    }
}
BlueJ output of KboatLetterFreq.java

Use ↑ ↓ to move between questions. Press ↓ once to reveal a solution.

Free sample bank