Professional Documents
Culture Documents
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.
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.
Paquete java.lang
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 java.util.Collection;//interface
import java.util.Collections;//clase
import java.util.*;
import java.io.*;
Puntos importantes:
Se debe tener cuidado. Cada tipo tiene métodos propios. Un String es un Object, pero un
Object no es un String.
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 --
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.
Autoboxing y autounboxing
Asignación directa entre tipos primitivos y objetos.
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.
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
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;
//métodos de acceso
public String getValor(String valor){
return valor;
}
}
Intanciación de clases externas e internas
Externa.java
class Externa{
private String valor;
@Override
public String toString(){
return "Externa{valor="+valor+"}";
}
@Override
public String toString(){
return "Interna{valor="+valor+"}";
}
}
}
//Main
ClaseExterna.ClaseStaticInterna ref = new ConstructorExterna.ConstructorStaticInterna();
Main.java
public class Main{
System.out.println(obj1);
System.out.println(obj3);
System.out.println(obj5);
}
}
Externa.java
class Externa{
private String valor;
@Override
public String toString(){
return "Externa{valor="+valor+"}";
}
class Interna{
private String valor;
@Override
public String toString(){
return "Interna{valor="+valor+"}";
}
}
}
//Main
ClaseExterna.ClaseInterna ref = ref.new ConstructorInterna();
Main.java
public class Main{
System.out.println(obj1);
System.out.println(obj3);
}
}
Modificadores
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.
Main.java
public class Main{
}
}
//Esto no se puede:
//class Dos extends Unica{}
//Una clase final no puede heredar
class X{
public static final int CONSTANTE = 30;
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
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.
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 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.
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
Abstract
Static
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.
Constructores
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.
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.
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(){}
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.
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();
}
@Override
public void saludar() {
System.out.println("Hola, buen día!!");
}
@Override
public void comer() {
System.out.println("A comer”);
}
}
-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();
}
@Override
public void saludar() {
System.out.println("Hola, buen día!!");
}
@Override
public void comer() {
System.out.println("A comer!!");
}
@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)
//Esto no se puede:
//Empleado obj3 = new Persona();//Empleado es una extensión de Persona, ya es una
Persona
//Esto no se puede:
//Programador obj6 = new Empleado();//Programador es una extensión de Empleado, ya
es un Empleado
Clases abstractas
}
//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
Herencia e Implementación
interface Modales{
abstract void saludar();
}
}
//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!!");
}
//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
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;
}
}
interface Modales{
void saludar();
}
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;
}
}
interface Modales{
void saludar();
}
//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{}
Main.java
public class Main {
public static void main(String[] args) {
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
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
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.
class BookDetails {
String title;
void setBook(String title){
this.title=title;
}
}
@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
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){}
}
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");
//}
}
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;
ArrayList
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()
Enumeraciones:
java.time.DayOfWeek
java.time.Month
Excepciones
java.time.DateTimeException
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
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
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
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
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
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
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
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
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
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
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
Interfaces Lambdas
java.util.function.Consumer;
java.util.function.Predicate;
java.util.function.Supplier;
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
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)
//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)
}
}
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;
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());
}
}
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;
java.lang.Math != java.math
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 MyException(){
super();
}
//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;
public MyException(){
super();
}
Expresiones lambdas
Main.java
import java.util.function.Supplier;
@FunctionalInterface
interface Usable{
void hola();
}
}
//Salida:
//Hola, mundo!
//Numero aleatorio:4
//Numero aleatorio:91
Main.java
import java.util.function.Function;
Main.java
import java.util.function.Supplier;
Main.java
import java.util.function.Consumer;
import com.codemonkey.clases.Persona;
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;
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;
public MyException(){
super();
}
class Refractor {
public Refractor(){}
public MyException(){
super();
}
Main.java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
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");
}
Main.java
import java.time.Period;
Main.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
//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());
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);
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 Empleado(){}
@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;
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;
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;
}
}
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;
try{
vector[0]= 10;
vector[1]= 8;
vector[2]= 2;
}catch(NullPointerException | ArrayIndexOutOfBoundsException e4){
err.println("Causa:"+e4.getCause()+" - Mensaje:"+e4.getMessage());
e4.printStackTrace();
}
}
}
//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;
Main.java
import static java.lang.System.out;
import static java.lang.System.err;
MyExcepcionA(){
super();
}
MyExcepcionA(String msg){
super(msg);
}
class GeneradorPDF{
private String archivo;
protected GeneradorPDF(){}
GeneradorPDF(String archivo){
this.archivo=archivo;
}
}
//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;
tryEntero(obj1);
tryEntero(obj4);
tryString(obj1);
tryString(obj2);
tryString(obj3);
Main.java
import static java.lang.System.out;
import static java.lang.System.err;
import java.util.Random;
//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;
//6
Main.java
import static java.lang.System.out;
}
//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;
//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;
}
//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;
}
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...");
}
}
//3
Main.java
import static java.lang.System.out;
import static java.lang.System.err;
}
//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;
}
//2
Main.java
import static java.lang.System.out;
//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;
}
}
PClass(String msg){
out.println(msg);
}
}
RClass(String msg){
out.println(msg);
}
}
Main.java
import static java.lang.System.out;
import static java.lang.System.err;
class Vehiculo{
private String type = "4W";
private int maxSpeed = 100;
//Esto no compilara:
//Auto(String trans){
// this.trans=trans;
//}
//15
Main.java
import static java.lang.System.out;
import static java.lang.System.err;
}
}
//Correcto:
public void resolve(){}
//14
Main.java
import static java.lang.System.out;
import static java.lang.System.err;
//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;
//12
Main.java
import static java.lang.System.out;
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;
}
//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;
class Y extends X{
@Override
void metodo(){
out.println("Hola, desde Y");
}
}
class Ejemplo{
void metodo(X objX){
objX.metodo();
}