Java Array
Java Array
All Blogs
Table of Contents
1. Introduction
2. Creating Arrays
3. Accessing Array Elements
4. Modifying Array Elements
5. Displaying Array Elements
6. Finding Array Length
7. Inserting Elements into an Array
8. Deleting Elements from an Array
9. Merging Arrays
10. Practice Problems
11. Conclusion
Introduction
Arrays allow you to store multiple items of the same type together, making it easier to manage
and manipulate data. Whether you're working with numbers, strings, or custom objects,
understanding arrays is crucial for becoming a proficient Java developer.
In this blog post, we'll explore the basics of Java arrays, from creation to manipulation, with
plenty of examples and practice opportunities along the way.
Creating Arrays
To create an array in Java, you need to specify two things: the type of elements it will hold and
the number of elements it can contain. Here's how you can create an array:
This line creates an array called numbers that can hold five integers. The new keyword is used to
allocate memory for the array elements.
This creates an array with five elements, each initialized with the corresponding value.
Coding Task
Create an array of the first 5 positive integers and output "Done" to the console once the array
is defined.
Try it on CodeChef
Remember, the index of the last element is always one less than the array's length.
Coding Task
Write a program that outputs the 3rd element from a given array.
Try it on CodeChef
Coding Task
Update the 3rd month in an array of month names to "Mar" and output the updated element.
Try it on CodeChef
Coding Task
Create a string array with the days of the week and output the last two elements on separate
lines.
Try it on CodeChef
Coding Task
Create an integer array with the elements 10, 20, 30, 40, 50, 60, and output the number of
elements in the array.
Try it on CodeChef
// Shift elements
for (int i = arr.length - 1; i > position; i--) {
arr[i] = arr[i - 1];
}
// Shift elements
for (int i = position; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
Merging Arrays
To merge two arrays, create a new array large enough to hold all elements and copy them over:
Try it on CodeChef
Conclusion
We've covered the basics of creating, accessing, modifying, and manipulating arrays. With
practice, you'll become more comfortable using arrays in your Java programs.
Remember, the key to mastering arrays is practice. Try out the coding tasks and practice
problems, and don't hesitate to experiment with your own array manipulations. Happy coding!
We have curated a set of MCQ and coding problems on Arrays in Java. These problems will help
you in solidifying your knowledge of Java Arrays. Start solving these problems now!
You can also check our complete Learn Java course if you want to learn Java in the most fun and
engaging way possible.
More learning courses More practice paths More compilers Privacy Policy
www.codechef.com Follow Us