Gujarat Board, Class XII, Computer Science, Year 2018, Java Questions with Answers and Explanation
1) Which of the following statement is true for object-oriented programming language?
(i) It uses object as its
fundamental building block.
(ii) Similar objects are classified
using a concept of class
(iii) Abstraction, encapsulation, polymorphism,
and inheritance is its basic properties,
(A) only
(i) and (ii)
(B) only
(ii) and (iii)
(C) only
(i) and (iii)
(D) (i),
(ii) and (iii)
Answer: (D) (i), (ii), and (iii)
Explanation:
- (i) is true because object-oriented programming revolves around the concept of objects.
- (ii) is true because similar objects are grouped into classes in object-oriented programming.
- (iii) is true because abstraction, encapsulation, polymorphism, and inheritance are considered the basic properties or principles of object-oriented programming.
2) Which
of the following best suits to Java?
(A) A
procedural programming language
(B) An
object-oriented programming language
(C) A
query language
(D) An
editor
Answer: (B) An object-oriented programming language
Explanation:
Java is primarily known as an object-oriented programming (OOP) language. It follows the principles of object-oriented design, including concepts such as encapsulation, inheritance, and polymorphism. In Java, everything is treated as an object, and programming revolves around the creation and manipulation of objects.
While Java does support procedural programming features, its core strength lies in its object-oriented nature. It allows developers to create modular, reusable, and scalable code through the use of classes and objects.
Options (C) and (D) are not accurate descriptions of Java:
- (C) A query language: Java is not a query language. Query languages are typically associated with databases, and Java is not designed specifically for querying databases.
- (D) An editor: Java is not an editor. Java is a programming language used to write software applications. Editors are tools used to write and edit code in various programming languages, including Java.
Therefore, the most appropriate description for Java among the given options is (B) An object-oriented programming language.
3) Which
of the following is not a section of the icon that is used to represent a class
in class diagram?
(A) Name
(B) Attribute
(C) Behavior
(D)
Datatype
Answer: (D) Datatype
Explanation:
In a UML (Unified Modeling Language) class diagram, the icon representing a class is typically divided into three sections, each representing a different aspect of the class:
1. Name: This section displays the name of the class. It is usually located at the top of the class icon.
2. Attributes: The attributes section lists the properties or characteristics of the class. It is located in the middle of the class icon. Attributes describe the data that the class holds.
3. Behavior (Methods/Operations): The behavior section, located at the bottom of the class icon, lists the methods or operations that the class can perform. It describes the actions or functions associated with the class.
Therefore, in the context of the given question:
- (A) Name
- (B) Attribute
- (C) Behavior
are all sections of the icon used to represent a class in a class diagram. However, (D) Datatype is not typically represented as a separate section in the class icon. Instead, the datatype of attributes or parameters is usually specified within the attributes or methods themselves. The datatype information is part of the attribute or method details rather than having a dedicated section in the class icon.
4) In a class diagram, which symbol is used for public visibility?
(A) -
(B) #
(C) +
(D) ~
Answer: (C) +
Explanation: In UML (Unified Modeling Language) class diagrams, different symbols are used to represent the visibility or access level of class members, such as attributes and methods. Here's an explanation of the symbols:
- Public (+): Public visibility is denoted by the symbol '+'. Members (attributes or methods) with public visibility are accessible from outside the class. In other words, any class or object can access these members.
- Private (-): Private visibility is denoted by the symbol '-'. Members with private visibility are accessible only within the class where they are defined. They cannot be accessed directly from outside the class.
- Protected (#): Protected visibility is denoted by the symbol '#'. Members with protected visibility are accessible within the class and its subclasses (derived classes). They are not accessible from outside the class hierarchy.
- Package (default) visibility (~): The tilde (~) symbol is used to represent package or default visibility. Members with package visibility are accessible within the same package. This is a level of visibility between private and protected.
So, in the context of the question, when it mentions public visibility, the correct symbol is '+'. If you see a symbol like '+methodName()' or '+attributeName', it indicates that the method or attribute is publicly accessible from outside the class.
5) Which
of the following refers to representation of data in which the implementation
details are hidden?
(A) Encapsulation
(B)
Abstraction
(C)
Polymorphism
(D)
Composition
Answer: (B) Abstraction
Explanation:
Abstraction refers to the concept of hiding the complex implementation details and showing only the essential features of an object. It allows developers to focus on the functionality of an object rather than the intricate details of how that functionality is implemented. Abstraction helps in managing complexity by providing a simplified and high-level view.
Encapsulation (option A) is related to bundling the data (attributes) and methods (functions) that operate on the data into a single unit or class. It helps in hiding the internal details of how data is represented and manipulated.
Polymorphism (option C) is a concept where objects of different types can be treated as objects of a common type. It allows for flexibility and extensibility in code but is not directly related to hiding implementation details.
Composition (option D) involves creating complex objects by combining simpler objects. While it promotes code reuse and modularity, it is not specifically about hiding implementation details.
Therefore, the correct answer to the question is (B) Abstraction.
6) Polymorphism
is achieved using how many types of overloading?
(A) Two
(B) Three
(C) One
(D) Four
Answer: (A) Two
Explanation:
Polymorphism in programming allows objects of different types to be treated as objects of a common type. In Java, polymorphism is achieved through two types of overloading:
1. Method Overloading: This occurs when a class has two or more methods with the same name but different parameters (either different types or a different number of parameters). The compiler determines which method to invoke based on the arguments passed during the method call.
2. Operator Overloading: Java does not support operator overloading as directly as some other programming languages. However, it achieves a limited form of operator overloading through the use of predefined operators for certain types (e.g., `+` for addition of numbers and concatenation of strings).
So, the correct answer is (A) Two.
7) Which
of the following represents non-exclusive relationship between two classes?
(A)
Aggregation
(B)
Composition
(C)
Inheritance
(D)
Polymorphism
Answer: (A) Aggregation
Explanation:
In UML (Unified Modeling Language) and object-oriented programming, both aggregation and composition represent relationships between classes.
- Aggregation (Option A): In an aggregation relationship, one class represents a "whole" and another class represents a "part," but the "part" can exist independently of the "whole." It is a non-exclusive relationship, meaning that the "part" can be associated with multiple instances of the "whole" class.
- Composition (Option B): In a composition relationship, one class represents a "whole," and another class represents a "part," but the "part" cannot exist independently of the "whole." It is a more exclusive relationship, indicating a stronger association.
- Inheritance (Option C): Inheritance represents an "is-a" relationship where one class (subclass or derived class) inherits attributes and behaviors from another class (superclass or base class). It is not directly related to exclusive or non-exclusive relationships between instances of classes.
- Polymorphism (Option D): Polymorphism is a concept that allows objects of different types to be treated as objects of a common type, facilitating code reuse and flexibility. It is not inherently about relationships between classes.
Therefore, the correct answer is (A) Aggregation.
8) In
Inheritance, what is called an existing class?
(A) sub
class
(B) super
class
(C) child
class
(D) derived
class
Answer:
Explanation:
In inheritance, the existing class from which another class inherits is called the "super class" or "base class." The class that inherits from the super class is called the "sub class" or "derived class." Therefore, option (B) super class is the correct term for the existing class in the context of inheritance.
9) Which
of the following statement is true for Java language?
(i) Java language was developed by
Sun Microsystem.
(ii) Java is an object-oriented
language.
(iii) Java is not
platform-independent at both the source and binary level.
(A) only
(i) and (ii)
(B) only
(ii) and (iii)
(C) only
(i) and (iii)
(D) (ii)
and (iii)
Answer:
Explanation:
- (i) Java language was developed by Sun Microsystems. This statement is true. Java was indeed developed by Sun Microsystems, and the development started in the early 1990s.
- (ii) Java is an object-oriented language. This statement is true. Java is designed to be an object-oriented programming language, and it follows the principles of object-oriented design, including encapsulation, inheritance, and polymorphism.
- (iii) Java is not platform-independent at both the source and binary level. This statement is false. Java is known for its platform independence. Java source code is compiled into an intermediate form called bytecode, which can be executed on any device with a Java Virtual Machine (JVM) installed. This WORA (Write Once, Run Anywhere) capability makes Java platform-independent.
Therefore, the correct answer is (A) only (i) and (ii).
10) In
Java, float data type takes how many bytes of storage space?
(A) 2
bytes
(B) 4
bytes
(C) 8
bytes
(D) 16
bytes
Answer: (B) 4 bytes
Explanation:
In Java, the `float` data type is a 32-bit single-precision floating-point type, which means it occupies 4 bytes (32 bits) of storage space. The `float` type is used to represent decimal numbers with a fractional component.
11) In
Java, variable name must begin with which of the following?
(A) %
(B) digits
(C) spaces
(D)
alphabet
Answer:
Explanation:
In Java, variable names must follow certain rules:
1. Variable names are case-sensitive, so `myVar` and `myvar` are different.
2. Variable names must begin with a letter, currency character (`$`), or underscore (`_`).
3. After the first character, variable names can include letters, digits, underscores, and currency characters.
So, in this context, the correct answer is (D) alphabet. Variable names must begin with an alphabet letter, `$`, or `_`.
12) Which
of the following statement is right for boolean literals in Java?
(i) 0 is treated as false and 1 is
treated as true.
(ii) Literals are to be typed
without quotes.
(iii) For the boolean type, there
are two literals, true and false.
(A) only
(i) and (ii)
(B) only
(ii) and (iii)
(C) only
(i) and (iii)
(D) (i),
(ii) and (iii)
Answer: (B) only (ii) and (iii)
Explanation:
- (i) 0 is treated as false and 1 is treated as true. This statement is false for Java, because `0` is not a boolean literal in Java.
- (ii) Literals are to be typed without quotes. This statement is generally true. Boolean literals `true` and `false` are keywords in Java and should not be enclosed in quotes. Quotes are used for string literals.
- (iii) For the boolean type, there are two literals, true and false. This statement is true. In Java, the boolean type has two literals: `true` and `false`.
Therefore, the correct answer is (B) only (ii) and (iii).
13) Which
of the following is not a basic arithmetic operator of Java?
(A) +
(B) -
(C) *
(D) \
Answer: (D) \
Explanation:
In Java, the backslash (`\`) is not a basic arithmetic operator. Instead, it is used as an escape character in strings and character literals. The basic arithmetic operators in Java are:
- (A) `+`: Addition
- (B) `-`: Subtraction
- (C) `*`: Multiplication
- (D) `/`: Division
So, the correct answer is (D) \.
14) Which of
the following is not a comparison operator in Java?
(A) <=
(B) >=
(C) =
(D) !=
Explanation:
In Java, the equal sign (`=`) is not a comparison operator; it is used for assignment. The correct comparison operators are:
- (A) <= : Less than or equal to
- (B) >= : Greater than or equal to
- (C) = : Assignment (not a comparison operator)
- (D) != : Not equal to
So, the correct answer is (C) =.
15) How
many types of control structures are there in Java?
(A) One
(B) Two
(C) Three
(D) Four
Answer: (B) Two
Explanation:
In Java, there are two main types of control structures: loops and branches.
1. Loops are used to repeat a sequence of statements over and over until some condition occurs.
2. Branches are used to choose among two or more possible courses of action, also called selective structure.
16) In the switch statement of Java, the test expression should be of which of the following type?
(A) float
(B) double
(C) byte
(D)
boolean
Answer: (C) byte
Explanation:
In Java, the test expression in a `switch` statement should be of integral or enumerated type. This includes `byte`, `short`, `char`, and `int` primitive data types, as well as enumerated types (`enum`). The `switch` statement is used to select one of many code blocks to be executed based on the value of the expression.
So, the correct answer is (C) byte.
17) In
Java, which of the following loop is a exit-controlled or post-test loop
construct?
(A) for
loop
(B) while
loop
(C) do … while
loop
(D) switch
Explanation:
In Java, the `do … while` loop is an exit-controlled or post-test loop construct. This means that the loop body is executed at least once, and the loop condition is evaluated after the execution of the loop body. If the condition is true, the loop continues; otherwise, it exits.
So, the correct answer is (C) do … while loop.
18) After
execution of which statement in the loop of Java, all the following statements
in a body of the loop are skipped and no further iteration take place?
(A)
continue
(B) go
(C) break
(D) loop
Explanation:
In Java, the `break` statement is used to terminate the loop prematurely. When a `break` statement is encountered inside a loop, it causes the loop to exit immediately, and the control is transferred to the next statement after the loop.
So, the correct answer is (C) break.
19) In
Java, which of the following is not a step of creating an object from a class?
(A)
Declaration
(B)
Instantiation
(C)
Initialization
(D)
Calculation
Answer: (D) Calculation
Explanation:
In Java, the process of creating an object from a class involves three main steps:
1. Declaration: Declaring a reference variable of the class type without creating an object. For example: `ClassName obj;`
2. Instantiation: Using the `new` keyword to create an instance of the class and allocate memory for the object. For example: `obj = new ClassName();`
3. Initialization: Initializing the object by invoking its constructor and setting initial values for its attributes. This often occurs in conjunction with instantiation.
20) Which
operator is used to access instance variable via object in Java?
(A) :
(B) ,
(C) +
(D) .
Answer: (D) .
Explanation:
In Java, the dot (`.`) operator is used to access instance variables and methods via an object.
Example:
ClassName obj = new ClassName();
obj.variableName; // Accessing instance variable
obj.methodName(); // Invoking a method
21) In
Java, which of the following variables can be accessed without creating an
instance of a class?
(A)
Instance
(B) Static
(C) Local
(D)
Private
Answer: (B) Static
Explanation:
In Java, static variables (class variables) can be accessed without creating an instance of a class. Static variables are associated with the class rather than with instances of the class. They are shared among all instances of the class and can be accessed using the class name.
Example:
public class MyClass {
static int staticVariable = 10;
public static void main(String[] args) {
// Accessing static variable without creating an instance
System.out.println(MyClass.staticVariable);
}
}
In the example above, `staticVariable` can be accessed using the class name `MyClass` without creating an instance of the class.
22) In
Java, variables defined inside methods or blocks are known as which type of
variable?
(A) Local
(B)
Instance
(C) Class
(D) Public
Answer: (A) Local
Explanation:
In Java, variables defined inside methods or blocks are known as local variables. Local variables are only accessible within the scope in which they are declared, such as within a method, constructor, or block of code.
Example:
public class Example {
public void myMethod() {
// Local variable
int localVar = 5;
System.out.println(localVar);
}
public static void main(String[] args) {
Example obj = new Example();
obj.myMethod();
}
}
In the example above, `localVar` is a local variable defined within the `myMethod` method and can only be used within that method.
23) In
Java, which of the following refers to different methods that have the same
name but a different signature?
(A) Method
overloading
(B)
Duplicate method
(C)
Instance method
(D)
Overridden method
Answer: (A) Method overloading
Explanation:
In Java, method overloading refers to the ability to define multiple methods with the same name in the same class but with different parameters (different signature). The compiler differentiates between these methods based on the number or types of parameters.
Example:
public class Example {
// Method with one parameter
public void display(int x) {
System.out.println("Displaying integer: " + x);
}
// Method with two parameters
public void display(String str, int num) {
System.out.println("Displaying string and integer: " + str + ", " + num);
}
public static void main(String[] args) {
Example obj = new Example();
obj.display(5);
obj.display("Hello", 10);
}
}
In the example above, there are two `display` methods in the `Example` class with different parameter lists, demonstrating method overloading.
24) In
Java, which method is invoked automatically with creation of an object?
(A)
Instance method
(B)
Constructor
(C) Class
method
(D) Local
method
Explanation:
In Java, a constructor is a special method that is automatically invoked when an object of a class is created using the `new` keyword. Constructors are used to initialize the object's state and perform any necessary setup.
Example:
public class Example {
// Constructor
public Example() {
System.out.println("Constructor invoked. Object created.");
}
public void instanceMethod() {
System.out.println("Instance method called.");
}
public static void main(String[] args) {
// Creating an object invokes the constructor
Example obj = new Example();
// Invoking an instance method
obj.instanceMethod();
}
}
In the example above, when an object `obj` is created, the constructor `Example()` is automatically invoked, and the message "Constructor invoked. Object created." is printed.
So, the correct answer is (B) Constructor.
25) In
Java, when no visibility modifier is used, then what is the default visibility?
(A) Public
(B)
Package
(C)
Protected
(D)
Private
Explanation:
In Java, when no visibility modifier (such as `public`, `private`, or `protected`) is explicitly used, the default visibility is package-private, also known as default or package visibility. This means that the class, method, or variable is accessible only within the same package.
So, the correct answer is (B) Package.
26) In
Java, which of the following visibility modifier is used to achieve highest
level of protection?
(A) Public
(B)
Package
(C)
Protected
(D)
Private
Explanation:
In Java, the visibility modifiers control the access levels of classes, methods, and variables. Among the given options:
- `Public` makes the class, method, or variable accessible from anywhere.
- `Package` (default or package-private) makes the class, method, or variable accessible only within the same package.
- `Protected` makes the class, method, or variable accessible within the same package and by subclasses, even if they are in different packages.
- `Private` provides the highest level of protection. A `private` member is only accessible within the same class.
Therefore, the correct answer is (D) Private. Using `private` ensures that the member is hidden from other classes and can only be accessed within the declaring class.
27) In Java
if we want to allow data to be modified by others. then which method do we have
to write?
(A)
Accessor (B)
Mutator
(C)
Accepter (D)
Edit
Explanation:
In Java, if you want to allow the modification of data by others, you would typically write a method called a "mutator" method. A mutator method, often prefixed with "set," is used to modify the state or attributes of an object.
Example:
public class MyClass {
private int myVariable; // Private instance variable
// Mutator method to set the value of myVariable
public void setMyVariable(int newValue) {
myVariable = newValue;
}
// Other methods and code...
}
In the example above, `setMyVariable` is a mutator method that allows others to modify the value of the private variable `myVariable` by providing a new value.
So, the correct answer is (B) Mutator.
28) In
Java, which keyword is used to call the constructor of superclass in the
constructor of subclass.
(A) Base
(B) Sub
(C) Super
(D) Parent
Explanation:
In Java, the `super` keyword is used to call the constructor of the superclass (parent class) from the constructor of the subclass (child class). This is often used when you want to initialize the attributes inherited from the superclass before performing any additional initialization in the subclass constructor.
Example:
public class Parent {
public Parent() {
System.out.println("Constructor of Parent class");
}
}
public class Child extends Parent {
public Child() {
super(); // Calling the constructor of the superclass
System.out.println("Constructor of Child class");
}
}
public class Main {
public static void main(String[] args) {
Child obj = new Child();
}
}
In this example, when an object of the `Child` class is created, the constructor of the `Parent` class is called first using `super()`, followed by the constructor of the `Child` class.
So, the correct answer is (C) Super.
29) In Java, array index value starts from which number?
(A) 0
(B) 1
(C) -1
(D) 8
Answer: (A) 0
Explanation:
In Java, array index values start from 0. The first element of an array is accessed using the index 0, the second element with index 1, and so on.
For example:
int[] myArray = {10, 20, 30, 40, 50};
// Accessing elements using array indices
System.out.println(myArray[0]); // Prints 10
System.out.println(myArray[1]); // Prints 20
System.out.println(myArray[2]); // Prints 30
In the example above, `myArray` is an array, and elements are accessed using indices starting from 0.
So, the correct answer is (A) 0.
30) In Java, initial value for 1-D array are separated using which symbol?
(A) . (full stop)
(B) , (comma)
(C) : (colon)
(D) - (dash)
Answer: (B) , (comma)
Explanation:
In Java, the initial values for a one-dimensional array are separated using the comma (`,`) symbol. The values are enclosed within curly braces `{}`.
Example:
int[] myArray = {10, 20, 30, 40, 50};
In the example above, the values 10, 20, 30, 40, and 50 are the initial values of the one-dimensional array `myArray`, and they are separated by commas.
So, the correct answer is (B) , (comma).
31) Which
of the following is not a correct way to create and Initialize an array named
marks?
(A) int
marks[] = new int [3];
(B) int[] marks
= new int [3];
(C) int
marks [] = {0, 10, 20};
(D) int marks
[3] = {0, 10, 20};
Explanation:
In Java, when you specify the size of an array using square brackets (`[]`), it should not be repeated during initialization. Option (D) repeats the size (`[3]`) during initialization, which is incorrect.
The correct ways to create and initialize an array named `marks` are:
- (A) `int marks[] = new int[3];`
- (B) `int[] marks = new int[3];`
- (C) `int marks[] = {0, 10, 20};`
These options correctly create an array of size 3 and initialize it with values.
So, the correct answer is (D) int marks [3] = {0, 10, 20};
32) sort( ) and fill( ) are methods of which of the following Java class ?
(A) java.string
(B)
java.util.Arrays
(C)
java.io
(D)
java.util.io
Explanation:
The `sort()` and `fill()` methods are part of the `java.util.Arrays` class in Java.
- `sort()`: This method is used to sort the elements of an array in ascending order. It has overloaded versions for different data types.
Example:
int[] numbers = {5, 2, 8, 1, 7};
Arrays.sort(numbers);
- `fill()`: This method is used to fill the elements of an array with a specified value.
Example:
int[] numbers = new int[5];
Arrays.fill(numbers, 10);
So, the correct answer is (B) java.util.Arrays.
33) In the following statement for declaring two-dimensional array of Java, 5 represents what?
int marks[]
[] = new int [5] [3]
(A) number
of rows
(B) number
of columns
(C) array
size
(D) number
of bytes
Explanation:
In the given statement:
int marks[][] = new int[5][3];
The `5` represents the number of rows in the two-dimensional array. The size of the array is specified as `[5][3]`, where `5` is the number of rows, and `3` is the number of columns.
So, the correct answer is (A) number of rows.
34) In
Java, which of the following constructor creates a string object same as object
specified in argument?
(A) String
(char ary [])
(B) String
( )
(C) String
(String literal)
(D) String
(String strObj)
Explanation:
In Java, the constructor `String(String strObj)` creates a new string object that contains the same character sequence as the specified `String` object (`strObj`). It essentially creates a copy of the existing string.
Example:
String originalString = "Hello";
String copiedString = new String(originalString);
In the example above, `copiedString` will be a new string object with the same content as `originalString`.
So, the correct answer is (D) String (String strObj).
35) In Java, int compareTo (String str) method returns which of the following value if invoking string is greater than str ?
(A) 0
(B) >0
(C) <0
(D)
Logical value
Explanation:
In Java, the `compareTo(String str)` method of the `String` class returns an integer value:
- If the invoking string is lexicographically greater than the `str` argument, it returns a value greater than 0.
- If the invoking string is lexicographically smaller than the `str` argument, it returns a value less than 0.
- If the two strings are lexicographically equal, it returns 0.
So, the correct answer is (B) >0.
36) Which of the following method of Java, returns an array of characters as bytes from invoking string?
(A) string
concat( )
(B) char
getByte()
(C) byte[ ]
getBytes( )
(D) string
to bytes( )
Answer: (C) byte[ ] getBytes( )
Explanation:
In Java, the `getBytes()` method of the `String` class is used to obtain an array of bytes from the invoking string. This method returns the sequence of bytes representing the characters in the string.
Example:
String myString = "Hello, World!";
byte[] byteArray = myString.getBytes();
In the example above, `byteArray` will contain the bytes representing the characters in the string "Hello, World!".
37) In Java, which of the following method of Date class returns a string representing Date and time of invoking object?
(A) Date(
) (B)
String toString( )
(C) Date
char( ) (D)
Date Text( )
Answer: (B) String toString( )
Explanation:
In Java, the `toString()` method of the `Date` class is used to obtain a string representation of the date and time stored in the invoking object.
Example:
import java.util.Date;
public class Example {
public static void main(String[] args) {
Date currentDate = new Date();
String dateString = currentDate.toString();
System.out.println(dateString);
}
}
In the example above, `currentDate.toString()` returns a string representing the current date and time.
So, the correct answer is (B) String toString( ).
38) In
Java, which constant of calendar class returns day number within a week?
(A) DAY_OF_WEEK
(B) DAY_OF_MONTH
(C) DAY_OF_YEAR
(D) DATE
Answer: (A) DAY_OF_WEEK
Explanation:
In Java's `Calendar` class, the constant `DAY_OF_WEEK` is used to represent the day of the week. It returns a value ranging from `SUNDAY` (1) to `SATURDAY` (7). This constant is often used to get or set the day of the week within a `Calendar` instance.
Example:
import java.util.Calendar;
public class Example {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println("Day of the week: " + dayOfWeek);
}
}
In the example above, `Calendar.DAY_OF_WEEK` is used to get the current day of the week.
39) In Java program, if there is a syntax error, which of the following error we will get?
(A)
compile-time
(B)
run-time
(C)
print-time
(D) file save-time
Answer: (A) compile-time
Explanation:
In Java, if there is a syntax error in the program, it will result in a compile-time error. The Java compiler checks the syntax of the program during the compilation phase. If it encounters any syntax errors, it will not generate the bytecode, and the compilation process will fail.
Compile-time errors are often related to issues such as missing semicolons, incorrect variable names, mismatched parentheses, etc.
So, the correct answer is (A) compile-time.
40) In
Java, which exception class is used for condition resulting in an attempt to
access a non-existing file?
(A)
ArraylndexOutOfBoundsException
(B)
FileNotFoundException
(C)
NullPointerException
(D)
PrinterIOException
Explanation:
In Java, the `FileNotFoundException` is used to indicate that an attempt to open the file denoted by a specified pathname has failed because the file does not exist.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
try {
// Attempting to open a non-existing file
File file = new File("nonexistent.txt");
Scanner scanner = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
In the example above, if the file "nonexistent.txt" does not exist, a `FileNotFoundException` will be thrown.
So, the correct answer is (B) FileNotFoundException.
41) In
exception handing of Java, which block contains the code that may give rise to
one or more exceptions?
(A) throw
(B) try
(C) catch
(D) finally
Answer: (B) try
Explanation:
In Java's exception handling mechanism, the `try` block contains the code that may give rise to one or more exceptions. The `try` block encloses the statements that could potentially throw an exception.
Example:
try {
// Code that may throw an exception
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
// Code to handle the exception
System.out.println("Exception caught: " + e.getMessage());
}
In the example above, the code within the `try` block attempts to divide by zero, which would result in an `ArithmeticException`. The `catch` block is used to handle the exception.
So, the correct answer is (B) try.
42) In
Java exception handing, which block is generally used to clean up at the end of
executing a try block?
(A) catch (B)
finally
(C) throw (D)
new
Explanation:
In Java's exception handling mechanism, the `finally` block is generally used to clean up at the end of executing a `try` block, regardless of whether an exception is thrown or not. The code inside the `finally` block will be executed whether an exception is caught or not.
Example:
try {
// Code that may throw an exception
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
// Code to handle the exception
System.out.println("Exception caught: " + e.getMessage());
} finally {
// Code to clean up, executed regardless of exception
System.out.println("Finally block executed.");
}
In the example above, the `finally` block will be executed even though an exception is thrown in the `try` block.
So, the correct answer is (B) finally.
43) In
Java exception handling, which of the following block is always executed
regardless of whether or not exceptions are thrown during the execution of the
associated try block?
(A) throw
(B)
finally
(C) catch
(D) new
Explanation:
In Java's exception handling mechanism, the `finally` block is always executed regardless of whether or not exceptions are thrown during the execution of the associated `try` block. The `finally` block is used for cleanup or releasing resources and is guaranteed to be executed.
Example:
try {
// Code that may throw an exception
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
// Code to handle the exception
System.out.println("Exception caught: " + e.getMessage());
} finally {
// Code to clean up, executed regardless of exception
System.out.println("Finally block executed.");
}
In the example above, the `finally` block will be executed even though an exception is thrown in the `try` block.
So, the correct answer is (B) finally.
44) The
object that we throw must be of which of the following Java class type?
(A)
java.lang.throw
(B)
java.lang.catch
(C) java.lång.throws
(D)
java.lang.ThrowabIe
Explanation:
In Java, when throwing an exception, the object being thrown must be of type `java.lang.Throwable` or a subclass of `Throwable`. The most common subclasses are `Exception` (checked exceptions) and `RuntimeException` (unchecked exceptions).
So, the correct answer is (D) java.lang.Throwable.
45) In
Java, when we write data to stream, what is that stream called?
(A) output
stream
(B) input
stream
(C) data
stream
(D) line
stream
Explanation:
In Java, when you write data to a stream, it is referred to as an "output stream." An output stream is used to write data from a program to an external destination, such as a file, console, or another program.
Examples of output streams in Java include `FileOutputStream` for writing to files, `System.out` for writing to the console, and others.
So, the correct answer is (A) output stream.
46) In
Java, text files and program codes are created using which stream?
(A) byte
stream
(B) binary
stream
(C)
character stream
(D)
boolean stream
Explanation:
In Java, text files and program codes are typically created using character streams. Character streams are designed for handling character data, and they provide a higher-level abstraction compared to byte streams.
The primary classes for character streams in Java include `FileReader` and `FileWriter`. These classes are used to read and write character data from and to files.
So, the correct answer is (C) character stream.
47) In
writer class of Java, which of the following exception occurs when there is a
failed I/O operation?
(A)
FileException
(B)
InputException
(C)
OutputException
(D)
IOException
Answer: (D) IOException
Explanation:
In Java, the `java.io.Writer` class is used for writing character data. When there is a failed I/O operation during writing, an `IOException` may be thrown. `IOException` is a checked exception that represents a failure or interruption during I/O operations.
So, the correct answer is (D) IOException.
48) In
Java, FileInputStream and FileOutputStream are classes of which package that
give us the ability to read and write bytes from and into any files in the
disk?
(A)
java.input
(B)
java.output
(C)
java.file
(D)
java.io
Explanation:
In Java, `FileInputStream` and `FileOutputStream` are classes provided by the `java.io` package. These classes give you the ability to read bytes from and write bytes into any files on the disk.
- `FileInputStream`: Used for reading byte-oriented data from a file.
- `FileOutputStream`: Used for writing byte-oriented data to a file.
Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
try {
// Reading from a file using FileInputStream
FileInputStream inputStream = new FileInputStream("input.txt");
int data;
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
inputStream.close();
// Writing to a file using FileOutputStream
FileOutputStream outputStream = new FileOutputStream("output.txt");
String text = "Hello, FileOutputStream!";
byte[] byteArray = text.getBytes();
outputStream.write(byteArray);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the example above, `FileInputStream` is used to read from a file, and `FileOutputStream` is used to write to a file.
So, the correct answer is (D) java.io.
49) In
Java, which method of scanner class scans the next token of the input as line?
(A) String
next( )
(B) String
nextLine( )
(C)
hasNext( )
(D) char
hasNext( )
Explanation:
In Java's `Scanner` class, the method `nextLine()` is used to scan the next token of the input as a line. This method reads the entire line, including any spaces or tabs, until the end of the line is reached.
Example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a line of text:");
String line = scanner.nextLine();
System.out.println("You entered: " + line);
scanner.close();
}
}
In the example above, `nextLine()` is used to read the entire line of text entered by the user.
So, the correct answer is (B) String nextLine( ).
50) In
Java, scanner class can be used to perform which of the following operations?
(A) Accept
input from the keyboard
(B) Write
data into file
(C) Reading
password
(D) Count
number of character in file
Answer: (A) Accept input from the keyboard
Explanation:
In Java, the `Scanner` class is used for reading input from various sources, and one of its common use cases is to accept input from the keyboard. It provides methods to read different types of data, such as integers, floating-point numbers, and strings, from the keyboard.
Example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer:");
int num = scanner.nextInt();
System.out.println("You entered: " + num);
System.out.println("Enter a string:");
String text = scanner.next();
System.out.println("You entered: " + text);
scanner.close();
}
}
In the example above, the `Scanner` class is used to accept an integer and a string from the keyboard.
Options (B), (C), and (D) are not primary use cases of the `Scanner` class. Writing data into a file, reading passwords securely, and counting the number of characters in a file are typically done using other classes and methods.
So, the correct answer is (A) Accept input from the keyboard.