How to execute a shell command in Java

    public String executeCommand(String command) {
	StringBuffer out = new StringBuffer();

	Process p;
	try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = "";
            while ((line = reader.readLine())!= null) {
		out.append(line + "\n");
            }

	} catch (Exception e) {
            e.printStackTrace();
	}

	return out.toString();
    }

Fibonacci

Soal untuk membuat algoritma Fibonacci juga banyak ditanyakan sewaktu interview untuk lowongan programmer. Berikut ini contoh code dalam bahasa Java:

package org.paingan.example;

public class Fibonacci {
	public static long fib(int n) {
		if (n <= 1)
			return n;
		else
			return fib(n - 1) + fib(n - 2);
	}

	public static void main(String[] args) {
		int n = 10;
		for (int i = 1; i <= n; i++)
			System.out.println(i + ": " + fib(i));
	}
}

Untuk memperdalam pengertian tentang Fibonacci bisa dilihat di artikel ini.

Bubble Sort

Ketika interview untuk lowongan pekerjaan programmer biasanya sering ditanya tentang Algoritma Bubble Sort. Berikut ini code simplenya menurut Saya:

package org.paingan.example;

import java.util.Arrays;

public class BubbleSort {

	public static void main(String[] args) {
		int number[] = { 24, 21, 6, 8, 33, 33, 54, 11, 7, 9 };

		for (int i = 0; i < number.length; i++) {
			for (int j = 1; j < number.length; j++) {
				if (number[j-1] > number[j]) {
					int tmp = number[j-1];
					number[j-1] = number[j];
					number[j] = tmp;
				}
			}
		}

		System.out.println("result: " + Arrays.toString(number));
	}
}