JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS


Java One Dimensional Arrays

One dimensional array is a list of same typed variables. To create an array, first you must declare an array variable of required type, the syntax is given below:

type variable-name[];

Example:

int account_numbers[];

To allocate memory or create array object the syntax is given below:

variable-name = new type[size of the array];

Example:

account_numbers = new int[10];

You must specify the size of the array during creating object.

After this statement, account_numbers will refer to 10 integers, and assigned to 0. You can access any element by index, array index starts with 0 and ends with (array length-1). We can assign array values as given below:

account_numbers[0] = 1016;
account_numbers[1] = 449;
account_numbers[2] = 1015;

The below line displays the value stored at index 1.

System.out.println(account_numbers[1]);

We can combine declaration of an array with allocation of array as given below:

int account_numbers[] = new int[10];

Arrays can be initialized when they are declaring as given below:

int account_numbers[] = {12,34,56,12,78,98,34};

Other Java Array Examples

Knowledge Center
When to use LinkedList or ArrayList?
Accessing elements are faster with ArrayList, because it is index based. But accessing is difficult with LinkedList. It is slow access. This is to access any element, you need to navigate through the elements one by one. But insertion and deletion is much faster with LinkedList, because if you know the node, just change the pointers before or after nodes. Insertion and deletion is slow with ArrayList, this is because, during these operations ArrayList need to adjust the indexes according to deletion or insetion if you are performing on middle indexes. Means, an ArrayList having 10 elements, if you are inserting at index 5, then you need to shift the indexes above 5 to one more.

About Author

My name is Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me at java2novice@gmail.com or you can comment on the page.

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 6 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2014 by Nataraja Gootooru. All Rights Reserved.