Search Java Programs

Thursday, January 7, 2010

Arrays, Strings and Other Common Types

Arrays

All primitive types can be turned into arrays. Arrays are simply indexed lists of the type in which they are initialized. Arrays are initialized by adding [] to the type when declaring the variable.
Create a file ArrayEx.java

class ArrayEx {
public static void main(String[] args) {
int[] iArr;
char cArr[] = {'F', 'a', 'k','e', 'S', 't', 'r', 'i', 'n', 'g'};

iArr = new int[4];
iArr[0] = 1;
iArr[1] = 10;
iArr[2] = 20;
iArr[3] = iArr[1] * iArr[2];
System.out.println(iArr.length);

System.out.println(cArr.length + " - " + cArr.toString());
}
}

First initialize an integer array and a character array. The character array is not a real string as the example will show. You need to use the String type explained next for that. Notice that the first index of the array is 0. So the integer array iArr has 4 indexes numbered 0-3.

Strings

Strings in Java are implemented through java.lang.String. java.lang.String provides a good interface for the storing and manipulation of string data.
Create the file StringEx.java

class StringEx {
public static void main(String[] args) {
String s = "new string";

System.out.println(s);
System.out.println("Length: " + s.length());
System.out.println("Number of words: " + s.split(" ").length);
}
}
Initialize a new String s with the value "new string" without the quotes. Print the string. Then print the length of the string. The split method accepts a string as an input and uses that to break the string into an array of strings. We then take the length of that array. In the example we split on a space and use that to calculate the number of words in the string.

No comments:

Post a Comment

Website Design by Mayuri Multimedia