![]() | Java Programming Understanding a Java Program | Java IDEs![]() |
NavigateGetting Started topic:() |
This article presents a small Java program which can be run from the console. It computes the distance between two points on a plane. You do not need to understand the structure and meaning of the program just yet; we will get to that soon. Also, because the program is intended as a simple introduction, it has some room for improvement, and later in the module we will show some of these improvements. But let's not get too far ahead of ourselves!
This class is namedDistance, so using your favorite editor orJava IDE, first create a file namedDistance.java
, then copy the source below, paste it into the file and save the file.
![]() | Code listing 2.1: Distance.javapublicclassDistance{privatejava.awt.Pointpoint0,point1;publicDistance(intx0,inty0,intx1,inty1){point0=newjava.awt.Point(x0,y0);point1=newjava.awt.Point(x1,y1);}publicvoidprintDistance(){System.out.println("Distance between "+point0+" and "+point1+" is "+point0.distance(point1));}publicstaticvoidmain(String[]args){Distancedist=newDistance(intValue(args[0]),intValue(args[1]),intValue(args[2]),intValue(args[3]));dist.printDistance();}privatestaticintintValue(Stringdata){returnInteger.parseInt(data);}} |
At this point, you may wish to review the source to see how much you might be able to understand. While perhaps not being the most literate of programming languages, someone with understanding of other procedural languages such as C, or other object oriented languages such as C++ or C#, will be able to understand most if not all of the sample program.
Once you save the file,compile the program:
![]() | Compilation command$ javac Distance.java |
(If thejavac
command fails, review theinstallation instructions.)
To run the program, you supply it with thex andy coordinates of two points on a plane separated by a space. For this version of Distance, only integer points are supported. The command sequence isjava Distance <x0> <y0> <x1> <y1>
to compute the distance between the points (x0, y0) and (x1, y1).
![]() | If you get ajava.lang.NumberFormatException exception, some arguments are not a number. If you get ajava.lang.ArrayIndexOutOfBoundsException exception, you did not provide enough numbers. |
Here are two examples:
![]() | Output for the distance between the points (0, 3) and (4, 0)$ java Distance 0 3 4 0Distance between java.awt.Point[x=0,y=3] and java.awt.Point[x=4,y=0] is 5.0 |
![]() | Output for the distance between the points (-4, 5) and (11, 19)$ java Distance -4 5 11 19Distance between java.awt.Point[x=-4,y=5] and java.awt.Point[x=11,y=19] is 20.518284528683193 |
We'll explain this strange looking output, and also show how to improve it, later.
As promised, we will now provide a detailed description of this Java program. We will discuss the syntax and structure of the program and the meaning of that structure.
![]() | Code listingpublicclassDistance{privatejava.awt.Pointpoint0,point1;publicDistance(intx0,inty0,intx1,inty1){point0=newjava.awt.Point(x0,y0);point1=newjava.awt.Point(x1,y1);}publicvoidprintDistance(){System.out.println("Distance between "+point0+" and "+point1+" is "+point0.distance(point1));}publicstaticvoidmain(String[]args){Distancedist=newDistance(intValue(args[0]),intValue(args[1]),intValue(args[2]),intValue(args[3]));dist.printDistance();}privatestaticintintValue(Stringdata){returnInteger.parseInt(data);}} |
Thesyntax of a Java class is the characters, symbols and their structure used to code the class. Java programs consist of a sequence of tokens. There are different kinds of tokens. For example, there are word tokens such asclass
andpublic
which representkeywords(in purpleabove) — special words with reserved meaning in Java. Other words such asDistance
,point0
,x1
, andprintDistance
are not keywords butidentifiers (in grey). Identifiers have many different uses in Java but primarily they are used as names. Java also has tokens to represent numbers, such as1
and3
; these are known asliterals(in orange).String literals(in blue), such as"Distance between "
, consist of zero or more characters embedded in double quotes, andoperators(in red) such as+
and=
are used to express basic computation such as addition or String concatenation or assignment. There are also left and right braces ({
and}
) which encloseblocks. The body of a class is one such block. Some tokens are punctuation, such as periods.
and commas,
and semicolons;
. You usewhitespace such as spaces, tabs, and newlines, to separate tokens. For example, whitespace is required between keywords and identifiers:publicstatic
is a single identifier with twelve characters, not two Java keywords.
public class Distance {
private java.awt.Point point0, point1;
public Distance(int x0, int y0, int x1, int y1) {
point0 = new java.awt.Point(x0, y0);
point1 = new java.awt.Point(x1, y1);
}
public void printDistance() {
System.out.println("Distance between " + point0 + " and " + point1
+ " is " + point0.distance(point1));
}
public static void main(String[] args) {
Distance dist = new Distance(
intValue(args[0]), intValue(args[1]),
intValue(args[2]), intValue(args[3]));
dist.printDistance();
}
private static int intValue(String data) {
return Integer.parseInt(data);
}
}
Sequences of tokens are used to construct the next building blocks of Java classes as shownabove: declarations and definitions. A class declaration provides the name and visibility of a class. In our example,public class Distance
is the class declaration. It consists (in this case) of two keywords,
andpublic
followed by the identifierclass
Distance
.
This means that we are defining a class namedDistance
. Other classes, or in our case, the command line, can refer to the class by this name. Thepublic
keyword is anaccess modifier which declares that this class and its members may be accessed from other classes. Theclass
keyword, obviously, identifies this declaration as a class. Java also allows declarations ofinterfaces andannotations.
The class declaration is then followed by a block (surrounded by curly braces) which provides the class's definition(in blue infigure 2.2). The definition is the implementation of the class – the declaration and definitions of the class's members. This class contains exactly six members, which we will explain in turn.
point0
andpoint1
(in green)The declaration
![]() | Code section 2.1: Declaration.privatejava.awt.Pointpoint0,point1; |
...declares twoinstance fields. Instance fields represent named values that are allocated whenever an instance of the class is constructed. When a Java program creates aDistance
instance, that instance will contain space forpoint0
andpoint1
. When anotherDistance
object is created, it will contain space for itsownpoint0
andpoint1
values. The value ofpoint0
in the firstDistance
object can vary independently of the value ofpoint0
in the secondDistance
object.
This declaration consists of:
private
access modifier,java.awt.Point
.Point
in thejava.awt
package.
These two fields could also have been declared with two separate but more verbose declarations,
![]() | Code section 2.2: Verbose declarations.privatejava.awt.Pointpoint0;privatejava.awt.Pointpoint1; |
Since the type of these fields is a reference type (i.e. a field thatrefers to or can hold areference to an object value), Java will implicitly initialize the values ofpoint0
andpoint1
to null when aDistance
instance is created. The null value means that a reference value does not refer to an object. The special Java literalnull
is used to represent the null value in a program. While you can explicitly assign null values in a declaration, as in
![]() | Code section 2.3: Declarations and assignments.privatejava.awt.Pointpoint0=null;privatejava.awt.Pointpoint1=null; |
It is not necessary and most programmers omit such default assignments.
Aconstructor is a special method in a class which is used to construct an instance of the class. The constructor can perform initialization for the object, beyond that which the Java VM does automatically. For example, Java will automatically initialize the fieldspoint0
andpoint1
to null.
![]() | Code section 2.4: The constructor for the classpublicDistance(intx0,inty0,intx1,inty1){point0=newjava.awt.Point(x0,y0);point1=newjava.awt.Point(x1,y1);} |
The constructor above consists of five parts:
public
Distance
in this case.()
. The parameter list declares the type and name of each of the method's parameters.throws
clause which declares theexceptions that the constructor may throw. This constructor does not declare any exceptions.{}
). This constructor's body contains two statements.This constructor accepts four parameters, namedx0, y0, x1
andy1
. Each parameter requires a parameter type declaration, which in this example is
for all four parameters. The parameters in the parameter list are separated by commas.int
The two assignments in this constructor use Java'snew
operator to allocate twojava.awt.Point
objects. The first allocates an object representing the first point,(x0, y0)
, and assigns it to thepoint0
instance variable (replacing the null value that the instance variable was initialized to). The second statement allocates a secondjava.awt.Point
instance with(x1, y1)
and assigns it to thepoint1
instance variable.
This is the constructor for the Distance class. Distance implicitly extends fromjava.lang.Object
. Java inserts a call to the super constructor as the first executable statement of the constructor if there is not one explicitly coded. The above constructor body is equivalent to the following body with the explicit super constructor call:
![]() | Code section 2.5: Super constructor.{super();point0=newjava.awt.Point(x0,y0);point1=newjava.awt.Point(x1,y1);} |
While it is true that this class could be implemented in other ways, such as simply storing the coordinates of the two points and computing the distance as, this class instead uses the existingjava.awt.Point
class. This choice matches the abstract definition of this class: to print the distance between two points on the plane. We take advantage of existing behavior already implemented in the Java platform rather than implementing it again. We will see later how to make the program more flexible without adding much complexity, because we choose to use object abstractions here. However, the key point is that this class uses information hiding. That is,how the class stores its state or how it computes the distance is hidden. We can change this implementation without altering how clients use and invoke the class.
Methods are the third and most important type of class member. This class contains threemethods in which the behavior of theDistance
class is defined:printDistance()
,main()
, andintValue()
TheprintDistance()
method prints the distance between the two points to the standard output (normally the console).
![]() | Code section 2.6:printDistance() method.publicvoidprintDistance(){System.out.println("Distance between "+point0+" and "+point1+" is "+point0.distance(point1));} |
Thisinstance method executes within the context of an implicitDistance
object. The instance field references,point0
andpoint1
, refer to instance fields of that implicit object. You can also use the special variablethis
to explicitly reference the current object. Within an instance method, Java binds the namethis
to the object on which the method is executing, and the type ofthis
is that of the current class. The body of theprintDistance
method could also be coded as
![]() | Code section 2.7: Explicit instance of the current class.System.out.println("Distance between "+this.point0+" and "+this.point1+" is "+this.point0.distance(this.point1)); |
to make the instance field references more explicit.
This method both computes the distance and prints it in one statement. The distance is computed withpoint0.distance(point1)
;distance()
is an instance method of thejava.awt.Point
class (of whichpoint0
andpoint1
are instances). The method operates onpoint0
(bindingthis
to the object thatpoint0
refers to during the execution of the method) and accepting another Point as a parameter. Actually, it is slightly more complicated than that, but we'll explain later. The result of thedistance()
method is a double precision floating point number.
This method uses the syntax
![]() | Code section 2.8: String concatenation."Distance between "+this.point0+" and "+this.point1+" is "+this.point0.distance(this.point1) |
to construct a String to pass to theSystem.out.println()
. This expression is a series ofString concatenation methods which concatenates Strings or the String representation of primitive types (such as doubles) or objects, and returns a long string. For example, the result of this expression for the points (0,3) and (4,0) is the String
![]() | Output"Distance between java.awt.Point[x=0,y=3] and java.awt.Point[x=4,y=0] is 5.0" |
which the method then prints toSystem.out
.
In order to print, we invoke theprintln()
. This is an instance method fromjava.io.PrintStream
, which is the type of the static fieldout
in the classjava.lang.System
. The Java VM bindsSystem.out
to the standard output stream when it starts a program.
Themain()
method is the main entry point which Java invokes when you start a Java program from the command line. The command
![]() | Outputjava Distance 0 3 4 0 |
instructs Java to locate the Distance class, put the four command line arguments into an array of String values, then pass those arguments to thepublic static main(String[])
method of the class. We will introduce arrays shortly. Any Java class that you want to invoke from the command line or desktop shortcut must have a main method with this signature or the following signature:public static main(String...)
.
![]() | Code section 2.9:main() method.publicstaticvoidmain(String[]args){Distancedist=newDistance(intValue(args[0]),intValue(args[1]),intValue(args[2]),intValue(args[3]));dist.printDistance();} |
Themain()
method invokes the final method,intValue()
, four times. TheintValue()
takes a single string parameter and returns the integer value represented in the string. For example,intValue("3")
will return the integer 3.
People who do test-first programming or perform regression testingwritea main() method in every Java class, anda main() function in every Python module,to run automated tests.When a person executes the file directly,the main() method executes and runs the automated tests for that file.When a person executes some other Java filethat in turn imports many other Java classes,only one main() method is executed --the main() method of the directly-executed file.
intValue()
methodTheintValue()
method delegates its job to theInteger.parseInt()
method. The main method could have calledInteger.parseInt()
directly; theintValue()
method simply makes themain()
method slightly more readable.
![]() | Code section 2.10:intValue() method.privatestaticintintValue(Stringdata){returnInteger.parseInt(data);} |
This method isprivate
since, like the fieldspoint0
andpoint1
, it is part of the internal implementation of the class and is not part of the external programming interface of theDistance
class.
Both themain()
andintValue()
methods arestatic methods. Thestatic
keyword tells the compiler to create a single memory space associated with the class. Each individual object instantiated has its own private state variables and methods but use the samestatic methods and members common to the single class object created by the compiler when the first class object is instantiated or created. This means that the method executes in a static or non-object context — there is no implicit separate instance available when the static methods run from various objects, and the special variablethis
is not available. As such, static methods cannot access instance methods or instance fields (such asprintDistance()
) orpoint0
) directly. Themain()
method can only invoke the instance methodprintDistance()
method via an instance reference such asdist
.
Most declarations have a data type. Java has several categories of data types: reference types, primitive types, array types, and a special type, void.
Theprimitive types are used to represent boolean, character, and numeric values. This program uses only one primitive type explicitly,
, which represents 32 bit signed integer values. The program also implicitly usesint
, which is the return type of thedouble
distance()
method ofjava.awt.Point
.double
values are 64 bit IEEE floating point values. Themain()
method uses integer values 0, 1, 2, and 3 to access elements of the command line arguments. TheDistance()
constructor's four parameters also have the typeint
. Also, theintValue()
method has a return type ofint
. This means a call to that method, such asintValue(args[0])
, is an expression of typeint
. This helps explain why the main method cannot call:
![]() | Code section 2.11: Wrong type.newDistance(args[0],args[1],args[2],args[3])// This is an error |
Since the type of theargs
array element is String, and our constructor's parameters must beint
, such a call would result in an error because Java will not automatically convert values of type String intoint
values.
Java's primitive types are
,boolean
,byte
,char
,short
,int
,long
andfloat
. Each of which are also Java language keywords.double
In addition to primitive types, Java supportsreference type. A reference type is a Java data type which is defined by a Java class or interface. Reference types derive this name because such valuesrefer to an object or contain areference to an object. The idea is similar to pointers in other languages like C.
Java represents sequences of character data, orString, with the reference typejava.lang.String
which is most commonly referred to asString
.String literals, such as"Distance between "
are constants whose type is String.
This program uses three separate reference types:
Java supportsarrays, which are aggregate types which have a fixed element type (which can be any Java type) and an integral size. This program uses only one array,String[] args
. This indicates thatargs
has an array type and that the element type isString
. The Java VM constructs and initializes the array that is passed to themain
method. Seearrays for more details on how to create arrays and access their size.
The elements of arrays are accessed with integer indices. The first element of an array is always element 0. This program accesses the first four elements of theargs
array explicitly with the indices 0, 1, 2, and 3. This program doesnot perform any input validation, such as verifying that the user passed at least four arguments to the program. We will fix that later.
void
is not a type in Java; it represents the absence of a type. Methods which do not return values are declared asvoid methods.
This class defines two void methods:
![]() | Code section 2.12: Void methodspublicstaticvoidmain(String[]args){...}publicvoidprintDistance(){...} |
Whitespace in Java is used to separate the tokens in a Java source file. Whitespace is required in some places, such as betweenaccess modifiers,type names and Identifiers, and is used to improve readability elsewhere.
Wherever whitespace is required in Java, one or more whitespace characters may be used. Wherever whitespace is optional in Java, zero or more whitespace characters may be used.
Java whitespace consists of the
' '
(0x20),Line separators are special whitespace characters in that they also terminate line comments, whereas normal whitespace does not.
Other Unicode space characters, including vertical tab, are not allowed as whitespace in Java.
Look at thestatic
methodintValue
:
![]() | Code section 2.13: Method declarationprivatestaticintintValue(Stringdata){returnInteger.parseInt(data);} |
Whitespace is required betweenprivate
andstatic
, betweenstatic
andint
, betweenint
andintValue
, and betweenString
anddata
.
If the code is written like this:
![]() | Code section 2.14: Collapsed codeprivatestaticintintValue(Stringdata){returnInteger.parseInt(data);} |
...it means something completely different: it declares a method which has the return typeprivatestaticint
It is unlikely that this type exists and the method is no longer static, so the above would result in a semantic error.
Java ignores all whitespace in front of a statement. As this, these two code snippets are identical for the compiler:
![]() | Code section 2.15: Indented codepublicstaticvoidmain(String[]args){Distancedist=newDistance(intValue(args[0]),intValue(args[1]),intValue(args[2]),intValue(args[3]));dist.printDistance();}privatestaticintintValue(Stringdata){returnInteger.parseInt(data);} |
![]() | Code section 2.16: Not indented codepublicstaticvoidmain(String[]args){Distancedist=newDistance(intValue(args[0]),intValue(args[1]),intValue(args[2]),intValue(args[3]));dist.printDistance();}privatestaticintintValue(Stringdata){returnInteger.parseInt(data);} |
However, the first one's style (with whitespace) is preferred, as the readability is higher. The method body is easier to distinguish from the head, even at a higher reading speed.
![]() | Java Programming Understanding a Java Program | Java IDEs![]() |