There was an error in this gadget

Friday, May 27, 2011

Doing Math in Java part 1: Operators

One of the most valuable uses of a computer is...computing. That is, acting as a mathematical calculator. Java has a plethora of tools for doing computation.


The standard math functions that are built into the Java language are called operators. These are the sort of math functions you would expect to find on a simple calculator, plus some extras:

+ - * / % ++ --

There are other operators used for comparisons, these are the math operators. You can learn more about them in the Java Language Specification, specifically in Integer Operations, Floating-Point Operations, and more extensively through Chapter 15, Expressions.

+ and - do what you would expect, they add and subtract one value from another. * is the symbol used for multiplication, instead of the × used in math class. * is used because it's easier for the computer to recognize it as a math operator, × just looks like a letter 'x' to the computer. Similarly, / is used for division. The ÷ sign isn't on most keyboards, but / has been common on keyboards even before they were attached to computers.

The % sign doesn't do what you might, at first, expect. It doesn't calculate a percentage, as it does on most calculators. It returns the remainder of a division. For example, if you do 10/3 (ten divided by three), the result will be 3. But what if you want to get the remainder? That's what % does. 10%3 will return a value of 1. '%' is sometimes called "modulo". It's a bit of a misnomer, mathematically, but the use of the term is common and well understood, so it's not unusual to pronounce 10%3 as "ten modulo three". This is a very valuable function for keeping a value within a certain range, such as keeping an object located onscreen in graphics by having it "wrap" from one side of the screen to the other when it reaches an edge.

++ and -- are the "increment" and "decrement" operators. Increment means "go up by one unit", and decrement "go down by one unit". So if you've got a variable like:

int i = 5;

And you do i++, the value of i will become 6. Doing i-- will take away 1. ++ and -- can be placed either before or after the value they act on, for example:

number = i++;
count = --j;

There will be different effects on your program depending on whether they come before or after the value. You can find information on that in the Java Language Specification as well, in sections 15.14 and 15.15 which cover the two ways of using these operators. In general, it's best to stick to using them after your value until you understand the differences.

Assignment Operators

You can also do math as part of assigning a value. For example, let's say we want to add three to a value in our program. The obvious way to do this would be:

i = i + 3;

This takes the prior value of i, adds 3 to it, then puts the result back into variable i. With an assignment operator we can do the same thing more tersely:

i += 3;

We've combined the + with = to create an operator. This does the same thing as i = i + 3;. Your program doesn't care which way you type it. The same thing can be done with the other operators that take two values:

i *= 4; // Multiply i by four, store result back in i.
i /= 2; // Divide i in half.
i %= 3; // Put the remainder of i/3 in i.
i -= 7; //Subtract seven from i.

More Complex Math

This is what we can do with the basic math operators built into the language. To get more operations, like those found on a scientific or programmer's calculator, we use methods of some of the standard packages of Java. Which I'll cover in a future article.

Until then, have a look at java.lang.Math.

Friday, May 20, 2011

Your Own Java Classes

To use Java effectively, you want to create and use your own classes. This is one of the great powers of object-oriented languages--the ability to construct programs out of independent building-blocks that cut large problems down into small, easily solvable ones. There's a lot more that can be said, and much of it is elsewhere. So I'll get right into a very simple, very basic example here.

We're going to create a very simple object class that will print a "Hello" message to the screen when called. This class will have two different methods that will do the same thing, though we'll vary the messages they print a bit so that we can see which one is doing the work.

Here's our class: (download HelloClass.Java)

public class HelloClass{

* sayHello() prints "Hello!" to the Java console output.
public void sayHello(){

* doHello() prints "Hello, hello!" to the Java console output.
* It's static, so you don't need to instatiate a HelloClass
* object to use it.
public static void doHello(){
System.out.println("Hello, hello!\n");

} // End of HelloClass

The two methods we have to print messages are sayHello() and doHello(). To use sayHello(), we need to have a HelloClass object created, then call that object's sayHello() method.

doHello(), however, is a static method. This means is belongs to the class, not to any object of the class. So we can use it without any HelloClass objects being created first.

Here's a class that uses these methods as described: (download

public class UseHello{
public static void main(String[] arg){

// We can use doHello() without a HelloClass object:
HelloClass.doHello(); // call the HelloClass's doHello() method.

// But we need to create a HelloClass object to use sayHello():
HelloClass hello=new HelloClass();
hello.sayHello(); // call hello's sayHello() method.

} // End of UseHello.

If we try to call sayHello() without first creating a HelloClass object, like this:

then we'll get the dreaded "calling a non-static method from a static context" error message. That's letting you know that you need to instantiate (or create) a HelloClass object first, then tell that object to call its method.

Static methods are useful for things like general arithmetic and calculation or other methods that might be used in a way where state information is unimportant. But beware, it's easy to create static methods when what's really wanted is an object that does what you want.

Files available for download through:

Friday, May 13, 2011

A Java CSV File Reader

One of the most common types of data file is a CSV (Comma Separated Value) file. They can be exported by many popular applications, notable spreadsheet programs like Excel and Numbers. They are easy to read into your Java programs once you know how.

Reading the file is as simple as reading a text file. The file has to be opened, a BufferedReader object is created to read the data in a line at a time.

Once a line of data has been read, we make sure that it's not null, or empty. If it is, we've hit the end of the file and there's no more data to read. If it isn't, we then use the split() method that's a member of Java's String object. This will split a string into an array of Strings using a delimiter that we give it.

The delimiter for a CSV file is a comma, of course. Once we've split() the string, we have all the element in an Array from which our Java programs can use the data. For this example, I just use a for loop to print out the data, but I could just as well sort on the values of one of the cells, or whatever I need to do with it in my program.

The Steps

  1. Open the file with a BufferedReader object to read it a line at a time.

  2. Check to see if we've got actual data to make sure we haven't finished the file.

  3. Split the line we read into an Array of String using String.split()

  4. Use our data.

The Program
//Reads a Comma Separated Value file and prints its contents.

import java.util.Arrays;

public class CSVRead{

public static void main(String[] arg) throws Exception {

BufferedReader CSVFile =
new BufferedReader(new FileReader("Example.csv"));

String dataRow = CSVFile.readLine(); // Read first line.
// The while checks to see if the data is null. If
// it is, we've hit the end of the file. If not,
// process the data.

while (dataRow != null){
String[] dataArray = dataRow.split(",");
for (String item:dataArray) {
System.out.print(item + "\t");
System.out.println(); // Print the data line.
dataRow = CSVFile.readLine(); // Read next line of data.
// Close the file once all data has been read.

// End the printout with a blank line.

} //main()
} // CSVRead


This program, and an example CSV file to use it with (a section of a spreadsheed I use to keep track of my integrated circuits) are available at my code archive.

Writing to CSV Files with Java

Writing to a CSV file is as simple as writing a text file. In this case, we write a comma between each field, and a newline at the end of each record.

Give it a try, starting with, modify it appropriately, then see what your favorite spreadsheet program thinks of the results.

Friday, May 6, 2011

Java File Save and File Load: Text

We've looked at saving and loading objects to files. If we need to exchange information for use by a different program than our own it will seldom be convenient to save objects. Text files are commonly used to do this.

Text files are even simpler to deal with than Object files, thanks to classes in the package. FileWriter gives us everything we need to write from our program to a text file. All we need to do is feed it String data.

FileReader lets us access a file, but using a BufferedReader makes it a lot easier to handle reading data from a file as lines of text.

As with object files, the basic steps are:
1. Open a file.
2. Write or read data.
3. Close the file.

Here are example programs, the first writes a simple text file. After you run it, you can take a look at the file it creates (in the same directory) using your favorite text viewer. You'll see normal text written line by line.

Then run the second program. It reads in the information line by line. It takes advantage of the fact that we know the format of the data file to read what's in it back into Java objects. You can do the same thing with any file that you either know the format of, or can detect the format of. For example, reading data from CSV files saved by spreadsheets (I'll provide a specific example of this in a future article.)

As always, you can download the program files from the Begin With Java Code Archive.


public class TextSave{

public static void main(String[] arg) throws Exception {
// Create some data to write.
int x=1, y=2, z=3;
String name = "Galormadron", race = "elf";
boolean hyperactive = true;

// Set up the FileWriter with our file name.
FileWriter saveFile = new FileWriter("TextSave.txt");

// Write the data to the file.
saveFile.write(x + "\n");
saveFile.write(y + "\n");
saveFile.write(z + "\n");
saveFile.write(name + "\n");
saveFile.write(race + "\n");
saveFile.write(Boolean.toString(hyperactive) + "\n");

// All done, close the FileWriter.

} //main()
} // TextSave


public class TextRead{

public static void main(String[] arg) throws Exception {
int x, y, z;
String name = "", race = "";
boolean hyperactive;

BufferedReader saveFile=
new BufferedReader(new FileReader("TextSave.txt"));

// Throw away the blank line at the top.
// Get the integer value from the String.
x = Integer.parseInt(saveFile.readLine());
y = Integer.parseInt(saveFile.readLine());
z = Integer.parseInt(saveFile.readLine());
name = saveFile.readLine();
race = saveFile.readLine();
hyperactive = Boolean.parseBoolean(saveFile.readLine());
// Not needed, but read blank line at the bottom.


// Print out the values.
System.out.println("x=" + x + " y=" + y + " z=" + z + "\n");
System.out.println("name: " + name + " race: " + race + "\n");
if (hyperactive)
System.out.println("Oh, yeah. He's hyperactive all right.");
else System.out.println("What a mellow dude.");

} //main()
} // TextRead