• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Array » One dimensional array – Java Examples
Next →
← Prev

One dimensional array – Java Examples

By Dinesh Thakur

Perhaps one of the most important of all concepts that you need to learn in order  to be effective is the array. Until now, we have looked at variables that hold just one  value – the ints hold one number and the strings hold one text string. Arrays are  used when we want to hold two or more values, perhaps a list. Arrays can be  thought as columns in a spreadsheet – a spreadsheet can have one or it can have  many columns.

An Array is a (fixed length) data structures used to store multiple data elements, that share a common name with the same data type. Array is a predefined class present in java.lang.package. It is a final class which can’t be inherited. The memory allocated to an array is consecutive. Each data item is an element of the array.

All the elements of an array are under one variable name. Its position accesses every data element of an array, and an integer value indicates that position that starts from 0 (zero) called index or subscript and go up for each position that has a value. The array size is fixed and cannot change at runtime of the program. Setting up an array requires that  you inform Java what type of data is being stored in it – strings, Booleans, integers,  and so on. Then you need to tell Java the number of positions in the array and do  this to set them up:  
int[] aryNums;

In Java, arrays can be of either type, primitive data types or references types. In primitive data type array, all elements are of a specific primitive data type. In references type array all elements are of specific reference type. There is only one way to reference the items: by using a subscript to indicate which element number to access. The number used to reference the specific element of an array is called the component.

A primitive type variable,such as int, holds a value. A reference type variable, such as an array, holds a memory address where the value is stored. In other words, array names contain references, as do all Java object names.

We can define an array name rollno to represent a set of roll no of a group of students — a particular value indicated by a number called index number. An index number is present in brackets after the array name.

Java One dimensional array

To create an One dimensional array, you need to perform three steps:

We’ll be covering the following topics in this tutorial:

  • Declaration of an One dimensional array
  • Create memory space
  • Initialization of One dimensional array
  • Example of One dimensional array
  • Representation of array in memory
  • How to access array elements?

Declaration of an One dimensional array

We can declare an array in java using subscript operator. The general form is

datatype var_name[];

is equivalent to

datatype[] var_name[];

Here, datatype is valid java datatype and var_name is the name of the array.

Example

int number[];

int[] number;

Create memory space

As defined earlier array length is fixed at its creation time and cannot be changed, i.e., using new operator an array can create for a definite number of elements of a homogeneous type. The constructing statement of array return reference value of resulting array and that assigned to the corresponding type array variable. The general form is:

array_name = new datatype[size];

Example

number = new int[10];

avg = new float[10];

It is also possible to combine the declaration and creation into one.

The general form is

datatype arrayname[] = new datatype [size];

Example

int number[] = new int[10];

float avg[] = new float[10];

<array-size> can be minimum 0, because Java support zero-length arrays constructions. But it can never be negative, otherwise it will throw NegativeArraySizeException. The length of constructed array will be the <array-size> given at the creation time. Later you can find the length of an array using <array-name>.length.

Initialization of One dimensional array

We can store values at the time of declaration. The compiler allocates the required space depending upon the list of values. The general form is:

datatype array_name[] = {list of values};

Example of One dimensional array

class arraynote {
     public static void main(String args[]){
         int days[]={30,28,29,31,30};
         System.out.println(“January has “+days[3]+” days”);
     }
}
class ArrayExample {
      public static void main(String args[]){
          int days[]=newint[5];
          days[0]=28; days[1]=31; days[2]=30; days[3]=31; days[4]=30;
          System.out.println(“January has “+days[1]+” days”);
      }
}
class arraynote {
        public static void main(String args[]){
            double arraynote[] = new double[3];
            arraynote [0] = 22.58;
            arraynote [1] = 60.48;
            arraynote [2] = 32.58;
            System.out.println(arraynote[0]);
            System.out.println(arraynote[1]);
            System.out.println(arraynote[2]);
       }
}

Representation of array in memory

• In java when the array is declared it captures a chunk of memory from the stack.
• Array is constructed at the run time.At the construction time by specifying the size of the array through new operator garbage collector allocates consecutive memory location from the heap.

• In java the compiler implicitly calls the new operator to allocates memory from heap for creation of an array without using new operator.

How to access array elements?

To access elements of an array, there is one array expression with a specific format that contains an array reference followed by an index number. An expression can calculate an index number, that must lie between integers 0 (zero) to n-1 (n is the length of the array).
At run time array accesses are checked which is an attempt to check whether an index is less than zero or greater than or equal to n (n is the length of the array) then ArraylndexOutOfBoundsException thrown.
Array index must be int value, but it can be short, byte, or char because they are implicitly converted to unary numeric value and become int values. A long index value generates a compile-time error.

For Example:

int an_Array = {1, 2, 3, 4, 5, 6, 7, 8 ,9}; //One dimensional array
  for(int i=0; i<10;i++)
       System.out.println(anArray[i]); //Accessing ith index value.
       int matrix[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
       //Two dimensional array
       for(int i=0; i<3; i++) {
            for(int j=0; j<3; j++)
                 System.out.print(matrix[i][j]);
                 System.out.println();
       }

You’ll also like:

  1. Passing Two Dimensional Array to a Method in Java
  2. Initializing Array in Java Examples
  3. Reusing Array Variables in Java Examples
  4. Enter 5 Names and Print them using One Dimensional Array
  5. Write byte array to a file using FileOutputStream | Java Examples
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW