Contenido de certificación
Buscar
Social
Ofertas laborales ES

Entries in ocjp (28)

domingo
jun112017

Sobreescribiendo métodos.

¿Compilaría y ejecutaría el siguiente código? Si no compila, ¿por qué razón? Si ejecuta, ¿cuál sería la salida?

01.package pruebas.ocp;
02. 
03.import java.io.FileNotFoundException;
04.import java.io.IOException;
05. 
06.public class Padre {
07.    protected void hola() throws IOException {
08.        System.out.println("Hola, soy el Padre");
09.    };
10.}
11. 
12.class Hijo extends Padre {
13. 
14.    public void hola() throws FileNotFoundException {
15.        System.out.println("Hola, soy el Hijo");
16.    };
17. 
18.    public static void main(String args[]) {
19.        Padre padre = new Padre();
20.        try {
21.            padre.hola();
22.        } catch (IOException e) {
23.            System.out.println("Exception " + e.getMessage());
24.        }
25. 
26.        Hijo hijo = new Hijo();
27. 
28.        try {
29.            hijo.hola();
30.        } catch (FileNotFoundException e) {
31.            System.out.println("Exception " + e.getMessage());
32.        }
33. 
34.        Padre mixto = new Hijo();
35. 
36.        try {
37.            mixto.hola();
38.        } catch (IOException e) {
39.            System.out.println("Exception " + e.getMessage());
40.        }
41. 
42.    }
43.}
jueves
abr092015

Más ejemplos sobre constructores

¿Compilaría y ejecutaría el siguiente código? Si no compila, ¿por qué razón? Si ejecuta, ¿cuál sería la salida?

Clase constructores1.Pruebas
01.package constructores1;
02. 
03. 
04.public class Pruebas {
05. 
06.    private String s = "publico";
07.     
08.    protected Pruebas() {
09.        this.s = "protected"
10.    }
11. 
12.    /* (non-Javadoc)
13.     * @see java.lang.Object#toString()
14.     */
15.    @Override
16.    public String toString() {
17.        return "Pruebas [s=" + s + "]";
18.    }
19.     
20. 
21.}
Clase constructores2.Pruebas
01.package constructores2;
02. 
03. 
04.public class Pruebas {
05. 
06.    private String s = "publico";
07.     
08.    protected Pruebas() {
09.        this.s = "protected"
10.    }
11. 
12.    /* (non-Javadoc)
13.     * @see java.lang.Object#toString()
14.     */
15.    @Override
16.    public String toString() {
17.        return "Pruebas4 [s=" + s + "]";
18.    }
19.     
20. 
21.}
Clase Principal
01.package constructores;
02. 
03.public class Principal {
04. 
05.    public static void main(String args[]){
06.        constructores1.Pruebas pruebas1 = new constructores1.Pruebas();
07.        System.out.println(pruebas1.toString());
08.         
09.        constructores1.Pruebas pruebas2 = new constructores2.Pruebas();
10.        System.out.println(pruebas2.toString());
11.         
12.    }
13.}
jueves
abr092015

Ejemplos sobre constructores

¿Compilarían los siguientes ejemplos?

Ejemplo 1
01.package constructores;
02. 
03.public class Pruebas1 {
04. 
05.    public Pruebas1(){
06.         
07.    };
08.     
09.    private Pruebas1(){
10.         
11.    };
12.     
13.     
14.}
Ejemplo 2
01.package constructores;
02. 
03.public class Pruebas2 {
04. 
05.    private Pruebas2(){
06.         
07.    };
08.     
09.     
10.}
lunes
jul142014

Duda sobre ArrayList y Vector.

Duda sobre ArrayList y Vector.

Buenos dís. Pensaba que tanto Vector como ArrayList se diferenciaban en que sus métodos eran (o no eran) thread-safe. Salió el debate en mi trabajo, y quise comprobarlo por mi mismo. Desarrollé el siguiente código. ¿Alguien puede indicarme la salida del mismo e intentar explicar la diferencia real, en un ejemplo práctico, entre Vector y ArrayList? Muchas gracias

01.import java.util.ArrayList;
02.import java.util.List;
03. 
04.public class Principal implements Runnable {
05. 
06.    private List<string> lista = new ArrayList<string>();
07.    private static List<principal> hilos = new ArrayList<principal>();
08. 
09.    private int i = 0;
10. 
11.    private final int MAX_VAL = 1000;
12.    private final static int MAX_VAL_STATIC = 1000;
13.    private final static int MAX_HILOS = 1000;
14.    private final static int TIEMPO_ESPERA_MS = 1000;
15. 
16.    public Principal(List<string> lista) {
17.        this.lista = lista;
18. 
19.    }
20. 
21.    public static void main(String[] args) throws InterruptedException {
22. 
23.        Long inicio = System.currentTimeMillis();
24.         
25.        List<string> lista = new ArrayList<string>();
26. 
27.        System.out.println("Iniciando hilos....");
28.        for (int i = 0; i < MAX_HILOS; i++) {
29.            Principal p = new Principal(lista);
30.            hilos.add(p);
31.        }
32. 
33.        System.out.println("OK");
34. 
35.        System.out.println("Ejecutando hilos....");
36.        for (Principal hilo : hilos) {
37.            hilo.run();
38.        }
39.        System.out.println("OK");
40. 
41.        System.out.println("Esperando finalización");
42. 
43.        boolean finalizado = true;
44.        do {
45.            Thread.sleep(TIEMPO_ESPERA_MS);
46. 
47.            for (Principal hilo : hilos) {
48.                if (hilo.i < MAX_VAL_STATIC) {
49.                    finalizado = false;
50.                }
51.            }
52. 
53.        } while (!finalizado);
54. 
55.        System.out.println("OK");
56. 
57.        System.out.println("EL TAMAÑO DE LA LISTA ES: " + lista.size());
58.        Long total = System.currentTimeMillis() - inicio;
59.    }
60. 
61.    public int getI() {
62.        return i;
63.    }
64. 
65.    public void setI(int i) {
66.        this.i = i;
67.    }
68. 
69.    @Override
70.    public void run() {
71.        while (i < MAX_VAL) {
72.            lista.add("" + i);
73.            i++;
74.        }
75.    }
76. 
77.}
78. 
79.</string></string></string></principal></principal></string></string>
lunes
abr072014

Más sobre GregorianCalendar....

¿Cuál es la siguiente salida y por qué?

Aclaraciones: se dispone de un equipo bastante potente a la hora de ejecución, y el día de ejecución es: 7 de Abril de 2014

NOTA: no vale hacer uso de IDE.
01.package es.orange.gateway.tools;
02. 
03.import java.text.SimpleDateFormat;
04.import java.util.Calendar;
05.import java.util.GregorianCalendar;
06. 
07.public class Pruebas {
08. 
09.    /**
10.     * @param args
11.     */
12.    public static void main(String[] args) {
13. 
14.        GregorianCalendar gc1 = new GregorianCalendar();
15. 
16.        gc1.set(Calendar.MONTH, 4);
17. 
18.        try {
19.            Thread.sleep(10);
20.        } catch (InterruptedException e) {
21.            // TODO Auto-generated catch block
22.            e.printStackTrace();
23.        }
24.        GregorianCalendar gc2 = new GregorianCalendar();
25. 
26.        gc2.set(Calendar.MONTH, 4);
27. 
28.        System.out.println(gc2.compareTo(gc1));
29.         
30.        GregorianCalendar gc3 = new GregorianCalendar();
31. 
32.        gc3.set(Calendar.MONTH, 4);
33.         
34.        GregorianCalendar gc4 = new GregorianCalendar();
35. 
36.        gc4.set(Calendar.MONTH, 4);
37. 
38.        System.out.println(gc4.compareTo(gc3));
39.         
40.        GregorianCalendar gc5 = new GregorianCalendar();
41. 
42.        gc3.set(Calendar.MONTH, 4);
43.         
44.        GregorianCalendar gc6 = new GregorianCalendar();
45. 
46.        gc6.set(Calendar.MONTH, 16);
47. 
48.        System.out.println(gc5.compareTo(gc6));
49. 
50.        System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(gc6.getTime()));
51. 
52.    }
53. 
54.}
jueves
mar272014

Preguntas sobre fechas

Buenos días.

Se plantean las siguientes preguntas, acerca gestión de fechas en Java.

1) Primera pregunta teórica, ¿qué diferencia existe entre las fechas de Java 6 y las últimas versiones de Java?

2) Pregunta práctica: ¿cómo determinar si una cadena, pasada como parámetro, se corresponde a una fecha correcta?

3) Segunda pregunta práctica: ¿cómo poder obtener el último día de un mes determinado?

Un saludo,

 

jueves
may302013

¿Cuál es la salida del siguiente programa y por qué?

 

public class Pruebas {
/**
* @param args
*/
public static void main(String[] args) {
  boolean a = true;
  boolean b = true;
  __main:
{
  if (a == true) {
  System.out.println("dentro del main: a es verdadero");
  System.out.println("ejecutamos break __main");
  break __main;
  } else {
  System.out.println("dentro del main: a es falso");
  }
  if (b == true) {
System.out.println("dentro del main: b es verdadero");
} else {
System.out.println("dentro del main: b es falso");
}
}
System.out.println("fuera del bloque __main");
} // end main
}

 

 

lunes
may062013

Pregunta sobre excepciones

Tenemos dos códigos: se pide en cada uno de ellos, decir si compila, y en tal caso, comentar la salida en tiempo de ejecución (lo más detallada posible).
CÓDIGO 1
package scjp;
public class Pregunta {
private int a = 0;
private int b = 10;
private int c = b / a;
public Pregunta() {
System.out.println("Hola JavaHispaneros "+c);
}
public static void main(String args[]) {
Pregunta p = new Pregunta();
}
}

package scjp;
public class Pregunta {
private int a = 0; private int b = 10; private int c = b / a;
public Pregunta() { System.out.println("Hola JavaHispaneros "+c); }
public static void main(String args[]) { Pregunta p = new Pregunta();
}}

 

CÓDIGO 2

package scjp;

 

public class Pregunta {

 

private D d = new D();

 

public Pregunta() {

System.out.println("Por aquí estamos otra vez " + d);

}

 

public static void main(String args[]) {

Pregunta p = new Pregunta();

 

}

 

class D {

 

D() throws PersonalException {

throw new PersonalException();

}

 

}

 

class PersonalException extends Exception {

 

}

}

 

lunes
abr152013

Más sobre Java 7

A continuación, comentamos las modificaciones principales que presenta Java 7 con respecto a Java 6. Un saludo, Jaime.

Click to read more ...

martes
abr092013

Pregunta sobre switch

Hola a todos,

¿Podéis argumentar cuál sería la salida en consola después de ejecutar el siguiente programa?

 

package javahispano;

public class EjemplosSwitch {

    public static void main(String args[]) {
        String jugador = "Cristiano Ronaldo";

        switch (jugador) {
        case "Cristiano Ronaldo":
            System.out.println("Real Madrid CF");
        case "Leo Messi":
            System.out.println("FC Barcelona");
        }
    }
}

Un saludo,

    Jaime.