Revising Basic Java Concepts

ICSE Class 10 Computer Applications · Sumita Arora Computer Applications · 91 solved questions

Exercise
1Objective Type Questions

Java uses ............... character set.

Show SolutionHide Solution↓

Java uses Unicode character set.

2Objective Type Questions

Smallest individual unit in a program is called ............... .

Show SolutionHide Solution↓

Smallest individual unit in a program is called token.

3Objective Type Questions

Which of the following is not a token ?

Show SolutionHide Solution↓

statement

Reason — Smallest individual unit in a program is called a token and a statement is composed of many tokens like keywords, identifiers, operators, constants etc.

4Objective Type Questions

Identify the illegal identifier from the following.

Show SolutionHide Solution↓

20_to_50

Reason — An identifier must not begin with a digit. It may contain underscore.

5Objective Type Questions

Which of the following does not represent a character literal ?

Show SolutionHide Solution↓

"a"

Reason — Since a is enclosed in double quotes (" "), it becomes a String literal. Character literals are always enclosed within single quotes (' ').

6Objective Type Questions

Which keyword turns a variable declaration into constant declaration ?

Show SolutionHide Solution↓

final

Reason — Keyword final creates a named constant.

7Objective Type Questions

ch += 2 is equivalent to

Show SolutionHide Solution↓

ch = ch + 2

Reason — += is a shorthand operator. The operator pair += tells the compiler to assign to ch the value of ch + 2.

8Objective Type Questions

The Math class is part of which Java library package.

Show SolutionHide Solution↓

java.lang

Reason — The Math class is part of java.lang package.

9Objective Type Questions

Which clause is optional in a switch statement?

Show SolutionHide Solution↓

default

Reason — The default clause is optional and, if it is missing, no action takes place if all matches fail.

10Objective Type Questions

Absence of which statement causes a fall-through in a switch statement.

Show SolutionHide Solution↓

break

Reason — In the absence of break statement, the control flows to the next case below the matching case leading to fall-through.

11Objective Type Questions

By default, the if-part and else-part of an if statement can contain these many statements in it.

Show SolutionHide Solution↓

1

Reason — By default, the if-part and else-part can contain only one statement. To include more than one statements, the set of statements need to be enclosed in curly braces and included as one compound statement.

12Objective Type Questions

Which of the following loops is mostly used for fixed number of iterations ?

Show SolutionHide Solution↓

for

Reason — for loop is usually used when the number of iterations are fixed.

13Objective Type Questions

Which of the following is not an entry controlled loop ?

Show SolutionHide Solution↓

do-while

Reason — do-while is an exit controlled loop as it executes atleast once even when the condition is false.

14Objective Type Questions

Which of the following is an exit controlled loop?

Show SolutionHide Solution↓

do-while

Reason — do-while is an exit controlled loop as it executes atleast once even when the condition is false. The condition is checked at the time of exit.

15Objective Type Questions

Which of the following statements terminates the complete execution of a loop ?

Show SolutionHide Solution↓

break

Reason — break statement is used to terminate the complete execution of a loop.

1Assignment Questions

What is meant by token? Name the tokens available in Java.

Show SolutionHide Solution↓

The smallest individual unit in a program is called a token.

Keywords, identifiers, literals, operators and punctuators are tokens available in Java.

2Assignment Questions

What are keywords ? Can keywords be used as identifiers ?

Show SolutionHide Solution↓

Keywords are the words with special meaning associated with them. These are reserved for special purpose and must not be used as normal identifier names. Some keywords of Java are default, return, if, private etc.

No, keywords cannot be used as identifiers.

3Assignment Questions

What is an identifier ? What is the identifier forming rule(s) of Java?

Show SolutionHide Solution↓

Identifiers are the names given by the programmer to various program units of Java. Identifiers are the names of variables, methods, classes, packages and interfaces etc.

Identifier forming rules of Java state the following:

  1. Identifiers can have alphabets, digits, _ (underscore) and $\text{\textdollar}$ characters and can be of any length.
  2. They must not be a keyword or Boolean literal or null literal.
  3. They must not begin with a digit.
  4. Java is case sensitive i.e., upper-case letters and lower-case letters are treated differently.
4Assignment Questions

What kind of program elements are the following ?

13, 'a', 4.38925, "a", main( )

Show SolutionHide Solution↓
13Integer Literal
'a'Character Literal
4.38925Floating point Literal
"a"String Literal
main( )Method
5Assignment Questions

What kind of constants are the following ?

14, 011, 0X2A, 17, 014, 0XBC1

Show SolutionHide Solution↓
14Decimal Integer Literal
011Octal Integer Literal
0X2AHexadecimal Integer Literal
17Decimal Integer Literal
014Octal Integer Literal
0XBC1Hexadecimal Integer Literal
6Assignment Questions

What is a character constant in Java ? How are non graphic characters represented in Java ?

Show SolutionHide Solution↓

Single character enclosed in single quotation marks (' ') makes a character literal. For example, 'a', '5', $\text{\textdollar}$, '1' are character literals.

Non-graphic characters are represented in Java using escape sequence. An escape sequence is represented by a backslash (\) followed by one or more characters. For example, '\n', '\t' are escape sequences for new line and tab respectively.

7(a)Assignment Questions

Write an equivalent Java expression for the following expressions:

$\text{ut} + \frac{1}{2}\text{ft}^2$

Show SolutionHide Solution↓

u * t + (1.0 / 2.0) * f * t * t

7(b)Assignment Questions

Write an equivalent Java expression for the following expressions:

$\sqrt{\text{a}^2 + \text{b}^2}$

Show SolutionHide Solution↓

Math.sqrt(Math.pow(a,2) + Math.pow(b,2))

7(c)Assignment Questions

Write an equivalent Java expression for the following expressions:

ab + b >= ba + a

Show SolutionHide Solution↓

Math.pow(a, b) + b >= Math.pow(b, a) + a

7(d)Assignment Questions

Write an equivalent Java expression for the following expressions:

$\Big(\frac{3x + 5y}{5x + 3y} - \frac{8xy}{2yx}\Big)^{3/2}$

Show SolutionHide Solution↓

Math.pow(((3 * x + 5 * y) / (5 * x + 3 * y)) - ((8 * x * y) / (2 * y * x)), 3.0 / 2)

8Assignment Questions

What is meant by implicit and explicit type conversion ?

Show SolutionHide Solution↓

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);
9Assignment Questions

What do you mean by type casting? What is type cast operator in Java?

Show SolutionHide Solution↓

The explicit conversion of an operand to a specific type is called Type Casting.

Type Casting in Java is done using the type cast operator. It is a unary operator. It's syntax is:

(<target datatype>) <value>

For example :

int a = 10;
double b = 25.5;
float c = (float)(a + b);
10Assignment Questions

What will be the resultant type of the following expression if bh represents a byte variable, i is an int variable, fl is a float variable and db is a double variable ?

bh - i + db / fl - i * fl + db / i
Show SolutionHide Solution↓

The resultant data type will be double.

    bh - i + db / fl - i * fl + db / i
⇒ byte - int + double / float - int * float + double / int
⇒ byte - int + double - float + double
⇒ int + double - float + double
⇒ double - float + double
⇒ double + double
⇒ double

11Assignment Questions

What will be the resultant type of the following expression if fl is a float variable and db is a double variable?

(int) (fl + db)
Show SolutionHide Solution↓

The resultant data type will be int.

Here, the programmer is performing an explicit type conversion to int using the type cast operator. Hence, the resultant data type will be int.

12Assignment Questions

Determine the data type of the expression

$\Big(\frac{100(1 - pq)}{(q + r)}\Big) - \Big(\frac{(p + r) / s}{(\text{long})(s + p)}\Big)$

If p is an int, r is a float, q is a long and s is double.

Show SolutionHide Solution↓

The result of the given expression will be double type.

$$\begin{aligned}\Big(\frac{\text{int} * (\text{int} - \text{int} * \text{long})}{\text{(\text{long} + \text{float})}}\Big) - \Big(\frac{(\text{int} + \text{float}) / \text{double}}{(\text{long})(\text{double} + \text{int})}\Big) \\[1em] \Rightarrow \Big(\frac{\text{int} * (\text{int} - \text{long})}{\text{float}}\Big) - \Big(\frac{\text{float} / \text{double}}{\text{long}}\Big) \\[1em] \Rightarrow \Big(\frac{\text{int} * \text{int}}{\text{float}}\Big) - \Big(\frac{\text{double}}{\text{long}}\Big) \\[1em] \Rightarrow \text{float} - \text{double} \\[1em] \Rightarrow \text{double}\end{aligned}$$

13Assignment Questions

Determine the data type of the expression

$\Big(\frac{2x + 3y}{5w + 6z} + \frac{8p}{5q}\Big)^4$

if x is int, y is long, w is float, z is double, p is short and q is long double.

Show SolutionHide Solution↓

The result will be of long double data type.

$$\begin{aligned}\Big(\frac{\text{int} + \text{long}}{\text{float} + \text{double}} + \frac{\text{short}}{\text{long double}}\Big)^4 \\[1em] \Rightarrow \Big(\frac{\text{long}}{\text{double}} + \frac{\text{short}}{\text{long double}}\Big)^4 \\[1em] \Rightarrow \Big(\text{double} + \text{long double}\Big)^4 \\[1em] \Rightarrow \text{long double}\end{aligned}$$

14(a)Assignment Questions

State the value and type of each expression.

Math.abs(-5) - Math.abs(-7)
Show SolutionHide Solution↓

The output value is -2. The type of expression is int.

    Math.abs(-5) - Math.abs(-7)
⇒ 5 - 7
⇒ -2

14(b)Assignment Questions

State the value and type of each expression.

Math.abs(-1e-1) +  Math.abs(-2e-2)
Show SolutionHide Solution↓

The output value is 0.12. The type of expression is double.

    Math.abs(-1e-1) + Math.abs(-2e-2)
⇒ 0.1 + 0.02
⇒ 0.12

14(c)Assignment Questions

State the value and type of each expression.

Math.sqrt(0.0064)
Show SolutionHide Solution↓

The output value is 0.08. The type of expression is double.

Math.sqrt() method returns the square root of its argument. As square root of 0.0064 is 0.08 hence that is the output. The return type of Math.sqrt() is double so the type of expression is double.

14(d)Assignment Questions

State the value and type of each expression.

Math.sqrt(Math.pow(2.7, 2))
Show SolutionHide Solution↓

The output value is 2.7. The type of expression is double.

Math.pow(2.7, 2) will calculate square of 2.7 as we are raising it to the power 2. After this, calculating square root with Math.sqrt() will return the same number 2.7. The return type of Math.sqrt() is double so the type of expression is double.

14(e)Assignment Questions

State the value and type of each expression.

Math.round(3.499)
Show SolutionHide Solution↓

The output value is 3. The type of expression is long.

Math.round() rounds off its argument to the nearest mathematical integer. If argument is float, return type is int, if argument is double, return type is long. In this case, 3.499 will be treated as double because suffix 'f' is not there. Hence, it will return a value of long data type.

14(f)Assignment Questions

State the value and type of each expression.

Math.max(1.5e-2, 0.095)
Show SolutionHide Solution↓

The output value is 0.095. The type of expression is double.

Math.max(a, b) returns the maximum of a and b. As 0.095 is greater than 1.5e-2, hence, 0.095 is the output. Since the argument is double so the data type of return value is also double.

14(g)Assignment Questions

State the value and type of each expression.

Math.ceil(4.002)
Show SolutionHide Solution↓

The output value is 5.0. The type of expression is double.

Math.ceil(x) returns the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer. Hence, output is 5.0 and data type of result is double.

14(h)Assignment Questions

State the value and type of each expression.

Math.min(-5, 1.0)
Show SolutionHide Solution↓

The output value is -5.0. The type of expression is double.

Math.min(a, b) returns the minimum of a and b. As one of the arguments is of double type hence, data type of return value is also double.

14(i)Assignment Questions

State the value and type of each expression.

Math.floor(7.99)
Show SolutionHide Solution↓

The output value is 7.0. The type of expression is double.

Math.floor( ) returns the largest double value that is less than or equal to the argument and is equal to a mathematical integer. Hence, output is 7.0 and data type of result is double.

14(j)Assignment Questions

State the value and type of each expression.

Math.ceil(-2.73)
Show SolutionHide Solution↓

The output value is -2.0. The type of expression is double.

Math.ceil( ) returns the smallest double value that is greater than or equal to the argument and is equal to a mathematical integer. -2.0 is the smallest mathematical integer greater than -2.73. Hence, output is -2.0 and data type of result is double.

14(k)Assignment Questions

State the value and type of each expression.

Math.pow(16, 0.25)
Show SolutionHide Solution↓

The output value is 2.0. The type of expression is double.

Math.pow(x, y) returns x raised to the power of y as a double value. Math.pow(16, 0.25) is equivalent to $\sqrt[4]{16}$. Hence, output is 2.0 and data type of result is double.

14(l)Assignment Questions

State the value and type of each expression.

Math.pow(4, -2)
Show SolutionHide Solution↓

The output value is 0.0625. The type of expression is double.

Math.pow(x, y) returns x raised to the power of y as a double value. Math.pow(4, -2) is equivalent to 4-2 i.e., $\frac{1}{4^2}$ = 0.0625. Hence, output is 0.0625 and data type of result is double.

14(m)Assignment Questions

State the value and type of each expression.

Math.round(1.49 + 0.1)
Show SolutionHide Solution↓

The output value is 2. The type of expression is long.

Math.round() rounds off its argument to the nearest mathematical integer. If argument is float, return type is int, if argument is double, return type is long. In this case, 1.49 + 0.1 = 1.59 so it will be rounded of to 2, the nearest mathematical integer. 1.59 will be treated as double because suffix 'f' is not there. Hence, it will return a value of long data type.

14(n)Assignment Questions

State the value and type of each expression.

Math.round(1.49) + 0.1
Show SolutionHide Solution↓

The output value is 1.1. The type of expression is long.

Math.round() rounds off its argument to the nearest mathematical integer.

    Math.round(1.49) + 0.1
⇒ 1 + 0.1
⇒ 1.1

If argument is float, return type is int, if argument is double, return type is long. In this case, 1.49 will be treated as double because suffix 'f' is not there. Hence, it will return a value of long data type.

15(a)Assignment Questions

Write the following as Java expressions.

$\sqrt{\text{a}^2 - \text{b}^2}$

Show SolutionHide Solution↓

Math.sqrt(Math.pow(a,2) - Math.pow(b,2))

15(b)Assignment Questions

Write the following as Java expressions.

π(x6 - y6)

Show SolutionHide Solution↓

Math.PI * (Math.pow(x,6) - Math.pow(y,6))

15(c)Assignment Questions

Write the following as Java expressions.

$\frac{4}{3} \pi r^3$

Show SolutionHide Solution↓

4.0 / 3.0 * Math.PI * Math.pow(r,3)

15(d)Assignment Questions

Write the following as Java expressions.

| z4 - 1 |

Show SolutionHide Solution↓

Math.abs(Math.pow(z,4) - 1)

16Assignment Questions

A student incorrectly attempted to produce a random value in the range 1.6 using the expression.

6*(int)Math.random( ) + 1

Correct the error in expression above to get the desired result.

Show SolutionHide Solution↓

The correct expression to get the desired result is given below:

(int)(6 * Math.random( )) + 1

The formula to get an integer number between 1 and n is:

int r = (int) (n * Math.random()) + 1

17Assignment Questions

What is the significance of a break statement in a switch statement ?

Show SolutionHide Solution↓

The break statement when used inside a switch, ends that case and proceeds to the first statement that follows switch statement. In case, the break statement is missing, the control flows to the next case below the matching case and continues to execute all the cases, till the end of switch statement. This is called fall through.

18Assignment Questions

What are iteration statements ? Name the iteration statements provided by Java.

Show SolutionHide Solution↓

The iterative constructs or iteration statements allow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iteration statements are also called loops or looping statements.

Java provides three iteration statements:

  1. for
  2. while
  3. do-while
19Assignment Questions

What is meant by an entry-controlled loop? Which Java loops are entry-controlled?

Show SolutionHide Solution↓

The loop which tests the condition before entering the loop is called entry-controlled loop. It does not execute if the condition is false.

for and while are entry controlled loops in Java.

20Assignment Questions

What is meant by an exit-controlled loop ? Which Java loops are exit-controlled ?

Show SolutionHide Solution↓

If a loop tests the condition at the time of exit from the loop, it is called exit-controlled loop. This loop executes at least once even if the condition is false.

do-while loop is an exit controlled loop in Java.

21Assignment Questions

What is the difference between a while and do-while loop ?

Show SolutionHide Solution↓
while loopdo-while loop
while is an entry-controlled loop.do-while is an exit-controlled loop.
while loop checks the test condition at the beginning of the loop.do-while loop checks the test condition at the end of the loop.
while loop executes only if the test condition is true.do-while loop executes at least once, even if the test condition is false.
while loop is helpful in situations where number of iterations is not known.do-while loop is suitable when we need to display a menu to the user.
Syntax:
while(test condition)
{
...
}
Syntax:
do
{
...
}while(condition);
22Assignment Questions

How many times is the loop body executed in a do loop, even if the test-condition is false ?

Show SolutionHide Solution↓

do-while loop is an exit controlled loop. Thus, its body is executed atleast once even if the test-condition is false.

23Assignment Questions

What is nested loop ?

Show SolutionHide Solution↓

A loop may contain another loop in its body. This form of a loop is called nested loop. In a nested loop, the inner loop must terminate before the outer loop.

For example:

for(int i = 0; i < 5; i ++) {
    for(int j = 0; j < i; j++)  {
        System.out.print(j + ' ');
    }
    System.out.println();
}
24Assignment Questions

Write a program to print pattern like :

        1
      2 1
    3 2 1
  4 3 2 1
5 4 3 2 1
Show SolutionHide Solution↓
public class KboatPattern
{
    public static void main(String args[]) {
        for (int i = 1; i <= 5; i++) {
            for (int j = 4; j >= i; j--)
                System.out.print(" ");
            for (int k = i; k >= 1; k--)
                System.out.print(k);
            System.out.println();
        }
    }
}
BlueJ output of KboatPattern.java
25Assignment Questions

Write a program to print a pattern as :

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Show SolutionHide Solution↓
public class KboatPattern
{
    public static void main(String args[]) {
        for (int i = 5; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}
BlueJ output of KboatPattern.java
26Assignment Questions

Write a program to print a pattern as :

1
1 0
1 0 1
1 0 1 0
1 0 1 0 1
Show SolutionHide Solution↓
//

public class KboatPattern
{
    public static void main(String args[]) {
        int a = 1, b = 0;
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                if (j % 2 == 0)
                    System.out.print(b + " ");
                else
                    System.out.print(a + " ");
            }
            System.out.println();
        }
    }
}
BlueJ output of KboatPattern.java
27Assignment Questions

Write a program to print a pattern as :

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

public class KboatPattern
{
    public static void main(String args[]) {
        for (int i = 5; i >= 1; i--) {
            for (int j = i; j < 5; j++) { 
                System.out.print(" ");
            }
            for (int k = 0; k < i; k++) { 
                System.out.print('*');
            }
            System.out.println();
        }
        for (int i = 4; i >= 1; i--) {
            for (int j = 1; j < i; j++) {
                System.out.print(" ");
            }
            for (int k = i; k <= 5; k++) {
                System.out.print('*');
            }
            System.out.println();
        }
    }
}
BlueJ output of KboatPattern.java
28Assignment Questions

Classify the following as primitive or non-primitive datatypes :

Show SolutionHide Solution↓
  1. Primitive data type
  2. Non-primitive data type
  3. Primitive data type
  4. Non-primitive data type
29Assignment Questions
System.out.print("BEST");
System.out.println("OF LUCK");

Choose the correct option for the output of the above statements

(i) BEST OF LUCK

(ii) BEST
     OF LUCK

Show SolutionHide Solution↓

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.

30(a)Assignment Questions

Write a Java expression for the following :

$\frac{\sqrt{3x + x^2}}{a + b}$

Show SolutionHide Solution↓

Math.sqrt(3 * x + Math.pow(x,2)) / (a + b))

30(b)Assignment Questions

What is the value of y after evaluating the expression given below ?

y += ++y + y-- + --y ; when int y = 8

Show SolutionHide Solution↓

The value of y will be 33.

    y += ++y + y-- + --y
⇒ y = y + ++y + y-- + --y         y = 8
⇒ y = 8 + 9 + y-- + --y              y = 9
⇒ y = 8 + 9 + 9 + --y                 y = 8
⇒ y = 8 + 9 + 9 + 7                    y = 7
⇒ y = 33

30(c)Assignment Questions

Give the output of the following :

Show SolutionHide Solution↓

(1) Math.floor(-4.7)

-5.0

Math.floor method returns the largest double value that is less than or equal to the argument and is equal to a mathematical integer. As -5.0 is the largest mathematical integer less than -4.7 so it is the output. Note that -4.7 is a negative number so the largest integer less than -4.7 is -5.0 and not -4.0.

(2) Math.ceil(3.4) + Math.pow(2,3)

12.0

Math.ceil(x) function returns the smallest whole number greater than or equal to x. Math.ceil(3.4) gives 4.0 and Math.pow(2,3) gives 8.0. So the output is 4.0 + 8.0 = 12.0.

31Assignment Questions

What are the values stored in variables r1 and r2 ?

Show SolutionHide Solution↓
  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.
32(a)Assignment Questions

Name the operators listed below :

Show SolutionHide Solution↓
  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)
32(b)Assignment Questions

State the number of bytes occupied by char and int data types.

Show SolutionHide Solution↓

char occupies 2 bytes and int occupies 4 bytes.

32(c)Assignment Questions

Write one difference between / and % operator.

Show SolutionHide Solution↓

/ operator computes the quotient whereas % operator computes the remainder.

33Assignment Questions

Predict the output :

class Test {
    public static void main (String args[]) { 
        double x, y, z ;
        x = 3;
        y = 4;
        z = Math.sqrt(x * x + y * y); 
        System.out.println("z = " + z);
    }
}
Show SolutionHide Solution↓

z = 5.0

z = Math.sqrt(x * x + y * y)
  ⇒ Math.sqrt(3.0 * 3.0 + 4.0 * 4.0)
  ⇒ Math.sqrt(9.0 + 16.0)
  ⇒ Math.sqrt(25.0)
  ⇒ 5.0

34Assignment Questions

Predict the output :

class Power {
    public static void main(String args[]) { 
        int e = 5, result, i;
        result = 1 ; 
        i = e ; 
        while(e > 0) {
            result *= 2 ;
            e--;
        }
        int n = result /2, p = i - 1;
	    System.out.println("2 to the power of " + i + " is " + result);
        System.out.println("2 to the power of " + p + " is " + n);
    }
}
Show SolutionHide Solution↓
2 to the power of 5 is 32
2 to the power of 4 is 16

The execution of while loop is shown in the table below:

e(e > 0)resultRemarks
5True2result = 1 x 2, e becomes 4
4True4result = 2 x 2, e becomes 3
3True8result = 4 x 2, e becomes 2
2True16result = 8 x 2, e becomes 1
1True32result = 16 x 2, e becomes 0
0FalseLoop terminates

    n = result / 2, p = i - 1;
⇒ n = 32 / 2, p = 5 - 1
⇒ n = 16, p = 4

35Assignment Questions

Predict the output :

class FindFac {
    public static void main (String args[]) { 
        for(int i = 2; i <= 100; i++) {
            System.out.print("Factors of" + i + ":  ");
            for(int j = 2; j < i; j++)
                if((i % j) == 0) 
                    System.out.print(j + " "); 
                System.out.println();
        }
    }
}
Show SolutionHide Solution↓

The output of the program is a list of the factors of each integer between 2 and 100, printed to the console.

Factors of2:  
Factors of3:  
Factors of4:  2 
Factors of5:  
Factors of6:  2 3 
Factors of7:  
Factors of8:  2 4 
Factors of9:  3 
Factors of10:  2 5 
...
...
Factors of95:  5 19 
Factors of96:  2 3 4 6 8 12 16 24 32 48 
Factors of97:  
Factors of98:  2 7 14 49 
Factors of99:  3 9 11 33 
Factors of100:  2 4 5 10 20 25 50

This Java program finds the factors of integers between 2 and 100.

The program uses two nested for loops to generate the integers to be factored and to find their factors. The outer for loop generates the numbers from 2 to 100 whose factors are to be found.

The inner for loop starts with j = 2 and continues until j < i, incrementing j by 1 each time through the loop. This loop checks whether j is a factor of i by checking whether the remainder of i divided by j is equal to zero. If j is a factor of i, it is printed to the console on the same line as the message "Factors of [i]: ".

After the inner loop has completed, a newline character is printed to the console using System.out.println(). This causes the next message ("Factors of [i+1]: ") to be printed on a new line.

Let us consider the execution of nested 'for' loop for a single value of i (say, i = 6). The given table follows the execution:

ii <= 100jj < i(i % j) == 0OutputRemarks
6True2TrueTrueFactors of 6: 26 % 2 = 0
  3TrueTrueFactors of 6: 2 36 % 3 = 0
  4TrueFalse 6 % 4 ≠ 0
  5TrueFalse 6 % 5 ≠ 0
  6False  j becomes equal to i, inner loop terminates and i becomes 7
36Assignment Questions

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);
Show SolutionHide Solution↓
20

Initially i = 5.

The test condition i > 10 is false and so the control comes to the next statement following 'for' loop — System.out.println(i * 4); and prints 20 (5 * 4) on the screen.

37Assignment Questions

Find the error

for(count = 0,  count < 5,  count = count + 1)	
System.out.println("This is  count:" + count);	
    System.out.println("Done!");	
Show SolutionHide Solution↓

The errors are as follows:

  1. The variable count is not declared. It needs to be declared before it can be used.
  2. The syntax of 'for' loop requires semicolons ( ; ) as separators, and not comma ( , ). The correct code is as follows:
for(int count = 0;  count < 5;  count = count + 1)	
	System.out.println("This is  count:" + count);	
System.out.println("Done!");
38Assignment Questions

Find the error :

x = 3;	
y = 4;	
z = math.power(x*x, y/2);	
Show SolutionHide Solution↓

The errors are as follows:

  1. The variables — x, y, z, are not declared. They need to be declared before they can be used.
  2. The letter 'm' in math should be in uppercase as Java is a case-sensitive language. Also, the correct name of the function is pow. Hence, it must be written as Math.pow().

The correct code snippet is as follows:

int x = 3;	
int y = 4;	
double z = Math.pow(x*x, y/2);
39Assignment Questions

Find the error:

class Test {	
	public static void main (String args[])  {	
		int x = 10;
        if(x == 10)  {
            int y = 20;
            System.out.println("x and y: "+ x +"  "+ y);
            x = y * 2;
        }
        y = 100;
        System.out.println("x is"+ x);
    }
}
Show SolutionHide Solution↓

The variable y is declared inside 'if' block. Its scope is limited to if block and it cannot be used outside the block.

The correct code snippet is as follows:

class Test {	
	public static void main (String args[])  {	
		int x = 10;	
        int y;
        if(x == 10)  {
            y = 20;
            System.out.println("x and y: "+ x +"  "+ y);
            x = y * 2;
        }
        y = 100;
        System.out.println("x is"+ x);
    }
}
40Assignment Questions

Write a program that inputs a number and tests if the given number is a multiple of both 3 and 5.

import java.util.Scanner;

public class KboatMultipleCheck
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int num = in.nextInt();
        
        if (num % 3 == 0 && num % 5 == 0)
            System.out.println("Multiple of 3 and 5");
        else
            System.out.println("Not a multiple of 3 and 5");
    }
}
BlueJ output of KboatMultipleCheck.java BlueJ output of KboatMultipleCheck.java

Solution not available in the source paper.

41Assignment Questions

Write a program that inputs a character and prints if the typed character is in uppercase or lowercase.

import java.util.Scanner;

public class KboatCheckCase
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter an alphabet: ");
        char ch = in.next().charAt(0);
        
        if(Character.isUpperCase(ch)) 
            System.out.println("Upper Case letter");
        else if(Character.isLowerCase(ch)) 
            System.out.println("Lower Case Letter");
        else
            System.out.println("Character not an alphabet");
    }
}
BlueJ output of KboatCheckCase.java BlueJ output of KboatCheckCase.java

Solution not available in the source paper.

42Assignment Questions

Write a program that inputs a character and prints if the user has typed a digit or an alphabet or a special character.

import java.util.Scanner;

public class KboatCheckLetterDigitSpChar
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a character: ");
        char ch = in.next().charAt(0);
        
        if(Character.isLetter(ch)) 
            System.out.println("Letter");       
        else if(Character.isDigit(ch)) 
            System.out.println("Digit");
        else if(!Character.isWhitespace(ch))
            System.out.println("Special character");
        
    }
}
BlueJ output of KboatCheckLetterDigitSpChar.java BlueJ output of KboatCheckLetterDigitSpChar.java BlueJ output of KboatCheckLetterDigitSpChar.java

Solution not available in the source paper.

43Assignment Questions

Write a program that inputs an alphabet and checks if the given alphabet is a vowel or not.

import java.util.Scanner;

public class KboatVowelCheck
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a character: ");
        char ch = in.next().charAt(0);
        ch = Character.toUpperCase(ch);
        
        if(ch == 'A' || 
        ch == 'E' || 
        ch == 'I' || 
        ch == 'O' || 
        ch == 'U') 
            System.out.println("Vowel");
                
        else
            System.out.println("Not a vowel");
        
    }
}
BlueJ output of KboatVowelCheck.java BlueJ output of KboatVowelCheck.java

Solution not available in the source paper.

44Assignment Questions

Write a program that takes a number and check if the given number is a 3 digit number or not. (Use if to determine)

import java.util.Scanner;

public class Kboat3DigitNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number: ");
        int n = in.nextInt();
        
        if (n >= 100 && n <= 999)
            System.out.println("Three Digit Number");
        else
            System.out.println("Not a three digit number");
    }
}
BlueJ output of Kboat3DigitNumber.java BlueJ output of Kboat3DigitNumber.java

Solution not available in the source paper.

45Assignment Questions

Write a program to input three numbers and print the largest of the three numbers.

import java.util.Scanner;

public class KboatLargestNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter first number: ");
        int a = in.nextInt();
        System.out.print("Enter second number: ");
        int b = in.nextInt();
        System.out.print("Enter third number: ");
        int c = in.nextInt();
        
        System.out.print("Largest number: ");
        if (a > b && a > c)
            System.out.println(a);
        else if (b > a && b > c)
            System.out.println(b);
        else
            System.out.println(c);
    }
}
BlueJ output of KboatLargestNumber.java

Solution not available in the source paper.

46Assignment Questions

Write a program that takes a number and check if the given number is a 3 digit number or not. (Use a loop to determine)

import java.util.Scanner;

public class KboatDigitCount
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = in.nextInt();
        int count = 0;
        
        while (n != 0)    {
            count++;
            n = n / 10;
        }
        
        if (count == 3)
            System.out.println("Three digit number");
        else
            System.out.println("Not a three digit number");
    }
}
BlueJ output of KboatDigitCount.java BlueJ output of KboatDigitCount.java

Solution not available in the source paper.

47Assignment Questions

Write a program that prints the squares of 10 even numbers in the range 10 .. 100.

public class KboatSquares
{
    public static void main(String args[])  {
        
        System.out.println("Squares of even number:");
        System.out.println("Number\tSquare");
        
        for(int i = 10; i < 30; i += 2) {
            int sq = i * i;
            System.out.println(i + "\t" + sq);
        }
    }
}
BlueJ output of KboatSquares.java

Solution not available in the source paper.

48Assignment Questions

Write a program that inputs a number and checks if the given number is a palindrome. A number that is equal to its reversed number is a palindrome number.

import java.util.Scanner;

public class KboatPalindromeNumber
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number: ");
        int num = in.nextInt();
        int copyNum = num;
        int revNum = 0;

        while(copyNum != 0) {
            int digit = copyNum % 10;
            copyNum /= 10;
            revNum = revNum * 10 + digit;
        }

        if (revNum == num) 
            System.out.println("A Palindrome number");
        else
            System.out.println("Not a Palindrome number");
    }
}
BlueJ output of KboatPalindromeNumber.java BlueJ output of KboatPalindromeNumber.java

Solution not available in the source paper.

49Assignment Questions

Write a program to input a number in the range 10 to 100 and check if it is a prime number.

import java.util.Scanner;

public class KboatPrime
{
    public static void main(String args[]) {
        System.out.print("Enter a number between 10 to 100 : ");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        
        int c = 0;
        
        if(num < 10 || num > 100)
            System.out.println("Number out of range");
        else    {
            for (int i = 1; i <= num; i++) {
                if (num % i == 0)
                    c++;
            }
            if (c == 2)
                System.out.println("Prime number");
            else
                System.out.println("Not a prime number");
        }
    }
}
BlueJ output of KboatPrime.java BlueJ output of KboatPrime.java

Solution not available in the source paper.

50Assignment Questions

Write a program to print following series of numbers: 2, 5, 8, 11, 14....

public class KboatSeries
{
    public static void main(String args[]) {
        for (int i = 2; i <= 100; i += 3) {
            System.out.print(i + " ");
        }       
    }
}
BlueJ output of KboatSeries.java

Solution not available in the source paper.

51Assignment Questions

Write a program to print Fibonacci series : 0, 1, 1, 2, 3, 5, 8....

public class KboatFibonacci
{
    public static void main(String args[]) {
        int a = 0;
        int b = 1;
        System.out.print(a + " " + b);
        /*
         * i is starting from 3 below
         * instead of 1 because we have 
         * already printed 2 terms of
         * the series. The for loop will 
         * print the series from third
         * term onwards.
         */
        for (int i = 3; i <= 20; i++) {
            int term = a + b;
            System.out.print(" " + term);
            a = b;
            b = term;
        }
    }
}
BlueJ output of KboatFibonacci.java

Solution not available in the source paper.

52Assignment Questions

Write a program to print factorial of a given number.

import java.util.Scanner;

public class KboatFactorial
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = in.nextInt();
        
        long f = 1;
        
        for (int i = 1; i <= n; i++) { 
            f *= i;
        }
        
        System.out.println("Factorial of " + n 
                            + " = " + f);
                
    }
}
BlueJ output of KboatFactorial.java

Solution not available in the source paper.

53Assignment Questions

Write a program to print Floyd's triangle as shown below:

1
2   3
4   5   6
7   8   9  10
11 12  13  14  15
import java.util.Scanner;

public class KboatFloydsTriangle
{
    public static void main(String args[]) {
        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();
        }
    }
}
BlueJ output of KboatFloydsTriangle.java

Solution not available in the source paper.

Press ↓ to reveal a solution and move to the next question. Back to Sumita Arora Computer Applications.

Free sample bank