Much of the power of any programming language lies in its accompanying library. Java is no exception and, fortunately, will be familiar turf to C and C++ programmers.
One of the most time-consuming parts of learning a new language is familiarizing oneself with its libraries. C and C++ programmers just learning Java will be happy to know that many of the functions and classes they work with regularly have their equivalents in Java. This article will give a quick run down of some Java counterparts to common C/C++ functions and classes to aid in the transition between languages.
Strings
I'll start with one of the classes I use the most. The C++ string class can be replaced by the Java String class. There are some differences to keep in mind when doing so. Java String objects are immutable. Their contents can be replaced but not modified. This means you can't change the individual characters that make up a string the way you do in C or C++. However, you can replace the entire contents of a string with another string. For example:
String a = "old"; String b = "+new"; String a = a + b;String a will now hold "old+new".
Many of the string utility functions in the C library such as strlen, strstr, etc. have equivalent methods (the Java counterpart to a C++ member function) in the String class. For instance, the field String.length (member object) provides the length of a string much like the C library's stlren. The method String.indexOf locates the first occurrence of a character in a string. It can be used in a way similar to strchr and strcspn.
C's strcmp can be replaced by Java's compareTo. The method String.startsWith determines whether a string starts with a certain substring. It can be used in a way similar to strncmp. In place of C's strcat, you can use the method String.concat. The plus operator can also be used with Java String objects as shown in the previous example.
The method String.charAt gets a character from a specified index in a string. This function is the Java equivalent for accessing a character in an array of characters, which is traditionally done in C by using the operators [] or *. In place of strupr, available with some compilers, or using toupper on each character in an array, the method String.toUpperCase can be used to create a string with all uppercase characters. Java also has the complementary function String.toLowerCase.
Other useful Java String methods include String.substring and String.trim. Functions like these are often found in C and C++ programmers' string utilities libraries. Many of the methods in the Java String class operate similarly to member functions in the C++ string class. However, the names are different. Also, Java's String class uses 16-bit Unicode characters, not the one-byte characters most C and C++ programmers are accustomed to working with.
If you want the equivalent of the C strtok function, Java provides an entire class called java.util.StringTokenizer. Java also provides more sophisticated parsing utilities in its java.io.StreamTokenizer class.
When you need to modify individual characters, you're better off using the StringBuffer class. It offers methods such as setCharAt and append. You can also easily convert to and from String and StringBuffer objects so that you can work with the most efficient objects for your needs. StringBuffers are good for input/output, when you are appending, inserting, or changing characters often. They're also useful in cases where you don't know how large a string may grow.
If you need C functions like isdigit, isspace, tolower, toupper, these are all grouped together in the Java class Character. Java equivalents include methods such as Character.isDigit, Character.isSpace, Character.toLowerCase, and Character.toUpperCase.
Functions like C's memcpy and/or strcpy can often be replaced by System.arraycopy. Conversion functions like atoi and itoa are replaced by conversion methods in appropriate corresponding classes.
Conversions
To convert a String to an int, for example, use Integer.parseInt. To convert a String to a long, try Long.parseLong. To convert an Integer or a Long to a String, use the toString method for the particular class. Several other Java classes also provide a toString method. It's useful in debugging or when outputting information about an object to standard output or a file.
Math functions such as sin, max, min, exp, log, and sqrt are available in Java as part of the Math class. This class also includes a random method to create random numbers. There's a java.util.Random class if you need still more functionality.
For time and date functions, Java provides a Date class. The current date and time can be accessed by creating a Date object in Java with no arguments. The Date class can also be used to work with dates and times that the programmer specifies. There is no replacement method for C's difftime, but you can use methods such as before, after, and equals to compare two different Date objects.
The Date class's toLocaleString method is a substitute for C's strftime with a %c argument. The toGMTString method creates a string with a Greenwich Mean Time (GMT) representation of the date and time.
To get the number of elapsed milliseconds since midnight of January 1, 1970 GMT for a date and time represented by a Date object, you can use the getTime method. You can also get this value for the current date and time by using the System.currentTimeMillis method. The date class provides accessors to get and set hours, minutes, months, seconds, etc. You can even retrieve information about day of the week.
Input and Output
Writing to standard output and error are often useful capabilities in many C and C++ programs. Here's a quick comparison of how to write to standard output in C, C++ and Java, In C:
printf("%s", "to standard output");In C++:
cout << "to standard output";And in Java:
System.out.println ("to standard output");Reading and writing standard streams in Java is done using the System object. The standard output stream in Java is System.out, the input stream System.in, and for error output there's System.err. System.out and System.err can use any of the PrintStream methods, and System.in can use any of the InputStream methods.
If your program doesn't use standard input and output, it probably receives its input and output by way of a more complicated user interface such as those provided by GUI libraries. The equivalent of GUI windowing libraries like MFC, OWL, and Motif are found in the java.awt library. This library includes classes to create frames, dialogs, and controls such as push buttons and listboxes. It also has methods for handling events such as key or button presses. If you're already familiar with a GUI library, the Java awt has similarities with many common GUIs. It is fairly easy to make the transition to it.
C++ provides the classes istream, ostream, fstream, and strstream for file and standard input/output. Java has a whole series of stream classes for input and output. These are all available in the java.io library. The java.io.DataInputStream class is one of the most popular classes for reading from files. Both DataOutputStream and PrintStream are useful for writing to files. For random file access, the java.io.RandomAccessFile class works well.
Instead of C routines such as opendir, readdir, and closedir, you can use the java.io.File class. It provides methods like java.io.File.list, isFile, and isDirectory. To check if a file exists in C, you use a function like access or stat. In Java, the File class has an exists method. Some C compilers have a filelength function, or you can get the length from functions such as stat and fstat. The method java.io.File.length lets you get the length of a file in Java.
To rename a file, there's the java.io.File.renameTo method. To remove or unlink a file, there's java.io.File.delete.
Containers and More
Some of the STL container classes are replaceable by classes in the java.util library. The STL vector class can be replaced by java.util.Vector. If you need the functionality of an associative array or map class, in Java the Hashtable is a good choice.
There is a major difference between STL and the Java equivalents, however. STL is based on templates and uses generic programming techniques. Java bases all its classes on class Object. It uses inheritance in its counterpart to STL's container classes. When you add an object, such as a String object, to a Vector or Hashtable, the item is stored as an Object. On retrieval, you need to cast the object back to its original derived type, (i.e. cast the String object returned as an Object back to a String object). Incidentally, the casts in Java use the same syntax as that in C, not the new C++ syntax style.
Java has a more limited set of containers available than STL. It currently does not have the extensive algorithm support that STL has. There are no built-in Java parallels to algorithms such as sort, transform, reverse, rotate, accumulate, etc. The nearest equivalent to STL's iterators is Java's Enumeration class, which works with Vector, Hashtable, Properties, Dictionary, and AppletContext classes. There are several Java libraries currently available and in the works, both over the Internet and commercially, that will add more functionality.
Java provides some system related capabilities. The equivalent of C's exec or spawn functions are found in the Runtime.exec method. If you need an application to sleep for a certain number of seconds in Java, you can use a command such as Thread.sleep. The System.exit method does the same as the C exit function, it stops the program.
There's also a very convenient class in Java for creating the equivalent of a Windows INI file. You can store properties to a file and read them back in with defaults using the java.util.Properties class. In C, many compilers let you access environment variables. In Java, you can access only properties. Some properties are preset when you run a Java application or applet. Examples of preset properties include os.name, which is the name of the operating system, and java.version, the version of the Java interpreter you're working with.
In C, most compilers provide functions to get the current working directory. In Java, this information is also available as a preset system property, user.dir. To set system properties, some versions of the Java interpreter let you specify properties on the command line using the -D option. The System.getProperties method returns all system properties, while the System.getProperty method lets you access a specific property. To set system properties, use the System.setProperties method.
Applets require you specify information to be used in the program using the HTML PARAM tag. You retrieve these values by using the Applet.getParameter method. You can also pass information to a Java application on the command line, just as you do in C and C++ programs. The command-line information is available to an application's main method in the String args[] parameter.
Unless the C or C++ function is a system specific one (such as a command that lets you set registers or access an area of memory or a com port), there's usually an equivalent Java method. Java also has built-in library support for useful programming areas like threading and network operations. If you are not working on a very system-dependent C or C++ program, you can usually convert the program over to Java easily. Java is also very useful for prototyping C and C++ programs since some of its features, like garbage collection and bounds checking, can make coding in Java faster than coding in C or C++. Prototyping in Java may also encourage you to look for coding solutions in a new way. So, when you return to C/C++, you may come up with a design that you would not have considered if you only prototyped and coded your project using C or C++. o
Laura Michaels is a senior software engineer at INTERCOMP, creator of entertainment, hobby, and custom software. She can be reached through INTERCOMP, section INT-IP, Box 6514, Delray, FL 33482 or http://members.aol.com/lauram3017/index.html.