Arrays and strings
Declaring and initializing arrays
In Java, an array is a collection of variables of the same data type. You can declare an array by specifying its data type, followed by square brackets ([]
), and then the array name. You can then initialize the array by specifying its length and assigning values to each element. Here's an example:
In the above example, we declare an integer array called numbers
with a length of 3. We then assign the values 1, 2, and 3 to the first, second, and third elements of the array, respectively. We then print the values of the first, second, and third elements to the console.
Accessing array elements
You can access elements of an array using their index number, which starts at 0 for the first element. Here's an example:
In the above example, we declare and initialize an integer array called numbers
with the values 1, 2, and 3. We then print the values of the first, second, and third elements to the console.
Multi-dimensional arrays
In Java, you can also create multi-dimensional arrays, which are arrays of arrays. Here's an example of a two-dimensional array:
In the above example, we declare and initialize a two-dimensional integer array called matrix
with the values 1, 2, 3, and 4. We then print each element of the matrix to the console.
Working with strings
In Java, a string is a sequence of characters. You can declare a string variable by specifying its data type as String
, and then assigning a string value to it. Here's an example:
In the above example, we declare a string variable called greeting
with the value "Hello, world!". We then print the value of greeting
to the console.
You can also concatenate strings using the +
operator, or use methods to manipulate strings. Here are some examples:
In the above example, we declare two string variables firstName
and lastName
, and concatenate them to create a fullName
variable. We then print the value of fullName
to the console.
We also demonstrate the use of the length()
method of the String
class, which returns the length of the string.
That covers the basics of arrays and strings in Java!
Last updated