You are on page 1of 128

OCA JSE 8 Programmer

Guía de estudio
Temas
1. Java básico
2. Tipo de datos Java
3. Operadores y decisiones
4. Creación y uso de Arrays
5. Uso de bucles
6. Métodos y encapsulación
7. Herencia
8. Manejo de excepciones
9. Time API
10. Lambdas

El lenguaje Java fue concebido como un lenguaje orientado a objetos. Java organiza datos y
código juntos (encapsulación). Un objeto adecuadamente encapsulado usa protección de
datos y expone solo algunos de sus datos y métodos. Los datos y métodos que están
diseñados para uso interno en el objeto no están expuestos a otros objetos.
El diseño orientado a objetos también fomenta la abstracción, la capacidad de generalizar
algoritmos. La abstracción facilita la reutilización y flexibilidad del código.

Java también es un lenguaje robusto y seguro. Java fue diseñado para no tener punteros
explícitos. Las variables de Java almacenan referencias a objetos pero no permiten el acceso
o la modificación de la dirección de memoria almacenada en la referencia.

La JVM ejecuta periódicamente el recolector de basura.


Paquete: es un contenedor de clases que permite agrupar las distintas partes de un
programa y que por lo general tiene una funcionalidad y elementos comunes, definiendo la
ubicación de dichas clases en un directorio de estructura jerárquica.

Ejemplos:
package com.codemonkey.clases;
package com.codemonkey.interfaces;
package com.codemonkey.enumeraciones;
package com.codemonkey.anotaciones;
package com.codemonkey.xmls;

El uso de paquetes nos permite agrupar clases con carcaterísticas comunes, reutilizer
código, seguridad en niveles de acceso, evitar collision de clases con el mismo nombre,
mantener código y su exportación.

La cláusula import nos permite importer paquetes.

Paquete java.lang

import java.lang.*; // No es necesario importer este paquete


import java.lang.Object; // Todos los objetos son hijos de la clase Object
import java.lang.String;
import java.lang.StringBuffer;
import java.lang.StringBuilder;
import java.lang.Integer;

Usar static después de la cláusula import nos permitirá invocar los métodos estáticos sin
necesidad de escibir el nombre de la clase a la que pertenecen.

import static java.lang.System.out;


import static java.lang.System.exit;
import static java.lang.System.gc;

out.println(“Se puede usar algo como esto”);


gc();
exit(0);

import java.lang.Math;//Sin usar static

int numero = (int) (Math.random()*100);

import static java.lang.Math.random;//Usando static

int numero = (int) (random()*100);


import java.util.Date;
import java.util.Arrays;//clase
import java.util.List;//interface
import java.util.Set;// interface
import java.util.SortedSet;// interface
import java.util.TreeSet;//clase
import java.util.Queue;// interface
import java.util.ArrayList;//clase
import java.util.Stack;//clase
import java.util.Timer;
import java.util.Map;//interface
import java.util.HashMap;//clase
import java.util.HashSet;//clase
import java.util.Hashtable;//clase

Interface ref = new ConstructorClase();


Clase ref = new ConstructorClase();

List<Integer> listaEnterosA = new ArrayList<Integer>();


ArrayList<Integer> listaEnterosB = new ArrayList<Integer>();
ArrayList<Integer> listaEnterosC = new ArrayList< >();

Map<Integer,String> mapaA = new HashMap<Integer,String>();


HasMap<Integer,String> mapaB = new HashMap<Integer,String>();

Set<Empleado> empleadosA = new HashSet<Empleados>();


HasSet<Empleado> empleadosB = new HashSet<Empleados>();

SortedSet<Tecnico> tecnicosA = new TreeSet<Tecnico>();


TreeSet<Tecnico> tecnicosB = new TreeSet<Tecnico>();

import java.util.Collection;//interface
import java.util.Collections;//clase

import java.util.*;

import java.io.*;

Creación de interfaces gráficas:


import java.awt.*;
import javafx;
import javax.swing.*;

Uso de flujo de datos, serialización de objetos y uso de ficheros y archivos:


import java.io.*;
Operaciones aritméticas con enteros de presición arbitaria y operaciones decimales con
precision arbitraria:
import java.math.*;
import java.math.BigDecimal;
import java.math.BigInteger;

Para aplicaciones de red:


import java.net.*;
import java.net.HttpCookie;
import java.net.Proxy;
import java.net.URI;
import java.net.URL;
import java.net.Inet4Address;
import java.net.Socket;//clase
import java.net.SocketOption;//interface
import java.net.SocketOptions;//interface

Colecciones, uso de fechas, internacionalización, base64, tokens, números aleatorios, listas,


arreglos:
import java.util.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;

Fechas, tiempo, instantes y duración:


import java.time.*;
import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.DayOfWeek;//Enumeración
import java.time.Month;//Enumeración

Para leer y escribir en archivos JAR:


import java.util.jar.*;

Para manejo y tratamiento de texto, fechas, números y mensajes:


import java.text.*;
import java.text.Format;
import java.text.CharacterIterator;//interface

Para accede y procesar datos almacenados en bases de datos:


import java.sql.*;
import java.sql.Date;
import java.sql.Time;
import java.sql.DriverManager;
import java.sql.SQLPermission;

modificador class NombreClase [extends] [ClasePadre] [implements] [InterfaceA],


[InterfaceB], [InterfaceN]{
[datos miembro]
[constructores]
[métodos]
}

modificador interface NombreIntereface [extends] [InterfacePadre]{


[datos miembro]
[constructores]
[métodos]
}

Puntos importantes:

-Toda clase creada y wrapper es hija de Object.


Object obj1 = new Object();
Object obj2 = new String();
Object[] obj3 = new Character[3];
Object[] obj4 = new int[3];
Object[] obj5 = new Object[2];

Se debe tener cuidado. Cada tipo tiene métodos propios. Un String es un Object, pero un
Object no es un String.

-Tipos de datos en Java:

1. Primitivos
byte 1 byte = 8 bits
short 2 bytes = 16 bits
int 4 bytes = 32 bits
long 8 bytes = 64 bits
float 4 bytes = 32 bits
double 8 bytes = 64 bits
boolean --
char --

2. Wrappers/Clases envoltorio (java.lang)


Byte
Short
Integer
Long
Float
Double
Boolean
Character

A cada primitivo le corresponde un wrapper.


boolean verdadero = new Boolean(“true”);
Short num = 3;
Integer n = 9;
char letra = new Character(‘A’);

Cada primitivo tiene un tamaño definido. Se debe tener cuidado al realizar operaciones de
asignación.
Long tam =12;
int b =6;
int resultado = tam * b; // puede ocasionar pérdida de bits
//Solución:
int resultado = (int) tam * b;

Boxing y unboxing
Integer Entero = new Integer(entero); //de primitivo a objeto se llama boxing.
int aEntero = Entero.intValue(); //de objeto a primitivo se llama unboxing.

boolean verdadero = new Boolean(“true”);//unboxing


Boolean falso = new Boolean(false);//boxing

Autoboxing y autounboxing
Asignación directa entre tipos primitivos y objetos.

int enteroPrimitivo = 90;


Integer objEntero = enteroPrimitivo;//autoboxing
int otroentero = objEntero;//autounbonxing

Link:
https://preparandoscjp.wordpress.com/guia-rapida/

Heap y Stack
El Heap (Montículo) y el Stack (Pila) son diferentes memorias que utiliza la Java Virtual
Machine de Java.

Mientras que para cada thread en la JVM se tiene un Stack privado, el Heap es un espacio
de memoria dinámica único que se crea al inicio de la máquina virtual. El administrador del
Heap es el sistema de administración de almacenamiento automático o más conocido como
Garbage Collector.

¿Qué se guarda en el Stack?


– variables locales
– variables de referencia
– parámetros y valores de retorno
– resultados parciales
– el control de la invocación y retorno de métodos

¿Qué se guarda en el Heap?


– objetos
– variables de instancia

Instancia de una clase:


Clase referencia = new Constructor();

Donde:
Clase es el tipo o clase
referencia es el nombre de la variable que hace referencia
new es el operadorpara crear un nuevo objeto de unca clase
Constructor es el método de una clase que comparte su nombre y sirve para inicializar un
objeto

Modificadores de acceso

 private (Acceso solo dentro de la clase)


 protected (Acceso desde la clase y sus hijos "herencia")
 default (Sin escribir nada, denominado acceso de paquete)
 public (Acceso publico desde cualquier lugar)
Declaración de una clase

Una clase es una plantilla que describe las propiedades y el comportamiento que van a tener
los objetos de esa clase.
La sintaxis para declarar una clase es la siguiente:
[Modificadores] class NombreClase [extends SuperClase] [implementes Interface]{}
La mínima expresión de una declaración de clase sería:
class MinimaClase{}
Los modificadores y las cláusulas de herencia e interfaces son opcionales.
Reglas de Declaración en el fichero fuente
Solo puede existir una clase pública en un fichero .java
El nombre del fichero debe coincidir con el de la clase pública.
La sentencia package (si existe) debe ser la primera sentencia del fichero.
Las sentencias import (si existen) deben seguir a la sentencia package y preceder a las
declaraciones de clases.
Pueden existir más clases en el fichero pero no pueden ser públicas.
Las sentencias package e import afectarán a todas las clases declaradas en el fichero.
El nombre de los ficheros que solo tengan declaraciones de clase no públicas no tiene que
coincidir con ninguna de las clases.
Modificadores de acceso
Existen tres modificadores de acceso: public, protected y private. Sin embargo, existen cuatro
niveles de acceso. Cuando no se especifica ninguno de los tres modificadores anteriores se
tiene el nivel de acceso por defecto, que es el nivel de paquete.
Para las clases de primer nivel solo se permite:
public
nivel de paquete
Para atributos, métodos, clases anidadas, se permiten todos.
Los explicamos un poco más, desde el más restrictivo al menos restrictivo:
private: solo es accesible dentro de su clase. No se especifica (nivel de paquete): es
accesible dentro de su clase y por todas las clases de su paquete.
protected: es accesible dentro de su clase, por todas las clases de su paquete y por las
clases hijas que estén en otro paquete diferente.
public: es accesible para cualquier clase Java.
X.java
package com.codemonkey.clases; //Paquete

public class X{

//Dato(s) miembro(s)/Atributo(s)
private String valor;

//Constructor sin parámetros


public X(){}

//Constructor con parámetros


public X(String valor){
this.valor=valor;
}

//métodos de acceso
public String getValor(String valor){
return valor;
}

public void setValor(String valor){


this.valor=valor;
}

}
Intanciación de clases externas e internas

Externa.java
class Externa{
private String valor;

public Externa(String valor){


setValor(valor);
}

public String getValor(){


return valor;
}

public void setValor(String valor){


this.valor=valor;
}

@Override
public String toString(){
return "Externa{valor="+valor+"}";
}

static class Interna{


private String valor;

public Interna(String valor){


setValor(valor);
}

public String getValor(){


return valor;
}

public void setValor(String valor){


this.valor=valor;
}

@Override
public String toString(){
return "Interna{valor="+valor+"}";
}
}
}

//Main
ClaseExterna.ClaseStaticInterna ref = new ConstructorExterna.ConstructorStaticInterna();
Main.java
public class Main{

public static void main(String[] args){


//Correcto, Externa es un Object, pero Object no es una Externa
Object obj1 = new Externa("Valor 1");

//Esto no se puede hacer:


//Externa obj2 = new Externa(); El compilador borra el constructor vacío si nosotros
creamos uno con parámetros y no definimos uno vacío

Externa obj3 = new Externa("Valor 2");

//Esto no se puede hacer:


//Externa.Interna obj4 = new Externa.Interna();El compilador borra el constructor vacío
si nosotros creamos uno con parámetros y no definimos uno vacío

//ClaseExterna.ClaseStaticInterna ref = new


ConstructorExterna.ConstructorStaticInterna();
Externa.Interna obj5 = new Externa.Interna("Valor 3");

System.out.println(obj1);
System.out.println(obj3);
System.out.println(obj5);

}
}

Externa.java
class Externa{
private String valor;

public Externa(String valor){


setValor(valor);
}

public String getValor(){


return valor;
}

public void setValor(String valor){


this.valor=valor;
}

@Override
public String toString(){
return "Externa{valor="+valor+"}";
}

class Interna{
private String valor;

public Interna(String valor){


setValor(valor);
}

public String getValor(){


return valor;
}

public void setValor(String valor){


this.valor=valor;
}

@Override
public String toString(){
return "Interna{valor="+valor+"}";
}
}
}

//Main
ClaseExterna.ClaseInterna ref = ref.new ConstructorInterna();

Main.java
public class Main{

public static void main(String[] args){


//Correcto, Externa es un Object, pero Object no es una Externa
Object obj1 = new Externa("Valor 1");

//Esto no se puede hacer:


//Externa obj2 = new Externa(); El compilador borra el constructor vacío si nosotros
creamos uno con parámetros y no definimos uno vacío

Externa obj3 = new Externa("Valor 2");

//ClaseExterna.ClaseInterna ref = ref.new ConstructorInterna();


//Externa.Interna obj4 = obj4.new Interna("Valor 3");

System.out.println(obj1);
System.out.println(obj3);

}
}

Modificadores

1. Strictfp puede modificar una clase o un método, nunca una variable.

Cuando marcamos una clase como strictp significa que todo el código de la clase sigue la
especificación IEEE754 para flotantes. Cuando marcamos strictfp a un método el código del método
sigue la especificación anterior.

Si cumplimos esta especificación prevenimos que los números flotantes puedan ser dependientes de la
plataforma.

2. Final

Cuando marcamos una clase como final estamos indicando que esta clase no puede ser extendida en
subclases.
Los métodos marcados como final no pueden sobrescribirse.
Si una variable se marca como final, se convierte en una constante.

3. Abstract

Cuando marcamos una clase como abstract estamos indicando que no se puede instanciar. Su objetivo
es ser extendida en subclases.
Una clase abstracta puede tener tanto métodos abstractos como no abstractos. Un solo método abstracto
obliga a declarar la clase como abstracta.
Este tipo de clases son útiles cuando la implementación queremos que se concrete en sus clases hijas.

No tiene sentido declarar una clase final y abstracta.

Main.java
public class Main{

public static void main(String[] args){


//Esto no se puede:
//Abstracta obj1 = new Abstracta();//Una clase abstract sólo tiene el objetivo heredar a
otra clase

//A es Abstraca, pero Abstracta no es A


Abstracta obj2 = new A();
obj2.nada();

A obj3 = new A();


obj3.nada();

Unica obj4 = new Unica();


X obj5 = new X();
System.out.println(obj5.CONSTANTE);
obj5.mensaje();
obj5.heredable();

Y obj6 = new Y();


System.out.println(obj6.CONSTANTE);
obj6.mensaje();
obj6.heredable();

}
}

abstract class Abstracta{


abstract void nada();
}

class A extends Abstracta{


@Override
public void nada(){
System.out.println("Mensaje sin nada desde A");
}
}

final class Unica{}

//Esto no se puede:
//class Dos extends Unica{}
//Una clase final no puede heredar

class X{
public static final int CONSTANTE = 30;

final public void mensaje(){


System.out.println("Metodo no sobreescribible desde X");
}

public void heredable(){


System.out.println("Metodo heredable desde X");
}

class Y extends X{
@Override
public void heredable(){
System.out.println("Metodo heredable desde Y");
}
//esto no se puede hacer:
//@Override
//public void mensaje(){
// System.out.println("Metodo no sobreescribible");
//}
}

Instanciaciones

Abstracta ref1 = new Hija();


Hija ref2 = new Hija();

Interface ref3 = new InterfaceImpl();


InterfaceImpl ref4 = InterfaceImpl();

Padre ref5 = new Hija();


Hija ref6 = new Hija();

//Esto no se puede hacer


//Hija ref7 = new Padre();
//Hija es una extension de Padre

Interfaz

La interfaz pública de una clase es un “contrato” entre el código cliente y la clase que proporciona el
servicio.

Decimos que una clase implementa una interfaz cuando implementa todos los métodos declarados en
ella.

Varias clases pueden implementar la misma interfaz. Una sola clase puede implementar varias
interfaces.

La sintaxis para declarar una interfaz es la siguiente:

[Modificadores] interface NombreInterface [extends InterfacePadre]{


<public static final atributos>
<public abstract metodos>
}

Todos los métodos declarados en una interfaz son public y abstract, aunque no se especifique.
Todos los atributos en una interfaz son public, static y final, aunque no se especifique. Es decir,
constantes.

Los métodos no pueden ser static ni final, strictfp, o native.

Una interfaz puede extender solo otras interfaces.


Las interfaces se usan para:

declarar métodos que serán implementados por una o varias clases.


dar a conocer la interfaz de programación sin revelar la implementación
identificar similitudes entre clases no relacionadas
simular la herencia múltiple declarando una clase que implemente varias interfaces

Variables Locales y Modificadores

Los modificadores de acceso no son aplicables a variables locales, provocaría error de compilación.
El único modificador que podría aplicarse a variables locales sería final.

Modificadores de acceso para miembros de una clase

Se pueden aplicar: public, protected, paquete (por defecto), private.

Otros modificadores para miembros de una clase

Strictfp

Para miembros de clase sólo se puede aplicar a métodos. Cuando marcamos strictfp a un método el
código del método sigue la especificación anterior IEEE754 para flotantes.

Final

Los métodos marcados como final no pueden sobrescribirse.


Los argumentos marcados como final no pueden cambiar su valor.
Si una variable se marca como final, se convierte en una constante.

Abstract

Un método abstracto se declara pero no se implementa. Acaba en ;.


Un solo método abstracto obliga a declarar la clase como abstracta.
La primera subclase concreta debe implementar todos los métodos abstractos.

Static

Pueden marcarse static: métodos, variables, clases anidadas y bloques de inicialización.

Crea miembros que están asociados a la Clase y no necesitan que exista un objeto instanciado de la
Clase para existir.

Synchronized

Sólo métodos pueden marcarse synchronized. Significa que solo un hilo puede acceder al método a la
vez.

Native
Sólo métodos pueden marcarse native. Indica que el método está implementado en un lenguaje que es
dependiente de la plataforma, usualmente C. Su declaración acabará en ‘;’ como los métodos
abstractos, ya que su implementación no se especifica.

Transient variable

Si marcamos una variable de instancia transient no se añadirá en la serialización del objeto que la
contenga.

Volatile variable

Indica al hilo que accede a la variable que siempre debe reconciliar su copia privada con la copia en
memoria. Solo aplica a variables de instancia.

Argumentos variables

Para especificar un método con un número variable de argumentos, se define el tipo seguido de ‘…’, un
espacio y un nombre para el array asociado.

El argumento variable debe ser el último en la declaración del método y solo se permite uno.

[Modificador] ValorDeRetorno NombreMetodo (Tipo… a) {}

Constructores

Un constructor es un conjunto de sentencias para inicializar una instancia.No se consideran métodos.


No tienen valores de retorno ni se heredan.

El nombre del constructor debe coincidir con el de la clase.

Cada clase tiene al menos un constructor. Si no se escribe ninguno Java suministra uno por defecto. En
ese caso el constructor no tiene argumentos y su cuerpo está vacío.

En el momento que nosotros escribamos un constructor se pierde el constructor por defecto.

La sintaxis es:
[Modificadores] nombreClase (<argumentos>){}

Static

La palabra clave static declara miembros (atributos, métodos y clases anidadas) que están asociados a
la clase en lugar de a una instancia de la clase.

Utilidad

A veces puede ser útil tener una variable compartida por todos los objetos de la clase (algo parecido a
una variable global). En este caso marcaríamos esta variable como static.
Si una variable static no se marca como private, es posible acceder a ella desde fuera de la clase. Para
hacerlo, no se necesita ningún objeto, se hace referencia a ella mediante el nombre de la clase.

Mundo static != mundo object

Main.java
public class Main {
public static void main(String[] args) {
X objX = new X();
objX.setValor(true);
objX.metodoDeClase();

//métodos static
objX.metodoStatic();
new X().metodoStatic();
}
}

class X {
private boolean valor;

public X(){}

public X(boolean valor) {


super();
this.valor = valor;
}

public boolean isValor() {


return valor;
}

public void setValor(boolean valor) {


this.valor = valor;
}

public static void metodoStatic(){


//Esto no se puede:
//System.out.println("Valor="+valor);Error
//System.out.println("Valor="+this.valor);Error
//"El mundo static" es diferente al "mundo object"
// un metodo static no puede acceder a los datos miembros/atributos de una clase
//Solo a variables locales:
boolean valor = false;
System.out.println("Valor="+valor);
}
public void metodoDeClase(){
System.out.println("Valor="+valor);
System.out.println("Valor="+this.valor);//se puede usar this (this.valor)
}
}

Conversión Implícita (Widening)

Se produce cuando los tipos son compatibles y Java realiza la conversión de forma automática.
Siempre es posible asignar un valor de un tipo más pequeño en una variable de un tipo mayor.

long largo = 10;//es int, 10 es muy pequeño


short corto = 4;// puede ser int
int entero = corto;

Conversión Explícita (Cast)

Cuando los tipos son incompatibles o existe la posibilidad de perder información en una asignación, el
compilador dará un error pidiendo que se confirme esa asignación con una conversión explícita.

int entero = (int) 100L;//100L es long y muy grande para ser int, se necesita hacer uso de cast
final short corto = 120;
//Error
//short result = (short) corto * 0.7; 0.7 es double y mayor a short
//Solución:
short result = corto * (short) 0.7; //0.7 se convierte a short

Arrays multidimensionales

char[][] letras = {
{'e','9','7'},
{'Q','k'},
{new Character('A'), '3','U', new Character('6')}
}; //[][]
System.out.println(letras.length);
System.out.println(letras[0].length);
//0
//4
//letras[0][4]

System.out.println("#############");
//for clásico
for(int i=0; i < letras.length; i++){
for(int j=0; j < letras[i].length; j++){
System.out.println(letras[i][j]);
}
}

System.out.println("#############");
//for each
for(char[] letra : letras){
for(char let : letra){
System.out.println(let);
}
}

Clases internas

Main.java
public class Main {
public static void main(String[] args) {
X objX = new X();
A objA = new A();
//interna static
X.Y objInternaStatic = new X.Y();
//interna
A.B objInterna = objA.new B();
}
}

class X{
static class Y{}
}

class A {
class B{}
}

Herencia en Java

interface Modales{
void saludar();
}

abstract class Persona implements Modales{


abstract void comer();
}

class Empleado extends Persona{

@Override
public void saludar() {
System.out.println("Hola, buen día!!");
}

@Override
public void comer() {
System.out.println("A comer”);
}
}

class Programador extends Empleado{

-La clase Persona es abstracta (abstract), usa a la interface Modales, pero no está obligada a
implementar sus métodos.
-La clase Empleado es una extension de la clase Persona, está obligada a implementar los métodos
heredados (de la clase Persona y de la interface Modales).
-La clase Programador es una extension de la clase Empleado, pero no esta obligada a implementar los
métodos heredados de la clase Persona y de la interface Modales.

Sobreescritura de métodos

interface Modales{
void saludar();
}

abstract class Persona implements Modales{


abstract void comer();
}

class Empleado extends Persona{

@Override
public void saludar() {
System.out.println("Hola, buen día!!");
}

@Override
public void comer() {
System.out.println("A comer!!");
}

public void heredable(){


System.out.println("Metodo heredable desde Empleado");
}

public final void noModificable(){


System.out.println("Metodo noModificable desde Empleado");
}

public static void noHeredable(){


System.out.println("Metodo noHeredable desde Empleado");
}
}

class Programador extends Empleado{

@Override
public void heredable(){
System.out.println("Metodo sobreescrito heredable desde Programador");
}

@Override
public void comer(){
System.out.println("Metodo sobreescrito heredable desde Programador");
}
}

Main.java
public class Main {
public static void main(String[] args) {
//Esto no se puede:
//Modales obj1 = new Persona(); //Persona es abstracta (abstract)

Persona obj2 = new Empleado();//Permitido, Empleado is-a Persona, pero Persona no es


Empleado

//Esto no se puede:
//Empleado obj3 = new Persona();//Empleado es una extensión de Persona, ya es una
Persona

Empleado obj4 = new Empleado();

Empleado obj5 = new Programador();//Permitido, Programador is-a Empleado, pero


Empleado no es Programador

//Esto no se puede:
//Programador obj6 = new Empleado();//Programador es una extensión de Empleado, ya
es un Empleado

Programador obj7 = new Programador();


}
}

Clases abstractas

abstract class Abstracta{


abstract void saludar();
}

//Persona es abstract, no está obligada a implementar el metodo saludar de la clase Abstracta


abstract class Persona extends Abstracta{

}
//Empleado es una extensión de Persona, Persona es una extensiónde Abstracta
//Empleado está obligado a implementar los métodos de la clase Abstracta
class Empleado extends Persona{

@Override
public void saludar() {
System.out.println("Hola, buen día!!");
}

//Programador es una extensión de Empleado, no esta obligado a implementar los métodos de la clase
Abstract ni de la clase Empleado
class Programador extends Empleado{

}
Abstracta

Persona*

Empleado*

Programador

abstract class Abstracta{}


abstract class Persona extends Abstracta{}
class Empleado extends Persona{}
class Programador extends Empleado{}

Herencia e Implementación

interface Modales{
abstract void saludar();
}

abstract class Abstracta implements Modales{


abstract void comer();
}

//Persona es abstract, no está obligada a implementar el metodo comer ni de la clase Abstracta el de


saludar de la interface Modales
abstract class Persona extends Abstracta{

}
//Empleado es una extensión de Persona, Persona es una extensiónde Abstracta
//Empleado está obligado a implementar los métodos de la clase Abstracta
class Empleado extends Persona{
@Override
public void saludar() {
System.out.println("Hola, buen día!!");
}

@Override
public void comer() {
System.out.println("Hola, es hora de comer!!");
}

public void heredable(){


System.out.println("Metodo heredable desde Empleado");
}
}

//Programador es una extensión de Empleado, no esta obligado a implementar los métodos de la clase
Abstract ni de la clase Empleado
class Programador extends Empleado{

Modales Abstracta

Persona*

Empleado*

Programador

interface Modales{}
abstract class Abstracta implements Modales{}
abstract class Persona extends Abstracta{}
class Empleado extends Persona{}
class Programador extends Empleado{}

Main.java
public class Main {
public static void main(String[] args) {
//Esto no se puede:
//Modales obj1 = new Abstracta();//Abstracta es abstract, no se puede crear una instancia
directa
//Abstracta obj2 = new Abstracta();//Abstracta es abstract, no se puede crear una
instancia directa
//Persona obj3 = new Persona();//Persona es abstract, no se puede crear una instancia
directa

Persona obj4 = new Empleado();


Empleado obj5 = new Empleado();
Programador obj6 = new Programador();
Boolean b;

b = obj4 instanceof Persona;System.out.println("obj4: "+b);//true


b = obj4 instanceof Modales;System.out.println("obj4: "+b);//true
b =obj4 instanceof Object;System.out.println("obj4: "+b);//true
b =obj4 instanceof Empleado;System.out.println("obj4: "+b);//true
b = obj4 instanceof Programador;System.out.println("obj4: "+b);//false
System.out.println("------------------------------");

b = obj5 instanceof Persona;System.out.println("obj5: "+b);//true


b = obj5 instanceof Empleado;System.out.println("obj5: "+b);//true
b = obj5 instanceof Modales;System.out.println("obj5: "+b);//true
b = obj5 instanceof Programador;System.out.println("obj5: "+b);//false
System.out.println("------------------------------");

b = obj6 instanceof Empleado;System.out.println("obj6: "+b);//true


b = obj6 instanceof Modales;System.out.println("obj6: "+b);//true
b = obj6 instanceof Persona;System.out.println("obj6: "+b);//true
b = obj6 instanceof Programador;System.out.println("obj6: "+b);//true
System.out.println("------------------------------");

b = null instanceof Persona;System.out.println("null: "+b);//false


b = null instanceof Empleado;System.out.println("null: "+b);//false
//b = obj6 instanceof String;//Error obj6 (de Programador) no es un String
}
}

Modales Persona

interface Modales{}
class Persona implements Modales{}
Main.java
public class Main {
public static void main(String[] args) {
//Interface ref = new InterfaceImpl
Modales obj1 = new Persona();
Persona obj2 = new Persona();
Boolean b;

b = obj1 instanceof Modales;System.out.println("obj1: "+b);//true


b = obj1 instanceof Persona;System.out.println("obj1: "+b);//true
System.out.println("-------------------");
b = obj2 instanceof Modales;System.out.println("obj2: "+b);//true
b = obj2 instanceof Persona;System.out.println("obj2: "+b);//true

}
}

interface Modales{
void saludar();
}

//Persona está obligada a implementar los métodos de la interface Modales


class Persona implements Modales{
@Override
public void saludar(){
System.out.println("Hola, buen día!!");
}
}

//Permitido, pero no se puede instanciar directamente: X objX = new X();


abstract class X extends Persona{}
final class Y extends X{}
//Esto no se puede:
//class Z extends Y{}
//Y es una clase final, no puede heredar
Modales Persona*

interface Modales{}
class Persona implements Modales{}//Obligada a implementar métodos de Modales
abstract class X extends Persona{}//Permitido, pero no se puede instanciar directamente
final class Y extends X{}
class Z extends Y{} //Error, Y es final, no puede heredar

Main.java
public class Main {
public static void main(String[] args) {
//Interface ref = new InterfaceImpl
Modales obj1 = new Persona();
Persona obj2 = new Persona();
Boolean b;

b = obj1 instanceof Modales;System.out.println("obj1: "+b);//true


b = obj1 instanceof Persona;System.out.println("obj1: "+b);//true
System.out.println("-------------------");
b = obj2 instanceof Modales;System.out.println("obj2: "+b);//true
b = obj2 instanceof Persona;System.out.println("obj2: "+b);//true
System.out.println("-------------------");
//Esto no se puede hacer:
//X obj3 = new X();//X es abstract

Y obj4 = new Y();


b = obj4 instanceof Modales;System.out.println("obj4: "+b);//true
b = obj4 instanceof Persona;System.out.println("obj4: "+b);//true
b = obj4 instanceof X;System.out.println("obj4: "+b);//true

}
}

interface Modales{
void saludar();
}

//Persona está obligada a implementar los métodos de la interface Modales


class Persona implements Modales{
@Override
public void saludar(){
System.out.println("Hola, buen día!!");
}
}

//Permitido, pero no se puede instanciar directamente: X objX = new X();


abstract class X extends Persona{}
final class Y extends X{}
//Esto no se puede:
//class Z extends Y{}
//Y es una clase final, no puede heredar

Tipos de declaraciones en Java

1. De asignación (assignment statement)


2. De condición (conditional statement)
3. De iteración (iteration statement)

//asignación
byte b = 0;
short corto =32;
int numero=23;
long largo = 12000;
float real = 12.0F;// o 12.0f
double valor =90.88;
char letra=’A’;
boolean verdadero=false;

//condicional
boolean verdadero = 34 > 45;//false
boolean falso = “FER”.length() >=3;//true
String nombre = 45>56? “FER” : 34>22? “TOM” : “MILL”;
MyInterface Parent*

Child

interface MyInterface{}
class Parent{}
class Child extends Parent implements MyInterface{}

Parent obj1 = new Parent();


obj1 instanceof Parent : true
obj1 instanceof Child : false
obj1 instanceof MyInterface : false

Parent obj2 = new Child();


obj2 instanceof Parent : true
obj2 instanceof Child : true
obj2 instanceof MyInterface : true

Child obj3 = new Child();


obj3 instanceof Parent : true
obj3 instanceof Child : true
obj3 instanceof MyInterface : true

Main.java
public class Main {
public static void main(String[] args) {

Parent obj1 = new Parent();


Parent obj2 = new Child();

System.out.println("obj1 instanceof Parent: "


+ (obj1 instanceof Parent));//true
System.out.println("obj1 instanceof Child: "
+ (obj1 instanceof Child));//false
System.out.println("obj1 instanceof MyInterface: "
+ (obj1 instanceof MyInterface));//false

System.out.println("----------------------------");
System.out.println("obj2 instanceof Parent: "
+ (obj2 instanceof Parent));//true
System.out.println("obj2 instanceof Child: "
+ (obj2 instanceof Child));//true
System.out.println("obj2 instanceof MyInterface: "
+ (obj2 instanceof MyInterface));//true

Child obj3 = new Child();

System.out.println("----------------------------");
System.out.println("obj3 instanceof Parent: "
+ (obj3 instanceof Parent));//true
System.out.println("obj3 instanceof Child: "
+ (obj3 instanceof Child));//true
System.out.println("obj3 instanceof MyInterface: "
+ (obj3 instanceof MyInterface));//true
}
}

interface MyInterface {}
class Parent {}
class Child extends Parent implements MyInterface {}

34>8 || false
true

!(34>8 || false)
false

true && (3==6 && false)


false

false || (56>77 || 34>=90 || 33<8)


false

(100>99.9 && 2<0) && (10==10 && false)


false

(100>99.9 && 2<0) && (10==10 && false)


false

Tipo de datos que admite un switch


byte, short, int, char, enum, String
String en Java

String str1 = "FER";


String str2 = "FER";
String str3 = new String(str2);

if (str1 == str2) {
System.out.println("str1 == str2");//str1==str2
}else{
System.out.println("str1 != str2");
}
if(str1.equals(str2)) {
System.out.println("str1.equals(str2)");//str1.equals(str2)
} else {
System.out.println("!str1.equals(str2)");
}

if (str3 == str2) {
System.out.println("str3 == str2");
}else{
System.out.println("str1 != str2");//str1 != str2
}
if(str3.equals(str2)) {
System.out.println("str3.equals(str2)");//str3.equals(str2)
} else {
System.out.println("!str3.equals(str2)");
}

Salida:
str1 == str2
str1.equals(str2)
str1 != str2
str3.equals(str2)

¿Qué es polimorfismo?

La capacidad de definir una función en múltiples formas se llama Polimorfismo. En java, c ++ existen
dos tipos de polimorfismo: compilación de polimorfismo de tiempo (sobrecarga) y polimorfismo de
tiempo de ejecución (anulación).

Anulación de método: sucede cuando una clase secundaria implementa el método con la misma firma
que un método en una clase principal. Cuando anula los métodos, JVM determina los métodos
adecuados para llamar en el tiempo de ejecución del programa, no en el tiempo de compilación.
Sobrecarga de métodos: ocurre cuando varios métodos tienen los mismos nombres pero diferentes
números o tipos de parámetros. La sobrecarga se determina en el tiempo de compilación.

La sobrecarga ocurre cuando:


Firma de método diferente y diferente número o tipo de parámetros.
La misma firma de método pero diferente número de parámetros.
La misma firma de método y el mismo número de parámetros pero de diferente tipo

class BookDetails {
String title;
void setBook(String title){
this.title=title;
}
}

class ScienceBook extends BookDetails {


String publisher;
float price;

@Override
void setBook(String title){
this.title=title;
} //overriding

//Overloading
void setBook(String title, String publisher,float price){
setBook(title);
this.publisher=publisher;
this.price=price;
} //overloading
}

BookDetails

ScienceBook

BookDetails is-a Object


BookDetails is-a BookDetails
ScienceBook is-a BookDetails
ScienceBook is-a ScienceBook

class X{
void calculo(){}
void calcuo(byte x){}
//int calculo(){}//Error: ya existe un método llamdo calculo, se crea ambiguedad
//String calculo(){return "";}//Error: ya existe un método llamdo calculo, se crea ambiguedad
String calculo(char c){return "";}
boolean calculo(int b){return 3>8;}
char calculo(String c){return c.charAt(2);}
void calculo(byte x, int c){}
}

Clases, métodos y variables final

class A {
public final void noModificable(){
System.out.println("Esto no se puede modificar ni sobreescribir");
}
}

class B extends A{
//Esto no se puede: un método final no puede sr sobreescrito
//@Override
//public final void noModificable(){
//System.out.println("Esto no se puede modificar ni sobreescribir");
//}
}

-Los métodos final no pueden ser modificados/sobreescritos.

final class NoHeredable{}


//Esto no se puede hacer:
//class X extends NoHeredable{}

-Una clase final no puede heredar.

final int entero = 9;


//Esto no se puede hacer:
//entero = 78;

final Map map = new HashMap();


map.put("key";,"value");
map = new HashMap(); // error
-Una variable final no puede ser modificado; es una constante.

Stack Heap
Primitivos Objetos

Main.java
public class Main {
public static void main(String[] args) {
X objX = new X(5);
System.out.println(objX.getN() == 5? "5" : "6");//5
objX = new X(6);
System.out.println(objX.getN());//8

}
}

class X{
private int n=8;

public X(int n){


if(n>5){
return;
}
this.n=n;
}

public int getN() {


return n;
}

public void setN(int n) {


this.n = n;
}

ArrayList

//De ArrayList a array(vector)


Integer[] enterosArray = new Integer[listaEnteros.size()];
enterosArray = listaEnteros.toArray(enterosArray);
System.out.println("+++++++++++++++++++++++");
for(Integer entero : enterosArray){
System.out.print(entero+",");
}
System.out.println();

//De array(vector) a ArrayList


java.util.List<Integer> listaEnterosNueva = java.util.Arrays.asList(enterosArray);
ArrayList<Integer> listaEnterosFinal = new ArrayList<>();
listaEnterosFinal.addAll(listaEnterosNueva);
System.out.println(">>"+listaEnterosFinal);

Métodos de ArrayList

add(index, value)
insert(index, value)
addAll(Collection)
get(indice)
toString()
isEmpty()
size()
remove(indice)
removeAll(Collection)
sort(Comparator)
toArray()
contains()
clear()
clone()
replaceAll()

Time y Date API


Clases:
java.time.Clock
java.time.Duration
java.time.Instant
java.time.LocalDate
java.time.LocalDateTime
java.time.LocalTime
java.time.MonthDay
java.time.OffsetDateTime
java.time.OffsetTime
java.time.Period
java.time.Year
java.time.YearMonth
java.time.ZonedDateTime
java.time.ZoneId
java.time.ZoneOffset

Enumeraciones:
java.time.DayOfWeek
java.time.Month

Excepciones
java.time.DateTimeException

import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime

LocalDate localDate = LocalDate.now();


LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();

System.out.println("LocalDate:"+localDate);//LocalDate:2018-04-06
System.out.println("LocalTime:"+localTime);//LocalTime:12:55:35.957
System.out.println("LocalDateTime:"+localDateTime);//LocalDateTime:2018-04-06T12:55:35.957

java.lang.Byte

Constructores

Constructor and Description


Byte(byte value)
Constructs a newly allocated Byte object that represents the specified byte value.
Byte(String s)
Constructs a newly allocated Byte object that represents the byte value indicated by the String
parameter.

Métodos
Modifier and
Method and Description
Type
byteValue()
byte
Returns the value of this Byte as a byte.
compare(byte x, byte y)
static int
Compares two byte values numerically.
int compareTo(Byte anotherByte)
Compares two Byte objects numerically.
static decode(String nm)
Byte Decodes a String into a Byte.
doubleValue()
double
Returns the value of this Byte as a double after a widening primitive conversion.
equals(Object obj)
boolean
Compares this object to the specified object.
floatValue()
float
Returns the value of this Byte as a float after a widening primitive conversion.
hashCode()
int
Returns a hash code for this Byte; equal to the result of invoking intValue().
hashCode(byte value)
static int
Returns a hash code for a byte value; compatible with Byte.hashCode().
intValue()
int
Returns the value of this Byte as an int after a widening primitive conversion.
longValue()
long
Returns the value of this Byte as a long after a widening primitive conversion.
static parseByte(String s)
byte Parses the string argument as a signed decimal byte.
parseByte(String s, int radix)
static
Parses the string argument as a signed byte in the radix specified by the second
byte
argument.
shortValue()
short
Returns the value of this Byte as a short after a widening primitive conversion.
toString()
String
Returns a String object representing this Byte's value.
static toString(byte b)
String Returns a new String object representing the specified byte.
toUnsignedInt(byte x)
static int
Converts the argument to an int by an unsigned conversion.
static toUnsignedLong(byte x)
long Converts the argument to a long by an unsigned conversion.
static valueOf(byte b)
Byte Returns a Byte instance representing the specified byte value.
static valueOf(String s)
Byte Returns a Byte object holding the value given by the specified String.
valueOf(String s, int radix)
static
Returns a Byte object holding the value extracted from the specified String when
Byte
parsed with the radix given by the second argument.
java.lang.Short
Constructores

Constructor and Description


Short(short value)
Constructs a newly allocated Short object that represents the specified short value.
Short(String s)
Constructs a newly allocated Short object that represents the short value indicated by the String
parameter.

Métodos
Modifier and
Method and Description
Type
byteValue()
byte
Returns the value of this Short as a byte after a narrowing primitive conversion.
compare(short x, short y)
static int
Compares two short values numerically.
compareTo(Short anotherShort)
int
Compares two Short objects numerically.
static decode(String nm)
Short Decodes a String into a Short.
doubleValue()
double
Returns the value of this Short as a double after a widening primitive conversion.
equals(Object obj)
boolean
Compares this object to the specified object.
floatValue()
float
Returns the value of this Short as a float after a widening primitive conversion.
hashCode()
int
Returns a hash code for this Short; equal to the result of invoking intValue().
hashCode(short value)
static int
Returns a hash code for a short value; compatible with Short.hashCode().
intValue()
int
Returns the value of this Short as an int after a widening primitive conversion.
longValue()
long
Returns the value of this Short as a long after a widening primitive conversion.
static parseShort(String s)
short Parses the string argument as a signed decimal short.
parseShort(String s, int radix)
static
Parses the string argument as a signed short in the radix specified by the second
short
argument.
reverseBytes(short i)
static
Returns the value obtained by reversing the order of the bytes in the two's
short
complement representation of the specified short value.
shortValue()
short
Returns the value of this Short as a short.
toString()
String
Returns a String object representing this Short's value.
static toString(short s)
String Returns a new String object representing the specified short.
toUnsignedInt(short x)
static int
Converts the argument to an int by an unsigned conversion.
static toUnsignedLong(short x)
long Converts the argument to a long by an unsigned conversion.
static valueOf(short s)
Short Returns a Short instance representing the specified short value.
static valueOf(String s)
Short Returns a Short object holding the value given by the specified String.
valueOf(String s, int radix)
static
Returns a Short object holding the value extracted from the specified String
Short
when parsed with the radix given by the second argument.

java.lang.Integer
Constructores

Constructor and Description


Integer(int value)
Constructs a newly allocated Integer object that represents the specified int value.
Integer(String s)
Constructs a newly allocated Integer object that represents the int value indicated by the String
parameter.

Métodos
Modifier and
Method and Description
Type
bitCount(int i)
static int Returns the number of one-bits in the two's complement binary representation of the
specified int value.
byteValue()
byte
Returns the value of this Integer as a byte after a narrowing primitive conversion.
compare(int x, int y)
static int
Compares two int values numerically.
compareTo(Integer anotherInteger)
int
Compares two Integer objects numerically.
compareUnsigned(int x, int y)
static int
Compares two int values numerically treating the values as unsigned.
static decode(String nm)
Integer Decodes a String into an Integer.
divideUnsigned(int dividend, int divisor)
static int Returns the unsigned quotient of dividing the first argument by the second where each
argument and the result is interpreted as an unsigned value.
doubleValue()
double Returns the value of this Integer as a double after a widening primitive
conversion.
equals(Object obj)
boolean
Compares this object to the specified object.
floatValue()
float Returns the value of this Integer as a float after a widening primitive
conversion.
static getInteger(String nm)
Integer Determines the integer value of the system property with the specified name.
static getInteger(String nm, int val)
Integer Determines the integer value of the system property with the specified name.
static getInteger(String nm, Integer val)
Integer Returns the integer value of the system property with the specified name.
hashCode()
int
Returns a hash code for this Integer.
hashCode(int value)
static int
Returns a hash code for a int value; compatible with Integer.hashCode().
highestOneBit(int i)
static int Returns an int value with at most a single one-bit, in the position of the highest-
order ("leftmost") one-bit in the specified int value.
intValue()
int
Returns the value of this Integer as an int.
longValue()
long
Returns the value of this Integer as a long after a widening primitive conversion.
lowestOneBit(int i)
static int Returns an int value with at most a single one-bit, in the position of the lowest-order
("rightmost") one-bit in the specified int value.
max(int a, int b)
static int
Returns the greater of two int values as if by calling Math.max.
min(int a, int b)
static int
Returns the smaller of two int values as if by calling Math.min.
static int numberOfLeadingZeros(int i)
Returns the number of zero bits preceding the highest-order ("leftmost") one-bit in the
two's complement binary representation of the specified int value.
numberOfTrailingZeros(int i)
static int Returns the number of zero bits following the lowest-order ("rightmost") one-bit in
the two's complement binary representation of the specified int value.
parseInt(String s)
static int
Parses the string argument as a signed decimal integer.
parseInt(String s, int radix)
static int Parses the string argument as a signed integer in the radix specified by the second
argument.
parseUnsignedInt(String s)
static int
Parses the string argument as an unsigned decimal integer.
parseUnsignedInt(String s, int radix)
static int Parses the string argument as an unsigned integer in the radix specified by the second
argument.
remainderUnsigned(int dividend, int divisor)
static int Returns the unsigned remainder from dividing the first argument by the second where
each argument and the result is interpreted as an unsigned value.
reverse(int i)
static int Returns the value obtained by reversing the order of the bits in the two's complement
binary representation of the specified int value.
reverseBytes(int i)
static int Returns the value obtained by reversing the order of the bytes in the two's
complement representation of the specified int value.
rotateLeft(int i, int distance)
static int Returns the value obtained by rotating the two's complement binary representation of
the specified int value left by the specified number of bits.
rotateRight(int i, int distance)
static int Returns the value obtained by rotating the two's complement binary representation of
the specified int value right by the specified number of bits.
shortValue()
short Returns the value of this Integer as a short after a narrowing primitive
conversion.
signum(int i)
static int
Returns the signum function of the specified int value.
sum(int a, int b)
static int
Adds two integers together as per the + operator.
toBinaryString(int i)
static
String Returns a string representation of the integer argument as an unsigned integer in
base 2.
toHexString(int i)
static
String Returns a string representation of the integer argument as an unsigned integer in
base 16.
toOctalString(int i)
static
String Returns a string representation of the integer argument as an unsigned integer in
base 8.
toString()
String
Returns a String object representing this Integer's value.
static toString(int i)
String Returns a String object representing the specified integer.
toString(int i, int radix)
static
String Returns a string representation of the first argument in the radix specified by the
second argument.
static toUnsignedLong(int x)
long Converts the argument to a long by an unsigned conversion.
static toUnsignedString(int i)
String Returns a string representation of the argument as an unsigned decimal value.
toUnsignedString(int i, int radix)
static
String Returns a string representation of the first argument as an unsigned integer value in
the radix specified by the second argument.
static valueOf(int i)
Integer Returns an Integer instance representing the specified int value.
static valueOf(String s)
Integer Returns an Integer object holding the value of the specified String.
valueOf(String s, int radix)
static
Returns an Integer object holding the value extracted from the specified String
Integer
when parsed with the radix given by the second argument.

java.lang.Long
Constructores
Constructor and Description
Long(long value)
Constructs a newly allocated Long object that represents the specified long argument.
Long(String s)
Constructs a newly allocated Long object that represents the long value indicated by the String
parameter.

Métodos
Modifier and
Method and Description
Type
bitCount(long i)
static
Returns the number of one-bits in the two's complement binary representation of the
int
specified long value.
byteValue()
byte
Returns the value of this Long as a byte after a narrowing primitive conversion.
static compare(long x, long y)
int Compares two long values numerically.
compareTo(Long anotherLong)
int
Compares two Long objects numerically.
static compareUnsigned(long x, long y)
int Compares two long values numerically treating the values as unsigned.
static decode(String nm)
Long Decodes a String into a Long.
divideUnsigned(long dividend, long divisor)
static
long Returns the unsigned quotient of dividing the first argument by the second where each
argument and the result is interpreted as an unsigned value.
doubleValue()
double
Returns the value of this Long as a double after a widening primitive conversion.
equals(Object obj)
boolean
Compares this object to the specified object.
floatValue()
float
Returns the value of this Long as a float after a widening primitive conversion.
static getLong(String nm)
Long Determines the long value of the system property with the specified name.
static getLong(String nm, long val)
Long Determines the long value of the system property with the specified name.
static getLong(String nm, Long val)
Long Returns the long value of the system property with the specified name.
hashCode()
int
Returns a hash code for this Long.
static hashCode(long value)
int Returns a hash code for a long value; compatible with Long.hashCode().
highestOneBit(long i)
static
Returns a long value with at most a single one-bit, in the position of the highest-order
long
("leftmost") one-bit in the specified long value.
intValue()
int
Returns the value of this Long as an int after a narrowing primitive conversion.
longValue()
long
Returns the value of this Long as a long value.
lowestOneBit(long i)
static
Returns a long value with at most a single one-bit, in the position of the lowest-order
long
("rightmost") one-bit in the specified long value.
static max(long a, long b)
long Returns the greater of two long values as if by calling Math.max.
static min(long a, long b)
long Returns the smaller of two long values as if by calling Math.min.
numberOfLeadingZeros(long i)
static
Returns the number of zero bits preceding the highest-order ("leftmost") one-bit in the
int
two's complement binary representation of the specified long value.
numberOfTrailingZeros(long i)
static
Returns the number of zero bits following the lowest-order ("rightmost") one-bit in the
int
two's complement binary representation of the specified long value.
static parseLong(String s)
long Parses the string argument as a signed decimal long.
parseLong(String s, int radix)
static
Parses the string argument as a signed long in the radix specified by the second
long
argument.
static parseUnsignedLong(String s)
long Parses the string argument as an unsigned decimal long.
parseUnsignedLong(String s, int radix)
static
Parses the string argument as an unsigned long in the radix specified by the second
long
argument.
remainderUnsigned(long dividend, long divisor)
static
long Returns the unsigned remainder from dividing the first argument by the second where
each argument and the result is interpreted as an unsigned value.
reverse(long i)
static
Returns the value obtained by reversing the order of the bits in the two's complement
long
binary representation of the specified long value.
reverseBytes(long i)
static
Returns the value obtained by reversing the order of the bytes in the two's complement
long
representation of the specified long value.
rotateLeft(long i, int distance)
static
Returns the value obtained by rotating the two's complement binary representation of
long
the specified long value left by the specified number of bits.
rotateRight(long i, int distance)
static
Returns the value obtained by rotating the two's complement binary representation of
long
the specified long value right by the specified number of bits.
shortValue()
short
Returns the value of this Long as a short after a narrowing primitive conversion.
static signum(long i)
int Returns the signum function of the specified long value.
static sum(long a, long b)
long Adds two long values together as per the + operator.
static toBinaryString(long i)
String Returns a string representation of the long argument as an unsigned integer in base 2.
toHexString(long i)
static
Returns a string representation of the long argument as an unsigned integer in
String
base 16.
static toOctalString(long i)
String Returns a string representation of the long argument as an unsigned integer in base 8.
toString()
String
Returns a String object representing this Long's value.
static toString(long i)
String Returns a String object representing the specified long.
toString(long i, int radix)
static
String Returns a string representation of the first argument in the radix specified by the
second argument.
static toUnsignedString(long i)
String Returns a string representation of the argument as an unsigned decimal value.
toUnsignedString(long i, int radix)
static
String Returns a string representation of the first argument as an unsigned integer value in the
radix specified by the second argument.
static valueOf(long l)
Long Returns a Long instance representing the specified long value.
static valueOf(String s)
Long Returns a Long object holding the value of the specified String.
valueOf(String s, int radix)
static
Returns a Long object holding the value extracted from the specified String when
Long
parsed with the radix given by the second argument.

java.lang.Float
Constructores

Constructor and Description


Float(double value)
Constructs a newly allocated Float object that represents the argument converted to type float.
Float(float value)
Constructs a newly allocated Float object that represents the primitive float argument.
Float(String s)
Constructs a newly allocated Float object that represents the floating-point value of type float
represented by the string.

Métodos
Modifier and
Method and Description
Type
byteValue()
byte
Returns the value of this Float as a byte after a narrowing primitive conversion.
compare(float f1, float f2)
static int
Compares the two specified float values.
int compareTo(Float anotherFloat)
Compares two Float objects numerically.
doubleValue()
double
Returns the value of this Float as a double after a widening primitive conversion.
equals(Object obj)
boolean
Compares this object against the specified object.
floatToIntBits(float value)
static int Returns a representation of the specified floating-point value according to the IEEE
754 floating-point "single format" bit layout.
floatToRawIntBits(float value)
static int Returns a representation of the specified floating-point value according to the IEEE
754 floating-point "single format" bit layout, preserving Not-a-Number (NaN) values.
floatValue()
float
Returns the float value of this Float object.
hashCode()
int
Returns a hash code for this Float object.
hashCode(float value)
static int
Returns a hash code for a float value; compatible with Float.hashCode().
static intBitsToFloat(int bits)
float Returns the float value corresponding to a given bit representation.
intValue()
int
Returns the value of this Float as an int after a narrowing primitive conversion.
isFinite(float f)
static
Returns true if the argument is a finite floating-point value; returns false
boolean
otherwise (for NaN and infinity arguments).
isInfinite()
boolean
Returns true if this Float value is infinitely large in magnitude, false otherwise.
isInfinite(float v)
static
Returns true if the specified number is infinitely large in magnitude, false
boolean
otherwise.
isNaN()
boolean
Returns true if this Float value is a Not-a-Number (NaN), false otherwise.
isNaN(float v)
static
Returns true if the specified number is a Not-a-Number (NaN) value, false
boolean
otherwise.
longValue()
long
Returns value of this Float as a long after a narrowing primitive conversion.
static max(float a, float b)
float Returns the greater of two float values as if by calling Math.max.
static min(float a, float b)
float Returns the smaller of two float values as if by calling Math.min.
static parseFloat(String s)
float Returns a new float initialized to the value represented by the specified String,
as performed by the valueOf method of class Float.
shortValue()
short
Returns the value of this Float as a short after a narrowing primitive conversion.
static sum(float a, float b)
float Adds two float values together as per the + operator.
static toHexString(float f)
String Returns a hexadecimal string representation of the float argument.
toString()
String
Returns a string representation of this Float object.
static toString(float f)
String Returns a string representation of the float argument.
static valueOf(float f)
Float Returns a Float instance representing the specified float value.
valueOf(String s)
static
Returns a Float object holding the float value represented by the argument string
Float
s.

java.lang.Double
Constructores

Constructor and Description


Double(double value)
Constructs a newly allocated Double object that represents the primitive double argument.
Double(String s)
Constructs a newly allocated Double object that represents the floating-point value of type double
represented by the string.

Métodos
Modifier and
Method and Description
Type
byteValue()
byte
Returns the value of this Double as a byte after a narrowing primitive conversion.
compare(double d1, double d2)
static int
Compares the two specified double values.
compareTo(Double anotherDouble)
int
Compares two Double objects numerically.
doubleToLongBits(double value)
static
long Returns a representation of the specified floating-point value according to the IEEE
754 floating-point "double format" bit layout.
doubleToRawLongBits(double value)
static
long Returns a representation of the specified floating-point value according to the IEEE
754 floating-point "double format" bit layout, preserving Not-a-Number (NaN) values.
doubleValue()
double
Returns the double value of this Double object.
equals(Object obj)
boolean
Compares this object against the specified object.
floatValue()
float
Returns the value of this Double as a float after a narrowing primitive conversion.
hashCode()
int
Returns a hash code for this Double object.
hashCode(double value)
static int
Returns a hash code for a double value; compatible with Double.hashCode().
intValue()
int
Returns the value of this Double as an int after a narrowing primitive conversion.
isFinite(double d)
static
Returns true if the argument is a finite floating-point value; returns false
boolean
otherwise (for NaN and infinity arguments).
isInfinite()
boolean Returns true if this Double value is infinitely large in magnitude, false
otherwise.
isInfinite(double v)
static
Returns true if the specified number is infinitely large in magnitude, false
boolean
otherwise.
isNaN()
boolean
Returns true if this Double value is a Not-a-Number (NaN), false otherwise.
isNaN(double v)
static
Returns true if the specified number is a Not-a-Number (NaN) value, false
boolean
otherwise.
static longBitsToDouble(long bits)
double Returns the double value corresponding to a given bit representation.
longValue()
long
Returns the value of this Double as a long after a narrowing primitive conversion.
static max(double a, double b)
double Returns the greater of two double values as if by calling Math.max.
static min(double a, double b)
double Returns the smaller of two double values as if by calling Math.min.
parseDouble(String s)
static
Returns a new double initialized to the value represented by the specified String,
double
as performed by the valueOf method of class Double.
shortValue()
short
Returns the value of this Double as a short after a narrowing primitive conversion.
static sum(double a, double b)
double Adds two double values together as per the + operator.
static toHexString(double d)
String Returns a hexadecimal string representation of the double argument.
toString()
String
Returns a string representation of this Double object.
static toString(double d)
String Returns a string representation of the double argument.
static valueOf(double d)
Double Returns a Double instance representing the specified double value.
valueOf(String s)
static
Returns a Double object holding the double value represented by the argument
Double
string s.

java.lang.Character
Constructores

Constructor and Description


Character(char value)
Constructs a newly allocated Character object that represents the specified char value.

Métodos
Modifier and Type Field and Description
BYTES
static int The number of bytes used to represent a char value in unsigned binary
form.
COMBINING_SPACING_MARK
static byte
General category "Mc" in the Unicode specification.
CONNECTOR_PUNCTUATION
static byte
General category "Pc" in the Unicode specification.
CONTROL
static byte
General category "Cc" in the Unicode specification.
CURRENCY_SYMBOL
static byte
General category "Sc" in the Unicode specification.
DASH_PUNCTUATION
static byte
General category "Pd" in the Unicode specification.
DECIMAL_DIGIT_NUMBER
static byte
General category "Nd" in the Unicode specification.
DIRECTIONALITY_ARABIC_NUMBER
static byte
Weak bidirectional character type "AN" in the Unicode specification.
DIRECTIONALITY_BOUNDARY_NEUTRAL
static byte
Weak bidirectional character type "BN" in the Unicode specification.
DIRECTIONALITY_COMMON_NUMBER_SEPARATOR
static byte
Weak bidirectional character type "CS" in the Unicode specification.
DIRECTIONALITY_EUROPEAN_NUMBER
static byte
Weak bidirectional character type "EN" in the Unicode specification.
DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR
static byte
Weak bidirectional character type "ES" in the Unicode specification.
DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR
static byte
Weak bidirectional character type "ET" in the Unicode specification.
DIRECTIONALITY_LEFT_TO_RIGHT
static byte
Strong bidirectional character type "L" in the Unicode specification.
DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING
static byte
Strong bidirectional character type "LRE" in the Unicode specification.
DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE
static byte
Strong bidirectional character type "LRO" in the Unicode specification.
DIRECTIONALITY_NONSPACING_MARK
static byte
Weak bidirectional character type "NSM" in the Unicode specification.
DIRECTIONALITY_OTHER_NEUTRALS
static byte
Neutral bidirectional character type "ON" in the Unicode specification.
DIRECTIONALITY_PARAGRAPH_SEPARATOR
static byte
Neutral bidirectional character type "B" in the Unicode specification.
DIRECTIONALITY_POP_DIRECTIONAL_FORMAT
static byte
Weak bidirectional character type "PDF" in the Unicode specification.
DIRECTIONALITY_RIGHT_TO_LEFT
static byte
Strong bidirectional character type "R" in the Unicode specification.
DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC
static byte
Strong bidirectional character type "AL" in the Unicode specification.
DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING
static byte
Strong bidirectional character type "RLE" in the Unicode specification.
DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE
static byte
Strong bidirectional character type "RLO" in the Unicode specification.
DIRECTIONALITY_SEGMENT_SEPARATOR
static byte
Neutral bidirectional character type "S" in the Unicode specification.
DIRECTIONALITY_UNDEFINED
static byte
Undefined bidirectional character type.
DIRECTIONALITY_WHITESPACE
static byte
Neutral bidirectional character type "WS" in the Unicode specification.
ENCLOSING_MARK
static byte
General category "Me" in the Unicode specification.
END_PUNCTUATION
static byte
General category "Pe" in the Unicode specification.
FINAL_QUOTE_PUNCTUATION
static byte
General category "Pf" in the Unicode specification.
FORMAT
static byte
General category "Cf" in the Unicode specification.
INITIAL_QUOTE_PUNCTUATION
static byte
General category "Pi" in the Unicode specification.
LETTER_NUMBER
static byte
General category "Nl" in the Unicode specification.
LINE_SEPARATOR
static byte
General category "Zl" in the Unicode specification.
LOWERCASE_LETTER
static byte
General category "Ll" in the Unicode specification.
MATH_SYMBOL
static byte
General category "Sm" in the Unicode specification.
MAX_CODE_POINT
static int
The maximum value of a Unicode code point, constant U+10FFFF.
MAX_HIGH_SURROGATE
static char The maximum value of a Unicode high-surrogate code unit in the UTF-16
encoding, constant '\uDBFF'.
MAX_LOW_SURROGATE
static char The maximum value of a Unicode low-surrogate code unit in the UTF-16
encoding, constant '\uDFFF'.
MAX_RADIX
static int
The maximum radix available for conversion to and from strings.
MAX_SURROGATE
static char The maximum value of a Unicode surrogate code unit in the UTF-16
encoding, constant '\uDFFF'.
MAX_VALUE
static char The constant value of this field is the largest value of type char,
'\uFFFF'.
MIN_CODE_POINT
static int
The minimum value of a Unicode code point, constant U+0000.
MIN_HIGH_SURROGATE
static char The minimum value of a Unicode high-surrogate code unit in the UTF-16
encoding, constant '\uD800'.
MIN_LOW_SURROGATE
static char The minimum value of a Unicode low-surrogate code unit in the UTF-16
encoding, constant '\uDC00'.
MIN_RADIX
static int
The minimum radix available for conversion to and from strings.
MIN_SUPPLEMENTARY_CODE_POINT
static int The minimum value of a Unicode supplementary code point, constant
U+10000.
MIN_SURROGATE
static char The minimum value of a Unicode surrogate code unit in the UTF-16
encoding, constant '\uD800'.
MIN_VALUE
static char The constant value of this field is the smallest value of type char,
'\u0000'.
MODIFIER_LETTER
static byte
General category "Lm" in the Unicode specification.
MODIFIER_SYMBOL
static byte
General category "Sk" in the Unicode specification.
NON_SPACING_MARK
static byte
General category "Mn" in the Unicode specification.
OTHER_LETTER
static byte
General category "Lo" in the Unicode specification.
OTHER_NUMBER
static byte
General category "No" in the Unicode specification.
OTHER_PUNCTUATION
static byte
General category "Po" in the Unicode specification.
OTHER_SYMBOL
static byte
General category "So" in the Unicode specification.
PARAGRAPH_SEPARATOR
static byte
General category "Zp" in the Unicode specification.
PRIVATE_USE
static byte
General category "Co" in the Unicode specification.
SIZE
static int The number of bits used to represent a char value in unsigned binary
form, constant 16.
SPACE_SEPARATOR
static byte
General category "Zs" in the Unicode specification.
START_PUNCTUATION
static byte
General category "Ps" in the Unicode specification.
SURROGATE
static byte
General category "Cs" in the Unicode specification.
TITLECASE_LETTER
static byte
General category "Lt" in the Unicode specification.
static TYPE
Class<Character> The Class instance representing the primitive type char.
UNASSIGNED
static byte
General category "Cn" in the Unicode specification.
UPPERCASE_LETTER
static byte
General category "Lu" in the Unicode specification.

java.lang.Boolean
Constructores
Constructor and Description
Boolean(boolean value)
Allocates a Boolean object representing the value argument.
Boolean(String s)
Allocates a Boolean object representing the value true if the string argument is not null and is
equal, ignoring case, to the string "true".

Métodos
Modifier and
Method and Description
Type
booleanValue()
boolean
Returns the value of this Boolean object as a boolean primitive.
compare(boolean x, boolean y)
static int
Compares two boolean values.
compareTo(Boolean b)
int
Compares this Boolean instance with another.
equals(Object obj)
boolean Returns true if and only if the argument is not null and is a Boolean object that
represents the same boolean value as this object.
getBoolean(String name)
static
Returns true if and only if the system property named by the argument exists and is
boolean
equal to the string "true".
hashCode()
int
Returns a hash code for this Boolean object.
hashCode(boolean value)
static int Returns a hash code for a boolean value; compatible with
Boolean.hashCode().
logicalAnd(boolean a, boolean b)
static
Returns the result of applying the logical AND operator to the specified boolean
boolean
operands.
logicalOr(boolean a, boolean b)
static
Returns the result of applying the logical OR operator to the specified boolean
boolean
operands.
logicalXor(boolean a, boolean b)
static
Returns the result of applying the logical XOR operator to the specified boolean
boolean
operands.
static parseBoolean(String s)
boolean Parses the string argument as a boolean.
toString()
String
Returns a String object representing this Boolean's value.
static toString(boolean b)
String Returns a String object representing the specified boolean.
static valueOf(boolean b)
Boolean Returns a Boolean instance representing the specified boolean value.
static valueOf(String s)
Boolean Returns a Boolean with a value represented by the specified string.

java.lang.String
Constructores

Constructor and Description


String()
Initializes a newly created String object so that it represents an empty character sequence.
String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default
charset.
String(byte[] bytes, Charset charset)
Constructs a new String by decoding the specified array of bytes using the specified charset.
String(byte[] ascii, int hibyte)
Deprecated.
This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do
this is via the String constructors that take a Charset, charset name, or that use the platform's
default charset.
String(byte[] bytes, int offset, int length)
Constructs a new String by decoding the specified subarray of bytes using the platform's default
charset.
String(byte[] bytes, int offset, int length, Charset charset)
Constructs a new String by decoding the specified subarray of bytes using the specified charset.
String(byte[] ascii, int hibyte, int offset, int count)
Deprecated.
This method does not properly convert bytes into characters. As of JDK 1.1, the preferred way to do
this is via the String constructors that take a Charset, charset name, or that use the platform's
default charset.
String(byte[] bytes, int offset, int length, String charsetName)
Constructs a new String by decoding the specified subarray of bytes using the specified charset.
String(byte[] bytes, String charsetName)
Constructs a new String by decoding the specified array of bytes using the specified charset.
String(char[] value)
Allocates a new String so that it represents the sequence of characters currently contained in the
character array argument.
String(char[] value, int offset, int count)
Allocates a new String that contains characters from a subarray of the character array argument.
String(int[] codePoints, int offset, int count)
Allocates a new String that contains characters from a subarray of the Unicode code point array
argument.
String(String original)
Initializes a newly created String object so that it represents the same sequence of characters as the
argument; in other words, the newly created string is a copy of the argument string.
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer
argument.
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder
argument.

Métodos
Modifier and
Method and Description
Type
charAt(int index)
char
Returns the char value at the specified index.
codePointAt(int index)
int
Returns the character (Unicode code point) at the specified index.
codePointBefore(int index)
int
Returns the character (Unicode code point) before the specified index.
codePointCount(int beginIndex, int endIndex)
int Returns the number of Unicode code points in the specified text range of this
String.
compareTo(String anotherString)
int
Compares two strings lexicographically.
compareToIgnoreCase(String str)
int
Compares two strings lexicographically, ignoring case differences.
concat(String str)
String
Concatenates the specified string to the end of this string.
contains(CharSequence s)
boolean Returns true if and only if this string contains the specified sequence of char
values.
contentEquals(CharSequence cs)
boolean
Compares this string to the specified CharSequence.
contentEquals(StringBuffer sb)
boolean
Compares this string to the specified StringBuffer.
static copyValueOf(char[] data)
String Equivalent to valueOf(char[]).
static copyValueOf(char[] data, int offset, int count)
String Equivalent to valueOf(char[], int, int).
endsWith(String suffix)
boolean
Tests if this string ends with the specified suffix.
equals(Object anObject)
boolean
Compares this string to the specified object.
equalsIgnoreCase(String anotherString)
boolean
Compares this String to another String, ignoring case considerations.
static format(Locale l, String format, Object... args)
String Returns a formatted string using the specified locale, format string, and arguments.
static format(String format, Object... args)
String Returns a formatted string using the specified format string and arguments.
getBytes()
byte[] Encodes this String into a sequence of bytes using the platform's default
charset, storing the result into a new byte array.
getBytes(Charset charset)
byte[] Encodes this String into a sequence of bytes using the given charset, storing the
result into a new byte array.
getBytes(int srcBegin, int srcEnd, byte[] dst,
int dstBegin)
Deprecated.
void
This method does not properly convert characters into bytes. As of JDK 1.1, the
preferred way to do this is via the getBytes() method, which uses the
platform's default charset.
getBytes(String charsetName)
byte[] Encodes this String into a sequence of bytes using the named charset, storing
the result into a new byte array.
getChars(int srcBegin, int srcEnd, char[] dst,
void int dstBegin)
Copies characters from this string into the destination character array.
hashCode()
int
Returns a hash code for this string.
indexOf(int ch)
int Returns the index within this string of the first occurrence of the specified
character.
indexOf(int ch, int fromIndex)
int Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
indexOf(String str)
int Returns the index within this string of the first occurrence of the specified
substring.
indexOf(String str, int fromIndex)
int Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
intern()
String
Returns a canonical representation for the string object.
boolean isEmpty()
Returns true if, and only if, length() is 0.
join(CharSequence delimiter, CharSequence... elements)
static
Returns a new String composed of copies of the CharSequence elements
String
joined together with a copy of the specified delimiter.
join(CharSequence delimiter, Iterable<? extends
static CharSequence> elements)
String Returns a new String composed of copies of the CharSequence elements
joined together with a copy of the specified delimiter.
lastIndexOf(int ch)
int Returns the index within this string of the last occurrence of the specified
character.
lastIndexOf(int ch, int fromIndex)
int Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.
lastIndexOf(String str)
int Returns the index within this string of the last occurrence of the specified
substring.
lastIndexOf(String str, int fromIndex)
int Returns the index within this string of the last occurrence of the specified
substring, searching backward starting at the specified index.
length()
int
Returns the length of this string.
matches(String regex)
boolean
Tells whether or not this string matches the given regular expression.
offsetByCodePoints(int index, int codePointOffset)
int Returns the index within this String that is offset from the given index by
codePointOffset code points.
regionMatches(boolean ignoreCase, int toffset,
boolean String other, int ooffset, int len)
Tests if two string regions are equal.
regionMatches(int toffset, String other, int ooffset,
boolean int len)
Tests if two string regions are equal.
replace(char oldChar, char newChar)
String Returns a string resulting from replacing all occurrences of oldChar in this
string with newChar.
replace(CharSequence target, CharSequence replacement)
String Replaces each substring of this string that matches the literal target sequence with
the specified literal replacement sequence.
replaceAll(String regex, String replacement)
String Replaces each substring of this string that matches the given regular expression
with the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression
with the given replacement.
split(String regex)
String[]
Splits this string around matches of the given regular expression.
split(String regex, int limit)
String[]
Splits this string around matches of the given regular expression.
startsWith(String prefix)
boolean
Tests if this string starts with the specified prefix.
startsWith(String prefix, int toffset)
boolean Tests if the substring of this string beginning at the specified index starts with the
specified prefix.
subSequence(int beginIndex, int endIndex)
CharSequence
Returns a character sequence that is a subsequence of this sequence.
substring(int beginIndex)
String
Returns a string that is a substring of this string.
substring(int beginIndex, int endIndex)
String
Returns a string that is a substring of this string.
toCharArray()
char[]
Converts this string to a new character array.
toLowerCase()
String Converts all of the characters in this String to lower case using the rules of the
default locale.
toLowerCase(Locale locale)
String Converts all of the characters in this String to lower case using the rules of the
given Locale.
toString()
String
This object (which is already a string!) is itself returned.
toUpperCase()
String Converts all of the characters in this String to upper case using the rules of the
default locale.
toUpperCase(Locale locale)
String Converts all of the characters in this String to upper case using the rules of the
given Locale.
trim()
String Returns a string whose value is this string, with any leading and trailing
whitespace removed.
static valueOf(boolean b)
String Returns the string representation of the boolean argument.
static valueOf(char c)
String Returns the string representation of the char argument.
static valueOf(char[] data)
String Returns the string representation of the char array argument.
valueOf(char[] data, int offset, int count)
static
Returns the string representation of a specific subarray of the char array
String
argument.
static valueOf(double d)
String Returns the string representation of the double argument.
static valueOf(float f)
String Returns the string representation of the float argument.
static valueOf(int i)
String Returns the string representation of the int argument.
static valueOf(long l)
String Returns the string representation of the long argument.
static valueOf(Object obj)
String Returns the string representation of the Object argument.

java.lang.StringBuilder
Constructores

Constructor and Description


StringBuilder()
Constructs a string builder with no characters in it and an initial capacity of 16 characters.
StringBuilder(CharSequence seq)
Constructs a string builder that contains the same characters as the specified CharSequence.
StringBuilder(int capacity)
Constructs a string builder with no characters in it and an initial capacity specified by the capacity
argument.
StringBuilder(String str)
Constructs a string builder initialized to the contents of the specified string.

Métodos
Modifier and Type Method and Description
append(boolean b)
StringBuilder
Appends the string representation of the boolean argument to the sequence.
append(char c)
StringBuilder
Appends the string representation of the char argument to this sequence.
append(char[] str)
StringBuilder
Appends the string representation of the char array argument to this sequence.
append(char[] str, int offset, int len)
StringBuilder Appends the string representation of a subarray of the char array argument to
this sequence.
append(CharSequence s)
StringBuilder
Appends the specified character sequence to this Appendable.
append(CharSequence s, int start, int end)
StringBuilder
Appends a subsequence of the specified CharSequence to this sequence.
append(double d)
StringBuilder
Appends the string representation of the double argument to this sequence.
append(float f)
StringBuilder
Appends the string representation of the float argument to this sequence.
append(int i)
StringBuilder
Appends the string representation of the int argument to this sequence.
append(long lng)
StringBuilder
Appends the string representation of the long argument to this sequence.
append(Object obj)
StringBuilder
Appends the string representation of the Object argument.
append(String str)
StringBuilder
Appends the specified string to this character sequence.
append(StringBuffer sb)
StringBuilder
Appends the specified StringBuffer to this sequence.
appendCodePoint(int codePoint)
StringBuilder
Appends the string representation of the codePoint argument to this sequence.
capacity()
int
Returns the current capacity.
charAt(int index)
char
Returns the char value in this sequence at the specified index.
codePointAt(int index)
int
Returns the character (Unicode code point) at the specified index.
codePointBefore(int index)
int
Returns the character (Unicode code point) before the specified index.
codePointCount(int beginIndex, int endIndex)
int Returns the number of Unicode code points in the specified text range of this
sequence.
delete(int start, int end)
StringBuilder
Removes the characters in a substring of this sequence.
deleteCharAt(int index)
StringBuilder
Removes the char at the specified position in this sequence.
ensureCapacity(int minimumCapacity)
void
Ensures that the capacity is at least equal to the specified minimum.
getChars(int srcBegin, int srcEnd, char[] dst,
int dstBegin)
void
Characters are copied from this sequence into the destination character array
dst.
indexOf(String str)
int Returns the index within this string of the first occurrence of the specified
substring.
indexOf(String str, int fromIndex)
int Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
insert(int offset, boolean b)
StringBuilder
Inserts the string representation of the boolean argument into this sequence.
insert(int offset, char c)
StringBuilder
Inserts the string representation of the char argument into this sequence.
insert(int offset, char[] str)
StringBuilder
Inserts the string representation of the char array argument into this sequence.
insert(int index, char[] str, int offset, int len)
StringBuilder Inserts the string representation of a subarray of the str array argument into this
sequence.
insert(int dstOffset, CharSequence s)
StringBuilder
Inserts the specified CharSequence into this sequence.
insert(int dstOffset, CharSequence s, int start,
StringBuilder int end)
Inserts a subsequence of the specified CharSequence into this sequence.
insert(int offset, double d)
StringBuilder
Inserts the string representation of the double argument into this sequence.
insert(int offset, float f)
StringBuilder
Inserts the string representation of the float argument into this sequence.
insert(int offset, int i)
StringBuilder
Inserts the string representation of the second int argument into this sequence.
insert(int offset, long l)
StringBuilder
Inserts the string representation of the long argument into this sequence.
insert(int offset, Object obj)
StringBuilder Inserts the string representation of the Object argument into this character
sequence.
insert(int offset, String str)
StringBuilder
Inserts the string into this character sequence.
lastIndexOf(String str)
int Returns the index within this string of the rightmost occurrence of the specified
substring.
lastIndexOf(String str, int fromIndex)
int Returns the index within this string of the last occurrence of the specified
substring.
length()
int
Returns the length (character count).
offsetByCodePoints(int index, int codePointOffset)
int Returns the index within this sequence that is offset from the given index by
codePointOffset code points.
StringBuilder replace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters in the
specified String.
reverse()
StringBuilder
Causes this character sequence to be replaced by the reverse of the sequence.
setCharAt(int index, char ch)
void
The character at the specified index is set to ch.
setLength(int newLength)
void
Sets the length of the character sequence.
subSequence(int start, int end)
CharSequence
Returns a new character sequence that is a subsequence of this sequence.
substring(int start)
String Returns a new String that contains a subsequence of characters currently
contained in this character sequence.
substring(int start, int end)
String Returns a new String that contains a subsequence of characters currently
contained in this sequence.
toString()
String
Returns a string representing the data in this sequence.
trimToSize()
void
Attempts to reduce storage used for the character sequence.

java.lang.StringBuffer
Constructores
Constructor and Description
StringBuffer()
Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(CharSequence seq)
Constructs a string buffer that contains the same characters as the specified
CharSequence.
StringBuffer(int capacity)
Constructs a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str)
Constructs a string buffer initialized to the contents of the specified string.

Métodos
Modifier and
Method and Description
Type
append(boolean b)
StringBuffer
Appends the string representation of the boolean argument to the sequence.
append(char c)
StringBuffer
Appends the string representation of the char argument to this sequence.
append(char[] str)
StringBuffer
Appends the string representation of the char array argument to this sequence.
append(char[] str, int offset, int len)
StringBuffer Appends the string representation of a subarray of the char array argument to
this sequence.
append(CharSequence s)
StringBuffer
Appends the specified CharSequence to this sequence.
append(CharSequence s, int start, int end)
StringBuffer
Appends a subsequence of the specified CharSequence to this sequence.
append(double d)
StringBuffer
Appends the string representation of the double argument to this sequence.
append(float f)
StringBuffer
Appends the string representation of the float argument to this sequence.
append(int i)
StringBuffer
Appends the string representation of the int argument to this sequence.
append(long lng)
StringBuffer
Appends the string representation of the long argument to this sequence.
append(Object obj)
StringBuffer
Appends the string representation of the Object argument.
append(String str)
StringBuffer
Appends the specified string to this character sequence.
append(StringBuffer sb)
StringBuffer
Appends the specified StringBuffer to this sequence.
appendCodePoint(int codePoint)
StringBuffer
Appends the string representation of the codePoint argument to this sequence.
capacity()
int
Returns the current capacity.
charAt(int index)
char
Returns the char value in this sequence at the specified index.
codePointAt(int index)
int
Returns the character (Unicode code point) at the specified index.
codePointBefore(int index)
int
Returns the character (Unicode code point) before the specified index.
codePointCount(int beginIndex, int endIndex)
int Returns the number of Unicode code points in the specified text range of this
sequence.
delete(int start, int end)
StringBuffer
Removes the characters in a substring of this sequence.
deleteCharAt(int index)
StringBuffer
Removes the char at the specified position in this sequence.
ensureCapacity(int minimumCapacity)
void
Ensures that the capacity is at least equal to the specified minimum.
getChars(int srcBegin, int srcEnd, char[] dst,
void int dstBegin)
Characters are copied from this sequence into the destination character array dst.
indexOf(String str)
int Returns the index within this string of the first occurrence of the specified
substring.
indexOf(String str, int fromIndex)
int Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
insert(int offset, boolean b)
StringBuffer
Inserts the string representation of the boolean argument into this sequence.
insert(int offset, char c)
StringBuffer
Inserts the string representation of the char argument into this sequence.
insert(int offset, char[] str)
StringBuffer
Inserts the string representation of the char array argument into this sequence.
insert(int index, char[] str, int offset, int len)
StringBuffer Inserts the string representation of a subarray of the str array argument into this
sequence.
insert(int dstOffset, CharSequence s)
StringBuffer
Inserts the specified CharSequence into this sequence.
insert(int dstOffset, CharSequence s, int start,
StringBuffer int end)
Inserts a subsequence of the specified CharSequence into this sequence.
insert(int offset, double d)
StringBuffer
Inserts the string representation of the double argument into this sequence.
insert(int offset, float f)
StringBuffer
Inserts the string representation of the float argument into this sequence.
insert(int offset, int i)
StringBuffer
Inserts the string representation of the second int argument into this sequence.
insert(int offset, long l)
StringBuffer
Inserts the string representation of the long argument into this sequence.
insert(int offset, Object obj)
StringBuffer Inserts the string representation of the Object argument into this character
sequence.
insert(int offset, String str)
StringBuffer
Inserts the string into this character sequence.
lastIndexOf(String str)
int Returns the index within this string of the rightmost occurrence of the specified
substring.
lastIndexOf(String str, int fromIndex)
int Returns the index within this string of the last occurrence of the specified
substring.
length()
int
Returns the length (character count).
offsetByCodePoints(int index, int codePointOffset)
int Returns the index within this sequence that is offset from the given index by
codePointOffset code points.
replace(int start, int end, String str)
StringBuffer Replaces the characters in a substring of this sequence with characters in the
specified String.
reverse()
StringBuffer
Causes this character sequence to be replaced by the reverse of the sequence.
setCharAt(int index, char ch)
void
The character at the specified index is set to ch.
setLength(int newLength)
void
Sets the length of the character sequence.
subSequence(int start, int end)
CharSequence
Returns a new character sequence that is a subsequence of this sequence.
substring(int start)
String Returns a new String that contains a subsequence of characters currently
contained in this character sequence.
substring(int start, int end)
String Returns a new String that contains a subsequence of characters currently
contained in this sequence.
toString()
String
Returns a string representing the data in this sequence.
trimToSize()
void
Attempts to reduce storage used for the character sequence.

java.time.Period
Métodos
Modifier and Type Method and Description
Temporal addTo(Temporal temporal)
Adds this period to the specified temporal object.
static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
Obtains a Period consisting of the number of years, months, and days between two dates.
boolean equals(Object obj)
Checks if this period is equal to another period.
static Period from(TemporalAmount amount)
Obtains an instance of Period from a temporal amount.
long get(TemporalUnit unit)
Gets the value of the requested unit.
IsoChronology getChronology()
Gets the chronology of this period, which is the ISO calendar system.
int getDays()
Gets the amount of days of this period.
int getMonths()
Gets the amount of months of this period.
List<TemporalUnit> getUnits()
Gets the set of units supported by this period.
int getYears()
Gets the amount of years of this period.
int hashCode()
A hash code for this period.
boolean isNegative()
Checks if any of the three units of this period are negative.
boolean isZero()
Checks if all three units of this period are zero.
Period minus(TemporalAmount amountToSubtract)
Returns a copy of this period with the specified period subtracted.
Period minusDays(long daysToSubtract)
Returns a copy of this period with the specified days subtracted.
Period minusMonths(long monthsToSubtract)
Returns a copy of this period with the specified months subtracted.
Period minusYears(long yearsToSubtract)
Returns a copy of this period with the specified years subtracted.
Period multipliedBy(int scalar)
Returns a new instance with each element in this period multiplied by the specified scalar.
Period negated()
Returns a new instance with each amount in this period negated.
Period normalized()
Returns a copy of this period with the years and months normalized.
static Period of(int years, int months, int days)
Obtains a Period representing a number of years, months and days.
static Period ofDays(int days)
Obtains a Period representing a number of days.
static Period ofMonths(int months)
Obtains a Period representing a number of months.
static Period ofWeeks(int weeks)
Obtains a Period representing a number of weeks.
static Period ofYears(int years)
Obtains a Period representing a number of years.
static Period parse(CharSequence text)
Obtains a Period from a text string such as PnYnMnD.
Period plus(TemporalAmount amountToAdd)
Returns a copy of this period with the specified period added.
Period plusDays(long daysToAdd)
Returns a copy of this period with the specified days added.
Period plusMonths(long monthsToAdd)
Returns a copy of this period with the specified months added.
Period plusYears(long yearsToAdd)
Returns a copy of this period with the specified years added.
Temporal subtractFrom(Temporal temporal)
Subtracts this period from the specified temporal object.
String toString()
Outputs this period as a String, such as P6Y3M1D.
long toTotalMonths()
Gets the total number of months in this period.
Period withDays(int days)
Returns a copy of this period with the specified amount of days.
Period withMonths(int months)
Returns a copy of this period with the specified amount of months.
Period withYears(int years)
Returns a copy of this period with the specified amount of years.

java.time.LocalDate

Métodos

Modifier and Type Method and Description


Temporal adjustInto(Temporal temporal)
Adjusts the specified temporal object to have the same date as this object.
LocalDateTime atStartOfDay()
Combines this date with the time of midnight to create a LocalDateTime at the start
of this date.
ZonedDateTime atStartOfDay(ZoneId zone)
Returns a zoned date-time from this date at the earliest valid time according to
the rules in the time-zone.
LocalDateTime atTime(int hour, int minute)
Combines this date with a time to create a LocalDateTime.
LocalDateTime atTime(int hour, int minute, int second)
Combines this date with a time to create a LocalDateTime.
LocalDateTime atTime(int hour, int minute, int second, int nanoOfSecond)
Combines this date with a time to create a LocalDateTime.
LocalDateTime atTime(LocalTime time)
Combines this date with a time to create a LocalDateTime.
OffsetDateTime atTime(OffsetTime time)
Combines this date with an offset time to create an OffsetDateTime.
int compareTo(ChronoLocalDate other)
Compares this date to another date.
boolean equals(Object obj)
Checks if this date is equal to another date.
String format(DateTimeFormatter formatter)
Formats this date using the specified formatter.
static LocalDate from(TemporalAccessor temporal)
Obtains an instance of LocalDate from a temporal object.
int get(TemporalField field)
Gets the value of the specified field from this date as an int.
IsoChronology getChronology()
Gets the chronology of this date, which is the ISO calendar system.
int getDayOfMonth()
Gets the day-of-month field.
DayOfWeek getDayOfWeek()
Gets the day-of-week field, which is an enum DayOfWeek.
int getDayOfYear()
Gets the day-of-year field.
Era getEra()
Gets the era applicable at this date.
long getLong(TemporalField field)
Gets the value of the specified field from this date as a long.
Month getMonth()
Gets the month-of-year field using the Month enum.
int getMonthValue()
Gets the month-of-year field from 1 to 12.
int getYear()
Gets the year field.
int hashCode()
A hash code for this date.
boolean isAfter(ChronoLocalDate other)
Checks if this date is after the specified date.
boolean isBefore(ChronoLocalDate other)
Checks if this date is before the specified date.
boolean isEqual(ChronoLocalDate other)
Checks if this date is equal to the specified date.
boolean isLeapYear()
Checks if the year is a leap year, according to the ISO proleptic calendar system rules.
boolean isSupported(TemporalField field)
Checks if the specified field is supported.
boolean isSupported(TemporalUnit unit)
Checks if the specified unit is supported.
int lengthOfMonth()
Returns the length of the month represented by this date.
int lengthOfYear()
Returns the length of the year represented by this date.
LocalDate minus(long amountToSubtract, TemporalUnit unit)
Returns a copy of this date with the specified amount subtracted.
LocalDate minus(TemporalAmount amountToSubtract)
Returns a copy of this date with the specified amount subtracted.
LocalDate minusDays(long daysToSubtract)
Returns a copy of this LocalDate with the specified number of days subtracted.
LocalDate minusMonths(long monthsToSubtract)
Returns a copy of this LocalDate with the specified number of months subtracted.
LocalDate minusWeeks(long weeksToSubtract)
Returns a copy of this LocalDate with the specified number of weeks subtracted.
LocalDate minusYears(long yearsToSubtract)
Returns a copy of this LocalDate with the specified number of years subtracted.
static LocalDate now()
Obtains the current date from the system clock in the default time-zone.
static LocalDate now(Clock clock)
Obtains the current date from the specified clock.
static LocalDate now(ZoneId zone)
Obtains the current date from the system clock in the specified time-zone.
static LocalDate of(int year, int month, int dayOfMonth)
Obtains an instance of LocalDate from a year, month and day.
static LocalDate of(int year, Month month, int dayOfMonth)
Obtains an instance of LocalDate from a year, month and day.
static LocalDate ofEpochDay(long epochDay)
Obtains an instance of LocalDate from the epoch day count.
static LocalDate ofYearDay(int year, int dayOfYear)
Obtains an instance of LocalDate from a year and day-of-year.
static LocalDate parse(CharSequence text)
Obtains an instance of LocalDate from a text string such as 2007-12-03.
static LocalDate parse(CharSequence text, DateTimeFormatter formatter)
Obtains an instance of LocalDate from a text string using a specific formatter.
LocalDate plus(long amountToAdd, TemporalUnit unit)
Returns a copy of this date with the specified amount added.
LocalDate plus(TemporalAmount amountToAdd)
Returns a copy of this date with the specified amount added.
LocalDate plusDays(long daysToAdd)
Returns a copy of this LocalDate with the specified number of days added.
LocalDate plusMonths(long monthsToAdd)
Returns a copy of this LocalDate with the specified number of months added.
LocalDate plusWeeks(long weeksToAdd)
Returns a copy of this LocalDate with the specified number of weeks added.
LocalDate plusYears(long yearsToAdd)
Returns a copy of this LocalDate with the specified number of years added.
<R> R query(TemporalQuery<R> query)
Queries this date using the specified query.
ValueRange range(TemporalField field)
Gets the range of valid values for the specified field.
long toEpochDay()
Converts this date to the Epoch Day.
String toString()
Outputs this date as a String, such as 2007-12-03.
Period until(ChronoLocalDate endDateExclusive)
Calculates the period between this date and another date as a Period.
long until(Temporal endExclusive, TemporalUnit unit)
Calculates the amount of time until another date in terms of the specified unit.
LocalDate with(TemporalAdjuster adjuster)
Returns an adjusted copy of this date.
LocalDate with(TemporalField field, long newValue)
Returns a copy of this date with the specified field set to a new value.
LocalDate withDayOfMonth(int dayOfMonth)
Returns a copy of this LocalDate with the day-of-month altered.
LocalDate withDayOfYear(int dayOfYear)
Returns a copy of this LocalDate with the day-of-year altered.
LocalDate withMonth(int month)
Returns a copy of this LocalDate with the month-of-year altered.
LocalDate withYear(int year)
Returns a copy of this LocalDate with the year altered.

java.time.LocalDateTime;
Métodos
Modifier and Type Method and Description
Temporal adjustInto(Temporal temporal)
Adjusts the specified temporal object to have the same date and time as this object.
OffsetDateTime atOffset(ZoneOffset offset)
Combines this date-time with an offset to create an OffsetDateTime.
ZonedDateTime atZone(ZoneId zone)
Combines this date-time with a time-zone to create a ZonedDateTime.
int compareTo(ChronoLocalDateTime<?> other)
Compares this date-time to another date-time.
boolean equals(Object obj)
Checks if this date-time is equal to another date-time.
String format(DateTimeFormatter formatter)
Formats this date-time using the specified formatter.
static LocalDateTime from(TemporalAccessor temporal)
Obtains an instance of LocalDateTime from a temporal object.
int get(TemporalField field)
Gets the value of the specified field from this date-time as an int.
int getDayOfMonth()
Gets the day-of-month field.
DayOfWeek getDayOfWeek()
Gets the day-of-week field, which is an enum DayOfWeek.
int getDayOfYear()
Gets the day-of-year field.
int getHour()
Gets the hour-of-day field.
long getLong(TemporalField field)
Gets the value of the specified field from this date-time as a long.
int getMinute()
Gets the minute-of-hour field.
Month getMonth()
Gets the month-of-year field using the Month enum.
int getMonthValue()
Gets the month-of-year field from 1 to 12.
int getNano()
Gets the nano-of-second field.
int getSecond()
Gets the second-of-minute field.
int getYear()
Gets the year field.
int hashCode()
A hash code for this date-time.
boolean isAfter(ChronoLocalDateTime<?> other)
Checks if this date-time is after the specified date-time.
boolean isBefore(ChronoLocalDateTime<?> other)
Checks if this date-time is before the specified date-time.
boolean isEqual(ChronoLocalDateTime<?> other)
Checks if this date-time is equal to the specified date-time.
boolean isSupported(TemporalField field)
Checks if the specified field is supported.
boolean isSupported(TemporalUnit unit)
Checks if the specified unit is supported.
LocalDateTime minus(long amountToSubtract, TemporalUnit unit)
Returns a copy of this date-time with the specified amount subtracted.
LocalDateTime minus(TemporalAmount amountToSubtract)
Returns a copy of this date-time with the specified amount subtracted.
LocalDateTime minusDays(long days)
Returns a copy of this LocalDateTime with the specified number of days subtracted.
LocalDateTime minusHours(long hours)
Returns a copy of this LocalDateTime with the specified number of hours subtracted.
LocalDateTime minusMinutes(long minutes)
Returns a copy of this LocalDateTime with the specified number of
minutes subtracted.
LocalDateTime minusMonths(long months)
Returns a copy of this LocalDateTime with the specified number of
months subtracted.
LocalDateTime minusNanos(long nanos)
Returns a copy of this LocalDateTime with the specified number of
nanoseconds subtracted.
LocalDateTime minusSeconds(long seconds)
Returns a copy of this LocalDateTime with the specified number
of seconds subtracted.
LocalDateTime minusWeeks(long weeks)
Returns a copy of this LocalDateTime with the specified number of weeks subtracted.
LocalDateTime minusYears(long years)
Returns a copy of this LocalDateTime with the specified number of years subtracted.
static LocalDateTime now()
Obtains the current date-time from the system clock in the default time-zone.
static LocalDateTime now(Clock clock)
Obtains the current date-time from the specified clock.
static LocalDateTime now(ZoneId zone)
Obtains the current date-time from the system clock in the specified time-zone.
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute)
Obtains an instance of LocalDateTime from year, month, day, hour and minute,
setting the second and nanosecond to zero.
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int
Obtains an instance of LocalDateTime from year, month, day, hour, minute and
second, setting the nanosecond to zero.
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int
Obtains an instance of LocalDateTime from year, month, day, hour, minute,
second and nanosecond.
static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute)
Obtains an instance of LocalDateTime from year, month, day, hour and minute,
setting the second and nanosecond to zero.
static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, in
Obtains an instance of LocalDateTime from year, month, day, hour, minute and
second, setting the nanosecond to zero.
static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, in
Obtains an instance of LocalDateTime from year, month, day, hour, minute,
second and nanosecond.
static LocalDateTime of(LocalDate date, LocalTime time)
Obtains an instance of LocalDateTime from a date and time.
static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offse
Obtains an instance of LocalDateTime
using seconds from the epoch of 1970-01-01T00:00:00Z.
static LocalDateTime ofInstant(Instant instant, ZoneId zone)
Obtains an instance of LocalDateTime from an Instant and zone ID.
static LocalDateTime parse(CharSequence text)
Obtains an instance of LocalDateTime from a text string
such as 2007-12-03T10:15:30.
static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)
Obtains an instance of LocalDateTime from a text string using a specific formatter.
LocalDateTime plus(long amountToAdd, TemporalUnit unit)
Returns a copy of this date-time with the specified amount added.
LocalDateTime plus(TemporalAmount amountToAdd)
Returns a copy of this date-time with the specified amount added.
LocalDateTime plusDays(long days)
Returns a copy of this LocalDateTime with the specified number of days added.
LocalDateTime plusHours(long hours)
Returns a copy of this LocalDateTime with the specified number of hours added.
LocalDateTime plusMinutes(long minutes)
Returns a copy of this LocalDateTime with the specified number of minutes added.
LocalDateTime plusMonths(long months)
Returns a copy of this LocalDateTime with the specified number of months added.
LocalDateTime plusNanos(long nanos)
Returns a copy of this LocalDateTime with the specified number of
nanoseconds added.
LocalDateTime plusSeconds(long seconds)
Returns a copy of this LocalDateTime with the specified number of seconds added.
LocalDateTime plusWeeks(long weeks)
Returns a copy of this LocalDateTime with the specified number of weeks added.
LocalDateTime plusYears(long years)
Returns a copy of this LocalDateTime with the specified number of years added.
<R> R query(TemporalQuery<R> query)
Queries this date-time using the specified query.
ValueRange range(TemporalField field)
Gets the range of valid values for the specified field.
LocalDate toLocalDate()
Gets the LocalDate part of this date-time.
LocalTime toLocalTime()
Gets the LocalTime part of this date-time.
String toString()
Outputs this date-time as a String, such as 2007-12-03T10:15:30.
LocalDateTime truncatedTo(TemporalUnit unit)
Returns a copy of this LocalDateTime with the time truncated.
long until(Temporal endExclusive, TemporalUnit unit)
Calculates the amount of time until another date-time in terms of the specified unit.
LocalDateTime with(TemporalAdjuster adjuster)
Returns an adjusted copy of this date-time.
LocalDateTime with(TemporalField field, long newValue)
Returns a copy of this date-time with the specified field set to a new value.
LocalDateTime withDayOfMonth(int dayOfMonth)
Returns a copy of this LocalDateTime with the day-of-month altered.
LocalDateTime withDayOfYear(int dayOfYear)
Returns a copy of this LocalDateTime with the day-of-year altered.
LocalDateTime withHour(int hour)
Returns a copy of this LocalDateTime with the hour-of-day altered.
LocalDateTime withMinute(int minute)
Returns a copy of this LocalDateTime with the minute-of-hour altered.
LocalDateTime withMonth(int month)
Returns a copy of this LocalDateTime with the month-of-year altered.
LocalDateTime withNano(int nanoOfSecond)
Returns a copy of this LocalDateTime with the nano-of-second altered.
LocalDateTime withSecond(int second)
Returns a copy of this LocalDateTime with the second-of-minute altered.
LocalDateTime withYear(int year)
Returns a copy of this LocalDateTime with the year altered.

java.time.LocalTime
Métodos

Modifier and Type Method and Description


Temporal adjustInto(Temporal temporal)
Adjusts the specified temporal object to have the same time as this object.
LocalDateTime atDate(LocalDate date)
Combines this time with a date to create a LocalDateTime.
OffsetTime atOffset(ZoneOffset offset)
Combines this time with an offset to create an OffsetTime.
int compareTo(LocalTime other)
Compares this time to another time.
boolean equals(Object obj)
Checks if this time is equal to another time.
String format(DateTimeFormatter formatter)
Formats this time using the specified formatter.
static LocalTime from(TemporalAccessor temporal)
Obtains an instance of LocalTime from a temporal object.
int get(TemporalField field)
Gets the value of the specified field from this time as an int.
int getHour()
Gets the hour-of-day field.
long getLong(TemporalField field)
Gets the value of the specified field from this time as a long.
int getMinute()
Gets the minute-of-hour field.
int getNano()
Gets the nano-of-second field.
int getSecond()
Gets the second-of-minute field.
int hashCode()
A hash code for this time.
boolean isAfter(LocalTime other)
Checks if this time is after the specified time.
boolean isBefore(LocalTime other)
Checks if this time is before the specified time.
boolean isSupported(TemporalField field)
Checks if the specified field is supported.
boolean isSupported(TemporalUnit unit)
Checks if the specified unit is supported.
LocalTime minus(long amountToSubtract, TemporalUnit unit)
Returns a copy of this time with the specified amount subtracted.
LocalTime minus(TemporalAmount amountToSubtract)
Returns a copy of this time with the specified amount subtracted.
LocalTime minusHours(long hoursToSubtract)
Returns a copy of this LocalTime with the specified number of hours subtracted.
LocalTime minusMinutes(long minutesToSubtract)
Returns a copy of this LocalTime with the specified number of minutes subtracted.
LocalTime minusNanos(long nanosToSubtract)
Returns a copy of this LocalTime with the specified number of nanoseconds subtracted.
LocalTime minusSeconds(long secondsToSubtract)
Returns a copy of this LocalTime with the specified number of seconds subtracted.
static LocalTime now()
Obtains the current time from the system clock in the default time-zone.
static LocalTime now(Clock clock)
Obtains the current time from the specified clock.
static LocalTime now(ZoneId zone)
Obtains the current time from the system clock in the specified time-zone.
static LocalTime of(int hour, int minute)
Obtains an instance of LocalTime from an hour and minute.
static LocalTime of(int hour, int minute, int second)
Obtains an instance of LocalTime from an hour, minute and second.
static LocalTime of(int hour, int minute, int second, int nanoOfSecond)
Obtains an instance of LocalTime from an hour, minute, second and nanosecond.
static LocalTime ofNanoOfDay(long nanoOfDay)
Obtains an instance of LocalTime from a nanos-of-day value.
static LocalTime ofSecondOfDay(long secondOfDay)
Obtains an instance of LocalTime from a second-of-day value.
static LocalTime parse(CharSequence text)
Obtains an instance of LocalTime from a text string such as 10:15.
static LocalTime parse(CharSequence text, DateTimeFormatter formatter)
Obtains an instance of LocalTime from a text string using a specific formatter.
LocalTime plus(long amountToAdd, TemporalUnit unit)
Returns a copy of this time with the specified amount added.
LocalTime plus(TemporalAmount amountToAdd)
Returns a copy of this time with the specified amount added.
LocalTime plusHours(long hoursToAdd)
Returns a copy of this LocalTime with the specified number of hours added.
LocalTime plusMinutes(long minutesToAdd)
Returns a copy of this LocalTime with the specified number of minutes added.
LocalTime plusNanos(long nanosToAdd)
Returns a copy of this LocalTime with the specified number of nanoseconds added.
LocalTime plusSeconds(long secondstoAdd)
Returns a copy of this LocalTime with the specified number of seconds added.
<R> R query(TemporalQuery<R> query)
Queries this time using the specified query.
ValueRange range(TemporalField field)
Gets the range of valid values for the specified field.
long toNanoOfDay()
Extracts the time as nanos of day, from 0 to 24 * 60 * 60 * 1,000,000,000 - 1.
int toSecondOfDay()
Extracts the time as seconds of day, from 0 to 24 * 60 * 60 - 1.
String toString()
Outputs this time as a String, such as 10:15.
LocalTime truncatedTo(TemporalUnit unit)
Returns a copy of this LocalTime with the time truncated.
long until(Temporal endExclusive, TemporalUnit unit)
Calculates the amount of time until another time in terms of the specified unit.
LocalTime with(TemporalAdjuster adjuster)
Returns an adjusted copy of this time.
LocalTime with(TemporalField field, long newValue)
Returns a copy of this time with the specified field set to a new value.
LocalTime withHour(int hour)
Returns a copy of this LocalTime with the hour-of-day altered.
LocalTime withMinute(int minute)
Returns a copy of this LocalTime with the minute-of-hour altered.
LocalTime withNano(int nanoOfSecond)
Returns a copy of this LocalTime with the nano-of-second altered.
LocalTime withSecond(int second)
Returns a copy of this LocalTime with the second-of-minute altered.

Interfaces Lambdas

java.util.function.Consumer;

Modifier and Type Method and Description


void accept(T t)
Performs this operation on the given argument.
default Consumer<T> andThen(Consumer<? super T> after)
Returns a composed Consumer that performs, in sequence,
this operation followed by the after operation.
java.util.function.Function;
Modifier and Type Method and Description
default <V> Function<T,V> andThen(Function<? super R,? extends V> after)
Returns a composed function that first applies this function
to its input, and then applies the after function to the result.
R apply(T t)
Applies this function to the given argument.
default <V> Function<V,R> compose(Function<? super V,? extends T> before)
Returns a composed function that first applies the before function
to its input, and then applies this function to the result.
static <T> Function<T,T> identity()
Returns a function that always returns its input argument.

java.util.function.Predicate;

Modifier and Type Method and Description


default Predicate<T> and(Predicate<? super T> other)
Returns a composed predicate that represents a short-circuiting logical
AND of this predicate and another.
static <T> Predicate<T> isEqual(Object targetRef)
Returns a predicate that tests if two arguments are equal according to
Objects.equals(Object, Object).
default Predicate<T> negate()
Returns a predicate that represents the logical negation of this predicate.
default Predicate<T> or(Predicate<? super T> other)
Returns a composed predicate that represents a short-circuiting logical
OR of this predicate and another.
boolean test(T t)
Evaluates this predicate on the given argument.

java.util.function.Supplier;

Modifier and Type Method and Description


T get()
Gets a result.

Main.java
public class Main {
public static void main(String ... args){
main("private", args);
}
private static void main(String tipo, String[] args){
System.out.println(args[0]+" : "+args[1]);
}
}
//Compila y se ejecuta sin problemas

Main.java
public class Main{
public static void main(String[] args) {
Integer enteroWrapper = 2;
byte wrapperToByte = enteroWrapper.byteValue();
short wrapperToShort = enteroWrapper.shortValue();
int wrapperToInt = enteroWrapper.intValue();
long wrapperToLong = enteroWrapper.longValue();
float wrapperToFloat = enteroWrapper.floatValue();
double wrapperToDouble = enteroWrapper.doubleValue();
//No existe metodos para char y boolean

String wrapperToString = enteroWrapper.toString();

System.out.println("Integer:"+enteroWrapper);
System.out.println("byte:"+wrapperToByte);
System.out.println("short:"+wrapperToShort);
System.out.println("int:"+wrapperToInt);
System.out.println("long:"+wrapperToLong);
System.out.println("float:"+wrapperToFloat);
System.out.println("double:"+wrapperToDouble);
System.out.println("String:"+wrapperToString);

}
}

Main.java
public class Main{
public static void main(String[] args) {
//byte = 1 byte = 8 bits
byte b1 = 12;
byte b2 = new Byte(b1);
byte b3 = new Byte("7");
Byte b4 = 1;
Byte b5;
//b5 = new Byte(2);// no existe Byte(int)
b5 = new Byte((byte)2);//Cast permitido
//Constructores Byte: new Byte(byte) , new Byte(String)

//short = 2 bytes = 16 bits


short s1 = 3;
short s2 = new Short((short)3);//Se hace el Cast de int a short
Short s3 = new Short("2");
Short s4 = s1;
//Constructores de Short: new Short(short), new Short(String)

//int = 4 bytes = 32 bits


int int1 = 12;
int int2 =(int) 10000L;
Integer int3 = int1;
Integer int4 = new Integer("12");
Integer int5 = new Integer(int1);
Integer int6 = Integer.parseInt(new String("123"));
//Constructores de Integer: new Integer(int), new Integer(String)

//long = 8 bytes = 64 bits


long l1 = 10000L;
long l2 = new Long(50000);
Long l3 = l1;
long l4 = new Long("25000");
Long l5 = new Long(l2);
//Constructores de Long: new Long(long), new Long(String)

//float = 4 bytes = 32 bits


float f1 = 9f;
float f2 = 34.0F;
float f3 = (float)0.01D;
float f4 = new Float(f1);
Float f5 = new Float("12.0F");
Float f6 = new Float("1.0f");
float f7 = new Float(120.0D);
//Constructores de Float: new Float(float), new Float(String), new Float(double)

//double = 8 bytes = 64 bits


double d1 = 12.8D;
double d2 = 12.99;
double d3 = new Double("120.00D");
Double d4 = d1;
Double d5 = new Double(d2);
//Constructores de Double: new Double(double), new Double(String)

//char ('\u0000')
char c1 = '\u0000';
char c2 = '\u039A';
char c3 = 'x';
//Esto no se puede:
//char c4 = 'ABGGGG';//no se puede asignar este valor a char
char c5 = new Character('\u049A');
Character c6 = new Character(c1);
//Constructores de Character: new Character(char)
//boolean (true o false)
Boolean v1 = true;
Boolean v2 = "FER".length()==3;
boolean v3 = false;
boolean v4 = new Boolean("true");
boolean v5 = new Boolean(false);
//Constructores de Boolean: new Boolean(boolean), new Boolean(String)

String str1 = "null";


String str2 = new String("null");
String str3 = new String(str1);
char[] letras = {'F','E','R'};
String str4 = new String(letras);
String str5 = new String();
String str6 = new String(new StringBuilder("Algo"));
String str7 = new String(new StringBuffer("Nada"));
String str8 = String.valueOf("1220");
StringBuilder builderToString = new StringBuilder("Genesis");
String str9 = builderToString.toString();
CharSequence secuencia = "A_B_C";
StringBuffer bufferToString = new StringBuffer(secuencia);
String str10 = bufferToString.toString();
//Algunos constructores de String: new String(), new String(String), new String(char[]),
new String(StringBuilder), new String(StringBuffer)

StringBuilder stb1 = new StringBuilder();//la capacidad original es de 16


System.out.println(stb1.capacity());//16
StringBuilder stb2 = new StringBuilder("Fernando");
StringBuilder stb3 = new StringBuilder(10);
CharSequence charSequence = "Secuencia";
StringBuilder stb4 = new StringBuilder(charSequence);
//Constructores de StringBuilder: new StringBuilder(),new
StringBuilder(CharSequence),new StringBuilder(int), new StringBuilder(String)

StringBuffer stf1 = new StringBuffer();//la capacidad original es de 16


System.out.println(stf1.capacity());//16
StringBuffer stf2 = new StringBuffer(charSequence);
StringBuffer stf3 = new StringBuffer("Fernando");
StringBuffer stf4 = new StringBuffer(8);//la capacidad original es de 16
//Constructores de StringBuffer: new StringBuffer(),new
StringBuffer(CharSequence),new StringBuffer(int),new StringBuffer(String),

}
}

Main.java
public class Main{
public static void main(String[] args) {
String str1 = "null";
String str2 = "null";
System.out.println(str2.equalsIgnoreCase(str1));//true

if(str1 == str2){
System.out.println("str1 == str2");//str1 == str2
}

if(str2.equals(str1)){
System.out.println("str2.equals(str1)");//str2.equals(str1)
}

if(str1.equals(str2)){
System.out.println("str1.equals(str2)");//str1.equals(str2)
}
}
}

java.lang.Object

Constructor
Constructor and Description
Object()

Métodos

Modifier and
Method and Description
Type
protected clone()
Object Creates and returns a copy of this object.
equals(Object obj)
boolean
Indicates whether some other object is "equal to" this one.
finalize()
protected
void Called by the garbage collector on an object when garbage collection determines
that there are no more references to the object.
getClass()
Class<?>
Returns the runtime class of this Object.
hashCode()
int
Returns a hash code value for the object.
notify()
void
Wakes up a single thread that is waiting on this object's monitor.
notifyAll()
void
Wakes up all threads that are waiting on this object's monitor.
String toString()
Returns a string representation of the object.
wait()
void Causes the current thread to wait until another thread invokes the notify()
method or the notifyAll() method for this object.
wait(long timeout)
Causes the current thread to wait until either another thread invokes the notify()
void
method or the notifyAll() method for this object, or a specified amount of time
has elapsed.
wait(long timeout, int nanos)
Causes the current thread to wait until another thread invokes the notify()
void
method or the notifyAll() method for this object, or some other thread
interrupts the current thread, or a certain amount of real time has elapsed.

Main.java
//No es necesario importar al paquete java.lang
import java.lang.String;
import java.lang.StringBuilder;
import java.lang.StringBuffer;
import java.lang.CharSequence;

public class Main{


public static void main(String[] args) {
CharSequence charSequence = "Jose Mari";
String str = new String();
char[] caracteres = new char[3];//0,1,2
caracteres[0]='F';
caracteres[1]='E';
caracteres[2]='R';
str = new String(caracteres);

StringBuffer sbf = new StringBuffer(charSequence);


StringBuilder stb = new StringBuilder(charSequence);

System.out.println(str);//FER
System.out.println(sbf.toString());//Jose Mari, tam=9 , indices:0,1,2,3,4,5,6,7,8
System.out.println(stb.toString());//Jose Mari, tam=9 , indices:0,1,2,3,4,5,6,7,8

str.replace("E","A");//str.replace("oldStr","newStr")
//Se imprimira FER porque String es inmutable, contrario a StringBuffer y StringBuilder
que son mutables
System.out.println(str);//FER
//podemos crear una nueva cadena
String nuevaStr = str.replace("E","A");
System.out.println(nuevaStr);//FAR
//nuevaStr = FAR : [0,1,2]
//Jose Mari : [0,1,2,3,4,5,6,7,8]
//J=0
//o=1
//s=2
//e=3
// =4
//M=5 >>> start (inicio de copia) : F
//a=6 :A
//r=7 :R
//i=8 >>> end (fin de no copia, permanece)
//Resultado = Jose FARi
//"Jose Mari".sbf.replace(5, 8, "FAR")
sbf.replace(5, 8, nuevaStr);
System.out.println(sbf.toString());

String newStr = new String("JAVA");//[0,1,2,3]


//newStr = JAVA : [0,1,2,3]
//Jose Mari : [0,1,2,3,4,5,6,7,8]
//J=0 >>> start (inicio de copia) : J
//o=1 :A
//s=2 :V
//e=3 :A
// =4 >>> end (fin de no copia, permanece)
//M=5
//a=6
//r=7
//i=8
//Resultado = JAVA Mari
//"Jose Mari".sbf.replace(0, 4, "JAVA")
stb.replace(0, 4, newStr);
System.out.println(stb.toString());

}
}

Main.java
public class Main {
public static void main(String[] args) {
String cad1 = "FER";
String cad2 = new String("FER");
System.out.println(cad1==cad2);//false
System.out.println(cad1=="FER");//true
System.out.println(cad1.equals(cad2));//true
System.out.println(cad1.equalsIgnoreCase(cad2));//true
}
}
Main.java
public class Main {
private static int $;//0
public static void main(String[] main) {
String a_b;//Correcto, pero deber tener valor asignado antes de usarse
System.out.print($);
System.out.print(a_b);//No compilará, a_b no han sido declaradas
}
}

Main.java
//No es necesario importar el paquete java.lang
import java.lang.String;
import java.lang.StringBuilder;
import java.lang.StringBuffer;

public class Main {

public static void main(String[] main) {


String s1 = "Java";
String s2 = "Java";
StringBuilder sb1 = new StringBuilder();
sb1.append("Ja").append("va");
System.out.println(s1 == s2);//true
System.out.println(s1.equals(s2));//true
System.out.println(sb1.toString() == s1);//false
System.out.println(sb1.toString().equals(s1));//true
System.out.println();
StringBuffer sf1 = new StringBuffer();
sf1.append("Ja").append("va");
System.out.println(sf1.toString() == s1);//false
System.out.println(sf1.toString() == s2);//false
System.out.println(sf1.toString().equalsIgnoreCase(s2));//true
}
}

java.lang.Math != java.math

java.lang.Math  clase del paquete java.lang


java.math  paquete

Main.java
public class Main {
public static void main(String[] main) {
System.out.print("a");
try {
System.out.print("b");
throw new IllegalArgumentException();
}catch(RuntimeException e) {
System.out.print("c");
} finally {
System.out.print("d");
}
System.out.print("e");
}
}
//Salida: abcde

Main.java
public class Main {
public static void main(String[] main) {
System.out.print("a");
try {
System.out.print("b");
throw new IllegalArgumentException();
}catch(RuntimeException e) {
System.out.print("c");
}catch(Exception e) {//Esta parte ya no se ejecuta
System.out.print("X");
}finally {
System.out.print("d");
}
System.out.print("e");
}
}
//Salida: abcde

Main.java
public class Main {
public static void main(String[] main) {
System.out.print("a");
try {
int n = (int) Integer.parseInt("22F");
System.out.println(n);
}catch(ArithmeticException ae) {//Esto no se ejecutara
System.out.print("c");
}catch(Exception e) {
System.out.print("X");
}finally {
System.out.print("d");
}
System.out.print("e");
}
}
//aXde
Main.java
public class Main {
public static void main(String[] main) {
System.out.print("a");
try {
int n = (int) Integer.parseInt("22F");
System.out.println(n);
}catch(NumberFormatException nfe) {
System.out.print("c");
}catch(Exception e) {//Esto no se ejecutara
System.out.print("X");
}finally {
System.out.print("d");
}
System.out.print("e");
}
}
//acde

Main.java
public class Main {
public static void main(String[] main) {
int x = 5, j = 0;
EXTERNA: for(int i=0; i < 3; )
DENTRO: do{
i++; x++;System.out.println("A:"+x);//6, 11
if(x > 10) break DENTRO; //11 > 10
x += 4; System.out.println("B:"+x);// 6 + 4=10
j++;
}while(j<= 2);
System.out.println("C:"+x);
}
}//Salida: 12

Excepciones personalizadas
Main.java
public class Main {
public static void main(String[] main) {
Refractor refractor = new Refractor();
//refractor.generarPDF("Almanaque Mundial de Futbol.pdf");//Error: no compilara
//Es necesario hacer un try{}catch{}
try{
refractor.generarPDF("Almanaque Mundial de Futbol.pdf");
}catch(MyException mye){
mye.printStackTrace();
}catch(Exception e){//Esto no se ejecutara
System.err.println("Ha ocurrido un error");
}
}
}

class Refractor {
public Refractor(){}

public void generarPDF(String pdf)throws MyException{


if(pdf.length() > 25){
throw new MyException("El nombre del archivo no debe extender a 10
caracteres, total:"+pdf.length());
}
System.out.println("Se esta generando un pdf de nombre:"+pdf);
}
}

class MyException extends Exception{

private static final long serialVersionUID = 1L;

public MyException(){
super();
}

public MyException(String msj){


super(msj);
}
}

//Salida:
//com.codemonkey.MyException: El nombre del archivo no debe extender a 10 caracteres, total:31
//at com.codemonkey.Refractor.generarPDF(Main.java:28)
//at com.codemonkey.Main.main(Main.java:14)

Main.java
public class Main {
public static void main(String[] main) {
Extractor extractor=null;
try{
//extractor = new Extractor();//Error, no existe construtor vacío
extractor = new Extractor("Almanaque Mundial de Rockbol.pdf");
}catch(MyException mye){
mye.printStackTrace();
}catch(Exception e){
System.err.println("Ha ocurrido una excepcion de origen desconocido");
}finally{
System.out.println("Fin del programa");
}
System.out.println("Adios!!");
}
}
//Salida:
//com.codemonkey.MyException: No se puede asignar un valor de:32
//Fin del programa
//Adios!!
// at com.codemonkey.Extractor.<init>(Main.java:29)
// at com.codemonkey.Main.main(Main.java:12)

class Extractor{
private String valor;

Extractor(String valor) throws MyException{


if(valor.length()>10){
throw new MyException("No se puede asignar un valor de:"+valor.length());
}
this.valor=valor;
}

public String getValor() {


return valor;
}

public void setValor(String valor) {


this.valor = valor;
}
}

class MyException extends Exception{

private static final long serialVersionUID = 1L;

public MyException(){
super();
}

public MyException(String msj){


super(msj);
}
}

Expresiones lambdas
Main.java
import java.util.function.Supplier;

public class Main{


public static void main(String[] args) {
Usable uso = () -> {System.out.println("Hola, mundo!");};
uso.hola();
Supplier<Integer> numeroRandomInt = () -> (int)(Math.random()*100);
System.out.println("Numero aleatorio:"+numeroRandomInt.get());
Supplier<String> numeroRandomStr = () -> "Numero aleatorio:"+ (int)
(Math.random()*100);
System.out.println(numeroRandomStr.get());

@FunctionalInterface
interface Usable{
void hola();
}
}
//Salida:
//Hola, mundo!
//Numero aleatorio:4
//Numero aleatorio:91

Main.java
import java.util.function.Function;

public class Main{


public static void main(String[] args) {
//Funciones: Reciben un argumento y devuelven un resultado
Function<Integer, Integer> suma = x -> x + 8;
System.out.println("La suma de 5 + 8: " + suma.apply(5));

Function<String, Integer> tamanioCadena = str -> str.length();


String cadena = "Lambdas tipo funciones";
System.out.println("Número de caracteres es : " + tamanioCadena.apply(cadena));
}
}
//Salida:
//La suma de 5 + 8: 13
//Número de caracteres es : 22
Main.java
import java.util.function.Predicate;

public class Main{


public static void main(String[] args) {
//Predicado: reciben un argumento y devuelven un valor logico
Predicate<String> predicate = (s) -> s.length() > 0;
//evalua si la cadena "predicado" es mayor a 0
System.out.println(predicate.test("predicado")); // true
//niega la valor de la evaulación
System.out.println(predicate.negate().test("predicado")); // false
}
}

Main.java
import java.util.function.Supplier;

public class Main{


public static void main(String[] args) {
//Proveedor: no tiene parametros de entrada, pero devuelve un resultado
Supplier<String> cadena = () -> "Ejemplo de Proveedor";
System.out.println(cadena.get());
}
}

Main.java
import java.util.function.Consumer;
import com.codemonkey.clases.Persona;

public class Main{


public static void main(String[] args) {
//Consumidor: un solo valor y no devuelve valor alguno
Consumer<Persona> persona = (p) -> System.out.println("Hola, " + p.getNombre()+"
"+p.getApellidos()+" tienes "+p.getEdad()+" años de edad ");
persona.accept(new Persona("Horacio", "Valdez",23));
}
}

Main.java
public class Main{
public static void main(String[] args) {
//Consumidor: un solo valor y no devuelve valor alguno
Operables operables = () -> System.out.println("Hola desde un metodo");
operables.mensaje();
}
}
interface Operables{
void mensaje();
}

Main.java
public class Main{
public static void main(String[] args) {
int[] numeros = {12,43,22,44,50,0,1};//tam:7, indices[0,1,2,3,4,5,6]
try{
numeros[7]=-21;
}catch(NullPointerException npe){
System.err.println("Error (NullPointerException):"+npe.getMessage());
}catch(RuntimeException re){//Esto se ejecutara
re.printStackTrace();
}catch(Exception e){
System.err.println("Error (Exception):"+e.getMessage());
}finally{
System.exit(0);
}
}
}
//Salida:
//java.lang.ArrayIndexOutOfBoundsException: 7
// at com.codemonkey.Main.main(Main.java:10)

Main.java
public class Main {
public static void main(String[] args){
int numeros[] = {2, 6, 4, -21, 9, -44, 3};
try{
numeros[7]=-32;
}catch(NumberFormatException nfe){
System.err.println("Numero con formato incorrecto");
}catch(RuntimeException re){//java.lang.ArrayIndexOutOfBoundsException es hija de
java.lang.RuntimeException
re.printStackTrace();
}catch(Exception e){
System.err.println("Ha ocurrido una excepcion de origen desconocido");
}
}
}//Salida:
//java.lang.ArrayIndexOutOfBoundsException: 7
//at com.codemonkey.Main.main(Main.java:11)
Main.java
public class Main {
public static void main(String[] main) {
Generador generador = new Generador();
try{
generador.generarPDF("/home/user/Documents/inexistente.PDF");
}catch(Exception e){
e.printStackTrace();
}
}
}
//Salida:
//java.lang.Exception: El archivo no debe superar el no. de caracteres maximo:36
//at com.codemonkey.Generador.generarPDF(Main.java:30)
//at com.codemonkey.Main.main(Main.java:10)

class Generador {
private String ruta;

public String getRuta() {


return ruta;
}

public void setRuta(String ruta) {


this.ruta = ruta;
}

public void generarPDF(String ruta) throws Exception{


if(ruta.length() > 10){
throw new Exception("El archivo no debe superar el no. de caracteres
maximo:"+ruta.length());
}
System.out.println("Generando archivo PDF...");
}

Main.java
public class Main {
public static void main(String[] main) {
Extractor extractor=null;
try{
//extractor = new Extractor();//Error, no existe construtor vacío
extractor = new Extractor("Almanaque Mundial de Rockbol.pdf");
}catch(MyException mye){
mye.printStackTrace();
}catch(Exception e){
System.err.println("Ha ocurrido una excepcion de origen desconocido");
}finally{
System.out.println("Fin del programa");
}
System.out.println("Adios!!");
}
}
//Salida:
//com.codemonkey.MyException: No se puede asignar un valor de:32
//Fin del programa
//Adios!!
// at com.codemonkey.Extractor.<init>(Main.java:29)
// at com.codemonkey.Main.main(Main.java:12)

class Extractor{
private String valor;

Extractor(String valor) throws MyException{


if(valor.length()>10){
throw new MyException("No se puede asignar un valor de:"+valor.length());
}
this.valor=valor;
}

public String getValor() {


return valor;
}

public void setValor(String valor) {


this.valor = valor;
}
}

class MyException extends Exception{

private static final long serialVersionUID = 1L;

public MyException(){
super();
}

public MyException(String msj){


super(msj);
}
}
Main.java
public class Main {
public static void main(String[] main) {
Refractor refractor = new Refractor();
//refractor.generarPDF("Almanaque Mundial de Futbol.pdf");//Error: no compilara
//Es necesario hacer un try{}catch{}
try{
refractor.generarPDF("Almanaque Mundial de Futbol.pdf");//Error, el nombre
excede 10 caracteres
}catch(MyException mye){
mye.printStackTrace();
}catch(Exception e){//Esto no se ejecutara
System.err.println("Ha ocurrido un error");
}
}
}
//Salida:
//com.codemonkey.MyException: El nombre del archivo no debe extender a 10 caracteres, total:31
//at com.codemonkey.Refractor.generarPDF(Main.java:28)
//at com.codemonkey.Main.main(Main.java:14)

class Refractor {
public Refractor(){}

public void generarPDF(String pdf)throws MyException{


if(pdf.length() > 10){
throw new MyException("El nombre del archivo no debe extender a 10
caracteres, total:"+pdf.length());
}
System.out.println("Se esta generando un pdf de nombre:"+pdf);
}
}

class MyException extends Exception{

private static final long serialVersionUID = 1L;

public MyException(){
super();
}

public MyException(String msj){


super(msj);
}
}
Main.java
import java.time.Period;

public class Main {


public static void main(String[] args){
Period per1 = Period.of(2018, 12, 365);//[años, meses, dias]
System.out.println("Dias:"+per1.getDays());//365
System.out.println("Meses:"+per1.getMonths());//12
System.out.println("Años:"+per1.getYears());//2018
System.out.println("Total de meses:"+per1.toTotalMonths());//24228
String negativo = per1.isNegative()? "si" : "no";
System.out.println("Perido es negativo?:"+negativo);//no
String cero = per1.isZero()? "si" : "no";
System.out.println("Peridodo es cero?:"+cero);//no
CharSequence charSequence= "P9Y12M34D";
per1 = Period.parse(charSequence);
System.out.println(per1.toString());//P9Y12M34D
System.out.println("De dias:"+per1.ofDays(12));//P12D
System.out.println("De semanas:"+per1.ofWeeks(333));//P2331D
System.out.println("De meses:"+per1.ofMonths(12));//P12M
System.out.println("De años:"+per1.ofYears(2017));//P2017Y
System.out.println("Negate:"+per1.negated());//P-9Y-12M-34D
System.out.println(per1.toString());//P9Y12M34D
per1 = Period.parse("P5Y6M3D");
System.out.println(per1.toString());//P5Y6M3D
per1.plusDays(2);//no cambia el valor de dias de per1
System.out.println(per1.toString());//P5Y6M3D
per1.plusDays(2);//no cambia el valor de dias de per1
System.out.println(per1.toString());//P5Y6M3D
System.out.println(per1.plusDays(2));//P5Y6M5D
System.out.println(per1.toString());//P5Y6M3D
System.out.println(per1.plusMonths(3));//P5Y9M3D
System.out.println(per1.plusYears(1));//P6Y6M3D
}
}
//Salida:
Dias:365
Meses:12
Años:2018
Total de meses:24228
Perido es negativo?:no
Peridodo es cero?:no
P9Y12M34D
De dias:P12D
De semanas:P2331D
De meses:P12M
De años:P2017Y
Negate:P-9Y-12M-34D
P9Y12M34D
P5Y6M3D
P5Y6M3D
P5Y6M3D
P5Y6M5D
P5Y6M3D
P5Y9M3D
P6Y6M3D

Main.java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class Main {


public static void main(String[] args){
LocalDate localDate = LocalDate.now();
System.out.println("Fecha de hoy:"+localDate);//2018-04-17
System.out.println("Fecha de hoy:"+localDate.toString());//2018-04-17
System.out.println("Dia del mes:"+localDate.getDayOfMonth());//17
System.out.println("Dia del año:"+localDate.getDayOfYear());//107
System.out.println("Dia de la semana:"+localDate.getDayOfWeek()
+"("+getSemana(localDate.getDayOfWeek().toString())+")");//TUESDAY(MARTES)
System.out.println("Año:"+localDate.getYear());//2018
System.out.println("Mes (valor):"+localDate.getMonthValue());//4
System.out.println("Mes:"+localDate.getMonth());//APRIL
System.out.println("Longitud del mes:"+localDate.lengthOfMonth());//30
System.out.println("Longitud del año:"+localDate.lengthOfYear());//365

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");


CharSequence charSequence = "17/04/2018";
localDate = LocalDate.parse(charSequence, formatter);
System.out.println(localDate);//2018-04-17

String fecha = "2018-04-17";


//default, ISO_LOCAL_DATE
localDate = LocalDate.parse(fecha);
System.out.println(localDate);//2018-04-17

try{
formatter = DateTimeFormatter.ofPattern("E, MMM d yyyy");
String date = "Tue, Aug 16 2016";
localDate = LocalDate.parse(date, formatter);
System.out.println(localDate);
System.out.println(formatter.format(localDate));
}catch (DateTimeParseException dte){
System.err.println("La fecha no puede ser procesada");
}

String bisiesto = localDate.isLeapYear()? "Si": "No";


System.out.println("Año bisiesto?:"+bisiesto);//No
localDate = LocalDate.now();
System.out.println("Fecha de hoy:"+localDate);//2018-04-17
System.out.println("Con dia del mes 2:"+localDate.withDayOfMonth(2));//2018-04-02
System.out.println("Con dia del año 100:"+localDate.withDayOfYear(100));//2018-04-10

static String getSemana(String cad){


String dia="";
switch(cad){
case "MONDAY": dia="LUNES"; break;
case "TUESDAY": dia="MARTES"; break;
case "WEDNESDAY": dia="MIERCOLES"; break;
case "THURSDAY": dia="JUEVES"; break;
case "FRIDAY": dia="VIERNES"; break;
case "SATURDAY": dia="SABADO"; break;
case "SUNDAY": dia="DOMINGO"; break;
default: dia="no especificado"; break;
}
return dia;
}
}

Main.java
import java.time.Period;

public class Main {


public static void main(String[] args){
Period per1 = Period.of(2018, 12, 365);//[años, meses, dias]
System.out.println("Dias:"+per1.getDays());//365
System.out.println("Meses:"+per1.getMonths());//12
System.out.println("Años:"+per1.getYears());//2018
System.out.println("Total de meses:"+per1.toTotalMonths());//24228
String negativo = per1.isNegative()? "si" : "no";
System.out.println("Perido es negativo?:"+negativo);//no
String cero = per1.isZero()? "si" : "no";
System.out.println("Peridodo es cero?:"+cero);//no
CharSequence charSequence= "P9Y12M34D";
per1 = Period.parse(charSequence);
System.out.println(per1.toString());//P9Y12M34D
System.out.println("De dias:"+per1.ofDays(12));//P12D
System.out.println("De semanas:"+per1.ofWeeks(333));//P2331D
System.out.println("De meses:"+per1.ofMonths(12));//P12M
System.out.println("De años:"+per1.ofYears(2017));//P2017Y
System.out.println("Negate:"+per1.negated());//P-9Y-12M-34D
System.out.println(per1.toString());//P9Y12M34D
per1 = Period.parse("P5Y6M3D");
System.out.println(per1.toString());//P5Y6M3D
per1.plusDays(2);//no cambia el valor de dias de per1
System.out.println(per1.toString());//P5Y6M3D
per1.plusDays(2);//no cambia el valor de dias de per1
System.out.println(per1.toString());//P5Y6M3D
System.out.println(per1.plusDays(2));//P5Y6M5D
System.out.println(per1.toString());//P5Y6M3D
System.out.println(per1.plusMonths(3));//P5Y9M3D
System.out.println(per1.plusYears(1));//P6Y6M3D
}
}

Main.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main{


public static void main(String[] args){
//Consumers
List<String> nombres = Arrays.asList("Fernando", "Gabriel", "Antonio");
nombres.forEach(nombre -> System.out.println("Hola, " + nombre));
Map<String, Integer> edades = new HashMap<>();
edades.put("Fernando", 25);
edades.put("Gabriel", 24);
edades.put("Antonio", 30);
edades.forEach((nombre, edad) -> System.out.println(nombre + " tiene " + edad + " años
de edad"));

//Predicates
List<String> names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
List<String> namesWithA = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
System.out.println("Nombres que inician con A:"+namesWithA.toString());

//Operadores
List<String> namess = Arrays.asList("bob", "josh", "megan");
namess.replaceAll(name -> name.toUpperCase());
namess.replaceAll(String::toUpperCase);//Forma mas corta
System.out.println(namess.toString());

List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);


int sum = values.stream()
.reduce(0, (i1, i2) -> i1 + i2);
System.out.println("Suma:"+sum);
}
}

Main.java
public class Main{
public static void main(String ... args){
FooExtended fooExtended = () -> "Hola, mundo!";
System.out.println(fooExtended.method());//Hola, mundo!
fooExtended.defaultBar();//Hola desde Bar
fooExtended.defaultBaz();//Hola desde Baz
}
}

@FunctionalInterface
interface FooExtended extends Baz, Bar {}

@FunctionalInterface
interface Baz {
String method();
default void defaultBaz() {
System.out.println("Hola desde Baz");
}
}

@FunctionalInterface
interface Bar {
String method();
default void defaultBar() {
System.out.println("Hola desde Bar");
}
}

Predicates
Main.java
import com.codemonkey.clases.Empleado;
import static com.codemonkey.clases.EmpleadoPredicate.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main{
public static final int TAM = 4;
public static void main(String[] args){
Empleado[] empleados = new Empleado[TAM];//[0,1,2,3]
empleados[0] = new Empleado(1, "Tomas",
"Alcantara", 22, "futbol",
"Ingeniero", 10, 20000);
empleados[1] = new Empleado(2, "Alejandra",
"Sanchez", 33, "lectura",
"Contadora", 10, 15000);
empleados[2] = new Empleado(3, "Paola",
"Mercado", 26, "cocinar",
"Ingeniero", 10, 24000);
empleados[3] = new Empleado(4, "Mario",
"Molina", 22, "futbol",
"quimico", 45, 30000);

List<Empleado> employees = new ArrayList<Empleado>();


employees.addAll(Arrays.asList(empleados));

System.out.println(filterEmpleado(employees, isIngeniero()));
System.out.println(filterEmpleado(employees, mayor20000()));
System.out.println(filterEmpleado(employees, menor20000()));

Empleado.java
package com.codemonkey.clases;

public class Empleado extends Persona {

private String puesto;


private int horas;
private double salario;

public Empleado(){}

public Empleado(int id, String nombre,


String apellidos, int edad, String aficiones,
String puesto, int horas, double salario) {
super(id, nombre,apellidos, edad, aficiones);
this.puesto = puesto;
this.horas = horas;
this.salario = salario;
}

public Empleado(String puesto, int horas, double salario) {


super();
this.puesto = puesto;
this.horas = horas;
this.salario = salario;
}

public Empleado(String puesto){


this(puesto, 0, 0.0);
}

public Empleado(int horas){


this("",horas, 0.0);
}

public Empleado(double salario){


this("", 0, salario);
}

public String getPuesto() {


return puesto;
}

public void setPuesto(String puesto) {


this.puesto = puesto;
}

public int getHoras() {


return horas;
}

public void setHoras(int horas) {


this.horas = horas;
}

public double getSalario() {


return salario;
}

public void setSalario(double salario) {


this.salario = salario;
}

@Override
public String toString() {
return super.toString()+"::Empleado [puesto=" + puesto + ", horas=" + horas + ",
salario=" + salario + "]";
}

EmpleadoPredicate.java
package com.codemonkey.clases;

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class EmpleadoPredicate {

public static Predicate<Empleado> isIngeniero() {


return p -> p.getPuesto().equalsIgnoreCase("Ingeniero");
}

public static Predicate<Empleado> mayor20000(){


return p -> p.getSalario() > 20000;
}

public static Predicate<Empleado> menor20000(){


return p -> p.getSalario() < 20000;
}

public static List<Empleado> filterEmpleado (List<Empleado> empleado,


Predicate<Empleado> predicate) {
return empleado.stream().filter( predicate ).collect(Collectors.<Empleado>toList());
}
}

Main.java
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main{


public static void main(String[] args){
LocalDate localDate = LocalDate.now();
System.out.println(localDate.toString()); //
System.out.println(localDate.getDayOfWeek().toString()); //
System.out.println(localDate.getDayOfMonth()); //
System.out.println(localDate.getDayOfYear()); //
System.out.println(localDate.isLeapYear()); //
System.out.println(localDate.plusDays(12).toString()); //

//LocalTime localTime = LocalTime.now(); //


LocalTime localTime = LocalTime.of(12, 20);
System.out.println(localTime.toString()); //
System.out.println(localTime.getHour()); //
System.out.println(localTime.getMinute()); //
System.out.println(localTime.getSecond()); //
System.out.println(localTime.MIDNIGHT); //
System.out.println(localTime.NOON); //

LocalDateTime localDateTime = LocalDateTime.now();


System.out.println(localDateTime.toString()); //
System.out.println(localDateTime.getDayOfMonth()); //
System.out.println(localDateTime.getHour()); //
System.out.println(localDateTime.getNano()); //

OffsetDateTime offsetDateTime = OffsetDateTime.now();


System.out.println(offsetDateTime.toString()); //

offsetDateTime = OffsetDateTime.now(ZoneId.of("+05:30"));
System.out.println(offsetDateTime.toString()); //

offsetDateTime = OffsetDateTime.now(ZoneId.of("-06:30"));
System.out.println(offsetDateTime.toString()); //

ZonedDateTime zonedDateTime =
ZonedDateTime.now(ZoneId.of("Europe/Paris"));
System.out.println(zonedDateTime.toString()); //

}
}

Main.java
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.function.Function;
import java.util.function.Predicate;
import com.codemonkey.clases.Empleado;

public class Main{


public static void main(String[] args){
//Consumidor: un solo valor y no devuelve valor alguno
Consumer<Empleado> consumerEmp = emp -> System.out.println(emp.toString());
Empleado empleado = new Empleado("Programador", 10, 120000.00);
empleado.setId(1);
empleado.setNombre("Mario");
empleado.setApellidos("Sanchez Lopez");
empleado.setEdad(33);
empleado.setAficiones("Lectura");
consumerEmp.accept(empleado);

//Proveedor: no tiene parametros de entrada, pero devuelve un resultado


Supplier<Empleado> empSupplier = () -> new Empleado(2, "Armand","Weller", 36,
"Natacion","Analista", 12, 22000);
System.out.println(empSupplier.get());

//Predicado: reciben un argumento y devuelven un valor logico


Predicate<Empleado> empPredicate = emp ->
emp.getPuesto().equalsIgnoreCase("Ingeniero");
if(empPredicate.test(new Empleado(3, "Julio","Matosa", 45, "Ver TV","Ingeniero", 10,
24000))){
System.out.println("Hola, ingeniero!!");
}

//Funciones: Reciben un argumento y devuelven un resultado


Function<Empleado, String> empFunction= (Empleado e)-> {return
e.getNombre().concat(" "+e.getApellidos());};
System.out.println(empFunction.apply(new Empleado(2, "Armand","Weller", 36,
"Natacion","Analista", 12, 22000)));

}
}

Main.java
//Ejemplo de múltiples cath
import static java.lang.System.out;
import static java.lang.System.err;

import java.io.FileNotFoundException;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;

public class Main{


public static void main(String[] args) {
int division=0;
out.println("Excepciones:");
try{
division =3/0;
}catch(ArithmeticException | NullPointerException e1){
err.println("Causa:"+e1.getCause()+" - Mensaje:"+e1.getMessage());
e1.printStackTrace();
}
try{
division = 4/0;
}catch(NullPointerException | ArithmeticException e2){
err.println("Causa:"+e2.getCause()+" - Mensaje:"+e2.getMessage());
e2.printStackTrace();
}

int[] vector = new int[2];//tam=2, indices [0,1]


try{
vector[0]= 2;
vector[1]= 4;
vector[2]= 5;
}catch(ArrayIndexOutOfBoundsException | NullPointerException e3){
err.println("Causa:"+e3.getCause()+" - Mensaje:"+e3.getMessage());
e3.printStackTrace();
}

try{
vector[0]= 10;
vector[1]= 8;
vector[2]= 2;
}catch(NullPointerException | ArrayIndexOutOfBoundsException e4){
err.println("Causa:"+e4.getCause()+" - Mensaje:"+e4.getMessage());
e4.printStackTrace();
}

File file = new File("/home/fer/Documents/noExiste.dat");


BufferedReader br = null;
try{
FileReader fr = new FileReader(file);
br = new BufferedReader(fr);
String cad;
while((cad=br.readLine())!=null){
out.println(cad);
}
br.close();
}catch(java.io.IOException | NullPointerException e5){
err.println("Error leyendo el archivo:");
e5.printStackTrace();
}
try {
java.io.LineNumberReader lineReader = new java.io.LineNumberReader(new
FileReader("/home/fer/Documents/noExiste.dat"));
String line = lineReader.readLine();
lineReader.close();
out.println(line);
}catch (FileNotFoundException fne) {
err.println("Archivo no existente");//Esto se ejecutará
}catch (java.io.IOException ioe) {
err.println("Error leyendo el archivo");
}catch(Exception ex){
err.println("Ha ocurrido una excepcion");
}

}
}
//Salida:
Excepciones:
Causa:null - Mensaje:/ by zero
java.lang.ArithmeticException: / by zero
at com.codemonkey.Main.main(Main.java:25)
Causa:null - Mensaje:/ by zero
java.lang.ArithmeticException: / by zero
at com.codemonkey.Main.main(Main.java:31)
Causa:null - Mensaje:2
java.lang.ArrayIndexOutOfBoundsException: 2
at com.codemonkey.Main.main(Main.java:41)
Causa:null - Mensaje:2
java.lang.ArrayIndexOutOfBoundsException: 2
at com.codemonkey.Main.main(Main.java:50)
Error leyendo el archivo:
java.io.FileNotFoundException: /home/fer/Documents/noExiste.dat (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:196)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:139)
at java.base/java.io.FileReader.<init>(FileReader.java:72)
at com.codemonkey.Main.main(Main.java:59)
Archivo no existente

Main.java
import static java.lang.System.out;
import static java.lang.System.err;

public class Main{


public static void main(String[] args) {
String cadena = null;
CharSequence charSequence = "Godofredo";
try{
cadena += " "+cadena.concat(" "+new String(new
StringBuilder(charSequence)));
}catch(ArrayIndexOutOfBoundsException | NullPointerException npe){
err.println("Error, se trata de operar con un objeto null");
npe.printStackTrace();
}

String[] cadenas = {"Alpha", "Beta", "Gamma","Omega"};


try{
for(int i=0; i < 5; i++){
out.println(cadenas[i]);
}
}catch(ArrayIndexOutOfBoundsException | IllegalArgumentException ex){
err.println("Ha ocurrido una excepcion de tipo
ArrayIndexOutOfBoundsException");
ex.printStackTrace();
}
}
}
//Salida:
//Error, se trata de operar con un objeto null
//java.lang.NullPointerException
// at com.codemonkey.Main.main(Main.java:17)
//Alpha
//Beta
//Gamma
//Omega
//Ha ocurrido una excepcion de tipo ArrayIndexOutOfBoundsException
//java.lang.ArrayIndexOutOfBoundsException: 4
// at com.codemonkey.Main.main(Main.java:26)

Main.java
import static java.lang.System.out;
import static java.lang.System.err;

public class Main{


public static void main(String[] args) {
String archivo = null;
GeneradorPDF generadorPDF = null;
try{
generadorPDF = new GeneradorPDF();
generadorPDF.setArchivo(archivo);
generadorPDF.generadorPDF();
}catch(NullPointerException | MyExcepcionA ex){
err.println("Ha ocurrido una excepcion");
ex.printStackTrace();
}
}
}

class MyExcepcionA extends Exception{

MyExcepcionA(){
super();
}

MyExcepcionA(String msg){
super(msg);
}

class GeneradorPDF{
private String archivo;

protected GeneradorPDF(){}

GeneradorPDF(String archivo){
this.archivo=archivo;
}

public String getArchivo(){


return archivo;
}

public void setArchivo(String archivo){


this.archivo=archivo;
}

public void generadorPDF() throws MyExcepcionA{


String miArchivo = this.getArchivo();
if(miArchivo == null){
throw new MyExcepcionA("El archivo que tratas de crear es null");
}
out.println("Generando archivo PDF \""+miArchivo+"\".pdf");
}

}
//Salida:
Ha ocurrido una excepcion
com.codemonkey.MyExcepcionA: El archivo que tratas de crear es null
at com.codemonkey.GeneradorPDF.generadorPDF(Main.java:61)
at com.codemonkey.Main.main(Main.java:20)

Main.java
import static java.lang.System.out;
import static java.lang.System.err;

public class Main{

static public void main(String $[]){


Object obj1 = "1";
Object obj2 = new String("null");
Object obj3 = null;
Object obj4 = 0;//int, Integer, short, Short
Object obj5 = '\u009e';//char, Character
Object obj6 = 78.0F;//float, Float
Object obj7 = new Boolean("true");//boolean, Boolean
Object obj8 = 127;//byte , Byte
Object obj9 = 120000L;//long, Long
Object obj10 = 123.000000;//double, Double

tryEntero(obj1);
tryEntero(obj4);
tryString(obj1);
tryString(obj2);
tryString(obj3);

static void tryString(Object obj){


try{
String string = (String) obj;
out.println("String:"+string);
}catch(ClassCastException | NullPointerException e2){
err.println("Excepcion ocurrida por:"+e2.getCause());
e2.printStackTrace();
}
}

static void tryEntero(Object obj){


try{
Integer entero = (Integer) obj;
out.println("Entero:"+entero);
}catch(ClassCastException | NumberFormatException e1){
err.println("Excepcion ocurrida por:"+e1.getCause());
e1.printStackTrace();
}
}
}
//Salida:
//Excepcion ocurrida por:null
//java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
// at com.codemonkey.Main.tryEntero(Main.java:32)
// at com.codemonkey.Main.main(Main.java:24)
//Entero:0
//String:1
//String:null
//String:null

Main.java
import static java.lang.System.out;
import static java.lang.System.err;

import java.util.Random;

public class Main{

static public void main(String $[]){


Main.tryRandom();
}

protected static void tryRandom(){


try{
Random random = new Random();
int n = random.nextInt(3);
if(n == 0){
throw new ArrayIndexOutOfBoundsException();
}else{
throw new NullPointerException();
}
}catch(ArrayIndexOutOfBoundsException | NullPointerException e){
err.println("Ha ocurrido una excepcion:"+e.getMessage());
e.printStackTrace();
}
}
}
//Salida:
//Ha ocurrido una excepcion:null
//java.lang.ArrayIndexOutOfBoundsException
// at com.codemonkey.Main.tryRandom(Main.java:22)
// at com.codemonkey.Main.main(Main.java:14)

//7
Main.java
import static java.lang.System.out;
import static java.lang.System.err;
import static java.lang.System.in;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main{

static public void main(String $[]){


Main.tryScanner();
}

protected static void tryScanner(){


try(Scanner sc = new Scanner(in)){
out.println("Numero del mes del año:");
int numero=sc.nextInt();
out.println("Faltan "+(12-numero)+" para que termine el año");
}catch(InputMismatchException ime){
err.println("Una excepcion en la entrada de datos:"+ime.getCause());
ime.printStackTrace();
}
}
}

//6
Main.java
import static java.lang.System.out;

public class Main{

static public void main(String $[]){


new Main().tryTestA();
Main.tryTestB();
}

public void tryTestA(){


try{
out.println("Hi!");
}finally{
out.println("Ciao!");
}
}

public static void tryTestB(){


out.println("A");
try{
out.println("B");
new NumberFormatException();
out.println("C");
}finally{
out.println("D");
}
out.println("E");
}

}
//Salida:
//Hi!
//Ciao!
//A
//B
//C
//D
//E

//5
Main.java
import static java.lang.System.out;
import static java.lang.System.err;
import static java.lang.System.exit;
import java.util.ArrayList;

public class Main{

static public void main(String $[]){


Main.tryEsEntero();//tambien puede ser asi: tryEsEntero()
tryCatchClassCast();
Main.tryArrayIndex();
tryTestA();//Formato del numero incorrecto
tryTestB();//El argumento no es valido
Main.tryTestC();//Hola
}

public static void tryEsEntero(){


try{
int numero = Integer.parseInt("223R");
}catch(NumberFormatException nfe){
err.println("Hay un problema con el formato del numero:"+nfe.getMessage());
nfe.printStackTrace();
}catch(IllegalArgumentException iae){
err.println("Hay un problema:"+iae.getMessage());
iae.printStackTrace();
}
catch(RuntimeException re){
err.println("Hay un problema:"+re.getMessage());
re.printStackTrace();
}
catch(Exception e){
err.println("Hay un problema:"+e.getMessage());
e.printStackTrace();
}
}

public static void tryCatchClassCast(){


ArrayList listaEnteros = new ArrayList();
listaEnteros.add(0,"21");
listaEnteros.add(1,"33");
listaEnteros.add(2,"111");
try{
Integer entero = (Integer)listaEnteros.get(1);
}catch(ClassCastException cce){
err.println("Ha ocurrido una excepcion con el \"casteo\":"+cce.getMessage());
cce.printStackTrace();
}catch(IllegalArgumentException iae){
err.println("Ha ocurrido una excepcion:"+iae.getMessage());
iae.printStackTrace();
}
catch(RuntimeException re){
err.println("Ha ocurrido una excepcion:"+re.getMessage());
re.printStackTrace();
}catch(Exception e){
err.println("Ha ocurrido una excepcion:"+e.getMessage());
e.printStackTrace();
}
}

public static void tryArrayIndex(){


int[] arreglo [] = {{2,5,4},{0,-3,-3},{-1,7,-3}};
try{
int entero = arreglo[0][3];
}catch(ArrayIndexOutOfBoundsException aie){
err.println("Tratas de acceder a un indice inexistente:"+aie.getMessage());
aie.printStackTrace();
}catch(NumberFormatException nfe){
err.println("El numero no tiene formato correcto:"+nfe.getMessage());
nfe.printStackTrace();
}catch(IllegalArgumentException iae){
err.println("El argumento es incorrecto:"+iae.getMessage());
iae.printStackTrace();
}catch(RuntimeException re){
err.println("Excepcion en tiempo de ejecucion:"+re.getMessage());
re.printStackTrace();
}
}
public static void tryTestA(){
try{
throw new NumberFormatException();
}catch(NumberFormatException nfe){
err.println("Formato del numero incorrecto");
}
}

public static void tryTestB(){


try{
throw new IllegalArgumentException();
}catch(IllegalArgumentException iae){
err.println("El argumento no es valido");
}
}

public static void tryTestC(){


try{
out.println("Hola");
exit(0);//El programa termina, ya no se ejecuta ninguna otra sentencia
}finally{
out.println("Adios");
}
}

//Salida:
//Hay un problema con el formato del numero:For input string: "223R"
//java.lang.NumberFormatException: For input string: "223R"
// at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
// at java.lang.Integer.parseInt(Integer.java:580)
// at java.lang.Integer.parseInt(Integer.java:615)
// at com.codemonkey.Main.tryEsEntero(Main.java:23)
// at com.codemonkey.Main.main(Main.java:14)
//Ha ocurrido una excepcion con el "casteo":java.lang.String cannot be cast to java.lang.Integer
//java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
// at com.codemonkey.Main.tryCatchClassCast(Main.java:47)
// at com.codemonkey.Main.main(Main.java:15)
//Tratas de acceder a un indice inexistente:3
//java.lang.ArrayIndexOutOfBoundsException: 3
// at com.codemonkey.Main.tryArrayIndex(Main.java:67)
// at com.codemonkey.Main.main(Main.java:16)
//Formato del numero incorrecto
//El argumento no es valido
//Hola

//4
Main.java
import static java.lang.System.out;
import static java.lang.System.err;

public class Main{

static public void main(String $[]){


String archivo = "archivo.xml";
GeneradorPDF generadorPDFA = new GeneradorPDF();
try{
generadorPDFA.setArchivo(archivo);
generadorPDFA.generadorPDF();
}catch(MyExcepcionA | NullPointerException e1){
err.println("Ha ocurrido una excepcion de tipo:"+e1.getCause());
e1.printStackTrace();
}

String doc = "documento.docx";


GeneradorXML generadorXML = new GeneradorXML();
try{
generadorXML.GeneradorXML(doc);
}catch(MyExcepcionB | ArrayIndexOutOfBoundsException e2){
err.println("Ha ocurrido una excepcion generando XML, causa:"+e2.getCause());
e2.printStackTrace();
}
}

}
//Salida:
//GeneradorPDF
//Generando PDF...
//Ha ocurrido una excepcion generando XML, causa:null
//com.codemonkey.MyExcepcionB: El archivo no debe tener extension *.docx
// at com.codemonkey.GeneradorXML.GeneradorXML(Main.java:66)
// at com.codemonkey.Main.main(Main.java:24)

class GeneradorPDF {
private String archivo;

GeneradorPDF(){
out.println("GeneradorPDF");
}

GeneradorPDF(String archivo){
super();
this.archivo=archivo;
}

public String getArchivo(){


return archivo;
}

public void setArchivo(String archivo){


this.archivo=archivo;
}

public void generadorPDF() throws MyExcepcionA{


if(this.archivo == null){
throw new MyExcepcionA("El archivo no puede ser null");
}
out.println("Generando PDF...");
}
}

class GeneradorXML {
void GeneradorXML(String nombre)throws MyExcepcionB{
if(nombre.endsWith(".docx")){
throw new MyExcepcionB("El archivo no debe tener extension *.docx");
}
out.println("Generando XML...");
}
}

class MyExcepcionA extends Exception{


public MyExcepcionA(){
super();
}

public MyExcepcionA(String msg){


super(msg);
}
}

class MyExcepcionB extends Exception{


public MyExcepcionB(){
super();
}

public MyExcepcionB(String msg){


super(msg);
}
}

//3
Main.java
import static java.lang.System.out;
import static java.lang.System.err;

public class Main{

static public void main(String $[]){


String archivo = null;
GeneradorPDF generadorPDFA = new GeneradorPDF();
try{
generadorPDFA.setArchivo(archivo);
generadorPDFA.generadorPDF();
}catch(MyExcepcionA | NullPointerException e1){
err.println("Ha ocurrido una excepcion de tipo:"+e1.getCause());
e1.printStackTrace();
}
}

}
//Salida:
//GeneradorPDF
//Ha ocurrido una excepcion de tipo:null
//com.codemonkey.MyExcepcionA: El archivo no puede ser null
// at com.codemonkey.GeneradorPDF.generadorPDF(Main.java:47)
// at com.codemonkey.Main.main(Main.java:16)

class GeneradorPDF {
private String archivo;

GeneradorPDF(){
out.println("GeneradorPDF");
}

GeneradorPDF(String archivo){
super();
this.archivo=archivo;
}

public String getArchivo(){


return archivo;
}

public void setArchivo(String archivo){


this.archivo=archivo;
}

public void generadorPDF() throws MyExcepcionA{


if(this.archivo == null){
throw new MyExcepcionA("El archivo no puede ser null");
}
}

class MyExcepcionA extends Exception{


public MyExcepcionA(){
super();
}

public MyExcepcionA(String msg){


super(msg);
}
}

//2
Main.java
import static java.lang.System.out;

public class Main{


static int c, a=10, b=21/2; //10
static{
c=a;
}

//Correcto:
static public void main(String $[]){
out.println(b);
}

//Correcto:
//static public void main(String... $){
// out.println(b);
//}

//Correcto:
//public static void main(String ... args){
// out.println(b);
//}

//Correcto:
//public static void main(String[] args){
// out.println(b);
//}
}
//Salida:
//10
Main.java
import static java.lang.System.out;

public class Main{


public static void main(String[] args){
FinalClass finalClass = new FinalClass();
finalClass.metodoFinal();//Hola, desde FinalClass

XClass xClass = new XClass();


xClass.saludar();//Hola, desde XClass

Object pClass = new PClass();//Hola, desde PClass


QClass qClass = new QClass();//Hola, desde PClass
//RClass rClass = new RClass();//No compilará, se crea un ciclo

}
}

final class FinalClass {


final void metodoFinal(){
out.println("Hola, desde FinalClass");
}
}

abstract class AbstractClass {


abstract void saludar();
}

class XClass extends AbstractClass {


@Override
public void saludar(){
out.println("Hola, desde XClass");
}
}

class PClass extends Object{


PClass(){
this("Hola, desde PClass");//Invoca al constructor PClass(String msg)
}

PClass(String msg){
out.println(msg);
}
}

class QClass extends PClass{}

//Error: se creara un ciclo


class RClass extends RClass{
protected RClass(){
super();//Invocara al constructor PClass()
this("Hola, desde RClass");//Invoca al constructor RClass(String msg)
}

RClass(String msg){
out.println(msg);
}
}

Main.java
import static java.lang.System.out;
import static java.lang.System.err;

public class Main{


static public void main(String $[]){
Vehiculo auto = new Auto("3W", 200,"Chocolates");
out.println("Type:"+auto.getType());
out.println("Maxima velocidad:"+auto.getMaxSped());
//Error de compilacion: getTrans() no pertenece a Vehiculo
//out.println("Transporte:"+auto.getTrans());
}
}

class Vehiculo{
private String type = "4W";
private int maxSpeed = 100;

Vehiculo(String type, int maxSpeed){


this.type=type;
this.maxSpeed=maxSpeed;
}

public String getType(){


return type;
}

public void setType(String type){


this.type=type;
}

public int getMaxSped(){


return maxSpeed;
}

public void setMaxSped(int maxSpeed){


this.maxSpeed=maxSpeed;
}
}

class Auto extends Vehiculo{


private String trans;

//Esto no compilara:
//Auto(String trans){
// this.trans=trans;
//}

Auto(String type, int maxSpeed, String trans){


super(type,maxSpeed);
this.trans=trans;
}

public String getTrans(){


return trans;
}

public void setTrans(String trans){


this.trans=trans;
}
}

//15
Main.java
import static java.lang.System.out;
import static java.lang.System.err;

public class Main{


static public void main(String $[]){

}
}

abstract class Planeta{


protected void resolve(){}
abstract void rotate();
}

class Tierra extends Planeta{

//Error: no compilara, no se puede sobreescribir un metodo protected


//void resolve(){}

//Correcto:
public void resolve(){}

protected void rotate(){}


}

//14
Main.java
import static java.lang.System.out;
import static java.lang.System.err;

public class Main{


static public void main(String $[]){
try{
Short s1 = 200;
Integer s2 = 400;
Long s3 = (long) s1 + s2;//600
String s4 = (String) (s3 * s2);//Error de compilacion
out.println("Suma:"+s4);
}catch(ClassCastException | NumberFormatException nfe){
err.println("Exception gnral.:"+nfe.getMessage());
nfe.printStackTrace();
}catch(Exception e){
err.println("Exception:"+e.getMessage());
e.printStackTrace();
}
}
}

//13
Main.java
import static java.lang.System.out;
import static java.lang.System.err;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.UnsupportedTemporalTypeException;

public class Main{


static public void main(String $[]){
CharSequence charSequence = "2018-05-04";
try{
String date = LocalDate.parse(charSequence).format(DateTimeFormatter.ISO_DATE_TIME);
out.println(date);
}catch(ArrayIndexOutOfBoundsException | UnsupportedTemporalTypeException ute){
err.println("Ha ocurrido un error en la fecha: "+ute.getMessage());
ute.printStackTrace();
}
}
}
//Salida:
//Ha ocurrido un error en la fecha: Unsupported field: HourOfDay
//java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
//...

//12
Main.java
import static java.lang.System.out;

public class Main{


static public void main(String $[]){
int a = 9;
if(a++ < 10){
//a sigue valiendo 9, 9 < 10
out.println("Hola, Fer!");
}else{
out.println("Hola, Adela!");
}

int b = 2;
if(++b <= 2){
//3 <= 2, no se ejecutara
out.println("Hola, Fer!");
}else{
out.println("Hola, Adela!");
}
}
}
//Salida:
//Hola, Fer!
//Hola, Adela!

//11
Main.java
import static java.lang.System.out;

public class Main{

static public void main(String $[]){


Producto prd = new Producto();
prd.precio = 200;
double newPrecio = 100;
Test test = new Test();
//test.actualizaPrecio(200, 100)
test.actualizaPrecio(prd, newPrecio);
out.println(prd.precio+" : "+newPrecio);//400 : 100
}

}
//Salida:
//400.0 : 100.0

class Producto{
double precio;
}

class Test{
public void actualizaPrecio(Producto producto, double precio){
precio = precio * 2;//100 * 2 = 200
producto.precio = producto.precio + precio;//200 + 200 = 400
}
}

//10
Main.java
import static java.lang.System.out;

public class Main{

static public void main(String $[]){


Ejemplo ejemplo = new Ejemplo();
X objY = new Y();
ejemplo.metodo(objY);//Hola, desde Y
}
}
//Salida:
//Hola, desde Y

class X extends Object{


void metodo(){
out.println("Hola, desde X");
}
}

class Y extends X{
@Override
void metodo(){
out.println("Hola, desde Y");
}
}

class Ejemplo{
void metodo(X objX){
objX.metodo();
}

void metodo(Y objY){


objY.metodo();
}

You might also like