Arrays in Java

Hello Guys....
This is my second post and in this i am going to talk about Arrays in Java Programming Language.
So let's get started:-

1-D Array

There are two ways of declaring 1-D array in java :-

1st Method (without using the new keyword) :-

Consider this code :- 
When we  run this code in a file named array.java we get the output as follows :-
Months - 
1
2
3
4
5
6
7
8
9
10
11
12

2nd Method (using the new keyword) :-

Consider this code :-
When we run this code in a file named array.java we get the output as follows :-

Rahul Malhotra is a coder 

2-D Array  

We can declare the 2-D array in java also by two methods :-

1st Method (using the new keyword) :-

The declaration of the 2-D array is the same by the two methods that we just discussed in the 1-D array. The main feature that Java provides in the 2-D array is that, out of the two attributes, one attribute is fixed and other can vary.... Let's learn with an example :-
This will create a simple 2-D array that can store 4 elements, 2 in each row (on visualizing).
When we  run this code in a file named array.java we get the output as follows :-
1 
2 
2 
3

Now, after considering this code Let's See another code :-
In the above code, you will get the following ouput :-
1
3

4

In the above code, the 2-D array is made in which in the first row, we have only one element and in the second row we have 2 elements as we can store 2 elements in second row but not in the first row.
The lines commented will create an error if we remove the comments as we cannot store more than one element in 1st row.

When we  run this code by removing the comments in a file named array.java we get the error like this :-

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at array.main(array.java:24)

We get this error as we are trying to store the element at 2nd position in the 1st row which doesn't exist, therefore array will go out of bound or out of range in this case.

Now, Let's see another way of creating such a 2-D array....

2nd Method (without using the new keyword) :-

Consider this code :-
In the above code, you will get the following ouput :-
1
1
2
1
2
3

In the above code, the 2-D array is made in which in the first row, we have only one element and in the second row we have 2 elements and in the 3rd row, we have 3 elements but notice that the way of defining this array is different from the above method.

The lines commented will create an error if we remove the comments as explained in the example above.

So, that's all for now, if you like this post then do share it... :)

Comments

Popular posts from this blog

Important Basics of Java Programming Language

FILE MANAGER

How to make a Turbo C++ Program compatible for CodeBlocks IDE