Sei sulla pagina 1di 75

INGENIERA EN SISTEMAS

COMPUTACIONALES
UNIDAD 2

EVIDENCIA #1

Investigacin y Complemento del Compilador

INTEGRANTES DEL EQUIPO:


Ana Karen Hernndez Cruz.
Tania Hernndez Martnez.
Adriana Morales Antonio.
Csar Manuel Reyes.
Gerardo Reyes Chavero.

MATERIA:
Lenguajes y Autmatas I

CATEDRTICO:
Ing. Jos Gregorio Mrquez Vega

SEMESTRE: 6

TURNO: Matutino 1
Fecha de Entrega: 02 de Marzo del 2015.

FUNCIONES LXICAS
print( )

DEFINICION
EJEMPLO
Ana Karen
Imprime el argumento parado a la public void print(String s)
salida estndar (normalmente la public void print(Boolean b)

println( )

consola).
public void print(Char c)
Es similar al mtodo print( )
System.out.println(x es + x + , y es + y);
excepto un carcter fin de lnea o
secuencia se aade al final.

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

paint()

Es un mtodo vaco.
public void paint(Graphics g) {
g.setFont(f);
g.setColor(Color.red);

do-while

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


Se utiliza para repetir la ejecucin int x = 1;
de sentencias y se ejecuta al
menos una vez.

do {

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


x++;
} while (x <= 10);
try-catch

captura de excepciones

try
bloqueAIntentar

//aunque

sea

una

sentencia sta ir entre {}


catch (tipoExcepcion1 identificador1)
boqueSentencias1
[catch (tipoExcepcion2 identificador2)
boqueSentencias2]
[finally
boqueSentenciasN]
o bien
try
bloqueAIntentar
finally
abstract

Declara
abstractos

clases

boqueSentenciasN
mtodos abstract tipo nombre (lista de parmetros)

nica

double

Tipo de Dato primitivo de punto class caja{


flotante por defecto (32 bits).

double anchura;
double altura;
//calculo y devuelve el volumen
double volumen(){
return anchura *altura *profundidad;

int

}
Tipo de Dato primitivo entero por int

strictfp

defecto (32 bits).


short s= 1; int d= s + c; // s seconvierte a int
Especifica bajo que standard se strictfp class StrictFPClass {

a=1,

b=2;

int

c=

b;

calcularn las operaciones con double num1 = 10e+102;


datos de punto flotante, para double num2 = 6e+08;
determinar el grado de precisin double calculate() {
de los resultados.

return num1 + num2;


}

boolean

}
Tipo de Dato primitivo booleano clase
(true o false).

pblica

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

Evaluacin

de

la

condicin int puntuacion;

lgicamente opuesta a un if o else String nota;


if.

if (puntuacion >= 90) {


nota = "Sobresaliente";
}

else

{
}

nota
else

{
}
{

(puntuacion
=

nota
else

Declara interfases.

>=

70)
"Bien";

(puntuacion

nota

80)

"Notable";

(puntuacion

}
interface

>=

>=

60)

"Suficiente";

else

nota = "Insuficiente";}
public interface NombreInterfaz
{
public

abstract

tipoDeResultado

nombreMtodo();
//otras declaraciones de mtodos vacos.
}
super

Hace referencia a la clase padre o


al constructor de la clase padre
del objeto actual.

void myMethod (String a, String b) {


// colocar cdigo aqu

super.myMethod(a,b);
// colocar ms cdigo
}
break

Rompe el flujo normal del bloque


de cdigo actual.

switch (oper) {
case '+':
addargs(arg1, arg2);
break;
case '-':
subargs(arg1, arg2);
break;
case '*':

extends

multargs(arg1, arg2);
Indica que una clase o interfase class Empleado extends Persona
hereda de otra clase o interfase.

public static final cantidad = 50;


//declaracin de variables
//declaraciones de mtodos
long
switch

}
Tipo de Dato primitivo entero (64 Int num1=100;
bits).
Long num2=num1;
Estructura de control condicional
switch (oper) {
mltiple.
case '+':
addargs(arg1, arg2);
break;
case '-':
subargs(arg1, arg2);
break;
case '*':

byte

multargs(arg1, arg2);
Tipo de Dato primitivo entero (8 int a;

bits).

byte n1, n2;


short x;

final

Declara

la

clase,

mtodo

o
public class AnotherFinalClass {

variable como "definitiva".

public static final int aConstantInt = 123;


public final String aConstatString = Hello
world!);

native

}
Indica que el mtodo va a ser class HolaMundo {
especificado

en

un

lenguaje public native void presentaSaludo();

diferente a Java.

static {
System.loadLibrary( "hola" );
}

synchronized

}
Indica que el mtodo, o bloque de public void metodo() {
cdigo deber prevenir que no

synchronized(this) {

sean cambiados los objectos a

// codigo del metodo aca

afectar
case

dentro

del

bloque

o }

mtodo.
}
Verifica cada valor evaluado en
switch (x) {
una sentencia switch.

case 2:
case 4:
case 6:
case 8:
System.out.println("x es un nmero par.");
break;
default: System.out.println("x es un nmero
finally

impar.");
Determina el bloque de cdigo finally{
que se ejecutar siempre luego de cdigo;
un try asi sea que se capture o no {

new

una excepcin.
Solicita
al cargador

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

clases correspondiente, un objeto 20, 25, 30, 15);


this

de esa clase.
Hace referencia el objeto actual o class punto
al constructor del objeto actual.

int x,y;

punto(int x,int y){


this.x=x;
this.y=y;
}
int leer x(){
return x;
}
int leer y(){
return y;
}
catch

}
Atrapa excepciones dentro de un public void metodo() {
bloque try.

try{
}
catch(tipoExcepcion e){
try{
}
catch(tipoExcepcion e1){
}

float

}
Tipo de Dato primitivo de punto public
flotante (64 bits).

float

static

void

main(String[]

args)

{
a;

float

b;

float

c;

(float)

0.6917;

(float)

0.6911;

a-b;

System.out.println(c);
return;
package

Especifica

el

paquete

al

}
que Package nombrepaquete;

pertenece esa clase o interfase.


Package

Mipaquete

;//

crea

un

paquete

Mipaquete }
throw

Lanza una excepcin mediante try


cdigo.

bloqueAIntentar
catch(NumberFormatException identificador)
{
//...
throw (identificador);

char 30

Tipo

de

almacena

Dato
hasta

UNICODE (16 bits).

primitivo
un

}
que Char miCharacter=n; char mi Character1=110;

caracter

for

Tania
Estructura de control cclica.
for (inicializacin; test; incremento) {
sentencias;

private

Modificador

de

visibilidad

}
de private static class MiClase extiende java.util.

atributos y mtodos limitndolos a ArrayList


la propia clase.

private final Object ocl = new Object ( ) ; final


privado

Objeto

OCL

new

Object

();

}
throws

Especifica

la(s)

}
excepcione(es) [modificadoresDeMtodos]

que podra lanzar el mtodo.

tipoDeResultado

nombreMtodo
([tipoParmetro1 parmetro1
[,tipoParmetro2 parmetro2[, ...]]])
[throws Excepcin1[,
Excepcin2[,...]]]
{
//cuerpo del mtodo que no trata la excepcin

class

Declara clases

}
public class Persona {

private String nombre;


private String apellidos;
private in edad;
protected

Modificador

de

visibilidad

de

atributos y mtodos limitndolos a


la propia clase, paquete e hijo(s).

public class AProtectedClass {


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 class TransientExample {
serializar.

transient int hobo;


...

If

Estructura de control condicional.

}
// Respuesta dependiente del botn quehaya
pulsado

el

usuario

//

OK

if

(respuesta

//

Cdigo

Modificador
clases,

de

interfaces,

mtodos

hacindolo

atributos
visible

cdigo

}
de public

visibilidad

OK)

la

accin

OK

else

//
public

==

para

Cancel

y public

para

la

class
static

{
accin

Cancel

InstanceDemo

void

main(String[]

{
args){

al MyClass

cl1

new

MyClass();

MyClass

cl2

new

MyClass();

universo.

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


try

}
Declara un bloque de cdigo que public void metodo(){
posiblemente

lanzar

una

try{

excepcin.

try{
}
catch(tipoExcepcion e){
}
}
catch(tipoExcepcion e) {
}
}

continue

Rompe el flujo normal del bloque


de cdigo actual.

for(int j = 0; j<10; j++){


sentencia 1;
sentencia 2;
sentencia 3;
continue;
sentencia 4;
};

implements

Indica que una clase implementa a public


una (o varias) interfase(s).

class

Implementa

[extends

Padre]

implements NombreInterfaz
{
public tipoDeResultado nombreMtodo()
{

return

//...
Retorna (normalmente un valor) If(error==true)return ERROR;

void

desde el mtodo actual.


Indica que el mtodo no retornar public
valor alguno.

public

class
void

ladrar

sistem.out.printlin("wouf

perro{
()

{
wouf");

}
public
...

void

morder(){

}
}
default

Modificador
clases,

de

visibilidad

interfaces,

atributos

de
y

mtodos limitndolos a la clase y


paquete.

switch ( op ) {
default :
System.out.println("error");
break;
case '+':
System.out.println( a + b );
break;

import

Indica la(s) ruta(s) en la que se import nombrePaquete.*;


encuentran

short

las

clases

y/o import nombrePaquete.NombreClase;

interfases usadas en el cdigo


import nombrePaquete.NombreInterfaz;
Tipo de Dato primitivo entero (16 int
a=1,
b=2;
int
c=
a
+
bits).

volatile

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

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


Indica que a la referencia de la volatile int contador;
variable siempre se debera leer Public void aumentar() {
sin

b;

aplicar

ningn

tipo

de Contador++;

optimizaciones ya que el dato }


almacenado
probabilidad

tiene

alta

de cambiar

do

muy frecuentemente.
Estructura de control cclica

salida("Tercer iterador");
do {
salida("x es " + x--);
} while ( x > 0 );
System.exit(0);

instanceof

}
Operador que determina si un if (profesor43 instanceof ProfesorInterino) {}
objeto es una instancia de una else { }

static

clase.
Indica que el mtodo, variable o
atributo pertenece a la clase y no
a la instancia (objeto).

class FamilyMember {
static String surname = Johnson;
String name;

while

Estructura de control cclica.

int age; }
while
(System.in.read()

!=

-1)

contador++;
System.out.println("Se ha leido el carcter =" +
contador);
null

}
Se puede usar para declarar public static Empleado read (BufferedReader

cadenas vacas.

br)

throws

String

Exception{

nombre,

tarifaStr;

int

tarifa;

nombre
if

(nombre

tarifaStr
if

return
true

=
new

}
El valor verdadero de los datos class
booleanos.

null)

return

(tarifaStr

tarifa

==

br.readLine();

==

br.readLine();
null)

return

Empleado(nombre,
Bool

Enva todo el buffer.

encontrado=true;
salida.flush();
}
catch(FileNotFoundExceptione) {

close()

Cierra el flujo de datos

tarifa);
{

public static void main ( String argumentos[] ) {

{...}
flush()

null;

Integer.parseInt(tarifaStr);

boolean a=true;boolean b=true;


boolean encontrado=false;

false

null;

}
System.out.prinln(e.getMessage()); }
finally {

salida close();
}
arrayList

Implementa

una

}
de // Vector de cadenas

lista

elementos mediante un array de ArrayList<String> a= new ArrayList<String>();


tamao variable. Conforme se a.add("Hola");
aaden elementos el tamao del String s = a.get(0);
array

ir

creciendo

si

es a.add(new Integer(20)); // Dara error!!

necesario. El array tendr una // HashMap con claves enteras y valores de


capacidad inicial, y en el momento vectores
en

el

que

capacidad,

se
se

rebase

dicha HashMap

aumentar

tamao del array.


vector

<Integer,

ArrayList>hm

new

el HashMap();
hm.put(1, a);

ArrayList a2 = hm.get(1);
El Vector es una implementacin String
similar

al

ArrayList,

con

la s1=elemento,s2=elemento,s3=elemento;

diferencia de que el Vector si que String []array={s1,s2,s3};


est sincronizado. Este es un caso Vector v=new Vector();
especial,

ya

que

la v.addElement(s1);

v.addElement(s2);

implementacin bsica del resto v.addElement(s3);


de

tipos

de

sincronizada

datos

no

est System.out.println(Las componentes del array


son:);

for
una

cadena

(int

i=0;

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

i<3;

StringBuffer

Representa

int

binarySearch

tamao puede variar.


StringBuffer( String str );
Permite buscar un elemento de Int x[]={1,2,3,4,5,6,7,8,9,10,11,12};

i++)
len

forma ultrarrapida en un array Array.sort(x);


ordenado

(en

un

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

desprdenado sus resultado son


imprescindibles).

Devuelve

el

ndice en el que est colocado el


elemento.
System.arraysCopy

Adriana
La clase System tambin posee Int uno[]={1,1,2};
un mtodo relacionado con los Int dos[]={3,3,3,3,3,3,3,3,3};
arrays,

dicho

mtodo

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

copiar un array en otro. Recibe For (int i=0,i<=8,i++){


cinco argumentos: el array que se System.out.print(dos[i]+ );
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 tamao de la copia

);

(nmero
String.valueOf

de

elementos

de

la

copia).
Este mtodo pertenece no solo a String numero= String.valueOf(1234);
la clase String, sino a otras y String fecha= String.valueOf(new Date());
siempre

es

un

mtodo

que

convierte valores de una clase a


otra. Permite convertir valores que
sort

no son cadena a forma de cadena.


Permite ordenar un array en orden Int x[]={4,5,2,3,7,8,2,3,9,5};
ascendente. Se puede ordenar Array.sort(x);//Estara ordenado
solo

una

serie

de

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

desde un determinado pnto hasta


length

un determinado punto.
Permite devolver la longitud de String texto1= Prueba;
una

charAt

cadena(el

nmero

caracteres de la cadena)
Devuelve un carcter

de

de System.out.println(texto1.length());
la String s1= Prueba;

cadena. El carcter a devolver se Char c1=s1.charAt(2);


indica por su posicin (el primer
caracter es la posicin 0). Si la
posicin es negativa o sobrepasa
el tamao de la cadena, ocurre un

error de ejecucin, una excepcin


substring

tipo IndexOutOfBounds-Exception.
Da como resultado una porcin String s1=Buenos Das;
del texto de la cadena. La porcin String s2=s1.substring(7,10);//s2= Das
se toma desde una posicin final
(sin incluir esa posicin final). Si
las posiciones indicadas no son
validas ocurre una excepcin de
tipo IndexOutOfBounds-Exception.
Se empieza a contar desde la

indexOf

posicin.
Devuelve la primera posicin en la String s1=Quera decirte que quiero que te
que aparece un determinado texto vayas;
en la cadena buscada no se System.out.println(s1.indexOf(que));// Da 15
encuentra, devuelve -1. El texto a

lastIndexOf

buscar puede ser har o String.


Devuelve la ltima posicin en la String s1=Quera decirte que quiero que te
que aparece un determinado texto vayas;
en la cadena. Es casi idntica a la System.out.println(s1.lasIndexOf(que));//

Da

anterior, solo que busca desde el 26


endsWith

final.
Devuelve true si la cadena termina String s1=Quera decirte que quiero que te

con un determinado texto.

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

replace

true
Cambia todas las apariciones de String s1= Mariposa
un caracter por otro en el texto System.out.println(s1.replace(a,e));

Da

que se indique y lo almacene Meripose


como resultado. El texto original System.out.println(s1);//Sigue

valiendo

no se cambia, por lo que hay que Mariposa


asignar el resultado de replace a
un String para almacenar el texto
replaceAll

cambiado.
Modifica en un texto cada entrada String s1= Cazar armadillos;
de una cadena por otra y devuelve System.out.println(s1.replace(ar,er));

Da

el resultado. El primer parmetro Cazer ermedillos


es el texto que se busca (que System.out.println(s1);//Sigue valiendo Cazar
puede ser una expresin regular), armadilos
el segundo parmetro es el texto
con

el

que

se

remplaza

el

buscado. La cadena original no se


finalize

modifica.
Es un mtodo que es llamado Class uno {
antes de eliminar definitivamente dos d;

al objeto para hacer limpieza final. uno(){


Un uso puede ser eliminar los d=new dos();
objetos creados en la clase para }
eliminar referencias circulares. Es Protected void finalize(){
un

mtodo de tipo protected d=null;//Se elimina d por lo que pudiera pasar

heredado por todas las clases ya }


que est definido en la clase raz }
printf(boolean b)

Object.
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"); //


printf(char c)

Imprime un caracter.

Ok.
Locale.setDefault(Locale.US);
Scanner lectura = newScanner(System.in);
char a;
a='\u2299';
System.out.printf("%c%n",a);

print(char[] s)
printf(double d)

}
Imprime un arreglo de caracteres. Printf (char arregloCadena[] = "buenas");
Imprime un nmero de tipo double n = 123.4567;
double.

print(float f)

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

%.2f\n", n, n*n);
Imprime un nmero de punto Public class tipoDecimales
flotante.

{
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)
{
printf("Hola, mundo!\n");
return 0; }

print(long l)

Imprime un largo entero

Long enteroGrande;
System.out.println(Entero grande);
EnteroGrande=lectura.nextLong();

print(Object obj)

print(String s)

Imprime un objeto, invocando su Public boolean equals (Object obj) {


funcin toString()

If (obj instanceof Persona){

Imprime un objeto de tipo String

Persona tmpPersona=(Persona)obj;
String nombre1, nombre2;
Int edad1, edad2;
System.out.print(Ingrese el nombre);

println()

Imprime un separador de nueva


lnea.

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

println(boolean x)

Imprime un valor booleano y public static boolean esPositivo(int x) {


termina la lnea.

if (x<0) return false;


else return true;

}
println(char x)

}
Imprime un caracter y termina la public
lnea.

public

static

int

class

Main

void

main(String[]

double

args)

=
A

char

{
5;

4.56;

'a';

System.out.println("Variable

"

N);

System.out.println("Variable

"

A);

System.out.println("Variable

"

C);

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


System.out.println(A + " - " + N + " = " + (A-N));
System.out.println("Valor numrico del carcter
"

"

"

(int)C);

}
println(char[] x)

}
Imprime un arreglo de caracteres int
y termina la lnea.

char
edades

println(double x)

edades[];
codigo[];
=

new

int

[5];

codigos = new char[5];


Imprime un nmero de precisin double x;
doble y termina la lnea.

system.out.println(Introduzca nmero de tipo

double: );
println(float x)

x=sc nextDouble();
Imprime un nmero de punto publicclass DivCeroFloat{
flotante y termina la lnea.

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 publicclass IntGrande{
lnea.

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 public class Factorial {
la lnea.

public static void main(String args[]) {


long

Long.parseLong(args[0]);

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


+ Factorial(n)); }

println(Object x)

Imprime un objeto invocando su import java.io.*;


mtodo toString() y termina la public class PrintStreamDemo {
lnea.

public static void main(String[] args) {


Object c = 15;
// create printstream object
PrintStream

ps

new

new

PrintStream(System.out);
// print an object and change line
ps.println(c);
ps.print("New Line");
// flush the stream
ps.flush();
}
}
println(String x)

Csar
Imprime un trozo de texto y import java.io.*;
termina la lnea.

public class Main {


public static void main(String[] args) {
String c = "from java2s.com";
PrintStream

ps

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 mport

java.io.IOException;

se pueden leer (o pasar por alto) import

java.io.InputStream;

desde esta entrada sin bloquear la public


prxima llamada a lectura.

class

TiposEntradaEstandarPipe

static

void

{
public

main(String[]

args)

{
InputStream
int

entrada

leido

System.in;

0;

entrada.read())

!=

try
{
if(entrada.available()>0)
{
while((leido

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

-1)

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

la

}catch

entrada

Estandar");

(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 public class createfile {
libera

todos

asociados.

los

recursos

private Formatter x;
public void openFile(){
try{
x

new

Formatter("supermanvsbatman.txt");
}
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 prximo byte de datos import java.io.IOException;
desde la entrada, espera por los public class MainClass {
datos.

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);
}
catch (IOException e){
System.out.println("Error reading from

user");
}
}
read(byte[] b)

}
Lee de la entrada los bytes que import java.io.IOException;
llenan el arreglo b, devuelve la import java.io.FileInputStream;
cantidad

de

almacenaron.

bytes

que

se 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);
// 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();
}
}
read(byte[] b, int off, int len)

}
Lee hasta en bytes de datos import java.io.BufferedInputStream;
adentro del arreglo de bytes b import java.io.FileInputStream;

empezando en off.

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
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;
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);
// 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 import java.lang.Math;
valor double.

public class MathDemo {


public static void main(String[] args) {
// get some doubles to find their absolute
values
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 import java.lang.*;
valor float.

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 + ")=" +
Math.abs(y));
System.out.println("Math.abs(-145.0f)=" +
Math.abs(-145.0f));

}
abs(int a)

}
Devuelve el valor absoluto de un int absoluto(int x){
valor int.

int abs;
if(x>0) abs=x;
else abs=-x;
return abs;

abs(long a)

}
Devuelve el valor absoluto de un import java.lang.*;
valor long.

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 + ")=" +
Math.abs(y));
System.out.println("Math.abs(18885785959l)=" + Math.abs(-18885785959l));
}

acos(double a)90

}
Devuelve el arcocoseno de un public class calc{
ngulo, en el rango de 0.0 hasta

private double x;

pi.

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));

asin(double a)

Devuelve

el

arcoseno

de

}
un public class bloqueStatic {

ngulo, en el rango de -pi/2 hasta static double tablaSeno[] = new double[360];


pi/2.

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

0;

System.out.println("Angulo:

<

360;
"+i+"

i++)
Seno=

"+tablaSeno[i]);
}
atan(double a)

}
Devuelve el arcotangente de un import java.lang.*;
ngulo, en el rango de -pi/2 hasta
pi/2.

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);
// get the arc tangent of x
System.out.println("Math.atan(" + x + ")" +
Math.atan(x));
}

atan2(double y, double x)

Convierte

}
coordenadas import java.lang.*;

rectangulares (x, y) a polares (r, public class MathDemo {


theta).

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 raz cuadrada de un import java.lang.*;
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

ms

}
pequeo import java.lang.*;

(cercano al infinito negativo) valor public class MathDemo {


double que es ms grande o igual

public static void main(String[] args) {

al argumento a y es igual a un

// get two double numbers

entero matemtico.

double x = 125.9;
double y = 0.4873;
// call ceal for these these numbers
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 trigonomtrico import java.lang.*;
de un ngulo.

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 + ")=" +
Math.cos(y));
}

cosh(double x)

}
Devuelve el coseno hiperblico de import java.lang.*;
un valor value.

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 import java.lang.*;
elevado a la potencia del valor public class MathDemo {
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)

e 1
x

Devuelve

}
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 + ")="
+ Math.expm1(y));
}

floor(double a)

}
Devuelve el ms largo (cercano al import java.lang.*;
positivo infinito) valor double que public class MathDemo {
es menor o igual al argumento a y
es igual a un entero matemtico.

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

}
import java.lang.*;
sin

overflow o underflow intermedio.

el public class MathDemo {


public static void main(String[] args) {
// 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
double f2)

}
f1, Computa la operacin prescripta import java.lang.*;
por el estndar IEEE 754 entre los public class MathDemo {

dos argumentos f1 y f2.

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));
}

log(double a)

Devuelve

el

logaritmo

}
natural import java.lang.*;

(base e) de un valor double.

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 import java.lang.*;
de un valor double.

public class MathDemo {


public static void main(String[] args) {
// get two double numbers
double x = 60984.1;
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));
}

max(double a, double b)

}
Devuelve el ms grande de los import java.lang.*;
dos valores double a y b.

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 ms grande de los import java.lang.*;
dos valores float a y b.

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
+ ")=" + Math.max(x, y));
}

max(int a, int b)

}
Devuelve el ms grande de los import java.lang.*;
dos valores int a y b.

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));
}
}
max(long a, long b)

Gerardo Chavero
Devuelve el ms grande de los import java.lang.*;
dos valores long a y b.

public class MathDemo {


public static void main(String[] args) {
// get two long numbers
long x = 6098499785l;
long y = 1000087898745l;
// 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 ms pequeo de los import java.lang.*;
dos valores double a y b.

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 ms pequeo de los import java.lang.*;
dos valores float a y b.

public class MathDemo {


public static void main(String[] args) {
// get two float numbers
float x = 9875.875f;
float y = 154.134f;
// 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 ms pequeo de los import java.lang.*;
dos valores int a y b.

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 ms pequeo de los import java.lang.*;
dos valores long a y b.

public class MathDemo {


public static void main(String[] args) {
// get two long numbers
long x = 98759765l;
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 import java.lang.*;
elevado a la potencia de

b : ab

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
que cero y menor que uno 1.0.

import java.util.Random;
public class Programa {
public static void main(String arg[ ]) {
Random

rnd

new

Random();

System.out.println("Nmero aleatorio
real entre [0,1[ : "+rnd.nextDouble());
}

rint(double a)

}
Devuelve el valor double que es import java.lang.*;
ms cercano al valor a y es igual a public class MathDemo {
un entero matemtico.

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

cercano al argumento.

long

}
ms public static double round(double value, int
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 ms cercano public static BigDecimal round(float d, int
al argumento.

decimalPlace) {
BigDecimal

bd

new

BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace,
BigDecimal.ROUND_HALF_UP);
return bd;
signum(double d)

La

funcin

signo,

cero

si

}
el import java.lang.*;

argumento es cero, 1.0 si el public class MathDemo {


argumento es mayor que cero y

public static void main(String[] args) {

-1.0 si el argumento es menor que

// get two double numbers

cero.

double x = 50.14;
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

funcin

signo,

cero

si

}
el import java.lang.*;

argumento es cero, 1.0 si el public class MathDemo {


argumento es mayor que cero y

public static void main(String[] args) {

-1.0 si el argumento es menor que

// get two float numbers

cero.

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));
}

sin(double a)

}
Devuelve el seno trigonomtrico import java.lang.*;
de un ngulo.

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 hiperblico de import java.lang.*;
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 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 raz cuadrada positiva import java.lang.*;

redondeada de un valor double.

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));
System.out.println("Math.sqrt(" + y + ")=" +
Math.sqrt(y));
}

tan(double a)

Devuelve

la

}
tangente import java.lang.*;

trigonomtrica de un ngulo.

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 hiperblica import java.lang.*;
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 import java.lang.*;
radianes al aproximado en grados.

public class MathDemo {


public static void main(String[] args) {
// get two double numbers numbers
double x = 45;
double y = -180;
// 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 import java.lang.*;
grados al aproximado en radianes.

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));
}
ulp(double d)

Ver

definicin

en

documentacin completa.

}
la 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

definicin

en

}
la import java.lang.*;

documentacin 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.

public class Array


{
public static void main(String arg[])

Normalmente

los

elementos

individuales se referencian por

int [] losValores = null;

el valor de un ndice.

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

Int hashCode()

}
Este mtodo devuelve un cdigo import java.lang.*;
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

mtodo

compara

instancia de Boole con otro.

}
esta import java.lang.*;
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 ){
System.out.println( str3 );
}
}
}
Este mtodo devuelve el valor de import java.lang.*;
Byte byteValue()

este byte como un byte.

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
anotherByte)

}
compareTo(Byter Este mtodo compara dos objetos import java.lang.*;
Byte numricamente.

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 ){
System.out.println( str3 );
}
}
Static byte decode(String nm)

Este

mtodo

decodifica

cadena en un byte.

}
una 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");
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 mtodo devuelve el valor de import java.lang.*;


este byte como un doble.

public class ByteDemo {


public static void main(String[] args) {
// create 2 Byte objects b1, b2
Byte b1, b2;
// create 2 double primitives d1, d2
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 mtodo compara este objeto import java.lang.*;
para el objeto especificado.

public class ByteDemo {


public static void main(String[] args) {
// create 2 Byte objects b1, b2
Byte b1, b2;
// 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 ); }
Float floatValue()

}
Este mtodo devuelve el valor de import java.lang.*;
este byte como un flotador.

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 );
}

Potrebbero piacerti anche