Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Palabras reservadas
Ejemplos vlidos
anioDeNacimiento2
_otra_variable
3valores
Dia&mes
&
Dos ms
(espacio)
Dos-valores
NombreDeVariableMuyLargoNoImp
orta
BotonPulsacion
ejemplo: int i = 0 ;
9
// hacer algo
// hacer otra cosa
10
Tipos Numricos
Integrales
Caracteres
boolean
char
Punto Flotante
Nmeros Enteros
byte short int long
float double
12
13
14
^ es el XOR
xor 0
0
1
0
1
1
1
0
6^3=5
~ es el complemento
-3 -2
110 con 11
110
11
101 =5
-1
~2 = -3
~-2 = 1
17
0
1
27
128
26
25
64
24
32 16
13<<1=26
13>>1=6
=13
23
22
21
20
1 byte = 8 bits
18
19
-------------------------------------------------------
if (<exprBooleana>) {
<grupoSentencias>;
-------------------------------------------------------
if (<exprBooleana>) {
<grupoSentencias>;
}else{
<grupoSentencias>;
-------------------------------------------------------
if (<exprBooleana>) {
<grupoSentencias>;
}else if (<exprBooleana>){
<grupoSentencias>;
}else{
<grupoSentencias>;
if (cont == 0)
System.out.println(cont = cero);
-------------------------------------------------------------------------------
if (cont == 0) {
System.out.println(cont = cero);
System.out.println(otra sentencia);
-------------------------------------------------------------------------------
if (cont == 0) {
System.out.println(cont = cero);
}else{
System.out.println(cont != cero);
-------------------------------------------------------------------------------
if (nota<4) {
System.out.println("Insuficiente");
}else if (nota<6) {
System.out.println("Suficiente");
}else{
System.out.println(Muy Bien");
20
int da = 4;
switch (da) {
case 1: System.out.println("Lunes");
break;
case 2: System.out.println("Martes");
break;
case 3: System.out.println("Mircoles");
break;
case 4: System.out.println("Jueves");
break;
case 5: System.out.println("Viernes");
break;
case 6: System.out.println("Sbado");
break;
case 7: System.out.println("Domingo");
break;
default: System.out.println(Error");
}
21
22
int cont = 0;
while (cont++ < 10) {
System.out.println(contador: + i );
}
do while
do{
<grupoSentencias>;
}while (<exprBooleana>);
int cont = 0;
do{
System.out.println(contador: + i );
} while (cont++ < 10);
23
resultado
Iteracin: 1
Iteracin: 2
Continue
La instruccin continue sirve para transferir el control del programa desde la instruccin continue
directamente a la cabecera del bucle (for, do-while o while) donde se encuentra.
int i;
for (i=1; i<=4; i++) {
if (i==3) continue;
System.out.println("Iteracin: "+i);
}
resultado
Iteracin: 1
Iteracin: 2
Iteracin: 4
24
String[] names;
names = new String[3];
names[0] = "Georgianna";
names[1] = "Jen";
names[2] = "Simon";
2)
String[] names = {
"Georgianna",
"Jen",
"Simon"
};
1)
MyDate[] dates;
dates = new MyDate[3];
dates[0] = new MyDate(22, 7, 1964);
dates[1] = new MyDate(1, 1, 2000);
dates[2] = new MyDate(22, 12, 1964);
2)
MyDate[] dates = {
new MyDate(22, 7, 1964),
new MyDate(1, 1, 2000),
new MyDate(22, 12, 1964)
};
26
27
Recorriendo Array
public void printElements(int[] list) {
for ( int element : list ) {
System.out.println(element);
}
}
Redimensionando un Array
NO SE PUEDE HACER
Qu hacemos entonces?
Usamos ARRAYCOPY
int[] myArray = { 1, 2, 3, 4, 5, 6 };
// nuevo array ms grande
int[] hold = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
// copia todo lo de myArray al array hold
System.arraycopy(myArray, 0, hold, 0, myArray.length);
29
????
0xFFFF000
0
dia
10
mes
08
anio
2003
31
final. Una clase declarada final impide que pueda ser superclase de
otras clases. Dicho de otra forma, ninguna clase puede heredar de
una clase final.
32
33
34
35
36
37
Tipos de Atributos:
de Objeto: son variables u objetos que almacenan valores distintos para instancias
distintas de la clase (para objetos distintos).
de Clase: son variables u objetos que almacenan el mismo valor para todos los objetos
instanciados a partir de esa clase.
Declaracin de Atributos:
static. Mediante la palabra reservada static se declaran atributos
de clase.
38
46
Herencia Simple
public class Employee {
public String name = "";
public double salary;
public Date birthDate;
public String getDetails() {...}
}
public class Manager extends
Employee {
public String department;
}
47
48
Visibilidad o Acceso
49
51
52
54
56
Objetos Polimrficos
Employee [] staff = new Employee[1024];
staff[0] = new Manager();
staff[1] = new Employee();
staff[2] = new Engineer();
public class TaxService {
public void chargeTax(){
TaxService taxSvc = new TaxService();
Manager m = new Manager();
TaxRate t = taxSvc.findTaxRate(m);
}
public TaxRate findTaxRate(Employee e) { }
}
57
Operador instanceof
public class Employee extends Object
public class Manager extends Employee
public class Engineer extends Employee
---------------------------------------public void doSomething(Employee e) {
if ( e instanceof Manager ) {
..
} else if ( e instanceof Engineer ) {
..
} else {
}
}
58
Casting de objetos
public void doSomething(Employee e) {
if ( e instanceof Manager ) {
Manager m = (Manager) e;
System.out.println(This is the manager of + m.getDepartment());
}
..
}
59
60
61
64
65
66
67
68
69
Iteracin :
while, do-while y for.
Transferencia :
break, continue, return, try-catch-finally y
assert.
70
Ejemplo
71
Ejemplo mejorado
72
73
Usando finally
Siempre se ejecuta
74
Categorias de Exception
75
THROWS
Try - catch
Intentando atrapar .
?
76
THROWS
77
Ejemplo de Throws
78
79
80
Ejercicio
Cuenta
saldo : double
Cuenta(saldoInicial : double)
getSaldo() : double
depositar(cantidad : double)
retirar(cantidad : double)
<<Exception>>
SobreGiroException
deficit : double
SobreGiroException()
getDeficit()
CuentaCorriente
cantidadSobreGiro : double
CuentaCorriente(saldoInicial : double, sobreGiro : double)
CuentaCorriente(saldoInicial : double)
retirar(cantidad : double)
81
System Properties
Lo usamos para dialogar con las variables del
entorno del sistema operativo
System.getProperties, devuelve un objeto
Properties
System.getProperty, devuelve un String con el
valor de determinada propiedad
El objeto Properties tiene un mtodo
propertiesNames() que se recorre con un
Enumeration
82
Ejemplo
83
Consola I/O
System.out : salida estndar al monitor
Genera un objeto de tipo PrintStream
84
85
86
Files
Import java.io
File myFile;
myFile = new File("myfile.txt");
myFile = new File("MyDocs", "myfile.txt");
87
Para Escribir:
FileWriter (escribe caracteres)
PrintWriter (tiene declarado los mtodos print y
println)
88
89
90
Collections
Un Collection es un objeto que representa
un grupo de objetos conocidos como
elementos
91
Coleccin ordenada
CON elementos duplicados
Coleccin desordenada
SIN elementos duplicados
92
Imprime:
[one, second, 5.0, 3rd, 4]
93
Imprime:
[one, second, 3rd, 4, 5.0, second, 4]
94
Collections : Generics
Elimina la necesidad de hacer casting
Antes de Generics
ArrayList list = new ArrayList();
list.add(0, new Integer(42));
int total = ((Integer)list.get(0)).intValue();
Despus de Generics
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = list.get(0).intValue();
96
97
Iterators
Iteration es el proceso de recuperar cada elemento en una collecion.
Un Iterator de un Set est desordenado.
Un ListIterator de un List puede ser escaneado hacia adelante (usando el
mtodo next ) o hacia atrs (usando el mtodo previous).
Ejemplo:
99
101