Show Menu
Cheatography

Java Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Hello World

public class HelloPrinter
{
    public static void main (String[] args)
        {
         System.out.println ("Hello, World!");
     }
 }

Data Types

int
-123 ,10
double
235.13
char
'U'
boolean
true, false
String
"­Hello World"

Strings

charAt //returns char value from string
Position of last character is always 1 less than length of string. 

// Extracts Substrings
str.substring (start, pastEnd)

// Compares strings
if (string1.equals(string2))
 

Statements

If Statem­ent
 if ( expre­ssion ) {
  ­ ­st­ate­ments 
 } else if ( expre­ssion ) {
  ­ ­st­ate­ments
 } else {
  ­ ­st­ate­ments
 }

While Loop
 while ( expre­ssion ) {
  ­ ­st­ate­ments
 }

For Loop
 for ( int i = 0; i < max; ++i) {
  ­ ­st­ate­ments
 }
 

Arithmetic Operators

x + y
add
x - y
subtract
x * y
multiply
x / y
divide
x % y
modlus­/re­mainder
x++
increment
   
x--
decrement
x == y
equal
x != y
not equal

Boolean

!x
not
x&­&y
and
x||y
or

Input and Output

// Imports Scanner class
import java.util.Scanner;

// Obtains scanner object 
Scanner in = new Scanner (System.in);

// Reads values
int bottles = in.nextInt();
double price = in.nextDouble();
String name = in.next();
String lines = in.nextLine();

// Output to user
System.out.print ();
System.out.println();

// Formatted Output to 2 digits after integer
System.out.printf("Price per ounce: %8.2f", priceperounce);