Cheat sheet

This cheat sheet is a quick reference guide for some simple Python to Java translations. Try not to overuse this resource. You'll save time if you remember the code instead of always referring back to this sheet.

Concept Python Java
Inline comments
# this is an inline comment
// this is an inline comment
Multiline comments
'''this is
a multiline
comment (or string)'''
/**
 * This is
 * a multiline
 * comment
 * (NOT a string)
 */
Print statements
print("hello")
System.out.println("hello");
Integer variables
w = 3
int w = 3;
Floating point variables
x = 7.89
double x = 7.89;
Boolean variables
y1 = True # capitalized
y2 = False
boolean y1 = true; // all lowercase
boolean y2 = false;
String variables
z = "abc" # double quotes...
z = 'abc' # ...or single - either is fine
String z = "abc"; // must use double quotes
 
If-statements
if x < 10:
    print("x less than 10")

elif x > 10:
    print("x greater than 10")

else:
    print("x equal to 10")
 
if (x < 10) {
    System.out.println("x less than 10");
}
else if (x > 10) {
    System.out.println("x greater than 10");
}
else {
    System.out.println("x equal to 10");
}
While loops
i = 0
while i < 10:
    print(i)
    i += 1 # adds 1 to i
 
print('done')
int i = 0;
while (i < 10) {
    System.out.println(i);
    i ++; // adds 1 to i
}
System.out.println("done");
For loops
for i in range(10):
    print(i)
 
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}
Getting user input
# no imports needed
# no class or main function needed
 
 
user_name = input("What is your name?\n")

print("Your name is", user_name)
import java.util.Scanner;
// everything below needs to be inside
// a class and the main method
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
String userName = sc.nextLine();
System.out.println("Your name is " + userName);
Lists/arrays
x = [1, 2]
x[0] = 55       # x now [55, 2]
x[len(x)-1] = 9 # x now [55, 9]
x.append(6)     # x now [55, 9, 6]
x[1] = "abc"    # x now [55, "abc", 6]
int[] x = {1, 2};
x[0] = 55;              // x now [55, 2]
x[x.length - 1] = 9;    // x now [55, 9]
// can't append, size fixed at 2
// can't do this - all values must be type int