Learn to code Java

Introduction to Java

Printing to console

Java makes it easy to show messages to the user. In developer terms, this is called "printing output to the console". We simply type the name of the input/output object, IO.

Then we "call" the print function by typing its name print. Finally, we provide what we want to print by typing a "String" value: "Hello World".

IO.print("Hello World");

Reading from console

It's also easy to request information from the user. This is called "reading input from the console". We do this by telling the IO object to readln() or "read a line typed by the user".

var value = IO.readln("Enter text:");
IO.println("Text doubled: " + value + ' ' + value);

Creating UI

Mostly, we interact with our applications through "User Interface". This code shows how to create and show a Button and have it react when clicked.

// Create button, configure, animate register action and show
Button button = new Button("Hello World");
button.setPropsString("Font:Arial 24; Margin:40; Padding:10; Effect:Shadow;");
button.setAnimString("Time: 2000; Rotate: 360");
button.getAnim(0).setLoopCount(3).play();
button.addEventHandler(e -> show(new Label("Stop that")), View.Action);
show(button);

Creating a 3D Chart

Since a picture is worth a thousand words, we sometimes want to communicate with images. This code shows how to generate a 3D Chart.

var x = DoubleArray.fromMinMax(-3, 3);
var y = DoubleArray.fromMinMax(-4, 4);
var z = mapXY(x, y, (a,b) -> Math.sin(a) + Math.cos(b));
var chart = chart3D(x, y, z);
show(chart);

Java UI with Swing

Java also has a full-featured built-in UI library called Swing.

import javax.swing.*;

JFrame frame = new JFrame("Hello World");
frame.setPreferredSize(new java.awt.Dimension(300, 300));
JButton button = new JButton("Hello World");
frame.setContentPane(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);