Está en la página 1de 104

ÍNDICE

Salida programa Java | Grupo 1................................................................................................6


Programa 1.................................................................................................................6
Programa 2.................................................................................................................6
Programa 3.................................................................................................................6
Programa 4.................................................................................................................7
Salida programa Java | Grupo 2................................................................................................8
Question 1.................................................................................................................8
Question 2.................................................................................................................8
Salida programa Java | Grupo 3................................................................................................8
Question 1.................................................................................................................8
Question 2.................................................................................................................9
Question 3.................................................................................................................9
Question 4................................................................................................................10
Salida programa Java | Grupo 4...............................................................................................10
Question 1................................................................................................................10
Question 2................................................................................................................10
Salida programa Java | Grupo 5 (Overloading).................................................................................11
Program 1:................................................................................................................11
Program 2:................................................................................................................11
Program 3:................................................................................................................11
Program 4:................................................................................................................12
Salida programa Java | Grupo 6...............................................................................................12
Program 1:................................................................................................................12
Programa 2:...............................................................................................................12
Programa 3:...............................................................................................................13
Programa 4:...............................................................................................................13
Salida programa Java | Grupo 7...............................................................................................14
Programa 2:...............................................................................................................14
Programa 3:...............................................................................................................15
Programa 4:...............................................................................................................15
Programa 5:...............................................................................................................16
Salida programa Java | Grupo 8...............................................................................................16
Programa 1:...............................................................................................................16
Programa 2:...............................................................................................................17
Programa 3:...............................................................................................................18
Programa 4:...............................................................................................................18
Salida Programaa Java | Grupo 9..............................................................................................19
Programa 1:...............................................................................................................19
Programa 2:...............................................................................................................19
Programa 3:...............................................................................................................20
Programa 4:...............................................................................................................20
Resultado programa Java | Grupo 10 (Garbage Collection)......................................................................21
Programa 1 :..............................................................................................................21
Programa 2 :..............................................................................................................21
Programa 3 :..............................................................................................................22
Programa 4 :..............................................................................................................23
Programa 5 :..............................................................................................................23
Salida programa Java | Grupo 11..............................................................................................24
Question 1 :..............................................................................................................24
Question 2 :..............................................................................................................24
Question 3:...............................................................................................................25
Question 4:...............................................................................................................25
Question 5:...............................................................................................................26
Question 6:...............................................................................................................26

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.

Predice la salida de los siguientes programas Java.


Programa 1.
// filename Main.java

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

(See this GFact for more details)

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.

See this GFact for details.


class Test {
private static int x;
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
return ++x;
}
} // Resultado: 1

Salida programa Java | Grupo 2.


Predice la salida de los siguientes programas 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;

public Point(int _x, int _y) {


x = _x;
y = _y;
}
}

public class Main {


public static void main(String args[]) {
Point p = new Point(); //Constructor de la clase
System.out.println("x = " + p.x + ", y = " + p.y);
}
}
Resultado:

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

Salida programa Java | Grupo 3.


Question 1.
Predice el resultado del siguiente programa java:

// 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); } }

// This class contains an instance of Test1


class Test2 {
Test1 t1 = new Test1(10);
Test2(int i) { t1 = new Test1(i); }
public static void main(String[] args) {
Test2 t2 = new Test2(5); } }
Resultado:
The output of the program is Constructor called 10 Constructor called 5.

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.

Salida programa Java | Grupo 4.

Predice el resultado del siguiente programa java:


Question 1.
// file name: Main.java

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;
}
}

public class Main {


public static void main(String[] args) {
Complex c1 = new Complex();
Complex c2 = new Complex(c1);

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.

Salida programa Java | Grupo 5 (Overloading).


Predice la salida de los siguientes programas Java.
Program 1:
// 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 main(String args[]) { gfg(null); } } //end class
Resultado:
String

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).

Salida programa Java | Grupo 6.


Nivel de dificultad : Intermedio

Predice la salida de los siguientes programas Java.


Program 1:
class First { public First() { System.out.println("a"); } }
class Second extends First { public Second() { System.out.println("b"); } }
class Third extends Second { public Third() { System.out.println("c"); } }
public class MainClass { public static void main(String[] args) { Third c = new Third(); } }

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
}

class Second extends First


{
public Second(int j)
{
super(j);
System.out.println(i);
this.i = j * 20;
}
}

public class MainClass


{
public static void main(String[] args)
{
Second n = new Second(20);
System.out.println(n.i);
}
}

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:

class ThreadEx extends Thread


{
public void run()
{
System.out.print("Hola...");
}
public static void main(String args[])
{
ThreadEx T1 = new ThreadEx();
T1.start();
T1.stop();
T1.start();
}
}

Página 13 de 104
Resultado:
Run Time Exception

Explicación:

Exception in thread “main” java.lang.IllegalThreadStateException at java.lang.Thread.start


Thread cannot be started twice.

Salida programa Java | Grupo 7.


Nivel de dificultad : Intermedio

Predice la salida de los siguientes programas Java.


Programa 1 :
public class Calculator
{
int num = 100;
public void calc(int num) { this.num = num * 10; }
public void printNum() { System.out.println(num); }

public static void main(String[] args)


{ Calculator obj = new Calculator();
obj.calc(2);
obj.printNum();
}
}
Options :

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; }

public static void main(String[] args)


{
MyStuff m1 = new MyStuff("guitar");
MyStuff m2 = new MyStuff("tv");
System.out.println(m2.equals(m1));
}

@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 "); }
}

public class Beta extends Alpha


{
public Beta() { System.out.print("beta "); }

void go()
{
type = "b ";
System.out.print(this.type + super.type);
}

public static void main(String[] args)


{
new Beta().go();
}
}
Options :
A) alpha beta b b
B) alpha beta a b
C) beta alpha b b
D) beta alpha a b

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");
}
}

public class Programmer extends Author


{
public static void write()
{
System.out.println("Writing code");
}

public static void main(String[] args)


{
Author a = new Programmer();
a.write();
}
}
Options:

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.

Salida programa Java | Grupo 8.


Nivel de dificultad : Intermedio

Predice la salida de los siguientes programas Java.

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)");
}

public static void whoAmI()


{
System.out.println("Inside static method, Person(whoAmI)");
}

public void whoAreYou()


{
who();
System.out.println("Inside virtual method, Person(whoAreYou)");
}
}

class Kid extends Person


{
private void who()
{
System.out.println("Kid(who)");
}

public static void whoAmI()


{
System.out.println("Kid(whoAmI)");
}

public void whoAreYou()


{
who();
System.out.println("Kid(whoAreYou)");
}
}
public class Gfg
{
public static void main(String args[])
{
Person p = new Kid();
p.whoAmI();
p.whoAreYou();
}
}
Resultado:
Inside static method, People(whoAmI)
Kid(who)
Kid(whoAreYou)

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.

Salida Programaa Java | Grupo 9.


Nivel de dificultad : Intermedio
Predice la salida de los siguientes programas Java.

Programa 1:

class Gfg
{
// constructor
Gfg()
{
System.out.println("ElCaminoDe");
}
static Gfg a = new Gfg(); //line 8

public static void main(String args[])


{
Gfg b; //line 12
b = new Gfg();
}
}
Resultado:
ElCaminoDe
ElCaminoDe
Explicación:
We know that static variables are called when a class loads and static variables are called only once. Now line 13 results
to creation of object which inturn calls the constructor and “ElCaminoDe” is printed second time.
If in line 8 static variable would not have been used the object would have been called recursively infinitely leading to
StackOverFlow error. See this for a sample run.

Programa 2:
class Gfg
{
static int num;
static String mystr;

// constructor
Gfg()
{
num = 100;
mystr = "Constructor";
}

// First Static block


static
{
System.out.println("Static Block 1");
num = 68;
mystr = "Block1";
}

// Second static block


static
{
System.out.println("Static Block 2");
num = 98;
mystr = "Block2";
}

public static void main(String args[])

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);

Integer c = 100, d = 100;


System.out.println(c == d);
}
}
Resultado:
false
true
Explicación:
In the source code of Integer object we will find a method ‘valueOf’ in which we can see that the range of the Integer
object lies from IntegerCache.low(-128) to IntegerCache.high(127). Therefore the numbers above 127 will not give

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.

Resultado programa Java | Grupo 10 (Garbage Collection).


Prerequisito – Garbage Collection in Java

Nivel de dificultad : Intermedio

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.

Predice el resultado del siguiente programa java:

Programa 1 :
public class Test
{
public static void main(String[] args) throws InterruptedException
{
String str = new String("ElCaminoDe");

// making str eligible for gc


str = null;

// calling garbage collector


System.gc();

// waiting for gc to complete


Thread.sleep(1000);

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();

// making t eligible for garbage collection


t = null;

// calling garbage collector


System.gc();

// waiting for gc to complete


Thread.sleep(1000);

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();

// making t eligible for garbage collection


t = null;

// calling garbage collector


System.gc();

// waiting for gc to complete


Thread.sleep(1000);

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 ;

static int count =0;

public static void main(String[] args) throws InterruptedException


{
Test t1 = new Test();

// making t1 eligible for garbage collection


t1 = null; // line 12

// calling garbage collector


System.gc(); // line 15

// waiting for gc to complete


Thread.sleep(1000);

// making t eligible for garbage collection,


t = null; // line 21

Página 22 de 104
// calling garbage collector
System.gc(); // line 24

// waiting for gc to complete


Thread.sleep(1000);

System.out.println("finalize method called "+count+" times");

@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
}

static void m1()


{
Test t1 = new Test();
Test t2 = new Test();
}
}

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

static Test m1(Test temp)


{
temp = new Test();
return temp;
}
}
Question :
How many objects are eligible for garbage collection after execution of line 8?
Answer :
1
Explicación:
By the time line 8 has executed, the only object without a reference is the one generated i.e as a result of line 6.
Remember that “Java is strictly pass by value” so the reference variable t1 is not affected by the m1() method. We
can check it using finalize() method. The statement “System.out.println(this.hashcode())” in finalize() method print the
object hashcode value on which finalize() method is called,and then just compare the value with other objects hashcode
values created in main method.

Salida programa Java | Grupo 11.


Predice el resultado del siguiente programa java:
Question 1 :
public class Base
{
private int data;

public Base()
{
data = 5;
}

public int getData()


{
return this.data;
}
}

class Derived extends Base


{
private int data;
public Derived()
{
data = 6;
}
private int getData()
{
return data;
}

public static void main(String[] args)


{
Derived myData = new Derived();
System.out.println(myData.getData());
}
}

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;

public int getData()


{
return this.data;
}
public int getData(int value)
{
return (data+1);
}
public int getData(int... value)
{
return (data+2);
}

public static void main(String[] args)


{
Test temp = new Test();
System.out.println(temp.getData(7, 8, 12));
}
}

a) Either Compile time or Runtime error


b) 8.
c) 10
d) 7
Answer:
(d)
Explicación:
(int… values) is passed as parameter to a method when you are not aware of the number of input parameter but know that the type
of parameter(in this case it is int). When a new object is made in the main method, variable data is initialized to 5. A call
to getData() method with attributes (7, 8 ,12), makes a call to the third getData() method, which increments the value of data
variable by 2 and return 7.

Question 3:
public class Base
{
private int multiplier(int data)
{
return data*5;
}
}

class Derived extends Base


{
private static int data;
public Derived()
{
data = 25;
}
public static void main(String[] args)
{
Base temp = new Derived();
System.out.println(temp.multiplier(data));
}

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:

Which of the following is FALSE about finally block?


a) For each try block, there can be only 1 finally block.
b) finally block will not be executed if Programa exits by calling System.exit();
c) If an exception is not handled in the catch statement, before terminating the program, JVM executes
the finally block
d) finally block contains important code segment and so the code inside finally block is executed
with/without the presence of try block in java code.

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;

public class newclass


{
public static void main(String[] args)
{
try
{
System.out.printf("%d", 1);
throw(new Exception());
}
catch(IOException e)
{
System.out.printf("%d", 2);
}
catch(EmptyStackException e)
{
System.out.printf("%d", 3);
}
catch(Exception e)
{
System.out.printf("%d", 4);
}
finally
{
System.out.printf("%d", 5);
}
}
}

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;
}

public static void main(String[] args)


{
System.out.printf("%d", (new javaclass()).function() + myMethod());
}
}
a) 123
b) 45
c) 12345
d) 1239
Answer
(d)
Explicación:
static blocks in Java are executed even before the call to main is made by the compiler. In the main method, a new object of
javaclass is made and its function() method is called which return 4. Number 5 is returned by a call to static function
myMethod(). 4+5 = 9. Therefore, the output of the Programa is 1239, because 123 is printed
on the console even before main method executes and main method on execution returns 9.

Resultado programa Java | Grupo 12.

Predice el resultado del siguiente programa java:

1) ¿Cuál será el resultado del programa?


public class Test implements Runnable
{
public void run()
{
System.out.printf("%d",3);
}
public static void main(String[] args) throws InterruptedException
{
Thread thread = new Thread(new Test());
thread.start();
System.out.printf("%d",1);
thread.join();
System.out.printf("%d",2);
}

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.

2) ¿Cuál será el resultado del programa?


public class Test
{
private static int value = 20;
public int s = 15;
public static int temp = 10;
public static class Nested
{
private void display()
{
System.out.println(temp + s + value);
}
}

public static void main(String args[])


{
Test.Nested inner = new Test.Nested();
inner.display();
}
}

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);
^

3) ¿Cuál será el resultado del programa?

import java.io.*;
public class Test
{
public void display() throws IOException
{
System.out.println("Test");
}

class Derived extends Test


{
public void display() throws IOException
{
System.out.println("Derived");
}
public static void main(String[] args) throws IOException
{
Derived object = new Derived();
object.display();
}
}

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.

4) ¿Cuál será el resultado del programa?


public class Test extends Thread
{
public void run()
{
System.out.printf("Test ");
}
public static void main(String[] args)
{
Test test = new Test();
test.run();
test.start();
}
}

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.

5) ¿Cuál será el resultado del programa?

public class Test extends Thread


{
public static void main(String[] args)
{
String a = "ElCaminoDe";
String b = new String(a);
int value = 0;
value = (a==b) ? 1:2;
if(value == 1)
{
System.out.println("ElCaminoDe");
}
else if(value == 2)
{
System.out.println("Geeks for Geeks");
}
else
{
System.out.println("GFG");
}

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.

6) ¿Cuál será el resultado del programa?

public class Test


{
try
{
public Test()
{
System.out.println("ElCaminoDe");
throw new Exception();
}
}
catch(Exception e)
{
System.out.println("GFG");
}
public static void main(String[] args)
{
Test test = new Test();
}
}

a) ElCaminoDe
b) GFG
c) Compilation error
d) None of the above
Ans:
(c)

Explicación:
Constructors cannot be enclosed in try/catch block.

7) For the given code select the correct answer.


public interface Test
{
public int calculate();
protected interface NestedInterface
{
public void nested();
}
}

a) Compile time error due to NestedInterface


b) Compile time error due to access modifier of NestedInterface
c) No Compile time error
d) NestedInterface cannot hold any function declaration.

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

8) Which of the following are true about constructor declaration?

a) Constructors can be declared final.


b) Constructors can be surrounded by try/catch blocks.
c) Constructor cannot throw exception.
d) Constructors can hold synchronized code(so that each thread can access constructor sequentially).

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

Predice el resultado del siguiente programa java:

1) ¿Cuál será el resultado del programa?

import java.util.*;

public class priorityQueue


{
public static void main(String[] args)
{
PriorityQueue<Integer> queue =
new PriorityQueue<>();
queue.add(11);
queue.add(10);
queue.add(22);
queue.add(5);
queue.add(12);
queue.add(2);

while (queue.isEmpty() == false)


System.out.printf("%d ", queue.remove());

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.

2) ¿Cuál será el resultado del programa?


import java.util.*;

public class Treeset


{
public static void main(String[] args)
{
TreeSet<String> treeSet = new TreeSet<>();

treeSet.add("Geeks");
treeSet.add("for");
treeSet.add("Geeks");
treeSet.add("ElCaminoDe");

for (String temp : treeSet)


System.out.printf(temp + " ");

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’.

3) ¿Cuál será el resultado del programa?


import java.util.*;

public class linkedList


{
public static void main(String[] args)
{
List<String> list1 = new LinkedList<>();
list1.add("Geeks");
list1.add("for");
list1.add("Geeks");
list1.add("GFG");
list1.add("ElCaminoDe");

List<String> list2 = new LinkedList<>();


list2.add("Geeks");

list1.removeAll(list2);

for (String temp : list1)


System.out.printf(temp + " ");

System.out.println();
}
}

a) for Geeks GFG ElCaminoDe


b) for GFG ElCaminoDe
c) for GFG for
d) for GFG ElCaminoDe
Ans.
(d)

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.

4) Which of the given choices is a possible output ?


import java.util.*;

public class hashSet


{
public static void main(String[] args)
{
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Geeks");
hashSet.add("for");
hashSet.add("Geeks");
hashSet.add("ElCaminoDe");

System.out.println(hashSet);

}
}

a) [Geeks, for, Geeks, ElCaminoDe]


b) [ElCaminoDe, Geeks, for]

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.

5) ¿Cuál será el resultado del programa?


import java.util.*;

public class stack


{
public static void main(String[] args)
{
List<String> list = new LinkedList<>();
list.add("Geeks");
list.add("for");
list.add("Geeks");
list.add("ElCaminoDe");
Iterator<Integer> iter = list.iterator();

while (iter.hasNext())
System.out.printf(iter.next() + " ");

System.out.println();
}
}

a) Geeks for Geeks ElCaminoDe


b) ElCaminoDe Geeks for Geeks
c) Runtime Error
d) Compilation Error
Answer.
(d)

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.

Resultado programa Java | Set 14 (Constructors).


Prerequisito – Java Constructors

Predice el resultado del siguiente programa java:

1) ¿Cuál será el resultado del programa?

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.

2) ¿Cuál será el resultado del programa?

public class Test implements Runnable


{
public void run()
{
System.out.printf(" Thread's running ");
}

try
{
public Test()
{
Thread.sleep(5000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}

public static void main(String[] args)


{
Test obj = new Test();
Thread thread = new Thread(obj);
thread.start();
System.out.printf(" GFG ");
}
}

a) GFG Thread’s running


b) Thread’s running GFG
c) Compilation error
d) Runtimer error
Answer
(c)
Explicación:

A constructor cannot be enclosed inside a try/catch block.

3) ¿Cuál será el resultado del programa?

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();
}
}

a) Constructor called Method called


b) Compilation error
c) Runtime error
d) None of the above
Answer
(a)

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?

public class Test


{
public Test()
{
System.out.printf("1");
new Test(10);
System.out.printf("5");
}
public Test(int temp)
{
System.out.printf("2");
new Test(10, 20);
System.out.printf("4");
}
public Test(int data, int temp)
{
System.out.printf("3");

public static void main(String[] args)


{
Test obj = new Test();

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).

5) ¿Cuál será el resultado del programa?

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();
}

public static void main(String[] args)


{
Derived obj = new Derived();
System.out.printf(s);
}
}
a) 21 Super Class
b) Super Class 21
c) Compilation error
d) 12 Super Class

Ans.
(c)

Explicación:
Constructor call to super class must be the first statement in the constructor of the Derived class.
private

Salida programa Java | Grupo 15 (Inner Classes).

Predice el resultado del siguiente programa java:


Prerequisito :- Local inner classes , anonymous inner classes

1) ¿Cuál será el resultado del programa?


public class Outer
{
public static int temp1 = 1;
private static int temp2 = 2;
public int temp3 = 3;
private int temp4 = 4;

public static class Inner


{
private static int temp5 = 5;

private static int getSum()


{
return (temp1 + temp2 + temp3 + temp4 + temp5);
}
}

public static void main(String[] args)


{
Outer.Inner obj = new Outer.Inner();
System.out.println(obj.getSum());
}

}
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.

2) ¿Cuál será el resultado del programa?


public class Outer
{
private static int data = 10;
private static int LocalClass()
{
class Inner
{
public int data = 20;
private int getData()
{
return data;
}
};
Inner inner = new Inner();
return inner.getData();
}

public static void main(String[] args)


{
System.out.println(data * LocalClass());
}
}

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.

3) ¿Cuál será el resultado del programa?


interface Anonymous
{
public int getValue();
}
public class Outer
{
private int data = 15;
public static void main(String[] args)
{
Anonymous inner = new Anonymous()
{
int data = 5;
public int getValue()
{
return data;
}
public int getData()
{
return data;
}
};
Outer outer = new Outer();
System.out.println(inner.getValue() + inner.getData() + outer.data);
}

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.

4) ¿Cuál será el resultado del programa??


public class Outer
{
private int data = 10;

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

5) ¿Cuál será el resultado del programa?

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);
}

public static void main(String[] args)


{
Outer obj = new Outer();
obj.InnerMethod();
}
}

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.

Salida programa Java | Grupo 16 (Threads).


Predice el resultado del siguiente programa java:
Prerequisitos: multi-threading in java , Life cycle and states of a thread , Joining threads in java , start() method in java

1)¿Cuál será el resultado del programa?

public class Test implements Runnable


{
public void run()
{
System.out.printf("GFG ");
System.out.printf("Geeks ");
}
public static void main(String[] args)
{
Test obj = new Test();
Thread thread = new Thread(obj);

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.

2)¿Cuál será el resultado del programa?

public class Test implements Runnable


{
public void run()
{
System.out.printf("GFG ");
}
public static void main(String[] args) throws InterruptedException
{
Thread thread1 = new Thread(new Test());
thread1.start();
thread1.start();
System.out.println(thread1.getState());
}
}

a) GFG GFG TERMINATED


b) GFG TERMINATED
c) Compilation Error
d) Runtime Error

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.

3)¿Cuál será el resultado del programa?

public class Test extends Thread implements Runnable


{
public void run()
{
System.out.printf("GFG ");
}
public static void main(String[] args) throws InterruptedException
{
Test obj = new Test();
obj.run();
obj.start();
}
}

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.

4)¿Cuál será el resultado del programa?

class myThread implements Runnable


{
public void run()
{
Test.obj.notify();
}
}

public class Test implements Runnable


{
public static Test obj;
private int data;
public Test()
{
data = 10;
}
public void run()
{
obj = new Test();
obj.wait();
obj.data += 20;

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();

System.out.printf(" GFG - ");


}
}
a) 30 GFG –
b) GFG – 30
c) GFG –

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.

5)¿Cuál será el resultado del programa?


import java.util.concurrent.*;

public class Test implements Runnable


{
public static CyclicBarrier barrier = new CyclicBarrier(3);
public void run()
{

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.

Salida programa Java | Grupo 17.


Predice el resultado del siguiente programa java:
1) What is the output of following program?
filter_none
edit
play_arrow
brightness_4

public class Test


{
private static float temp()
{
public static float sum = 21;
return(--(sum));
}
public static void main(String[] args)
{
Test test = new Test();
System.out.println(test.temp());
}
}
a) 21
b) 20
c) Compilation error
d) Runtime error

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.

2) ¿Cuál será el resultado del programa?

public class Test


{
public static void main(String[] args)
{
int value = 3, sum = 6 + -- value;

int data = --value + ++value / sum++ * value++ + ++sum % value--;


System.out.println(data);
}
}

a) 1
b) 2
c) 0
d) 3
Ans.
(b)

Explicación:
Refer to Operator precedence rule in java.

3) ¿Cuál será el resultado del programa?

public class Test


{
public static void main(String[] args)
{
int temp = 40;
if(temp == 30 && temp/0 == 4)
{
System.out.println(1);
}
else
{
System.out.println(2);
}
}
}

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.

4) ¿Cuál será el resultado del programa?

public class Test


{
public static void main(String[] args)
{

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.

5) ¿Cuál será el resultado del programa?


public class Test
{
public static void main(String[] args)
{
int temp = null;
Integer data = null;
System.out.println(temp + " " + data);
}
}
a) null null
b) Compilation error due to temp
c) Compilation error due to data
d) Runtime error
Ans.
(b)

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.

Salida programa Java | Grupo 18 (Overriding).


Prerequisito – Overriding in Java

1) ¿Cuál será el resultado del programa?


class Derived
{
protected final void getDetails()
{
System.out.println("Derived class");
}
}

public class Test extends Derived


{
protected final void getDetails()
{
System.out.println("Test class");
}
public static void main(String[] args)
{
Derived obj = new Derived();
obj.getDetails();
}
}
a) Derived class
b) Test class
c) Runtime error
d) Compilation error

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 ?

2) ¿Cuál será el resultado del programa?


class Derived
{
public void getDetails(String temp)
{
System.out.println("Derived class " + temp);
}
}

public class Test extends Derived


{
public int getDetails(String temp)
{
System.out.println("Test class " + temp);
return 0;
}
public static void main(String[] args)
{
Test obj = new Test();
obj.getDetails("GFG");
}
}

a) Derived class GFG


b) Test class GFG
c) Compilation error
d) Runtime error
Ans.
(c)

Explicación:
The overriding method must have same signature, which includes, the argument list and the return type. For details, See :
Overriding in Java

3) ¿Cuál será el resultado del programa?


class Derived
{
public void getDetails()
{
System.out.println("Derived class");
}
}

public class Test extends Derived


{
protected void getDetails()
{
System.out.println("Test class");
}
public static void main(String[] args)
{
Derived obj = new Test(); // line xyz
obj.getDetails();
}
}

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.

4) ¿Cuál será el resultado del programa?


import java.io.IOException;

class Derived
{
public void getDetails() throws IOException //line 23
{
System.out.println("Derived class");
}
}

public class Test extends Derived


{
public void getDetails() throws Exception //line 24
{
System.out.println("Test class");
}
public static void main(String[] args) throws IOException //line 25
{
Derived obj = new Test();
obj.getDetails();
}
}

a) Compilation error due to line 23


b) Compilation error due to line 24
c) Compilation error due to line 25
d) All the above
Ans.
(b)

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.

5) ¿Cuál será el resultado del programa?


class Derived
{
public void getDetails()
{
System.out.printf("Derived class ");
}
}

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();
}
}
a) Test class Derived class
b) Derived class Test class
c) Compilation error
d) Runtime error
Ans. (a)

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();
}
}

a) Test class Derived class


b) Derived class Test class
c) Compilation error
d) Runtime error
Ans.
(a)
Explicación:

super keyword is used to invoke the overridden method from a child class explicitly.

Salida programa Java | Grupo 19.


Predice la salida de los siguientes programas Java.
Program 1 :

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());
}
}

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:

No magic of polymorphism here; the instance variable c from A is simply hidden in B


– a.c is ‘A’ because it is so Grupo in the class A
– a.getValue() returns ‘B’ because the object is of type B

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;

public static void main(String[] args)


{
HasStatic hs1 = new HasStatic();
hs1.x++;

HasStatic hs2 = new HasStatic();


hs2.x++;

hs1 = new HasStatic();


hs1.x++;

HasStatic.x++;
System.out.println("Adding to 100, x = " + x);

test t1 = new test();


t1.y++;

test t2 = new test();


t2.y++;

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

Salida programa Java | Grupo 20 (Inheritance).


Prerequisito – Inheritance in Java

Predice la salida de los siguientes programas Java.

Program 1 :

class A
{
public Top(String s)
{
System.out.print("A");

Página 49 de 104
}
}

public class B extends A


{
public B(String s)
{
System.out.print("B");
}
public static void main(String[] args)
{
new B("C");
System.out.println(" ");
}
}

Resultado: Compilation fails


3: error: invalid method declaration; return type required
public Top(String s)
^
1 error
Explicación: The implied super() call in B’s constructor cannot be satisfied because there isn’t a no-
arg constructor in A. A default, no-arg constructor is generated by the compiler only if the class has
no constructor defined explicitly.For detail See – Constructors in Java

Program 2 :
class Clidder
{
private final void flipper()
{
System.out.println("Clidder");
}
}

public class Clidlet extends Clidder


{
public final void flipper()
{
System.out.println("Clidlet");
}
public static void main(String[] args)
{
new Clidlet().flipper();
}
}
Resultado:
Clidlet
Explicación: Although a final method cannot be overridden, in this case, the method is private, and
therefore hidden. The effect is that a new, accessible, method flipper is created. Therefore, no
polymorphism occurs in this example, the method invoked is simply that of the child class, and no
error occurs.

Program 3 :
class Alpha
{
static String s = " ";
protected Alpha()
{
s += "alpha ";
}
}
class SubAlpha extends Alpha
{
private SubAlpha()
{
s += "sub ";
}
}

public class SubSubAlpha extends Alpha


{

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()");
}
}

class Parent extends Grandparent

Página 51 de 104
{
public void Print()
{
System.out.println("Parent's Print()");
}
}

class Child extends Parent


{
public void Print()
{
super.super.Print();
System.out.println("Child's Print()");
}
}

public class Main


{
public static void main(String[] args)
{
Child c = new Child();
c.Print();
}
}

Resultado:

Compiler Error in super.super.Print()

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

Related Article: Quiz on Inheritance in Java

Resultado programa Java | Grupo 21 (Type Conversions).


Predice el resultado del siguiente programa java:
Prerequisito – Type Conversions in Java with Examples

1) ¿Cuál será el resultado del programa?


public class Test
{
public static void main(String[] args)
{
int value = 554;
String var = (String)value; //line 1
String temp = "123";
int data = (int)temp; //line 2
System.out.println(data + var);
}
}
a) 677
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. (d)
Explicación: Converting from int to String as well as converting from String to int is not allowed in
java.

2) ¿Cuál será el resultado del programa?


ublic class Test
{
public static void main(String[] args)
{
double data = 444.324;
int value = data;
System.out.println(data);
}
}

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.

3) ¿Cuál será el resultado del programa?


public class Test
{
public static void main(String[] args)
{
double data = 444.324;
int sum = 9;
float value = 5.1f;
System.out.println(data + sum + value);

}
}

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.

4) ¿Cuál será el resultado del programa?


public class Test
{
public static void main(String[] args)
{
byte var = 1;
var = (byte) var * 0; //line 1
byte data = (byte) (var * 0); //line 2
System.out.println(var);
}
}

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.

5) ¿Cuál será el resultado del programa?


public class Test
{
public static void main(String[] args)
{
System.out.println((100/25.0)*Integer.parseInt("5") + 50);
}
}

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

1) ¿Cuál será el resultado del programa?


public class Test
{
public int getData() //getdata() 1
{
return 0;
}
public long getData() //getdata 2
{
return 1;
}
public static void main(String[] args)
{
Test obj = new Test();
System.out.println(obj.getData());
}
}

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.

2) ¿Cuál será el resultado del programa?


public class Test
{
public int getData(String temp) throws IOException
{
return 0;
}
public int getData(String temp) throws Exception
{
return 1;
}
public static void main(String[] args)
{
Test obj = new Test();
System.out.println(obj.getData("GFG"));
}
}

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.

3) ¿Cuál será el resultado del programa?


public class Test
{
private String function()
{
return ("GFG");
}
public final static String function(int data)
{
return ("ElCaminoDe");
}

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.

4) ¿Cuál será el resultado del programa?


public class Test
{
private String function(String temp, int data)
{
return ("GFG");
}
private String function(int data, String temp)
{
return ("ElCaminoDe");
}
public static void main(String[] args)
{
Test obj = new Test();
System.out.println(obj.function(4, "GFG"));
}
}

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.

5) ¿Cuál será el resultado del programa?


public class Test
{
private String function(String temp, int data, int sum)
{
return ("GFG");
}
private String function(String temp, int data)
{
return ("ElCaminoDe");
}
public static void main(String[] args)
{
Test obj = new Test();
System.out.println(obj.function("GFG", 0, 20));
}
}

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.

Salida programa Java | Grupo 23 (Inheritance).


Predice el resultado del siguiente programa java:

Página 55 de 104
Prerequisito: Inheritance in Java

1) ¿Cuál será el resultado del programa?


public class A extends B
{
public static String sing()
{
return "fa";
}
public static void main(String[] args)
{
A a = new A();
B b = new A();
System.out.println(a.sing() + " " + b.sing());
}
}
class B
{
public static String sing()
{
return "la";
}
}

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

2) ¿Cuál será el resultado del programa?


class Building
{
Building()
{
System.out.println("Geek-Buiding");
}
Building(String name)
{
this();
System.out.println("Geek-building: String Constructor" + name);
}
}
public class House extends Building
{
House()
{
System.out.println("Geek-House ");
}
House(String name)
{
this();
System.out.println("Geek-house: String Constructor" + name);
}
public static void main(String[] args)
{
new House("Geek");
}
}
Resultado:
Geek-Buiding
Geek-House
Geek-house: String ConstructorGeek
Explicación: Constructors call their superclass default constructor, which execute first, and that
constructors can be overloaded.
First House constructor with one argument is called and flow shifts to no-arg constructor of house
class due to this(). From here, due to superclass default constructor, no-arg constructor of building
is called. Hence the order shown. For detail See – Constructors in Java

3) ¿Cuál será el resultado del programa?

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!");
}
}
}

Resultado: Compiler error


Explicación: exception ArithmeticException has already been caught is shown. Terminal
Ordering of catch blocks is important The More specific/subclass (ArithmeticException) need to come
earlier and more general/superclass (Exception) need to be written later. The program will execute
correctly if the order of Arithmetic exception and general exception is interchanged.

5) ¿Cuál será el resultado del programa?


abstract class Vibrate
{
static String s = "-";
Vibrate()
{
s += "v";
}
}
public class Echo extends Vibrate
{
Echo()

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 + " ");
}
}

Resultado: block -ve2e made -ve2e


Explicación: The static initialization block is the only place where an instance of Echo is created.
Then the Echo instance is created, Echos no-arg constructor calls its 1-arg constructor, which then
calls Vibrates constructor (which then secretly calls Objects constructor). At that point, the various
constructors execute, starting with Objects constructor and working back down to Echos no-arg
constructor. see static keyword

Salida programa Java | Grupo 24 (Inheritance)Java Inheritance.


Predice el resultado del siguiente programa java:
Question 1
Output of following Java Program?
class Base {
public void show() {
System.out.println("Base::show() called");
}
}

class Derived extends Base {


public void show() {
System.out.println("Derived::show() called");
}
}

public class Main {


public static void main(String[] args) {
Base b = new Derived();;
b.show();
}
}
Derived::show() called
B Base::show() called
Run on IDE
Java Inheritance
Discuss it

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");
}
}

class Derived extends Base {


public void show() {

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 Derived extends Base {


public static void show() {
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
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?

1) Private methods are final.


2) Protected members are accessible within a package and
inherited classes outside the package.
3) Protected methods are final.
4) We cannot override private methods.
Java Inheritance
Discuss it

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 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();
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"); }
}

class Derived extends Base {


private void foo() { System.out.println("Derived"); }
}

public class Main {


public static void main(String args[]) {
Base b = new Derived();
b.foo();
}
}

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()");
}
}

class Parent extends Grandparent {


public void Print() {
System.out.println("Parent's Print()");
}
}

class Child extends Parent {


public void Print() {
super.super.Print();
System.out.println("Child's Print()");
}
}

public class Main {


public static void main(String[] args) {
Child c = new Child();
c.Print();
}

Compiler Error in super.super.Print()


B Grandparent's Print()
Parent's Print()
Child's Print()
C Runtime Error

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 Parent extends Grandparent {


public void Print() {
super.Print();
System.out.println("Parent's Print()");
}
}

class Child extends Parent {


public void Print() {
super.Print();
System.out.println("Child's Print()");
}
}

class Main {
public static void main(String[] args) {
Child c = new Child();
c.Print();
}
}

Question 9
final class Complex {

private final double re;


private final double im;

public Complex(double re, double im) {


this.re = re;
this.im = im;
}

public String toString() {


return "(" + re + " + " + im + "i)";
}
}

class Main {
public static void main(String args[])
{
Complex c = new Complex(10, 15);
System.out.println("Complex number is " + c);
}
}

Run on IDE

Complex number is (10.0 + 15.0i)


B
Compiler Error
C
Complex number is SOME_GARBAGE
D
Complex number is Complex@8e2fb5
Here 8e2fb5 is hash code of c
Java Inheritance
Discuss it

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.

Java Abstract Class and Interface Discuss it

Question 2.
Which of the following is true about interfaces in java.

1) An interface can contain following type of members.


....public, static, final fields (i.e., constants)
....default and static methods with bodies

2) An instance of interface can be created.

3) A class can implement multiple interfaces.

4) Many classes can implement the same interface.

1, 3 and 4
B
1, 2 and 4
C
2, 3 and 4
D
1, 2, 3 and 4

Java Abstract Class and Interface Discuss it

Question 3.
Predict the output of the following program.

abstract class demo


{
public int a;
demo()
{
a = 10;
}

abstract public void Grupo();

abstract final public void get();

class Test extends demo


{

public void Grupo(int a)


{
this.a = a;
}

final public void get()

Página 63 de 104
{
System.out.println("a = " + a);
}

public static void main(String[] args)


{
Test obj = new Test();
obj.Grupo(20);
obj.get();
}
}

A
a = 10
B
a = 20
C
Compilation error

Java Abstract Class and Interface


Discuss it

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.

Which of the following is used to make an Abstract class?


Java Abstract Class and Interface UGC NET CS 2015 Dec – III
Discuss it

Question 7

A Declaring it abstract using the virtual keyword


B Making at least one member function as virtual function
C Making at least one member function as pure virtual function
D Making all member function const
We can make a class abstract by
Java Abstract Class and Interface ISRO CS 2008
Discuss it

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.

Salida programa Java | Grupo 26.


Predice el resultado del siguiente programa java:

Question 1: What is the output of this program?

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.

Question 2: What is the output of this program?

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.

Question 3: What is the output of this program?


class comma_operator
{
public static void main(String args[])
{
int sum = 0;
for (int i = 0, j = 0; i < 5 & j < 5; ++i, j = i + 1)
sum += i;
System.out.println(sum);
}
}
options:
a) 5
b) 6
c) 14
d) compilation error
Respuesta: b
Explicación: Using comma operator , we can include more than one statement in the initialization and
iteration portion of the for loop. Therefore both ++i and j = i + 1 is executed i gets the value : 0,
1, 2, 3, and j gets the values : 0, 1, 2, 3, 4, 5.

Question 4. What will be the output of the program?


class Geeks
{
public static void main(String [] args)
{
Geeks g = new Geeks();
g.start();
}

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

Question5. What will be the output of the program?


class BitShift
{
public static void main(String [] args)
{
int x = 0x80000000;
System.out.print(x + " and ");
x = x >>> 31;
System.out.println(x);
}
}

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

Salida programa Java | Grupo 27.


Predice el resultado del siguiente programa java:

Question 1. What is the output of the following?


import java.util.*;

public class Test {


public static void main(String[] args)
{
int[] x = new int[3];
System.out.println("x[0] is " + x[0]);
}
}

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.

Question 2. What is the output of the following?

Página 67 de 104
import java.util.*;

public class Test {


public static void main(String[] args)
{
int[] x = { 120, 200, 016 };
for (int i = 0; i < x.length; i++)
System.out.print(x[i] + " ");
}
}

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.*;

public class Test {


public static void main(String args[])
{
String s1 = "java";
String s2 = "java";
System.out.println(s1.equals(s2));
System.out.println(s1 == s2);
}
}
Options :
A. false true
B. false false
C. true false
D. true true
Answer : D
Explicación: Both == and equals() are same things and evaluate to true/false.

Question 4. What is the output of the following?


import java.util.*;

public class Test {


public static void main(String args[])
{
String S1 = "S1 =" + "123" + "456";
String S2 = "S2 =" + (123 + 456);
System.out.println(S1);
System.out.println(S2);
}
}

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.

Question 5. What is the output of the following?

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.

Salida programa Java| Grupo 28.


Predice el resultado del siguiente programa java:

Question 1. What is the output of the following question?


class Test {
int a = 10;
static int b = 20;

public
static void main(String[] args)
{
Test t1 = new Test();
t1.a = 100;
t1.b = 200;

Test t2 = new Test();

System.out.println("t1.a =" + t1.a + " t1.b =" + t1.b);


System.out.println("t2.a =" + t2.a + " t2.b =" + t2.b);
}
}

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.

Question 2. What is the output of the following question?


class Test2 {
public
static void main(String[] args)
{
byte x = 12;
byte y = 13;
byte result = x + y;
System.out.print(result);
}
}

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.

Question 4. What is the output of the following question?


class Test4 {
public
static void main(String[] args)
{
int x = 0198;
int y = 0xfree;
int result = x + y;
System.out.print(x + " : " + y + " : " + result);
}
}

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.

Question 5. What is the output of the following question?


class Test5 {
public
static void main(String[] args)
{
final int a = 1, b = 5;

for (int i = 0; a < b; i++) {


System.out.println("Hola");
}
System.out.println("Hi");
}
}

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”.

Resultado programa Java | Grupo 29.

Predice el resultado del siguiente programa java:

Question 1. What is the output of the following question?


class Test1 {
public
static void main(String[] args)
{
int String = 65;
int Runnable = 97;

System.out.print(String + " : " + Runnable);


}
}

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;

System.out.println(if + " : " + else);


}
}

Option
A) Error
B) A : B
C) 65 : 97
D) None

Resultado: A
Explicación: We can’t use reserved words as identifiers.

Question 3. What is the output of the following question?


class Test3 {
public
static void main(String[] args)
{
int x = 1;

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.

Question 4. What is the output of the following question?


class Test4 {
public
static void main(String[] args)
{
double d1 = 123.456;
double d2 = 12_3.4_5_6;
double d3 = 12_3.4_56;

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.

Question 5. What is the output of the following question?


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: A
Explicación: We can use the ‘_’ (under score) symbol only between the digits. if we are using anywhere
else we will get compile time error – Illegal under score.

Resultado programa Java | Grupo 30.


Predice el resultado del siguiente programa java:

Question 1 What is the output of this program ?


public class Prg {
public static void main(String args[])
{
System.out.print('A' + 'B');
}
}

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?

public class Prg {


public static void main(String args[])
{
System.out.print("A" + "B" + 'A' + 10);
}
}

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.

Question. 4 What is the output?

public class Prg {


public static void main(String[] args)
{
char[] str = { 'i', 'n', 'c', 'l', 'u',
'd', 'e', 'h', 'e', 'l', 'p' };
System.out.println(str.toString());
}
}
OPTION
a) includehelp
b) Error
c) [C@19e0bfd (Memory Address)
d) NULL
Respuesta c
Explicación: [C@19e0bfd (Memory Address) : str is a character array, if you try to print
str.toString() it will not converted to string because str is an object of character array that will
print an address in string format.

Question. 5 what is output of this program?


public class prg {

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.

Resultado programa Java | Grupo 31 (Arrays en Java).


Predice el resultado del siguiente programa java:
Prerequisito : Arrays in Java

1. ¿Cuál será el resultado del programa?

public class Test {


public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
System.out.println(arr);
}
}

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.

2. ¿Cuál será el resultado del programa?


public
class Test {
public
static void main(String[] args)
{
int b = 2147483648;
System.out.println(b);
}
}

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.

3. What will be the output of the following program?

public class Test


{

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.

4. ¿Cuál será el resultado del programa?

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.

5. ¿Cuál será el resultado del programa?

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.

Resultado programa Java | Grupo 32 (Arrays en Java).


Predice el resultado del siguiente programa java:
Prerequisito : Arrays in Java

Question 1. What is the output of following program?


class ArrayDemo {
public static void main(String[] args)
{
int arr1[] = { 1, 2, 3, 4, 5 };
int arr2[5] = { 1, 2, 3, 4, 5 };

for (int i = 0; i < 5; i++)


System.out.print(arr1[i] + " ");

System.out.println();

for (int i = 0; i < 5; i++)


System.out.print(arr2[i] + " ");
}
}

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

Question 2. What is the output of following program?


class ArrayDemo1 {
public static void main(String[] args)
{
int arr1[], arr2[];
int[] arr3, [] arr4;
}
}

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.

Question 3. What is the output of following program?


class ArrayDemo1 {

Página 76 de 104
public static void main(String[] args)
{
int arr1[] = new int[0];
int arr2[] = new int[-1];

System.out.print(arr1.length + " : " + arr2.length);


}
}
Option
A) 0 : 0
B) 0 : -1
C) Compiler Error
D) Run time Exception

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.

Question 4. What is the output of following program?


class ArrayDemo1 {
public static void main(String[] args)
{
int arr1[] = new int[2147483647];
int arr2[] = new int[2147483648];

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.

Question 5. What is the output of following program?

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.

Resultado programa Java | Grupo 33 (Collections).


Predice el resultado del siguiente programa java:
Prerequisito: Java – Collections

1. What is the output of following Java Program?


import java.util.ArrayList;
class Demo {
public void show()
{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(7);
list.add(1);
for (int number : list) {
System.out.print(number + " ");
}
}
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo();
demo.show();
}
}

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.

2. What is the output of following Java Program?


import java.util.LinkedList;

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.

3. What is the output of following Java Program?


import java.util.ArrayList;
class Demo {
public void show()
{
ArrayList<String> list = new ArrayList<String>();
System.out.print(list.get(0));
}
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo();
demo.show();
}
}

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.

4. What is the Output of following Java Program?


import java.util.ArrayList;

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.

5. What is the Output of following Java 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.

Resultado programa Java | Grupo 34 (Collections).


Predice el resultado del siguiente programa java:

1. What is the Output of following Java Program?

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.

2. What is the output of following Java Program?


import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

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.

3. What is the Output of following Java Program?


import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

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();
}
}

A. Compilation Error cannot give Collections.sort() after Iterator.


B. apple banana
C. banana apple
Respuesta B. apple banana
Explicación: Collections.sort() sort element and Iterator is an object used to traverse through a
Collection. Iterator is an interface available in Collection framework in java.util.package. It is
used to traverse elements one by one.

4. What is the Output of following Java Program?


import java.util.ArrayList;

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.

Resultado programa Java | Grupo 35 (Decision Making).


Predice el resultado del siguiente programa java:
Prerequisito: Decision Making in Java

1. What will be the output of the following program?

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

2. What will be the output of the following program?


public
class Test {
public
static void main(String[] args)
{
int x = 10;
if (x)
System.out.println("HOLA GEEKS");
System.out.println("WELCOME");

else
{
System.out.println("BYE");

Página 82 de 104
}
}
}
Options:
1. HOLA GEEKS
WELCOME
2. HOLA GEEKS
3. BYE

4. Compile time error


Resultado:
The answer is option (4)
Explicación: Curly braces are optional in if part. Without curly braces only one statement is allowed
under if. If we will try to give more than one statement then we will get compile time error saying
error: ‘else’ without ‘if’.

3. What will be the output of the following program?


public
class Test {
public
static void main(String[] args)
{
int x = 10, y = 20;
if (x < y)
int a = 10;
else {
System.out.println("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.

4.What will be the output of the following program?


public
class Test {
public
static void main(String[] args)
{
int x = 10, y = 20;
if (x < y) {
if (x > y) {
System.out.println("HOLA GEEKS");
} else {
System.out.println("WELCOME");
}
}
}
}

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).

5. What will be the output of the following program?


class Test {
public
static void main(String[] args)

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.

6. What will be the output of the following program?


class MainClass {
public
static void main(String[] args)
{
int x = 10;
int y = 20;
switch (x) {
case 10:
System.out.println("HOLA");
break;
case y:
System.out.println("GEEKS");
break;
}
}
}

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.

7. What will be the output of the following program?


class MainClass {
public
static void main(String[] args)
{
int x = 10;
final int y = 20;
switch (x) {
case 10:
System.out.println("HOLA");
break;
case y:
System.out.println("GEEKS");
break;
}
}
}

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.

7. What will be the output of the following program?


class MainClass {
public
static void main(String[] args)
{
int x = 10;
switch (x + 1 + 1) {
case 10:
System.out.println("HOLA");
break;
case 10 + 1 + 1:
System.out.println("GEEKS");
break;
}
}
}

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.

8. What will be the output of the following program?


class MainClass {
public
static void main(String arg[])
{
char stream = 'C';
int x = 2;

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.

Resultado programa Java | Grupo 36 (do-while loop).


Predice el resultado del siguiente programa java:
Prerequisito : while loop in Java

1. ¿Cuál será el resultado del programa?


class Test {
public
static void main(String[] args)
{
do
while (true)
System.out.println("HOLA");
while (false);
}
}

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.

2. ¿Cuál será el resultado del programa?


class Test {
public
static void main(String[] args)
{
do
System.out.println("FRIENDS");
while (true);
System.out.println("ENEMY");
}
}

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");

3. ¿Cuál será el resultado del programa?


class Test {
public
static void main(String[] args)
{
int x = 1, y = 2;
do
System.out.println("FRIENDS");
while (x < y);
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.

4. ¿Cuál será el resultado del programa?


class Test {
public
static void main(String[] args)
{
do
while (true)
;
System.out.println("HOLA");
}
}

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.

5. ¿Cuál será el resultado del programa?


class Test {
public static void main(String[] args)
{
do {
System.out.print(1);
do {

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.

Resultado programa Java | Grupo 37 (If-else).


Predice el resultado del siguiente programa java:
Prerequisito: if else, for loops

1. ¿Cuál será el resultado del programa?


public
class Test {
public
static void main(String[] args)
{
for (;;)
System.out.println("GEEKS");
}
}

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.

2. ¿Cuál será el resultado del programa?


class Test {
public
static void main(String[] args)
{

for (int i = 0; i < 3


System.out.println("GEEKS");
}
}

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).

3. ¿Cuál será el resultado del programa?


class Test {
public
static void main(String[] args)
{
boolean b = true;
if (b = false) {
System.out.println("HOLA");
} else {
System.out.println("BYE");
}
}
}

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.

4. ¿Cuál será el resultado del programa?


public
class Test {
public
static void main(String[] args)
{
int a = 10, b = 20;
if (a < b) {
if (a > b) {
System.out.println("HOLA GEEKS");
} else {
System.out.println("WELCOME");
}
}
}
}

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.

5. ¿Cuál será el resultado del programa?

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.

Resultado programa Java | Grupo 38 (Arrays).


Predice el resultado del siguiente programa java:
Prerequisito : Arrays in Java

Question 1. What is the output of this question


class Test1 {
public
static void main(String[] args)
{
int arr[] = { 11, 22, 33 };
System.out.print(arr[-2]);
}
}

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.

Question 2. What is the output of this question?

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.

Question 3. What is the output of this question?

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.

Question 4. What is the output of this question ?


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 < 3; 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: D
Explicación: This program will give exception :java.lang.ArrayIndexOutOfBoundsException
because we want to print the value out of range of array.

Question 5. What is the output of this question?


class Test5 {
public
static void main(String[] args)
{
int arr[] = new int[5];
int arr2[] = new int[5];
System.out.print(arr.length + " ");
System.out.print(arr2.length());
}
}

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().

Resultado programa Java | Grupo 39 (throw keyword).


Predice el resultado del siguiente programa java:
Prerequisito : Exception Handling, Throws

What will be the output of the following program?

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.

2. What will be the output of the following program?


class Geeks {
static ArithmeticException ae = new ArithmeticException();
public
static void main(String[] args)
{
throw ae;
}
}

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.

3. What will be the output of the following program?


class Geeks {
static ArithmeticException ae;
public
static void main(String[] args)
{
throw ae;
}
}

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.

4. What will be the output of the following program?


class Geeks {
public
static void main(String[] args)
{
throw new ArithmeticException("/ by zero");
System.out.println("Hola Geeks");
}
}

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.

5. What will be the output of the following program?


class Geeks {
public
static void main(String[] args)
{
throw new Geeks();
System.out.println("Hola Geeks");
}
}

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.

Resultado programa Java | Grupo 40 (for loop).


Prerequisito : Loops in Java

1 what will be the output of the following program?


public
class Test {
public
static void main(String[] args)
{
for (int i = 0; i < 10; i++)
int x = 10;
}
}

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.

2. what will be the output of the following program?


public
class Test {
public
static void main(String[] args)
{
for (int i = 0, String = "GFG"; i < 2; i++)
System.out.println("HOLA GEEKS");
}
}

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.

3. what will be the output of the following program?


public
class Test {
public
static void main(String[] args)
{
int i = 0;
for (System.out.println("HI"); i < 1; i++)
System.out.println("HOLA GEEKS");
}
}

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.

4. what will be the output of the following program?


public
class Test {
public
static void main(String[] args)
{
for (int i = 0;; i++)
System.out.println("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.

5. what will be the output of the following program?


public
class Test {
public
static void main(String[] args)
{
for (int i = 0; i < 1; System.out.println("WELCOME"))
System.out.println("GEEKS");
}
}

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.

Resultado programa Java | Grupo 41 (try-catch).


Predice el resultado del siguiente programa java:
Prerequisito : try-catch, Exception Handling

1. What will be the output of the following program?

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.

2. What will be the output of the following program?

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.

3. What will be the output of the following program?


class Geeks
{
public static void main(String[] args)
{
try
{
System.out.println(1/0);
}
catch(Exception e)
{
System.out.println("Hola Geeks");
}
catch(ArithmeticException e)
{
System.out.println("Welcome");
}
}
}

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.

4. What will be the output of the following program?


class Geeks
{
public static void main(String[] args)
{
try
{
System.out.println(1/0);
}
}
}

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.

5. What will be the output of the following program?


class Geeks
{
public static void main(String[] args)

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
^

Resultado programa Java | Grupo 42 (Arrays).


Predice el resultado del siguiente programa java:
Prerequisito : Java Arrays

Question 1. What is the output of this question?


class Test1 {
public
static void main(String[] args)
{
int arr[] = new int[5];
int arr2[] = new int['a'];
byte bt = 10;
int arr3[] = new int[bt];
System.out.println(arr.length);
System.out.println(arr2.length);
System.out.println(arr3.length);
}
}
Option
A) Error
B) Runtime Exception
C) 5
97
10
D) 5
65
10
Resultado: C
Explicación: To specify array size allowed data type are –
byte, short, int, char and all of these are valid data types here.

Question 2. What is the output of this question?


class Test2 {
public
static void main(String[] args)
{
int a[] = new int[5]; // line 1
int[] a11 = new int[]; // line 2
}
}

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

Question 3. Which of the following declarations are invalid?


class Test3 {
public
static void main(String[] args)
{
int[][] arr1 = new int[2][3]; // Line 1
int[][] arr2 = new int[2][]; // line 2
int[][] arr3 = new int[][]; // line 3
int[][] arr4 = new int[][2]; // line 4
}
}

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

Question 4. Which of the following lines give error?


class Test4 {
public
static void main(String[] args)
{
int[][][] arr1 = new int[1][2][3]; // Line 1
int[][][] arr2 = new int[1][2][]; // Line 2
int[][][] arr3 = new int[2][][]; // Line 3
int[][][] arr4 = new int[][][]; // Line 4
int[][][] arr5 = new int[][2][3]; // Line 5
int[][][] arr6 = new int[][][3]; // Line 6
int[][][] arr7 = new int[][2][]; // Line 7
}
}

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.

Question 5. What is the output of this question?


class Test5 {
public
static void main(String[] args)
{
int arr[] = new int[5];
System.out.println(arr);
System.out.println(arr[0]);
}
}

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.

Resultado programa Java | Grupo 43 (Conditional statements & Loops).


Prerequisito: Decision Control and Loops

1. What will be the output of the following program?


class Test {
public
static void main(String[] args)
{
int i = 0, j = 9;
do {
i++;
if (j-- < i++) {
break;
}
} while (i < 5);
System.out.println(i + "" + j);
}
}

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.

2. What will be the output of the following program?


class Test {
public
static void main(String[] args)
{
int j = 0;
do

for (int i = 0; i++ < 1


System.out.println(i);
while (j++ < 2);
}
}

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.

3. What will be the output of the following program?


class Test {
static String s = "";
public

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.

4. What will be the output of the following program?


class Test {
public
static void main(String[] args)
{
int x = 10;
if (++x < 10 && (x / 0 > 10)) {
System.out.println("Bishal");
} else {
System.out.println("GEEKS");
}
}
}

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.

5. What will be the output of the following program?


class Test {
public
static void main(String[] args)
{
final int a = 10, b = 20;
while (a > b) {
System.out.println("Hola");
}
System.out.println("GEEKS");
}
}

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.

Página 100 de 104


Resultado programa Java | Grupo 44 (throws keyword).
Prerequisito : throws

1. What will be the output of the following program?


class Geeks throws ArithmeticException {
public
static void main(String[] args) throws ArithmeticException
{
System.out.printl(10 / 0);
System.out.println("Hola Geeks");
}
}

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.

2. What will be the output of the following program?


class Geeks {
public
static void main(String[] args) throws Geeks
{
Thread.sleep(10000);
System.out.println("Hola Geeks");
}
}

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.

3. What will be the output of the following program?


class Test {
void m1() throws ArithmeticException
{
throw new ArithmeticException("Calculation error");
}
void m2() throws ArithmeticException
{
m1();
}
void m3()
{
try {
m2();
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException");
}
}
public
static void main(String args[])
{
Test t = new Test();
t.m3();
System.out.println("Handled by Geeks");
}

Página 101 de 104


}
Options:
1. Calculation error
2. ArithmeticException
3. Handled by Geeks
4. ArithmeticException Handled by Geeks
Resultado:
The answer is option (4)
Explicación: As you can see that we have

an exception occurred in m1() method which has been handled in the chain-calling method m3().

4. What will be the output of the following program?


class Test {
void Div() throws ArithmeticException
{
int a = 25, b = 0, rs;
rs = a / b;
System.out.print("\n\tThe result is : " + rs);
}
public
static void main(String[] args)
{
Test t = new Test();
try {
t.Div();
}
catch (ArithmeticException e) {
System.out.print("\n\tError : " + e.getMessage());
}
System.out.print("\n\tBYE GEEKS");
}
}
Options:
1. BYE GEEKS
2. Compile time error
3. Error: / by zero
4. Error : / by zero
BYE GEEKS
Resultado:

The answer is option (4)


Explicación: In the above program, Div() method is throwing an ArithmeticException, therefore, we have
written the calling statement of Div() method in try-catch block.

5. What will be the output of the following program?


class Test {
public
static void main(String[] args)
{
fun();
}
public
static void fun()
{
moreFun();
}
public
static void moreFun() throws InterruptedException
{
Thread.sleep(10000);
System.out.println("GEEKS");
}
}

Options:
1. GEEKS
2. No Output
3. Compile time error
4. Run-time Exception
Resultado:

Página 102 de 104


The answer is option (3)
Explicación: In the above program, we are throwing InterruptedException from a method where exception
may be rise. But we will get compile time error saying error: unreported exception
InterruptedException; must be caught or declared to be thrown because moreFun() method is called by
fun() method and fun() method is called by main() method. Thats why we have to use throws keyword for
every caller.

Resultado programa Java | Grupo 45 (static and instance variables).


Prerequisito : static and instance variables

Question 1. What is the output of this question?


class Test1 {
int x = 10;
public static void main(String[] args)
{
Test1 t1 = new Test1();
Test1 t2 = new Test1();
t1.x = 20;
System.out.print(t1.x + " ");
System.out.println(t2.x);
}
}

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.

Question 2. What is the output of this question?


class Test1 {
static int i = 1;
public static void main(String[] args)
{
for (int i = 1; i < 10; i++) {
i = i + 2;
System.out.print(i + " ");
}
}
}

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.

Question 3. What is the output of this question?


class Test1 {
static int i = 1;
public static void main(String[] args)
{
int i = 1;
for (Test1.i = 1; Test1.i < 10; Test1.i++) {
i = i + 2;
System.out.print(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

Página 103 de 104


Explicación: Here, two different i copies of variable are declared, one is static and other one is
local. If we write Test1.i then, static variable is executed and if we write only i, then local
variable are executed.

Question 4. What is the output of this question?


class Test1 {
static int i = 1;
public static void main(String[] args)
{
static int i = 1;
for (Test1.i = 1; Test1.i < 10; Test1.i++) {
i = i + 2;
System.out.print(i + " ");
}
}
}

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.

Question 5. What is the output of this question?


class Test1 {
public static void main(String[] args)
{
static int arr1[] = { 11, 22, 33 };
static int arr2[] = { 11, 22, 33, 44, 55 };
static int ptr[];
ptr = arr1;
arr1 = arr2;
arr2 = ptr;
System.out.print(arr1.length + " ");
System.out.println(arr2.length);
}
}

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.

Página 104 de 104

También podría gustarte