investigación y complemento del compilador

Post on 06-Feb-2016

18 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Investigación y Complemento del Compilador, Lenguajes y Autómatas I

TRANSCRIPT

2

Lenguajes y Autómatas I

74

INGENIERÍA EN SISTEMAS COMPUTACIONALES

UNIDAD 2 EVIDENCIA #1

Investigación y Complemento del Compilador

INTEGRANTES DEL EQUIPO:

Ana Karen Hernández Cruz.

Tania Hernández Martínez.

Adriana Morales Antonio.

César Manuel Reyes.

Gerardo Reyes Chavero.

MATERIA:

Lenguajes y Autómatas I

CATEDRÁTICO:

Ing. José Gregorio Márquez Vega

SEMESTRE: 6 TURNO: Matutino 1

Fecha de Entrega: 02 de Marzo del 2015.

Lenguajes y Autómatas I

3

FUNCIONES LÉXICAS DEFINICION EJEMPLO

Ana Karen

print( ) Imprime el argumento parado a la

salida estándar (normalmente la

consola).

public void print(String s)

public void print(Boolean b)

public void print(Char c)

println( ) Es similar al método print( )

excepto un carácter fin de línea o

secuencia se añade al final.

System.out.println(“x es “ + x + “, y es “ + y);

System.out.println(“x - y = “ + (x - y));

System.out.println(“x * y = “ + (x * y));

System.out.println(“x / y = “ + (x / y));

paint() Es un método vacío. public void paint(Graphics g) {

g.setFont(f);

g.setColor(Color.red);

g.drawString(“Hello again!”, 5, 25); }

do-while Se utiliza para repetir la ejecución

de sentencias y se ejecuta al

menos una vez.

int x = 1;

do {

System.out.println("Lazo, vuelta " + x);

x++;

} while (x <= 10);

try-catch captura de excepciones try

bloqueAIntentar //aunque sea una única

Lenguajes y Autómatas I

4

sentencia ésta irá entre {}

catch (tipoExcepcion1 identificador1)

boqueSentencias1

[catch (tipoExcepcion2 identificador2)

boqueSentencias2]

[finally

boqueSentenciasN]

o bien

try

bloqueAIntentar

finally

boqueSentenciasN

abstract Declara clases o métodos

abstractos

abstract tipo nombre (lista de parámetros)

double Tipo de Dato primitivo de punto

flotante por defecto (32 bits).

class caja{

double anchura;

double altura;

//calculo y devuelve el volumen

double volumen(){

return anchura *altura *profundidad; }

}

Lenguajes y Autómatas I

5

int Tipo de Dato primitivo entero por

defecto (32 bits).

int a=1, b=2; int c= a + b;

short s= 1; int d= s + c; // s seconvierte a int

strictfp Especifica bajo que standard se

calcularán las operaciones con

datos de punto flotante, para

determinar el grado de precisión

de los resultados.

strictfp class StrictFPClass {

double num1 = 10e+102;

double num2 = 6e+08;

double calculate() {

return num1 + num2;

}

}

boolean Tipo de Dato primitivo booleano

(true o false).

clase pública JavaBooleanExample{

public static void main (String [] args)

/ / Crear un objeto utilizando un booleano

eldado por debajo de los medios //1. Crear

unobjeto booleano de valor booleano

BooleanblnObj1 = new Boolean ( true ) ;

else Evaluación de la condición

lógicamente opuesta a un if o else

if.

int puntuacion;

String nota;

if (puntuacion >= 90) {

nota = "Sobresaliente";

} else (puntuacion >= 80)

{ nota = "Notable";

Lenguajes y Autómatas I

6

} else (puntuacion >= 70)

{ nota = "Bien";

} else (puntuacion >= 60)

{ nota = "Suficiente";

} else {

nota = "Insuficiente";}

interface Declara interfases. public interface NombreInterfaz

{

public abstract tipoDeResultado

nombreMétodo();

//otras declaraciones de métodos vacíos.

}

super Hace referencia a la clase padre o

al constructor de la clase padre

del objeto actual.

void myMethod (String a, String b) {

// colocar código aquí

super.myMethod(a,b);

// colocar más código

}

break Rompe el flujo normal del bloque

de código actual.

switch (oper) {

case '+':

addargs(arg1, arg2);

break;

Lenguajes y Autómatas I

7

case '-':

subargs(arg1, arg2);

break;

case '*':

multargs(arg1, arg2);

extends Indica que una clase o interfase

hereda de otra clase o interfase.

class Empleado extends Persona

{

public static final cantidad = 50;

//declaración de variables

//declaraciones de métodos

}

long Tipo de Dato primitivo entero (64

bits).

Int num1=100;

Long num2=num1;

switch Estructura de control condicional

múltiple.

switch (oper) {

case '+':

addargs(arg1, arg2);

break;

case '-':

subargs(arg1, arg2);

break;

case '*':

Lenguajes y Autómatas I

8

multargs(arg1, arg2);

byte Tipo de Dato primitivo entero (8

bits).

int a;

byte n1, n2;

short x;

final Declara la clase, método o

variable como "definitiva".

public class AnotherFinalClass {

public static final int aConstantInt = 123;

public final String aConstatString = “Hello

world!”);

}

native Indica que el método va a ser

especificado en un lenguaje

diferente a Java.

class HolaMundo {

public native void presentaSaludo();

static {

System.loadLibrary( "hola" );

}

}

synchronized Indica que el método, o bloque de

código deberá prevenir que no

sean cambiados los objectos a

afectar dentro del bloque o

método.

public void metodo() {

 synchronized(this) {

 // codigo del metodo aca

}

}

case Verifica cada valor evaluado en switch (x) {

Lenguajes y Autómatas I

9

una sentencia switch. case 2:

case 4:

case 6:

case 8:

System.out.println("x es un número par.");

break;

default: System.out.println("x es un número

impar.");

finally Determina el bloque de código

que se ejecutará siempre luego de

un try asi sea que se capture o no

una excepción.

finally{

código;

{

new Solicita al cargador de

clases correspondiente, un objeto

de esa clase.

new Animator();new Box(Color.black,

Color.red, 20, 25, 30, 15);

this Hace referencia el objeto actual o

al constructor del objeto actual.

class punto

int x,y;

punto(int x,int y){

this.x=x;

this.y=y;

}

Lenguajes y Autómatas I

10

int leer x(){

return x;

}

int leer y(){

return y;

}

}

catch Atrapa excepciones dentro de un

bloque try.

public void metodo() {

try{

}

catch(tipoExcepcion e){

try{

}

catch(tipoExcepcion e1){

}

}

float Tipo de Dato primitivo de punto

flotante (64 bits).

public static void main(String[] args) {

float a;

float b;

float c;

a = (float) 0.6917;

Lenguajes y Autómatas I

11

b = (float) 0.6911;

c = a-b;

System.out.println(c);

return;

}

package Especifica el paquete al que

pertenece esa clase o interfase.

Package nombrepaquete;

Package Mipaquete ;// crea un paquete

Mipaquete }

throw Lanza una excepción mediante

código.

try

bloqueAIntentar

catch(NumberFormatException identificador)

{

//...

throw (identificador);

}

char 30 Tipo de Dato primitivo que

almacena hasta un caracter

UNICODE (16 bits).

Char miCharacter=’n’; char mi Character1=110;

Tania

for Estructura de control cíclica. for (inicialización; test; incremento) {

sentencias;

Lenguajes y Autómatas I

12

}

private Modificador de visibilidad de

atributos y métodos limitándolos a

la propia clase.

private static class MiClase extiende java.util.

ArrayList

private final Object ocl = new Object ( ) ; final

privado Objeto OCL = new Object ();

}

}

throws Especifica la(s) excepcione(es)

que podría lanzar el método.

[modificadoresDeMétodos] tipoDeResultado

nombreMétodo

([tipoParámetro1 parámetro1

[,tipoParámetro2 parámetro2[, ...]]])

[throws Excepción1[,

Excepción2[,...]]]

{

//cuerpo del método que no trata la excepción

}

class Declara clases public class Persona {

private String nombre;

private String apellidos;

private in edad;

protected Modificador de visibilidad de public class AProtectedClass {

Lenguajes y Autómatas I

13

atributos y métodos limitándolos a

la propia clase, paquete e hijo(s).

private protected int aProtectedInt = 4;

private protected String aProtectedString =

“and a 3 and a “;

private protected float aProtectedMethod() {

. . . .

}

}

transient Indica que el objeto no se debe

serializar.

class TransientExample {

transient int hobo;

. . .

}

If Estructura de control condicional. // Respuesta dependiente del botón quehaya

pulsado el usuario

// OK o Cancel

if (respuesta == OK) {

// Código para la acción OK

} else {

// código para la acción Cancel

}

public Modificador de visibilidad de

clases, interfaces, atributos y

public class InstanceDemo {

public static void main(String[] args){

Lenguajes y Autómatas I

14

métodos haciéndolo visible al

universo.

MyClass cl1 = new MyClass();

MyClass cl2 = new MyClass();

System.out.println(cl1.ocl==cl2.ocl && cl1!=cl2);

}

try Declara un bloque de código que

posiblemente lanzará una

excepción.

public void metodo(){

   try{

      try{

      }

      catch(tipoExcepcion e){

      }

   }

   catch(tipoExcepcion e) {

   }

}

continue Rompe el flujo normal del bloque

de código actual.for(int j = 0; j<10; j++){

sentencia 1;

sentencia 2;

sentencia 3;

continue;

sentencia 4;

Lenguajes y Autómatas I

15

};

implements Indica que una clase implementa a

una (o varias) interfase(s).

public class Implementa [extends Padre]

implements NombreInterfaz

{

public tipoDeResultado nombreMétodo()

{

//...

return Retorna (normalmente un valor)

desde el método actual.

If(error==true)return ERROR;

void Indica que el método no retornará

valor alguno.

public class perro{

public void ladrar () {

sistem.out.printlin("wouf wouf");

}

public void morder(){

...

}

}

default Modificador de visibilidad de

clases, interfaces, atributos y

métodos limitándolos a la clase y

switch ( op ) {

Lenguajes y Autómatas I

16

paquete.default :

System.out.println("error");

break;

case '+':

System.out.println( a + b );

break;

import Indica la(s) ruta(s) en la que se

encuentran las clases y/o

interfases usadas en el código

import nombrePaquete.*;

import nombrePaquete.NombreClase;

import nombrePaquete.NombreInterfaz;

short Tipo de Dato primitivo entero (16

bits).

int a=1, b=2; int c= a + b;

short s= 1; int d= s + c; // s se convierte a int

float f= 1.0 + a; // a se convierte a float

volatile Indica que a la referencia de la

variable siempre se debería leer

sin aplicar ningún tipo de

optimizaciones ya que el dato

almacenado tiene alta

probabilidad de cambiar

muy frecuentemente.

volatile int contador;

Public void aumentar() {

Contador++;

}

do Estructura de control cíclica salida("Tercer iterador");

Lenguajes y Autómatas I

17

do {

salida("x es " + x--);

} while ( x > 0 );

System.exit(0);

}

instanceof Operador que determina si un

objeto es una instancia de una

clase.

if (profesor43 instanceof ProfesorInterino) {…}

else { …}

static Indica que el método, variable o

atributo pertenece a la clase y no

a la instancia (objeto).

class FamilyMember {

static String surname = “Johnson”;

String name;

int age; }

while Estructura de control cíclica. while (System.in.read() != -1) {

contador++;

System.out.println("Se ha leido el carácter =" +

contador);

}

null Se puede usar para declarar

cadenas vacías.

public static Empleado read (BufferedReader

br) throws Exception{

String nombre, tarifaStr;

int tarifa;

Lenguajes y Autómatas I

18

nombre = br.readLine();

if (nombre == null) return null;

tarifaStr = br.readLine();

if (tarifaStr == null) return null;

tarifa = Integer.parseInt(tarifaStr);

return new Empleado(nombre, tarifa);

}

true El valor verdadero de los datos

booleanos.

class Bool {

public static void main ( String argumentos[] ) {

boolean a=true;boolean b=true;

false boolean encontrado=false;

{...}

encontrado=true;

flush() Envía todo el buffer. salida.flush();

}

catch(FileNotFoundExceptione) {

}

close() Cierra el flujo de datos System.out.prinln(e.getMessage()); }

finally {

salida close();

}

Lenguajes y Autómatas I

19

}

arrayList Implementa una lista de

elementos mediante un array de

tamaño variable. Conforme se

añaden elementos el tamaño del

array irá creciendo si es

necesario. El array tendrá una

capacidad inicial, y en el momento

en el que se rebase dicha

capacidad, se aumentará el

tamaño del array.

// Vector de cadenas

ArrayList<String> a= new ArrayList<String>();

a.add("Hola");

String s = a.get(0);

a.add(new Integer(20)); // Daría error!!

// HashMap con claves enteras y valores de

vectores

HashMap <Integer, ArrayList>hm = new

HashMap();

hm.put(1, a);

ArrayList a2 = hm.get(1);

vector El Vector es una implementación

similar al ArrayList, con la

diferencia de que el Vector si que

está sincronizado. Este es un caso

especial, ya que la

implementación básica del resto

de tipos de datos no está

sincronizada

String

s1=”elemento”,s2=”elemento”,s3=”elemento”;

String []array={s1,s2,s3};

Vector v=new Vector();

v.addElement(s1); v.addElement(s2);

v.addElement(s3);

System.out.println(“Las componentes del array

son:”);

for (int i=0; i<3; i++)

Lenguajes y Autómatas I

20

{System.out.println(array[i]);}

StringBuffer Representa una cadena cuyo

tamaño puede variar.

StringBuffer(); StringBuffer( int len );

StringBuffer( String str );

binarySearch Permite buscar un elemento de

forma ultrarrapida en un array

ordenado (en un array

desprdenado sus resultado son

imprescindibles). Devuelve el

índice en el que está colocado el

elemento.

Int x[]={1,2,3,4,5,6,7,8,9,10,11,12};

Array.sort(x);

System.out.println(Array.binarySearch(x,8));

Adriana

System.arraysCopy La clase System también posee

un método relacionado con los

arrays, dicho método permite

copiar un array en otro. Recibe

cinco argumentos: el array que se

copia, el índice desde que se

empieza a copiar en el origen, el

array destino de la copia, el índice

desde el que se copia en el

destino, y el tamaño de la copia

Int uno[]={1,1,2};

Int dos[]={3,3,3,3,3,3,3,3,3};

System.arraycopy(uno,0,dos,0,uno.length);

For (int i=0,i<=8,i++){

System.out.print(dos[i]+ “ “);

}

Lenguajes y Autómatas I

21

(número de elementos de la

copia).

String.valueOf Este método pertenece no solo a

la clase String, sino a otras y

siempre es un método que

convierte valores de una clase a

otra. Permite convertir valores que

no son cadena a forma de cadena.

String numero= String.valueOf(1234);

String fecha= String.valueOf(new Date());

sort Permite ordenar un array en orden

ascendente. Se puede ordenar

solo una serie de elementos

desde un determinado pnto hasta

un determinado punto.

Int x[]={4,5,2,3,7,8,2,3,9,5};

Array.sort(x);//Estara ordenado

Array.sort(x,2,5);//Ordena del 20 al 40

elemento

length Permite devolver la longitud de

una cadena(el número de

caracteres de la cadena)

String texto1= “Prueba”;

System.out.println(texto1.length());

charAt Devuelve un carácter de la

cadena. El carácter a devolver se

indica por su posición (el primer

caracter es la posición 0). Si la

posición es negativa o sobrepasa

String s1= “Prueba”;

Char c1=s1.charAt(2);

Lenguajes y Autómatas I

22

el tamaño de la cadena, ocurre un

error de ejecución, una excepción

tipo IndexOutOfBounds-Exception.

substring Da como resultado una porción

del texto de la cadena. La porción

se toma desde una posición final

(sin incluir esa posición final). Si

las posiciones indicadas no son

validas ocurre una excepción de

tipo IndexOutOfBounds-Exception.

Se empieza a contar desde la

posición.

String s1=”Buenos Días”;

String s2=s1.substring(7,10);//s2= Días

indexOf Devuelve la primera posición en la

que aparece un determinado texto

en la cadena buscada no se

encuentra, devuelve -1. El texto a

buscar puede ser har o String.

String s1=”Quería decirte que quiero que te

vayas”;

System.out.println(s1.indexOf(“que”));// Da 15

lastIndexOf Devuelve la última posición en la

que aparece un determinado texto

en la cadena. Es casi idéntica a la

anterior, solo que busca desde el

String s1=”Quería decirte que quiero que te

vayas”;

System.out.println(s1.lasIndexOf(“que”));// Da

26

Lenguajes y Autómatas I

23

final.

endsWith Devuelve true si la cadena termina

con un determinado texto.

String s1=”Quería decirte que quiero que te

vayas”;

System.out.println(s1.endsWith(“vayas”));// Da

true

replace Cambia todas las apariciones de

un caracter por otro en el texto

que se indique y lo almacene

como resultado. El texto original

no se cambia, por lo que hay que

asignar el resultado de replace a

un String para almacenar el texto

cambiado.

String s1= “Mariposa”

System.out.println(s1.replace(‘a’,’e’)); Da

Meripose

System.out.println(s1);//Sigue valiendo

Mariposa

replaceAll Modifica en un texto cada entrada

de una cadena por otra y devuelve

el resultado. El primer parámetro

es el texto que se busca (que

puede ser una expresión regular),

el segundo parámetro es el texto

con el que se remplaza el

buscado. La cadena original no se

String s1= “Cazar armadillos”;

System.out.println(s1.replace(‘ar’,’er’)); Da

Cazer ermedillos

System.out.println(s1);//Sigue valiendo Cazar

armadilos

Lenguajes y Autómatas I

24

modifica.

finalize Es un método que es llamado

antes de eliminar definitivamente

al objeto para hacer limpieza final.

Un uso puede ser eliminar los

objetos creados en la clase para

eliminar referencias circulares. Es

un método de tipo protected

heredado por todas las clases ya

que está definido en la clase raíz

Object.

Class uno {

dos d;

uno(){

d=new dos();

}

Protected void finalize(){

d=null;//Se elimina d por lo que pudiera pasar

}

}

printf(boolean b) Imprime una variable booleana float x = 0

long  y = 5;

int *iptr = 0;

if (x == false) printf("x falso");            // Error.

if (y == truee) printf("y cierto");           // Error.

if (iptr == false) printf("Puntero nulo");    // Error.

if ((bool) x == false) printf("x falso");           // Ok.

if ((bool) y == true)  printf("y cierto");          // Ok.

if ((bool) iptr == false) printf("Puntero nulo");   //

Ok.

Lenguajes y Autómatas I

25

printf(char c) Imprime un caracter. Locale.setDefault(Locale.US);

Scanner lectura = newScanner(System.in);

char a;

a='\u2299';

System.out.printf("%c%n",a);

}

print(char[] s) Imprime un arreglo de caracteres. Printf (char arregloCadena[] = "buenas");

printf(double d) Imprime un número de tipo

double.

double n = 123.4567;

System.out.printf("El cuadrado de %.2f es %.2f\

n", n, n*n);

print(float f) Imprime un número de punto

flotante.

Public class tipoDecimales

{

Public static void main(String[]arg)

{

Float valor;

Valor=2.6;

System.out.println(“Valor de dato=”+valor);

}

}

print(int i) Imprime un entero.int main(void)

Lenguajes y Autómatas I

26

{

printf("¡Hola, mundo!\n");

return 0; }

print(long l) Imprime un largo enteroLong enteroGrande;

System.out.println(“Entero grande”);

EnteroGrande=lectura.nextLong();

print(Object obj) Imprime un objeto, invocando su

función toString()

Public boolean equals (Object obj) {

If (obj instanceof Persona){

Persona tmpPersona=(Persona)obj;

print(String s) Imprime un objeto de tipo String String nombre1, nombre2;

Int edad1, edad2;

System.out.print(“Ingrese el nombre”);

println() Imprime un separador de nueva

línea.System.out.println("3 x 1 = 3");

System.out.println("3 x 2 = 6");

println(boolean x) Imprime un valor booleano y

termina la línea.

public static boolean esPositivo(int x) {

if (x<0) return false;

else return true;

Lenguajes y Autómatas I

27

}

}

println(char x) Imprime un caracter y termina la

línea.

public class Main {

public static void main(String[] args) {

int N = 5;

double A = 4.56;

char C = 'a';

System.out.println("Variable N = " + N);

System.out.println("Variable A = " + A);

System.out.println("Variable C = " + C);

System.out.println(N + " + " + A + " = " +(N+A));

System.out.println(A + " - " + N + " = " + (A-N));

System.out.println("Valor numérico del carácter

" + C + " = " + (int)C);

}

}

println(char[] x) Imprime un arreglo de caracteres

y termina la línea.

int edades[];

char codigo[];

edades = new int [5];

codigos = new char[5];

println(double x) Imprime un número de precisión double x;

Lenguajes y Autómatas I

28

doble y termina la línea. system.out.println(“Introduzca número de tipo

double: ”);

x=sc nextDouble();

println(float x) Imprime un número de punto

flotante y termina la línea.

publicclass DivCeroFloat{

publicstaticvoid main(String[] args){

float x = 5.0f;

float y = 0.0f;

float z = x/y;

System.out.println(z);

}

}

println(int x) Imprime un entero y termina la

línea.

publicclass IntGrande{

publicstaticvoid main(String[] args){

int j = 2147483647;

int i = j + 1;

System.out.println("El valor obtenido es " + i);

}

}

println(long x) Imprime un entero largo y termina

la línea.

public class Factorial {

public static void main(String args[]) {

long n = Long.parseLong(args[0]);

Lenguajes y Autómatas I

29

System.out.println("El factorial de " + n + " es: "

+ Factorial(n)); }

println(Object x) Imprime un objeto invocando su

método toString() y termina la

línea.

import java.io.*;

public class PrintStreamDemo {

public static void main(String[] args) {

Object c = 15;

// create printstream object

PrintStream ps = new

PrintStream(System.out);

// print an object and change line

ps.println(c);

ps.print("New Line");

// flush the stream

ps.flush();

}

}

César

println(String x) Imprime un trozo de texto y

termina la línea.

import java.io.*;

public class Main {

public static void main(String[] args) {

String c = "from java2s.com";

Lenguajes y Autómatas I

30

PrintStream ps = new

PrintStream(System.out);

// print a string and change line

ps.println(c);

ps.print("from java2s.com");

// flush the stream

ps.flush();

}

}

available() Devuelve la cantidad de bytes que

se pueden leer (o pasar por alto)

desde esta entrada sin bloquear la

próxima llamada a lectura.

mport java.io.IOException;

import java.io.InputStream;

public class TiposEntradaEstandarPipe

{

public static void main(String[] args)

{

InputStream entrada = System.in;

int leido = 0;

try

{

if(entrada.available()>0)

{

Lenguajes y Autómatas I

31

while((leido = entrada.read()) != -1)

System.out.print((char)leido);

}

else

System.out.print("No se han encontrado datos

en la entrada Estandar");

}catch (IOException e)

{

System.out.print("Ha ocurrido un Error al leer la

entrada Estandar");

System.out.print(e.getMessage());

}

}

}

close() Cierra esta entrada de datos y

libera todos los recursos

asociados.

public class createfile {

private Formatter x;

public void openFile(){

try{

x = new

Formatter("supermanvsbatman.txt");

}

Lenguajes y Autómatas I

32

catch(Exception e){

System.out.println("you have an error");

}

}

public void addRecords(){

x.format("%s%s%s","20 ", "Bruce ",

"Wayne ");

}

public void closeFile(){

x.close();

}

}

read() Lee el próximo byte de datos

desde la entrada, espera por los

datos.

import java.io.IOException;

public class MainClass {

public static void main(String[] args) {

int inChar;

System.out.println("Enter a Character:");

try {

inChar = System.in.read();

System.out.print("You entered ");

System.out.println(inChar);

Lenguajes y Autómatas I

33

}

catch (IOException e){

System.out.println("Error reading from

user");

}

}

}

read(byte[] b) Lee de la entrada los bytes que

llenan el arreglo b, devuelve la

cantidad de bytes que se

almacenaron.

import java.io.IOException;

import java.io.FileInputStream;

public class FileInputStreamDemo {

public static void main(String[] args) throws

IOException {

FileInputStream fis = null;

int i = 0;

char c;

byte[] bs = new byte[4];

try{

// create new file input stream

fis = new FileInputStream("C://test.txt");

// read bytes to the buffer

i=fis.read(bs);

Lenguajes y Autómatas I

34

// prints

System.out.println("Number of bytes read: "+i);

System.out.print("Bytes read: ");

// for each byte in buffer

for(byte b:bs)

{

// converts byte to character

c=(char)b;

// print

System.out.print(c);

}

}catch(Exception ex){

// if any error occurs

ex.printStackTrace();

}finally{

// releases all system resources from the

streams

if(fis!=null)

fis.close();

}

}

Lenguajes y Autómatas I

35

}

read(byte[] b, int off, int len) Lee hasta en bytes de datos

adentro del arreglo de bytes b

empezando en off.

import java.io.BufferedInputStream;

import java.io.FileInputStream;

import java.io.InputStream;

public class BufferedInputStreamDemo {

public static void main(String[] args) throws

Exception {

InputStream inStream = null;

BufferedInputStream bis = null;

try{

// open input stream test.txt for reading

purpose.

inStream = new

FileInputStream("c:/test.txt");

// input stream is converted to buffered

input stream

bis = new

BufferedInputStream(inStream);

// read number of bytes available

int numByte = bis.available();

// byte array declared

Lenguajes y Autómatas I

36

byte[] buf = new byte[numByte];

// read byte into buf , starts at offset 2, 3

bytes to read

bis.read(buf, 2, 3);

// for each byte in buf

for (byte b : buf) {

System.out.println((char)b+": " + b);

}

}catch(Exception e){

e.printStackTrace();

}finally{

// releases any system resources

associated with the stream

if(inStream!=null)

inStream.close();

if(bis!=null)

bis.close();

}

}

}

skip(long n) Salta y destruye los n caracteres import java.io.BufferedInputStream;

Lenguajes y Autómatas I

37

de datos. import java.io.FileInputStream;

import java.io.FilterInputStream;

import java.io.IOException;

import java.io.InputStream;

public class FilterInputStreamDemo {

public static void main(String[] args) throws

Exception {

InputStream is = null;

FilterInputStream fis = null;

int i=0;

char c;

try{

// create input streams

is = new FileInputStream("C://test.txt");

fis = new BufferedInputStream(is);

while((i=fis.read())!=-1)

{

// converts integer to character

c=(char)i;

// skips 3 bytes

fis.skip(3);

Lenguajes y Autómatas I

38

// print

System.out.println("Character read: "+c);

}

}catch(IOException e){

// if any I/O error occurs

e.printStackTrace();

}final{

// releases any system resources

associated with the stream

if(is!=null)

is.close();

if(fis!=null)

fis.close();

}

}

}

abs(double a) Devuelve el valor absoluto de un

valor double.

import java.lang.Math;

public class MathDemo {

public static void main(String[] args) {

// get some doubles to find their absolute

values

Lenguajes y Autómatas I

39

double x = 4876.1874d;

double y = -0.0d;

// get and print their absolute values

System.out.println("Math.abs(" + x + ")=" +

Math.abs(x));

System.out.println("Math.abs(" + y + ")=" +

Math.abs(y));

System.out.println("Math.abs(-9999.555d)="

+ Math.abs(-9999.555d));

}

}

abs(float a) Devuelve el valor absoluto de un

valor float.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get some floats to find their absolute values

float x = 1.2345f;

float y = -857.54f;

// get and print their absolute values

System.out.println("Math.abs(" + x + ")=" +

Math.abs(x));

System.out.println("Math.abs(" + y + ")=" +

Lenguajes y Autómatas I

40

Math.abs(y));

System.out.println("Math.abs(-145.0f)=" +

Math.abs(-145.0f));

}

}

abs(int a) Devuelve el valor absoluto de un

valor int.

int absoluto(int x){

int abs;

if(x>0) abs=x;

else abs=-x;

return abs;

}

abs(long a) Devuelve el valor absoluto de un

valor long.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get some longs to find their absolute values

long x = 76487687634l;

long y = -1876487618764l;

// get and print their absolute values

System.out.println("Math.abs(" + x + ")=" +

Math.abs(x));

System.out.println("Math.abs(" + y + ")=" +

Lenguajes y Autómatas I

41

Math.abs(y));

System.out.println("Math.abs(-

18885785959l)=" + Math.abs(-18885785959l));

}

}

acos(double a)90 Devuelve el arcocoseno de un

ángulo, en el rango de 0.0 hasta

pi.

public class calc{

private double x;

private double y;

public calc(double x,double y){

this.x=x;

this.y=y;

}

public void print(double theta){

x = x*Math.cos(theta);

y = y*Math.sin(theta);

System.out.println("cos 90 : "+x);

System.out.println("sin 90 : "+y);

}

public static void main(String[]args){

calc p = new calc(3,4);

p.print(Math.toRadians(90));

Lenguajes y Autómatas I

42

}

asin(double a) Devuelve el arcoseno de un

ángulo, en el rango de -pi/2 hasta

pi/2.

public class bloqueStatic {

static double tablaSeno[] = new double[360];

static {

for(int i = 0; i < 360; i++)

tablaSeno[i] = Math.sin(Math.PI*i/180.0);

}

public static void main (String args[]) {

for(int i = 0; i < 360; i++)

System.out.println("Angulo: "+i+" Seno=

"+tablaSeno[i]);

}

}

atan(double a) Devuelve el arcotangente de un

ángulo, en el rango de -pi/2 hasta

pi/2.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get a variable x which is equal to PI/2

double x = Math.PI / 2;

// convert x to radians

x = Math.toRadians(x);

Lenguajes y Autómatas I

43

// get the arc tangent of x

System.out.println("Math.atan(" + x + ")" +

Math.atan(x));

}

}

atan2(double y, double x) Convierte coordenadas

rectangulares (x, y) a polares (r,

theta).

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get a variable x which is equal to PI/2

double x = Math.PI / 2;

// get a variable y which is equal to PI/3

double y = Math.PI / 3;

// convert x and y to degrees

x = Math.toDegrees(x);

y = Math.toDegrees(y);

// get the polar coordinates

System.out.println("Math.atan2(" + x + "," +

y + ")=" + Math.atan2(x, y));

}

}

cbrt(double a) Devuelve la raíz cuadrada de un import java.lang.*;

Lenguajes y Autómatas I

44

valor double. public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 125;

double y = 10;

// print the cube roots of three numbers

System.out.println("Math.cbrt(" + x + ")=" +

Math.cbrt(x));

System.out.println("Math.cbrt(" + y + ")=" +

Math.cbrt(y));

System.out.println("Math.cbrt(-27)=" +

Math.cbrt(-27));

}

}

ceil(double a) Devuleve el más pequeño

(cercano al infinito negativo) valor

double que es más grande o igual

al argumento a y es igual a un

entero matemático.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 125.9;

double y = 0.4873;

// call ceal for these these numbers

Lenguajes y Autómatas I

45

System.out.println("Math.ceil(" + x + ")=" +

Math.ceil(x));

System.out.println("Math.ceil(" + y + ")=" +

Math.ceil(y));

System.out.println("Math.ceil(-0.65)=" +

Math.ceil(-0.65));

}

}

cos(double a) Devuelve el coseno trigonométrico

de un ángulo.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 45.0;

double y = 180.0;

// convert them to radians

x = Math.toRadians(x);

y = Math.toRadians(y);

// print their cosine

System.out.println("Math.cos(" + x + ")=" +

Math.cos(x));

System.out.println("Math.cos(" + y + ")=" +

Lenguajes y Autómatas I

46

Math.cos(y));

}

}

cosh(double x) Devuelve el coseno hiperbólico de

un valor value.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 45.0;

double y = 180.0;

// convert them to radians

x = Math.toRadians(x);

y = Math.toRadians(y);

// print their hyperbolic cosine

System.out.println("Math.cosh(" + x + ")=" +

Math.cosh(x));

System.out.println("Math.cosh(" + y + ")=" +

Math.cosh(y));

}

}

exp(double a) Devuelve el valor e de Euler

elevado a la potencia del valor

import java.lang.*;

public class MathDemo {

Lenguajes y Autómatas I

47

double a. public static void main(String[] args) {

// get two double numbers

double x = 5;

double y = 0.5;

// print e raised at x and y

System.out.println("Math.exp(" + x + ")=" +

Math.exp(x));

System.out.println("Math.exp(" + y + ")=" +

Math.exp(y)); }

}

expm1(double x) Devuelve ex−1 . import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 5;

double y = 0.5;

// call expm1 for both numbers and print the

result

System.out.println("Math.expm1(" + x + ")="

+ Math.expm1(x));

System.out.println("Math.expm1(" + y + ")="

Lenguajes y Autómatas I

48

+ Math.expm1(y));

}

}

floor(double a) Devuelve el más largo (cercano al

positivo infinito) valor double que

es menor o igual al argumento a y

es igual a un entero matemático.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 60984.1;

double y = -497.99;

// call floor and print the result

System.out.println("Math.floor(" + x + ")=" +

Math.floor(x));

System.out.println("Math.floor(" + y + ")=" +

Math.floor(y));

System.out.println("Math.floor(0)=" +

Math.floor(0));

}

}

hypot(double x, double y)Devuelve sqrt(x2+ y2) sin el

overflow o underflow intermedio.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

Lenguajes y Autómatas I

49

// get two double numbers

double x = 60984.1;

double y = -497.99;

// call hypot and print the result

System.out.println("Math.hypot(" + x + "," +

y + ")=" + Math.hypot(x, y)); }

}

IEEEremainder(double f1,

double f2)

Computa la operación prescripta

por el estándar IEEE 754 entre los

dos argumentos f1 y f2.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 60984.1;

double y = -497.99;

// get the remainder when x/y

System.out.println("Math.IEEEremainder("

+ x + "," + y + ")="

+ Math.IEEEremainder(x, y));

// get the remainder when y/x

System.out.println("Math.IEEEremainder("

+ y + "," + x + ")="

+ Math.IEEEremainder(y, x));

Lenguajes y Autómatas I

50

}

}

log(double a) Devuelve el logaritmo natural

(base e) de un valor double.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 60984.1;

double y = -497.99;

// get the natural logarithm for x

System.out.println("Math.log(" + x + ")=" +

Math.log(x));

// get the natural logarithm for y

System.out.println("Math.log(" + y + ")=" +

Math.log(y));

}

}

log10(double a) Devuelve el logaritmo en base 10

de un valor double.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 60984.1;

Lenguajes y Autómatas I

51

double y = 1000;

// get the base 10 logarithm for x

System.out.println("Math.log10(" + x + ")="

+ Math.log10(x));

// get the base 10 logarithm for y

System.out.println("Math.log10(" + y + ")="

+ Math.log10(y));

}

}

log1p(double x) Devuelve ex+1 . import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 60984.1;

double y = 1000;

// call log1p and print the result

System.out.println("Math.log1p(" + x + ")="

+ Math.log1p(x));

// call log1p and print the result

System.out.println("Math.log1p(" + y + ")="

+ Math.log1p(y));

Lenguajes y Autómatas I

52

}

}

max(double a, double b) Devuelve el más grande de los

dos valores double a y b.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 60984.1;

double y = 1000;

// print the larger number between x and y

System.out.println("Math.max(" + x + "," + y

+ ")=" + Math.max(x, y));

}

}

max(float a, float b) Devuelve el más grande de los

dos valores float a y b.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two float numbers

float x = 60984.1f;

float y = 1000f;

// print the larger number between x and y

System.out.println("Math.max(" + x + "," + y

Lenguajes y Autómatas I

53

+ ")=" + Math.max(x, y));

}

}

max(int a, int b) Devuelve el más grande de los

dos valores int a y b.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two integer numbers

int x = 60984;

int y = 1000;

// print the larger number between x and y

System.out.println("Math.max(" + x + "," + y

+ ")=" + Math.max(x, y));

}

}

Gerardo Chavero

max(long a, long b) Devuelve el más grande de los

dos valores long a y b.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two long numbers

long x = 6098499785l;

long y = 1000087898745l;

Lenguajes y Autómatas I

54

// print the larger number between x and y

System.out.println("Math.max(" + x + "," + y

+ ")=" + Math.max(x, y)); }

}

min(double a, double b) Devuelve el más pequeño de los

dos valores double a y b.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 9875.875;

double y = 154.134;

// print the smaller number between x and y

System.out.println("Math.min(" + x + "," + y

+ ")=" + Math.min(x, y));

}

}

min(float a, float b) Devuelve el más pequeño de los

dos valores float a y b.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two float numbers

float x = 9875.875f;

float y = 154.134f;

Lenguajes y Autómatas I

55

// print the smaller number between x and y

System.out.println("Math.min(" + x + "," + y

+ ")=" + Math.min(x, y));

}

}

min(int a, int b) Devuelve el más pequeño de los

dos valores int a y b.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two int numbers

int x = 9875;

int y = 154;

// print the smaller number between x and y

System.out.println("Math.min(" + x + "," + y

+ ")=" + Math.min(x, y));

}

}

min(long a, long b) Devuelve el más pequeño de los

dos valores long a y b.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two long numbers

long x = 98759765l;

Lenguajes y Autómatas I

56

long y = 15428764l;

// print the smaller number between x and y

System.out.println("Math.min(" + x + "," + y

+ ")=" + Math.min(x, y));

}

}

pow(double a, double b) Devuelve el valor del argumento a

elevado a la potencia de b : ab.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 2.0;

double y = 5.4;

// print x raised by y and then y raised by x

System.out.println("Math.pow(" + x + "," + y

+ ")=" + Math.pow(x, y));

System.out.println("Math.pow(" + y + "," + x

+ ")=" + Math.pow(y, x));

}

}

random() Devuelve un valor de tipo double

con signo positivo, mayor o igual

import java.util.Random;

    public class Programa {

Lenguajes y Autómatas I

57

que cero y menor que uno 1.0.         public static void main(String arg[ ]) {

              Random rnd = new Random();

              System.out.println("Número aleatorio

real entre [0,1[ : "+rnd.nextDouble());

      }

    }

rint(double a) Devuelve el valor double que es

más cercano al valor a y es igual a

un entero matemático.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 1654.9874;

double y = -9765.134;

// find the closest integers for these double

numbers

System.out.println("Math.rint(" + x + ")=" +

Math.rint(x));

System.out.println("Math.rint(" + y + ")=" +

Math.rint(y));

}

}

round(double a) Devuelve el valor long más public static double round(double value, int

Lenguajes y Autómatas I

58

cercano al argumento. places) {

if (places < 0) throw new

IllegalArgumentException();

long factor = (long) Math.pow(10, places);

value = value * factor;

long tmp = Math.round(value);

return (double) tmp / factor;

}

round(float a) Devuelve el valor int más cercano

al argumento.

public static BigDecimal round(float d, int

decimalPlace) {

BigDecimal bd = new

BigDecimal(Float.toString(d));

bd = bd.setScale(decimalPlace,

BigDecimal.ROUND_HALF_UP);

return bd;

}

signum(double d) La función signo, cero si el

argumento es cero, 1.0 si el

argumento es mayor que cero y -

1.0 si el argumento es menor que

cero.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers

double x = 50.14;

Lenguajes y Autómatas I

59

double y = -4;

// call signum for both doubles and print the

result

System.out.println("Math.signum(" + x +

")=" + Math.signum(x));

System.out.println("Math.signum(" + y +

")=" + Math.signum(y));

}

}

signum(float f)120 La función signo, cero si el

argumento es cero, 1.0 si el

argumento es mayor que cero y -

1.0 si el argumento es menor que

cero.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two float numbers

float x = 50.14f;

float y = -4f;

// call signum for both floats and print the result

System.out.println("Math.signum(" + x +

")=" + Math.signum(x));

System.out.println("Math.signum(" + y +

")=" + Math.signum(y));

}

Lenguajes y Autómatas I

60

}

sin(double a) Devuelve el seno trigonométrico

de un ángulo.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers numbers

double x = 45;

double y = -180;

// convert them to radians

x = Math.toRadians(x);

y = Math.toRadians(y);

// print the trigonometric sine for these

doubles

System.out.println("Math.sin(" + x + ")=" +

Math.sin(x));

System.out.println("Math.sin(" + y + ")=" +

Math.sin(y)); }

}

sinh(double x) Devuelve el seno hiperbólico de

un valor double.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers numbers

Lenguajes y Autómatas I

61

double x = 45;

double y = -180;

// convert them to radians

x = Math.toRadians(x);

y = Math.toRadians(y);

// print the hyperbolic sine for these doubles

System.out.println("sinh(" + x + ")=" +

Math.sinh(x));

System.out.println("sinh(" + y + ")=" +

Math.sinh(y));

}

}

sqrt(double a) Devuelve la raíz cuadrada positiva

redondeada de un valor double.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers numbers

double x = 9;

double y = 25;

// print the square root of these doubles

System.out.println("Math.sqrt(" + x + ")=" +

Math.sqrt(x));

Lenguajes y Autómatas I

62

System.out.println("Math.sqrt(" + y + ")=" +

Math.sqrt(y));

}

}

tan(double a) Devuelve la tangente

trigonométrica de un ángulo.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers numbers

double x = 45;

double y = -180;

// convert them in radians

x = Math.toRadians(x);

y = Math.toRadians(y);

// print the tangent of these doubles

System.out.println("Math.tan(" + x + ")=" +

Math.tan(x));

System.out.println("Math.tan(" + y + ")=" +

Math.tan(y));

}

}

tanh(double x) Devuelve la tangente hiperbólica import java.lang.*;

Lenguajes y Autómatas I

63

de un valor double. public class MathDemo {

public static void main(String[] args) {

// get two double numbers numbers

double x = 45;

double y = -180;

// convert them in radians

x = Math.toRadians(x);

y = Math.toRadians(y);

// print the hyperbolic tangent of these doubles

System.out.println("Math.tanh(" + x + ")=" +

Math.tanh(x));

System.out.println("Math.tanh(" + y + ")=" +

Math.tanh(y));

}

}

toDegrees(double angrad) Convierte un ángulo medido en

radianes al aproximado en grados.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers numbers

double x = 45;

double y = -180;

Lenguajes y Autómatas I

64

// convert them in degrees

x = Math.toDegrees(x);

y = Math.toDegrees(y);

// print the hyperbolic tangent of these

doubles

System.out.println("Math.tanh(" + x + ")=" +

Math.tanh(x));

System.out.println("Math.tanh(" + y + ")=" +

Math.tanh(y));

}

}

toRadians(double angdeg) Convierte un ángulo medido en

grados al aproximado en radianes.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers numbers

double x = 45;

double y = -180;

// convert them in radians

x = Math.toRadians(x);

y = Math.toRadians(y);

// print the hyperbolic tangent of these doubles

Lenguajes y Autómatas I

65

System.out.println("Math.tanh(" + x + ")=" +

Math.tanh(x));

System.out.println("Math.tanh(" + y + ")=" +

Math.tanh(y));

}

}

ulp(double d) Ver definición en la

documentación completa.

import java.lang.*;

public class MathDemo {

public static void main(String[] args) {

// get two double numbers numbers

double x = 956.294;

double y = 123.1;

// print the ulp of these doubles

System.out.println("Math.ulp(" + x + ")=" +

Math.ulp(x));

System.out.println("Math.ulp(" + y + ")=" +

Math.ulp(y));

}

}

ulp(float f) Ver definición en la import java.lang.*;

Lenguajes y Autómatas I

66

documentación completa. public class MathDemo {

public static void main(String[] args) {

// get two double float numbers

float x = 956.294f;

float y = 123.1f;

// print the ulp of these floats

System.out.println("Math.ulp(" + x + ")=" +

Math.ulp(x));

System.out.println("Math.ulp(" + y + ")=" +

Math.ulp(y));

}

}

Array Objeto contenedor que almacena

una secuencia indexada de los

mismos tipos de datos.

Normalmente los elementos

individuales se referencian por

el valor de un índice.

public class Array

{

public static void main(String arg[])

{

int [] losValores = null;

losValores[4] = 100;

System.out.println(losValores[4]); }

}

Int hashCode() Este método devuelve un código import java.lang.*;

Lenguajes y Autómatas I

67

hash de este objeto Boolean. public class BooleanDemo {

public static void main(String[] args) {

// create 2 Boolean objects b1, b2

Boolean b1, b2;

// assign values to b1, b2

b1 = new Boolean(true);

b2 = new Boolean(false);

// create 2 int primitives

int i1, i2;

// assign the hash code of b1, b2 to i1, i2

i1 = b1.hashCode();

i2 = b2.hashCode();

String str1 = "Hash code of " + b1 + " is " +i1;

String str2 = "Hash code of " + b2 + " is " +i2;

// print i1, i2 values

System.out.println( str1 );

System.out.println( str2 );

}

}

In compareTo(Boolean b) Este método compara esta import java.lang.*;

Lenguajes y Autómatas I

68

instancia de Boole con otro. public class BooleanDemo {

public static void main(String[] args) {

// create 2 Boolean objects b1, b2

Boolean b1, b2;

// assign values to b1, b2

b1 = new Boolean(true);

b2 = new Boolean(false);

// create an int res

int res;

// compare b1 with b2

res = b1.compareTo(b2);

String str1 = "Both values are equal ";

String str2 = "Object value is true";

String str3 = "Argument value is true";

if( res == 0 ){

System.out.println( str1 );

}

else if( res > 0 ){

System.out.println( str2 );

}

else if( res < 0 ){

Lenguajes y Autómatas I

69

System.out.println( str3 );

}

}

}

Byte byteValue() Este método devuelve el valor de

este byte como un byte.

import java.lang.*;

public class ByteDemo {

public static void main(String[] args) {

// create a Byte object b

Byte b;

// assign value to b

b = new Byte("100");

// create a byte primitive bt

byte bt;

// assign primitive value of b to bt

bt = b.byteValue();

String str = "Primitive byte value of Byte

object " + b + " is " + bt;

// print bt value

System.out.println( str ); }

}

Int compareTo(Byter Este método compara dos objetos import java.lang.*;

Lenguajes y Autómatas I

70

anotherByte) Byte numéricamente. public class ByteDemo {

public static void main(String[] args) {

// create 2 Byte objects b1, b2

Byte b1, b2;

// assign values to b1, b2

b1 = new Byte("-100");

b2 = new Byte("10");

// create an int res

int res;

// compare b1 with b2 and assign result to res

res = b1.compareTo(b2);

String str1 = "Both values are equal ";

String str2 = "First value is greater";

String str3 = "Second value is greater";

if( res == 0 ){

System.out.println( str1 );

}

else if( res > 0 ){

System.out.println( str2 );

}

else if( res < 0 ){

Lenguajes y Autómatas I

71

System.out.println( str3 );

}

}

}

Static byte decode(String nm) Este método decodifica una

cadena en un byte.

import java.lang.*;

public class ByteDemo {

public static void main(String[] args) {

// create 4 Byte objects

Byte b1, b2, b3, b4;

/**

* static methods are called using class name.

* decimal value is decoded and assigned

to Byte object b1 */

b1 = Byte.decode("100");

// hexadecimal values are decoded and

assigned to Byte objects b2, b3

b2 = Byte.decode("0x6b");

b3 = Byte.decode("-#4c");

// octal value is decoded and assigned to

Byte object b4

b4 = Byte.decode("0127");

Lenguajes y Autómatas I

72

String str1 = "Byte value of decimal 100

is " + b1;

String str2 = "Byte value of hexadecimal 6b

is " + b2;

String str3 = "Byte value of hexadecimal -4c

is " + b3;

String str4 = "Byte value of octal 127 is " +

b4;

// print b1, b2, b3, b4 values

System.out.println( str1 );

System.out.println( str2 );

System.out.println( str3 );

System.out.println( str4 );

}

}

Double doubleValue() Este método devuelve el valor de

este byte como un doble.

import java.lang.*;

public class ByteDemo {

public static void main(String[] args) {

// create 2 Byte objects b1, b2

Byte b1, b2;

// create 2 double primitives d1, d2

Lenguajes y Autómatas I

73

double d1, d2;

// assign values to b1, b2

b1 = new Byte("100");

b2 = new Byte("-10");

// assign double values of b1, b2 to d1, d2

d1 = b1.doubleValue();

d2 = b2.doubleValue();

String str1 = "double value of Byte " + b1 + "

is " + d1;

String str2 = "double value of Byte " + b2 + "

is " + d2;

// print d1, d2 values

System.out.println( str1 );

System.out.println( str2 );

}

}

Boolean equals(Object obj) Este método compara este objeto

para el objeto especificado.

import java.lang.*;

public class ByteDemo {

public static void main(String[] args) {

// create 2 Byte objects b1, b2

Byte b1, b2;

Lenguajes y Autómatas I

74

// create 2 boolean primitives bool1, bool2

boolean bool1, bool2;

// assign values to b1, b2

b1 = new Byte("100");

b2 = new Byte("100");

// compare b1 and b2 and assign result to

bool1

bool1 = b1.equals(b2);

/**

* compare b1 with object 100 and assign

result to bool2, it

* returns false as 100 is not a Byte object

*/

bool2 = b1.equals("100")

String str1 = b1 + " equals " + b2 + " is " +

bool1;

String str2 = b1 + " equals object value 100

is " + bool2;

// print bool1, bool2 values

System.out.println( str1 );

System.out.println( str2 ); }

Lenguajes y Autómatas I

75

}

Float floatValue() Este método devuelve el valor de

este byte como un flotador.

import java.lang.*;

public class ByteDemo {

public static void main(String[] args) {

// create 2 Byte objects b1, b2

Byte b1, b2;

// create 2 float primitives f1, f2

float f1, f2;

// assign values to b1, b2

b1 = new Byte("100");

b2 = new Byte("-10");

// assign float values of b1, b2 to f1, f2

f1 = b1.floatValue();

f2 = b2.floatValue();

String str1 = "float value of Byte " + b1 + " is

" + f1;

String str2 = "float value of Byte " + b2 + " is

" + f2;

// print f1, f2 values

System.out.println( str1 );

System.out.println( str2 ); }

Lenguajes y Autómatas I

76

}

top related