Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Ejercicios de Test Java
Ejercicios de Test Java
Página 1 de 104
Resultado programa Java | Grupo 12...........................................................................................27
1) ¿Cuál será el resultado del programa?..................................................................................27
2) ¿Cuál será el resultado del programa?..................................................................................27
3) ¿Cuál será el resultado del programa?..................................................................................28
4) ¿Cuál será el resultado del programa?..................................................................................28
5) ¿Cuál será el resultado del programa?..................................................................................29
6) ¿Cuál será el resultado del programa?..................................................................................29
7) For the given code select the correct answer...........................................................................30
8) Which of the following are true about constructor declaration?.........................................................30
Resultado programa Java | Grupo 13 (Collections).............................................................................30
1) ¿Cuál será el resultado del programa?..................................................................................30
2) ¿Cuál será el resultado del programa?..................................................................................31
3) ¿Cuál será el resultado del programa?..................................................................................31
4) Which of the given choices is a possible output ?......................................................................32
5) ¿Cuál será el resultado del programa?..................................................................................32
Resultado programa Java | Set 14 (Constructors)..............................................................................33
1) ¿Cuál será el resultado del programa?..................................................................................33
2) ¿Cuál será el resultado del programa?..................................................................................33
3) ¿Cuál será el resultado del programa?..................................................................................34
5) ¿Cuál será el resultado del programa?..................................................................................35
Salida programa Java | Grupo 15 (Inner Classes)..............................................................................36
1) ¿Cuál será el resultado del programa?..................................................................................36
2) ¿Cuál será el resultado del programa?..................................................................................36
3) ¿Cuál será el resultado del programa?..................................................................................37
4) ¿Cuál será el resultado del programa??.................................................................................37
5) ¿Cuál será el resultado del programa?..................................................................................38
Salida programa Java | Grupo 16 (Threads)....................................................................................39
1)¿Cuál será el resultado del programa?...................................................................................39
2)¿Cuál será el resultado del programa?...................................................................................39
3)¿Cuál será el resultado del programa?...................................................................................40
4)¿Cuál será el resultado del programa?...................................................................................40
5)¿Cuál será el resultado del programa?...................................................................................41
Salida programa Java | Grupo 17..............................................................................................42
1) What is the output of following program?...............................................................................42
2) ¿Cuál será el resultado del programa?..................................................................................42
3) ¿Cuál será el resultado del programa?..................................................................................42
4) ¿Cuál será el resultado del programa?..................................................................................43
5) ¿Cuál será el resultado del programa?..................................................................................43
Salida programa Java | Grupo 18 (Overriding).................................................................................44
1) ¿Cuál será el resultado del programa?..................................................................................44
2) ¿Cuál será el resultado del programa?..................................................................................44
3) ¿Cuál será el resultado del programa?..................................................................................45
4) ¿Cuál será el resultado del programa?..................................................................................45
5) ¿Cuál será el resultado del programa?..................................................................................46
Salida programa Java | Grupo 19..............................................................................................46
Program 1 :...............................................................................................................46
Program 2 :...............................................................................................................47
Program 3 :...............................................................................................................47
Program 4 :...............................................................................................................48
Program 5 :...............................................................................................................48
Salida programa Java | Grupo 20 (Inheritance)................................................................................49
Program 1 :...............................................................................................................49
Program 2 :...............................................................................................................49
Program 3 :...............................................................................................................50
Program 4 :...............................................................................................................50
Program 5 :...............................................................................................................51
Resultado programa Java | Grupo 21 (Type Conversions)........................................................................51
1) ¿Cuál será el resultado del programa?..................................................................................51
Página 2 de 104
2) ¿Cuál será el resultado del programa?..................................................................................52
3) ¿Cuál será el resultado del programa?..................................................................................52
4) ¿Cuál será el resultado del programa?..................................................................................52
5) ¿Cuál será el resultado del programa?..................................................................................53
Salida programa Java | Grupo 22 (Overloading)................................................................................53
1) ¿Cuál será el resultado del programa?..................................................................................53
2) ¿Cuál será el resultado del programa?..................................................................................53
3) ¿Cuál será el resultado del programa?..................................................................................54
4) ¿Cuál será el resultado del programa?..................................................................................54
5) ¿Cuál será el resultado del programa?..................................................................................54
Salida programa Java | Grupo 23 (Inheritance)................................................................................55
1) ¿Cuál será el resultado del programa?..................................................................................55
2) ¿Cuál será el resultado del programa?..................................................................................55
3) ¿Cuál será el resultado del programa?..................................................................................56
5) ¿Cuál será el resultado del programa?..................................................................................57
Salida programa Java | Grupo 24 (Inheritance)Java Inheritance................................................................57
Question 1................................................................................................................57
Question 2................................................................................................................58
Question 3................................................................................................................58
Question 4................................................................................................................59
Question 5................................................................................................................59
Question 6................................................................................................................59
Question 7................................................................................................................60
Question 8................................................................................................................60
Question 9................................................................................................................61
Salida programa Java | Grupo 25 (Java abstract class and interface)..........................................................62
Question 1................................................................................................................62
Question 2................................................................................................................62
Question 3................................................................................................................62
Question 4................................................................................................................63
Question 4 Explicación:...................................................................................................63
Question 6................................................................................................................64
Salida programa Java | Grupo 26..............................................................................................64
Question 1: What is the output of this program?...........................................................................64
Question 2: What is the output of this program?...........................................................................65
Question 3: What is the output of this program?...........................................................................65
Question 4. What will be the output of the program?.......................................................................65
Question5. What will be the output of the program?........................................................................66
Salida programa Java | Grupo 27..............................................................................................66
Question 1. What is the output of the following?..........................................................................66
Question 2. What is the output of the following?..........................................................................67
Question 4. What is the output of the following?..........................................................................67
Question 5. What is the output of the following?..........................................................................67
Salida programa Java| Grupo 28...............................................................................................68
Question 1. What is the output of the following question?.................................................................68
Question 2. What is the output of the following question?.................................................................68
Question 4. What is the output of the following question?.................................................................69
Question 5. What is the output of the following question?.................................................................69
Resultado programa Java | Grupo 29...........................................................................................70
Question 1. What is the output of the following question?.................................................................70
Question 3. What is the output of the following question?.................................................................70
Question 4. What is the output of the following question?.................................................................71
Question 5. What is the output of the following question?.................................................................71
Resultado programa Java | Grupo 30...........................................................................................71
Question 1 What is the output of this program ?...........................................................................71
Question. 4 What is the output?...........................................................................................72
Question. 5 what is output of this program?...............................................................................73
Resultado programa Java | Grupo 31 (Arrays en Java)..........................................................................73
Página 3 de 104
1. ¿Cuál será el resultado del programa?..................................................................................73
2. ¿Cuál será el resultado del programa?..................................................................................73
3. What will be the output of the following program?......................................................................74
4. ¿Cuál será el resultado del programa?..................................................................................74
5. ¿Cuál será el resultado del programa?..................................................................................74
Resultado programa Java | Grupo 32 (Arrays en Java)..........................................................................75
Question 1. What is the output of following program?......................................................................75
Question 2. What is the output of following program?......................................................................75
Question 3. What is the output of following program?......................................................................76
Question 4. What is the output of following program?......................................................................76
Question 5. What is the output of following program?......................................................................76
Resultado programa Java | Grupo 33 (Collections).............................................................................77
1. What is the output of following Java Program?..........................................................................77
2. What is the output of following Java Program?..........................................................................77
3. What is the output of following Java Program?..........................................................................78
4. What is the Output of following Java Program?..........................................................................78
5. What is the Output of following Java Program?..........................................................................78
Resultado programa Java | Grupo 34 (Collections).............................................................................79
1. What is the Output of following Java Program?..........................................................................79
2. What is the output of following Java Program?..........................................................................79
3. What is the Output of following Java Program?..........................................................................80
4. What is the Output of following Java Program?..........................................................................80
Resultado programa Java | Grupo 35 (Decision Making).........................................................................81
1. What will be the output of the following program?......................................................................81
2. What will be the output of the following program?......................................................................81
3. What will be the output of the following program?......................................................................82
4.What will be the output of the following program?.......................................................................82
5. What will be the output of the following program?......................................................................82
6. What will be the output of the following program?......................................................................83
7. What will be the output of the following program?......................................................................84
7. What will be the output of the following program?......................................................................84
8. What will be the output of the following program?......................................................................84
Resultado programa Java | Grupo 36 (do-while loop)...........................................................................85
1. ¿Cuál será el resultado del programa?..................................................................................85
2. ¿Cuál será el resultado del programa?..................................................................................86
3. ¿Cuál será el resultado del programa?..................................................................................86
4. ¿Cuál será el resultado del programa?..................................................................................86
5. ¿Cuál será el resultado del programa?..................................................................................87
Resultado programa Java | Grupo 37 (If-else).................................................................................87
1. ¿Cuál será el resultado del programa?..................................................................................87
2. ¿Cuál será el resultado del programa?..................................................................................87
3. ¿Cuál será el resultado del programa?..................................................................................88
4. ¿Cuál será el resultado del programa?..................................................................................88
5. ¿Cuál será el resultado del programa?..................................................................................88
Resultado programa Java | Grupo 38 (Arrays)..................................................................................89
Question 1. What is the output of this question...........................................................................89
Question 2. What is the output of this question?..........................................................................89
Question 3. What is the output of this question?..........................................................................89
Question 4. What is the output of this question ?.........................................................................90
Question 5. What is the output of this question?..........................................................................90
Resultado programa Java | Grupo 39 (throw keyword)...........................................................................90
What will be the output of the following program?.........................................................................90
2. What will be the output of the following program?......................................................................91
3. What will be the output of the following program?......................................................................91
4. What will be the output of the following program?......................................................................91
5. What will be the output of the following program?......................................................................92
Resultado programa Java | Grupo 40 (for loop)................................................................................92
1 what will be the output of the following program?.......................................................................92
Página 4 de 104
2. what will be the output of the following program?......................................................................92
3. what will be the output of the following program?......................................................................93
4. what will be the output of the following program?......................................................................93
5. what will be the output of the following program?......................................................................93
Resultado programa Java | Grupo 41 (try-catch)...............................................................................94
1. What will be the output of the following program?......................................................................94
2. What will be the output of the following program?......................................................................94
3. What will be the output of the following program?......................................................................95
4. What will be the output of the following program?......................................................................95
5. What will be the output of the following program?......................................................................95
Resultado programa Java | Grupo 42 (Arrays)..................................................................................96
Question 1. What is the output of this question?..........................................................................96
Question 2. What is the output of this question?..........................................................................96
Question 3. Which of the following declarations are invalid?..............................................................97
Question 4. Which of the following lines give error?......................................................................97
Question 5. What is the output of this question?..........................................................................97
Resultado programa Java | Grupo 43 (Conditional statements & Loops)..........................................................98
1. What will be the output of the following program?......................................................................98
2. What will be the output of the following program?......................................................................98
3. What will be the output of the following program?......................................................................98
4. What will be the output of the following program?......................................................................99
5. What will be the output of the following program?......................................................................99
Resultado programa Java | Grupo 44 (throws keyword)..........................................................................99
1. What will be the output of the following program?.....................................................................100
2. What will be the output of the following program?.....................................................................100
3. What will be the output of the following program?.....................................................................100
4. What will be the output of the following program?.....................................................................101
5. What will be the output of the following program?.....................................................................101
Resultado programa Java | Grupo 45 (static and instance variables)..........................................................102
Question 1. What is the output of this question?.........................................................................102
Question 2. What is the output of this question?.........................................................................102
Question 3. What is the output of this question?.........................................................................102
Question 4. What is the output of this question?.........................................................................103
Question 5. What is the output of this question?.........................................................................103
Página 5 de 104
Salida programa Java | Grupo 1.
Nivel de dificultad: rookie.
class Test {
protected int x, y;
}
class Main {
public static void main(String args[]) {
Test t = new Test();
System.out.println(t.x + " " + t.y);
}
}
Resultado:
0 0
Explicación:
En java, un miembro protegido es accesible en todas las clases del el mismo paquete y en las clases heredadas de
otros paquetes, ya que las clases test y main están en el mismo paquete, no hay problemas de acceso en el programa.
También los constructores por defecto inicializarán las variables enteras en java. Esto es por lo cual tenemos la
salida 0 . 0
Programa 2.
// filename Test.java
class Test {
public static void main(String[] args) {
for(int i = 0; 1; i++) {
System.out.println("Hola");
break; } } }
Resultado:
Compiler Error
Explicación:
Hay un error en la comprobación de la condición para la ejecución de la condición del bucle. Java difiere de C++ o
C. En C++ considera todos los valores diferentes de cero como true y 0 como falso.
Un valor entero o una expresión que dé un valor entero no puede ser colocado en un sitio en el cual se expera un
valor booleano.
// filename Test.java
class Test {
public static void main(String[] args) {
for(int i = 0; true; i++) {
System.out.println("Hola");
break;
}
}
} // Resultado: Hola
Programa 3.
// filename Main.java
class Main {
public static void main(String args[]) {
System.out.println(fun()); }
int fun() {
return 20;
}
}
Resultado:
Página 6 de 104
Compiler Error
Explicación:
Como en C++, en Java, métodos no estáticos no pueden ser llamados en en un método estático. Si hacemos fun() estático,
entonces el programa se compila sin errores.
Aquí está el programa corregido.
/ filename Main.java
class Main {
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
return 20;
}
}
// Resultado: 20
Programa 4.
// filename Test.java
class Test {
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
static int x= 0;
return ++x;
}
}
Resultado:
Compiler Error
Explicación:
A diferencia de C++, Las variables estáticas locales no están permitidas en Java.
Página 7 de 104
Question 1.
package main;
class Base { public void Print() { System.out.println("Base "); } }
class Derived extends Base { public void Print() { System.out.println("Derived"); } }
class Main{ public static void DoPrint( Base o ) { o.Print(); }
public static void main(String[] args) { Base x = new Base(); //Constructor
Base y = new Derived();
Derived z = new Derived();
DoPrint(x);
DoPrint(y);
DoPrint(z); } }
Resultado:
Base
Derived
Derived
Explicación:
Predecir la primera línea de la salida es fácil. Creamos un objeto del tipo Base y llamamos a DoPrint(). DoPrint
llama a la función print y así obtenemos la primera línea.
DoPrint(y) produce la segunda línea de salida. Como en C++, asignar una referencia de clase derivada a una
referencia de clase base está permitido en Java. Por lo tanto la expresión Base y = new Derived() es un sentencia
válida en Java. En DoPrint(), o comienza referiendo al mismo objeto que el referido por y. Así que cuando llamamos
a o.print(), el método print() de la clase derivada es llamado debido a un polimorfismo en tiempo de ejecución
presente por defecto en Java.
DoPrint(z) produce la tercera línea de la salida, nosotros pasamos una referencia del tipo derivado el método
print() de la clase derivada es llamado de nuevo. El punto a tener en cuenta aquí es: unlike C++, object slicing no
ocurre en Java, porque los tipos no-primitivos son siempre asignados por referencia.
Question 2.
package main;
// filename Main.java
class Point {
protected int x, y;
Compiler Error
Explicación:
En este ejemplo no hay problemas por los permisos de acceso porque Test y Main están en mismo paquete y los
miembros protegidos de la clase pueden ser accedidos en otras del mismo paquete.
El problema con el código es: No hay un constructor por defecto en Point.. Like C++, si escribimos nuestro propio
constructor parametrizado entonces el compilador de Java no crea el constructor por defecto.
Dos cambios en la clase punto que pueden arreglar el problema.
Eliminar el constructor parametrizado.
Añadir un constructor sin parámetros
// filename: Test1.java
Página 8 de 104
class Test {
int x = 10;
public static void main(String[] args) {
Test t = new Test();
System.out.println(t.x);
}
}
Resultado:
10
Explicación.
El programa funciona bien e imprime 10. En java los miembros de unamembers can initialized with declaration of
class. This initialization works well when the initialization value is available and the initialization can be put
on one line (See this for more details). For example, the following program also works fine.
Question 2.
// filename: Test2.java
class Test {
int y = 2;
int x = y+2;
public static void main(String[] args) {
Test m = new Test();
System.out.println("x = " + m.x + ", y = " + m.y);
}
}
Resultado:
x = 4, y = 2
explicación:
Output of the above program is “x = 4, y = 2”. y is initialized first, then x is initialized as y + 2. So the value
of x becomes 4.
What happen when a member is initialized in class declaration and constructor both? Consider the following program.
Question 3.
// filename: Test3.java
public class Test
{
int x = 2;
Test(int i) { x = i; }
public static void main(String[] args) {
Test t = new Test(5);
System.out.println("x = " + t.x);
}
}
Resultado:
x = 5
Explicación:
La salida del programa es “x = 5”. The initialization with class declaration in Java is like
initialization using Initializer List in C++. So, in the above program, the value assigned inside the
constructor overwrites the previous value of x which is 2, and x becomes 5.
Question 4.
// filename: Test4.java
class Test1 {
Test1(int x) {
Página 9 de 104
System.out.println("Constructor called " + x); } }
Explicación:
First t2 object is instantiated in the main method. As the order of initialization of local variables comes first
than the constructor, first the instance variable (t1), in the class Test2 is allocated to the memory. In this line
a new Test1 object is created, constructor is called in class Test1 and ‘Constructor called 10’ is printed. Next
the constructor of Test2 is called and again a new object of the class Test1 is created and ‘Constructor called 5’
is printed.
class Base {
protected void foo() {}
}
class Derived extends Base {
void foo() {}
}
public class Main {
public static void main(String args[]) {
Derived d = new Derived();
d.foo();
}
}
Resultado:
Compiler Error
Explicación:
foo() is protected in Base and default in Derived. Default access is more restrictive. When a derived class
overrides a base class function, more restrictive access can’t be given to the overridden function. If we make
foo() public, then the program works fine without any error. The behavior in C++ is different. C++ allows to give
more restrictive access to derived class methods.
Question 2.
// file name: Main.java
class Complex {
private double re, im;
public String toString() {
return "(" + re + " + " + im + "i)";
}
Complex(Complex c) {
re = c.re;
im = c.im;
}
}
Página 10 de 104
System.out.println(c2);
}
}
Resultado:
Compiler Error in line “Complex c1 = new Complex();”
Explicación:
In Java, if we write our own copy constructor or parameterized constructor, then compiler doesn’t create the
default constructor. This behavior is same as C++.
Please write comments if you find anything incorrect, or you want to share more information about the topic
discussed above.
Explicación:
In case of method overloading, the most specific method is chosen at compile time. As ‘java.lang.String’ is a more
specific type than ‘java.lang.Object’. In this case the method which takes ‘String’ as a parameter is choosen.
Program 2:
// Main.java
public class Main
{
public static void gfg(String s) { System.out.println("String"); }
public static void gfg(Object o) { System.out.println("Object"); }
public static void gfg(Integer i) { System.out.println("Integer"); }
public static void main(String args[]) { gfg(null); } } //end class
Resultado:
Compile Error at line 19.
Explicación:
In this case of method Overloading, the most specific method is choosen at compile time.
As ‘java.lang.String’ and ‘java.lang.Integer’ is a more specific type than ‘java.lang.Object’,but between
‘java.lang.String’ and ‘java.lang.Integer’ none is more specific. In this case the Java is unable to decide which
method to call.
Program 3:
// Main.java
public class Main
{ public static void main(String args[]) {
String s1 = "abc";
String s2 = s1;
s1 += "d";
System.out.println(s1 + " " + s2 + " " + (s1 == s2));
StringBuffer sb1 = new StringBuffer("abc");
StringBuffer sb2 = sb1;
sb1.append("d");
System.out.println(sb1 + " " + sb2 + " " + (sb1 == sb2)); }
} //end class
Resultado:
abcd abc false
abcd abcd true
Página 11 de 104
Explicación:
In Java, String is immutable and string buffer is mutable.
So string s2 and s1 both pointing to the same string abc. And, after making the changes the string s1 points to
abcd and s2 points to abc, hence false. While in string buffer, both sb1 and sb2 both point to the same object.
Since string buffer are mutable, making changes in one string also make changes to the other string. So both string
still pointing to the same object after making the changes to the object (here sb2).
Program 4:
// Main.java
public class Main
{
public static void main(String args[])
{
short s = 0;
int x = 07;
int y = 08;
int z = 112345;
s += z;
System.out.println("" + x + y + s);
}
} //end class
Resultado:
Compile Error at line 8
Explicación:
1. In Line 12 The “” in the println causes the numbers to be automatically cast as strings. So it doesn’t do
addition, but appends together as string.
2. In Line11 the += does an automatic cast to a short. However the number 123456 can’t be contained within a short,
so you end up with a negative value (-7616).
3. Those other two are red herrings however as the code will never compile due to line 8. Any number beginning with
zero is treated as an octal number (which is 0-7).
Resultado:
a
b
c
Explicación:
While creating a new object of ‘Third’ type, before calling the default constructor of Third class, the default
constructor of super class is called i.e, Second class and then again before the default constructor of super
class, default constructor of First class is called. And hence gives such output.
Programa 2:
class First
{
int i = 10;
public First(int j)
{
System.out.println(i);
this.i = j * 10;
}
Página 12 de 104
}
Resultado:
10
200
400
Explicación:
Since in ‘Second’ class it doesn’t have its own ‘i’, the variable is inherited from the super class. Also, the constructor of
parent is called when we create an object of Second.
Programa 3:
import java.util.*;
class I
{
public static void main (String[] args)
{
Object i = new ArrayList().iterator();
System.out.print((i instanceof List) + ", ");
System.out.print((i instanceof Iterator) + ", ");
System.out.print(i instanceof ListIterator);
}
}
Resultado:
false, true, false
Explicación:
The iterator() method returns an iterator over the elements in the list in proper sequence, it doesn’t return a
List or a ListIterator object. A ListIterator can be obtained by invoking the listIterator method.
Programa 4:
Página 13 de 104
Resultado:
Run Time Exception
Explicación:
A) 20
B) 100
C) 1000
D) 2
Answer :
A) 20
Explicación:
Here the class instance variable name(num) is same as calc() method local variable name(num). So for referencing class
instanc
variable from calc() method, this keyword is used. So in statement this.num = num * 10, num represents local variable of
the method whose value is 2 and this.num represents class instance variable whose initial value is 100. Now in
printNum() method, as it has no local variable whose name is same as class instance variable, so we can directly use num
to reference instance variable, although this.num can be used.
Programa 2:
public class MyStuff
{
String name;
MyStuff(String n) { name = n; }
@Override
public boolean equals(Object obj)
{
MyStuff m = (MyStuff) obj;
if (m.name != null) { return true; }
return false;
}
Página 14 de 104
}
Options :
A) The output is true and MyStuff fulfills the Object.equals() contract.
B) The output is false and MyStuff fulfills the Object.equals() contract.
C) The output is true and MyStuff does NOT fulfill the Object.equals() contract.
D) The output is false and MyStuff does NOT fulfill the Object.equals() contract.
Answer :
C) The output is true and MyStuff does NOT fulfill the Object.equals() contract.
Explicación:
As equals(Object obj) method in Object class, compares two objects on the basis of equivalence relation. But here
we are just confirming that the object is null or not, So it doesn’t fulfill Object.equals() contract. As m1 is not
null, true will be printed.
Programa 3:
class Alpha
{
public String type = "a ";
public Alpha() { System.out.print("alpha "); }
}
void go()
{
type = "b ";
System.out.print(this.type + super.type);
}
Respuesta
A) alpha beta b b
Explicación:
The statement new Beta().go() executes in two phases. In first phase Beta class constructor is called. There is no
instance member present in Beta class. So now Beta class constructor is executed. As Beta class extends Alpha
class, so call goes to Alpha class constructor as first statement by default(Put by the compiler) is super() in the
Beta class constructor. Now as one instance variable(type) is present in Alpha class, so it will get memory and now
Alpha class constructor is executed, then call return to Beta class constructor next statement. So alpha beta is
printed.
In second phase go() method is called on this object. As there is only one variable(type) in the object whose value
is a. So it will be changed to b and printed two times. The super keyword keyword here is of no use.
Programa 4:
public class Test
{
public static void main(String[] args)
{
StringBuilder s1 = new StringBuilder("Java");
String s2 = "Love";
s1.append(s2);
s1.substring(4);
int foundAt = s1.indexOf(s2);
System.out.println(foundAt);
}
}
Página 15 de 104
Options :
A) -1
B) 3
C) 4
D) A StringIndexOutOfBoundsException is thrown at runtime.
Respuesta
C) 4
Explicación:
append(String str) method,concatenate the str to s1. The substring(int index) method return the String from the
given index to the end. But as there is no any String variable to store the returned string,so it will be
destroyed.Now indexOf(String s2) method return the index of first occurrence of s2. So 4 is printed as
s1=”JavaLove”.
Programa 5:
class Writer
{
public static void write()
{
System.out.println("Writing...");
}
}
class Author extends Writer
{
public static void write()
{
System.out.println("Writing book");
}
}
A) Writing…
B) Writing book
C) Writing code
D) Compilation fails
Answer :
B) Writing book
Explicación:
Since static methods can’t be overridden, it doesn’t matter which class object is created. As a is a Author
referenced type, so always Author class method is called. If we remove write() method from Author class then Writer
class method is called, as Author class extends Writer class.
Programa 1:
class GfG
{
public static void main(String args[])
Página 16 de 104
{
String s1 = new String("ElCaminoDe");
String s2 = new String("ElCaminoDe");
if (s1 == s2)
System.out.println("Equal");
else
System.out.println("Not equal");
}
}
Resultado:
Not equal
Explicación:
Since, s1 and s2 are two different objects the references are not the same, and the == operator compares object
reference. So it prints “Not equal”, to compare the actual characters in the string .equals() method must be used.
Programa 2:
class Person
{
private void who()
{
System.out.println("Inside private method Person(who)");
}
Página 17 de 104
Explicación:
Static binding (or compile time) happens for static methods. Here p.whoAmI() calls the static method so it is called
during compile time hence results in static binding and prints the method in People class.
Whereas p.whoAreYou() calls the method in Kid class since by default Java takes it as a virual method i.e, dynamic
binding.
Programa 3:
class GfG
{
public static void main(String args[])
{
try
{
System.out.println("First statement of try block");
int num=45/3;
System.out.println(num);
}
catch(Exception e)
{
System.out.println("Gfg caught Exception");
}
finally
{
System.out.println("finally block");
}
System.out.println("Main method");
}
}
Resultado:
First statement of try block
15
finally block
Main method
Explicación:
Since there is no exception, the catch block is not called, but the finally block is always executed
after a try block whether the exception is handled or not.
Programa 4:
class One implements Runnable
{
public void run()
{
System.out.print(Thread.currentThread().getName());
}
}
class Two implements Runnable
{
public void run()
{
new One().run();
new Thread(new One(),"gfg2").run();
new Thread(new One(),"gfg3").start();
}
}
class Three
{
public static void main (String[] args)
{
new Thread(new Two(),"gfg1").start();
}
}
Resultado:
gfg1gfg1gfg3
Página 18 de 104
Explicación:
Initially new Thread is started with name gfg1 then in class Two the first run method runs the thread with the name
gfg1, then after that a new thread is created calling run method but since a new thread can be created by calling start
method only so the previous thread does the action and again gfg1 is printed.Now a new thread is created by calling the
start method so a new thread starts with gfg3 name and hence prints gfg3.
Programa 1:
class Gfg
{
// constructor
Gfg()
{
System.out.println("ElCaminoDe");
}
static Gfg a = new Gfg(); //line 8
Programa 2:
class Gfg
{
static int num;
static String mystr;
// constructor
Gfg()
{
num = 100;
mystr = "Constructor";
}
Página 19 de 104
{
Gfg a = new Gfg();
System.out.println("Value of num = " + a.num);
System.out.println("Value of mystr = " + a.mystr);
}
}
Resultado:
Static Block 1
Static Block 2
Value of num = 100
Value of mystr = Constructor
Explicación:
Static block gets executed when the class is loaded in the memory. A class can have multiple Static blocks, which are
executed in the same sequence in which they have been written into the Programa.
Note: Static Methods can access class variables without using object of the class. Since constructor is called when a new
instance is created so firstly the static blocks are called and after that the constructor is called. If we would have run
the same Programa without using object, the constructor would not have been called.
Programa 3:
class superClass
{
final public int calc(int a, int b)
{
return 0;
}
}
class subClass extends superClass
{
public int calc(int a, int b)
{
return 1;
}
}
public class Gfg
{
public static void main(String args[])
{
subClass get = new subClass();
System.out.println("x = " + get.calc(0, 1));
}
}
Resultado:
Compilation fails.
Explicación:
The method calc() in class superClass is final and so cannot be overridden.
Programa 4:
public class Gfg
{
public static void main(String[] args)
{
Integer a = 128, b = 128;
System.out.println(a == b);
Página 20 de 104
the expected output. The range of IntegerCache can be observed from the source code of the IntegerCache class.
Please refer this for details.
In Java, object destruction is taken care by the Garbage Collector module and the objects which do not have any
references to them are eligible for garbage collection. Below are some important output questions on Garbage collection.
Programa 1 :
public class Test
{
public static void main(String[] args) throws InterruptedException
{
String str = new String("ElCaminoDe");
System.out.println("end of main");
}
@Override
protected void finalize()
{
System.out.println("finalize method called");
}
}
Resultado:
end of main
Explicación:
We know that finalize() method is called by Garbage Collector on an object before destroying it. But here, the trick is
that the str is String class object, not the Test class. Therefore, finalize() method of String class(if overridden in
String class) is called on str. If a class doesn’t override finalize method, then by default Object class finalize() method
is called.
Programa 2 :
public class Test
{
public static void main(String[] args) throws InterruptedException
{
Test t = new Test();
System.out.println("end main");
Página 21 de 104
}
@Override
protected void finalize()
{
System.out.println("finalize method called");
System.out.println(10/0);
}
}
public class Test
{
public static void main(String[] args) throws InterruptedException
{
Test t = new Test();
System.out.println("end main");
}
@Override
protected void finalize()
{
System.out.println("finalize method called");
System.out.println(10/0);
}
}
Resultado:
finalize method called
end main
Explicación:
When Garbage Collector calls finalize() method on an object, it ignores all the exceptions raised in the method and
Programa will terminate normally.
Programa 3 :
public class Test
{
static Test t ;
Página 22 de 104
// calling garbage collector
System.gc(); // line 24
@Override
protected void finalize()
{
count++;
t = this; // line 38
Resultado:
finalize method called 1 times
Explicación:
After execution of line 12, t1 becomes eligible for garbage collection. So when we call garbage collector at line 15,
Garbage Collector will call finalize() method on t1 before destroying it. But in finalize method, in line 38, we are again
referencing the same object by t, so after execution of line 38,this object is no longer eligible for garbage collection.
Hence, Garbage Collector will not destroy the object.
Now again in line 21, we are making same object eligible for garbage collection one more time. Here, we have to clear
about one fact about Garbage Collector i.e. it will call finalize() method on a particular object exactly one time. Since on
this object, finalize() method is already called, so now Garbage Collector will destroy it without calling finalize() method
again.
Programa 4 :
public class Test
{
public static void main(String[] args)
{
// How many objects are eligible for
// garbage collection after this line?
m1(); // Line 5
}
Question :
How many objects are eligible for garbage collection after execution of line 5 ?
Answer :
2
Explicación:
Since t1 and t2 are local objects of m1() method, so they become eligible for garbage collection after complete execution
of method unless any of them is returned.
Programa 5 :
public class Test
{
public static void main(String [] args)
{
Test t1 = new Test();
Test t2 = m1(t1); // line 6
Página 23 de 104
Test t3 = new Test();
t2 = t3; // line 8
public Base()
{
data = 5;
}
a) 6
b) 5
c) Compile time error
d) Run time error
Respuesta:
(c)
Explicación:
Página 24 de 104
When overriding a method of superclass, the method declaration in subclass cannot be more restrictive than that
declared in the superclass.
Question 2 :
public class Test
{
private int data = 5;
Question 3:
public class Base
{
private int multiplier(int data)
{
return data*5;
}
}
a) 125
b) 25
c) Runtime error
d) Compile time error
Respuesta:
Página 25 de 104
(d)
Explicación:
Since the method multiplier is marked as private, it isn’t inherited and therefore is not visible to the Derived.
Question 4:
Answer:
(d)
Explicación:
Statement (d) is false because finally blocks can exist only if it succeeds try or a catch block. Using a finally block without
try block would give a compile time error.
Question 5:
import java.io.IOException;
import java.util.EmptyStackException;
a) 12345
b) 15
c) 135
d) 145
Answer
(d)
Explicación:
The catch statements are written in the order: more specific to more general. In the code above, a new
exception of type Exception is thrown. First the code jumps to first catch block to look for exception
handler. But since the IOException is not
of the same type it is moves down to second catch block and finally to the third, where
the exception is caught and 4 is printed. Therefore, the answer is 145, as the order
of execution in terms of blocks is: try->catch->finally.
Question 6:
public class javaclass
Página 26 de 104
{
static
{
System.out.printf("%d", 1);
}
static
{
System.out.printf("%d", 2);
}
static
{
System.out.printf("%d", 3);
}
private static int myMethod()
{
return 4;
}
private int function()
{
return 5;
}
a) 123
b) 213
c) 132
d) 321
Answer:
(c)
Explicación:
Página 27 de 104
The parent thread waits for the newly created thread to complete using join. join() method allows one thread to wait
until another thread completes its execution. So, parent thread prints 1 and wait for the child thread to complete. The
child thread prints 3 on console and finally the parent thread prints 2.
a) Compilation error
b) 1020
c) 101520
d) None of the above
Answer:
(a)
Explicación:
A non-static variable can not be accessed in static nested inner class. “Nested” cannot access non-static variables[variable s
in this case]. Therefore the error:
10: error: non-static variable s cannot be referenced from a static context
System.out.println(temp + s + value);
^
import java.io.*;
public class Test
{
public void display() throws IOException
{
System.out.println("Test");
}
a) Test
b) Derived
c) Compilation error
d) Runtime error
Ans:
Página 28 de 104
(b)
Explicación:
If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception
but cannot declare parent exception.
a) Compilation error
b) Runtime error
c) Test
d) Test Test
Ans:
(d)
Explicación:
test.run() executes the run method. test.start() creates a new thread and executes the overriden run method of the
Thread class. The Thread.start() method always starts a new thread, and the entry point for this thread is the run()
method. If you are calling run() directly it will execute in the same thread BUT it is always recommendable logically
calling Thread.start() to start a new thread of execution followed by the run() method.
a) ElCaminoDe
b) Geeks for Geeks
c) GFG
d) None of the above
Ans:
(b)
Explicación:
Página 29 de 104
== operator checks if two variable refer to the same object. Here a and b
refers to two different objects. ?: is another form of if else statement that could be read as, condition : if true then do
this : else do this.
a) ElCaminoDe
b) GFG
c) Compilation error
d) None of the above
Ans:
(c)
Explicación:
Constructors cannot be enclosed in try/catch block.
Ans: (b)
Explicación: Access modifier of NestedInterface can only be public. Therefore the error:
4: error: illegal combination of modifiers: public and protected
protected interface NestedInterface
^
1 error
Ans:
(d)
Explicación:
Constructors allows a sequential access of data between threads.
Página 30 de 104
Resultado programa Java | Grupo 13 (Collections).
Prerequisito – Collections in Java
import java.util.*;
System.out.println("\n");
}
}
a) 11 10 22 5 12 2
b) 2 12 5 22 10 11
c) 2 5 10 11 12 22
d) 22 12 11 10 5 2
Answer:
(c)
Explicación:
Priority queue always outputs the minimum element from the queue when remove() method is called, no matter what
the sequence of input is.
treeSet.add("Geeks");
treeSet.add("for");
treeSet.add("Geeks");
treeSet.add("ElCaminoDe");
System.out.println("\n");
}
}
a) Geeks for Geeks ElCaminoDe
b) Geeks for ElCaminoDe
c) Geeks ElCaminoDe for
d) for ElCaminoDe Geeks
Ans.
Página 31 de 104
(c)
Explicación:
A TreeSet sorts the data in ascending order that is inserted in it. Therefore, the output string contains all the strings
arranged in ascending order. A TreeSet does not contain any duplicate element as it is a Grupo. So in the output, there is just
a single occurance of string ‘Geeks’.
list1.removeAll(list2);
System.out.println();
}
}
Explicación:
list1.removeAll(list2) function deletes all the occurance of string in list2 from list1. Here, the string ‘Geeks’ appears in
list2, so all the nodes of linked list in list1 that contains ‘Geeks’ as its data is removed from list1.
System.out.println(hashSet);
}
}
Página 32 de 104
Answer.
(b)
Explicación:
A HashSet is a Grupo and as a Grupo doesn’t contain any duplicate element therefore, the string ‘Geeks’ appears only
once in the output.
while (iter.hasNext())
System.out.printf(iter.next() + " ");
System.out.println();
}
}
Explicación:
An iterator made for iterating over Integer cannot be used to iterate over String data type. Corrected program :
https://ide.ElCaminoDe.org/DgeN0P
to contribute, you can also write an article using contribute.ElCaminoDe.org or mail your article to contribute@ElCaminoDe.org.
See your article appearing on the ElCaminoDe main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
class Helper
{
private int data;
private Helper()
{
data = 5;
}
}
public class Test
{
public static void main(String[] args)
{
Helper help = new Helper();
System.out.println(help.data);
}
}
Página 33 de 104
a) Compilation error
b) 5
c) Runtime error
d) None of these
Ans.
(a)
Explicación:
A private constructor cannot be used to initialize an object outside the class that it is defined within because it is no
longer visible to the external class.
try
{
public Test()
{
Thread.sleep(5000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
class Temp
{
private Temp(int data)
{
System.out.printf(" Constructor called ");
}
protected static Temp create(int data)
{
Temp obj = new Temp(data);
return obj;
}
public void myMethod()
{
System.out.printf(" Method called ");
}
}
Página 34 de 104
public class Test
{
public static void main(String[] args)
{
Temp obj = Temp.create(20);
obj.myMethod();
}
}
Explicación:
When a constructor is marked as private, the only way to create a new object of that class from some external class is
using a method that creates a new object, as defined above in the Programa. The method create() is responsible for
creation of Temp object from some other external class. Once the object is created, its method can be invoked from the
class in which the object is created.
4) Whats is the output of the following Programa?
a) 12345
b) Compilation error
c) 15
d) Runtime error
Answer
(a)
Explicación:
Constructors can be chained and overloaded. When Test() is called, it creates another Test object calling the constructor
Test(int temp).
Página 35 de 104
class Base
{
public static String s = " Super Class ";
public Base()
{
System.out.printf("1");
}
}
public class Derived extends Base
{
public Derived()
{
System.out.printf("2");
super();
}
Ans.
(c)
Explicación:
Constructor call to super class must be the first statement in the constructor of the Derived class.
private
}
a) 15
b) 9
c) 5
d) Compilation Error
Página 36 de 104
Ans.
(d)
Explicación:
static inner classes cannot access non-static fields of the outer class.
a) Compilation error
b) Runtime Error
c) 200
d) None of the above
Ans.
(c)
Explicación:
LocalClass() method defines a local inner class. This method creates an object of class Inner and return the value of the
variable data that resides within it.
Página 37 de 104
}
a) 25
b) Compilation error
c) 20
d) Runtime error
Ans.
(b)
Explicación:
the method getData() is undefined in Anonymous class which causes the compilation error.
class Inner
{
private int data = 20;
private int getData()
{
return data;
}
public void main(String[] args)
{
Inner inner = new Inner();
System.out.println(inner.getData());
}
}
private int getData()
{
return data;
}
public static void main(String[] args)
{
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
System.out.printf("%d", outer.getData());
inner.main(args);
}
}
a) 2010
b) 1020
c) Compilation Error
d) None of these
Ans.
(c)
Explicación:
Inner class defined above though, have access to the private variable data of the Outer class, but declaring a variable
data inside an inner class makes it specific to the Inner class with no conflicts in term of variable declaration. For more
see Shadowing
interface OuterInterface
{
public void InnerMethod();
public interface InnerInterface
{
public void InnerMethod();
Página 38 de 104
}
}
public class Outer implements OuterInterface.InnerInterface, OuterInterface
{
public void InnerMethod()
{
System.out.println(100);
}
a) 100
b) Compilation Error
c) Runtime Error
d) None of the above
Ans.
(a)
Explicación:
Nested Interfaces are defined in java. As both the interfaces has declaration of InnerMethod(), implementing it once
works for both the InnerInterface and OuterInterface.
This article is contributed by Mayank Kumar. If you like ElCaminoDe and would like to contribute, you can also write an
article using contribute.ElCaminoDe.org or mail your article to contribute@ElCaminoDe.org. See your article appearing on
the ElCaminoDe main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed
above.
thread.start();
System.out.printf("Geeks ");
try
{
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("for ");
}
Página 39 de 104
}
a) GFG Geeks Geeks for
b) Geeks GFG Geeks for
c) Either a or b
d) Both a and b together
Ans.
(c)
Explicación:
From the statement “thread.start()”, we have two threads Main thread and “thread” thread. So either “GFG” can be
printed or “Geeks”, depend on which thread, thread scheduler schedule.
For (a), the parent thread after calling start() method is paused and the thread scheduler schedules the child thread
which then completes its execution. Following this, the parent thread is scheduled. For (b), the parent thread calls
start() method but continues its execution
and prints on the console. When join() method is called, the parent thread has to wait for its child to complete its
execution. Thread scheduler schedules child thread while the parent waits for the child to complete.
Ans.
(d)
Explicación:
Invoking start() method on a thread moves the thread to a RUNNABLE state. But invoking start() method on a thread that has
already started throws a IllegalThreadStateException because the thread is already in RUNNABLE state.
a) Runtime error
b) Compilation error
Página 40 de 104
c) GFG GFG
d) None of the above
Ans.
(c)
Explicación:
Test class extends Thread class that has start() method implemented. So invoking start() on an object that extends Thread class
invokes run() method defined in the program.
System.out.println(obj.data);
}
public static void main(String[] args) throws InterruptedException
{
Thread thread1 = new Thread(new Test());
Thread thread2 = new Thread(new myThread());
thread1.start();
thread2.start();
d) Compilation error
Ans.
(d)
Explicación:
An object must first acquire a lock before calling wait() method. Also wait() method throws Checked
exception(InterruptedException), we must include it in a try-catch block or throws it.
Página 41 de 104
System.out.printf(" GFG ");
try
{
barrier.await();
} catch (InterruptedException | BrokenBarrierException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException
{
Thread thread1 = new Thread(new Test());
Thread thread2 = new Thread(new Test());
thread1.start();
thread2.start();
System.out.printf(" ElCaminoDe ");
try
{
barrier.await();
} catch (InterruptedException | BrokenBarrierException e)
{
e.printStackTrace();
}
System.out.printf(" End ");
}
}
a) ElCaminoDe GFG GFG End
b) GFG ElCaminoDe GFG End
c) GFG GFG ElCaminoDe End
d) All the above
Ans.
(d)
Explicación:
For (a), the parent thread keep executing until it reaches the barrier. The child thread are then scheduled. For (b),
thread scheduler scheduler thread1. Once it reaches the barrier, the parent thread is scheduled. Once parent thread
reached the barrier, thread2 is scheduled. For (c), Both the child thread are scheduled. Finally when each of the child
threads reach the barrier, the parent thread is scheduled.
Página 42 de 104
Ans.
(c)
Explicación:
static variables are associated with the class and are therefore, not allowed inside a method body.
a) 1
b) 2
c) 0
d) 3
Ans.
(b)
Explicación:
Refer to Operator precedence rule in java.
a) 1
b) 2
c) Runtime Exception of java.lang.ArithmeticException
d) Compilation error due to divisibility by 0
Ans.
(b)
Explicación:
&& operator is evaluated from right to left. If the first expression of && operator evaluates to false, then the second
operator is not evaluated. There is no compilation error because divide by 0 is a runtime exception.
Página 43 de 104
int temp = 9;
int data = 8;
System.out.println(temp & data);
}
}
a) 9
b) 8
c) 1000
d) 1001
Ans.
(b)
Explicación:
& operator is logical bit-wise and operator in java. The and of 9(1001) and 8(1000) is 1000 which is 8.
Explicación:
temp is a primitive data type. Primitive data types cannot be assigned null values. data is an instance of class Integer and
therefore can hold null values.
Página 44 de 104
Ans.
(d)
Explicación:
Final and static methods cannot be overridden. For more details Check: Can we Overload or Override static methods in java ?
Explicación:
The overriding method must have same signature, which includes, the argument list and the return type. For details, See :
Overriding in Java
a) Test class
b) Compilation error due to line xyz
c) Derived class
d) Compilation error due to access modifier
Ans:
Página 45 de 104
(d)
Explicación:
The overriding method can not have more restrictive access modifier.
class Derived
{
public void getDetails() throws IOException //line 23
{
System.out.println("Derived class");
}
}
Explicación:
The exception thrown by the overriding method should not be new or more broader checked exception. In the code above, Exception
is more broader class of checked exception than IOException, so this results in compilation error.
class Derived
{
public void getDetails()
{
System.out.printf("Derived class ");
}
}
Página 46 de 104
public class Test extends Derived
{
public void getDetails()
{
System.out.printf("Test class ");
super.getDetails();
}
public static void main(String[] args)
{
Derived obj = new Test();
obj.getDetails();
}
}
super keyword is used to invoke the overridden method from a child class explicitly.
class A
{
protected char c = 'A';
char getValue()
{
return c;
}
}
class B extends A
{
protected char c = 'B';
char getValue()
{
return c;
}
char getSuperValue()
{
return super.c;
}
}
Resultado:
A B B A
Explicación:
Program 2 :
public class RuntimePolymorphism
{
public static void main(String[] args)
{
A a = new B();
B b = new B();
System.out.println(a.c + " " + a.getValue() +
" " + b.getValue() + " " + b.getSuperValue());
Página 47 de 104
}
}
class A
{
protected char c = 'A';
char getValue()
{
return c;
}
}
class B extends A
{
protected char c = 'B';
char getSuperValue()
{
return super.c;
}
}
Resultado:
A A A A
Explicación:
Concept of polymorphism for methods cannot be used here, since in class B there is no function overloading a method in class A.
Refer run-time polymorphism for more details
Program 3 :
class test
{
public static int y = 0;
}
class HasStatic
{
private static int x = 100;
HasStatic.x++;
System.out.println("Adding to 100, x = " + x);
t1 = new test();
t1.y++;
System.out.print("Adding to 0, ");
System.out.println("y = " + t1.y + " " + t2.y + " " + test.y);
}
}
Resultado:
Adding to 100, x = 104
Adding to 0, y = 3 3 3
Explicación: Properties of static are shown in this example. When a variable is declared as static,
then a single copy of variable is created and shared among all objects at class level. Static
variables are, essentially, global variables. All instances of the class share the same static
variable. See more at: static keyword
Program 4 :
public class Except
{
Página 48 de 104
public static void main(String[] args)
{
try
{
throw new Error();
}
catch (Error e)
{
try
{
throw new RuntimeException();
}
catch (Throwable t)
{
}
}
System.out.println("phew");
}
}
Resultado: phew
Explicación: Its legal to throw and handle errors and runtime exceptions. RuntimeException is a sub-
subclass of Throwable. See exceptions for more details
Program 5 :
public class Boot
{
static String s;
static
{
s = "";
}
{
System.out.println("ElCaminoDe ");
}
static
{
System.out.println(s.concat("practice.ElCaminoDe "));
}
Boot()
{
System.out.println(s.concat("Quiz.ElCaminoDe"));
}
public static void main(String[] args)
{
new Boot();
System.out.println("Videos.ElCaminoDe");
}
}
Resultado:
practice.ElCaminoDe
ElCaminoDe
Quiz.ElCaminoDe
Videos.ElCaminoDe
Explicación: static init blocks run before instance init blocks (in the order in which they appear,
respectively). The order of initialization constructors and initializer block doesn’t matter,
initializer block is always executed before constructor. See static block for details
Program 1 :
class A
{
public Top(String s)
{
System.out.print("A");
Página 49 de 104
}
}
Program 2 :
class Clidder
{
private final void flipper()
{
System.out.println("Clidder");
}
}
Program 3 :
class Alpha
{
static String s = " ";
protected Alpha()
{
s += "alpha ";
}
}
class SubAlpha extends Alpha
{
private SubAlpha()
{
s += "sub ";
}
}
Página 50 de 104
private SubSubAlpha()
{
s += "subsub ";
}
public static void main(String[] args)
{
new SubSubAlpha();
System.out.println(s);
}
}
Resultado:
alpha subsub
Explicación:
SubSubAlpha extends Alpha! Since the code doesnt attempt to make a SubAlpha,
the private constructor in SubAlpha is okay.
Program 4 :
public class Juggler extends Thread
{
public static void main(String[] args)
{
try
{
Thread t = new Thread(new Juggler());
Thread t2 = new Thread(new Juggler());
}
catch (Exception e)
{
System.out.print("e ");
}
}
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
Thread.sleep(500);
}
catch (Exception e)
{
System.out.print("e2 ");
}
System.out.print(Thread.currentThread().getName()+ " ");
}
}
}
Resultado:
No output is produced.
Explicación:
In main(), the start() method was never called to start ”t” and ”t2”, so run() never ran.
For detail: See Multithreading in Java
Program 5 :
class Grandparent
{
public void Print()
{
System.out.println("Grandparent's Print()");
}
}
Página 51 de 104
{
public void Print()
{
System.out.println("Parent's Print()");
}
}
Resultado:
Explicación:
In Java, it is not allowed to do super.super. We can only access Grandparent’s members using Parent.
See Inheritance in Java
Página 52 de 104
a) 444.324
b) 444
c) Runtime error
d) Compilation error
Ans. (d)
Explicación: Converting from a bigger data type to a smaller data type is not allowed in java as it is
a lossy conversion.
}
}
a) 444.32495.1
b) 456
c) 458.42399
d) 458.4
Ans. (c)
Explicación: If one of the operands is long, double or float, the entire expression is converted to
long, double or float respectively.
a) 0
b) Compilation error due to line 1
c) Compilation error due to line 2
d) Compilation error due to line 1 and line 2
Ans. (b)
Explicación: When the expressions are evaluated, the data type of the result is implicitly changed to
a larger data type and therefore, explicit recasting has to be done as shown in line 2. On the other
hand, line 1 shows compilation error because the expression on the right side has data type as int
whereas left side it is byte.
a) Compilation error
b) 70
c) 70.0
d) Runtime error
Ans. (c)
Explicación: If a double value is used in an expression then the output is returned in double format
rather than an int.
Página 53 de 104
Salida programa Java | Grupo 22 (Overloading).
Predice el resultado del siguiente programa java:
Prerequisito – Overloading in Java
a) 1
b) 0
c) Runtime error
d) Compilation error
Ans. (d)
Explicación: For method overloading, methods must have different signatures. Return type of methods
does not contribute towards different method signature, so the code above give compilation error. Both
getdata 1 and getdata 2 only differ in return types and NOT signatures.
a) 0
b) 1
c) Compilation error
d) Runtime error
Ans. (c)
Explicación: Methods that throws different exceptions are not overloaded as their signature are still
the same.
Página 54 de 104
public static void main(String[] args)
{
Test obj = new Test();
System.out.println(obj.function());
}
}
a) Compilation error
b) Runtime error
c) GFG
d) None of these
Ans. (c)
Explicación: Access modifiers associated with methods doesn’t determine the criteria for overloading.
The overloaded methods could also be declared as final or static without affecting the overloading
criteria.
a) GFG
b) ElCaminoDe
c) Compilation error
d) Runtime error
Ans. (b)
Explicación: The order of argument are an important parameter for determining method overloading. As
the order of attributes are different, the methods are overloaded.
a) GFG
b) Compilation error
c) Runtime error
d) ElCaminoDe
Ans. (a)
Explicación: This one is really simple. Different number of arguments contribute towards method
overloading as the signature of methods is changed with different number of attributes. Whichever
matches the attributes is obviously called in Method Overloading.
Página 55 de 104
Prerequisito: Inheritance in Java
Resultado: fa la
Explicación: B b = new A(); b is object of type B, and hence b.sing() refers to the method sing of
class B see run-time polymorphism
Página 56 de 104
class Base
{
final public void show()
{
System.out.println("Base::show() called");
}
}
class Derived extends Base
{
public void show()
{
System.out.println("Derived::show() called");
}
}
class Main
{
public static void main(String[] args)
{
Base b = new Derived();
b.show();
}
}
Resultado: Compiler Error
Explicación: Final methods cannot be overridden. For Detail see final keyword. However, if we remove
the keyword final then, the output will be
Derived::show() called
.
4) ¿Cuál será el resultado del programa?
public class EH
{
public static void main(String args[])
{
int divisor =0;
int dividend = 11;
try
{
int result=dividend/divisor;
System.out.println("The result is "+result);
}
catch(Exception e)
{
System.out.println("An exception occured");
}
catch(ArithmeticException ae)
{
System.out.println("Division by zero");
}
finally
{
System.out.println("We are done!");
}
}
}
Página 57 de 104
{
this(7);
s += "e";
}
Echo(int x)
{
s += "e2";
}
public static void main(String[] args)
{
System.out.print("made " + s + " ");
}
static
{
Echo e = new Echo();
System.out.print("block " + s + " ");
}
}
Question 1 Explicación:
In the above program, b is a reference of Base type and refers to an abject of Derived class. In Java,
functions are virtual by default. So the run time polymorphism happens and derived fun() is called.
Question 2
class Base {
final public void show() {
System.out.println("Base::show() called");
}
}
Página 58 de 104
System.out.println("Derived::show() called");
}
}
class Main {
public static void main(String[] args) {
Base b = new Derived();;
b.show();
}
}
Run on IDE
Base::show() called
B Derived::show() called
Compiler Error
D Runtime Error
Java Inheritance
Discuss it
Question 2 Explicación:
Final methods cannot be overridden. See the compiler error here.
Question 3
class Base {
public static void show() {
System.out.println("Base::show() called");
}
}
class Main {
public static void main(String[] args) {
Base b = new Derived();;
b.show();
}
}
Run on IDE
Base::show() called
B Derived::show() called
C Compiler Error
Java Inheritance
Discuss it
Question 3 Explicación:
Like C++, when a function is static, runtime polymorphism doesn't happen.
Question 4
Which of the following is true about inheritance in Java?
A 1, 2 and 4
B Only 1 and 2
C 1, 2 and 3
D 2, 3 and 4
Página 59 de 104
Question 5
Output of following Java program?
class Base {
public void Print() {
System.out.println("Base");
}
}
class Main{
public static void DoPrint( Base o ) {
o.Print();
}
public static void main(String[] args) {
Base x = new Base();
Base y = new Derived();
Derived z = new Derived();
DoPrint(x);
DoPrint(y);
DoPrint(z);
}
}
Base
Derived
Derived
B Base
Base
Derived
C Base
Derived
Base
D Compiler Error
Java Inheritance
Discuss it
Question 5 Explicación:
See question 1 of http://www.geeksforgeeks.org/output-of-java-program-Grupo-2/
Question 6
Predict the output of following program. Note that fun() is public in base and private in derived.
class Base {
public void foo() { System.out.println("Base"); }
}
Run on IDE
Base
B Derived
Compiler Error
D Runtime Error
Página 60 de 104
Java Inheritance
Discuss it
Question 6 Explicación:
It is compiler error to give more restrictive access to a derived class function which overrides a
base class function.
Question 7
Which of the following is true about inheritance in Java. 1) In Java all classes inherit from the
Object class directly or indirectly. The Object class is root of all classes. 2) Multiple inheritance
is not allowed in Java. 3) Unlike C++, there is nothing like type of inheritance in Java where we can
specify whether the inheritance is protected, public or private.
Java where we can specify whether the inheritance is protected, public or private.
1, 2 and 3
B 1 and 2
C 2 and 3
D 1 and 3
Java Inheritance
Discuss it
Question 7 Explicación:
See Comparison of Inheritance in C++ and Java
Question 8
Predict the output of following Java Program
// filename Main.java
class Grandparent {
public void Print() {
System.out.println("Grandparent's Print()");
}
}
Java Inheritance
Discuss it
Question 8 Explicación:
Página 61 de 104
In Java, it is not allowed to do super.super. We can only access Grandparent's members using Parent.
For example, the following program works fine.
// Guess the output
// filename Main.java
class Grandparent {
public void Print() {
System.out.println("Grandparent's Print()");
}
}
class Main {
public static void main(String[] args) {
Child c = new Child();
c.Print();
}
}
Question 9
final class Complex {
class Main {
public static void main(String args[])
{
Complex c = new Complex(10, 15);
System.out.println("Complex number is " + c);
}
}
Run on IDE
Question 9 Explicación:
See http://www.geeksforgeeks.org/overriding-tostring-method-in-java/
Página 62 de 104
Salida programa Java | Grupo 25 (Java abstract class and interface).
Predice el resultado del siguiente programa java:
Question 1.
Which of the following is FALSE about abstract classes in Java.
A If we derive an abstract class and do not implement all the abstract methods, then the derived class
should also be marked as abstract using 'abstract' keyword
B Abstract classes can have constructors
C A class can be made abstract without any abstract method
D A class can inherit from multiple abstract classes.
Question 2.
Which of the following is true about interfaces in java.
1, 3 and 4
B
1, 2 and 4
C
2, 3 and 4
D
1, 2, 3 and 4
Question 3.
Predict the output of the following program.
Página 63 de 104
{
System.out.println("a = " + a);
}
A
a = 10
B
a = 20
C
Compilation error
Question 3 Explicación:
Final method can’t be overridden. Thus, an abstract function can’t be final.
Question 4
Type IV JDBC driver is a driver
A
which is written in C++
B
which requires an intermedio layer
C
which communicates through Java sockets
D
which translates JDBC function calls into API not native to DBMS
Java Abstract Class and Interface ISRO CS 2017
Discuss it
Question 4 Explicación:
JDBC type 4 driver,works directly by connecting to the database server through socket connections and
converts JDBC calls to vendor-specific database protocols.These drivers don't require any intermediate
layer. So, option (C) is correct.
Question 5
Which of the following statement(s) with regard to an abstract class in JAVA is/are TRUE ? I. An
abstract class is one that is not used to create objects. II. An abstract class is designed only to
act as a base class to be inherited by other classes.
A
Only I
B
Only II
C
Neither I nor II
D
Both I and II
Java Abstract Class and Interface UGC NET CS 2017 Jan - III
Discuss it
Question 5 Explicación:
Abstract data class is not used to create objects in Java and it is designed only to act as a base
class to be inherited by other classes. Both Statement are correct. For more information
Refer:Abstract Classes in Java Option (D) is correct.
Question 6
Página 64 de 104
Which of the following is used to make an Abstract class?
Question 6
Which of the following is used to make an Abstract class?
A Making atleast one member function as pure virtual function
B Making atleast one member function as virtual function
C Declaring as Abstract class using virtual keyword
D Declaring as Abstract class using static keyword
Question 6 Explicación:
Making atleast one member function as pure virtual function is the method to make abstract class. For
more information on Abstract Class Refer:Pure Virtual Functions and Abstract Classes in C++ Option (A)
is correct.
Question 7
Question 7 Explicación:
An abstract class is a class that is designed to be specifically used as a base class. An abstract
class contains at least one pure virtual function. A pure virtual function can be declared by using a
pure specifier ( = 0 ) in the declaration of a virtual member function in the class declaration.
Option (C) is correct.
class A
{
public int i;
private int j;
}
class B extends A
{
void display()
{
super.j = super.i + 1;
System.out.println(super.i + " " + super.j);
}
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
Página 65 de 104
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error
Respuesta: d
Explicación: Class A contains a private member variable j, this cannot be inherited by subclass B. So
in class B we can not access j. So it will give a compile time error.
class selection_statements
{
public static void main(String args[])
{
int var1 = 5;
int var2 = 6;
if ((var2 = 1) == var1)
System.out.print(var2);
else
System.out.print(++var2);
}
}
options:a) 1
b) 2
c) 3
d) 4
Respuesta: b
Explicación: In “If” statement, first var2 is initialized to 1 and then condition is checked whether
var2 is eaqual to var1. As we know var1 is 5 and var2 is 1, so condition will be false and else part
will be executed.
void start()
{
long [] a1 = {3, 4, 5};
long [] a2 = fix(a1);
System.out.print(a1[0] + a1[1] + a1[2] + " ");
System.out.println(a2[0] + a2[1] + a2[2]);
}
Página 66 de 104
long [] fix(long [] a3)
{
a3[1] = 7;
return a3;
}
}
options:
a) 12 15
b) 15 15
c) 3 4 5 3 7 5
d) 3 7 5 3 7 5
Respuesta: b
Explicación: The reference variables a1 and a3 refer to the same long array object. When fix() method
is called, array a1 is passed in that and the value of a3[2] become 7 which will reflect in a1[] So
the a1[] array become {3, 7, 5}.
So Resultado: 3 + 7 + 5 + ” ” 3 + 7 + 5
options:
a) -2147483648 and 1
b) 0x80000000 and 0x00000001
c) -2147483648 and -1
d) 1 and -2147483648
Respuesta a
Explicación: Option A is correct. The >>> operator moves all bits to the right, zero filling the left
bits. The bit transformation looks like this:
Before: 1000 0000 0000 0000 0000 0000 0000 0000
After: 0000 0000 0000 0000 0000 0000 0000 0001
Option C is incorrect because the >>> operator zero fills the left bits, which in this case changes
Options :
A. The program has a compile error because the size of the array wasn’t specified when declaring the
array.
B. The program has a runtime error because the array elements are not initialized.
C. The program runs fine and displays x[0] is 0.
D. The program has a runtime error because the array element x[0] is not defined.
Answer : C
Explicación:
Program is syntactically correct, so no error. In java, if the array is not initialized at the time of
declaration and creation then all the elements of the array are initialized to 0 by default.
Página 67 de 104
import java.util.*;
Options :
A. 120 200 16
B. 120 200 14
C. 120 200 016
D. 016 is a compile error. It should be written as 16.
Answer : B
Explicación: 016 is an octal number. The prefix 0 indicates that a number is in octal and in octal 16
is equal to 14.
Ques3. What is the output of the following?
import java.util.*;
Options :
A. S1=123456, S2=579
B. S1=123456, S2=123456
C. S1=579, S2=579
D. None of This
Answer : A
Explicación: If a number is quoted in “” then it b
as numeric values.
import java.util.*;
public class Test {
public static void main(String[] args)
{
int[] x = { 1, 2, 3, 4 };
int[] y = x;
x = new int[2];
Página 68 de 104
for (int i = 0; i < x.length; i++)
System.out.print(y[i] + " ");
}
}
Options :
A. 1 2 3 4
B. 0 0 0 0
C. 1 2
D. 0 0
Answer : C
Explicación: The length of x array is 2. So the loop will execute from i=0 to i=1.
public
static void main(String[] args)
{
Test t1 = new Test();
t1.a = 100;
t1.b = 200;
Option
A) t1.a=100 t1.b=200
t2.a=10 t2.b=200
B) t1.a=10 t1.b=200
t2.a=10 t2.b=200
C) t1.a=100 t1.b=200
t2.a=10 t2.b=20
D) t1.a=100 t1.b=200
t2.a=100 t2.b=200
Resultado: A
Explicación: static variable is class level variable. If we create multiple objects of class and all
objects can point same reference of static variable means If you can change the value of static
variable in any object, then compiler automatically updates the value of all object static variables.
Option
a) 25
b) Error
c) -25
d) none
Output : b
Página 69 de 104
Explicación: If we apply any arithmetic operator between two variables x and y, then the result type
is max(int, type of x, type of y). Therefore, here the compiler will give the error possible lossy
conversion int to byte.
Question 3. What is the output of the following question?
class Test3 {
public
static void main(String[] args)
{
int x = 011;
int y = 0xfee;
int result = x + y;
System.out.print(x + ":" + y + ":" + result);
}
}
Options
a) Error
b) 010 : 0xfee : 4089
c) 9 : 4078 : 4087
d) 010 : 0xfee : 4087
Output : C
Explicación: If any integer number start with 0, then that number is treated as octal number hence 011
means (1*8^1 + 1*8^0) 9 and also if any integer start with 0x means then that number is treated as
Hexadecimal number means we can have the value between[0-9] and [a-z or A-Z]. oxfee =(15*16^2 +
14*16^1 + 14*16^0) =>4078.
options
a) Error
b) 0198 : 0xfree : 68734
c) 144 : 68590 : 68734
d) 0198 :68590 : 68788
Output : a
Explicación: If we assign a 0 before integer number, then that number is treated as octal and we know
octal number range is [0-7]. If we assign the number outside of this range then we get error. Similar
to this, if any integer number start with 0x then that number is treated as Hexadecimal means we can
assign the value in between the [0-9] [a-z or A-Z]. If we assign it out of range, then program will
get the error.
option
a)Hola
Hola
…..
…..
…..
b) Error
c)Hola
Hola
Página 70 de 104
Hola
Hola
Hola
d)Hola
Hola
Hola
Hola
Hola
Hi
Resultado: b
Explicación: In Java, if we declare any variable as final then that variable value is fixed and can
not be changed at run time. In final variable, values are assigned at compile time means in this
program, compiler see both a and b are final variable and final variable value never change and
condition is always true. “Hi” statement is unreachable so compiler give the error Unreachable
statement “Hi”.
Option
A) Error
B) A : a
C) 65 : 97
D) None
Resultado: C
Explicación: We can use all predefined Java class name and interface name as identifiers.
Question 2. What is the output of the following question?
class Test2 {
public
static void main(String[] args)
{
int if = 65;
int else = 97;
Option
A) Error
B) A : B
C) 65 : 97
D) None
Resultado: A
Explicación: We can’t use reserved words as identifiers.
if (x) {
Página 71 de 104
System.out.print("ElCaminoDe");
} else {
System.out.print("GFG");
}
}
}
Option
A) ElCaminoDe
B) GFG
C) Error
D) None
Resultado: C
Explicación:In Java, Compiler gives error – Incompatible types : int can not be converted to boolean
type.
But in C or C++ its a valid statement.
System.out.println(d1);
System.out.println(d2);
System.out.println(d3);
}
}
Option
A) Error
B) 123.456
12_3.4_5_6
12_3.4_56
C) 123.456
123.456
123.456
D) None
Resultado: C
Explicación: From (1.7v onwards)we can use ‘_'(under Score) Symbol between digits of numeric literals.
See more at Java naming conventions.
Página 72 de 104
OPTION
a) AB
b) 195
c) 131
d) Error
Respuesta c
Explicación: Here, ‘A’ and ‘B’ are not strings they are characters. ‘A’ and ‘B’ will not concatenate.
The ASCII of the ‘A’ and ‘B’ will be added. The value of ‘A’ is 65 and ‘B’ is 66. Hence Output will be
131.
QUE.2 What is the output of this program?
OPTION
a) ABA10
b) AB65
c) Error
d) AB
Answer : a
Explicación: If you try to concatenate any different types of data like integer, character, float with
string value, the result will be a string. So ‘A’ will be concatenated with “AB” and answer will be
“ABA”.
QUE. 3 What is the output of this program ?
public
class Prg {
public static void main(String args[])
{
System.out.print(20 + 1.34f + "A" + "B");
}
}
OPTION
a) 201.34AB
b) 201.34fAB
c) 21.34AB
4) Error
Answer : c
Explicación: Similar data types are added and then converted to string. 20 and 1.34f will be added and
then 21.34 will be concatenated with “A” and “B”, hence output will be 21.34AB.
Página 73 de 104
public static void main(String[] args)
{
System.out.print("Hola");
System.out.println("Guys!");
}
}
OPTION
a) HolaGuys!
b) Hola Guys!
c) Hola
Guys!
d) Compile with a Warning
Answer : a
Explicación: System.out.print() does not print new line after printing string, while
System.out.println(); prints new line after printing string. Hence output will be HolaGuys! and then
new line.
Options:
1. 1
2. Compile-time error
3. 1 2 3 4 5
4. [I@Hashcode_in_Hexadecimal
Resultado:
The answer is option(4)
Explicación: In the above program, we are using declaration, creation and initialization in a single
statement. But while printing, we are printing the base address of the array and not the full array.
To display array, loops need to be used.
Options:
1. No output
2. 2147483648
3. 2147483647
4. compile-time error
Resultado:
The answer is option(4).
Explicación: int is the default data types of integral data types. Here we are assigning 2147483648 to
a byte variable and the given value is beyond the range of int. That’s why the above program will give
compile-time error saying error: integer number too large: 2147483648.
Página 74 de 104
static char ch = 59;
public static void main(String[] args)
{
System.out.println(ch);
}
}
Options:
1. compile-time error
2. null
3. No output
4. ; //ascii value of 59 is ;
Resultado:
The answer is option(4).
Explicación: As the static variable is of type char. When we print it, the ASCII value of the given
integer gets printed.
public
class Test {
public
static void main(String[] args)
{
int x = 0xGeeks;
System.out.println(x);
}
}
Options:
1. 1
2. Compile-time error
3. null
4. Run-time error
Resultado:
The answer
is option(2).
Explicación:
Here we try to assign literals in Hexadecimal-form in int data types. But according to rule the
allowed characters are A-F but here we are using characters which are not allowed. That’s why the
above program will compile time error saying error: not a statement.
public
class Test {
public
static void main(String[] args)
{
// we are assiging 8 byte data to 4 byte variable
float f = 10l;
System.out.println(f);
}
}
Options:
1. 10
2. Compile-time error
3. 10.0
4. RuntimeException
Resultado:
The answer
is option(3).
Explicación:
Página 75 de 104
Here we are assigning a long value to a float variable. According to the data types float is of 4 byte
and long is of double byte. Apart from that we can assign a long value to a float type.
System.out.println();
Option
A) 1 2 3 4 5
1 2 3 4 5
B) 1 2 3 4 5
1 2 3 4
C) Error
D)Exception
Resultado:
Explicación:
In Java at the time of declaration, we can not specify the size otherwise we will get compile time
Error : 1-‘]’ expected, 2- illegal start of expresión
Option
A) Compile time Error
B) Run time Exception
C) 4 empty size Array are initialized
D) none
Resultado:
A
Explicación:
In java, if we want to specify dimension before the variable that facility is applicable only for
first variable in a declaration. otherwise we will get compile time error –
1- expected.
2- ';' expected.
Página 76 de 104
public static void main(String[] args)
{
int arr1[] = new int[0];
int arr2[] = new int[-1];
Resultado:
Explicación:
In java, if we are trying to specify Array size with some negative int value then we will get run time
exception – NegativeArraySizeException.
System.out.println(arr1.length);
System.out.println(arr2.length);
}
}
Option
A) 2147483647
2147483648
B) Error
C) 2147483647
-1
D) 2147483647
2147483646
Resultado:
B
Explicación:
In java, maximum allowed array size is 2147483647 which is the maximum value of int.if you will give
more than this range then we will get compile time error – integer number too large.
class ArrayDemo1 {
public static void main(String[] args)
{
short s = 45;
int arr1[] = new int[s];
char ch = 'A';
int arr2[] = new int[ch];
long l = 10;
int arr3[] = new int[l];
System.out.println(arr1.length);
System.out.println(arr2.length);
System.out.println(arr3.length);
}
}
Página 77 de 104
Option
A)45
65
10
B) 45
A
10
C)Error
D)no output
Resultado:
C
Explicación:
In java, we can specify the array size with char, sort, int, byte but we can not with long, double,
string and float size. Otherwise we will get compile time error – incompatible types: possible lossy
conversion.
A. Compilation Error
B. 4 7 1
C. 1 4 7
D. None
Answer : B. 4 7 1
Explicación: List in java stores its elements in Sequential manner it maintains insertion order. List
provides the ability of accessing elements using index.Collections are in the package util so we are
importing java.util.ArrayList.
class Demo {
public void show()
{
LinkedList<String> list = new LinkedList<String>();
list.add("Element1"); // line 6
list.add("Element2");
System.out.print(list.getFirst()); // line 8
}
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo();
demo.show();
}
}
Página 78 de 104
A. Element1
B. Compilation Error at line 8
C. Runtime Error
Respuesta A. Element1
Explicación: LinkedList has a getFirst() method . It returns an elements at Zero index. LinkedList
also maintains its insertion order and provides easy accessing of elements.
A. ArrayIndexOutOfBoundException
B. IndexOutOfBoundException
C. null
Answer : B.IndexOutOfBoundException
Explicación: There is no element present in that index ‘0’ so it is IndexOutOfBoundException. In java,
if we access the elements out of the index it provides ArrayIndexOutOfBoundException in array. In
Collection. it provide IndexOutOfBoundException.
class Demo {
public void show()
{
ArrayList<String> list = new ArrayList<String>();
list.add("ElCaminoDe_one"); // line 6
list.add("ElCaminoDe_two");
System.out.print(list.getFirst()); // line 8
}
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo();
demo.show();
}
}
A. ElCaminoDe_one
B. Compilation Error
C. Runtime Error
Respuesta B. Compilation Error
Explicación: ArrayList doesn’t have method getFirst(). So it is compilation error.getmethod() is
available only LinkedList. Therefore, it provide compilation error in this program.
import java.util.LinkedList;
class Demo {
public void show()
{
LinkedList<String> list = new LinkedList<String>();
System.out.print(list.getFirst());
}
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo();
Página 79 de 104
demo.show();
}
}
A. null
B. IndexOutOfBoundException
C. NoSuchElementException
Respuesta C. NoSuchElementException
Explicación: There is no element in LinkedList so it return NoSuchElementException.
NoSuchElementException is a RuntimeException thrown when there is no more element in it.
NoSuchElementException extends RuntimeException.
import java.util.LinkedList;
class Demo {
public void show()
{
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(4);
list.add(7);
list.add(5);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo();
demo.show();
}
}
A. Compilation Error
B. 1 4 7 5
C. 1 4 5 7
Respuesta B. 1 4 7 5
Explicación: List stores element in sequential order and then we can access element in List using
index. List provides the ability to access its elements by using its index. But in Grupo, map elements
are not accessed by using index.
class Demo {
public void show()
{
List<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(4);
list.add(7);
list.add(5);
Collections.sort(list); // line 9
System.out.println(list);
}
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo();
demo.show();
}
}
Página 80 de 104
A. Compilation Error at line 9
B. [1, 4, 5, 7]
C. [1, 4, 7, 5]
Respuesta B. [1, 4, 5, 7]
Explicación: Collections.sort() sort the list in ascending order. Collections class provides static
methods for sorting the elements in collections. If Collection elements are of Grupo type elements are
inserted in sorted order no need to sort.
class Demo {
public void show()
{
ArrayList<String> list = new ArrayList<String>();
list.add("banana");
list.add("apple");
Iterator itr = list.iterator();
Collections.sort(list);
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo();
demo.show();
}
}
class Demo {
public void show()
{
ArrayList<String> list = new ArrayList<String>();
ArrayList<Integer> list1 = new ArrayList<Integer>();
boolean check = (list.getClass() == list1.getClass());
System.out.println(check);
}
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo();
demo.show();
}
}
A. true
B. false
Respuesta A. true
Explicación: getclass() method return the runtime class of an object. That class object is the object
that is locked by static synchronized method of represented class. Here both are in ArrayList Class so
answer is true.
5. What is the Output of following Java Program?
import java.util.LinkedList;
Página 81 de 104
class Demo {
public void show()
{
LinkedList<String> list = new LinkedList<String>();
System.out.println(list.getClass());
}
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo();
demo.show();
}
}
A. class java.util.LinkedList
B. String
C. Compiler Error
Respuesta A. class java.util.LinkedList
Explicación: getclass() method returns the runtime class of an object. That class object is the object
that is locked by static synchronized method of represented class. Here LinkedList is the runtime
class so the answer is java.util.LinkedList.
public
class Test {
public
static void main(String[] args)
{
int x = 10;
if (x) {
System.out.println("HOLA GEEKS");
} else {
System.out.println("BYE");
}
}
}
Options:
1. HOLA GEEKS
2. Compile time error
3. Runtime Error
4. BYE
Resultado:
The answer is option (2).
Explicación: The argument of if statement should be Boolean type. By mistake if we are trying to
provide any other data type then we will get compile-time error saying incompatible types. Here the
argument is of int type, therefore we will get compile time error saying error: incompatible types:
int cannot be converted to Boolean
else
{
System.out.println("BYE");
Página 82 de 104
}
}
}
Options:
1. HOLA GEEKS
WELCOME
2. HOLA GEEKS
3. BYE
Options:
1. 10
2. BYE
3. NO output
4. Compile time error
Resultado:
The answer is option (4).
Explicación: In the above program, there is a declarative statement in the if statement without curly
braces that’s why we will get compile time error saying Error: variable declaration not allowed here.
Resultado:
1. HOLA GEEKS
2. Compile time error
3. WELCOME
4. No Output
The answer is option (3)
Explicación: There is no dangling else problem in java. Every else is mapped to the nearest if
statement.Here the inner else if mapped with the nearest if part i.e. if(x>y).
Página 83 de 104
{
String day = "Sunday";
switch (day) {
case "Monday":
System.out.println("Let's Work");
break;
case "Saturday":
System.out.println("waiting for Sunday");
break;
case "Sunday":
System.out.println("Today is fun day");
}
}
}
Options:
1. Compile time error
2. Lets work
3. Run- time error
4. Today is fun day
Resultado:
The answer is option (4)
Explicación: The allowed arguments type for the switch statement are byte, short, char, int until 1.4
version. But from 1.5 version onward corresponding wrapper classes and enum type also allowed. From
1.7 version onward String type also allowed. Refer this article for detail
class MainClass {
public
static void main(String[] args)
{
int x = 10;
Switch(x)
{
System.out.println("GEEKS");
}
}
}
Options:
1. GEEKS
2. Compile time error
3. No Output
4. Run-time error
Resultado:
The answer is option (2)
Explicación: Inside switch every statement should be under some case or default i.e. independent are
not allowed inside switch otherwise we will get compile time error saying error:’;’ expected.
Options:
1. HOLA
2. No Output
3. GEEKS
4. Compile time error
Resultado:
The answer is option (4)
Página 84 de 104
Explicación: Every case label should be constant otherwise we will get compile time error. But we can
add variable as case label but we have to declare that variable as final. But here we are using
variable y as a case label that’s why we will get compile time error saying error: constant expression
required.
Options:
1. GEEKS
2. Compile time error
3. HOLA
4. NO Output
Resultado:
The answer is option (3)
Explicación: Every case label should be constant otherwise we will get compile time error. But we can
add variable as case label but we have to declare that variable as final. But here we are using
variable y as a case label that’s why we will get result as HOLA.
Resultado:
1. Compile time error
2. GEEKS
3. HOLA
4. No Output
The answer is option (2).
Explicación: Both Switch argument and case label can be expressions. But case label should be constant
expression.Here the case label “10+1+1” is treated as case 12 and switch argument “x+1+1” is also
treated as 12.
switch (x) {
Página 85 de 104
case 1:
System.out.println("SCIENCE, MATHS, PHYSICS");
break;
case 2:
switch (stream) {
case 'A':
System.out.println("Welcome");
break;
case 'C':
System.out.println("ElCaminoDe");
break;
case 'B':
System.out.println("Have a nice day");
break;
}
break;
case 3:
switch (stream) {
case 'C':
System.out.println("Welcome");
break;
case 'D':
System.out.println("In");
break;
case 'E':
System.out.println("GFG");
break;
}
break;
}
}
}
Options:
1. Compile time error
2. GFG
3. No Output
4. ElCaminoDe
Resultado:
The answer is option (4)
Explicación: Nested switch case is possible in java. A nested switch statement is a switch statement
within another switch statement.
Options:
1. HOLA
2. Compile time error
3. HOLA (infinitely)
4. No Output
The answer is option (3)
Explicación: Think the above example like this
do
while(true)
System.out.println("HOLA");
while(false);
Página 86 de 104
This is the simple do-while loop. As we know that in while loop without curly braces we can take only
one statement which should not be declarative. Here, HOLA is that one statement of while loop which is
without curly braces. Here the inner while loop always gives true and the program output will HOLA
infinitely.
Options:
1. Compile time error
2. FRIENDS
3. No output
4. ENEMY
The answer is option (1)
Explicación: Here while loop always give true and it will print FRIENDS infinitely and did not give
change to print ENEMY. Which gives compile time error saying
prog.java:8: error: unreachable statement
System.out.println("ENEMY");
Options:
1. FRIENDS
2. ENEMY
3. No Output
4. FRIENDS (Infinitely)
The answer is option (4)
Explaination: Here at the compile time compiler thinks that x and y both are variables and its value
can be changed and that will gives false to the while loop. Which gives the chance to print ENEMY
that’s why compiler did not throw any compile time error.
Options:
1 HOLA
2 HOLA (Infinitely)
3 Error: Unreachable statement
4 Error: ; expected
The answer is option (4)
Página 87 de 104
Explicación: In the above example there is a syntax error of do-while loop. As we all know that
without curly braces we can take a statement which cannot be declarative but if we are not specifying
any statement and not mentioning any curly braces then compiler will give an error saying Error: ;
expected.
System.out.print(2);
} while (false);
} while (false);
}
}
Options:
1. 12
2. 21
3. 1
4. 2
The answer is option (1)
Explicación: In the above example, nesting in a do while will work under nesting process. First inner
do-while loop will be executed after that the outer one.
Options:
1.GEEKS
2.Compile time error
3.Run time Exception
4.GEEKS (Infinitely)
The answer is option (4)
Explicación: In the above example, we are using for loop. In for loop if we did not provide any
initialization, condition-check and increment/decrement part then it will go to infinite loop if we
did not provide any condition in statement.
Página 88 de 104
Options:
1.GEEKS GEEKS GEEKS
2.Compile time error
3.GEEKS (Infinitely)
4.No output
The answer is option (3)
Explicación: When we are not taking any statement in increment/decrement section therefore overtime it
does not increment/decrement the value of I and the condition always true. That’s why it results into
GEEKS (Infinitely).
Option:
1.HOLA
2.BYE
3.Compile time error: re- initialization
4.No output
The answer is option (2)
Explicación: In the condition of if statement, we assigning are false to b which return a boolean
value which is false. Therefore the control goes to the else part and the output is BYE.
Option:
1.HOLA GEEKS
2.WELCOME
3.Compile time error
4.HOLA GEEKS WELCOME
The answer is option (2)
Explicación: Here we are defining nested if and a single else part. In java, there is no dangling else
problem in java. Every else is mapped to the nearest if statement. Therefore the else part belongs to
if(x>y) in the above program, which returns false that’s why control goes to else part and the output
is WELCOME.
class Test {
public
static void main(String[] args)
{
for (int i = 0;; i++) {
System.out.println("HIII");
}
System.out.println("BYE");
}
}
Página 89 de 104
Options:
1. HIII
2. HIII(infinitely)
3. BYE
4. Compile time error
The answer is option (4)
Explicación: In the above for loop it will go for infinite loop and the above program does not give
any chance to the next lines of the program. That’s why compiler will give compile time error saying
error: unreachable statement.
Option
A) 11 33
B) Error
C) exception
D) 11 -33
Resultado: C
Explicación: We will get java.lang.ArrayIndexOutOfBoundsException because [-2] index is out of range.
class Test2 {
public
static void main(String[] args)
{
int arr[][] = { { 11, 22 }, { 33, 44, 55 } };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < arr.length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Option
A) 11 22
33 44 55
B) 11 22
33 44
C) Error
D) Exception
Resultado: B
Explicación: Here arr.length returns 2 of the array size, because first dimension size if 2.
class Test2 {
public
static void main(String[] args)
{
int arr[][] = { { 11, 22 }, { 33, 44, 55 } };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < arr[i].length; j++)
Página 90 de 104
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Option
A) 11 22
33 44 55
B) 11 22
33 44
C) Exception
D) Error
Resultado: A
Explicación: Here arr[i].length returns first time 2 because first dimension size is 2 and second time
3 because 3 second dimension array size is 3.
Option
A) 11 22
33 44 55
B) 11 22
33 44
C) Error
D) Exception
Resultado: D
Explicación: This program will give exception :java.lang.ArrayIndexOutOfBoundsException
because we want to print the value out of range of array.
Option
A) 5 5
B) Error
C) Exception
D) None
Resultado: B
Explicación: It will give error because length() method is not in java. error : Can not find symbol
length().
Página 91 de 104
class Geeks {
public
static void main(String[] args)
{
throw new ArithmeticException();
}
}
Options:
1. RuntineException:java.lang.ArithmeticExcetion
2. RuntineException:/ by zero
3. RuntineException:java.lang.ArithmeticExcetion:/ by zero
4. RuntineException:ArithmeticExcetion
The answer is option (1)
Explicación: In the above program, we are throwing an exception object explicitly to the JVM and the
default handler print the description of the exception object, without any description of the object
because here we are calling default constructor.
Options:
1. RuntineException:java.lang.ArithmeticExcetion
2. RuntineException:/ by zero
3. RuntineException:java.lang.ArithmeticExcetion:/ by zero
4. RuntineException:ArithmeticExcetion
The answer is option (1)
Explicación: In the above program, we are throwing an exception object explicitly to the JVM and the
default handler print the description of the exception object.
Options:
1. RuntineException:java.lang.ArithmeticExcetion
2. RuntineException:NullPointerException
3. No Output
4. RuntineException:ArithmeticExcetion
The answer is option (2)
Explicación: Here ae refers to null because static variable is initialized by the compiler by giving
default value and the value of reference is null. Thats why we will get RuntimeException saying
Exception in thread “main” java.lang.NullPointerException.
Options:
1. Run-time Exception
2. Compile-time error
Página 92 de 104
3. No Output
4. Compile-time Exception
The answer is option (2)
Explicación: In the above program, we are throwing an exception object explicitly to the JVM but after
throwing an exception object explicitly we cant declare any statement directly because that statement
will not get the chance to execute. Thats why we will get compile time error saying error: unreachable
statement.
Options:
1. Hola Geeks
2. No Output
3. Run-time Exception
4. Compile-time error
The answer is option (4)
Explicación: we can use throw keyword only for throwable object types. If we are trying to use for
normal java objects, we will get compile time error saying incompatible types.
Options:
1. No Output
2. 10
3. Compile time error
4. 10 (10 times)
The answer is option (3)
Explicación: Curly braces are optional and without curly braces we can take only one statement under
for loop which should not be declarative statement. Here we are declaring a variable that’s why we
will get compile time error saying error: variable declaration not allowed here.
Options:
1. HOLA GEEKS
2. Compile time error
3. HOLA GEEKS
HOLA GEEKS
HOLA GEEKS
4. No Output
Página 93 de 104
The answer
is option (2)
Explicación:
Initialization part of the for loop will be executed only once in the for loop life cycle. Here we can
declare any number of variables but should be of same type. By mistake if we are trying to declare
different data types variables then we will get compile time error saying error: incompatible types:
String cannot be converted to int.
Resultado:
1. HI
HOLA GEEKS
2. No Output
3. Compile time error
4. HOLA GEEKS
The answer is option (1)
Explicación:I n the initialization section we can take any valid java statement including
System.out.println(). In the for loop initialization section is executed only once that’s why here it
will print first HI and after that HOLA GEEKS.
Options:
1. Compile time error
2. HOLA GEEKS
3. HOLA GEEKS (Infinitely)
4. Run-time Exception
The answer:
is option (3)
Explicación:
In the conditional check we can take any valid java statement but should be of type Boolean. If we did
not give any statement then it always returns true.
Página 94 de 104
Options:
1.GEEKS
WELCOME
GEEKS
WELCOME
2.No Output
3.Compile time error
4.GEEKS WELCOME(Infinitely)
Resultado:
The answer
is option (4)
Explicación:
In increment-decrement section we can take any valid java statement including System.out.println().
Here in the increment/decrement section, a statement is there, which result the program to go to
infinite loop.
class Geeks
{
public static void main(String[] args)
{
try
{
System.out.println(1/0);
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
}
}
Options:
1. java.lang.ArithmeticExcetion
2. / by zero
3. java.lang.ArithmeticExcetion:/ by zero
4. ArithmeticExcetion
The answer
is option (2)
Explicación:
In the above program, we are calling getMessage() method to print the exception information. We know
that getMessage() method will always be printed as the description of the exception which is / by
zero.
class Geeks
{
public static void main(String[] args)
{
try
{
System.out.println(1/0);
}
catch(ArithmeticException e)
{
System.out.println("Hola Geeks");
}
catch(Exception e)
{
Página 95 de 104
System.out.println("Welcome");
}
}
}
Options:
1. Hola Geeks
2. No Output
3. Compile-time error
4. welcome
The answer is option (1)
Explicación: In the above program, we are following the approach of try with multiple catch blocks.
Here 1/0 is an ArithmeticException, which is cought by the first catch block and it is executed.
Options:
1. Hola Geeks
2. No Output
3. Compile-time error
4. welcome
The answer is option (3)
Explicación: If we are trying try with multiple catch block then we should take care that the child
class catch block is first then parent class catch block. Otherwise we will get compile time error
saying error: exception ArithmeticException has already been caught.
Options:
1. Run-time Exception
2. Compile-time error
3. No Output
4. Compile-time Exception
The answer is option (2)
Explicación: In the above program, we are declaring a try block without any catch or finally block. We
have to always declare try with catch or finally block because single try block is invalid. That’s Why
it will give compile time error saying error: ‘try’ without ‘catch’, ‘finally’ or resource
declarations.
Página 96 de 104
{
try
{
System.out.println(1/0);
}
System.out.println("Hola GEEKS");
catch(ArithmeticException e)
{
System.out.println("Welcome");
}
}
}
Options:
1. Hola Geeks
2. Hola Geeks
Welome
3. Run-time Exception
4. Compile-time error
The answer is option (4)
Explicación: In the above program, we are declaring a try block and also a catch block but both are
separated by a single line which will cause compile time error:
prog.java:5: error: 'try' without 'catch', 'finally' or resource declarations
try
^
Option
A) Error
B) Exception
Página 97 de 104
C) Run successfully
D) None
Resultado: A
Explicación: One Dimension array have size declaration as compulsory feature.
Error : array dimension missing
int []a11 = new int[]; // line 2
Option
A) All
B) line 1, 3, 4
C) line 3, 4
D) line 2, 3, 4
Resultado: C
Explicación: First two declarations are allowed and so no error. line 3 and 4 have zero and last
dimension respectively.
error: array dimension missing
int [][]arr3=new int[][];//line 3
^
error: ']' expected
int [][]arr4=new int[][2];//line 4
^
error: ';' expected
int [][]arr4=new int[][2];//line 4
Option
A) line 4, 5, 6, 7
B) All
C) No Error
D) line 4, 7
Resultado: A
Explicación: In three dimensional array have first two dimension declaration is compulsory other wise
we will get compile time error:illegal startup expression.
Página 98 de 104
Option
A) 0
0
B)[I@6bc7c054
0
C) 0 0 0 0 0
0
D) none
Resultado: B
Explicación: arr : It is giving the base address of array
arr[0] : It is giving value of array element at 0th location.
Options:
1.44
2.55
3.66
4.77
The answer is option (3)
Explicación: In the above program, we have to specially take care about the break statement. The
execution of the program is going as usual as the control flow of do-while loop but whenever compiler
encountered break statement its control comes out from the loop.
Options:
1. 111
2. 222
3. 333
4. error
The answer is option (1)
Explicación: As we all know that curly braces are optional in do and for loop. But the only criteria
is if we declare a statement without curly statement, then the statement should not be declarative.
Página 99 de 104
static void main(String[] args)
{
P:
for (int i = 2; i < 7; i++) {
if (i == 3)
continue;
if (i == 5)
break P;
s = s + i;
}
System.out.println(s);
}
}
Options:
1. 32
2. 23
3. 24
4. 42
The answer is option (3)
Explicación: In the above example, when the first for loop is executed then it holds the value of i as
2. As long as the i value is 2, the loop will not execute the if condition and will be directly as
s=s+i. Here s stores the value in a string format. Next time when s=s+i is executed, the i value
becomes 4. Both these values are stored in the s in the form of a string.
Options:
1.Compile time error
2. RuntimeException:ArithmeticException: / by zero
3. Bishal
4. GEEKS
The answer is option (4)
Explicación: In the above program we are using && operator (short-circuit operator). Whenever we use
&& operator then if the first condition is false then the control does not go to the 2nd condition
whether it is true or false. In the above program, the first condition in the if block is not true
that’s why the else part is executed.
Options:
1. Compile time error
2. GEEKS
3. Hola
4. No Output
The answer is option (1)
Explicación: In the above program, we declare two variables as final. In the while loop, it always
returns false and the control does not go inside while loop and it does not get the chance in the
entire program. Thats why we will get compile time error saying error: unreachable statement.
Options:
1. Hola Geeks
2. No Output
3. Run-time Exception
4. Compile time error
Resultado:
The answer is option (4)
Explicación: In the above program, we are throwing ArithmeticException from the class. But we have to
take care of the convention when we are using throws keyword that we can use throws keyword for
methods and constructors but not for classes.
Options:
1. Hola Geeks
2. compile time error
3. No Output
4. Run-time exception
Resultado:
The answer is option (2)
Explicación: We can use throws keyword only for throwable types. If we are trying to use for normal
java classes then we will get compile time error saying incompatible types.
an exception occurred in m1() method which has been handled in the chain-calling method m3().
Options:
1. GEEKS
2. No Output
3. Compile time error
4. Run-time Exception
Resultado:
Option
A) 10 10
B) 20 20
C) 10 20
D) 20 10
Resultado: D
Explicación: instance variable is object level variable means for every object a separate copy of
instance variable will be created.
Option
A) 3 6 9
B) 3 6 9 …. 27
C) Error
D) none
Resultado: A
Explicación: Here local variables are printed after execution. If we want to execute static variables,
then we write Test1.i or we write Test1 object.i.
Option
A) 1 3 9
B) 1 2 3 … 9
C) 3 5 7 9 11 13 15 17 19
D) None
Resultado: C
Option
A)Error
B)1 3 9
C)3 5 7 9 11 13 15 17 19
D)1 2 3 … 9
Resultado: A
Explicación: We can not declare the static variable inside the block. If we declare static variable inside the
block, then we will get the compile time error: illegal start of expression.
Option
A)Error
B)5 5
C)5 3
D)3 5
Resultado: A
Explicación:Here we are trying to declare array as static type but we can not declare the local array
as static type. If we will try to declare the local variable as static, then will get error : illegal
start of expression.