Java vs GoLang

Control Flow

Conditionals

Java

if (x < y) {
    return x;
} else {
    return y;
}

GoLang

if x < y {
	return x
} else {
	return y
}

If with a statement

Java

int five = 5;
int four = 2+2;
if (four < five) {
	return five;
}

GoLang

five := 5
if four := 2+2; four < five {
	return five
}

Switch expression

Java

String language = "French";
switch(language) {
    case "Spanish":
        System.out.println("Buenos dias!");
        break;
    case "French":
        System.out.println("Bonjour!");
        break;
    default:
        System.out.println("Hello!");
}

GoLang

language := "French"
switch language {
	case "Spanish":
		fmt.Println("Buenos dias.")
	case "French":
		fmt.Println("Bonjour!")
	default:
		fmt.Println("Hello!")
}

For loop

Java

int sum = 0
for (int i = 0; i < 10; i++) {
	sum += i;
}

GoLang

sum := 0
for i := 0; i < 10; i++ {
	sum += i
}

While loop

Java

int sum = 1;
while (sum < 1000) {
	sum += sum;
}

GoLang

sum := 1
for sum < 1000 {
	sum += sum
}

Finally clause/defer

Java

void write(String fileName, String text) {
	File file = new File(fileName);
	PrintWriter writer;
	try {
		file.createNewFile();
		writer = new PrintWriter(file)
		writer.println(text);
	} catch (IOException e) {
		throw new RuntimeException(e);
	} finally {
		writer.close(); // finally always executes at the end
	}
}

GoLang

func write(fileName string, text string) {
	file, err := os.Create(fileName)
	if err != nil {
		panic(err)
	}
	defer file.Close() // if WriteString fails, it'll make sure that file is closed
	_, err = io.WriteString(file, text)
	if err != nil {
		panic(err)
	}
}
Java 11 & Go 1.13

GitHub stars

Author: @amarszalek