Use PC Speaker from Java

Getting the PC speaker to emit a annoying beep might seem to be a quite easy task. And it is provided that you are in a graphical environment such as X.org och MS Windows™. Then using this easy bit of code will do:

package beeptest;

import java.awt.Toolkit;

public class BeepTest {
        public static void main(String[] args) {
                try {
                        Toolkit.getDefaultToolkit().beep();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}

But if you (like me) wants to run a console application Toolkit.getDefaultToolkit().beep(); seems to do nothing. Then the following lines will do (at lest on Linux® based operating systems).

package beeptest;

public class BeepTest2 {
        public static void main(String[] args) {
                try {
                        System.out.print ( "\007" );
                        System.out.flush();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}