Getting Started

User Input

Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.println(str);
int num = in.nextInt();
System.out.println(num);

Conditionals

int j = 10;
if (j == 10) {
  System.out.println("I get printed");
} else if (j > 10) {
  System.out.println("I don't");
} else {
  System.out.println("I also don't");
}

See: Conditionals

Type Casting

// Widening
// byte<short<int<long<float<double
int i = 10;
long l = i;               // 10
// Narrowing 
double d = 10.02;
long l = (long)d;         // 10
String.valueOf(10);       // "10"
Integer.parseInt("10");   // 10
Double.parseDouble("10"); // 10.0

Swap

int a = 1;
int b = 2;
System.out.println(a + " " + b); // 1 2
int temp = a;
a = b;
b = temp;
System.out.println(a + " " + b); // 2 1

Arrays

char[] chars = new char[10];
chars[0] = 'a'
chars[1] = 'b'
String[] letters = {"A", "B", "C"};
int[] mylist = {100, 200};
boolean[] answers = {true, false};

See: Arrays

Loops

String word = "QuickRef";
for (char c: word.toCharArray()) {
  System.out.print(c + "-");
}
// Outputs: Q-u-i-c-k-R-e-f-

See: Loops

Strings

String first = "John";
String last = "Doe";
String name = first + " " + last;
System.out.println(name);

See: Strings

Primitive Data Types

Data Type Size Default Range
byte 1 byte 0 -128 to 127
short 2 byte 0 -215 to 215-1
int 4 byte 0 -231 to 231-1
long 8 byte 0 -263 to 263-1
float 4 byte 0.0f N/A
double 8 byte 0.0d N/A
char 2 byte \u0000 0 to 65535
boolean N/A false true / false

Variables

int num = 5;
float floatNum = 5.99f;
char letter = 'D';
boolean bool = true;
String site = "quickref.me";

Hello.java

public class Hello {
  // main method
  public static void main(String[] args)
  {
    // Output: Hello, world!
    System.out.println("Hello, world!");
  }
}

Compiling and running

$ javac Hello.java
$ java Hello
Hello, world!
Comments