java4python 3.0 documentation

Basics

«  Getting Started   ::   Contents   ::   Lists and Maps  »

Basics

Base Types

One of the great things about Python is that all of the basic data types are objects. Integers are objects, floating point numbers are objects, lists are objects, everything. In Java that is not the case. In Java some of the most basic data types like integers and floating point numbers are not objects. The benefit of having these primitive data types be non-objects is that operations on the primitives are fast; however, this increases the complexity of the language.

In Java, it is very important to distinguish base types from object types. The base types are integers and floating point numbers. There are several integer types of different sizes.

integer type size values (approximately)
void 0 bits none
boolean 1 bit true, false
byte 8 bits -128 .. 127
char 16 bits -/+ 32,000 (5 decimal digits)
int 32 bits -/+ 2 billion (10 decimal digits)
long 64 bits -/+ 9 quintillion (19 decimal digits)

For the most part, we will use int to represent integer values. We may also use long, when we need to count above 2 billion. The types void, boolean and char are typically used for special purposes. We will not use byte often.

  • void is used for the type of functions that do not return any value.
  • boolean is used for conditional execution (if statements and loops).
  • char is used for unicode characters
floating point type size precision
float 32 bits 24 bits (about 7 decimal digits)
double 64 bits 54 bits (about 16 decimal digits)

Strings

Strings are objects in Java, but they are important enough to have their own special status in the language.

Strings in Java and Python are quite similar. Like Python, Java strings are immutable — ie, the value of a string cannot change. However, manipulating strings in Java is not quite as obvious since Strings do not support an indexing or slicing operator. That is not to say that you can’t index into a Java string — you can. You can also pull out a substring just as you can with slicing. The difference is that Java uses method calls where Python uses Operators.

In fact this is the first example of another big difference between Java and Python. Java does not support any operator overloading. Table 3 maps common Python string operations to their Java counterparts. For the examples shown in the table we will use a string variable called str.

Python Java Description
str[3] str.charAt(3) Return character in 3rd position
str[2:5] str.substring(2,4) Return substring from 2nd to 4th
len(str) str.length() Return the length of the string
str.find('x') str.indexOf('x') Find the first occurrence of x
str.split() str.split('\s') Split the string on whitespace into a list/array of strings
str.split(',') str.split(',') Split the string at ',' into a list/array of strings
str1 + str2 str1.concat(str2) Concatenate two strings together
str.strip() str.trim() Remove any whitespace at the beginning or end

Java does support exactly one operator on strings: the plus operator can be used as shorthand for concat. Thus, you can write str1 + str2 as shorthand for str1.concat(str2).

Conversions

Java allows for conversions between the base types and between strings and base types. Unlike python, these conversions must often be written explicitly. Some of these conversions may result in a loss of information if the source number is too large or has too great a precision to be stored in the target.

The following table shows the syntax for some conversions in the typical case where a variable is used to store the converted value.

Conversion Syntax Lossy?
int from boolean anInt = aBoolean ? 1 : 0; No
int from char anInt = aChar; No
int from long anInt = (int) aLong; Yes
int from float anInt = (int) aFloat; Yes
int from double anInt = (int) aDouble; Yes
int from String anInt = Integer.parseInt(aString); Yes
float from int aFloat = int; Yes
float from long aFloat = aLong; Yes
float from double aFloat = (float) aDouble; Yes
float from String aFloat = Float.parseFloat(aString); Yes
double from int aDouble = int; No
double from long aDouble = aLong; Yes
double from float aDouble = aFloat; No
double from String aDouble = Double.parseDouble(aString); Yes
String from boolean aString = Boolean.toString(aBoolean) No
String from int aString = Integer.toString(anInt) No
String from long aString = Long.toString(aLong) No
String from float aString = Float.toString(aFloat) No
String from double aString = Double.toString(aDouble) No

Example: Fahrenheit to Celsius

Lets go back in time and look at another of our very early Python programs. Here is a simple Python function to convert a Fahrenheit temperature to Celsius.

def main():
    fahr = input("Enter the temperature in F: ")
    cel = (fahr - 32) * 5.0/9.0
    print "the temperature in C is: ", cel

Next, lets look at the Java Equivalent.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import java.util.Scanner;

public class TempConv {
    public static void main(String[] args) {
        double fahr;
        double cel;
        Scanner in;

        in = new Scanner(System.in);
        System.out.println("Enter the temperature in F: ");
        fahr = in.nextDouble();

        cel = (fahr - 32) * 5.0/9.0;
        System.out.println("The temperature in C is: " + cel);

        System.exit(0);
    }

}

There are several new concepts introduced in this example. We will look at them in the following order:

  • Import
  • Variable Declaration
  • Input/Output and the Scanner Class

Import

In Java you can use any class that is available without having to import the class subject to two very important conditions:

  1. The javac and java must know that the class exists.
  2. You must use the full name of the class

You first question might be how do the java and javac commands know that certain classes exist. The answer is the following:

  1. Java knows about all the classes that are defined in .java and .class files in your current working directory.
  2. Java knows about all the classes that are shipped with java.
  3. Java knows about all the classes that are included in your CLASSPATH environment variable. Your CLASSPATH environment variable can name two kinds of structures.
    1. A jar file that contains java classes
    2. Another unix directory that contains java class files

You can think of the import statement in Java as working a little bit like the from module import xxx statement in Python. However, behind the scenes the two statements actually do very different things. The first important difference to understand is that the class naming system in Java is very hierarchical. The full name of the Scanner class is really java.util.Scanner. You can think of this name as having two parts: The first part java.util is called the package and the last part is the class. We’ll talk more about the class naming system a bit later. The second important difference is that it is the Java class loader’s responsibility to load classes into memory, not the import statement’s.

So, what exactly does the import statement do? What it does is tell the compiler that we are going to use a shortened version of the class’s name. In this example we are going to use the class java.util.Scanner but we can refer to it as just Scanner. We could use the java.util.Scanner class without any problem and without any import statement provided that we always referred to it by its full name. As an Experiment you may want to try this yourself. Remove the import statement and change the string Scanner to java.util.Scanner in the rest of the code. The program should still compile and run.

Declaring Variables

Here is where we run into one of the most important differences between Java and Python. Python is a dynamically typed language. In a dynamically typed language a variable can refer to any kind of object at any time. When the variable is used, the interpreter figures out what kind of object it is. Java is a statically typed language. In a statically typed language the association between a variable and the type of object the variable can refer to is determined when the variable is declared. Once the declaration is made it is an error for a variable to refer to an object of any other type.

In the example above, lines 5—7 contain variable declarations. Specifically we are saying that fahr and cel are going to variables holding values of type double. The variable in will reference a Scanner object. This means that if we were to try an assignment like fahr = "xyz" the compiler would generate an error because "xyz" is a string and fahr is supposed to be a double.

For Python programmers the following error is likely to be even more common. Suppose we forgot the declaration for cel and instead left line 6 blank. What would happen when we type javac TempConv.java on the command line?

TempConv.java:13: cannot find symbol
symbol  : variable cel
location: class TempConv
         cel = (fahr - 32) * 5.0/9.0;
         ^
TempConv.java:14: cannot find symbol
symbol  : variable cel
location: class TempConv
         System.out.println("The temperature in C is: " + cel);
                                                          ^
2 errors

When you see the first kind of error, where the symbol is on the left side of the equals sign it usually means that you have not declared the variable. If you have ever tried to use a Python variable that you have not initialized the second error message will be familiar to you. The difference here is that we see the message before we ever try to test our program. More common error messages are discussed in the section Common Mistakes.

The general rule in Java is that you must decide what kind of an object your variable is going to reference and then you must declare that variable before you use it. There is much more to say about the static typing of Java but for now this is enough.

Input / Output / Scanner

In the previous section you saw that we created a Scanner object. In Java Scanner objects make getting input from the user, a file, or even over the network relatively easy. In our case we simply want to ask the user to type in a number at the command line, so in line 9 we construct a Scanner by calling the constructor and passing it the System.in object. Notice that this Scanner object is assigned to the name in, which we declared to be a Scanner on line 7. System.in is similar to System.out except of course it is used for input. If you are wondering why we must create a Scanner to read data from System.in when we can write data directly to System.out using println, you are not alone. We will talk about the reasons why this is so later when we talk in depth about Java streams. You will also see in other examples that we can create a Scanner by passing the Scanner a File object. You can think of a scanner as a kind of “adapter” that makes low level objects easier to use.

On line 11 we use the Scanner object to read in a number. Here again we see the implications of Java being a strongly typed language. Notice that we must call the method nextDouble. Because the variable fahr was declared as a double. So, we must have a function that is guaranteed to return each kind of object we might want to read. In this case we need to read a double so we call the function nextDouble. The compiler matches up these assignment statments and if you try to assign the results of a method call to the wrong kind of variable it will be flagged as an error.

Table 2 shows you some commonly used methods of the scanner class. There are many more methods supported by this class and we will talk about how to find them in the next chapter.

Return type Method name Description
boolean hasNext() returns true if more data is present
boolean hasNextInt() returns true if the next thing to read is an integer
boolean hasNextFloat() returns true if the next thing to read is a float
boolean hasNextDouble() returns true if the next thing to read is a double
int nextInt() returns the next thing to read as an integer
Float nextFloat() returns the next thing to read as a float
double nextDouble() returns the next thing to read as a double
String next() returns the next thing to read as a String

Java applications may also employ a graphical user interface (GUI). Lets look at a version of our temperature control application that uses dialog boxes for input and output.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import javax.swing.*;

public class TempConvGUI {

    public static void main(String[] args) {
        String fahrString;
        double fahr, cel;

        fahrString = JOptionPane.showInputDialog("Enter the temperature in F");
        fahr = Double.parseDouble(fahrString);
        cel = (fahr - 32) * 5.0/9.0;

        JOptionPane.showMessageDialog(null,"The temperature in C is, " + cel);
    }

}

This example illustrates a couple of interesting points:

First, the function call JOptionPane.showInputDialog pops up a dialog box to allow you to enter a temperature. But, since you could enter anything into the text input box it returns a String. On the next line the string is converted into a double by the function Double.parseDouble. This is similar to what happens in Python when you call float() with either a string or an integer as the argument.

The next dialog box is JOptionPane.showMessageDialog. Notice that the first parameter is null In Java null serves the same purpose as None in Python. The first parameter is null because we do not have a ‘main window’ for this little application. When we look at creating full blown java programs with user interfaces, we will learn more about this parameter.

The second parameter is "The temperature in C is, " + cel. Now you may be thinking to yourself that this must surely be a violation of the strong typing I have been describing to you. After all you should not be able to add together a string and a double right? You are correct, however, all java objects have a method called tostring. The tostring method acts much like the Python method __str__() and is called automatically by the compiler whenever it makes sense to convert a Java object to a string.

List

Lets look at another early Python program. We are going to read numbers from a file and produce a histogram that shows the frequency of the various numbers. The data file we will use has one number between 0 and 9 on each line of the file. Here is a simple Python program that creates and prints a histogram.

def main():
    count = [0]*10
    data = open('test.dat')

    for line in data:
        count[int(line)] = count[int(line)] + 1

    idx = 0
    for num in count:
        print idx, " occured ", num, " times."
        idx += 1

Now if we run this program on a data file that looks like this:

9 8 4 5 3 5 2 1 5

We will get output that looks like this:

0 occurred 0 times
1 occurred 1 times
2 occurred 1 times
3 occurred 1 times
4 occurred 1 times
5 occurred 3 times
6 occurred 0 times
7 occurred 0 times
8 occurred 1 times
9 occurred 1 times

Lets review what is happening in this little program. In the first line we create a list and initialize the first 10 positions in the list to be 0. Next we open the data file called ‘test.dat’ Third, we have a loop that reads each line of the file. As we read each line we convert it to an integer and increment the counter at the position in the list indicated by the number on the line we just read. Finally we iterate over each element in the list printing out both the position in the list and the total value stored in that position.

To write the Java version of this program we will have to introduce several new Java concepts. First, you will see the Java equivalent of a list, called an ArrayLlist. Next you will see three different kinds of loops used in Java. Two of the loops we will use are going to be very familiar, the third one is different from what you are used to in Python but is easy when you understand the syntax:

while
Used with boolean expression for loop exit condition.
for
Used to iterate over a sequence. This is very similar to for i in xxx where xxx is a list or string or file.
for
Used to iterate through a sequence of numbers. This is most similar to for i in range(), except the syntax is different.

Here is the Java code needed to write the exact same program:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;

public class Histo {

    public static void main(String[] args) {
        Scanner data = null;
        ArrayList<Integer> count;
        int idx;

        try {
                data = new Scanner(new File("test.dat"));
        }
        catch ( IOException e) {
            System.out.println("Sorry but I was unable to open your data file");
            e.printStackTrace();
            System.exit(0);
        }

        count = new ArrayList<Integer>(10);
        for (int i =0; i<10;i++) {
            count.add(i,0);
        }

        while(data.hasNextInt()) {
            idx = data.nextInt();
            count.set(idx,count.get(idx)+1);
        }

        idx = 0;
        for(int i : count) {
            System.out.println(idx + " occured " + i + " times.");
            idx++;
        }
    }
}

Before going any further, I suggest you try to compile the above program and run it on some test data that you create.

Now, lets look at what is happening in the Java source. As usual we declare the variables we are going to use at the beginning of the method. In this example we are declaring a Scanner variable called data, an integer called idx and an ArrayList called count. However, there is a new twist to the ArrayList declaration. Unlike Python where lists can contain just about anything, in Java we let the compiler know what kind of objects our array list is going to contain. In this case the ArrayList will contain Integers. The syntax we use to declare what kind of object the list will contain is the <``*Type*>`` syntax.

Technically, you don’t have to declare what is going to be on an array list. The compiler will allow you to leave the <``*Type*>`` off the declaration. If you don’t tell Java what kind of object is going to be on the list Java will give you a warning message like this:

Note: Histo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Without the <Integer> part of the declaration Python simply assumes that any object can be on the list. However, without resorting to an ugly notation called casting, you cannot do anything with the objects on a list like this! So, if you forget you will surely see more errors later in your code. (Try it and see what you get)

Lines 13—20 are required to open the file. Why so many lines to open a file in Java? The additional code mainly comes form the fact that Java forces you to reckon with the possibility that the file you want to open is not going to be there. If you attempt to open a file that is not there you will get an error. A try/catch construct allows us to try things that are risky, and gracefully recover from an error if one occurs. The following example shows the general structure of a try catch block.

try {
   Put some risky code in here.... like opening a file
}
catch (Exception e) {
   If an error happens in the try block an exception is thrown.
   We will catch that exception here!
}

Notice that in line 16 we are catching an IOException. In fact we will see later that we can have multiple catch blocks to catch different types of exceptions. If we want to be lazy and catch any old exception we can catch an Exception which is the parent of all exceptions.

On line 22 we create our array list and give it an initial size of 10. Strictly speaking it is not necessary to give the ArrayList any size. It will grow or shrink dynamically as needed just like a list in Python. On line 23 we start the first of three loops. The for loop on lines 23–25 serves the same purpose as the Python statement count = [0]*10, that is it initializes the first 10 positions in the ArrayList to hold the value 0.

The syntax of this for loop probably looks very strange to you, but in fact it is not too different from what happens in Python using range. In fact for(int i = 0; i < 10; i++) is exactly equivalent to the Python for i in range(10) The first statement inside the parenthesis declares and initializes a loop variable i. The second statement is a Boolean expression that is our exit condition. In other words we will keep looping as long as this expression evaluates to true. The third clause is used to increment the value of the loop variable at the end of iteration through the loop. In fact i++ is Java shorthand for i = i + Java also supports the shorthand i-- to decrement the value of i. Like Python you can also write i += 2 as shorthand for i = i + 2 Try to rewrite the following Python for loops as Java for loops:

  • for i in range(2,101,2)
  • for i in range(1,100)
  • for i in range(100,0,-1)
  • for x,y in zip(range(10),range(0,20,2)) [hint, you can separate statements in the same clause with a ,]

The next loop (lines 27–30) shows a typical Java pattern for reading data from a file. Java while loops and Python while loops are identical in their logic. In this case we will continue to process the body of the loop as long as data.hasNextInt() returns true.

Line 29 illustrates another important difference between Python and Java. Notice that in Java we can not write count[idx] = count[idx] + 1. This is because in Java there is no overloading of operators. Everything except the most basic math and logical operations is done using methods. So, to set the value of an ArrayList element we use the set method. The first parameter of set indicates the index or position in the ArrayList we are going to change. The next parameter is the value we want to set. Notice that once again we cannot use the indexing square bracket operator to retrieve a value from the list, but we must use the get method.

The last loop in this example is similar to the Python for loop where the object of the loop is a Sequence. In Java we can use this kind of for loop over all kinds of sequences, which are called Collection classes in Java. The for loop on line 33 for(int i : count) is equivalent to the Python loop for i in count: This loop iterates over all of the elements in the ArrayList called count. Each time through the loop the int variable i is bound to the next element of the ArrayList. If you tried the experiment of removing the <Integer> part of the ArrayList declaration you probably noticed that you had an error on this line. Why?

Arrays

As I said at the outset of this Section we are going to use Java ArrayLists because they are easier to use and more closely match the way that Python lists behave. However, if you look at Java code on the internet or even in your Core Java books you are going to see examples of something called arrays. In fact you have already seen one example of an array declared in the ‘Hello World’ program. Lets rewrite this program to use primitive arrays rather than array lists.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class HistoArray {
    public static void main(String[] args) {
        Scanner data = null;
        int[] count = {0,0,0,0,0,0,0,0,0,0};
        int idx;



        try {
                data = new Scanner(new File("test.dat"));
        }
        catch ( IOException e) {
            System.out.println("Sorry but I was unable to open your data file");
            e.printStackTrace();
            System.exit(0);
        }

        while(data.hasNextInt()) {
            idx = data.nextInt();
            count[idx] = count[idx] + 1;
        }

        idx = 0;
        for(int i : count) {
            System.out.println(idx + " occured " + i + " times.");
            idx++;
        }
    }
}

The main difference between this example and the previous example is that we declare count to be an Array of integers. We also can initialize short arrays directly using the syntax shown on line 8. Then notice that on line 24 we can use the square bracket notation to index into an array.

Conditionals

Conditional statements in Python and Java are very similar. In Python we have three patterns:

if condition:
    statement1
    statement2
    ...

In Java this same pattern is simply written as:

if (condition) {
    statement1
    statement2
    ...
}

Once again you can see that in Java the curly braces define a block rather than indentation. In Java the parenthesis around the condition are required because if is technically a function that evaluates to True or False.

if condition:
    statement1
    statement2
    ...
else:
    statement1
    statement2
    ...

In Java this is written as:

if (condition) {
    statement1
    statement2
    ...
} else {
    statement1
    statement2
    ...
}

Java does not have an elif pattern like Python. In Java you can get the functionality of an elif statement by nesting if and else. Here is a simple example in both Python and Java.

if grade < 60:
    print 'F'
elif grade < 70:
    print 'D'
elif grade < 80:
    print 'C'
elif grade < 90:
    print 'B'
else:
    print 'A'

In Java we have a couple of ways to write this

if (grade < 60>) {
    System.out.println('F');
} else {
    if (grade < 70) {
        System.out.println('F');
    } else {
        if (grade < 80) {
            System.out.println('F');
        } else {
            if (grade < 90) {
                System.out.println('F');
            } else {
                System.out.println('F');
            }

We can get even closer to the elif statement by taking advantage of the Java rule that a single statement does not need to be enclosed in curly braces. Since the if is the only statement used in each else we can get away with the following.

if (grade < 60) {
    System.out.println('F');
} else if (grade < 70) {
    System.out.println('D');
} else if (grade < 80) {
    System.out.println('C');
} else if (grade < 90) {
    System.out.println('B');
} else  System.out.println('A');

Java also supports a switch statement that acts something like the elif statement of Python under certain conditions. To write the grade program using a switch statement we would use the following:

int tempgrade = grade / 10;
switch(tempgrade) {
case 10:
case 9:
    System.out.println('A');
    break;
case 8:
    System.out.println('B');
    break;
case 7:
    System.out.println('C');
    break;
case 6:
    System.out.println('A');
    break;
default:
    System.out.println('F');
}

The switch statement is not used very often, and I recommend you do not use it! First, it is not as powerful as the else if model because the switch variable can only be compared for equality with an integer or enumerated constant. Second it is very easy to forget to put in the break statement. If the break statement is left out then then the next alternative will be automatically executed. For example if the grade was 95 and the break was omitted from the case 9: alternative then the program would print out both A and B.

The conditionals used in the if statement can be boolean variables, simple comparisons, and compound boolean expressions.

Java also supports the boolean expression. condition ? trueValue : falseValue This expression can be used to test a condition as part of an assignment statement. For example a = a % 2 == 0 ? a*a : 3*x -1 In the previous assignment statement the expression a%2 ==0 is first checked. If it is true then a is assigned the value a * a if it is false then a is assigned the value of 3*x-1. Of course all of this could have been accomplished using a regular if else statement, but sometimes the convenience of a single statement is too much to resist.

Loops and Iteration

You have already seen a couple of examples of iteration and looping in Java. So this section will just serve as a reference for the differences in Snytax.

In Python the easiest way to write a definite loop is using the for loop in conjunction with the range function. For example:

for i in range(10):
   print i

In Java we would write this as:

for (int i = 0; i < 10; i++ ) {
    System.out.println(i);
}

Recall that the range function provides you with a wide variety of options for controlling the value of the loop variable.

range(stop)
range(start,stop)
range(start,stop,step)

The Java for loop is really analogous to the last option giving you explicit control over the starting, stopping, and stepping in the three clauses inside the parenthesis. You can think of it this way:

for (start clause; stop clause; step clause) {
    statement1
    statement2
    ...
}

If you want to start at 100, stop at 0 and count backward by 5 the Python loop would be written as:

for i in range(100,-1,-5):
    print i

In Java we would write this as:

for (int i = 100; i >= 0; i -= 5)
    System.out.println(i);

In Python the for loop can also iterate over any sequence such as a list, a string, or a tuple. Java also provides a variation of its for loop that provides the same functionality in its so called for each loop.

In Python we can iterate over a list as follows:

l = [1, 1, 2, 3, 5, 8, 13, 21]
for fib in l:
   print fib

In Java we can iterate over an ArrayList of integers too:

ArrayList<Integer> l = new ArrayList<Integer>();
l.add(1); l.add(1); l.add(2); l.add(3);
for (int i : l) {
    System.out.println(i)
}

This example stretches the imagination a bit, and in fact points out one area where Java’ s primitive arrays are easier to use than an array list. In fact all primitive arrays can be used in a for each loop.

int l[] = {1,1,2,3,5,8,13,21};
for(int i : l) {
    System.out.println(i);
}

To iterate over the characters in a string in Java do the following:

String t = "Hello World";
for (char c : t.toCharArray()) {
    System.out.println(c);
}

Both Python and Java support the while loop. Recall that in Python the while loop is written as:

while  condition:
   statement1
   statement2
   ...

In Java we add parenthesis and curly braces to get:

while (condition) {
    statement1
    statement2
    ...
}

Java adds an additional, if seldom used variation of the while loop called the do loop. The do loop is very similar to while except that the condition is evaluated at the end of the loop rather than the beginning. This ensures that a loop will be executed at least one time. Some programmers prefer this loop in some situations because it avoids an additional assignment prior to the loop. For example:

do {
    statement1
    statement2
    ...
} while (condition);

Common Mistakes

  • Forgetting to declare your variables.

    Histo.java:21: cannot find symbol
    symbol  : variable count
    location: class Histo
            count = new ArrayList<Integer>(10);
            ^
    
  • Not importing a class.

    Histo.java:9: cannot find symbol
    symbol  : class Scanner
    location: class Histo
            Scanner data = null;
            ^
    
  • Forgetting to use the new keyword to create an object. Here’s an example of the error message that occurs when you forget to use the new keyword. Notice that the message is pretty unhelpful. Java thinks you are trying to call the Method Scanner, but there are two problems. First Scanner is not really a method it is a constructor.:

    Histo.java:14: cannot find symbol
    symbol  : method Scanner(java.io.File)
    location: class Histo
                    data = Scanner(new File("test.dat"));
                           ^
    
  • Forgetting a Semicolon.

    Histo.java:19:
    ';' expected
                System.exit(0);
                ^
    
  • Forgetting to declare the kind of object in a container.

    Note: Histo.java uses unchecked or unsafe operations. Note:
    Recompile with -Xlint:unchecked for details.
    

Naming Conventions

Java has some very handy naming conventions.

  • Class names always start with an upper case letter. For example, Scanner, System, Hello
  • Method names always start with a lower case letter, and use camelCase to represent multiword method names. for example nextInt()
  • Instance variables of a class start with a lower case letter and use camelCase
  • Constants are in all upper case letters. for example Math.MAXINT

Java Documentation Online

All Java class libraries are documented and available online. Here are two good resources for you to use:

  • JavaDoc The Javadocs.org website provides a nice searchable interface. Search for a classname and you will get the documentation you are looking for.
  • JavaAPI contains the same information but in a browsable format. If you don’t know the class name exactly this is a good way to see what is close.

In general the Javadoc page for any class contains information about:

  • Where this class falls in the class hierarchy. What classes are its parents and what classes are its decendents.
  • A summary and some examples of using the class.
  • A summary listing of instance variables
  • A summary listing of Constructors
  • A summary listing of Methods
  • Detailed documentation on constructors and methods.

Typically the Javadoc pages are constructed from the source code where the class is implemented. This encourages Java programmers to do a good job of documenting their code, while providing a user friendly way to read the documentation without looking at the code directly.

«  Getting Started   ::   Contents   ::   Lists and Maps  »