Chapter 1. Elements of Programming
This document rehashes material covered in “Chapter One Elements of Programming” of Computer Science, An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. Do not use this document as a substitute for reading Sedgewick and Wayne’s excellent book. Do note that some information not covered in the textbook or not covered in chapter 1 and a few prompts to help you test your understanding of the material are provided here.
Contents
1.1 Your First Program | Prompts
1.2 Built-in Types of Data | Prompts
Prompts for Section 1.1
- The authors of Computer Science, An Interdisciplinary Approach divide the process of developing a Java program into three steps. What are those three steps?
- What is source code?
- What effects do comments have on a computer program?
- Describe the simplest Java program you can write that will both compile and execute successfully.
- What are some rules for naming Java source code files?
- What is the significance of the word
public
when it appears (or does not appear) immediately before the wordclass
in a Java program? - Describe the purpose and usage of the programs
javac.exe
,java.exe
, andjavadoc.exe
. - How are parameters and arguments related, and how are they different?
- Write a Java program that prints the string “Goodnight, Moon.”
- Write a Java program that uses a command line argument.
- Why is the parameter of a Java program’s
main
method namedargs
instead of, say,arg
or something else altogether?
Section 1.1 Your First Program
To program in Java, you need to:
- Create a program.
- Compile the program.
- Execute or run the program.
Creating a Java program
A Java program is defined by a collection of text files that contain Java source code.
Source code is a sequence of characters arranged “just so” so that other programs, when executed, can interpret the code and direct the actions of a computer or translate the code from one language into another. Programs that translate source code from one language into another language are call compilers. Output produced by a compiler can be a program expressed (or very nearly expressed) in a language that a particular piece of hardware — a computer or, more specifically, a computer’s central processing unit (CPU) — understands, or it may be a program written in a language that can be either interpreted or compiled yet again. Regardless of how it eventually happens, the ultimate goal of all computer programs is to instruct a computer to perform certain actions. Just as there are many spoken languages that people use to express themselves, there are many different programming languages that programmers can use to make their intentions known to a computer via source code.
The simplest Java program that not only compiles but also successfully runs must include a Java class with a main method stored in a file with a .java
filename extension.
For example, the following Java source code snippet saved in a file named Bar.java
defines a Java program, albeit an impotent one, that can be successfully compiled and executed.
class Foo { public static void main(String[] args) { // This program has comments but no instructions. /* This line of text and the previous one are comments. */ } }
Inserting the word public
followed by a space before the word class
in the code snippet above changes the Java program in more and less obvious ways.
The word public
is a class modifier that affects whether classes defined in other source code files can access the class.
Class declarations that begin with the public
modifier must be stored in a file with a .java
extension that has the same name as the public class;
therefore, there can only be one public class per source code file. (Convince yourself of this fact by performing experiments.)
For example, the following code must be stored in a file named Foo.java
; otherwise, the compiler will report an error and the program will not compile.
public class Foo { public static void main(String[] args) { // This class must be saved in a file named Foo.java. } }
Source code may include comments that have no bearing on the actions a computer takes as a result of the way the program is written.
However, comments can be processed by programs that produce byproducts like specially formatted program documentation.
The following Java code snippet includes a special type of comment called a javadoc comment that tells the javadoc.exe
program
to produce documentation formatted in HTML (hypertext markup language) for the class the comment precedes.
/** * The <a href="https://en.wikipedia.org/wiki/Foobar"><code>Foo</code></a> * class is a demonstration of a simple Java class that must be stored in a * file named Foo.java since the class is declared to be <code>public</code>. */ public class Foo { public static void main(String[] args) { // Not much to see and nothing to do here. } }
The JDK
“The” Java Development Kit (JDK) includes two essential programs, javac.exe
and java.exe
,
and many optional ones (e.g. javadoc.exe
) that can be used to program in Java.
These programs are stored in the bin
directory of the directory where the JDK package is installed.
The full pathname of the bin
directory associated with a particular JDK installation on a particular computer is:
C:\Program Files\Java\jdk1.8.0_111\bin
javac.exe
The filename of the Java compiler included with the JDK is javac.exe
.
Java programs may be compiled by passing zero or many options followed by one or many file names to the javac
compiler.
For example, the following command executes the javac
compiler and passes the string Foo.java
to the compiler as the single command-line argument.
javac Foo.java
Files that contain Java source code may be encoded in a variety of ways.
If the encoding used for a file containing Java source code does not match the default encoding that the javac
compiler is configured to use,
then you can tell the javac compiler which encoding to use via the -encoding
option.
For example, the following command instructs the javac compiler to use an encoding called unicode when reading the contents of a file named Foo.java
.
javac -encoding unicode Foo.java
java.exe
Documentation from Oracle describes the java.exe
program this way:
Thejava
command starts a Java application. It does this by starting a Java runtime environment, loading a specified class, and calling that class'smain
method.The method must be declared
public
andstatic
, it must not return any value, and it must accept aString
array as a parameter. The method declaration has the following form:public static void main(String[] args)
By default, the first argument without an option is the name of the class to be called.
After a program containing a class named Foo
with a main method defined “just so” (i.e. as described above) has been compiled,
the following command can be used to start the program beginning at the beginning of said main
method.
java Foo
If you are curious, you can learn more about javac
, java
, javadoc
and the Java Virtual Machine by reading
various Wikipedia articles including
Java Development Kit,
javac,
javadoc and
Java virtual machine;
you might also enjoy reading the blog posts
java vs javaw vs javaws and
Differentiate JVM JRE JDK JIT
published by Joe at javapapers.com.
First Programs
When learning a new programming language, programmers traditionally try to write a program that will print the sentence “Hello, World!” or something similar. A more challenging task that ambitious beginners can try to tackle is implementing the Trabb Pardo–Knuth algorithm in a new language. Such programs are examples of programming chrestomathy.Here is source code for a "Hello, World!" program written in Java:
public class HelloWorld { public static void main(String[] args) { System.out.print("Hello, World!"); } }
Parameters and Arguments
On page 187 of the third edition of volume 1 of The Art of Computer Programming, Donald Ervin Knuth explains the meanings of the words parameter and argument:When a subroutine is written to handle a general case, it is expressed in terms of parameters. Parameters are values that govern the subroutine’s actions; they are subject to change from one call of the subroutine to another.Consider a Java program comprised of the following lines of source code stored in a file namedThe coding in the outside program that transfers control to the subroutine and gets it properly started is known as the calling sequence. Particular values of parameters, supplied when a subroutine is called, are known as arguments.
HelloSomeone.java
.
public class HelloSomeone { public static void main(String[] args) { DoSomething.print("Hello, " + args[0] + "!"); } } class DoSomething { public static void print(String what) { } }
Parameters are variables that “govern the actions” of methods or functions or subroutines. Arguments are related to parameters, but the two words are not synonymous.
In the code snippet above, the identifiers args
and what
are names of a type of variable called a parameter.
In contrast, the string formed by concatenating the string "Hello, "
and the string referred to by args[0]
and the string "!"
is the argument passed to the method DoSomething.print
.
Arguments passed to the main
method of a Java program are sometimes called command line arguments.
The identifier args
is practically the de facto standard
name used for the parameter that every Java program’s main
method must be defined in terms of;
however, nothing other than shame, perhaps, prevents you from using any valid name for that or any other parameter.
Prompts for Section 1.2
- What are the eight primitive Java data types?
- What are the four primitive Java data types used to represent integers?
- What are the two primitive Java data types used to represent real numbers?
- What is the difference between a primitive Java data type and a built-in Java data type? What is an example of the latter?
- What are some similarities and differences between the Java data types
String
andchar
? - What is a literal?
- List two examples of literal values for each of the eight primitive Java data types. Use the appropriate type of quote character(s) and decimal points where applicable.
- What is an operator?
- Explain the Java operators
&&
,||
, and!
. - Which of the following are valid Java identifiers? For each sequences of characters that is not a valid identifier, explain why it is invalid.
J
j
2
_
$
&
j2
2J
_k
k_
$x
x$
-y
y*
camelCase
PascalCase
OXYMORONIC
Java
Public
public
BAD_VARIABLE_NAME_DO_NOT_USE_IT_IS_TOO_LONG
- What is a variable?
- What does the phrase camel case mean?
- What is the difference between the expressions
x = y
andx == y
? - What is the difference between declaring a variable and initializing a variable?
- Can a variable be declared and initialized in one Java statement? If so, provide an example of such a statement.
- Is the following Java statement valid? If so, what does it do? If not, why not? If you are not sure, how could you find out? (Find out!)
int a, b, c = 123;
- What does the following expression evaluate to?
(true || false) && !false
- Assume
x
andy
are variables of typeboolean
. For what values ofx
andy
does the following expression evaluate to true?((x = y) == (x == y))
- What does the following program print?
public class Plus { public static void main(String[] args) { System.out.print(1 + '2'); System.out.println("1" + '2'); } }
1.2 Built-in Types of Data
Sedgewick and Wayne feel so strongly about the importance of data types that they write:
When programming in Java, you must always be aware of the type of data that your program is processing.‘Always’ is a strong word! And the authors of Computer Science, An Interdisciplinary Approach don't stop there. They go on to say that understanding the distinctions among types is so important that we formally define the idea:
a data type is a set of values and a set of operations defined on those values.A few sentences later they reiterate the point again.
Understanding data types (values and operations on them) is an essential step in beginning to program.
The Wikipedia article Data type (accessed on 6 October 2017) describes the notion of a data type a little bit more verbosely:
A data type provides a set of values from which an expression (i.e. variable, function ...) may take its values. The type defines the operations that can be done on the data, the meaning of the data, and the way values of that type can be stored.
Java’s Eight Primitive Data Types
Type | Category | Sample Values | Sample Operation (operator) |
---|---|---|---|
byte |
whole number (integer) | 127 , -128 |
addition (+ ) |
short |
whole number (integer) | 32767 , -32768 |
addition (+ ) |
int |
whole number (integer) | 2147483647 , -2147483648 |
addition (+ ) |
long |
whole number (integer) | 0 | addition (+ ) |
float |
real (floating-point) number | 1.0 | addition (+ ) |
double |
real (floating-point) number | 1.0 | addition (+ ) |
boolean |
truth (boolean) value | true , false |
negation (! ) |
char |
character (symbol) | 'a' , '$' , '7' |
variable increment (++ ) |