[post-views]
int
, all double
, etc.
Arrays in Java can be of the following types
To declare an array in Java, you use the following syntax:
dataType[] arrayName;
Example: The following declares an array named month_days with the type “array of int”:
int month_days[];
This declaration establishes the fact that month_days is an array variable.
To link month_days with an actual, physical array of integers, you must allocate one using a new operator and assign it to month_days.
Note: new is a special operator that allocates memory.
To initialize an array, you can use the following syntax.
arrayName = new dataType[arraySize];
Example
month_days = new int[12];
Or you can declare and initialize in one line:
dataType[] arrayName = new dataType[arraySize];
Example
int[] month_days = new int[12]; //or
int month_days[] = new int[12];
This example allocates a 12-element array of integers and links them to month_days as shown below.
Note: All elements in the array named month_days will be initialized to zero.
You can also initialize an array with values directly:
dataType[] arrayName = {value1, value2, value3, ...};
// OR
dataType arrayName[] = {value1, value2, value3, ...};
Example-1
int month_days[] = { 31, 28, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31 };
Example-2
int[] numbers = new int[5];
String[] names = {"Alice", "Bob", "Charlie"};
Array elements are accessed using their index. The first element is at index 0
, the second element at index 1
, and so on.
Example
int[] numbers = {3, 4, 5, 6, 7};
//Accessing the 1st element
int firstNumber=numbers[0];
numbers[3] = 10; //Modifying the fourth element
The length
property of an array can be used to find out how many elements it can hold.
int[] numbers = {3, 4, 5, 6, 7};
System.out.println("The array has "+numbers.length+" elements.");
//Display 5
Let’s understand the need for an Array using an example.
Let’s consider an example where we need to store the marks of 5 students. Without an array, you might do something like this.
int student1Mark = 85;
int student2Mark = 90;
int student3Mark = 75;
int student4Mark = 88;
int student5Mark = 92;
This approach is not scalable or efficient, especially if the number of students increases. It also makes operations on the set of marks, like calculating the average, cumbersome.
Now, let’s use an array:
int[] studentMarks = {85, 90, 75, 88, 92};
With this array, you can easily iterate over all the marks using a loop, making operations like calculating the average much simpler and more efficient.
package ch6;
public class AverageMarks {
public static void main(String[] args) {
int[] studentMarks = {85, 90, 75, 88, 92};
int total = 0;
for (int i = 0; i<studentMarks.length; i++) {
total += studentMarks[i];
}
double average=(double)total/studentMarks.length;
System.out.println("Average marks: " + average);
}
}
Output
Average marks: 86.0
This example demonstrates the need for arrays in situations where you are dealing with a collection of similar items. It simplifies the code, makes it more readable, and improves scalability.
Storing elements in an array from user input in Java typically involves using a Scanner
object for input, followed by various operations on the array.
Here are three detailed examples showcasing different operations:
import java.util.Scanner;
public class SumAndAverage {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Asking the user for the number of elements
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
double[] numbers = new double[n];
// Reading numbers from the user
System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextDouble();
}
// Calculating sum and average
double sum = 0;
for (double num : numbers) {
sum += num;
}
double average = sum / n;
// Displaying the results
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
scanner.close();
}
}
Output
Enter the number of elements: 5
Enter the numbers:
80
78
89
67
75
Sum: 389.0
Average: 77.8
import java.util.Scanner;
public class FindLargest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Getting the size of the array from the user
System.out.print("Enter the number of elements: ");
int size = scanner.nextInt();
int[] array = new int[size];
// Reading integers from the user
System.out.println("Enter the integers:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
// Finding the largest number
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
// Displaying the largest number
System.out.println("The largest number is: " + max);
scanner.close();
}
}
Develop a Java program that efficiently locates a book by its unique identification number in a small-scale library system. The library uses a 1D array to store the identification numbers of the books in no particular order. Your task is to implement a linear search algorithm to find whether a book is available in the library and, if so, retrieve its position within the array.
Input:
booksArray
) containing n
integers, where each integer represents the unique identification number of a book. The array does not follow any specific order.searchId
) representing the unique identification number of the book to be searched within the library system.
Sample Execution:
Enter the number of books in the library: 5
Enter the book IDs: 102, 203, 345, 123, 456
Enter the ID of the book to search for: 123
The book with ID 123 is located at position 3.
Objective: Write a Java program to reverse the elements of a 1D integer array. Do not use any built-in methods for reversing.
Sample Input: [1, 2, 3, 4, 5]
Expected Output: [5, 4, 3, 2, 1]
Objective: Develop a Java program to find the second largest number in a given 1D integer array. Assume the array has at least two distinct elements.
Sample Input: [7, 5, 6, 1, 4, 2]
Expected Output: 6
Objective: Create a Java program that checks if a 1D array of integers is a palindrome. An array is a palindrome if it reads the same backward as forward.
Sample Input: [1, 2, 3, 2, 1]
Expected Output: true
Objective: Implement a Java program that merges two sorted arrays into a single sorted array. The input arrays are sorted in non-decreasing order. Do not use any built-in sorting functions.
Sample Input: Array 1: [1, 3, 5]
, Array 2: [2, 4, 6, 8]
Expected Output: [1, 2, 3, 4, 5, 6, 8]
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.