Computer Answers –
1. C) int
2. B) false
3. B) int num = input.nextInt();
4. B) chooses between two alternatives
5. A) for loop
6. A) true
7. B) float
8. A) 0
9. D) all of the above
10. B) Scanner sc = new Scanner(System.in);
11. Data types are the means to recognize the type of data involved in an operation. They are
the means to identify an entity or entities and their operations known as data types. Ex – int,
long.
12. The nextInt() method in Java, primarily found within the java.util.Scanner class, serves the
purpose of reading and parsing the next token of input as an integer.
13. S.
No if if-else
.
if statement allows us to if-else statement allows us to
execute a code block execute different code blocks
1.
when the condition is based on whether the condition is
True. True or False.
if statement does if-else statement executes the
2. nothing in case condition statements indented below else
evaluates to False. when the condition is False.
14. An iterative construct in Java, also known as a loop or looping statement, is a programming
construct that allows a block of code to be executed repeatedly until a specified condition is
met or a certain number of iterations have occurred. This facilitates the automation of
repetitive tasks and the processing of collections of data. Ex – for loop, while loop.
15. The Boolean data type in Java represents a logical value that can only be one of two
states: true or false. It is fundamental for controlling program flow, making decisions, and
representing conditions.
public class BooleanExample {
public static void main(String[] args) {
// Declaring and initializing boolean variables
boolean isJavaFun = true;
boolean hasPassedExam = false;
// Using boolean variables in conditional statements
if (isJavaFun) {
System.out.println("Learning Java is enjoyable!");
} else {
System.out.println("Java might require more effort.");
}
// Using boolean variables in expressions
int score = 75;
boolean isEligibleForNextLevel = (score >= 70 && hasPassedExam);
System.out.println("Is eligible for next level? " + isEligibleForNextLevel);
}
}
16. The Scanner class in Java, found in the java.util package, serves the primary purpose of
parsing primitive types and strings from various input sources.
Its key functionalities include:
Reading User Input:
It is commonly used to obtain input from the user via the console (keyboard), allowing
interactive programs.
Parsing Different Data Types:
The Scanner class provides methods like nextInt(), nextDouble(), nextLine(), nextBoolean(),
etc., to read and parse specific primitive data types and strings from the input stream.
Reading from Files and Strings:
Beyond console input, Scanner can also be used to read and parse data from files and even
directly from String objects, making it versatile for various data processing tasks.
17. To read a string input from the user in Java, the Scanner class is commonly used.
Steps:
Import the Scanner class: This class is part of the java.util package, so you need to include
the following line at the beginning of your Java file:
import java.util.Scanner;
Create a Scanner object: Instantiate the Scanner class, passing System.in as the argument to
its constructor. System.in represents the standard input stream, typically the console.
Scanner scanner = new Scanner(System.in);
Prompt the user (Optional but recommended): Before reading input, it's good practice to
display a message to the user, instructing them what to enter.
System.out.println("Enter a string:");
Read the string input: Use the nextLine() method of the Scanner object to read the entire
line of text entered by the user until a newline character is encountered. This method
returns the input as a String.
String userInput = scanner.nextLine();
18. public class NumberCheck {
public static void main(String[] args) {
int number = -5; // You can change this value to test different cases
if (number > 0) {
System.out.println(number + " is a positive number.");
} else if (number < 0) {
System.out.println(number + " is a negative number.");
} else {
System.out.println(number + " is zero.");
}
}
}
19. The basic syntax of a for loop in Java is as follows:
for (initialization; condition; update) {
// Code to be executed in each iteration
}
20. A while loop is a control flow statement that allows code to be executed repeatedly based on
a given Boolean condition. The while loop can be thought of as a repeating if statement.
A do-while loop is similar to while loop with the only difference that it checks for the
condition after executing the statements, and therefore is an example of Exit Control Loop.
21. Int data type is a type of primitive data type in Java. It is used to store integral type data such
as integers. Its range is from -2147483648 to 2147483647. It is used in storing and doing
operations in the numbers between its range.
22. import java.util.Scanner; // Import the Scanner class to read input
public class SumOfTwoNumbers {
public static void main(String[] args) {
// Create a Scanner object to read input from the console
Scanner inputScanner = new Scanner(System.in);
// Prompt the user to enter the first number
System.out.print("Enter the first number: ");
// Read the first integer from the user
int number1 = inputScanner.nextInt();
// Prompt the user to enter the second number
System.out.print("Enter the second number: ");
// Read the second integer from the user
int number2 = inputScanner.nextInt();
// Calculate the sum of the two numbers
int sum = number1 + number2;
// Display the sum to the user
System.out.println("The sum of " + number1 + " and " + number2 + " is: " + sum);
// Close the scanner to release system resources
inputScanner.close();
}
}
23. The switch statement is more updated and flexible than the if-else-if ladder. It provides an
easy way to execute various parts of the code based on the value of an expression. It allows
to transfer the program control to the matching case on the basis of value of variable or
expression. It terminates as soon as the break statement appears. If matching case is not
found, then the control transfers to the default case and executes the statements, then
terminates the switch block.
24. import java.util.Scanner; // Import the Scanner class to read user input
public class EvenOddChecker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Create a Scanner object
System.out.print("Enter an integer: "); // Prompt the user for input
int number = input.nextInt(); // Read the integer input from the user
// Check if the number is even or odd using the if-else statement
if (number % 2 == 0) { // If the remainder when divided by 2 is 0, it's even
System.out.println(number + " is an even number.");
} else { // Otherwise, it's an odd number
System.out.println(number + " is an odd number.");
}
input.close(); // Close the scanner object
}
}
25. import java.util.Scanner; // Import the Scanner class to read user input
public class LargestOfThree {
public static void main(String[] args) {
// Create a Scanner object to get input from the user
Scanner input = new Scanner(System.in);
// Prompt the user to enter three numbers
System.out.print("Enter the first number: ");
int num1 = input.nextInt(); // Read the first integer
System.out.print("Enter the second number: ");
int num2 = input.nextInt(); // Read the second integer
System.out.print("Enter the third number: ");
int num3 = input.nextInt(); // Read the third integer
int largest; // Declare a variable to store the largest number
// Use if-else if-else to find the largest number
if (num1 >= num2 && num1 >= num3) {
largest = num1; // num1 is the largest
} else if (num2 >= num1 && num2 >= num3) {
largest = num2; // num2 is the largest
} else {
largest = num3; // num3 is the largest
}
// Print the largest number
System.out.println("The largest number is: " + largest);
// Close the scanner to prevent resource leaks
input.close();
}
}
26. For Loop:
A for loop is typically used when the number of iterations is known or can be easily
determined before the loop begins. Its syntax integrates initialization, condition checking,
and iteration (increment/decrement) into a single line, making it concise and readable for
fixed-iteration scenarios.
While Loop:
A while loop is used when the number of iterations is not known beforehand and the loop
should continue as long as a specific condition remains true. It is more flexible for scenarios
where the loop's termination depends on a dynamic condition.
27. public class PrintNaturalNumbers {
public static void main(String[] args) {
System.out.println("The first 10 natural numbers are:");
// Loop from 1 to 10 (inclusive)
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
28. The break statement works like a barrier for each case within the switch block and if the
barrier is removed, then the process will continue till the next barrier is found. As soon as
the break statement appears, the control stops falling.
29. import java.util.Scanner;
public class FactorialCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = input.nextInt();
// Handle negative input
if (number < 0) {
System.out.println("Factorial is not defined for negative numbers.");
} else {
long factorial = 1; // Use long to handle larger factorials
// Calculate factorial using a for loop
for (int i = 1; i <= number; i++) {
factorial *= i; // factorial = factorial * i;
}
System.out.println("The factorial of " + number + " is: " + factorial);
}
input.close(); // Close the scanner
}
}
30. The continue statement in Java is a control flow statement used exclusively within loops (for,
while, do-while). Its purpose is to skip the current iteration of the loop and immediately
proceed to the next iteration. When continue is encountered, any remaining code within the
current iteration of the loop is bypassed, and the loop's condition is re-evaluated to
determine if the next iteration should commence.
31. import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
scanner.close(); // Close the scanner to prevent resource leaks
}
// Function to check if a number is prime
public static boolean isPrime(int num) {
if (num <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}
// Check for divisibility from 2 up to the square root of the number
// This optimization reduces the number of iterations significantly
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false; // If divisible, it's not prime
}
}
return true; // If no divisors found, it's prime
}
}
32. Conditional constructs in Java enable the execution of different blocks of code based on
whether specified conditions evaluate to true or false. These constructs facilitate decision-
making within a program, allowing for varied behaviour depending on the state of variables
or the outcome of expressions. The primary conditional constructs in Java are if, if-else, if-
else if-else, and switch.
The if statement executes a block of code only if its condition is true. The if-else statement
provides an alternative block of code to execute when the if condition is false. The if-else if-
else structure allows for multiple conditions to be checked sequentially, executing the first
block whose condition is true, and a final else block if none of the preceding conditions are
met. The switch statement provides a more structured way to handle multiple possible
values for a single variable, executing the code block associated with the matching value.
Here is a Java program using the if-else construct to determine if a given year is a leap year:
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
boolean isLeapYear;
// A year is a leap year if it is divisible by 400
// OR if it is divisible by 4 but not by 100
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
isLeapYear = true;
} else {
isLeapYear = false;
}
if (isLeapYear) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
input.close();
}
}
33. Java categorizes data types into two main groups: primitive and non-primitive.
Primitive Data Types: These are the fundamental building blocks and directly store values.
byte: 8-bit signed two's complement integer. Range: -128 to 127.
short: 16-bit signed two's complement integer. Range: -32,768 to 32,767.
int: 32-bit signed two's complement integer. Range: -2,147,483,648 to 2,147,483,647.
long: 64-bit signed two's complement integer. Range: -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
float: 32-bit IEEE 754 floating-point. Range: Approximately ±3.4e-38 to ±3.4e+38 (with 6-7
decimal digits of precision).
double: 64-bit IEEE 754 floating-point. Range: Approximately ±1.8e-308 to ±1.8e+308 (with
15-16 decimal digits of precision).
char: 16-bit Unicode character. Range: '\u0000' (0) to '\uffff' (65,535).
boolean: Represents one bit of information. Values: true or false.
Non-Primitive Data Types: These are reference types and are created by the
programmer. They include classes, interfaces, and arrays. They do not have a fixed size and
store references to objects in memory.
Here is a Java program demonstrating the declaration and assignment of different primitive
data types:
public class DataTypeExample {
public static void main(String[] args) {
// Integer types
byte myByte = 100;
short myShort = 30000;
int myInt = 2000000000;
long myLong = 9000000000000000000L; // 'L' suffix for long literal
// Floating-point types
float myFloat = 3.14f; // 'f' suffix for float literal
double myDouble = 3.1415926535;
// Character type
char myChar = 'A';
// Boolean type
boolean myBoolean = true;
// Print the values
System.out.println("byte: " + myByte);
System.out.println("short: " + myShort);
System.out.println("int: " + myInt);
System.out.println("long: " + myLong);
System.out.println("float: " + myFloat);
System.out.println("double: " + myDouble);
System.out.println("char: " + myChar);
System.out.println("boolean: " + myBoolean);
}
}
34. Iterative constructs in Java, also known as loops, are control flow statements that allow a
block of code to be executed repeatedly as long as a specified condition remains true. They
are essential for performing repetitive tasks efficiently and reducing code redundancy. The
main types of iterative constructs in Java are for, while, and do-while loops.
Here is a Java program to display the multiplication table of a number using a while loop:
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number to display its multiplication table: ");
int number = input.nextInt();
int i = 1; // Initialize the counter
System.out.println("Multiplication Table of " + number + ":");
while (i <= 10) { // Condition for the loop to continue
System.out.println(number + " * " + i + " = " + (number * i));
i++; // Increment the counter
}
input.close(); // Close the scanner
}
}