Resumen Lenguaje Java Comentarios Elementos del Lenguaje De una sola línea // comentario De varias líneas /* Este es un comentario de varias líneas */ Comentarios para Javadoc /** * The Example class */ Convenciones Java para comentarios http://java.sun.com/docs/codeconv/html/codeconventions.doc4.html Tipos de Datos http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html Primitivos Tipos de datos Primitivos Ejemplos de valores literales Keyword Description Size/Format Integers Literal Value 178 int Data Type byte Byte-length integer 8-bit short Short integer 16-bit int Integer 32-bit long Long integer 64-bit Real numbers 8864L long 37.266 double 37.266D double 87.363F float 26.77e3 double 'c' char float Single-precision floating point 32-bit IEEE 754 double Double-precision floating point 64-bit IEEE 754 Other types true false boolean boolean char A single character 16-bit Unicode character boolean A boolean value (true or false) true or false
2 Referencia En otros lenguajes se conoce como apuntador (pointer) y representa una dirección de memoria. El valor que almacena una variable de tipo referencia es una referencia (dirección de) al valor o conjunto de valores almacenados en otra variable. E n J a v a l o s a r r e g l o s y l o s o b j e t o s s o n de tipo referencia. Conversión de Tipos Conversión de un dato de un tipo menor a uno mayor: no es necesario utilizar ninguna notación especial, simplemente se asigna un tipo a otro. Conversión de un dato de un tipo mayor a uno menor: debe indicarse al compilador en forma explicita usando casting. (tipo_dato al que se desea convertir) expresión_a_convertir Esta permitida la conversión entre datos numéricos, entre enteros y caracteres, pero no entre booleanos y enteros. Variables Declaración tipo_dato identificador = valor_inicial; La inicialización al declarar la variable es opcional. Ejemplo float presion = 32.361; char letra, sexo; Constantes Declaración final tipo_dato identificador = valor_inicial; Ejemplo final float ACELERACION = 9.6; final char letra = a ; Operadores Aritméticos Operadores http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arithmetic.html Operadores Aritméticos Unarios + +op Promotes op to int if it's a byte, short, or char - -op Arithmetically negates op
3 Operadores Aritméticos Binarios + op1 + op2 Adds op1 and op2; also used to concatenate strings - op1 - op2 Subtracts op2 from op1 * op1 * op2 Multiplies op1 by op2 / op1 / op2 Divides op1 by op2. % op1 % op2 Computes the remainder of dividing op1 by op2 (mod) El operador / está sobrecargado. Si op1 y op2 son de tipo entero calcula el cociente entero de dividir op1 entre op2 (div), de lo contrario calcula la división real. Operadores Aritméticos abreviados ++ op++ Increments op by 1; evaluates to the value of op before it was incremented ++ ++op Increments op by 1; evaluates to the value of op after it was incremented -- op-- Decrements op by 1; evaluates to the value of op before it was decremented -- --op Decrements op by 1; evaluates to the value of op after it was decremented Operadores relacionales http://java.sun.com/docs/books/tutorial/java/nutsandbolts/relational.html > op1 > op2 Returns true if op1 is greater than op2 >= op1 >= op2 Returns true if op1 is greater than or equal to op2 < op1 < op2 Returns true if op1 is less than op2 <= op1 <= op2 Returns true if op1 is less than or equal to op2 == op1 == op2 Returns true if op1 and op2 are equal!= op1!= op2 Returns true if op1 and op2 are not equal
4 Operadores lógicos http://java.sun.com/docs/books/tutorial/java/nutsandbolts/relational.html && op1 && op2 Returns true if op1 and op2 are both true; conditionally evaluates op2 op1 op2 Returns true if either op1 or op2 is true; conditionally evaluates op2!!op Returns true if op is false & op1 & op2 op1 op2 ^ op1 ^ op2 Returns true if op1 and op2 are both boolean and both true; always evaluates op1 and op2; if both operands are numbers, performs bitwise AND operation Returns true if both op1 and op2 are boolean and either op1 or op2 is true; always evaluates op1 and op2; if both operands are numbers, performs bitwise inclusive OR operation Returns true if op1 and op2 are different that is, if one or the other of the operands, but not both, is true. OR Exclusivo. Operadores de Bits http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html Operadores de desplazamiento << op1 << op2 Shifts bits of op1 left by distance op2; fills with 0 bits on the right side >> op1 >> op2 Shifts bits of op1 right by distance op2; fills with highest (sign) bit on the left side >>> op1 >>> op2 Shifts bits of op1 right by distance op2; fills with 0 bits on the left side Operador Uso Operación Operadores Lógicos & op1 & op2 Bitwise AND if both operands are numbers; conditional AND if both operands are boolean op1 op2 Bitwise OR if both operands are numbers; conditional OR if both operands are boolean ^ op1 ^ op2 Bitwise exclusive OR (XOR) ~ ~op Bitwise complement
5 Asignación http://java.sun.com/docs/books/tutorial/java/nutsandbolts/assignment.html = op1 = op2 Equivalent to op1 op2 Operadores de asignación abreviados += op1 += op2 Equivalent to op1 = op1 + op2 -= op1 -= op2 Equivalent to op1 = op1 - op2 *= op1 *= op2 Equivalent to op1 = op1 * op2 /= op1 /= op2 Equivalent to op1 = op1 / op2 %= op1 %= op2 Equivalent to op1 = op1 % op2 &= op1 &= op2 Equivalent to op1 = op1 & op2 = op1 = op2 Equivalent to op1 = op1 op2 ^= op1 ^= op2 Equivalent to op1 = op1 ^ op2 <<= op1 <<= op2 Equivalent to op1 = op1 << op2 >>= op1 >>= op2 Equivalent to op1 = op1 >> op2 >>>= op1 >>>= op2 Equivalent to op1 = op1 >>> op2 Operador ternario?: op1? op2 : op3 If op1 is true, returns op2; otherwise, returns op3 Prioridad de Operadores Prioridad Operador 1 ++ -- ~! x + - (unarios) (conversión de tipos) 2 * / %
6 3 + - + (concatenación) 4 >>> << >> 5 < <= > >= ==!= 6 && & 7 ^ Estructuras de Control http://java.sun.com/docs/books/tutorial/java/nutsandbolts/flowsummary.html Selectivas if (boolean expression) { if (boolean expression) { else { if (boolean expression) { else if (boolean expression) { else if (boolean expression) { else { The single statement block of which is executed if the boolean expression is true. The if statement executes the first block if the boolean expression is true; otherwise, it executes the second block. Ejemplo if (nota >= 9) calificación = 'SB'; else if (nota >= 7) calificacion = 'N'; else if (nota >= 5) calificacion = 'A'; else calificacion = 'S'; switch (integer or char expression) { case integer or char expression: break;... default: break; Ejemplos switch (califletra){ case 'A': puntos = 20; break; case 'B': puntos = 12; break; case 'C': puntos = 8; break; default : puntos = 0; break; switch (mes){ case 9: case 4: case 6: case 11: dias = 30; break; case 2 : dias = 28; break; default: dias = 31; break;
7 Repetitivas while (boolean expression) { do { while (expression); for (initialization; termination; increment) { Ejemplos estructura for Use the while statement to loop over a block of statements while a boolean expression remains true. The expression is evaluated at the top of the loop. Use the do-while statement to loop over a block of statements while a boolean expression remains true. The expression is evaluated at the bottom of the loop, so the statements within the do-while block execute at least once. The for statement loops over a block of statements and includes an initialization expression, a termination condition expression, and an increment expression. suma = 0; for(int i = 1; i <= n; i++) suma += i; for(float r = 0.0; r <= 15.0; r += 0.1) System.out.println("Valor: " + r) ; for(int i = 100; i >= 5; i -= 5) System.out.println("Valor: " + i); boolean encontrado = false; for(;!encontrado; ){ // instrucciones for(int i = 1, multiplo3 = 1; i <= 5; i++, multiplo3 += 2) System.out.println("Valor: " + multiplo3) ; System.out.println( ); Salida por Consola Ejemplo System.out.println( termino: + t + \n ); Referencia: http://java.sun.com/docs/books/tutorial/java/toc.html#nutsandbolts
8 Ejercicio de Aplicación /* * Serie.java * Created on 23 de marzo de 2006, 12:21 PM */ package unidad1_fatima; /** * Determina el valor de la serie * S = ln(x) + ln^3(x)/3! + ln^5(x)/5! + ln^7(x)/7!+... * El programa genera un valor de x aleatorio adecuado y * genera un valor t aleatorio no mayor que 10^-4 * Genera cada termino de la serie a partir del termino anterior * Cada termino se calcula como num / fac * Detiene el calculo de la serie cuando el valor absoluto del ultimo * termino sumado es menor que el valor de t * Finalmente escribe el numero de terminos y el valor de la sumatoria * author mdeabreu */ public class Serie { public static void main(string[] args) { // Genera valores aleatorios float x =(float) Math.random()*100; System.out.println("x: "+x); float t = (float)(math.random()*1e-4); System.out.println("t: " + t); // Calcula el primer termino fuera del ciclo float termino = (float)math.log(x); int i = 1; // contador de terminos System.out.println("termino: " + i + ": "+ termino+ "\n"); float lncuadrado = (float)(math.pow(s,2)); // inicializa acumuladores float num = termino; float fac = 1; float s = termino; // ciclo que calcula la serie do{ num *= lncuadrado; // num = num * lncuadrado i++; fac *= ((2*i-2)*(2*i-1)); termino = num/fac; s += termino; // s = s + termino System.out.println("termino: " + i + ": "+ termino+ "\n"); while (Math.abs(termino) >= t); // escribe por consola los valores calculados System.out.println("Suma: " + s + "\n"); System.out.println("Numero de terminos: "+ i);