0% found this document useful (0 votes)
63 views

Java Cheat Sheet

This document contains code snippets demonstrating various Java concepts including: 1) Printing output to the console using System.out.println(); declaring and initializing primitive variables like int and float; and getting user input using the Scanner class. 2) Defining one-dimensional and multi-dimensional arrays; initializing arrays; and traversing arrays using for loops and the length property. 3) The Arrays utility class for sorting, searching, copying, comparing, filling arrays; and converting arrays to strings. 4) Arithmetic, relational, and logical operators; and the instanceof operator.

Uploaded by

pepitaaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Java Cheat Sheet

This document contains code snippets demonstrating various Java concepts including: 1) Printing output to the console using System.out.println(); declaring and initializing primitive variables like int and float; and getting user input using the Scanner class. 2) Defining one-dimensional and multi-dimensional arrays; initializing arrays; and traversing arrays using for loops and the length property. 3) The Arrays utility class for sorting, searching, copying, comparing, filling arrays; and converting arrays to strings. 4) Arithmetic, relational, and logical operators; and the instanceof operator.

Uploaded by

pepitaaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

¡Hola mundo!

Salida por consola Variables Entrada de datos


class HolaMundo { class HolaMundo { int intVar = 100; import java.util.Scanner;
public static void main(String[] arg) { public static void main(String[] arg) { float floatVar = 100.80f;
System.out.println("¡Hola mundo!"); System.out.print("¡Hola mundo!"); String strVar = "Hola"; class Input {
} System.out.println("Otro mensaje"); public static void main(String[] args) {
} } int other;
} final int pi = 3.14; Scanner input = new Scanner(System.in);

Java arrays System.out.print("Dame un número entero: ");


int[] arrayOfInt; Tipos de datos primitivos
int number = input.nextInt();
int[] arrayOfInt = {10, 15, 20, 30, 40}; byte, char, short, int y long
System.out.println("Tecleaste " + number);
int[] arrayOfInt = new int[5]; float y double
}
int value = arrayOfInt[3]; boolean (valores true/false) y void
}
arrayOfInt[3] = 10;
int size = arrayOfInt.length; La clase Arrays
Recorrido de un array import java.util.Arrays;
class Main {
public static void main(String[] arg) { class Main {
int[] myArray = {10, 15, 20, 30, 40}; public static void main(String[] arg) {
int[] array1 = {90, 80, 70, 60, 50, 40, 30, 20, 10};
for (int value: myArray) { Arrays.sort(array1, 3, 6); // [90, 80, 70, 40, 50, 60, 30, 20, 10]
System.out.println(value); Estructuras multidimensionales Arrays.sort(array1); // [10, 20, 30, 40, 50, 60, 70, 80, 90]
} int[][] myArray = {
{10, 15, 20, 30, 40}, int[] myArray = {10, 15, 20, 30, 40};
for (int i = 0; i < myArray.length; i++) { {12, 14, 16, 18}, System.out.println(Arrays.binarySearch(myArray, 15)); // Muestra 1
System.out.println(myArray[i]); {11, 17, 23, 29, 31} System.out.println(Arrays.binarySearch(myArray, 45)); // Muestra -6
} };
} int[] shorter = Arrays.copyOf(myArray, 3)); // {10, 15, 20}
} System.out.println(myArray[1][3]); int[] longer = Arrays.copyOf(myArray, 7)); // {10, 15, 20, 30, 40, 0, 0}

Recorrido de estructuras multidimensionales int[] other = Arrays.copyOfRange(myArray, 2, 5); // {20, 30, 40}
// Recorrido por índices
for (int row = 0; row < myArray.length; row++) { int[] array3 = {10, 15, 20, 30, 40};
for (int col = 0; col < myArray[row].length; col++) { int[] array4 = {15, 10, 30, 40, 20};
System.out.println(myArray[row][col]); System.out.println(Arrays.equals(array3, array4)); // Muestra false
}
} int[] array5 = new int[10]; // {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
Arrays.fill(array5, 1); // {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
// Recorrido por valores Arrays.fill(array5, 4, 8, 2); // {1, 1, 1, 1, 2, 2, 2, 2, 1, 1}
for (int[] row: myArray) {
for (int value: row) { int[] array6 = {10, 15, 20, 30, 40};
System.out.println(value); String string1 = Arrays.toString(array6); // "[10, 15, 20, 30, 40]"
} }
} }
Operadores aritméticos Operador instanceof
public class Test { public class Test {
Operadores relacionales
public static void main(String args[]) { public static void main(String args[]) {
public class Test {
int a = 10; String name = "James";
int b = 20; boolean result = name instanceof String;
public static void main(String args[]) {
int c = 25; System.out.println( result ); true
int a = 10;
int d = 25; }
int b = 20;
}
System.out.println("a + b = " + (a + b) );
System.out.println("a == b = " + (a == b) );
System.out.println("a - b = " + (a - b) ); a + b = 30 a == b = false
System.out.println("a != b = " + (a != b) );
System.out.println("a * b = " + (a * b) ); a - b = -10 a != b = true
System.out.println("a > b = " + (a > b) );
System.out.println("b / a = " + (b / a) ); a * b = 200 a > b = false
System.out.println("a < b = " + (a < b) );
System.out.println("b % a = " + (b % a) ); b / a = 2 a < b = true
System.out.println("b >= a = " + (b >= a) );
System.out.println("c % a = " + (c % a) ); b % a = 0 b >= a = true
System.out.println("b <= a = " + (b <= a) );
System.out.println("a++ = " + (a++) ); c % a = 5 b <= a = false
}
System.out.println("b-- = " + (a--) ); a++ = 10 }
b-- = 11
// Check the difference in d++ and ++d public class Test {
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) ); d++ = 25 public static void main(String args[]) {
} ++d = 27 int a = 10;
} int b = 20;
int c = 0;
Operadores lógicos
public class Test { c = a + b;
System.out.println("c = a + b = " + c );
public static void main(String args[]) { c = a + b = 30
boolean a = true; c += a ;
boolean b = false; System.out.println("c += a = " + c );
c += a = 40
System.out.println("a && b = " + (a&&b)); c -= a ;
System.out.println("a || b = " + (a||b) ); a && b = false System.out.println("c -= a = " + c );
System.out.println("!(a && b) = " + !(a && b)); a || b = true c -= a = 30
} !(a && b) = true c *= a ;
} System.out.println("c *= a = " + c );
Operador condicional (? : ) c *= a = 300
public class Test { a = 10;
c = 15;
public static void main(String args[]) { c /= a ;
int a, b; System.out.println("c /= a = " + c );
a = 10; c /= a = 1
b = (a == 1) ? 20: 30; a = 10;
System.out.println( "Value of b is : " + b ); Value of b is : 30 c = 15;
c %= a ;
b = (a == 10) ? 20: 30; System.out.println("c %= a = " + c );
System.out.println( "Value of b is : " + b ); Value of b is : 20 c %= a = 5
} }
} }
Strings Secuencias de escape
String string1 = "Hola mundo"; \n Nueva línea. Coloca el cursor de la pantalla al inicio de la siguiente línea
char ch1 = 'a’; \t Tabulador horizontal. Desplaza el cursor hasta la siguiente posición de tab
String empty1 = ""; \r Retorno de carro. Coloca el cursor de la pantalla al inicio de la línea actual
String empty2 = new String(); \“ Imprime un carácter de doble comilla
int number = 10; \\ Imprime un carácter barra diagonal
String numberStr = ((Integer) number).toString();

Longitud de una string


String s1 = "esto es una string"; Comparación de strings
Acceso a carácteres y substrings System.out.println(s1.length()); // 18 String s1 = "esto es una string";
String s1 = "Hola mundo"; String s2 = "esto es otra string";
char c1 = s1.charAt(3); // ‘a String s3 = "esto es una string";
System.out.println(s1.equals(s2)); // false
String s1 = "Hola mundo"; Concatenación de strings System.out.println(s1.equals(s3)); // true
String s2 = s1.substring(1, 4); // "ola“ String s1 = "Hola";
String s2 = "mundo"; System.out.println("Hola".equalsIgnoreCase("hola")); // true
String s1 = "Hola mundo"; String s3 = s1 + " " + s2; // "Hola mundo“
String s2 = s1.substring(5); // "mundo" System.out.println(s1.compareTo(s2)); // 6
String s1 = "Hola"; System.out.println(s2.compareTo(s1)); // -6
String s2 = "mundo";
String s3 = s1.concat(" ").concat(s2); // "Hola mundo" También existe la versión .compareToIgnoreCase()

Contención
String s1 = "Hola mundo";
System.out.println(s1.contains("la mu")); // true
System.out.println(s1.contains("casa")); // false

Otras operaciones útiles

Comienzo public boolean startsWith(String chars)


Localización Fin public boolean endsWith(String chars)
String s1 = "Hola, bienvenidos a mi mundo"; Truncar public String trim()
int pos = s1.indexOf("bienvenidos"); // 6 Conv. a Minúsculas public String toLowerCase()
Conv. a Mayúsculas public String toUpperCase()
String s1 = "Hola, bienvenidos a mi mundo"; Dividir public String[] split(String regex)
int pos = s1.indexOf("bienvenidos", 9); // -1 public String[] split(String regex, int limit)

String s1 = "La araña con maña teje la telaraña";


int pos = s1.lastIndexOf("araña"); // 29

String s1 = "La araña con maña teje la telaraña";


int pos = s1.lastIndexOf("araña", 9); // 3
Clases y objetos Visibilidad
class MyClass {} • public.- visible para todo el mundo
MyClass myObject = new MyClass(); • protected.- visible para la clase, sus clases derivadas (subclases) y las clases definidas en el mismo package.
• private.-visible solo para la clase
Atributos de datos de objeto, inicialización
class MyClass { public class MyClass { Atributos de clase
int attribute1; private int attribute1; class MyClass {
int attribute2; private int attribute2; private static int clsAttr = 0;
private int objAttr1, objAttr2;
public MyClass(int value1, int value2) { MyClass(int value1, int value2) {
this.attribute1 = value1; this.attribute1 = value1; MyClass(int value1, int value2) {
this.attribute2 = value2; this.attribute2 = value2; this.objAttr1 = value1;
} } this.objAttr2 = value2;
} }
private int auxMethod(int param) {
class Main { return (this.attribute1 + this.attribute2) / param; public static void setClsAttr(int value) {
public static void main(String[] arg) { } clsAttr = value;
MyClass myObject = new MyClass(10, 15); }
} public int myMethod(int param) {
} return auxMethod(param); public static int getClsAttr() {
Encapsulamiento de datos
} return clsAttr;
class Person {
} }
private String name;
}
Herencia
Person(String name) { class One {} // Superclase class Main {
this.name = name;
public static void main(String[] arg) {
} class Two extends One {} // Subclase MyClass.setClsAttr(3);
System.out.println(MyClass.getClsAttr());
public String getName() { Inicialización de subclases
}
return this.name; class One { // Superclase
}
} int attr1;
Sustitución de métodos (overriding)
public void setName(String newName) { public One(int value) { class ClassOne extends BaseClass { // Subclase
this.name = newName; this.attr1 = value; @Override
} } public String message() {
} } return super.message() + " and then a message from ClassOne";
}
class Main { class Two extends One { // Subclase }
public static void main(String[] arg) { int attr2;
Person aPerson = new Person("Pepe");
Métodos heredados de Object
System.out.println(aPerson.getName()); public Two(int value1, int value2) { Clases abastractas
protected Object clone()
aPerson.setName("Juan"); super(value1); public abstract class Shape {
boolean equals(Object obj)
System.out.println(aPerson.getName()); this.attr2 = value2; public abstract double area();
Class<?> getClass()
} } }
String toString()
} }
Interfaces
public interface IShape {
public double area();
}
La interfaz Cloneable
public class Square implements IShape {
public class CloneableClass implements Cloneable {
double side;
int[] data;
int sum;
Square(double side) {
this.side = side;
CloneableClass() {
}
this.data = new int[]{1, 2, 3, 4, 5};
this.sum = 15;
@Override
}
public double area() {
return side * side;
@Override
}
public CloneableClass clone() throws CloneNotSupportedException {
}
CloneableClass newObject = (CloneableClass) super.clone();
public class Square extends Paralelogram implements IShape, Cloneable{...}
if (data != null) {
newObject.data = this.data.clone();
}

newObject.sum = this.sum; // No necesita clone por ser primitivo


return newObject;
}
}

La interfaz Comparable<T>
public class Pareja implements Comparable<Pareja>{
int a, b;

public Pareja(int a, int b){


this.a= a;
this.b= b;
}

public int compareTo(Pareja o){


if(a > o.a) return 1;
if(a < o.a) return -1;
if(b > o.b) return 1;
if(b < o.b) return -1;
return 0;
}
}

You might also like