CodeGym /Java Course /Module 1. Java Syntax /Advanced array handling

Advanced array handling

Module 1. Java Syntax
Level 7 , Lesson 3
Available

1. String array

I'd like to give you a brief overview about String arrays.

As we said previously, an array can be of any type. This means you can create an array of Strings. If we wanted to write a program that "reads 10 lines from the keyboard and displays them in reverse order," here's what the code would look like:

Scanner console = new Scanner(System.in);
String[] array = new String[10];
for (int i = 0; i < 10; i++)
{
   array[i] = console.nextLine();
}
for (int i = 9; i >= 0; i--)
{
   System.out.println(array[i]);
}
Create a Scanner object
Create a 10-element array object
Loop from 0 to 9

Read a string from the keyboard and save it in the next cell of the array
Loop from 9 to 0

Display the next cell in the array

The code barely changed! We only had to replace int with String when creating the array. Well, and when reading the string from the keyboard, we also replaced the nextInt() method with nextLine().


2. String array in memory

And one more useful fact. Let's consider 3 pictures:

Picture 1. How a String object is arranged in memory:

String array in memory

This picture was taken from previous lessons.

Please note that the text of the string is not stored directly in the variable: a separate block of memory is allocated for it. A String variable stores the address (reference) to an object that stores the text.

Picture 2. How an integer array is arranged in memory:

String array in memory 2

This picture is also familiar.

Picture 3. How a string array is arranged in memory:

How a String array is arranged in memory

On the left we see an array variable whose type is String[] (it stores the address of an array object).

In the middle, we have String array object itself.

And on the right are string objects that store some text.

The cells of the String array do not store the strings themselves (the text of the String objects). Instead, they store their addresses (references to them). In the same way that String variables store the addresses of string objects (where the text is stored).

Take this into consideration when you compare array cells:

String[] array = new String[10];

array[1] = "Hello";
array[2] = array[1];
array[3] = new String("Hello");
// Compare
array[1] == array[2];
array[1] == array[3];
array[1].equals(array[3]);
array[1].equalsIgnoreCase(array[3]);
Create an array of 10 strings

Put values into the array



true (the references are equal)
false (the references are not equal)
true (the strings are equal)
true (the strings are still equal)

7
Task
New Java Syntax, level 7, lesson 3
Locked
Welcome! But not everyone.
This is the signIn() method that greets website users. Currently, it greets all users, but it should only greet registered users. All unregistered users have the name "user". Add username validation at the beginning of the signIn() method. If the name is "user", use the return keyword to abort execu

3. Fast array initialization in Java

Arrays are super useful, so Java's creators tried to make working with them as convenient as possible.

The first thing they did was to simplify array initialization, the process by which you supply the initial values of an array.

After all, in addition to data read from somewhere, a program also quite often needs its own internal data in order to work. For example, suppose we need to store the lengths of each month in an array. This is what the code might look like:

int[] months = new int[12];
months[0] = 31; // January
months[1] = 28; // February
months[2] = 31; // March
months[3] = 30; // April
months[4] = 31; // May
months[5] = 30; // June
months[6] = 31; // July
months[7] = 31; // August
months[8] = 30; // September
months[9] = 31; // October
months[10] = 30; // November
months[11] = 31; // December

But thanks to Java's creators, there is a way to write this more concisely:

// Lengths of months of the year
int[] months = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

You can simply list all the values of the array, separated by commas!

Convenient, right? But that's not all.

As it happens, the compiler can determine the type of the container (array object) based on the type of the values of the array. And to determine the length of the array, it's trivial to count the number of elements written in the curly braces.

That means this code can be written even shorter:

// Lengths of months of the year
int[] months = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

A thing of beauty, isn't it? 🙂

This is called "fast array initialization". By the way, this works for types other than int...

// Names of months of the year
String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November ", "December"};

7
Task
New Java Syntax, level 7, lesson 3
Locked
A cube calculator
Let's implement a calculator that will compute the powers of numbers. To do this, create a cube() method. It must take a long integer value as an argument. The method should raise the passed value to the third power and return it as the method's result. The numbers you have to work with may be large
7
Task
New Java Syntax, level 7, lesson 3
Locked
A cubed cube calculator
You won't blow any minds by unveiling a calculator that can raise a number to the power of three. But a calculator that can raise a number to the power of nine is another matter! So let's implement one! To do this, create a public static long ninthDegree(long) method. It must take a long integer val
Comments (10)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
haalk3n Level 6, Romania
15 February 2024
The "Remove duplicate strings" exercise is very stupid. How in the world are we supposed to know what we are doing? I've had to learn documentation, ChatGPT 50 times, then fight the validation process. I come from python. Either java is just a broken language or the compiler doesn't do what it's supposed to do.
Anonymous #11378639 Level 12, Moldova, Republic of
21 January 2024
The validation in the task "Remove duplicate strings" is absolutely insane. Please rewrite it, because it only passes if a student copies the "correct" solution line-by-line. I wrote a working solution within 10 mins, and after for 30 mins I was sitting trying to clone the suggested solution and understand what's wrong with my code. Eventually, the issue was that if I don't have a variable "String currentString = strings[i];", my solution is marked as wrong.
Henk Level 7, Pretoria, South Africa
4 April 2023
if my solution does the same, but is not exactly typed or designed like your solution, it does not pass validation.....
Campbell, Jackson Level 12, Corona, USA
11 October 2023
same man, I used a very different way of doing it, but I tested it and it did the same thing :( maybe arrays aren't my jam
ABHISHEK PANDEY Level 14, Mumbai , India
18 September 2022
String[] array = new String[10]; array[1] = "Hello"; array[2] = array[1]; array[3] = new String("Hello"); // Compare array[1] == array[2]; /* here evaluation is true not false*/ array[1] == array[3]; array[1].equals(array[3]); array[1].equalsIgnoreCase(array[3]);
Winter Lee Level 16, San Ramon, United States
4 October 2022
I guess it is a typo
Dhanush Gowda K R Level 22, India, India
13 December 2022
array[1] == array[2] applies only for integers not for String for String type we have .equals(); .
Aniko Level 6, Hungary
27 June 2023
It's not true! We can use array[1] == array[2] for String as well: == compares the references of the Strings equals() compares the value of the Strings
Junior Meador Level 24, Savannah, USA
28 August 2022
The "Remove Duplicate Strings" exercise is great practice with arrays! It definitely makes you think.
Bala Vedam Level 19, Washington, USA
26 January 2023
yes, its a tricky one