Start of Tutorial > Start of Trail | Search |
TheCount
class shown below contains a method namedcountChars
that reads and counts characters from aReader
(an object that implements an input stream of characters) and then displays the number of characters read. Even a small method such as this uses many of the traditional language features of Java and classes from the Java API.import java.io.*; public class Count { public static void countChars(Reader in) throws IOException { int count = 0; while (in.read() != -1) count++; System.out.println("Counted " + count + " chars."); } // ... main method omitted ... }Through a line-by-line investigation of this simple method, this lesson describes Java's traditional language features such as variables and data types, operators, expressions, control flow statements, and so on.
Impurity Alert: UsingSystem.out
is not 100% Pure Java because some systems don't have the notion of standard output.The previous listing of the
Count
class omits themain
method needed to try thecountChars
method. Running thecountChars
Method shows you themain
method and how to run it.
Like other programming languages, Java allows you to declare variables in your programs. You use variables to contain data that can change during the execution of the program. All variables in Java have a type, a name, and scope. The example program shown previously declares these two variables among others:
int count = 0;
String[] args
The Java language provides a set of operators which you use to perform a function on one or two variables. ThecountChars
method uses several operators including the ones shown here in bold:
int count = 0;
in.read() != -1
count ++;
"Counted " + count + " chars."
Operators, variables, and method calls can be combined into sequences known as expressions. The real work of a Java program is achieved through expressions.
Thewhile
statement incountChars
is one of a group of statements known as control flow statements. As the name implies, control flow statements control the flow of the program. In other words, control flow statements govern the sequence in which a program's statements are executed.
Two important data types in any programming language are arrays and strings. In Java, both arrays and strings are full-blown objects. Other languages force programmers to manage data in arrays and strings at the memory level using direct pointer manipulation.
Start of Tutorial > Start of Trail | Search |