There was an error in this gadget

Thursday, October 20, 2011

Mobile Java

One of the nice things about Java is that is supported on more than desktop platforms, and has been for a long time. This means there is not only a large library of existing software, but also well-tuned development systems to use with mobile platforms.

By "mobile platform", I'm referring to smartphones and tablets. There are other mobile platforms, but these are the most common ones. Netbooks may also run a "mobile" operating system, or they may run a normal desktop OS. Those that run a normal desktop OS will run normal Java SE applications. Java SE is "Java, Standard Edition", the version that typically runs on a desktop or laptop computer.

Java ME is Java, Mobile Edition. It runs on most smartphones, and many tablets. It is very similar to the Java SE version covered in most of my articles. In fact, it is possible to write many applications using a subset of Java that will run without change under both Java SE and Java ME.

But normally a Java ME application will use user interface objects and interfaces that are specific to Java ME. In many ways these are more sophisticated than the ones for Java SE. Creating many types of graphical interfaces, such as tiled graphics, is easier in the mobile edition than in standard Java.

I have been writing small, simple applications for my cellphones for about ten years now. It's nice to be able to write your own little application for your own unique needs. I started writing Java applications for my Nokia 3650, called a "feature phone" at the time I got it. It was a Symbian Series 60 phone that ran an early version of Java ME with a very basic library of GUI features.

My next phone was a step up the Java ladder. It was a Sciphone G2, a fake Android phone. I didn't mind that it was "fake", it ran a real version of Java ME with updated GUI capabilities, which made it far easier to write applications for.

My current phone is a Blackberry Curve 8900. It runs Java ME with all the latest bells and whistles, plus a lot of Blackberry add-ons that make it easy to access the phone's features.

With my Nokia, I had a special Java development environment provided by Nokia that included a simulation of my phone, so that I could see how my programs would run before I put them on the phone. With the G2 I was on my own. I ran a standard Java ME development environment from within Eclipse, a great Java integrated development environment. The version linked above is a version specific to Java ME.

Now I'm back to having a development environment provided by my phone's maker. I have a program that simulates my phone on my computer, which again allows me to try out my programs before I put them on the phone (with my G2 I tested them as well as I could, then loaded them on the phone and hoped for the best.) It is build on Eclipse, so it is still very familiar. There is also a slew of information on the Blackberry site (linked above) about Java development.

Unfortunately, the tutorials on the site don't exactly match the actual current version of the software, but it's close enough it's not too hard to figure out. One thing that confused me, however, is the installation instructions. I thought I had to install the version of Eclipse they called for before installing the "Blackberry Java Eclipse Add-On". It's an add-on, right?

Well, it turns out that the "add-on" from Blackberry is actually the entire thing, Eclipse and all. So you just need to do that one download to get the development environment. Then download the simulator for your phone and any others you want to test your software on. Finally, apply for a signature key to make it so that you can "sign" your software to allow it to be installed on the phone through the software manager or Over The Air (OTA) when using the Blackberry-specific libraries.

If you'd rather not do this, you can develop software using a plain-jane version of Java ME, then transfer the software to your phone however you please. I put the software I developed for my Sciphone G2 on the memory card for my Blackberry, and it runs just fine.

Translating applications between Java SE and Java ME can be simple for ones with minimal amounts of graphics, like programs that mainly use text, buttons, and text entry boxes for communication. Things like games, with a more involved use of graphics, take more effort to translate between the two versions of Java. For these, I usually re-use the game logic code without changes, then rewrite the graphical display parts of the program from scratch. Because I use good object-oriented coding practices (most of the time), this isn't too much effort.

Java ME applets are easy to translate, though I write almost all of my Java software as applications now.
StumbleUpon

Monday, September 5, 2011

Numeric Literal Values

Java 7 has added a new feature, binary literals for integer number types (byte, short, int, and long.) Before we can get excited about this, we need to know what that means. In earlier versions of Java, we have had several other types of literal value.

Let's Get Literal

What is a "literal"? A literal is an explicit value. For example, in this line:
int number=123;
the value 123 is a "literal". Since it's a normal base-10 value, we might say it is a "decimal literal". Decimal values don't have to be marked in any special way.

A hexadecimal literal looks like this:
int number=0x007b;
The value 0x007b is a hexadecimal (base 16) number that is expressed literally (stated explicitly.) The 0x at the beginning is what marks it as a hexadecimal value. The leading zero shows that it's a numerical value, not a variable name or keyword or something like that. The x marks it as a hexadecimal number.

Hexadecimal numbers take binary values four bits at a time (a bit is a single one or zero value) and puts them into a single digit. Octal (base 8) digits each represent the values of three bits.

To tell Java you're using an octal value, place a leading zero in front of the number itself:
int number=0173;
Here the number 0173 is an octal value equal to 123 in decimal. If we accidentally put a zero in front of a decimal integer, we'll either get an error (if we use the digits 8 or 9 in that number) or the value will be interpreted incorrectly. For example, if we want to put the value of one hundred twenty-three into a variable, but instead of the line we have above we accidentally add a zero, like this:
int number=0123;
The value of the number will be interpreted as eighty-three, not one hundred twenty-three. So watch out for that.

New for Java 7--Binary Literals
In Java 7 we get a new ability, the use of binary numbers. Since you know that you can encode binary values into both octal and hex either three or four bits at a time, this may not seem like a really big deal. In fact, there's been a request to add this feature to Java for a long time, but it's been low priority.

But now it's finally here.

So you can define values as individual bits, like this:
int number=0b01111011;
That's the binary for one hundred twenty-three, by the way. Why is this important?

As Java becomes more mature, and more widely used, it is used in more places. Over time, high level languages that deal with things at a very abstract level tend to get used in more situations where it is nice to have the high level features while also having the ability to have low level control or simulation of the actual computer hardware. In cases like these, it is nice to be able to manipulate single bits in places where they represent specific individual signals in the computer system or simulation.

For example, let's say we want to recreate an old 1980s computer in a Java program, like a Commodore 64. The Commodore 64 reads several signal lines directly on its joystick ports. We want to be able to simulate the behavior of these ports so that we can play old C-64 games in our simulation. Each of the lines represents a switch in the joystick. So we may take a particular keypress and represent it as the following binary value:

byte stick_up=0b00001;

In this case, we show it setting the lowest order bit. We might have another like this:

byte fire_switch=0b100000;

Since these each equate to specific electrical signals that get "turned into bits" in the C-64's CIA chip, it's nice to be able to tell them to Java as bits. We could have used hex or octal, but it's a bit nicer to see them as individual bits.
StumbleUpon

Friday, June 24, 2011

Java Variable Value Assignment: Left Equals Right, Left Becomes Right

One of those things that vexes beginning programmers is assigning values to a variable in Java. Part of what makes it so vexing is that the problem is practically invisible to an experienced programmer. Another part of it is that we use the equals sign (=) to do the assignment.

Take a look at these statements:

int i = 1;
j=7;
7+count=c;
b+14=a+9;

The first two are fine (assuming that 7 is a valid value for whatever type of variable j is), but the last two are wrong.

Remember All That Algebra We Taught You? Well, We Broke It.

After you've gone to all the trouble to learn how to deal with things like 7+count=c and b+14=a+9 in algebra class, now we take what you know and turn it on its ear in programming class. Sweet, eh?

The problem is that the = we use in programming has pretty much nothing to do with the = that you use in math. It's just close enough to be confusing. In Java, the equals sign is an assignment operator, not an indicator of equality between values as it is in math. There is a comparison operator for equality in Java, it's ==, and we'll talk about it shortly. First, let's talk assignment.

Assignment

In computers, we use the term assignment to describe sticking a value into the computer's memory so that we can get it back later. It's like using the memory in a programmable calculator. We put some number into our calculator's memory so that we can get it back later for another part of our calculation. It's pretty much the same thing with computers.

With Java, we can store all kinds of values, not just numbers. We can store sections of text, called strings in a String variable, for example. (Java prefers the term "member" over variable, in general. For what we're talking about now, the two terms are interchangeable.) We can also store more than one thing at a time, like all the information about a bicycle in a Bicycle object that keeps track of a bicycle's color, frame size, tire size, gear ratios, etc., all together in one object.

But we're here to just look at assignment today, not the wide variety of things we can assign as values.

To store a value on a calculator, you use some key sequence like M+ or STO 00 to store the value in the calculator's display to memory. With Java, we use the equals sign to store some value on the right into whatever is on the left side of the equals sign. We read from left to right like this:

count = a;
"count equals a"

This means we take the value of a and place it in count. But a better way to read that equals sign is to use the word "becomes" instead of "equals":

count = 9;
"count becomes nine"

This makes it more obvious that we're putting in a new value that changes the value of count. In this case, we're putting in a value of 9. The statement up above would be "count becomes a" or, better yet, "count becomes a's value." Because what we're doing in count= a; is taking the value in variable a and copying it into count. If we then print the value in count, it will be the same as whatever is in a at that time.

We can also compute a value to put into our variable.

count = a + 1;
"count becomes a plus one"

This makes the value in count be one more than the current value of a.

What we can't do is change sides around the equals sign. In algebra, c = a + 1 is the same as a + 1 = c. But in Java that doesn't work:

a + 1 = count
This is wrong in Java. Does not compute. Norman, Norman, help me Norman!

We would be trying to make a+1 become the value in count. The problem is, you can't have a storage location named "a+1". Java doesn't see this the way your algebra trained eyes do.

Comparisons

In normal math, when we use the equals sign we are making a comparison. We are stating that what's on one side of the equals sign is the same as what's on the other side. For most algebra problems, we assume that the statement is true and try to find values for the variables that result in that.

Another use of equals in some math problems is to state that two things are equal when they may or may not be, then determine whether that statement is true or not. You remember those problems, they looked something like this:

State whether each of the following is true or false.
1. 11 = 6 + 5
2. 14 = 3 x 7
3 65 - 14 = 17 x 3


In Java, the equals sign is already used for assigning values to variables. How do we do a comparison to see whether it's true or not?

The == Operator

In some languages, = does both jobs. But in Java, there's a second operator for doing equality comparisons, ==, "equals equals". When we want to see if two values are the same, we compare them using a statement something like this:

if (count == 100) then stop();

This compares count to the value 100, and executes the method stop() if the result of the comparison is true.


The Dangers of the = Operator

Something to look out for is using = by accident in such a situation. Like this:

if (count = 100) then stop();
Don't do this if you want to compare count to 100!

What this does is assign the value 100 to count. If the assignment is successful (which it almost certainly will be, if the program compiles), the program will then do stop() every time it hits this statement! Because the assignment was successful, so the result is considered to be true.

Summary

The equals sign makes the variable on the left equal the computed value from the right side of the equals sign:

name = "Mergatroyd";
"name becomes Mergatroyd"

It doesn't work the other way around (putting something from the left into the variable on the right.)

If you want to compare to values to see if they're equal, use "equals equals":
if (state == "done") then exit();
"if state equals equals done then exit" or
"if state is equal to done then exit"
StumbleUpon

Tuesday, June 7, 2011

Doing Math in Java part 2:Functions

The basics of math in Java using operators was covered in Part 1: Operators. There I went over the standard operations built into the language itself, rather than in its APIs (libraries).

But that's hardly the end of useful math operations. Especially when doing graphics, where all those geometric and trigonometric functions come in so useful. Square root, cosine, absolute values, etc.

If you're wandering into the Java APIs unguided, the java.math package might catch your eye right away. Unfortunately, it's a false trail when what you're looking for is a simple general purpose math package (it's a nice special-purpose math package for particular sorts of calculation, however.)

What you really want is the java.lang.Math class, in the java.lang package.

This has most of the standard math functions you're used to. They're defined as static methods, so you don't need to create a Math object to use them. You just call them like this:

    float distance = Math.sqrt(dx*dx + dy*dy);
float speed = Math.abs(velocity);


These call the square root function Math.sqrt() and absolute value function Math.abs(). There are a slew of others like degree to radian conversion, the standard trig functions, and so on.

Date Calculations

Calculations with dates are another standard sort of math that's not covered by standard operators. In the package java.util we've got the Calendar class. The Calendar class itself is an abstract class. This means that it's a class used to build other classes with, not to use directly. The GregorianCalendar class is a concrete implementation of Calendar that you can use directly. The Calendar object's add() method will add or subtract some amount of time--days, minutes, hours, etc.--to or from a given date (the date that the object is set to:

  1. Create a GregorianCalendar Object

  2. Set its date

  3. Use its add() method to add or subtract the time difference.


Example:
GregorianCalendar myDate;
myDate = new GregorianCalendar(2011, 6, 7); //set the date to 07 June 2011.
myDate.add(Calendar.Date, 165); // add 165 days to that date.


before(), after() and compareTo will return whether one date occurs before or after another. Computing the number of days between two dates is a bit more complex, unfortunately, as are similar calculations. Basically, the procedure is to use getTime() to convert both dates to time values, get the difference, then divide that by the time units you want to see the difference in (e.g. divide by 24 hours periods to get the difference in days.)

Unfortunately, the Calendar class demonstrates one of the problems with much of Java. It's an overly generalized class that prevents simple solutions to many simple and obvious problems. The older Date class took a more direct approach, but it has been deprecated in favor of the Calendar based classes. Unfortunately, even obtaining a printable date value according to the system's current locale takes a fair bit of set up in Java. A better solution would have been a very general class like Calendar behind a more usable class for solving conventional problems, but Java's development got it backward. We got the simple class first, it's inflexibility for solving certain problems resulted in criticism, then came a general class, which is no good at doing simple and obvious things for most users. The extra layer that we should have to make Calendar more usable has not yet appeared in the standard API (and possibly never will.)

So it takes a lot of code to do what should only take a line or two, when working with dates.

Still, give the Calendar and GregorianCalendar class a look-over. Even though it takes some extra code and set-up to do some simple tasks, the solutions to these problems are well established and many examples are available. It's just not as simple as System.out.println(myDate);

I'll be adding articles dealing specifically with dates myself at a future date.
StumbleUpon

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.

Operators

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.
StumbleUpon

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(){
System.out.println("Hello!\n");
}

/**
* 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 UseHello.java)

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:
HelloClass.sayHello();

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: http://saundby.com/beginwithjava/.
StumbleUpon

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
// CSVRead.java
//Reads a Comma Separated Value file and prints its contents.


import java.io.*;
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.
CSVFile.close();

// End the printout with a blank line.
System.out.println();

} //main()
} // CSVRead


Downloads

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 TextSave.java, modify it appropriately, then see what your favorite spreadsheet program thinks of the results.
StumbleUpon

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 java.io 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.

TextSave.java


import java.io.*;

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("\n");
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");
saveFile.write("\n");

// All done, close the FileWriter.
saveFile.close();

} //main()
} // TextSave


TextRead.java


import java.io.*;

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.
saveFile.readLine();
// 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.
saveFile.readLine();

saveFile.close();

// 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.");
System.out.println();

} //main()
} // TextRead
StumbleUpon

Thursday, April 14, 2011

Java File Save and File Load: Objects

Jump to Reading Data from Files with Java>>

Saving Data to Files with Java


Saving objects to a file in Java has a few steps to it, but it's pretty easy. We open a file to write to, create a "stream" for putting objects into the file, write the objects to that stream to put them in the file, then close the stream and file when we're done.

To reiterate:

1. Open a file.

2. Open an object stream to the file.

3. Write the objects to that stream.

4. Close the stream and file.

1. Opening the File
To open a file for writing, we use a FileOutputStream object. When we construct the new FileOutputStream, we give it a file name to open. If the file name exists, it opens the existing file. Otherwise, it creates a new file. To keep things simple, we're not going to check for a file existing here, or anything like that.

Example:
FileOutputStream saveFile = new FileOutputStream("saveFile.sav");

2. Open an Object Stream
To write objects to the FileOutputStream, we create an ObjectOutputStream. We give it the FileOutputStream object we've set up when we construct the new ObjectOutputStream object.

Example:
ObjectOutputStream save = ObjectOutputStream(saveFile);

3. Write Objects
When we write objects to the ObjectOutputStream, they are sent out through it to the FileOutputStream and into the file.

Example:
save.writeObject(objectToSave);

4. Close Up
When we close the ObjectOutputStream, it'll also close our FileOutputStream for us, so this is just one step.

Example:
save.close();

Example Program:
import java.io.*;
import java.util.ArrayList;

public class SaveObjects{

public static void main(String[] arg){

// Create some data objects for us to save.
boolean powerSwitch=true;
int x=9, y=150, z= 675;
String name="Galormadron", setting="on", plant="rutabaga";
ArrayList stuff = new ArrayList();
stuff.add("One");
stuff.add("Two");
stuff.add("Three");
stuff.add("Four");
stuff.add("Five");

try{  // Catch errors in I/O if necessary.
// Open a file to write to, named SavedObj.sav.
FileOutputStream saveFile=new FileOutputStream("SaveObj.sav");

// Create an ObjectOutputStream to put objects into save file.
ObjectOutputStream save = new ObjectOutputStream(saveFile);

// Now we do the save.
save.writeObject(powerSwitch);
save.writeObject(x);
save.writeObject(y);
save.writeObject(z);
save.writeObject(name);
save.writeObject(setting);
save.writeObject(plant);
save.writeObject(stuff);

// Close the file.
save.close(); // This also closes saveFile.
}
catch(Exception exc){
exc.printStackTrace(); // If there was an error, print the info.
}
}
}

Reading Data Files with Java


Now we need to know how to get data back from a file with Java. Since the data objects were stored using an ObjectOutputStream, they are saved in a way that makes them easy to read back using an ObjectInputStream.

There's one problem with ObjectImputStream, however. It doesn't return objects of the specific classes that they were originally. It just returns generic Objects. To get things back into their original class, we have to cast them into that type. Usually that means we need to know what their class was when they were written. It's possible to save class information along with the data, but in this case we just assume that we're reading back a file we have written, so we already know what class everything should be. I'll go into the details of reading other files in another article.

The steps are practically the same as for writing objects to a file:

1. Open a file.

2. Open an object stream from the file.

3. Read the objects to that stream.

4. Close the stream and file.

1. Opening the File
To open a file for reading, we use a FileInputStream object. When we construct the new FileIntputStream, we give it a file name to open. If the file name exists, it opens the existing file. Otherwise, we get an error which will print out a nastygram when we get to our catch statement. To keep things simple, we're not going to check for a file existing here.

Example:
FileInputStream saveFile = new FileInputStream("saveFile.sav");

2. Open an Object Stream
To read objects to the FileInputStream, we create an ObjectInputStream. We give it the FileInputStream object we've set up when we construct the new ObjectInputStream.

Example:
ObjectInputStream restore = ObjectInputStream(saveFile);

3. Read Objects
When we read objects from the ObjectInputStream, it gets then from the file.

Example:
Object obj = restore.readObject();

3 and a half. Cast Back to Class
Step 3. only restores a generic Object. If we know the original class, we should cast the Object back to its original class when we read it. If we had stored a String object, we'd read it something like this:
String name = (String) restore.readObject();

4. Close Up
When we close the ObjectInputStream, it'll also close our FileInputStream for us, so this is just one step.

Example:
restore.close();

Here's an example program to read back information saved by the first example program:
import java.io.*;
import java.util.ArrayList;

public class RestoreObjects{

public static void main(String[] arg){

// Create the data objects for us to restore.
boolean powerSwitch=false;
int x=0, y=0, z=0;
String name="", setting="", plant="";
ArrayList stuff = new ArrayList();

// Wrap all in a try/catch block to trap I/O errors.
try{
// Open file to read from, named SavedObj.sav.
FileInputStream saveFile = new FileInputStream("SaveObj.sav");

// Create an ObjectInputStream to get objects from save file.
ObjectInputStream save = new ObjectInputStream(saveFile);

// Now we do the restore.
// readObject() returns a generic Object, we cast those back
// into their original class type.
// For primitive types, use the corresponding reference class.
powerSwitch = (Boolean) save.readObject();
x = (Integer) save.readObject();
y = (Integer) save.readObject();
z = (Integer) save.readObject();
name = (String) save.readObject();
setting = (String) save.readObject();
plant = (String) save.readObject();
stuff = (ArrayList) save.readObject();

// Close the file.
save.close(); // This also closes saveFile.
}
catch(Exception exc){
exc.printStackTrace(); // If there was an error, print the info.
}

// Print the values, to see that they've been recovered.
System.out.println("\nRestored Object Values:\n");
System.out.println("\tpowerSwitch: " + powerSwitch);
System.out.println("\tx=" + x + " y=" + y + " z=" + z);
System.out.println("\tname: " + name);
System.out.println("\tsetting: " + setting);
System.out.println("\tplant: " + plant);
System.out.println("\tContents of stuff: ");
System.out.println("\t\t" + stuff);
System.out.println();

// All done.
}
}

<<Return to How to Save to a File with Java

The example programs can be downloaded at:
Begin With Java Code Downloads
StumbleUpon

Sunday, March 20, 2011

Cleaning Out the Sun References

Today I'm going to start cleaning out the references in old posts to Sun Microsystems. Sun is gone now, except for a page that tells you it's gone and points toward Oracle. Oracle bought Sun, and now owns Java.

Many of my old articles point toward the previous Sun website. I'll be changing those to point to current locations for the same resources, mostly to be found on java.net.

If you come across something I appear to have missed, feel free to email me with the article title so that I can fix it. Thanks!

One More Thing

It's worth noting that since some of these articles were written, the official online resources have improved. I still think there are some major gotchas for new learners in Java, but things are definitely better than when I started this blog.
StumbleUpon

Tuesday, January 25, 2011

Java's File Names and Class Names

Java is picky about the file names you use.

Each source file can contain one public class. The source file's name has to be the name of that class. By convention, the source file uses a .java filename extension (a tail end of a file name that marks the file as being of a particular type of file.)

So, for a class declared as such:

public class HelloWorld{
...

The file it is stored in should be named HelloWorld.java.

The capitalization should be the same in both cases. Some operating systems don't notice whether file names are capitalized or not. It doesn't matter, you should be in the habit of using the correct capitalization in case you work on a system that does care about capitalization.

When you compile your file with javac, you pass the full file name to javac:

javac HelloWorld.java

Let's say we save the file under a different name. We write the following program:

public class HelloThere{
public static void main(String arg[]){
System.out.println("Hello There.");
}
}

Then we save it as HelloWorld.java, and try to compile it:

>javac HelloWorld.java
FileName.java:1: class HelloThere is public, should be declared
in a file named HelloThere.java
public class HelloThere{
^
1 error


Java lets us know that it won't compile until we rename the file appropriately (according to its rules.)

So let's rename the file. Let's call it HelloThere.javasource. Seems a bit more explicit than just .java, right? Let's run the compiler:


>javac HelloThere.javasource
error: Class names, 'HelloThere.javasource', are only accepted
if annotation processing is explicitly requested
1 error

Java's still not happy with us. Annotation processing? That's when we include extra information in the program about the program itself. We're not bothering with that just now. So we should just name the file HelloThere.java, and not get fancy with our file names.

But, under the right circumstances, javac does allow file name extensions other than .java. That's why we always type in the full file name, including .java, when we use javac. We say 'javac HelloThere.java', not just 'javac HelloThere'. Javac can't assume that we mean a .java file, though that's what it will usually be.

The Class File

Once we make javac happy with a proper file name, and a program with no errors, javac produces a new file. This file will have the original file name, but with .java replaced with .class. This is your bytecode file, the file that the Java Virtual Machine can run.

When we run the program with Java, we're running the .class file. In the case of HelloThere, we're running the HelloThere.class file. But we don't type in the full file name. Why?

Unlike javac, java requires a .class file. That's all it will work with. There's no opportunity to have a different extension to the file name. So it assumes the .class part of the file name. But that's not the whole story.

If you add .class yourself, here's what you'll get:

>java HelloThere.class
Exception in thread "main" java.lang.NoClassDefFoundError:
HelloThere/class
Caused by: java.lang.ClassNotFoundException: HelloThere.class
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)

Pretty ugly. What we're actually doing when we type "java HelloThere" is telling Java to run the class HelloThere. Java assumes that it will find this in a file called "HelloThere.class", so that's what it's looking for first.

We're not telling Java to run the file HelloThere.class, we're telling it to run the class HelloThere, which it expects to find in the file HelloThere.class.

But what if we ask for another class that doesn't have its own .class file?

Just for fun, let's change HelloThere.java like this, and see what happens:
public class HelloThere{
public static void main(String[] arg){
System.out.println("Hello.");
}
}

class HelloZoik{
public static void main(String[] arg){
System.out.println("Zoiks!");
}
}

After we edit it, we compile with 'javac HelloThere.java' and hold our breath.

Hurray! No errors!

Now we have a second class, HelloZoik, in the HelloThere.class file. Can Java find it?

Let's try:
 java HelloZoik
Zoiks!

It worked! Java found our class inside HelloThere.class.

This shows it's not the file name that we're calling with the 'java' command, it's the class name.

If Java doesn't find the class inside a file with the same name as the class followed by .class, it'll look in the other .class files available.
StumbleUpon

Tuesday, January 4, 2011

Should I Still Learn Java?

With all the controversy surrounding Java thanks to the purchase of Sun by Oracle, the lawsuits flying back and forth over the Java Community Process, the Apache Foundation, Android, and all the rest, does it still make sense to learn Java?

After all, the demise and abandonment of Java is being predicted practically every day.

I say Yes, now is the time to learn Java. No matter what your programming skill or background, Java is a valuable language to learn, it will be used and useful for a long time to come.

Never a Dull Moment

The Java language has been a-swirl in controversy since its public announcement. It has not become "the" language in many of the areas it originally claimed to be "the" language to use, but yet it has become popular in many other areas. In fact, Java is neck and neck with the language C for being the most popular computer language:

TIOBE Software Community Index (of most popular programming languages.)

langpop.com Programming Language Popularity Rankings.

Devtopics.com Most Popular Programming Languages.

Why Popularity Matters

Why does popularity matter? Because it entrenches a programming language, not just for now, but for many years to come. In fact, every language that has ever become deeply entrenched is still with us, so there's no way of knowing just how long popularity will keep a programming language alive.

When I was first learning to program, the big languages were assembly (the "real" programmer's language of the time), BASIC, FORTRAN, and COBOL. Every single one of those is still a viable language today. Though if you'd asked me then, I would never have thought COBOL would still be with us today. I would never have believed how popular it is, either.

But COBOL was re-invented in the late 80's. And there were a lot of big-money installations running on it. ADA failed to displace it. It's still here, and it's still a valuable part of a programmer's resume for many jobs.

FORTRAN is a language I expected to re-invent itself. It had already done so by the time I learned it (I first programmed in the original FORTRAN, but FORTRAN IV was already in common use.) But with the promulgation of Pascal, Modula-2, and C in the 80's I figured FORTRAN would be pushed into the recesses of obscurity. I was wrong.

Modula-2 was mishandled by the company that owned the rights to it, so it never took off as well as it might have. Pascal took off even though it was never intended to be anything but a classroom language. C took off since it didn't have Modula-2's licensing disadvantages and it had enough of its advantages to become the "next generation language" of its day.

Modula-2 is still with us, but it's insignificant among languages today. Because it never got popular. The others I mentioned got popular, and they're still popular today. Yeah, even Pascal. You could learn Pascal today and do a lot with it (though I don't recommend it unless you want the academic challenge of broadening yourself as a programmer.) I still write software in Pascal, though mostly for my own use, and only for older computer systems.

The key to a programming language's longevity is popularity. Once a language becomes sufficiently popular, for all practical purposes it will never die.

Java is that popular.

The Many Javas

Java has become deeply ingrained into the modern computer infrastructure. Not only does the Java Virtual Machine support a lot more languages than Java itself, but Java has spawned other languages so close to itself that if you know Java you can pick up the other languages without significant effort. C# is the most popular of these spin off languages.

Plus, there are different versions of Java. The Mobile Edition, used on cell phones, smart phones, and PDAs, is a major programming language for these platforms. Each of these platforms has its individual programming suite, and associated language. Their second language, the Esperanto of the portable world, is Java. Programmers that want their software to move easily between platforms often choose to write their code in Java.

The use of Java on servers is rife as well. Java Enterprise Edition became the most popular use of the Java language when Java was still struggling to be used as an applications programming language over a decade ago. Some say that Java on the server saved the Java language. Certainly this is what makes Java a good language to learn for professional reasons.


The Most Important Reason

The most important reason to ignore all the hullabaloo about Java's impending demise and not worry about learning it is that:

  • it is a good language that's fairly easy to learn,

  • expressive enough to do a lot of different things effectively,

  • easy to develop sophisticated modern programs in

  • without too much work for an individual or small group of developers,

  • gives access to all the important parts of the machine (graphics, sound, filesystem, peripherals)

  • and what you learn travels well to other languages when you go on to learn them.



It's not going to go away any time soon. There's too much momentum. There's no need to worry. Ever since the launch of Java I've heard that it's going to be gone or unusable tomorrow. History shows that just doesn't happen to popular programming languages.

If you learn Java now, you may still be using it 20 years from now. Or 30.

When I sat down to a card punch to write my first program 38 years ago as I write this, the computer lab know-it-all came to look over my shoulder.

"FORTRAN!" he said. "Why are you wasting your time with that language? It's a dead, old language. Did you know it's the oldest computer language? If you really want to be a programmer, you should start right out in BAL*! That's what real programmers use, and you're going to be behind if you waste your time on anything else."

FORTRAN doesn't make the "top 10" in programming languages much any more, but it gave me a good start. It's still among the most popular languages, around #20, or just out of the top 10 if you only count general purpose programming languages (that is, not counting scripting languages, query languages, application-specific languages, and so on.)

And learning FORTRAN never kept me from learning structured languages, AI languages, Object Oriented languages, and so on. Even though my first program included the "dreaded" GO TO statement.

There's never been a better time to learn to program. And there's never been a better time to learn Java (the language is in the best shape it's ever been!)

*Basic Assembly Language, a version of assembly language for IBM computers.
StumbleUpon