How to create arrays and strings – Java tutorial

Next, we will learn how to declare and initialize arrays, use subscripts with arrays, declare an array of objects, search an array for an exact match, pass an array to a method, and use the length field. An array is several data items that have the same type and name. You declare an array by placing brackets [ ] after the type. A subscript is the integer in the brackets that indicates an array’s elements. You initialize an array by placing the data for the array in curly braces { } after declaring the array. This next program shows how to utilize an array:

public class DemoArray
{
public static void main(String[] args)
{
double[] salary = {5.25, 6.55, 10.25, 16.85};
System.out.println("Salaries one by one are:");
for(int x = 0; x < 4; ++x)
System.out.println(salary[x]);
}
}

Here, salary is the actual array we want to declare, but in Java, it is preferred to put the brackets after double. After we declared the array, we initialized it with the data {5.25, 6.55, 10.25, 16.85} followed by the opening statement to print the arrays. The for() loop searches for the data and prints it out for as many times as there is data. The subscript [x] read the for loop for the elements to print.

When searching for an exact match, you need to combine all the information you have learned until now. Create a program like the one below:

public class Event2
{
private char eventType;
private double eventMinRate;
public Event2(char event, double rate)
{
eventType = event;
eventMinRate = rate;
}
public char getEventType()
{
return eventType;
}
public double getEventMinRate()
{
return eventMinRate;
}
}

Create arrays and strings

 

Let’s create a string arrays :

public class EventArray
{
static final double CORP_RATE = 75.99;
static final double PRI_RATE = 47.99;
static final double NON_PROF_RATE = 40.99;
public static void main(String[] args) throws Exception
{
Event2[] someEvents = new Event2[5];
int x;
char event = 'Z';
double rate = 0;
boolean codeIsValid;
char[] eventCode = {'C', 'P', 'N'};
double[] eventRate = {CORP_RATE, PRI_RATE, NON_PROF_RATE};
for(x = 0; x < 5; ++x)
{
System.out.println("Enter event type");
System.out.println("C for corporate");
System.out.println("P for private");
System.out.println("N for non-profit");
event = (char)System.in.read();
System.in.read(); System.in.read();
/* Absorbs the ENTER key */
codeIsValid = false;
for(int i = 0; i < 3; ++i)
{
if(event == eventCode[i])
{
rate = eventRate[i];
codeIsValid = true;
i = 3;
}
}
if(codeIsValid)
someEvents[x] = new Event2(event, rate);
else
--x;
}
for(x = 0; x < 5; ++x)
System.out.println("Event " + (x + 1) + " " + someEvents[x].getEventType() + " " + someEvents[x].getEventMinRate());
}
}

The doubles declared in the beginning, CORP_RATE = 75.99, PRI_RATE = 47.99, and NON_PROF_RATE = 40.99 are considered global because they are used throughout the program. Event2[ ] someEvents = new Event2[5] calls Event2 for the information for five different events. This is better known as “declaring an array of objects”. The statement boolean codeIsValid; checks for errors in input. char[ ] eventCode and double[ ] eventRate hold the data for the arrays. The for() loop for(int i = 0; i < 3; ++i) tests each input value to see if they are valid.

 

The if(codeIsValid) statement sends the data of the array unless it is incorrect, in which it subtracts 1 from the array so it can accept a correct input. Finally, the System.out.println(“Event ” + (x + 1) + ” ” + someEvents[x].getEventType() + ” ” + someEvents[x].getEventMinRate()); prints all five pieces of information.

This next program passes an array to a method. Although the code for this looks short, the printout is somewhat lengthy.

public class PassArrayElement
{
public static void main(String[] args)
{
int[] someNums = {5, 10, 15, 20};
int x;
for(x = 0; x < 4; ++x)
System.out.println("In main " + someNums[x]);
for(x = 0; x < 4; ++x)
methodGetsOneInt(someNums[x]);
for(x = 0; x < 4; ++x)
System.out.println("At end of main " + someNums[x]);
}
public static void methodGetsOneInt(int one)
{
System.out.println("In methodGetsOneInt " + one);
one = 999;
System.out.println("After change " + one);
}
}

You can even use arrays to input numbers. In programs like C, the use of scanf() accepts both character and integer alike. Java’s System.out.println() only accepts character input in the Unicode (or numeric) form. Integers are already numeric, so Java reads them in Unicode and prints them out that way. In order to use integers, you need to convert (or parse) them back to integers. The program below is one example:

public class NumInput
{
public static void main(String[] args) throws Exception
{
String inputString = new String();
char newChar;
int inputNumber;
System.out.println("Enter the number of guests at your event");
newChar = (char)System.in.read();
while(newChar >= '0' && newChar <= '9')
{
inputString = inputString + newChar;
newChar = (char)System.in.read();
}
System.in.read();
inputNumber = Integer.parseInt(inputString);
if(inputNumber > 100)
System.out.println("A surcharge will apply!");
}
}

Notice the line String inputString = new String();. This is the String constructor. This comes from the String class java.lang.String, which is automatically imported into every one of your programs that you create. Another way of writing this is String inputString = “”;. You can also create an array of Strings, such as String[] carMakers = {“Ford”, “Dodge”, “Chevrolet”};. Below is a program that uses a String array:

public class Employees
{
public static void main(String[] args)
{
String[] deptName = {"Accounting", "Human Resouces", "Sales"};
String[] empName = {"Don Johnson", "Mike Anderson", "Dave Larson"};
for(int a = 0; a < deptName.length; ++a)
System.out.println(deptName[a] + " -- " + empName[a]);
}
}

If you are comparing Strings, there are three methods you can use to make your comparisons, equals() which tests to see if two Strings are equal (i.e. aName.equals(anotherName)), equalsIgnoreCase() which tests to see if the two Strings have the same letters without checking the upper or lower case (i.e. aName.equalsIgnoreCase(“roGER”)), and compareTo() which tests to see what order the Strings should occur (“Robert” comes before “Roger” because “b” comes before “g”, the “Ro” in each name are the same).

In the “EventArray” program above, the line (“Event ” + (x + 1) + ” ” + someEvents[x].getEventType() + ” ” + someEvents[x].getEventMinRate()); adds several Strings together. This is called concatenation.

Question: Wow!! I like arrays. They seem to make programming so much easier to store multiple data items or allow for repetition. Is there a way to make two arrays work together?

Answer: Yes, there is. Next, we’ll learn about sorting, two-dimensional arrays and the StringBuffer class.