
















Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!

















(compilar) javac [-classpath camino ] [-d carpeta ] [-g] nombre .java (ejecutar) java [-classpath camino ] nombre_clase argumentos (ejecutar applet) appletviewer url (depurar) jdb nombre_clase (crear documentación) javadoc [-classpath camino ] [-d carpeta ] nombre .java
Comentarios
// Comentarios de una línea
/* Comentarios de varias líneas */
**/**** Comentarios que generan documentación automática */
/** Alumnos de la universidad */ public Vector alumnos;
/**
Declaración de constantes
final = ;
final int MAX_ELEM = 20;
enum { , ..., }
enum estacion { PRIMAVERA, VERANO, OTOÑO, INVIERNO } estacion a = estacion.VERANO;
string1.toUpperCase() // convierte el string a mayúsculas string1.valueOf(numero) // convierte un número a string
String s1 = "hola"; String s2 = "adios"; String s3 = s1 + " y " + s2 + " : " + 2004;
Los tipos de datos envolventes
boolean (^) → Boolean char (^) → Character
int i = 4; // "i" es una variable entera (tipo simple) Integer j = new Integer(5); // "j" es un objeto de la clase Integer (envolvente)
Los tipos de datos vector y matriz
** [];**
** = new [];**
** [][]...[];**
** = new []...[];**
float v[] = new float[10]; // Una dimensión con 10 elementos float M[][]= new float[3][4]; // Dos dimensiones con 3x4 elementos String s[] = {"hola", "adios"}; // Una dimensión con dos elementos inicializados
for (int i = 0; i < v.length; i++) v[i] = i;
for (int i = 0; i < M.length; i++) for (int j = 0; j < M[i].length; j++) M[i][j] = 0;
Las colecciones
<> ;
** = new <>();**
ArrayList miclase = new ArrayList(); miclase.add( new Alumno("Pepe", 5.0) ); miclase.add( new Alumno("Alex", 4.2) ); miclase.add( new Alumno("Pepa", 6.3) ); for (Iterator i = miclase.iterator(); i.hasNext();) { System.out.println( i.next() ); }
Código
instrucción;
instrucción1; instrucción2; ... }
Expresiones y operadores
*(asignación) = (aritmética) ++, --, +, -, , /, % (comparación) ==, ¡=, <, <=, >, >=, !, &&, ||, ?: (bits) &, |, ^, ~, <<, >>, >>> (conversión) (tipo)
Sentencias
if (condicion) { instrucciones; } else { instrucciones; }
if (a != 0) { System.out.println("x = " + -a/b); } else { System.out.println("Error"); }
switch (expresión) { case : instrucciones; [break;] case : instrucciones; [break;] ... [default: instrucciones;] }
switch (opcion) { case 1: x = x * Math.sqrt(y); break; case 2: case 3: x = x / Math.log(y); break; default: System.out.println("Error"); }
context. java.awt Contains all of the classes for creating user interfaces and for painting graphics and images. java.beans (^) Contains classes related to developing beans -- components based on the JavaBeans architecture. java.io (^) Provides for system input and output through data streams, serialization and the file system. java.lang Provides classes that are fundamental to the design of the Java programming language. java.math (^) Provides classes for performing arbitrary-precision integer arithmetic and arbitrary-precision decimal arithmetic. java.net (^) Provides the classes for implementing networking applications. java.nio (^) Defines buffers, which are containers for data, and provides an overview of the other NIO packages. java.rmi (^) Provides the RMI package. java.security (^) Provides the classes and interfaces for the security framework. java.sql (^) Provides the API for accessing and processing data stored in a data source (usually a relational database). java.text Provides classes and interfaces for handling text, dates, numbers, and messages in a manner independent of natural languages. java.util (^) Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array, zip&gzip file compression). javax.accessibility Defines a contract between user-interface components and an assistive technology that provides access to those components. javax.crypto (^) Provides the classes and interfaces for cryptographic operations. javax.imageio (^) The main package of the Java Image I/O API. javax.management (^) Provides the core classes for the Java Management Extensions. javax.naming Provides the classes and interfaces for accessing naming services. javax.net (^) Provides classes for networking applications. javax.print (^) Provides the principal classes and interfaces for the Java TM Print Service API. javax.rmi Contains user APIs for RMI-IIOP. javax.security.auth (^) This package provides a framework for authentication and authorization. javax.sound.midi (^) Provides interfaces and classes for I/O, sequencing, and synthesis of MIDI (Musical Instrument Digital Interface) data. javax.sound.sampled (^) Provides interfaces and classes for capture, processing, and playback of sampled audio data. javax.sql Provides the API for server side data source access and processing. javax.swing (^) Provides a set of "lightweight" components that, to the maximum degree possible, work the same on all platforms. javax.xml (^) Defines core XML constants and functionality from the XML specifications. org.ietf.jgss (^) This package presents a framework that allows application developers to make use of security services like authentication, data integrity and data confidentiality from a variety of underlying security mechanisms like Kerberos, using a unified API. org.omg.CORBA (^) Provides the mapping of the OMG CORBA APIs to the Java TM programming language, including the class ORB , which is implemented so that a programmer can use it as a fully-functional Object Request Broker (ORB). org.w3c.dom (^) Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing. org.xml.sax (^) This package provides the core SAX APIs.
Entrada y salida por pantalla
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); int i = Integer.parseInt(in.readLine());
Scanner in = new Scanner(System.in); String s = in.next(); int i = in.nextInt(); in.close();
System.out.println("Hola " + s + i);
System.out.printf("Hola %s %5d%n", s, i);
Entrada y salida por ficheros
Byte Input Stream Description BufferedInputStream (^) Reads a buffer of bytes from an InputStream, and then returns bytes from the buffer, making small reads more efficient. ByteArrayInputStream (^) Reads bytes sequentially from an array. CheckedInputStream (^) This java.util.zip class computes a checksum of the bytes it reads from an InputStream. DataInputStream (^) Reads binary representations of Java primitive types from an InputStream. FileInputStream Reads bytes sequentially from a file. FilterInputStream (^) The superclass of byte input stream filter classes. GZIPInputStream (^) This java.util.zip class uncompresses GZIP-compressed bytes it reads from an InputStream. InflaterInputStream (^) The superclass of GZIPInputStream and ZipInputStream. InputStream (^) The superclass of all byte input streams. LineNumberInputStream (^) This class is deprecated as of Java 1.1; use LineNumberReader instead. ObjectInputStream (^) Reads binary representations of Java objects and primitive values from a byte stream. This class is used for the deserialization of objects. PipedInputStream (^) Reads bytes written to the PipedOutputStream to which it is connected. Used in multithreaded programs. PushbackInputStream (^) Adds a fixed-size pushback buffer to an input stream, so that bytes can be unread. Useful with some parsers. SequenceInputStream (^) Reads bytes sequentially from two or more input streams, as if they were a single stream. StringBufferInputStream (^) This class is deprecated as of Java 1.1; use StringReader instead. ZipInputStream (^) This java.util.zip class uncompresses entries in a ZIP file. Character (unicode) Input Stream Description BufferedReader (^) Reads a buffer of characters from a Reader, and then returns characters from the buffer, making small reads more efficient. CharArrayReader (^) Reads characters sequentially from an array. FileReader (^) Reads characters sequentially from a file. An InputStreamReader subclass that reads from an automatically-created FileInputStream. FilterReader (^) The superclass of character input stream filter classes. InputStreamReader (^) Reads characters from a byte input stream. Converts bytes to characters using the encoding of the default locale, or a specified encoding. LineNumberReader Reads lines of text and keeps track of how many have been read. PipedReader (^) Reads characters written to the PipedWriter to which it is connected. Used in multithreaded programs. PushbackReader (^) Adds a fixed-size pushback buffer to a Reader, so that characters can be unread. Useful with some parsers. Reader The superclass of all character input streams. StringReader (^) Reads characters sequentially from a string. Byte Output Stream Description BufferedOutputStream Buffers byte output for efficiency; writes to an OutputStream only when the buffer fills up. ByteArrayOutputStream (^) Writes bytes sequentially into an array. CheckedOutputStream (^) This java.util.zip class computes a checksum of the bytes it writes to an OutputStream. DataOutputStream (^) Writes binary representations of Java primitive types to an OutputStream. DeflaterOutputStream The superclass of GZIPOutputStream and ZipOutputStream. FileOutputStream (^) Writes bytes sequentially to a file. FilterOutputStream The superclass of all byte output stream filters. GZIPOutputStream (^) This java.util.zip class outputs a GZIP-compressed version of the bytes written to it. ObjectOutputStream (^) Writes binary representations of Java objects and primitive values to an OutputStream. Used for the serialization of objects. OutputStream (^) The superclass of all byte output streams. PipedOutputStream (^) Writes bytes to the PipedInputStream to which it is connected. Used in multithreaded programs. PrintStream (^) Writes a textual representation of Java objects and primitive values. Deprecated except for use by the standard output stream System.out as of Java 1.1. In other contexts, use PrintWriter instead. ZipOutputStream (^) This java.util.zip class compresses entries in a ZIP file. Character (unicode) Output Stream Description BufferedWriter (^) Buffers output for efficiency; writes characters to a Writer only when the buffer fills up. CharArrayWriter Writes characters sequentially into an array. FileWriter (^) Writes characters sequentially to a file. A subclass of OutputStreamWriter that automatically creates a FileOutputStream. FilterWriter The superclass of all character output stream filters. OutputStreamWriter (^) Writes characters to a byte output stream. Converts characters to bytes using the encoding of the default locale, or a specified encoding. PipedWriter (^) Writes characters to the PipedReader to which it is connected. Used in multithreaded programs. PrintWriter Writes textual representations of Java objects and primitive values to a Writer. StringWriter (^) Writes characters sequentially into an internally-created StringBuffer. Writer (^) The superclass of all character output streams.
File raiz = new File("\"); String [] dir = raiz.list(); for (i = 0; i < dir.length; i++) System.out.println(dir[i]);
Programa principal y argumentos
class { public static void main(String[] args) { instrucciones; } }
// Imprime una palabra (primer argumento) // un número determinado de veces (segundo argumento) class Mensaje { public static void main(String [] args) { if (args.lenght == 2) { for (int i = 1; i <= Integer.parseInt(args[1]); i++) { System.out.println(args[0] + " : " + i); } } } }
class extends Applet { public void init() { instrucciones; } }
import java.awt.; import java.applet.;
public class HolaMundoApplet extends Applet { public void init() { repaint(); }
public void paint(Graphics g) { g.drawString("Hola Mundo!", 25, 25); } }
Clases
class [extends ] { // declaración de atributos visibilidad [modificadores] tipo atributo1 [= valor]; visibilidad [modificadores] tipo atributo2 [= valor];
... // declaración de métodos visibilidad [modificadores] tipo metodo1(argumentos) { instrucciones; } visibilidad [modificadores] tipo metodo2(argumentos) { instrucciones; }
... }
visibilidad = public, protected o private modificadores = final, static y abstract argumentos = declaración de variables separadas por comas
class Complejo { private double re, im;
public Complejo(double re, double im) { this.re = re; this.im = im; }
public String toString() { return(new String(re + "+" + im + "i")); }
public boolean equals(Complejo v) { return((re == v.re) && (im == v.im)); }
public double modul() { return(Math.sqrt(rere + imim)); }
public void suma(Complejo v) { re = re + v.re; im = im + v.im; }
visibilidad [modificadores] tipo metodo(Object ... args) { instrucciones; }
return new Complejo(re + r, im + i); }
public String toString() { return re + " + " + im + "i"; } }
Complejo c1 = new Complejo(1, 3); Complejo c2 = new Complejo(-4, 3.5); c2 = c1.sumar(c2); c2 = c2.sumar(0.5, -4); System.out.println(c1 + "\n" + c2 + "\n");
class nombre_clase {
public nombre_classe(parámetros) { código; }
public nombre_classe(otros parámetros) { código; }
... }
nombre_clase objeto = new nombre_clase(parámetros_constructor);
class Complejo { private double re, im;
public Complejo(double r, double i) { re = r; im = i; } }
class A { public A() { System.out.print("A"); } }
class B extends A { public B() { System.out.print("B"); } }
class Principal { public static void main(String[] args) { B b = new B();
class Complejo { private double re, im;
public Complejo(double re, double im) { this.re = re; // this.re es el atributo, y re el parámetro this.im = im; // this.im es el atributo, y im el parámetro } }
class Actor { private Vector pelicules;
public void inclourePelicula(Pelicula p) { pelicules.add(p); p.incloureActor(this); } }
class clase_hija extends clase_padre { ... }
tipo_retorno metodo_clase_hija(argumentos) { ... ... super. metodo_clase_padre(argumentos); ... }
objeto instanceof nombre_clase
(nueva_clase) objeto
class Persona { private String nombre; private int edad;
public Persona() { }
public Persona(String nombre, int edad) {
return num; }
public void finalize() throws Throwable { num--; super.finalize(); } }
class C { public static void main(String[] args) { Persona p1 = new Persona("Maria"); Persona p2 = new Persona("Alex"); System.out.println(Persona.cuantos()); } }
class Student {
public String name; public double test1, test2, test3;
public double getAverage() { return (test1 + test2 + test3) / 3; } }
...
Student std, std1, std2, std3; std = new Student(); std1 = new Student(); std2 = std1; std3 = null; std.name = "John Smith"; std1.name = "Mary Jones";
clase_padre objeto = new clase_descendiente(parámetros_constructor);
class Complex {
double re, im;
public Complex(double re, double im) { this.re = re; this.im = im; }
// Lo siguiente también podría ser "abstract public void imprimir();"
public void imprimir() { System.out.println(re + " " + im); }; }
class Complex1 extends Complex {
public Complex1(double re, double im) { super(re, im); }
public void imprimir() { System.out.println(re + "+" + im + "i"); } }
class Complex2 extends Complex {
public Complex2(double re, double im) { super(re, im); }
public void imprimir() { System.out.println("(" + re + "," + im + ")");
for (int j = i+1; j < num; j++) if (((Comparable)elementos[i]).compareTo(elementos[j]) > 0) { aux = elementos[i]; elementos[i] = elementos[j]; elementos[j] = aux; } }
public void imprimir() { for (int i = 0; i < num; i++) System.out.println((Imprimible)elementos[i]); } }
class Persona { public String nom; }
class Alumne extends Persona implements Comparable, Imprimible {
public double nota;
public int compareTo(Object o) { return nom.compareTo(((Alumne)o).nom); }
public String toString() { return nom + " " + nota; } }
class Principal {
public static void main(String[] args) {
miVector v = new miVector(5);
Alumne a = new Alumne(); a.nom = "Pepe"; a.nota = 6.7; v.añadir(a);
Alumne b = new Alumne(); b.nom = "Pepa"; b.nota = 7.6; v.añadir(b);
v.ordenar(); v.imprimir(); } }
Applets
import java.awt.; import java.applet.;**
class extends Applet {
// declaración de atributos visibilidad [modificadores] tipo atributo1 [= valor]; visibilidad [modificadores] tipo atributo2 [= valor]; ... // declaración de métodos
visibilidad [modificadores] tipo metodo1(argumentos) { instrucciones; }
public void init() { // método de inicialización (principal) instrucciones; }
public void start() { // método de activación (-> visible) instrucciones; }
public void paint(Graphics g) { // método de visualización (dibujar) instrucciones; }
public void stop() { // método de desactivación (-> invisible) instrucciones; }
public void destroy() { // método de destrucción instrucciones; }
... }
**
...
... código HTML si el navegador no puede ejecutar Java
**
import java.awt.; import java.applet.;
public class PruebaApplet extends Applet { Image logo; AudioClip melodia; TextField cuadroTexto;
public void init() { logo = getImage(getDocumentBase(), "imagenes/Logotipo.png"); melodia = getAudioClip(getDocumentBase(), "Melodia.au"); cuadroTexto = new TextField(20); cuadroTexto.setText("Aquí puedes escribir"); add(cuadroTexto); }
public void start() { melodia.loop(); }
public void paint(Graphics g) { g.drawImage(logo, 0, 0, this); g.drawString(cuadroTexto.getText(), 25, 25); }