Java Notes

public class Hello {  // the classic starter!

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

}

Most used primative types and wrappers

Primitive Object
int Integer
long Long
double Double
char Char
boolean Boolean

Examples below use string/String variables called w and u:

Python Java Description
w[3] w.charAt(3) Return character at index 3
w[2:4] w.substring(2,4) Return substring 2nd through 3rd index
len(w) w.length() Return the length of the string
w.split(',') w.split(",") Split w at ',' into a list/array
w.split() w.trim().split("\\s+") Split out non-whitespace strings
w + u same as Python Java: One operand can be not a string
w.strip() w.trim() Remove beginning, ending whitespace
w.upper() s.toUpperCase() Return string in uppercase
w.lower() s.toLowerCase() Return string in lowercase
w == u w.equals(u) True if w, u have the same characters
w.replace("me", "I") same as Python Replace all "me" occurences by "I"
w.find('xy') w.indexOf("xy") Index of first "xy", or -1 if none
w.find('xy', 5) w.indexOf("xy", 5) First index >= 5 of "xy", or -1
w.startswith('hi') w.startsWith("hi") True if w starts with "hi"
w.endswith('ing') w.endsWith("ing") True if w ends with "ing"

List methods: Suppose w and w2 are lists of strings --

Python Java Description
value of w[3] w.get(3) Return/get value of item at index 3
w[3] = 'a' w.set(3, "a") Set item at index 3
w.append('a') w.add("a") Append item
len(w) w.size() Return the number of items in the list
w.find('x') w.indexOf("x") Find index of the first occurrence of x, or -1
w += w2 w.addAll(w2) add all of list w2, modifying w
'x' in w w.contains("x") membership test
not bool(w) w.isEmpty() (Python w is True if not empty)
w[:]=[] w.clear() Remove all items
w.pop(2) w.remove(2) remove and return item at index 2
w[2:4] w.subList(2, 4) sub-list that you can iterate over
', '.join(w) String.join(", ",w) return string joined with ", " separators
w.sort() Collections.sort(w) sort according to natural ordering

You can create a Scanner, like new Scanner(System.in). Methods:

Return type Method name Description
boolean hasNext() returns true if more data is present
boolean hasNextInt() returns true if the next token is an int
boolean hasNextDouble() returns true if the next token is a double
Integer nextInt() returns the next token as an integer
double nextDouble() returns the next token as a double
String next() returns the next token as a String
String nextLine() returns all before the next newline

Here is a function to return a new array containing the squares of the numbers in a passed array. See the use of the length attribute:

public static int[] squares(int[] nums)
{
    int n = nums.length;
    int[] sq = new int[n];
    for (int i = 0; i < n; i++) {
        sq[i] = nums[i]*nums[i];
    }
    return sq;
}

It could be called with:

int[] vals = {2, 5, 6, 22},
      vals2 = squares(vals);

Dict/Hashmap

Python Java
d = dict() d = new HashMap<keyType, valueType>()
d[key] = v d.put(key, v)
v = d[key] v = d.get(key) // if key present
v = d.get(key, None) v = d.get(key) // null if key not present
d.keys() d.getKeys()

Print formatted string with fieldwidths, with any a converted to its string representation, and float/double b also with precision:

Python print('{:20} and {:7.2f}'.format(a, b))
Java System.out.format("%20s and %7.2f%n", a, b);

Note %n is needed at the end of the Java format to go on to the next line.

Boolean Operators

Python Java
and &&
or ||
not !

Conditionals in Java

if (condition) {
    statement1
    statement2
    ...
} else {
    statement1
    statement2
    ...
}

Loops and Iteration

for (int i = 0; i < 10; i++ ) { // Java
    System.out.println(i);
}


for (start clause; stop clause; step clause) {
    statement1
    statement2
    ...
}

If s is a sequence (of element type tp in Java)

for e in s:             # Python
  print(e)
for (tp e : s) {          // corresponding Java
    System.out.println(e)
}
while (condition) {  //Java while loop
    statement1
    statement2
    ...
}

Interfaces

public interface Response      // interface, not class
{
    boolean execute(String[] tokens); //public assumed

    String getCommandName();      // ; instead of body

    String help();

}

Heading for class using Response interface:

public class Goer implements Response