left-icon

Java Succinctly® Part 1
by Christopher Rose

Previous
Chapter

of
A
A
A

CHAPTER 3

Writing Output

Writing Output


Code Listing 3.0 shows the code to a basic “Hello, World!” application. The program prints some text to the console, then it exits. The numbers on the left side are included for reference and should not be typed into your code. Type or paste this code over the code in the MainClass.java file we created earlier.

Code Listing 3.0: Printing Output

1: public class MainClass { // Definition of MainClass

2: public static void main(String[] args) { // main method entry point

3:     System.out.println("This is a test application!");

4:     } // Close brace for main method.

5: } // Close brace for MainClass.

When we execute this code with either Debugging or Running (use keys F11 or Ctrl+F11, or click the debug or run buttons), the program will print “This is a test application!” to the system output.

Line 1: public class MainClass. This line declares a class called MainClass. The class is marked with the public modifier, which means it is visible to all other entities and packages in the application. After the public modifier, we use the keyword class, then we supply a unique name for our new class—MainClass, in this instance. This is followed by a curly brace, {, that indicates the beginning of the body of the class. Line 5 contains the matching closing curly brace, }, that marks the end of the body of this class.

Line 2: On line 2 we declare a static member method called main. The method is marked public, so that classes outside of this one are able to call it. The method is marked static, which means it belongs to the class rather than to any particular instance of the class. The method does not return any data to the caller, so the return type is void. In the brackets, the (String[] args) is the parameter list. This means an array of strings will be passed to this method when it is invoked. The array of strings is the command-line argument—when we run a program from the command line, we can optionally supply extra arguments. We will not be using the command line, and this array will always be empty in the example programs. After the parameter list, we see an open curly brace, {, that marks the beginning of the body for this method. The matching close brace for the main method is on line 4.

Line 3: This line invokes the println method, which belongs to the System.out class. System.out is a class, and println is a public static method belonging to the class. The method takes a String parameter and prints the string to the console output. The string is enclosed in brackets that indicate that it is a parameter to the method call. The parameter is a String because it is enclosed in double quotes. The line ends with a semicolon “;” that indicates that the statement is finished. All statements in Java end with a semicolon.

Line 4: This is the matching closing brace for the main method. The opening brace appeared on line 2. This brace indicates that we have finished describing the method.

Line 5: This is the matching closing brace for the MainClass class. The opening brace appeared on line 1. This brace indicates that the description of the MainClass is finished.

Don’t worry if some of these previous descriptions are too brief. We will look further into each of the keywords and other mechanisms as we progress through this book. Initially, Java has a fairly steep learning curve. In order to begin programming Java, even the most basic program contains a lot of syntax (syntax is the grammar of a programming language—the rules, spelling, and punctuation).

The name of the class can be any valid identifier. Valid identifier names contain letters and digits, but they cannot begin with a digit. Identifiers must be a single word (no spaces, tabs, or punctuation of any kind is allowed), but you are able to use the underscore character, e.g., Main_Class is a legal identifier, but “Main Class” is not because it contains a space.

When you run or debug the application from Code Listing 3.0, you will notice that message is printed to the Console panel at the lower portion of Eclipse, as per Figure 18.

Code Listing 3.0 Output

Figure 18: Code Listing 3.0 Output

Foundations of Java

In this section, we will briefly look at several aspects of programming Java that will become second nature as you become more accustomed to the language.

White space

White space is the use of space within code. This includes new lines, spaces, and tabs. Generally speaking, the Java compiler ignores white space, and programmers can lay out code however they wish. There are exceptions to this rule—for instance, in Strings, the compiler preserves the spaces because there is a big difference between the two strings: This is a variable and Thisisavariable.

Code Listing 3.1: White Space

c.setRadius(100);

c .        setRadius

(     100

)

;

Code Listing 3.1 shows two calls to the same method: c.setRadius(100); (this is a code snippet and has no main method—this code will not execute as an application). The compiler will read these two calls as being identical even though the second has a lot of white space and is very difficult to read.

Although white space is generally ignored by the compiler, we cannot break up tokens. The symbols used to express elements of the language are called tokens, and if we place white space between the characters of tokens, the compiler will not understand what we mean. For example, the term setRadius in Code Listing 3.1 is a token. If we place a space between the two words to create set Radius, it no longer forms a single token, but rather two. Likewise, we cannot place white space in the middle of numerical literals. For example, 150 is a single token meaning one hundred and fifty, but 1 50 is two tokens meaning one and fifty.

The use of white space is closely tied to programming style. There is no correct or best way to set out code, and no best way to use white space. For the code in this e-book, I have adopted common conventions used by many Java programmers that create code that is easy to read and debug. If you are new to programming, try to match the bracing and tabbing I have used here. This style of bracing and tabbing is very common, and if you are familiar with coding and reading it, you will have little trouble understanding other programmer’s code.

Tip: Learn to read and program in any style. How best to use white space is a hotly debated topic in many programming communities. But, as programmers, we need to read and understand other people's code, and we often need to program in teams in which the use of white space must be the same for all programmers. A programmer who can read anybody's code and can flip to any style without hesitation is far more valuable than one who argues about tabs versus spaces.

Identifiers

An identifier is a name a programmer selects to represent some entity or mechanism in the code. We select identifier names for our variables, methods, classes, and objects. In Code Listing 3.1, the terms MainClass, main, and args are all identifiers. System, out, and println are also identifiers—they were named by the folks who programmed the Java libraries.

When we select an identifier, we must ensure that it is unique to the current scope (or unique to the current code block—we will look later at scope and code blocks in detail). We cannot name two variables myVariable in a single code block because the compiler has no way of knowing which variable we are trying to reference (however, we will see that there is a scope operator that enables us to bend this rule slightly!).

We are not allowed to name our identifiers after keywords (see the next section for a description of keywords). For instance, we cannot name our methods or variables if or while. Again, this comes down to the fact that the compiler needs to differentiate keywords from identifiers, and it cannot do this if the identifiers have the same names as the keywords.

Identifier names cannot contain any white space (this includes spaces, tabs, and new lines). Identifier names must be a single, unbroken word. Identifier names can contain letters, digits, the dollar sign, $, and underscores, “_”, but they cannot begin with a digit. The compiler sees any token beginning with a digit as a numerical literal, and it will not allow us to name our identifiers things such as 67Hello because this would mean the number 67 with the meaningless suffix Hello.

Identifier names are case sensitive, which means the identifiers patientData, PATIENTdata, and patientdata are all seen as distinct by the compiler. Naming multiple identifiers that differ only in case is not recommended because this can lead to confusing and difficult-to-read code, although the compiler will have no trouble differentiating the identifiers.

Example identifiers are: someVariable, i, the_timer_for_rendering_graphics, iterator15, MY_CONSTANT, $euclideanDistance.

In Java, developers often use a technique called Camel Case for naming our identifiers. In Camel Case, the first letter of each of word is uppercase—except for the very first letter. For instance, a function for computing a score might be called computeScore, and a variable for summing a total of ages might be called sumTotalAges.

An exception to this rule of thumb is naming classes. When naming classes, Java programmers often use uppercase for the first letter of all words, including the first. A class for holding an automaton's generation grid might be called AutomatonGenerationGrid. This makes variables and classes easy to distinguish in the code. In Code Listing 3.1, the identifiers MainClass, System, and String are all classes, which means they begin with an uppercase letter. Whereas the identifiers args, out, and println are variables and method names, so they begin with a lowercase letter.

In addition to Camel Case, it is common to name final variables (similar to constants in other languages) with all capital letters. A final variable is simply a named value that cannot be changed, such as the mathematical variables PI or E. Because programmers use uppercase for all letters, when naming constants, it is common to split the words by using the underscore for spaces. A final variable for seconds per hour might be called SECONDS_PER_HOUR, or a final variable for the number of days in June might be called NUMBER_OF_DAYS_IN_JUNE or simply DAYS_IN_JUNE.

One final rule of thumb when naming identifiers—identifiers should be named logical, descriptive names in order to ensure that the code remains as readable as possible. For example, it is generally a better idea to name a variable marginOfError rather than mOE or m;, and it is better to name a function computeMedianOfHouses rather than doThing or cabbagesWithWhippedCream (assuming the function computes the median of houses). If we do not name our identifiers with logical, easy-to-understand names, other programmers might have difficulty comprehending and maintaining our code. And worse—we will not understand our own code, either. It is surprising how little time it takes before our own code becomes gibberish unless we are careful and name our identifiers intelligently.

Note: There are a few exceptions to naming identifiers with logical and descriptive names. For instance, it is common to call iterators (counter variables) in for loops single letter names such as i, j, x, y, or z. This provides no indication as to what the variable means, but their purposes will still be understood by other programmers. Also, some algorithms have specific variable names in their descriptions, and the common names for the variables are often used when programming an implementation of the algorithm, such as the A* path-finding algorithm, which uses the names t and h.

Keywords

Computer programming languages are very simple compared to human languages such as English. Java has a small collection of grammatical symbols (such as { and } braces) and a small collection of nonlexical terms called keywords. And Java has a series of rules for how to use these elements (i.e. it has a grammar). In Eclipse, we can identify keywords in our code because they are highlighted in dark purple, and they are bold, such as class and public in Code Listing 3.1.

Keywords form the main backbone of the way Java works. Keywords are reserved for specific uses in Java, and they cannot be used as identifier names. See the Appendix for a reference on the available keywords. The following is a list of the keywords we have encountered so far:

public: The public keyword is an access modifier. It means that external objects (objects that are not part of the class being defined) can access the methods or member variables.

class: The class keyword is used to indicate that the code block that follows is a description of a class.

static: The static keyword marks member methods and variables as belonging to the entire class rather than specific objects or instances of the class. This means we can access static members without creating objects from the class.

void: The void keyword is used as a placeholder for a return type when a method does not return any data. All methods must have a return type or must have the return type of void. The only exception to this rule is constructors that have no return type and have the same name as the class.

Dot operator

In Code Listing 3.1, line 3 reads as follows: System.out.println("This is a test application!");. This line contains several periods (or full stops). This is the dot operator (sometimes called the scope operator). It is the operator that connects classes to methods and member variables. System is a class, and out is an entity belonging to the System class. When we supply the terms System.out connected by the dot operator, we are saying, “The out entity that belongs to the System class” or, in short, “System's out.

The method println belongs to the out entity. When we invoke the method by specifying its name, System.out.println, followed by a parameter list, ("This is a test application!"), we are really saying: Execute the code specified in the method called println, which belongs to the entity out, which belongs to the class System. Notice how the dots indicate ownership from left to right—System owns out, and out owns println.

We will later look in more detail at object-oriented programming, but the main objective of object-oriented programming is to define hierarchies of objects, each owned by and potentially owning more objects, and each capable of performing methods with a collection of member variables. Different classes can contain variables and methods with the same names. For example, we might have multiple variables called cost, one belonging to a class called House and another belonging to a class Vehicle. We can distinguish these variables by using the dot House.cost vs. Vehicle.cost.

Comments

Code Listing 3.2 shows several comments, with the Eclipse highlights comments in green. A comment is a note to the programmer. The computer will ignore all comments when the program executes. There are many applications for comments, and every programmer has a unique style of commenting on his or her code. Although comments do not change the way a program runs, developing good commenting skills is extremely important. Comments allow a programmer to describe exactly what the code should be doing. This means that any other programmer should be able to read the comments and understand the implications of complex code at a glance.

In Java, there are two types of comments—single-line comments and multiline (or block) comments (see Code Listing 3.2).

Code Listing 3.2: Comments

// This is a single-line comment!

System.out.println("Press a key to continue..."); // Single-line comment!

/*

This is a multiline comment. It extends from the opening symbol of a slash and

star to the closing symbol, a star followed by a slash!

*/

Code Listing 3.2 shows the two different types of comments. The first is the single-line comment. These begin with two slashes, //. All text to the right of the // is ignored by the computer. If a line of code begins with the //, the entire line is ignored, but you can also place the // after some statements, such as a println.

The multiline comment begins with /* and extends until the */. The programmer can place any text inside the /* and */, including new lines. This is sometimes called a block comment because it enables a programmer to write blocks of text or to comment out blocks of code.

In the upcoming code examples, we will see many comments included to help the reader identify what the different lines of code are supposed to do.

Challenges

Challenge 3.0: Change the identifier args so that it is called arguments. Does the program compile and run?

Challenge 3.1: Change the identifier main to mainMethod. Does the program compile and run?

Challenge 3.2: Change the message that is printed to the screen to the string “Hello, World!”.

Challenge 3.3: Change the name of the class MainClass to MyClass. Does the program compile and run?


Challenge solutions

Challenge 3.0

The program compiles and runs when the args identifier is changed to arguments because this identifier is simply a parameter to the main method. Its name is up to the programmer.

Code Listing 3.3: Challenge 3.0

public class MainClass {

public static void main(String[] arguments) {

System.out.println("This is a test application!");

}

}

Challenge 3.1

The program does not compile and run if we change the main method’s name to mainMethod, because the JVM needs an entry point to the program and it searches for a method called main. When it cannot find such a method, it will not run the application.

Code Listing 3.4: Challenge 3.1

public class MainClass {

public static void mainMethod(String[] args) {

System.out.println("This is a test application!");

}

}

Challenge 3.2

Code Listing 3.5: Challenge 3.2

public class MainClass {

public static void main(String[] args) {

System.out.println("Hello, World!");

}

}

Challenge 3.3

The program will not compile and run if the name of MainClass is changed to MyClass without the name of the file (in which the code is written) also changing. In Java, classes should be placed into source code files with the same names.

Code Listing 3.6: Challenge 3.3

public class MyClass {

public static void main(String[] args) {

System.out.println("This is a test application!");

}

}

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.