whatsthecodeforthat.com

What is this?

As developers we often switch between various languages, and sometimes it’s difficult to remember how to do the little things.

How do I lower-case a string?

What’s the list append function called?

How do I iterate over the key/value pairs of a map?

Speaking of which, what’s the map initialization syntax again?

Don’t sweat it, that’s what whatsthecodeforthat.com is here for, with short snippets reminding you how to handle the small things in various languages. If you don’t see a section, example or language that you need, submit a pull request to help out.

Contents

1. Basics

1.1. Hello, World

go

package main

func main() {
	println("Hello, World")
}

java

public class HelloWorld {

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

}

javascript

console.log("Hello, World");

python

print("Hello, World")

1.2. Primitives

Demonstrates how to declare primitive variables.

go

i := 1
f := 1.0
b := true

java

int i = 1;
float f = 2.0;
boolean b = true;

javascript

var i = 1;
var f = 1.0;
var b = true;

python

i = 1
f = 1.0
b = True

1.3. Comments

Single and multi-line comments.

go

// This is a comment.

java

// This is a comment.

/* 
This is a multi-line comment 
*/

javascript

// This is a comment.

/* 
This is a multi-line comment 
*/

python

# This is a comment.

"""
This is a multi-line comment 
"""

2. Strings

2.1. String Initialization

go

s := "string"

s := `
multi-line string
`

java

String s = "string";

javascript

var s = "string";

python

s = "string"
s = """
multi-line string
"""

2.2. Lower/Upper Case

go

import "strings"

lower := strings.ToLower(s)
upper := strings.ToUpper(s)

java

String lower = s.toLowerCase();
String upper = s.toUpperCase();

javascript

var lower = s.toLowerCase();
var upper = s.toUpperCase();

python

lower = s.lower()
upper = s.upper()

2.3. Substring

go

s[start:end]

java

String substr = s.substring(start, end);

javascript

var substr = s.substring(start, end);

python

substr = s[start:end]

2.4. Index of Substring

go

import "strings"

idx := strings.Index(s, substring)

java

int idx = s.indexOf(substring);

javascript

var idx = s.indexOf(substring);

python

idx = s.index(substring)

2.5. Replace Substring

go

import "strings"

// Replace all occurrences of 'old' using -1...
replaced := strings.Replace(s, old, new, -1)

// ... or specify a limit.
replaced := strings.Replace(s, old, new, 2)

java

String replaced = s.replace(old, new);

javascript

var replaced = s.replace(old, new);

python

# Replace all occurrences of 'old'...
replaced = s.replace(old, new)

# ... or specify a limit.
replaced = s.replace(old, new, 2)

2.6. Parsing an Integer

go

import "strconv"

i, err := strconv.Atoi(str)

java

int i = Integer.parseInt(str);

javascript

var i = parseInt(str);

python

i = int(str)

2.7. Parsing a Float

go

import "strconv"

// For a 32-bit float
f, err := strconv.ParseFloat(str, 32)

// For a 64-bit float
f, err := strconv.ParseFloat(str, 64)

java

float f = Flaot.parseFloat(str);

javascript

var f = parseFloat(str);

python

f = float(str)

3. Arrays

3.1. Array Initialization

Initializing an array with a set of values.

go

Note: Technically the following initializes a slice instead of an array, which will be assumed in all of the following Go examples. Generally, slices are assumed to be used by default rather than arrays in Go.

arr := []type{val1, val2}

java

Type[] arr = {val1, val2};

javascript

var arr = [val1, val2];

python

arr = [val1, val2]

3.2. Iterating Arrays

Looping over each element of an array.

go

for i, val := range arr {
	print(i)
	print(val)
}

java

for (Type val : arr) {
	System.out.println(val);
}

javascript

for (var val in arr) {
	console.log(val);
}

python

for val in arr:
	print(val)

3.3. Array Indexing

Reading and writing to a specific array index.

go

val := arr[0]
arr[0] = val

java

Type val = arr[0];
arr[0] = val;

javascript

var val = arr[0];
arr[0] = val;

python

val = arr[0]
arr[0] = val

3.4. Array Appending

Appending an element to the end of an existing array.

go

arr = append(arr, val)

java

/**
 * The *array* type is of fixed length and cannot be appended 
 * to without first creating a copy with an increased length. 
 * Instead, you can use a `List` or `Set` type such as 
 * `ArrayList` or `HashSet`, in conjunction with the `add` 
 * method, like so:
 */

import java.util.ArrayList;
import java.util.List;

List<Type> list = new ArrayList<Type>();
list.add(val);

javascript

arr.push(val);

python

arr.append(val)

3.5. Joining an Array to String

Join all of the elements in an array into a single string.

go

import strings

strings.Join(arr, ",")

java

String.join(",", arr);

javascript

// Joins elements with a comma-separator by default
var str = arr.join(); 

// Optionally specify the separator
var str = arr.join('\n');

python

",".join(arr)

4. Maps

4.1. Map Initialization

Initializing a map with a set of key-value pairs.

go

m := map[keyType]valueType {
	key1: val1, key2: val2,
}

java

Map<KeyType, ValueType> m = new HashMap<KeyType, ValueType>();
m.put(key1, val1);
m.put(key2, val2);

javascript

var m = {key1: val1, key2: val2};

python

m = {key1: val1, key2: val2}

4.2. Iterating Key-Value Pairs

Looping over each key-value pair of a map.

go

for key, val := range m {
	print(key)
	print(val)
}

java

for (Map.Entry(KeyType, ValueType) entry : m.entrySet()) {
	System.out.println(entry.getKey());
	System.out.println(entry.getValue());
}

javascript

var keys = Object.keys(map);
for (var key in m) {
	var val = m[key];
	console.log(val);
}

python

for key in m:
	val = m[key]
	print(key, val)

4.3. Map Indexing

Reading and writing to a specific map index by key.

go

val := m[key]
m[key] = val

java

ValueType val = m[key];
m[key] = val;

javascript

var val = m[key];
m[key] = val;

python

val = m[key]
m[key] = val

5. Flow Control

5.1. if-statements

go

if condition {

} else if otherCondition {

} else {
	
}

java

if (condition) {

} else if (otherCondition) {

} else {
	
}

javascript

if (condition) {

} else if (otherCondition) {

} else {
	
}

python

if condition:

elif otherCondition:

else:

5.2. for-loops

go

for i := 0; i < 10; i++ {
	print(i)
}

java

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

javascript

for (var i = 0; i < 10; i++) {
	console.log(i);
}

python

for i in range(10):
	print(i)

5.3. while-loops

go

for condition {
	
}

java

while (condition) {
	
}

javascript

while (condition) {
	
}

python

while condition:

6. Functions

6.1. Function Declaration

Defining a function that accepts parameters and returns value(s).

go

func customFunc(param1 type1, param2 type2) (returnType1, returnType2) {
	return returnValue1, returnValue2
}

java

public ReturnType customFunc(Type1 param1, Type2 param2) {
	return returnValue;
}

javascript

function customFunc(param1, param2) {
	return returnVal1, returnVal2;
}

python

def custom_func(param1, param2):
	return returnVal1, returnVal2

6.2. Function Invocation

Invoking a function with parameters and receiving returns value(s).

go

val1, val2 := customFunc(param1, param2)

java

val1 = customFunc(param1, param2);

javascript

val1, val2 = customFunc(param1, param2);

python

val1, val2 = customFunc(param1, param2)

7. Custom Types

7.1. Class/Struct Definition

Definition of a class or struct type.

go

type CustomType struct {
	Field1 Type1
	Field2 Type2
}

java

public class CustomType {
	Type1 Field1
	Type2 Field2
}

javascript

class CustomType {
	constructor(field1, field2) {
		this.field1 = field1;
		this.field2 = field2;
	}
}

python

class CustomType:
	def __init__(self, field1, field2):
		this.field1 = field1
		this.field2 = field2

7.2. Instance Methods

go

func (c CustomType) customFunc(param1 type1, param2 type2) (returnType1, returnType2) {
	return returnValue1, returnValue2
}

java

public class CustomType {
	public ReturnType customFunc(Type1 param1, Type2 param2) {
		return returnValue;
	}
}

javascript

class CustomType {
	customFunc(param1, param2) {
		return returnVal1, returnVal2;
	}
}

python

class CustomType:
	def custom_func(self, param1, param2):
		return returnVal1, returnVal2