Introduction to Java : Data Types and Operators Part-3

Strings

As you may have noticed, in Java, there is no variable type called string. However, although Java does not have a built-in String type, it does provide you will a predefined class called String that you can use instead.

We’ll talk more about classes and using them in later sections. However, it would be nice to at least introduce the String class here so we can use it in the meantime.

To instantiate a String, you simply use the same syntax that you would if it were a type:

Strings have quite a few methods that allow you to manipulate them in every way that you could in Perl. To read about these methods, simply use the online documentation. We will talk about how to efficiently use the online documentation a little bit later but you should know that you can find the String class in the java.lang package.

Arrays

List arrays (also known simply as “arrays” for short) take the concept of scalar variables to the next level. Whereas scalar variables associate one value with one variable name, list arrays associate one array name with a “list” of values.

Java has a built-in array class that you can use to hold multiple values so long as those values are of the same data type.

In Java, arrays are fairly restrictive. For example, you may not change the size of an array once you have created it. To add elements to an array dynamically, for example, you actually have to create a new, larger array and copy the old array into the new one using arrayCopy() in the java.lang.System class.

For a dynamically resizable data structure, you may want to look to the Vector class in the java.util package. We’ll talk more about Vectors later.

However, for cases in which you do not need to dynamically resize your data structure, arrays work great. Java provides a zero-based array that is defined much as variables are. You first declare what type of data will be stored in an array, give the array a name, and then define how large it is. Consider the following example:

This array would hold 50 ints indexed from 0-49.

To get or set a value, you simply access it by its index in the array. For example, to fill an array with the number 0-49 and then print the value 49, you might use:

Java also allows you to define an array at the time of initialization such as in the following example: