45 Java (Computer Science) questions asked in DSSSB TGT / PGT previous year papers, each with the correct answer and explanation. Read them free on UTpaper, or attempt the full papers as timed online tests.
What correction is required for following Java code snippet to compile?
int [] X = new int [10];
for (int P = 0; P<= X.length(); P++)
X [P] = 5;
AX [P] = 5 should be X (P) = 5
BP<= X.length() should be P< X.length()
CX.length() should be X.length
DP++ should be P+1
Show answerHide answer
Correct answer: (C) X.length() should be X.length
Explanation
In Java, length is a field of an array, not a method, so X.length() will not compile and must be X.length. The <= would only cause a runtime exception, not a compile error.
Consider the following Java code segment:
public class while /* line 1*/
{
public void loop ( )
{
int x = 0;
While (1)/* line-6*/
{
system. out. println("x plus one is" + (x+1)):
}
}
}
Which of the following is true ?
AThere is a syntax error in line-1
BThere are syntax errors in line- 1 and line- 6
CThere is a syntax error in line- 6
DNo syntax error
Show answerHide answer
Correct answer: (A) There is a syntax error in line-1
Explanation
while is a reserved keyword in Java, so it cannot be used as a class name. "public class while" is a syntax error on line 1.
Which of the following methods in Java Script will display a window having a dialog box with a specified message, along with an OK and CANCEL button as options?
Aprompt ()
Balert ()
Cconfirm ()
Drequest ()
Show answerHide answer
Correct answer: (C) confirm ()
Explanation
confirm() shows a dialog with a message and OK and Cancel buttons and returns true or false. alert() has only OK, and prompt() also asks for text input.
Java is a ______ language. This means that you must be explicit about what type of data you are working with.
AWeakly typed
BStrongly typed
CDynamically typed
DLoosely typed
Show answerHide answer
Correct answer: (B) Strongly typed
Explanation
Java is strongly (and statically) typed: every variable must be declared with a type, and the compiler does not allow values of incompatible types to be mixed without an explicit cast.
Q6DSSSB TGT Computer Science (Technical), 7 Aug 2021, Shift 3
What is function of javap command?
AA command for running the java compiler
BA command that disassembles java class files
CA command for running a non-optimized version of java compiler
DA command that is used to generate API-style HTML documentation
Show answerHide answer
Correct answer: (B) A command that disassembles java class files
Explanation
javap is the Java class file disassembler. It shows the fields, methods and bytecode of a .class file. javac compiles and javadoc generates HTML docs.
Q7DSSSB TGT Computer Science (Technical), 7 Aug 2021, Shift 3
Which of the following statement is/are correct regarding JAVA programming?
I. A class marked as final cannot be inherited
II. A method marked final cannot be overridden
AOnly I
BOnly II
CBoth I and II
DNeither I nor II
Show answerHide answer
Correct answer: (C) Both I and II
Explanation
In Java, a final class cannot be subclassed and a final method cannot be overridden. Both are correct.
Q8DSSSB TGT Computer Science (Technical), 7 Aug 2021, Shift 3
What is the output of the following JAVA code?
String s = "exam" + 9 + 9 + 9;
System.out.println(s);
Aexam 27
Bexam: 27
Cexam: 9
Dexam: 999
Show answerHide answer
Correct answer: (D) exam: 999
Explanation
With a String on the left, each + is string concatenation: "exam" + 9 gives "exam9", and so on, giving "exam999". The 9s are not added to 27.
Q9DSSSB TGT Computer Science (Technical), 7 Aug 2021, Shift 2
Which of the following is/are correct about java programming?
I. All functions in java must be members of some class
II. Member functions are called methods in java
AOnly I
BOnly II
CBoth I and II
DNeither I nor II
Show answerHide answer
Correct answer: (C) Both I and II
Explanation
Java has no free-standing functions: every method must belong to a class, and member functions are called methods. Both are correct.
Q10DSSSB TGT Computer Science (Technical), 7 Aug 2021, Shift 2
What is the output of the following java code?
int m = 1000;
int k = 3000;
while (++m < --k);
System.out.println(m);
AError
B1000
C2000
D4000
Show answerHide answer
Correct answer: (C) 2000
Explanation
Each test increments m and decrements k. The loop stops when m >= k, which first happens at m = 2000, k = 2000 (1000 iterations). So 2000 is printed.
Q11DSSSB TGT Computer Science (Technical), 1 Aug 2021, Shift 3
What is AJAX in ASP.NET?
AAsynchronous JavaScript and XML
BAssociated JavaScript and XML
CAsynchronous java script and HTML
DAssociated JavaScript and HTML
Show answerHide answer
Correct answer: (A) Asynchronous JavaScript and XML
Explanation
AJAX stands for Asynchronous JavaScript and XML: it updates parts of a page by exchanging data with the server in the background.
Q12DSSSB TGT Computer Science (Technical), 1 Aug 2021, Shift 3
JAVA compiler translates source code into ________.
ASymbolic code
BAssembly code
CByte code
DHigh language code
Show answerHide answer
Correct answer: (C) Byte code
Explanation
The Java compiler (javac) translates source code into platform-independent bytecode (.class files), which the JVM then executes.
Q13DSSSB TGT Computer Science (Technical), 1 Aug 2021, Shift 3
Which of the following statement(s) is/are correct regarding java programming?
I. Place a semicolon immediately after a method header.
II. Define a method outside the braces of a class definition.
AOnly I
BOnly II
CBoth I and II
DNeither I nor II
Show answerHide answer
Correct answer: (D) Neither I nor II
Explanation
Both are common errors: a semicolon after a method header ends the declaration, and in Java every method must be defined inside the class body braces. Neither statement is correct.
Q14DSSSB TGT Computer Science (Technical), 1 Aug 2021, Shift 3
What is the output of the given java code?
byte x = 64, y;
y = (byte) (x << 4);
system.out.println(y);
A0
B128
C256
D32
Show answerHide answer
Correct answer: (A) 0
Explanation
x << 4 is 64 × 16 = 1024 = 0x400 (as int). Casting to byte keeps only the low 8 bits, 0x00, so y prints 0.
Q15DSSSB TGT Computer Science (Technical), 1 Aug 2021, Shift 3
Which HTML tag is used to embed Java script scripts in a page?
A<script> tag
B<embed> tag
C<java> tag
D<enable> tag
Show answerHide answer
Correct answer: (A) <script> tag
Explanation
JavaScript is placed in a page with the <script> tag, either inline or through src.
Q16DSSSB TGT Computer Science (Technical), 1 Aug 2021, Shift 1
A java program that is embedded in HTML document and runs in the context of java capable browser is known as ________.
AApplet
BCanvas
CDoctags
DFrame Window
Show answerHide answer
Correct answer: (A) Applet
Explanation
An applet is a small Java program embedded in an HTML page and run by a Java-enabled browser.
Which among the following is the primary purpose of using interfaces in Java?
ATo avoid creating objects
BTo achieve multiple inheritance
CTo improve user experience
DTo reduce memory usage
Show answerHide answer
Correct answer: (B) To achieve multiple inheritance
Explanation
A Java class can extend only one class but can implement many interfaces. Interfaces are therefore Java's way of achieving multiple inheritance of type.
What will be the output of the following code?
class Test {
Test(int x) {
System.out.println("Parameterized Constructor");
}
Test() {
this(10);
System.out.println("Default Constructor");
}
public static void main(String[] args) {
Test obj = new Test();
}
}
AParameterized Constructor followed by Default Constructor
BCompilation Error
CDefault Constructor
DParameterized Constructor
Show answerHide answer
Correct answer: (A) Parameterized Constructor followed by Default Constructor
Explanation
new Test() calls the no-argument constructor. Its first statement, this(10), runs the parameterized constructor first, so "Parameterized Constructor" is printed and then "Default Constructor".
What will be the output of the following code?
public class ExceptionDemo {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (Exception e) {
System.out.println("Exception caught: " + e.getClass().getName());
} finally {
System.out.println("Execution completed.");
}
}
}
numbers[5] is past the end of the array, so an ArrayIndexOutOfBoundsException is thrown. getClass().getName() gives its full name, and finally always runs.
int a = 4, b = 8, c = 6;
if (a > b) {
if (a > c) {
System.out.println("a is the largest");
} else if (b > c) {
System.out.println("b is the largest");
} else {
System.out.println("c is the largest");
}
} else {
if (b > c) {
System.out.println("b is the largest");
} else {
System.out.println("c is the largest");
}
}
What is the output of the above code snippet( Assume that it is written inside main() function
)?
Ac is the largest
Bb is the largest
Ca is the largest
DCompilation error
Show answerHide answer
Correct answer: (B) b is the largest
Explanation
a > b (4 > 8) is false, so the outer else block runs. There b > c (8 > 6) is true, so "b is the largest" is printed.
Which method binding is associated with method overriding in Java?
AStatic binding
BDynamic binding
CEarly binding
DCompile-time binding
Show answerHide answer
Correct answer: (B) Dynamic binding
Explanation
Method overriding is resolved at run time from the actual object type. This is dynamic (late) binding, the basis of runtime polymorphism. Static or early binding is used for overloading, private, static and final methods.
class Person {
private String name;
public Person(String name) {
this.name = name;
}
private void displayName() {
System.out.println("Name: " + name);
}
}
public class Test {
public static void main(String[] args) {
Person p = new Person("John");
p.displayName();
}
}
What will happen when the above code is compiled and executed?
ACompilation Error: The method displayName is not visible in Test.
BRuntime Error: The method displayName cannot be called.
CThe code will compile and display Name: John.
DCompilation Error: The field name is not visible in Test.
Show answerHide answer
Correct answer: (A) Compilation Error: The method displayName is not visible in Test.
Explanation
displayName() is private in Person, so it cannot be called from class Test. The compiler reports that displayName() has private access in Person.
What will be the output of the following Java code? public class DoWhileExample {
public static void main(String[] args) {
int x = 10;
do {
System.out.println("x = " + x);
x++;
} while (x < 13);
}
}
Ax = 10
x = 11
x = 12
Bx = 10
Cx = 10
x = 11
DNo output
Show answerHide answer
Correct answer: (A) x = 10
x = 11
x = 12
Explanation
A do-while body runs before the test: it prints x = 10, 11 and 12, and stops when x becomes 13 because 13 < 13 is false.
Consider the below Code snippet:
class Calculator {
void calculate(int a, int b) {
class Multiply {
int product() {
return a * b;
}
}
Multiply multiply = new Multiply();
System.out.println("Product: " + multiply.product());
}
}
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.calculate(5, 3);
}
}
What will be the output?
AProduct: 15
BProduct: 0
CRuntime Error.
DCompilation Error: Multiply cannot be defined inside calculate.
Show answerHide answer
Correct answer: (A) Product: 15
Explanation
Java allows a local class inside a method, and it can use the method's effectively final parameters a and b. product() returns 5 × 3 = 15, so "Product: 15" is printed.
What will be the output of the following Java code? public class IfExample {
public static void main(String[] args) {
int number = 10;
if (number > 5) {
System.out.println("Number is greater than 5");
}
}
}
ANumber is less than 5
BCompilation error
CNumber is greater than 5
DNo output
Show answerHide answer
Correct answer: (C) Number is greater than 5
Explanation
number = 10, so number > 5 is true and the if block prints "Number is greater than 5".
Which of the following is the correct way to define a function in Java?
Apublic void myFunction() {}
Bfunction myFunction() {}
Cdef myFunction() {}
DPublic myFunction() {}
Show answerHide answer
Correct answer: (A) public void myFunction() {}
Explanation
In Java a method needs a return type, as in public void myFunction() {}. "function" is JavaScript syntax, "def" is Python, and "Public" (capital P) with no return type is invalid.
Consider the following Java code snippet:
class Animal {
String name;
int age;
Animal() {
this.name = "Unknown";
this.age = 0;
}
Animal(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println("Animal: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Animal a1 = new Animal();
Animal a2 = new Animal("Dog", 5);
a1.displayInfo();
a2.displayInfo();
// Error-prone code:
//1. Animal a3 = new Animal("Cat");
//2. a2.name = null; a2.displayInfo();
// 3. Animal a4 = null; a4.displayInfo();
}
}
Which of the following statements is/are true regarding the above code?
1. The Animal class supports both default and parameterized constructors.
2. If line 1 in the comment is uncommented, the code will compile and run successfully.
3. If line 2 is executed, a2.displayInfo() will print "Animal: null, Age: 5".
4. If line 3 is executed, the program will throw a NullPointerException at runtime.
A1 and 4 only
B2 only
C1,2 and 4 only
D1,3 and 4 only
Show answerHide answer
Correct answer: (D) 1,3 and 4 only
Explanation
1 is true (no-arg and two-arg constructors). 2 is false: there is no Animal(String) constructor, so it would not compile. 3 is true: concatenating null prints "null". 4 is true: calling a method on a null reference throws NullPointerException.
Which of the following demonstrates the implementation of inheritance in Java?
Aclass B inherits A {}
Bclass A contains B {}
Cclass A implements B {}
Dclass A extends B {}
Show answerHide answer
Correct answer: (D) class A extends B {}
Explanation
Java uses the keyword extends for class inheritance, e.g. class A extends B. implements is used when a class implements an interface; inherits and contains are not Java keywords.
Given the following code, what will be the result?
public class Test {
public static void main(String[] args) {
Object obj = new String("Hello");
String str = (String) obj;
System.out.println(str);
}
}
AThrows ClassCastException.
BRuntime error.
CHello will be printed.
DCompilation error.
Show answerHide answer
Correct answer: (C) Hello will be printed.
Explanation
obj actually refers to a String object, so the downcast (String) obj succeeds at run time and "Hello" is printed. ClassCastException occurs only when the object is not of the target type.
Which among the following is an example of compile-time polymorphism in Java?
AMethod overriding
BInterfaces
CAbstract classes
DMethod overloading
Show answerHide answer
Correct answer: (D) Method overloading
Explanation
Method overloading (same name, different parameter lists) is resolved by the compiler, so it is compile-time (static) polymorphism. Method overriding is resolved at run time.
Which of the following is the correct way to declare a variable in Java?
Alet x = 10;
Bx = 10;
Cvar x = 10;
Dint x = 10;
Show answerHide answer
Correct answer: (D) int x = 10;
Explanation
Java is statically typed, so a variable is declared with its type: int x = 10;. let is JavaScript, and var x = 10 works only as local type inference from Java 10, so the standard answer is int.
class Parent {
protected void protectedMethod() {
System.out.println("Protected method in Parent");
}
}
class Child extends Parent {
public void childMethod() {
protectedMethod();
}
}
public class Test {
public static void main(String[] args) {
Child child = new Child();
child.childMethod();
}
}
What will happen when the code is executed?
AThe code will compile and print 'Protected method in Parent'.
BCompilation Error: The protectedMethod is not visible in the Child class.
CCompilation Error: childMethod is not visible due to access restrictions.
DRuntime Error: Cannot access protectedMethod from the Child class.
Show answerHide answer
Correct answer: (A) The code will compile and print 'Protected method in Parent'.
Explanation
A protected member is accessible in a subclass, so Child can call protectedMethod() directly. The code compiles and prints "Protected method in Parent".
super refers to the immediate parent (superclass) object; it is used to call parent constructors and access parent methods or fields. The current object is referred to by this.
public class ExceptionTest {
public static void main(String[] args) {
try {
System.out.println("Result: " + calculate(10, 0));
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
} catch (Exception e) {
System.out.println("General exception caught: " + e.getMessage());
} finally {
System.out.println("In finally block.");
}
}
public static int calculate(int a, int b) throws Exception {
try {
return a / b;
} catch (ArithmeticException e) {
throw new Exception("Division by zero not allowed");
} finally {
System.out.println("Inner finally block executed.");
}
}
}
What will be the output of the program?
AInner finally block executed. General exception caught: / by zero In finally block.
BInner finally block executed.
General exception caught: Division by zero not allowed
In finally block.
CInner finally block executed.
Result: 0
In finally block.
DInner finally block executed.
ArithmeticException caught: / by zero
In finally block.
Show answerHide answer
Correct answer: (B) Inner finally block executed.
General exception caught: Division by zero not allowed
In finally block.
Explanation
10/0 throws ArithmeticException inside calculate, which is caught and replaced by new Exception("Division by zero not allowed"). The inner finally prints first, then main's catch (Exception) prints that message, and finally main's finally block runs.
What will be the output of the following program?
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class TestCustomException {
public static void main(String[] args) {
try {
validateAge(15);
} catch (CustomException e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally {
System.out.println("Execution finished.");
}
}
public static void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be 18 or above.");
}
System.out.println("Age is valid.");
}
}
ACaught Exception: null
Execution finished.
BCompilation error because custom exceptions cannot extend Exception.
CAge is valid.
Execution finished.
DCaught Exception: Age must be 18 or above.
Execution finished.
Show answerHide answer
Correct answer: (D) Caught Exception: Age must be 18 or above.
Execution finished.
Explanation
validateAge(15) throws CustomException with the message "Age must be 18 or above.", so "Age is valid." is never printed. The catch prints the message and the finally block prints "Execution finished.".
What is the output of the following java program?
public class Solution{
public static void main(String[] args){
int[] p = {121, 201, 017};
for(int j = 0; j < p.length; j++){
System.out.print(p[j] + " ");
}
}
}
A1121 201 17
B1121 201 15
CCompilation error
DRuntime error
Show answerHide answer
Correct answer: (B) 1121 201 15
Explanation
A leading 0 makes 017 an octal literal, which equals 15. The program prints 121 201 15, which is option (B) (its text shows a stray leading 1).
The class-loader hierarchy is Bootstrap (Primordial) → Extension → System (Application). The System ClassLoader is at the bottom, so by default it has no child class loaders.
Which of the following is an example of the fifth-generation language?
AJava
BCobol
Cprolog
DPython
Show answerHide answer
Correct answer: (C) prolog
Explanation
Fifth-generation languages, such as Prolog, solve problems using constraints and logic rules instead of step-by-step algorithms. Java, COBOL and Python are third-generation languages.
What will be the output of the following java program?
class Example
{
public static void main(String args[ ])
{
int a = 50;
double b = 50.1;
boolean x = (a == b);
System.out.println(x);
}
}
ACompilation error
BFalse
CTrue
D50
Show answerHide answer
Correct answer: (A) Compilation error
Explanation
Note: the answer key gives (A), but the code compiles. In a == b the int is widened to double, and 50.0 == 50.1 is false, so the program prints "false" (option B).
In which of the following does the JDBC type represent a 'single precision' floating point number that supports seven digits of mantissa?
ADOUBLE
BREAL
CFLOAT
DINTEGER
Show answerHide answer
Correct answer: (B) REAL
Explanation
The JDBC type REAL is a single-precision floating-point number with 7 digits of mantissa (Java float). FLOAT and DOUBLE are double precision with 15 digits.
How to use these DSSSB TGT / PGT Computer Science questions
Every question here was asked in a real DSSSB TGT / PGT paper; the paper and shift are shown on the card, and the number opens the question on its own page. Try each one before tapping Show answer, then attempt the full DSSSB TGT / PGT papers as timed tests to check your speed under exam conditions.