NPTEL Programming in Java Week 2 Assignment Answers 2024
1. Which of the following is the correct way to declare a class in Java?
a. public class MyClass {}
b. class MyClass[] {}
c. public MyClass class {}
d. MyClass public class {}
Answer :- a
2. What is the purpose of a constructor in a class?
a. To destroy objects of the class
b. To create static methods
c. To implement inheritance
d. To initialize objects of the class
Answer :- d
3. Which keyword is used in Java to refer to the current object?
a. that
b. self
c. current
d. this
Answer :- For Answers Click Here
4. Consider the following code snippet. What will be the output?
class NPTEL_W2 {
int x;
NPTEL_W2(int x) {
this.x = x;
}
void printX() {
System.out.println(this.x);
}
public static void main(String[] args) {
NPTEL_W2 obj = new NPTEL_W2(10);
obj.printX();
}
}
a. 0
b. 10
c. Compilation error
d. Runtime error
Answer :- For Answers Click Here
5. Which of the following demonstrates constructor overloading in Java?
a. Defining multiple constructors in a class with different parameter lists
b. Defining multiple methods in a class with the same name
c. Defining a constructor in a subclass
d. Using the super keyword
Answer :-
6. What is the purpose of the this keyword in the context of avoiding name space collision?
a. To call another constructor in the same class
b. To refer to the current object
c. To differentiate between instance variables and parameters with the same name
d. To import another class
Answer :-
7. Which of the following is the correct signature of the main method in Java?
a. public void main(String[] args)
b. public static void main(String[] args)
c. public static void main()
d. public main(String[] args)
Answer :-
8. Which class is used in Java to take runtime data input from the user?
a. BufferReader
b. UserInputStreamReader
c. Scanner
d. DataInputStreamReader
Answer :- For Answers Click Here
9. What is the output of the following Java code snippet? (n in output is to be assumed to be the new line character)
public class Main {
public static void main(String[] args) {
System.out.print("Hello ");
System.out.println("World");
System.out.printf("Number: %d", 10);
}
}
a. Hello WorldnNumber: 10
b. Hello WorldNumber: 10
c. Hello nWorldnNumber: 10
d. Hello WorldnNumber: 10n
Answer :-
10. How do you read a line of text from the console using the Scanner class in Java?
a. scanner.readLine()
b. scanner.nextLine()
c. scanner.getLine()
d. scanner.fetchLine()
Answer :- For Answers Click Here