0% encontró este documento útil (0 votos)
5 vistas

Apuntes Java

Apuntes sobre Curso de Java

Cargado por

tomastablet
Derechos de autor
© © All Rights Reserved
Formatos disponibles
Descarga como TXT, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
5 vistas

Apuntes Java

Apuntes sobre Curso de Java

Cargado por

tomastablet
Derechos de autor
© © All Rights Reserved
Formatos disponibles
Descarga como TXT, PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 11

ATAJOS (se activan con TAB)

psvm = public static void main (String[] args){}


sout = System.out.println("");

PARA LEER LO QUE INGRESA EL TECLADO

import java.util.Scanner

static Scanner teclado = new Scanner (system.in);


Métodos asociados
variable = teclado.next() //lee el texto del teclado
variable = teclado.nextInt() // Lee un número entero
variable = teclado.nextFloat() // Lee un número con decimal
variable = teclado.nextLine() //permite el uso del espacio en un String.

IMPORTANTE: Si antes se llamo a un nextInt o nextFloat para usar el nextLine hace


falta hacerlo dos veces. Esto es porque queda el "Enter" como último caracter
guardado en el objeto Scanner.

COMPORTAMIENTO DEL .next()


Cada vez que ingresamos un espacio en blanco cuando utilizamos el método next() los
caracteres que siguen al espacio en blanco son recuperados en la siguiente llamada
al método next()

METODO PARA COMPARAR STRINGS


String1.equals(String2)
El método es Case Sensitive.
String1.equalsIgnoreCase(String2)
El método NO es Case Sensitive.

TIPOS DE VARIABLES
int = Enteros
String = Texto
Double = Decimales

TIPOS DE DATOS
PRIMITIVOS
NUMERICOS ENTEROS
byte
short
int
long
NUMERICOS EN PUNTO FLOTANTE
float
double
BOOLEANOS
bool
CARACTERES
char
CADENAS DE CARACTERES
String
VECTORES
Array
NULOS
void
ESTRUCTURADOS (CLASES)
Clases de la biblioteca Estándar de Java
Clases de terceros
Clases propias
ENVOLTORIO (WRAPPER)
TIPOS PRIMITIVOS "ENVUELTOS" EN UNA CLASE
Objetos

CONVERTIR A OTRO TIPO DE DATOS

String uno = "444";


int dos = Integer.parseInt(uno); CONVERTI DE STRING A INTEGER
String tres = String.ValueOf(dos); CONVERTI DE INTEGER A STRING

OPERACIONES ARITMETICAS

int uno = 2;
int dos = 3;

int suma = uno + dos


int resta = uno - dos
int multi = uno * dos
double div = uno / dos
int modulo = uno & dos EL RESTO DE UNA DIVISION

double potencia = Math.pow(2 ,5)


System.out.println(potencia);

o bien

System.out.println(uno + dos);
System.out.println(uno - dos);
System.out.println(uno * dos);
System.out.println(uno / dos);
System.out.println(uno & dos);

int uno = 10;


int uno+= uno; ES LO MISMO QUE uno = uno + uno
int uno+= 30; SUMARLE TREINTA
int uno-=6; Y TODAS LAS OPERACIONES ARITMETICAS

FUNCIONES RELACIONALES (DEVUELVEN TRUE O FALSE)

int uno = 10
int dos = 20

System.out.println(uno == dos); QUIERO SABER SI uno ES IGUAL A dos


System.out.println(uno != dos); QUIERO SABER SI uno ES DISTINTO A dos
System.out.println(uno < dos); QUIERO SABER SI uno ES MENOR A dos
System.out.println(uno > dos); QUIERO SABER SI uno ES MAYOR A dos
System.out.println(uno <= dos); QUIERO SABER SI uno ES MENOR O IGUAL A dos
System.out.println(uno >= dos); QUIERO SABER SI uno ES MAYOR O IGUAL A dos

OPERADOR CONDICIONAL

int uno = 10
int dos = 20

if(uno = dos){
System.out.println("Los números son" + uno + "y" + dos ". Los números son
iguales")
}
else{
System.out.println("Los números son" + uno + "y" + dos ". Los números no son
iguales")
}

OPERADORES LÓGICOS

int uno = 10
int dos = 20
int tres = 30

AND
System.out.println(uno == dos && dos < tres); AMBAS CONDICIONES DEBEN CUMPLIRSE

OR
System.out.println(uno == dos || dos < tres); AL MENOS UNA CONDICION DEBE CUMPLIRSE

XOR (O EXCLUSIVO)
System.out.println(uno == dos ^ dos < tres); SOLO UNA CONDICION DEBE CUMPLIRSE

INVERTIR OPERADOR
System.out.println(!(uno == dos)); SI ES TRUE VA A DEVOLER FALSE Y VICEVERSA

OPERADORES INCREMENTALES

int uno = 1;

uno++; LE AGREGA UNA UNIDAD A LA VARIABLE uno LUEGO DE LEERLA


++uno; LE AGREGA UNA UNIDAD A LA VARIABLE uno ANTES DE LEERLA
uno--; LE RESTA UNA UNIDAD A LA VARIABLE uno LUEGO DE LEERLA
--uno; LE RESTA UNA UNIDAD A LA VARIABLE uno ANTES DE LEERLA

OPERADORES CONCATENACION

String uno = "Tomasson";


int dos = 89

System.out.println(uno + dos) CONCATENA DIFERNTES TIPOS DE DATOS: Tomasson89

OPERADORES DE BITS

<< A << B; DESPLAZA A A LA IZQUIERDA EN B POSICIONES


>> A >> B; DESPLAZA A A LA DERECHA EN B POSICIONES (TIENE EN CUENTA SIGNO)
>>> A >>> B; DESPLAZA A A LA DERECHA EN B POSICIONES (NO TIENE EN CUENTA SIGNO)
& A & B; OPERACION AND A NIVEL DE BITS
| A | B; OPERACION OR A NIVEL DE BITS
^ A ^ B; OPERACION XOR A NIVEL DE BITS
~ A ~ B ; OPERACION COMPLEMENTO A NIVEL DE BITS

PREGUNTAR POR instanceof

ESTRUCTURAS DE CONTROL CONDICIONAL

IF

int uno = 100

if(uno = 99){
System.out.println("ES CORRECTO")
}
else{
System.out.println("NO ES CORRECTO")
}

SWITCH

int uno = 5

switch(uno) {
case 1: System.out.println("El valor es 1");break;
case 2: System.out.println("El valor es 2");break;
case 3: System.out.println("El valor es 3");break;
case 4: System.out.println("El valor es 4");break;
case 5: System.out.println("El valor es 5");break;
case 6: System.out.println("El valor es 6");break;
case 7: System.out.println("El valor es 7");break;
default: System.out.println("El valor no está entre 1 y 7");break;
}

TRY

try{
uno = 4/0;
} catch(Exception e) {
System.out.println(e);
}

CON ESTE CODIGO EL PROGRAMA INFORMA EL ERROR PERO NO SE DETIENE, CONTINUA

ESTRUCTURAS DE CONTROL ITERATIVA

WHILE

int uno = 1;

while(uno<7){

System.out.println("El valor " + uno + " no es suficiente. Sumando una unidad.");


uno++;
}

DO WHILE

do{
System.out.println("El valor " + uno + " no es suficiente. Sumando una
unidad.");
uno++;
}while(uno<7)

FOR

for(int i = 1; i < 10; i++){

System.out.println("El valor es " + i + ". Sumando unidad.")


}

FOR EACH (RECORRIENDO UN ARRAY)


String[]semana = {"Lunes", "Martes"; Miércoles", "Jueves", "Viernes"};

for (String i:semana){

System.out.println(i); ME VA A IMPRIMIR TODOS LOS DIAS DE LA SEMANA


}

FOR CON IF DENTRO

for (int uno=1; uno<=10; uno++){

if (uno==5) { EL IF ROMPE EL FOR Y TERMINA EL ALGORITMO CUANDO uno = 5


break;
}
if (uno > 2 && uno < 4){ EN ESTE CASO SE VA A SALTAR LA ACCION CUANDO uno = 3
continue;
}
}

ARRAYS o VECTORES

Un vector es una estructura de datos que permite almacenar un CONJUNTO de datos del
MISMO tipo.

String[]semana =
{"Lunes","Martes","Miercoles","Jueves","Viernes","Sabado","Domingo"};
String[]semana = new String[7]; ASIGNO CUANTOS ELEMENTOS VA A TENER

ASIGNAR VALORES
semana[0] = "Lunes";
semana[1] = "Martes";
semana[2] = "Miercoles";
semana[3] = "Jueves";
semana[4] = "Viernes";
semana[5] = "Sabado";
semana[6] = "Domingo";

System.out.println(semana[4]); ESTO VA A DAR "Viernes"

PUEDE SER CUALQUIER TIPO DE DATO


int[]ID_producto = {1,2,3,4,5,6};

Es conveniente llenar o imprimir datos de un vectores con un ciclo For, ya que


conocemos la cantidad de campos que tiene el mismo.

LLENAR DATOS DE UN VECTOR


for(int f=0;f<5;f++) {
System.out.print("Ingrese valor del componente:");
sueldos[f]=teclado.nextInt();
}

IMPRIMIR DATOS DE UN VECTOR


public void imprimir() {
for(int f=0;f<5;f++) {
System.out.println(sueldos[f]);
}
}
IMPORTANTE: Se puede usar sueldos.length como atributo para referirse al tamaño del
vector (esto sirve porque si cambiamos el tamaño del vector no hay que cambiar
todos los algoritmos para ajustar ese cambio). También para cuando el tamaño del
vector lo decide el usuario.

HASHTABLE (Tabla con Identificador y Campo)


import java.util.Hashtable;
Hashtable<Integer, String> vendedores = new Hashtable<Integer, String>;

vendedores.put(1,"Marcos");
vendedores.put(2,"Hernan");
vendedores.put(3,"Franco");
vendedores.put(4,"Jose");
vendedores.put(5,"Veronica");

System.out.println(vendedores.get(3));

ARRAYS MULTIDIMENSIONALES

int [][] valores = new int[2][2]; TRES FILAS Y TRES COLUMNAS

valores[0][0] = 1 ;
valores[0][1] = 2 ;
valores[0][2] = 3 ;
valores[1][0] = 4 ;
valores[1][1] = 5 ;
valores[1][2] = 6 ;
valores[2][0] = 7 ;
valores[2][1] = 8 ;
valores[2][2] = 9 ;

System.out.println(valores.get([1][2]) FILA 2 COLUMNA 3 (VALOR = 6)

OTRA FORMA DE INVOCAR UNA TABLA

int[][]valores={{1,2,3}{4,5,6}{7,8,9}};

ARRAYS DENTRO DE ARRAYS (MATRICES)

int[][][]valores={
1{
{1,2,3}{4,5,6}{7,8,9}
}
2{
{10,11,12}{13,14,15}{16,17,18}
}
3{
{19,20,21}{22,23,24}{25,26,27}
}
};

SI QUIERO LLAMAR AL 22
System.out.println(valores.get([2][1][0]));

LOS DATOS EN UNA MATRIZ SE COMPLETAN CON UN FOR ANIDADO

for(int f=0;f<3;f++) {
for(int c=0;c<5;c++) {
System.out.print("Ingrese componente:");
mat[f][c]=teclado.nextInt();
}
}

donde f es la fila y c la columna.

PARA IMPRIMIR SUS DATOS TAMBIEN USO EL FOR ANIDADO

for(int f=0;f<3;f++) {
for(int c=0;c<5;c++) {
System.out.print(mat[f][c]+" ");
}
System.out.println();
}
}

IMPORTANTE: System.out.println(); representa un salto de línea

Las Matrices son OBJETOS y tienen atributos.

matriz.length = cantidad de Filas de la Matriz

CREANDO UNA MATRIZ NUEVA


System.out.print("Cuantas fila tiene la matriz:");
int filas=teclado.nextInt();
System.out.print("Cuantas columnas tiene la matriz:");
int columnas=teclado.nextInt();
mat=new int[filas][columnas];

CREAR MATRICES IRREGULARES


Primero creamos la cantidad de filas dejando vacío el espacio que indica la
cantidad de columnas:
mat=new int[3][];

Luego debemos ir creando cada fila de la matriz indicando la cantidad de elementos


de la respectiva fila:
mat[0]=new int[2];
mat[1]=new int[4];
mat[2]=new int[3];

ARRAYLIST
import java.util.ArrayList; IMPORTO LA CLASE
ArrayList<String> tabla = new ArrayList<String>;

tabla.add("Lunes");
tabla.add("Martes");
tabla.add(2,"Miercoles"); ACA ESTOY DETERMINANDO EL INDICE AL QUE AGREGO EL STRING

System.out.println(tabla.get((2)); ME DA MIERCOLES
System.out.println(tabla.size(); CUANTOS ELEMENTOS TIENE
System.out.println(tabla.contains("Martes"); BUSCAR ELEMENTO EN LA TABLA (ME DA
TRUE O FALSE)
System.out.println(tabla.IndexOf("Martes"); BUSCAR EN QUE INDICE ESTA EL DATO (En
este caso es 1)
System.out.println(tabla.lastIndexOf("Martes"); EMPIEZA A BUSCAR DESDE EL FINAL AL
PRINCIPIO

tabla.remove(1); BORRO MARTES, AHORA MIERCOLES ES INDICE 1


tabla.clear(); LIMPIA TODOS LOS CAMPOS DE LA TABLA

System.out.println(tabla.isEmpty(); SABER SI ESTA VACIA, ME DA TRUE OR FALSE

DOS FORMAS DE COPIAR UNA TABLA


ArrayList tabla2 = (ArrayList) tabla.clone();
ArrayList <String> tabla2 = new ArrayList <String>(tabla);

CONVERTIR ARRAYLIST EN ARRAY


String[] tabla3 = newString[tabla.size()];
tabla.toArray(tabla3)

System.out.println(tabla[1]); VUELVO A PEDIR DATOS COMO EN UN ARRAY

CLASES

LAS CLASES TIENEN PROPIEDADES Y METODOS

EJEMPLO MASCOTA: PROPIEDADES (VARIABLES): NOMBRE, EDAD, PESO


METODOS (FUNCIONES): MOSTRAR NOMBRE, CALCULAR FECHA
NACIMIENTO, COSAS QUE HACE LA MASCOTA

OBJETOS

LOS OBJETOS SON UNA INSTANCIACION CONCRETA DE LA CLASE.

object GATO{
Maga
11
5
}

CREAR CLASE Y ASIGNARLE UN PAQUETE

Click derecho en Proyecto: New > New Java Class... DEFINIMOS NOMBRE Y PAQUETE

PUBLIC es un MODIFICADOR, significa que se puede acceder desde diferentes paquetes.


También puede ser PROTECTED o PRIVATE.

CREAR CLASE
package Paquete1;
public class Producto{

int ID_Producto;
String Nombre_Producto;
double Precio;
}

ESTRUCTURA DE UNA CLASE


class [nombre de la clase] {
[atributos o variables de la clase]
[métodos o funciones de la clase]
[main]
}
CONSTRUCTOR DE OBJETOS DE UNA CLASE

El constructor tiene las siguientes características:

Tiene el mismo nombre de la clase.


Es el primer método que se ejecuta.
Se ejecuta en forma automática.
No puede retornar datos.
Se ejecuta una única vez.
Un constructor tiene por objetivo inicializar atributos.

public Producto(int ID, String nom, double P){ ENTRE PARENTESIS LOS PARAMETROS

ID = ID_Producto
nom = Nombre_Producto
P = Precio
}

CREAR OBJETO

Producto Escoba = new Producto(1,"Escoba Genérica",45.00); ENTONCES ES Clase


Objeto = new Clase(Parámetros);

System.out.println(Escoba.ID_Producto); ME TIENE QUE DAR 1

CREAR METODO

public void remarcar(double NuevoPrecio){ CON VOID LE INDICO QUE NO TIENE QUE
DEVOLVER UN VALOR, SOLO REALIZAR LA ACCIÓN

NuevoPrecio = Precio

Es decir, la estructura es

SI NO RETORNA DATO

public void [nombre del método]([parámetros]) {


[algoritmo]
}

SI RETORNA DATO

public [tipo de dato] [nombre del método]([parámetros]) {


[algoritmo]
return [tipo de dato]
}

USANDO EL METODO

Escoba.remarcar(50.00); LA ESCOBA PASA A VALER 50pe

HERENCIA DE CLASE

public class Clase 1{

String Nombre;
String Apellido;

public class Clase2 extends Clase1{ CON ESTO LE DIGO QUE HEREDE TODOS LOS CAMPOS Y
METODOS DE LA CLASE1, ES DECIR QUEDAN YA DECLARADOS
}

SE PUEDE HEREDAER DE UNA CLASE SOLA

POLIMORFISMO
EL MISMO METODO PUEDE TENER DIFERENTES INSTRUCCIONES EN UNA CLASE QUE LO HEREDA SI
SE ESPECIFICA

CREAR CONSTANTES
final int = 4; SOBRE ESTA CONSTANTE NO SE PUEDE OPERAR

LEER LOS INPUT DEL USUARIO

import.util.Scanner;

System.out.println("Ponga un nombre, por favor.");


Scanner lectura = new Scanner (System.in);
String nombre = lectura.next();
System.out.println(nombre)

System.out.println("Ponga un número, por favor.");


Scanner lectura = new Scanner(System.in);
String nombre = lectura.nextINT();
System.out.println(nombre)

FORMA DE ORGANIZAR UN PROGRAMA QUE PIDE DATOS

- IMPORTO SCANNER
- DECLARO CLASE
- DEFINO VARIABLES
- CREO METODOS QUE CUMPLEN FUNCIONES DE PEDIR DATOS O RESOLVER
- EN EL METODO PRINCIPAL CREO UN NUEVO OBJETO DE LA CLASE y LLAMO A LOS METODOS
PARA RESOLVER EL PROBLEMA.

import java.util.Scanner;
public Class Programa {
private Scanner teclado;
int num1, num2, num3;

public void inicializar() {


teclado=new Scanner(System.in);
System.out.println("Pedir Datos Num1");
num1=teclado.nextInt();
System.out.println("Pedir Datos Num2");
num2=teclado.nextInt();
System.out.println("Pedir Datos Num3");
num3=teclado.nextInt();
}

public void resolver() {


ACA VAN LAS OPERACIONES CON LOS NUMEROS
OPERADORES LOGICOS; NUMERICOS; CONDICIONALES, ETC
System.out.println("LA RESPUESTA ES BLABLA")
}

public static void main (String[] ar) {


Programa numero1;
numero1 = new Programa();
numero1.inicializar();
numero1.resolver();
}
}

METODOS DE LA CLASE STRING

String1.equals(String2) ES UN BOOLEAN
String1.equalsIgnoreCase(String2) ES UN BOOLEAN
String1.CompareTo(String2) ES UN INTEGER da 0 si es menor alfabeticamente >0 si es
mayor alfabeticamente
String1.charAt(int pos) ES UN CHAR, devuelve el caracter que ocupa la posición que
designamos entre paréntesis
String1.length() ES UN INTEGER, cantidad de caracteres del String
String1.substring(int pos1,int pos2) Es otro String. Retorna un recorte entre los
caracteres que designamos para pos1 y pos2
String1.indexOf(String2) ES UN INTEGTER. Retorna -1 si no String2 no esta contenida
en String1. Si esatá contenido retorna la posición donde comienza a repetirse.
String1.toUpperCase()
String1.toLowerCase()

Protected es como Private pero permite que las subclases accedan a esos atriutos.

También podría gustarte