Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
To declare an array, define the variable type with square brackets [ ] :
String[] names;
We have now declared a variable that holds an array of strings. To insert values to it, you can place the values in a comma-separated list, inside curly braces { }:
String[] names = {"Saras","Krithi","Brindha","Magi"};
To create an array of integers, you could write:
int[] numbers = {10, 20, 30, 40};
Access the Elements of an Array
You can access an array element by referring to the index number.
String[] names = {"Saras","Krithi","Brindha","Magi"};
System.out.println(names[0]);
//output:Saras
This statement accesses the value of the first element in names: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change an Array Element
To change the value of a specific element, refer to the index number:
names[0] = "Sri"
String[] names = {"Saras","Krithi","Brindha","Magi"};
names[0] = "Sri";
System.out.println(names[0]);
//Now outputs Sri instead of Saras
Array Length
To find out how many elements an array has, use the length property:
String[] names = {"Saras","Krithi","Brindha","Magi"};
System.out.println(names.length);
// Outputs 3
The new Keyword
You can also create an array by specifying its size with new.
This makes an empty array with space for a fixed number of elements, which you can fill later:
String[] names = new String[4]; // size is 4
names[0] = "Saras";
names[1] = "Krithi";
names[2] = "Brindha"
names[3] = "Brindha"
System.out.println(names[0]); // Output:Saras
However, if you already know the values, you don't need to write new. Both of these create the same array:
//with **new**
String[] names = new String[] {"Saras","Krithi","Brindha","Magi"};
// Shortcut (most common)
String[] names = {"Saras","Krithi","Brindha","Magi"};
You cannot write new String[4] {"Volvo", "BMW", "Ford", "Mazda"}.
In Java, when using new, you either:
- Use new String[4] to create an empty array with 4 slots, and then fill them later
- Or use new String[] {"Saras","Krithi","Brindha","Magi"}; (without specifying the number of elements) to create the array and assign values at the same time The shortcut syntax is most often used when the values are known at the start. Use new with a size when you want to create an empty array and fill it later.
Java Arrays Loop
You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.
This example creates an array of strings and then uses a for loop to print each element, one by one:
public class Main {
public static void main(String[] args) {
String[] cars = {"Saras", "Krithi", "Brindha", "Magi"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
}
}
//output
Saras
Krithi
Brindha
Magi
Here is a similar example with numbers. We create an array of integers and use a for loop to print each value:
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
//output
10
20
30
40
Calculate the Sum of Elements
Now that you know how to work with arrays and loops, let's use them together to calculate the sum of all elements in an array:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 5, 10, 25};
int sum = 0;
// Loop through the array and add each element to sum
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println("The sum is: " + sum);
}
}
//output
The sum is: 41
what is += in java?
In Java, += is an addition assignment operator. It is a shorthand way to add a value to a variable and then assign the result back to that same variable.
Functionality:
Examples:
Numeric Addition.
int x = 5;
x += 3; // This is equivalent to x = x + 3; so x becomes 8
System.out.println(x); // Output: 8
String Concatenation.
String message = "Hello";
message += " World"; // This is equivalent to message = message + " World";
System.out.println(message); // Output: Hello World
It is a compound assignment operator, combining an arithmetic operation (addition) with an assignment operation.
It works for both numeric types (integers, floats, doubles) and String types (for concatenation).
Loop Through an Array with For-Each
The "for-each" loop in Java, also known as the enhanced for loop, is a control flow statement introduced in Java 5 to simplify iteration over arrays and collections.
It provides a more concise and readable way to process each element in a collection without explicitly managing an index or iterator.
Syntax:
for (DataType variable : collection) {
// Loop body: statements to be executed for each element
}
Explanation:
DataType: This specifies the data type of the elements within the collection.
variable: This is a new variable declared within the loop, and in each iteration, it takes on the value of the current element from the collection.
collection: This refers to the array or an object that implements the Iterable interface (e.g., ArrayList, HashSet, LinkedList).
How it works:
The for-each loop iterates through each element of the collectionfrom beginning to end. In each iteration, thevariable is automatically assigned the value of the current element, and the code within the loop body is executed.
Example:
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String car : cars) {
System.out.println(car);
}
}
}
//output:
Volvo
BMW
Ford
Mazda
Limitations:
No Index Access:You cannot directly access the index of the current element within a for-each loop. If index access is required, a traditional for loop is necessary.No Element Modification:You cannot modify the elements of the underlying collection directly within a for-each loop. If modification is needed, a traditional for loop or an iterator (for collections) should be used.Forward Iteration Only:It only supports forward iteration through the collection; reverse or selective iteration is not possible.you can create any empty array that value is 0 in default.
public class Student{
public static void main(String args[]){
int[] roll_no=new int[6];
roll_no[0]=1;
roll_no[1]=2;
System.out.println(roll_no[0]);
System.out.println(roll_no[4]);
System.out.println(roll_no[1]);
}
}
output
1
0
2
in the above program roll_no[4] can't be initialized but i got the output was 0. that means all int data type array have a default value 0
1D Array
public class Student{
public static void main(String args[]){
int[] roll_no=new int[10];
roll_no[0]=1;
roll_no[1]=2;
for(int i=0; i<10; i++){ //i=0 means index start from 0
System.out.println(roll_no[i]);
}
}
}
output
1
2
0
0
0
0
0
0
0
0
2D Array
public class Student{
public static void main(String args[]){
int[][] roll_no=new int[4][3];
roll_no[0][0]=1;
roll_no[0][1]=2;
roll_no[0][2]=3;
roll_no[1][0]=4;
roll_no[1][1]=5;
roll_no[1][2]=6;
roll_no[2][0]=7;
roll_no[2][1]=8;
roll_no[2][2]=9;
roll_no[3][0]=10;
roll_no[3][1]=11;
roll_no[3][2]=12;
for(int i=0; i<4; i++){
for(int j=0; j<3; j++) {
System.out.print(roll_no[i] [j]+"\t");
}
System.out.println();
}
}
}
ouput
1 2 3
4 5 6
7 8 9
10 11 12
Reducing array initialization
public class Student{
public static void main(String args[]){
int[][] roll_no=new int[4][3];
int num=1;
for(int i=0; i<4; i++){
for(int j=0; j<3; j++) {
num=roll_no[i][j];
num++;
System.out.print(num +"\t");
}
System.out.println( );
}
}
}
output
1 1 1
1 1 1
1 1 1
Here:
I created a 2D array
roll_no[4][3], but i never store any numbers inside it — all elements start as 0 (the default forint).Then i do
num = roll_no[i][j]; → sonumbecomes0.Then
num++→ becomes1every time.
So my output will be all 1’s:
Corrected program
public class Student {
public static void main(String[] args) {
int[][] roll_no = new int[4][3];
int num = 1;
// Fill and print the array
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
roll_no[i][j] = num; // store number in array
System.out.print(roll_no[i][j] + "\t");
num++; // increase for next value
}
System.out.println();
}
}
}
output
1 2 3
4 5 6
7 8 9
10 11 12
What changed:
roll_no[i][j] = num; → actually stores the number inside the array.num++→ moves to the next number for each element.
🧠 Default values by data type
| Data Type | Example Array | Default Value |
|---|---|---|
byte |
new byte[5] |
0 |
short |
new short[5] |
0 |
int |
new int[5] |
0 |
long |
new long[5] |
0L |
float |
new float[5] |
0.0f |
double |
new double[5] |
0.0 |
char |
new char[5] |
'\u0000' (blank character) |
boolean |
new boolean[5] |
false |
String (or any object) |
new String[5] |
null |
Top comments (0)