An array with one dimension is called one-dimensional array or single dimensional array in java.
It is a list of variables (called elements or components) containing values that all have the same type.
One dimensional array represents one row or one column of array elements that share a common name and is distinguishable by index values.
For example, marks obtained by a student in five subjects can be represented by single-dimensional array because these marks can be written as one row or one column.
Creating One dimensional Array in Java
There are basically two ways to create a one dimensional array in java that are as follows:
1. We can declare one-dimensional array and store values (or elements) directly at the time of its declaration, like this:
int marks[ ] = { 90, 97, 95, 99, 100 }; // declare marks[ ] and initialize with five values.
In this single dimensional array declaration, int represents integer type values that can be stored into the array. marks[ ] defines the name of array with one dimension.
A pair of square braces [ ] after array name represents one dimension. Then, we have mentioned marks obtained by five subjects (as elements) inside the curly { and } braces.
Now JVM will create five blocks represented by marks[0], marks[1], marks[2], and so on inside the memory with different addresses.
Here, the values 0, 1, 2, 3, . . . . is called index value of array that refers to the element position in an array. In these blocks of memory, JVM stores five elements into an array, shown below:
This is the first way to declare single dimensional array with storing elements at the time of its declaration. Let’s move on to the second way to declare a one-dimensional array.
2. The second way of creating a one-dimensional array is by declaring array first and then allocating memory for it using the new keyword.
The syntax is as follows:
int marks[ ]; // declare marks arrays. marks = new int[5]; // allocating memory for storing 5 integer elements into an array.
The above two statements can also be written by combining them into a single statement, as:
int marks[ ] = new int[5];
JVM has allocated memory locations for storing five integer elements into the array. But, we have not stored actual elements into the array so far. To store elements into the array, we can write statements like these in the program:
marks[0] = 90; marks[1] = 97; marks[2] = 95; marks[3] = 99; marks[4] = 100;
Or, the programmer can pass the values from the keyboard to the array by using for loop, as follows:
for(int i = 0; i < 5; i++) { // Read the integer values from the keyboard and store them into marks[i]. marks[i] = Integer.parseInt(br.readLine)); }
Let us see some more examples for single dimensional array:
1. float salary[ ] = {99859.55f, 15000f, 14500.75f, 9050f}; 2. float salary[ ] = new float[10]; 3. char ch [ ] = {'s', 'c', 'i', 'e', 'n', 't', 'e', 'c', 'h', 'e', 'a', 's', 'y'}; 4. char ch [ ] = new char [10] ; 5. String colors [ ] = {"Orange", "Red", "Sky blue", "Green"}; 6. String names = new String[5];
Alternative way of writing Single Dimensional Array in Java
We can also write the pair of square braces before or after the array name while single dimensional array. Let’s see some examples.
1. String names[ ] = new String[5]; 2. String[ ] names = {"Vidya", "Rashmi", "Deepak", "Amit", "Ivaan"};
Java Single Dimensional Array Example Programs
1. Let’s take a simple example program where we will create one dimensional array of five elements and read its elements by using for loop and display them one by one.
Program code:
package arraysProgram; public class OneDArr { public static void main(String[] args) { // Declare and initialize an array of five integer values. int arr[] = {2, 4, 6, 8, 10}; // Display all five elements on the console. for (int i = 0; i < arr.length; i++) System.out.println(arr[i] + " "); } }
Output: 2 4 6 8 10
In this example, we have initialized an array of five elements and then accessed the array by index by using for loop.
2. Let’s create a Java program in which we will find the length of an array.
Program code:
package arraysProgram; public class OneDArr { public static void main(String[] args) { // Declare and initialize an array of five integer values. int[ ] num = {2, 4, 6, 8, 10, 12, 14}; // Display the length of array. System.out.println("Length of array: " +num.length); } }
Output: Length of array: 7
3. Let’s create a program where we will accept the marks obtained by a student into a one-dimensional array from the keyboard and finds total marks and percentage of marks. Assume that the maximum mark in any subject is 100.
In this program, we will use Scanner class to take the input from the keyboard.
Program code:
package arraysProgram; import java.util.Scanner; public class OneDArr { public static void main(String[] args) { // Create an object of Scanner class to take input from the keyboard. Scanner sc = new Scanner(System.in); // Ask in how many subjects have you given exams. System.out.println("In how many subject have you given exams?"); int n = sc.nextInt(); // Create one-dimensional array with size n. int[ ] marks = new int[n]; System.out.println("Enter your marks obtained in subjects:"); // Store elements into the array using for loop. for(int i = 0; i < n; i++) { marks[i] = sc.nextInt(); } // Find the total marks obtained in subjects. int total = 0; for(int i = 0; i < n; i++) { total += marks[i]; // Or, total = total + marks[i]. } // Display the total marks on the console. System.out.println("Total marks: " +total); // Find the percentage. float percentage = (float)total/n; // Casting. System.out.println("Percentage: " +percentage+ "%"); } }
Output: In how many subject have you given exams? 5 Enter your marks obtained in subjects: 89 99 95 96 98 Total marks: 477 Percentage: 95.4%
In this program, we have calculated the percentage of marks by dividing total marks (total) by the number of subjects n.
Since total and n both are integers, when an integer value is divided by an integer then by default int value will be returned. This means total = 477 and n = 5, percentage of marks will be 95.0%. This result is definitely wrong.
Therefore, to get the right result, we have converted the type of total into float. float divided by int value will give float value. Thus, the percentage will be 95.4%.
4. Let’s create a simple Java program in which we will calculate the sum and average of six numbers.
Program code:
package arraysProgram; public class OneDArr { public static void main(String[] args) { int[ ] num = new int[6]; num[0] = 20; num[1] = 30; num[2] = 40; num[3] = 50; num[4] = 60; num[5] = 70; double avg = 0.0; int sum = 0; // Find the sum of these numbers. for(int i = 0; i < 6; i++) sum = sum + num[i]; avg = (double)sum/6; System.out.println("Sum of six numbers: " +sum); System.out.println("Average of six numbers: " +avg); } }
Output: Sum of six numbers: 270 Average of six numbers: 45.0
5. Let’s take an example program where we will accept numbers as input from the keyboard and calculate the sum and average of these numbers.
In this program, we will use InputStreamReader and BufferedReader classes to accept input from the keyboard. Look at the source code to understand better.
Program code:
package arraysProgram; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class OneDArr { public static void main(String[] args) throws NumberFormatException, IOException { // Create an object of InputStreamReader to accept data from the keyboard. InputStreamReader isr = new InputStreamReader(System.in); // Create an object of BufferedReader class and pass reference isr to its constructor. BufferedReader br = new BufferedReader(isr); // Create an int type array. System.out.println("How many numbers do you want to enter?"); int n = Integer.parseInt(br.readLine()); int[ ] num = new int[n]; System.out.println("Enter your numbers:"); for(int i = 0; i < n; i++){ num[i] = Integer.parseInt(br.readLine()); } double avg = 0.0; int sum = 0; // Find the sum of these numbers. for(int i = 0; i < n; i++) sum = sum + num[i]; avg = (double)sum/n; System.out.println("Sum: " +sum); System.out.println("Average: " +avg); } }
Output: How many numbers do you want to enter? 5 Enter your numbers: 2 4 6 8 10 Sum: 30 Average: 6.0
6. Let’s create a program in which we will sort a group of integer numbers in ascending order using the bubble sort technique. Concentrate on the source code to understand better.
Program code:
package arraysProgram; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Sorting { public static void main(String[] args) throws NumberFormatException, IOException { // Accepts the input from the keyboard. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // Create an int type array. System.out.println("How many numbers do you want to enter"); int n = Integer.parseInt(br.readLine()); int[ ] num = new int[n]; // Store the integer numbers into the array. System.out.println("Enter your numbers:"); for(int i = 0; i < n; i++){ num[i] = Integer.parseInt(br.readLine()); } // Here, we will use bubble sort technique to sort integer numbers. int limit = n - 1; // elements from 0 to n - 1. boolean flag = false; // If it is true, swapping done. int temp; // temporary variable. for(int i = 0; i < limit; i++) { for(int j = 0; j < limit - 1; j++) { // If first number is bigger than second one, swap. if(num[j] > num[j+1]) { temp = num[j]; num[j] = num[j+1]; num[j+1] = temp; flag = true; // true, swapping done. } } if(flag == false) break; // no swapping, so come out. else flag = false; // assign initial value. } // Display the sorted array in ascending order. System.out.println("Sorted array in ascending order: "); for(int i = 0; i < n; i++) System.out.println(num[i]); } }
Output: How many numbers do you want to enter 4 Enter your numbers: 20 30 10 50 Sorted array: 10 20 30 50
In this program, we have used the bubble sort technique. In this technique, all n elements from 0 to n-1 are taken into an array.
The first element of the array num[j] is compared with the intermediate element num[j+1]. If num[j] > num[j+1], they are interchanged (swapped).
Since we are sorting a group of numbers in ascending order, the smaller element will take the first position. When two elements are swapped, the number of elements to be sorted becomes lesser by 1.
When there are no more swaps found, the flag will become false and soring is aborted. This logic is implemented to sort a group of five numbers in ascending order in the above program.
Hope that this tutorial has covered almost all the important points related to one dimensional array (single dimensional array) in java with example programs. I hope that you will have understood how to create one-dimensional array and also its alternative ways.
Thanks for reading!!!
Next ⇒ Multidimensional Array in Java⇐ Prev Next ⇒