HelloJava
In the tradition of introductory programming texts, we will begin
with Java’s equivalent of the archetypal “Hello World” application,
HelloJava.
We’ll end up taking four passes at this example before we’re done
(HelloJava, HelloJava2, etc.), adding features and
introducing new concepts along the way. But let’s start with the
minimalist version:
publicclassHelloJava{publicstaticvoidmain(String[]args){System.out.println("Hello, Java!");}}
This five-line program declares a class called HelloJava and a method called main() . It uses a predefined method called
println() to write some
text as output. This is a command-line program, which
means that it runs in a shell or DOS window and prints its output there.
That’s a bit old-school for our taste, so before we go any further, we’re
going to give HelloJava a
graphical user interface (GUI). Don’t worry about the
code yet; just follow along with the progression here, and we’ll come back
for explanations in a moment.
In place of the line containing the println() method, we’re
going to use a JFrame object to put a
window on the screen. We can start by replacing the println line with the following three
lines:
JFrameframe=newJFrame("Hello, Java!");frame.setSize(300,300);frame.setVisible(true);
This snippet creates a JFrame
object with the title “Hello, Java!” The JFrame is a graphical window. To display it, we
simply configure its size on the screen using the setSize() method and make it visible by calling the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access