Java Reference
In-Depth Information
CHAPTER 1
Java Basics
This chapter contains examples that demonstrate the basic syntax of Java; it is
meant to be used in conjunction with Chapter 2 of Java in a Nutshell . If you have
substantial programming experience with C or C++, you should find the material
in this chapter straightforward. If you are coming to Java from another language,
however, you may need to study the examples here more carefully.
The most important step in learning a new programming language is mastering the
basic control statements of the language. With Java, this means learning the if/
else branching statement and the while and for looping statements. Learning to
program well is like learning to do word problems in high-school algebra class:
you have to translate the problem from an abstract description into the concrete
language of algebra (or, in this case, the language of Java). Once you learn to
think in if , while , and for statements, other Java statements, such as break , con-
tinue , switch , and try/catch/finally , should be easy to pick up. Note that
although Java is an object-oriented language, we won't discuss objects until Chap-
ter 2, Objects, Classes, and Interfaces .
So, with that as an introduction, and with mastery of basic syntax as our goal, let's
jump right in and start writing Java programs.
Hello World
As long ago as 1978, Brian Kernighan and Dennis Ritchie wrote, in their classic
topic The C Programming Language , that “the first program to write is the same
for all languages.” They were referring, of course, to the “Hello World” program.
The Java implementation of “Hello World” is shown in Example 1-1.
Example 1−1: Hello.java
package com.davidflanagan.examples.basics; // A unique class name prefix
public class Hello { // Everything in Java is a class
public static void main(String[] args) { // All programs must have main()
 
Search WWH ::




Custom Search