Java Reference

Variables and operations

Standard datatypes

int a = 1; 
long l = 1;
float f = 1.0;
double d = 1.0;
String s = "hello"; 
boolean b = false;

Printing

System.out.print()
System.out.println()

System.out.println("Hello world"!);

String message = "Hello world";
System.out.println( message );

Input

String input

java.util.Scanner reader = new java.util.Scanner(System.in);
String t = reader.nextLine();

Numeric input

java.util.Scanner reader = new java.util.Scanner(System.in);

System.out.print("Type a number:");
int i = reader.nextInt();

System.out.print("You typed ");
System.out.print( i );
System.out.print(", the next number is ");
System.out.println( i+1 );

Numerical operations

int a = 5;
int b = 4;
System.out.println( a + b );		// addition
System.out.println( a - b );		// subtraction
System.out.println( a * b );		// multiplication
System.out.println( a / b );		// division
System.out.println( a % b );		// modulus (remainder)

Integer v Float devision
Determined automatically based on the datatypes.

int a = 20;
int b = 6;
System.out.println( a / b );
System.out.println( a % b );

double c = 20;
double d = 6;
System.out.println( c / d );
System.out.println( c % d );

PEMDAS

System.out.println( 2 + 4 * 3 );		// 14 or 18?

Casting (converting between datatypes)

int num = Integer.parseInt( str ); 	// String to int
int num = (int)Math.round( d1 );		// double to int

double d1 = Double.parseDouble( str ); 	// String to double
double d1 = (double)i; 			// int to double

String str = Integer.toString( num ); 	// int to String
String str = Double.toString( d ); 	// double to String

String functions

String s1 = "hello";
String s2 = "What does the fox say?";

s1.length();           		// 5
s1.charAt(0);          		// "h"
s1.codePointAt(0);     		// 104 (unicode)
s2.indexOf("fox");     		// 14
s2.lastIndexOf("fox"); 		// 14
s2.substring(14,17);   		// fox
s2.replace("fox","goat");	// What does the goat say?
s2.toUpperCase();		      // WHAT DOES THE FOX SAY?
s2.toLowerCase();		      // what does the fox say?
    
String s3 = "Hi there! " + s2; 	// concatenation

String[] words = s2.split(" ");  // ["What","does","the","fox","say?"]

Want to change an individual letter inside a string? Unlike other languages, you can not do str[2] = 'x' or similar. Java Strings are immutable (unchangeable). Most "simple" solution...

String myName = "halftime";
myName = myName.substring(0,4) + 'x' + myName.substring(5);
System.out.println(myName);			// halfxime

Conditional execution

Numeric comparisons

(a == b)				IS EQUAL TO
(a != b)				IS NOT EQUAL TO
(a < b)				  IS LESS THAN
(a <= b)				IS LESS THAN OR EQUAL TO
(a > b)				  IS GREATER THAN
(a >= b)				IS GREATER THAN OR EQUAL TO

String comparisons

** Equality check **

Objects.equals(s1, s2)		// USE THIS
s1.equals(s2)	        		// OLD METHOD YOU'LL SEE USED ONLINE

** Comparing order **

s1.compareTo(s2)

== 0 when string values match
== negative when s1 is alphabetically 1st
== positive when s1 is alphabetically 2nd

Multiple comparisons

( condition1 && condition2 )		// AND
( condition1 || condition2 )		// OR
(! condition1 ) 				        // NOT

If construct

if ( condition ) {
   doSomething;
   doSomething;
} else if ( condition ) {
   doSomething;
   doSomething;
} else {
   doSomething;
   doSomething;
}

For construct

for ( initialization ; comparison ; iteration ) { 
   instructions();
}

While construct

while ( comparison ) { 
   instructions();
}

For each construct

Arrays & array lists

Declaring static arrays: Method 1

int[] primes = new int[10];
primes[0] = 1;
primes[1] = 2;
primes[2] = 3;
primes[3] = 5;
primes[4] = 7;
primes[5] = 11;
primes[6] = 13;
primes[7] = 17;
primes[8] = 19;
primes[9] = 23;

Declaring static arrays: Method 2

int[] primes = {1,2,3,5,7,11,13,17,19,23};

For loop thorugh an array

for (int item : primes) {
   System.out.println( item );
}

for (int i=0; i<primes.length; i++) {
   System.out.println( primes[i] );
}

Static array comparisons

import java.util.Arrays;

// Check if two arrays are filled with matching values
if ( Arrays.equals( primes, other )) {
    System.out.println("The two arrays match");
}

// Sort an array in ascending order
Arrays.sort( primes );

// Create a string listing the contents of the array
// output: [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
System.out.println( Arrays.toString( primes ));

ArrayList: Declaring

ArrayList<String> alist = new ArrayList<String>();
alist.add("first");
alist.add("second");
String item = alist.get(2);
int size = alist.size();
alist.remove(3);			// Remove 4th item (index==3)
Collectionssort(alist);

ArrayList: Converting between static arrays

** Array to ArrayList **

ArrayList arrlist = new ArrayList<>(Arrays.asList(arr))

** ArrayList to Array **
(assuming it is String… change as appropriate)

String[] arr = (String[])arrlist.toArray(new String[arrlist.size()]);

Example: Load file to ArrayList

One line per string

include java.io.File;
include java.utils.ArrayList;
include java.utils.Scanner;
...
File f = new File("/path/to/filename.ext");
Scanner reader = new Scanner(file);
ArrayList<String> content = new ArrayList<String>();
while (reader.hasNextLine()) {
   content.add(reader.nextLine());
}
reader.close();

Functions

public static returnType functionName(paramType param1, … ) {
   // insert code
   return value;
}

Example: Load file

public static String[] getFileAsArray( String filename ) {
   try {
      File f = new File(filename);
            Scanner reader = new Scanner(f);
            ArrayList<String> content = new ArrayList<String>();
            while (reader.hasNextLine()) {
               content.add(reader.nextLine());
            }
            reader.close();
            return((String[])content.toArray(new String[content.size()]));
        } catch (Exception e) {
           System.out.println("ERROR processing file "+filename);
             System.out.println(e.getMessage());
             return(new String[0]);
        }
}

public static void main(String[] args) {
   String[] words = getFileAsArray("dictionary.txt");
     for (String word : words) {
        System.out.println(word);
        }
        System.out.println("There were "+words.length+" words!");
}

Classes & objects