CProgramming Tutorial

  • C Programming Tutorial
  • Basics of C
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Type Casting
  • C - Booleans
  • Constants and Literals in C
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • Operators in C
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc Operators
  • Decision Making in C
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • Functions in C
  • C - Functions
  • C - Main Function
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • Scope Rules in C
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables

Arrays in C

  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • Pointers in C
  • C - Pointers
  • C - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Pointer to Pointer
  • C - Passing Pointers to Functions
  • C - Return Pointer from Functions
  • C - Function Pointers
  • C - Pointer to an Array
  • C - Pointers to Structures
  • C - Chain of Pointers
  • C - Pointer vs Array
  • C - Character Pointers and Functions
  • C - NULL Pointer
  • C - void Pointer
  • C - Dangling Pointers
  • C - Dereference Pointer
  • C - Near, Far and Huge Pointers
  • C - Initialization of Pointer Arrays
  • C - Pointers vs. Multi-dimensional Arrays
  • Strings in C
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C Structures and Unions
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Self-Referential Structures
  • C - Lookup Tables
  • C - Dot (.) Operator
  • C - Enumeration (or enum)
  • C - Structure Padding and Packing
  • C - Nested Structures
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • File Handling in C
  • C - Input & Output
  • C - File I/O (File Handling)
  • C Preprocessors
  • C - Preprocessors
  • C - Pragmas
  • C - Preprocessor Operators
  • C - Header Files
  • Memory Management in C
  • C - Memory Management
  • C - Memory Address
  • C - Storage Classes
  • Miscellaneous Topics
  • C - Error Handling
  • C - Variable Arguments
  • C - Command Execution
  • C - Math Functions
  • C - Static Keyword
  • C - Random Number Generation
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Cheat Sheet
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Arrays in C are a kind of data structure that can store a fixed-size sequential collection of elements of the same data type . Arrays are used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

What is an Array in C?

An array in C is a collection of data items of similar data type. One or more values same data type, which may be primary data types (int, float, char), or user-defined types such as struct or pointers can be stored in an array. In C, the type of elements in the array should match with the data type of the array itself.

The size of the array, also called the length of the array, must be specified in the declaration itself. Once declared, the size of a C array cannot be changed. When an array is declared, the compiler allocates a continuous block of memory required to store the declared number of elements.

Why Do We Use Arrays in C?

Arrays are used to store and manipulate the similar type of data.

Suppose we want to store the marks of 10 students and find the average. We declare 10 different variables to store 10 different values as follows −

These variables will be scattered in the memory with no relation between them. Importantly, if we want to extend the problem of finding the average of 100 (or more) students, then it becomes impractical to declare so many individual variables.

Arrays offer a compact and memory-efficient solution. Since the elements in an array are stored in adjacent locations, we can easily access any element in relation to the current element. As each element has an index, it can be directly manipulated.

Example: Use of an Array in C

To go back to the problem of storing the marks of 10 students and find the average, the solution with the use of array would be −

Run the code and check its output −

Array elements are stored in contiguous memory locations. Each element is identified by an index starting with "0". The lowest address corresponds to the first element and the highest address to the last element.

Arrays

Declaration of an Array in C

To declare an array in C, you need to specify the type of the elements and the number of elements to be stored in it.

Syntax to Declare an Array

The "size" must be an integer constant greater than zero and its "type" can be any valid C data type. There are different ways in which an array is declared in C.

Declaring an Uninitialized Array

In such type of declaration, the uninitialized elements in the array may show certain random garbage values.

Example: Declaring an Array in C

In the following example, we are declaring an array of 5 integers and printing the indexes and values of all array elements −

Initialization of an Array in C

At the time of declaring an array, you can initialize it by providing the set of comma-separated values enclosed within the curly braces {}.

Syntax to Initialize an Array

If a set of comma-separated sequence values put inside curly brackets is assigned in the declaration, the array is created with each element initialized with their corresponding value.

Example to Initialize an Array

The following example demonstrates the initialization of an integer array:

Example of Initializing all Array Elements to 0

To initialize all elements to 0, put it inside curly brackets

When you run this code, it will produce the following output −

Example of Partial Initialization of an Array

If the list of values is less than the size of the array, the rest of the elements are initialized with "0".

Example of Partial and Specific Elements Initialization

If an array is partially initialized, you can specify the element in the square brackets.

On execution, it will produce the following output −

Getting Size of an Array in C

The compiler allocates a continuous block of memory. The size of the allocated memory depends on the data type of the array.

Example 1: Size of Integer Array

If an integer array of 5 elements is declared, the array size in number of bytes would be "sizeof(int) x 5"

On execution, you will get the following output −

The sizeof operator returns the number of bytes occupied by the variable.

Example 2: Adjacent Address of Array Elements

The size of each int is 4 bytes. The compiler allocates adjacent locations to each element.

In this array, each element is of int type. Hence, the 0th element occupies the first 4 bytes 642016 to 19. The element at the next subscript occupies the next 4 bytes and so on.

Example 3: Array of Double Type

If we have the array type of double type, then the element at each subscript occupies 8 bytes

Example 4: Size of Character Array

The length of a "char" variable is 1 byte. Hence, a char array length will be equal to the array size.

Accessing Array Elements in C

Each element in an array is identified by a unique incrementing index, stating with "0". To access the element by its index, this is done by placing the index of the element within square brackets after the name of the array.

The elements of an array are accessed by specifying the index (offset) of the desired element within the square brackets after the array name. For example −

The above statement will take the 10th element from the array and assign the value to the "salary".

Example to Access Array Elements in C

The following example shows how to use all the three above-mentioned concepts viz. declaration, assignment, and accessing arrays.

On running this code, you will get the following output −

The index gives random access to the array elements. An array may consist of struct variables, pointers and even other arrays as its elements.

More on C Arrays

Arrays, being an important concept in C, need a lot more attention. The following important concepts related to arrays should be clear to a C programmer −

Sr.No Concept & Description
1

C supports multidimensional arrays. The simplest form of an multidimensional array is the two-dimensional array.

2

You can pass to the function a pointer to an array by specifying the array's name without an index.

3

C allows a function to return an array.

4

You can generate a pointer to the first element of an array by simply specifying the array name, without any index.

Working With Arrays in Java

How to intiialize, populate, access, and copy an array in Java

  • Java Programming
  • PHP Programming
  • Javascript Programming
  • Delphi Programming
  • C & C++ Programming
  • Ruby Programming
  • Visual Basic
  • M.A., Advanced Information Systems, University of Glasgow

If a program needs to work with a number of values of the same data type , you could declare a variable for each number. For example, a program that displays lottery numbers:

A more elegant way of dealing with values which can be grouped together is to use an array. An array is a container that holds a fixed number of values of a data type. In the above example, the lottery numbers could be grouped together in an int array:

Think of an array as a row of boxes. The number of boxes in the array cannot change. Each box can hold a value as long as it is of the same data type as the values contained within the other boxes. You can look inside a box to see what value it contains or replace the contents of the box with another value. When talking about arrays, the boxes are called elements.

Declaring and Initializing an Array

The declaration statement for an array is similar to the one used to declare any other variable . It contains the data type followed by the name of the array - the only difference is the inclusion of square brackets next to the data type:

The declaration statements above tell the compiler that

The number inside the brackets defines how many elements the array holds. The above assignment statement creates an int array with ten elements. Of course, there's no reason why the declaration and assignment can't happen in one statement:

Arrays are not limited to primitive data types. Arrays of objects can be created:

Using an Array

Once an array has been initialized the elements can have values assigned to them by using the array's index. The index defines the position of each element in the array. The first element is at 0, the second element at 1 and so on. It's important to note that the index of the first element is 0. It's easy to think that because an array has ten elements that the index is from 1 to 10 instead of from 0 to 9. For example, if we go back to the lottery numbers example we can create an array containing 6 elements and assign the lottery numbers to the elements:

There is a shortcut to filling elements in an array by putting the values for the elements in the declaration statement:

The values for each element is placed inside a pair of curly brackets. The order of the values determines which element is assigned the value starting with index position 0. The number of elements in the array is determined by the number of values inside the curly brackets.

To get the value of an element its index is used:

To find out how many elements an array has use the length field:

Note: A common mistake when using the length method is to forget is to use the length value as an index position. This will always result in an error as the index positions of an array are 0 to length - 1.

Multidimensional Arrays

The arrays we have been looking at so far are known as one-dimensional (or single dimensional) arrays. This means they only have one row of elements. However, arrays can have more than one dimension. A multidimensional is actually an array that contains arrays:

The index for a multidimensional array consists of two numbers:

Although the length of the arrays contained within a multidimensional array do not have to be the same length:

Copying an Array

To copy an array the easiest way is to use the

For example, to create a new array containing the last four elements of an

As arrays are a fixed length the

To further your knowledge about arrays you can learn about manipulating arrays using the Arrays class and making dynamic arrays (i.e., arrays when the number of elements is not a fixed number) using the ArrayList class .

  • Declaring Variables in Java
  • Creating a Java Table Using JTable
  • Coding a Simple Java User Interface Using NetBeans and Swing
  • Definition for the Java Term: Parameter
  • Definition of a Declaration Statement in Java
  • DefaultTableModel Overview
  • Using the ArrayList in Java
  • Odd Magic Squares in Java
  • Learn About Using Constants in Java
  • A Simple Java Table Program (With Example Code)
  • Definition of a Java Method Signature
  • Strongly Typed
  • Understanding Java's Cannot Find Symbol Error Message
  • Static Fields in Java
  • Example Java Code For Building a Simple GUI Application

Codeforwin

Arrays in C – Declare, initialize and access

Array is a data structure that hold finite sequential collection of homogeneous data .

To make it simple let’s break the words.

  • Array is a collection – Array is a container that can hold a collection of data.
  • Array is finite – The collection of data in array is always finite, which is determined prior to its use.
  • Array is sequential – Array stores collection of data sequentially in memory.
  • Array contains homogeneous data – The collection of data in array must share a same data type .

We can divide arrays in two categories.

  • One-dimensional array (Or single-dimensional array)
  • Multi-dimensional array

Why we need arrays?

Let us understand the significance of arrays through an example.

Suppose, I asked you to write a program to input 1000 students marks from user. Finally print average of their marks .

To solve the problem you will declare 1000 integer variable to input marks. Call I/O functions to input marks in 1000 variables and finally find the average.

Think for a while how tedious will be to code if solved using above approach. Declare 1000 variables, take input in all variables, then find average and finally print its average. The above increases length of code, complexity and degrades performance. If you don’t believe, try to code solution using above approach.

To solve above problem efficiently we use arrays. Arrays are good at handling collection of data (collection of 1000 student marks). Mind that in programming, we will always use some data structure (array in our case) to handle a collection of data efficiently.

How to use arrays?

Array representation in memory

Array in memory is stored as a continuous sequence of bytes. Like variables we give name to an array. However unlike variables, arrays are multi-valued they contain multiple values. Hence you cannot access specific array element directly.

For example, you can write sum = 432; to access sum . But, you cannot access specific array element directly by using array variable name. You cannot write marks to access 4 th student marks.

In array, we use an integer value called index to refer at any element of array. Array index starts from 0 and goes till N - 1 (where N is size of the array). In above case array index ranges from 0 to 4 .

To access individual array element we use array variable name with index enclosed within square brackets [ and ] . To access first element of marks array, we use marks[0] . Similarly to access third element we use marks[2] .

How to declare an array?

Syntax to declare an array.

  • data_type is a valid C data type that must be common to all array elements.
  • array_name is name given to array and must be a valid C identifier .
  • SIZE is a constant value that defines array maximum capacity.

Example to declare an array

How to initialize an array.

There are two ways to initialize an array.

  • Static array initialization – Initializes all elements of array during its declaration.
  • Dynamic array initialization – The declared array is initialized some time later during execution of program.

Static initialization of array

We define value of all array elements within a pair of curly braces { and } during its declaration. Values are separated using comma , and must be of same type.

Example of static array initialization

Note: Size of array is optional when declaring and initializing array at once. The C compiler automatically determines array size using number of array elements. Hence, you can write above array initialization as.

Dynamic initialization of array

You can assign values to an array element dynamically during execution of program. First declare array with a fixed size. Then use the following syntax to assign values to an element dynamically.

Example to initialize an array dynamically

Instead of hard-coding marks values, you can ask user to input values to array using scanf() function.

The array index is an integer value, so instead of hard-coding you can wrap array input code inside a loop .

The above code will run 5 times from 0 to 4 . In each iteration it ask user to input an integer and stores it in successive elements of marks array.

Example program to implement one-dimensional array

Let us write a C program to declare an array capable of storing 10 student marks. Input marks of all 10 students and find their average.

Output –

Array best practices

  • Arrays are fixed size, hence always be cautious while accessing arrays. Accessing an element that does not exists is undefined. You may get a valid value or the program may crash.For example, consider the below program. int array[5]; // Declare an integer array of size 5 /* Accessing sixth element of array which is undefined. */ array[5] = 50; /* Accessing -1th element of array is undefined */ array[-1] = 10;
  • Always keep in mind that all array element store a value of similar type.

Recommended array example programs

  • Program to read and print array element.
  • Program to find maximum and minimum element in array.
  • Program to insert a new element in array.
  • Program to search an element in array.
  • Program to sort array elements.
Practice more array programming exercises to learn more.

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

An array of 10 elements.

Each item in an array is called an element , and each element is accessed by its numerical index . As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

The following program, ArrayDemo , creates an array of integers, puts some values in the array, and prints each value to standard output.

The output from this program is:

In a real-world programming situation, you would probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as in the preceding example. However, the example clearly illustrates the array syntax. You will learn about the various looping constructs ( for , while , and do-while ) in the Control Flow section.

Declaring a Variable to Refer to an Array

The preceding program declares an array (named anArray ) with the following line of code:

Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type [] , where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.

Similarly, you can declare arrays of other types:

You can also place the brackets after the array's name:

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Creating, Initializing, and Accessing an Array

One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.

If this statement is missing, then the compiler prints an error like the following, and compilation fails:

The next few lines assign values to each element of the array:

Each array element is accessed by its numerical index:

Alternatively, you can use the shortcut syntax to create and initialize an array:

Here the length of the array is determined by the number of values provided between braces and separated by commas.

You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of brackets, such as String[][] names . Each element, therefore, must be accessed by a corresponding number of index values.

In the Java programming language, a multidimensional array is an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program:

Finally, you can use the built-in length property to determine the size of any array. The following code prints the array's size to standard output:

Copying Arrays

The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

The two Object arguments specify the array to copy from and the array to copy to . The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

The following program, ArrayCopyDemo , declares an array of String elements. It uses the System.arraycopy method to copy a subsequence of array components into a second array:

Array Manipulations

Arrays are a powerful and useful concept used in programming. Java SE provides methods to perform some of the most common manipulations related to arrays. For instance, the ArrayCopyDemo example uses the arraycopy method of the System class instead of manually iterating through the elements of the source array and placing each one into the destination array. This is performed behind the scenes, enabling the developer to use just one line of code to call the method.

For your convenience, Java SE provides several methods for performing array manipulations (common tasks, such as copying, sorting and searching arrays) in the java.util.Arrays class. For instance, the previous example can be modified to use the copyOfRange method of the java.util.Arrays class, as you can see in the ArrayCopyOfDemo example. The difference is that using the copyOfRange method does not require you to create the destination array before calling the method, because the destination array is returned by the method:

As you can see, the output from this program is the same, although it requires fewer lines of code. Note that the second parameter of the copyOfRange method is the initial index of the range to be copied, inclusively, while the third parameter is the final index of the range to be copied, exclusively . In this example, the range to be copied does not include the array element at index 9 (which contains the string Lungo ).

Some other useful operations provided by methods in the java.util.Arrays class are:

Searching an array for a specific value to get the index at which it is placed (the binarySearch method).

Comparing two arrays to determine if they are equal or not (the equals method).

Filling an array to place a specific value at each index (the fill method).

Sorting an array into ascending order. This can be done either sequentially, using the sort method, or concurrently, using the parallelSort method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.

Creating a stream that uses an array as its source (the stream method). For example, the following statement prints the contents of the copyTo array in the same way as in the previous example:

See Aggregate Operations for more information about streams.

Converting an array to a string. The toString method converts each element of the array to a string, separates them with commas, then surrounds them with brackets. For example, the following statement converts the copyTo array to a string and prints it:

This statement prints the following:

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

cppreference.com

Array declaration.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
Specifiers
function specifier
function specifier
(C++20)
/struct
volatile
(C++26)    
(C++11)
Declarators
Block declarations
(C++17)
(C++11)
declaration
directive
declaration (C++11)
declaration
(C++11)
Other declarations
(C++11)
(C++11)

Declares an object of array type.

Syntax Assignment Array-to-pointer decay Multidimensional arrays Arrays of unknown bound Array rvalues Defect reports See also

[ edit ] Syntax

An array declaration is any simple declaration whose declarator has the form

noptr-declarator expr (optional) attr (optional)
noptr-declarator - any valid declarator, but if it begins with , , or , it has to be surrounded by parentheses (otherwise the whole declarator is treated as a or ).
expr - an (until C++14)a of type (since C++14), which evaluates to a value greater than zero
attr - (since C++11) list of

A declaration of the form T a [ N ] ; , declares a as an array object that consists of N contiguously allocated objects of type T . The elements of an array are numbered ​ 0 ​ , …, N - 1 , and may be accessed with the subscript operator [] , as in a [ 0 ] , …, a [ N - 1 ] .

Arrays can be constructed from any fundamental type (except void ), pointers , pointers to members , classes , enumerations , or from other arrays of known bound (in which case the array is said to be multi-dimensional). In other words, only object types except for array types of unknown bound can be element types of array types. Array types of incomplete element type are also incomplete types.

The possibly (since C++20) specifier can be used as array element type in the declaration of a pointer or reference to array, which deduces the element type from the initializer or the function argument(since C++14), e.g. auto (*p)[42] = &a; is valid if a is an lvalue of type int[42].

(since C++11)

There are no arrays of references or arrays of functions.

Applying cv-qualifiers to an array type (through typedef or template type manipulation) applies the qualifiers to the element type, but any array type whose elements are of cv-qualified type is considered to have the same cv-qualification.

When used with new[]-expression , the size of an array may be zero; such an array has no elements:

[ edit ] Assignment

Objects of array type cannot be modified as a whole: even though they are lvalues (e.g. an address of array can be taken), they cannot appear on the left hand side of an assignment operator:

[ edit ] Array-to-pointer decay

There is an implicit conversion from lvalues and rvalues of array type to rvalues of pointer type: it constructs a pointer to the first element of an array. This conversion is used whenever arrays appear in context where arrays are not expected, but pointers are:

[ edit ] Multidimensional arrays

When the element type of an array is another array, it is said that the array is multidimensional:

Note that when array-to-pointer decay is applied, a multidimensional array is converted to a pointer to its first element (e.g., a pointer to its first row or to its first plane): array-to-pointer decay is applied only once.

[ edit ] Arrays of unknown bound

If expr is omitted in the declaration of an array, the type declared is "array of unknown bound of T", which is a kind of incomplete type , except when used in a declaration with an aggregate initializer :

Because array elements cannot be arrays of unknown bound, multidimensional arrays cannot have unknown bound in a dimension other than the first:

If there is a preceding declaration of the entity in the same scope in which the bound was specified, an omitted array bound is taken to be the same as in that earlier declaration, and similarly for the definition of a static data member of a class:

References and pointers to arrays of unknown bound can be formed, but cannot (until C++20) and can (since C++20) be initialized or assigned from arrays and pointers to arrays of known bound. Note that in the C programming language, pointers to arrays of unknown bound are compatible with pointers to arrays of known bound and are thus convertible and assignable in both directions.

Pointers to arrays of unknown bound cannot participate in pointer arithmetic and cannot be used on the left of the subscript operator , but can be dereferenced.

[ edit ] Array rvalues

Although arrays cannot be returned from functions by value and cannot be targets of most cast expressions, array prvalues may be formed by using a type alias to construct an array temporary using brace-initialized functional cast .

Like class prvalues, array prvalues convert to xvalues by when evaluated.

(since C++17)

Array xvalues may be formed directly by accessing an array member of a class rvalue or by using std::move or another cast or function call that returns an rvalue reference.

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++98 a pointer or reference to an array of unknown
bound could not be a function parameter
allowed
C++98 when omitted, the bound of an array could
not be inferred from a previous declaration
inference allowed
C++98 the bound of an array static data member could
not be omitted even if an initializer is provided
omission allowed
C++11 auto could not be used as element type allowed

[ edit ] See also

for Array declaration
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 4 April 2024, at 07:41.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)
  • Java Operators
  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement
  • Java Ternary Operator
  • Java for Loop

Java for-each Loop

  • Java while and do...while Loop
  • Java break Statement
  • Java continue Statement
  • Java switch Statement

Java Arrays

Java Multidimensional Arrays

Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • Java Strings
  • Java Access Modifiers
  • Java this Keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP(II)

  • Java Inheritance
  • Java Method Overriding
  • Java Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

  • Java File Class
  • Java Reader Class
  • Java Writer Class
  • Java InputStreamReader Class
  • Java OutputStreamWriter Class
  • Java FileReader Class
  • Java FileWriter Class
  • Java BufferedReader
  • Java BufferedWriter Class
  • Java StringReader Class
  • Java StringWriter Class
  • Java PrintWriter Class

Additional Topics

  • Java Keywords and Identifiers
  • Java Operator Precedence
  • Java Bitwise and Shift Operators
  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

Java Math max()

  • Java Math min()
  • Java ArrayList trimToSize()

An array is a collection of similar types of data.

For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names.

Here, the above array cannot store more than 100 names. The number of values in a Java array is always fixed.

  • How to declare an array in Java?

In Java, here is how we can declare an array.

  • dataType - it can be primitive data types like int , char , double , byte , etc. or Java objects
  • arrayName - it is an identifier

For example,

Here, data is an array that can hold values of type double .

But, how many elements can array this hold?

Good question! To define the number of elements that an array can hold, we have to allocate memory for the array in Java. For example,

Here, the array can store 10 elements. We can also say that the size or length of the array is 10.

In Java, we can declare and allocate the memory of an array in one single statement. For example,

  • How to Initialize Arrays in Java?

In Java, we can initialize arrays during declaration. For example,

Here, we have created an array named age and initialized it with the values inside the curly brackets.

Note that we have not provided the size of the array. In this case, the Java compiler automatically specifies the size by counting the number of elements in the array (i.e. 5).

In the Java array, each memory location is associated with a number. The number is known as an array index. We can also initialize arrays in Java, using the index number. For example,

Elements are stored in the array

  • Array indices always start from 0. That is, the first element of an array is at index 0.
  • If the size of an array is n , then the last element of the array will be at index n-1 .
  • How to Access Elements of an Array in Java?

We can access the element of an array using the index number. Here is the syntax for accessing elements of an array,

Let's see an example of accessing array elements using index numbers.

Example: Access Array Elements

In the above example, notice that we are using the index number to access each element of the array.

We can use loops to access all the elements of the array at once.

  • Looping Through Array Elements

In Java, we can also loop through each element of the array. For example,

Example: Using For Loop

In the above example, we are using the for Loop in Java to iterate through each element of the array. Notice the expression inside the loop,

Here, we are using the length property of the array to get the size of the array.

We can also use the for-each loop to iterate through the elements of an array. For example,

Example: Using the for-each Loop

  • Example: Compute Sum and Average of Array Elements

In the above example, we have created an array of named numbers . We have used the for...each loop to access each element of the array.

Inside the loop, we are calculating the sum of each element. Notice the line,

Here, we are using the length attribute of the array to calculate the size of the array. We then calculate the average using:

As you can see, we are converting the int value into double . This is called type casting in Java. To learn more about typecasting, visit Java Type Casting .

  • Multidimensional Arrays

Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare multidimensional arrays in Java.

A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself. For example,

Here, we have created a multidimensional array named matrix. It is a 2-dimensional array. To learn more, visit the Java multidimensional array .

  • Java Copy Array
  • Java Program to Print an Array
  • Java Program to Concatenate two Arrays
  • Java ArrayList to Array and Array to ArrayList
  • Java Dynamic Array

Table of Contents

  • Introduction

Before we wrap up, let’s put your knowledge of Java Array (With Examples) to the test! Can you solve the following challenge?

Write a function to calculate the average of an array of numbers.

  • Return the average of all numbers in the array arr with the size arrSize .
  • For example, if arr[] = {10, 20, 30, 40} and arrSize = 4 , the expected output is 25 .

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Java Tutorial

Java Library

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript arrays.

An array is a special variable, which can hold more than one value:

Why Use Arrays?

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

It is a common practice to declare arrays with the const keyword.

Learn more about const with arrays in the chapter: JS Array Const .

Spaces and line breaks are not important. A declaration can span multiple lines:

You can also create an array, and then provide the elements:

Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

The two examples above do exactly the same.

There is no need to use new Array() .

For simplicity, readability and execution speed, use the array literal method.

Advertisement

Accessing Array Elements

You access an array element by referring to the index number :

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element

This statement changes the value of the first element in cars :

Converting an Array to a String

The JavaScript method toString() converts an array to a string of (comma separated) array values.

Access the Full Array

With JavaScript, the full array can be accessed by referring to the array name:

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns John:

Objects use names to access its "members". In this example, person.firstName returns John:

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods:

Array methods are covered in the next chapters.

The length Property

The length property of an array returns the length of an array (the number of array elements).

The length property is always one more than the highest array index.

Accessing the First Array Element

Accessing the last array element, looping array elements.

One way to loop through an array, is using a for loop:

You can also use the Array.forEach() function:

Adding Array Elements

The easiest way to add a new element to an array is using the push() method:

New element can also be added to an array using the length property:

Adding elements with high indexes can create undefined "holes" in an array:

Associative Arrays

Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes .  

WARNING !! If you use named indexes, JavaScript will redefine the array to an object.

After that, some array methods and properties will produce incorrect results .

 Example:

The difference between arrays and objects.

In JavaScript, arrays use numbered indexes .  

In JavaScript, objects use named indexes .

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.

  • JavaScript does not support associative arrays.
  • You should use objects when you want the element names to be strings (text) .
  • You should use arrays when you want the element names to be numbers .

JavaScript new Array()

JavaScript has a built-in array constructor new Array() .

But you can safely use [] instead.

These two different statements both create a new empty array named points:

These two different statements both create a new array containing 6 numbers:

The new keyword can produce some unexpected results:

A Common Error

is not the same as:

How to Recognize an Array

A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns " object ":

The typeof operator returns object because a JavaScript array is an object.

Solution 1:

To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method Array.isArray() :

Solution 2:

The instanceof operator returns true if an object is created by a given constructor:

Nested Arrays and Objects

Values in objects can be arrays, and values in arrays can be objects:

To access arrays inside arrays, use a for-in loop for each array:

Complete Array Reference

For a complete Array reference, go to our:

Complete JavaScript Array Reference .

The reference contains descriptions and examples of all Array properties and methods.

Test Yourself With Exercises

Get the value " Volvo " from the cars array.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Java Course
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Arrays in Java

Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a single variable. They are useful for managing collections of data efficiently. Arrays in Java work differently than they do in C/C++. This article covers the basics and in-depth explanations with examples of array declaration , creation , and manipulation in Java.

Table of Content

Basics of Arrays in Java

In-depth concepts of java array, creating, initializing, and accessing an arrays in java, instantiating an array in java, array literal in java, types of arrays in java, 1. single-dimensional arrays, 2. multi-dimensional arrays, arrays of objects in java, multidimensional arrays in java, passing arrays to methods, returning arrays from methods, class objects for arrays, java array members, cloning of single-dimensional array in java, cloning multidimensional array in java, advantages of java arrays, disadvantages of java arrays, array declaration.

To declare an array in Java, use the following syntax:

  • type : The data type of the array elements (e.g., int , String ).
  • arrayName : The name of the array.

Array Declaration Example:

Here’s an example of declaring an integer array:

  • This statement declares an array named numbers that will hold integers. Note: The array is not yet initialized .

Create an Array

To create an array, you need to allocate memory for it using the new keyword :

  • This statement initializes the numbers array to hold 5 integers. The default value for each element is 0 .

Access an Element of an Array

We can access array elements using their index, which starts from 0 :

  • The first line sets the value of the first element to 10 . The second line retrieves the value of the first element.

Change an Array Element

To change an element, assign a new value to a specific index:

  • This statement updates the value of the first element from 10 to 20 .

Array Length

We can get the length of an array using the length property:

This retrieves the number of elements in the numbers array, which is 5 in this case.

The above are the basic details of Arrays in Java. Now, if you want to go through the in-depth concepts of Java Arrays , then scroll down below and go through the diagrams, examples, and explanations.

Following are some important points about Java arrays. 

  • In Java, all arrays are dynamically allocated .
  • Arrays may be stored in contiguous memory [consecutive memory locations].
  • Since arrays are objects in Java, we can find their length using the object property length . This is different from C/C++, where we find length using size of.
  • A Java array variable can also be declared like other variables with [] after the data type.
  • The variables in the array are ordered, and each has an index beginning with 0.
  • Java array can also be used as a static field, a local variable, or a method parameter.

An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class, depending on the definition of the array. In the case of primitive data types, the actual values might be stored in contiguous memory locations (JVM does not guarantee this behavior). In the case of class objects, the actual objects are stored in a heap segment . To learn more about Java Array, go through Java programming course here.

Java Arrays

Note: This storage of arrays helps us randomly access the elements of an array [Support Random Access].

The general form of array declaration is 

  • An array declaration has two components : the type and the name.
  • type declares the element type of the array.
  • The element type determines the data type of each element that comprises the array.
  • Like an array of integers, we can also create an array of other primitive data types like char, float, double, etc., or user-defined data types (objects of a class).
  • Thus, the element type for the array determines what type of data the array will hold. 

Example:  

  • Although the first declaration establishes that int Array is an array variable, no actual array exists .
  • It merely tells the compiler that this variable (int Array) will hold an array of the integer type.
  • To link int Array with an actual, physical array of integers, you must allocate one using new and assign it to int Array. 

When an array is declared, only a reference of an array is created. To create or give memory to the array, you create an array like this: The general form of new as it applies to one-dimensional arrays appears as follows: 

Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the name of the array variable that is linked to the array. To use new to allocate an array, you must specify the type and number of elements to allocate.

Note:  The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Do refer to default array values in Java .

Note:  The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Do refer to default array values in Java . Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java , all arrays are dynamically allocated.

In a situation where the size of the array and variables of the array are already known, array literals can be used. 

  • The length of this array determines the length of the created array.
  • There is no need to write the new int[] part in the latest versions of Java.

Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.

Implementation:

Complexity of the above method:.

Time Complexity: O(n) Auxiliary Space: O(1)

Java supports different types of arrays:

These are the most common type of arrays, where elements are stored in a linear order.

Single Dimensional Array in Java

Arrays with more than one dimension, such as two-dimensional arrays (matrices).

You can also access java arrays using for each loops . 

An array of objects is created like an array of primitive-type data items in the following way. 

Example of Arrays of Objects

Below is the implementation of the above mentioned topic:

  • The Student Array contains five memory spaces each of the size of Student class in which the address of five Student objects can be stored.
  • The Student objects have to be instantiated using the constructor of the Student class, and their references should be assigned to the array elements in the following way. 
Time Complexity: O(n) Auxiliary Space : O(1)

An array of objects is also created like : 

What happens if we try to access elements outside the array size?

JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of an array.

Below code shows what happens if we try to access elements outside the array size:

Example (Iterating the array):

Time Complexity: O(n), here n is size of array. Auxiliary Space: O(1) , since no extra space required.

Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other arrays. These are also known as Jagged Arrays . A multidimensional array is created by appending one set of square brackets ([]) per dimension. 

There are 2 methods to declare Java Multidimensional Arrays as mentioned below:

Multi-Dimensional Array

Declaration:

Java multidimensional arrays examples.

Like variables, we can also pass arrays to methods. For example, the below program passes the array to method sum to calculate the sum of the array’s values.

As usual, a method can also return an array. For example, the below program returns an array from method m1 . 

Time Complexity: O(n)  Auxiliary Space : O(1)

Every array has an associated Class object, shared with all other arrays with the same component type. 

Explanation of the above method:

  • The string “[I” is the run-time type signature for the class object “array with component type int .”
  • The only direct superclass of an array type is java.lang.Object .
  • The string “[B” is the run-time type signature for the class object “array with component type byte .”
  • The string “[S” is the run-time type signature for the class object “array with component type short .”
  • The string “[L” is the run-time type signature for the class object “array with component type of a Class.” The Class name is then followed.

Now, as you know that arrays are objects of a class, and a direct superclass of arrays is a class Object. The members of an array type are all of the following: 

  • The public final field length contains the number of components of the array. Length may be positive or zero.
  • All the members are inherited from class Object; the only method of Object that is not inherited is its clone method.
  • The public method clone() overrides the clone method in class Object and throws no checked exceptions .

Arrays Types and Their Allowed Element Types

Array TypesAllowed Element Types
Primitive Type ArraysAny type which can be implicitly promoted to declared type.
Object Type ArraysEither declared type objects or it’s child class objects.
Abstract Class Type ArraysIts child-class objects are allowed.
Interface Type ArraysIts implementation class objects are allowed.

When you clone a single-dimensional array, such as Object[] , a shallow copy is performed. This means that the new array contains references to the original array’s elements rather than copies of the objects themselves. A deep copy occurs only with arrays containing primitive data types, where the actual values are copied.

Below is the implementation of the above method:

Explanation of the above program:.

  • In this example, intArray and cloneArray are not the same object ( intArray == cloneArray is false ), but they share the same contents because primitive values are deeply copied.
  • For arrays containing objects, the references are copied, so the objects themselves are not duplicated.

Clone-of-Array

A clone of a multi-dimensional array (like Object[][]) is a “shallow copy,” however, which is to say that it creates only a single new array with each element array a reference to an original element array, but subarrays are shared. 

Multidimensional-Array-Clone

  • Efficient Access : Accessing an element by its index is fast and has constant time complexity, O(1).
  • Memory Management : Arrays have fixed size, which makes memory management straightforward and predictable.
  • Data Organization : Arrays help organize data in a structured manner, making it easier to manage related elements.
  • Fixed Size : Once an array is created, its size cannot be changed, which can lead to memory waste if the size is overestimated or insufficient storage if underestimated.
  • Type Homogeneity : Arrays can only store elements of the same data type, which may require additional handling for mixed types of data.
  • Insertion and Deletion : Inserting or deleting elements, especially in the middle of an array, can be costly as it may require shifting elements.

Related Articles to the topic :

Jagged Array in Java For-each loop in Java Arrays class in Java

Frequently Asked Questions – Java Arrays

How can we initialize an array in java.

Arrays in Java can be initialized in several ways: Static Initialization : int[] arr = {1, 2, 3}; Dynamic Initialization : int[] arr = new int[5]; Initialization with a loop : for (int i = 0; i < arr.length; i++) { arr[i] = i + 1; }

Can we use an array of primitive types in Java?

Yes, Java supports arrays of primitive types such as int , char , boolean , etc., as well as arrays of objects.

How are multidimensional arrays represented in Java?

Multidimensional arrays in Java are represented as arrays of arrays. For example, a two-dimensional array is declared as int[][] array , and it is effectively an array where each element is another array.

Can we change the size of an array after it is created in Java?

No, the size of an array in Java cannot be changed once it is initialized. Arrays are fixed-size. To work with a dynamically sized collection, consider using classes from the java.util package, such as ArrayList .

Can we specify the size of an array as long in Java?

No, we cannot specify the size of an array as long . The size of an array must be specified as an int . If a larger size is required, it must be handled using collections or other data structures.

What is the direct superclass of an array in Java?

The direct superclass of an array in Java is Object . Arrays inherit methods from the Object class, including toString() , equals() , and hashCode() .

Which interfaces are implemented by arrays in Java?

All arrays in Java implement two interfaces: Cloneable : Allows the array to be cloned using the clone() method. java.io.Serializable : Enables arrays to be serialized.

Please Login to comment...

Similar reads.

  • Java-Arrays
  • java-basics
  • How to Delete Discord Servers: Step by Step Guide
  • Google increases YouTube Premium price in India: Check our the latest plans
  • California Lawmakers Pass Bill to Limit AI Replicas
  • Best 10 IPTV Service Providers in Germany
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Using arrays

  • 8 contributors

You can declare an array to work with a set of values of the same data type . An array is a single variable with many compartments to store values, while a typical variable has only one storage compartment in which it can store only one value. Refer to the array as a whole when you want to refer to all the values it holds, or you can refer to its individual elements.

For example, to store daily expenses for each day of the year, you can declare one array variable with 365 elements, rather than declaring 365 variables. Each element in an array contains one value. The following statement declares the array variable with 365 elements. By default, an array is indexed beginning with zero, so the upper bound of the array is 364 rather than 365.

To set the value of an individual element, you specify the element's index. The following example assigns an initial value of 20 to each element in the array.

Changing the lower bound

Use the Option Base statement at the top of a module to change the default index of the first element from 0 to 1. In the following example, the Option Base statement changes the index for the first element, and the Dim statement declares the array variable with 365 elements.

You can also explicitly set the lower bound of an array by using a To clause, as shown in the following example.

Storing Variant values in arrays

There are two ways to create arrays of Variant values. One way is to declare an array of Variant data type , as shown in the following example:

The other way is to assign the array returned by the Array function to a Variant variable, as shown in the following example.

You identify the elements in an array of Variant values by index, no matter which technique you use to create the array. For example, the following statement can be added to either of the preceding examples.

Using multidimensional arrays

In Visual Basic, you can declare arrays with up to 60 dimensions. For example, the following statement declares a 2-dimensional, 5-by-10 array.

If you think of the array as a matrix, the first argument represents the rows and the second argument represents the columns.

Use nested For...Next statements to process multidimensional arrays. The following procedure fills a two-dimensional array with Single values.

  • Visual Basic conceptual topics

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Was this page helpful?

Additional resources

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Array assignment and reference in Java

I have initialized array a and assigning reference of a to new array b. Now I initialized a new array c and passed its reference to array a. Since array b is reference to array a, b should have new values that are in c but b is having old values of a. What is the reason behind it? Output is given below -

Anuj Gupta's user avatar

  • Thats fine this is how each programming language works. –  bit-shashank Commented Jun 24, 2017 at 4:27

5 Answers 5

Don't be irritated by the name 'list'. The images are taken from a python visualization, but the principle is the same in Java

Array a is assigned with a new array:

Assigning a

Array b is assigned to the instance behind a :

Assigning b

Array c is assigned with a new array:

Assigning c

And finally a is assigned to the instance behind c , b was not re-assigned and still keeps a reference to the old a :

Re-Assigning a

Images taken from a visualization on pythontutor.com

Felix's user avatar

Suppose you think of an object as a house, and a reference as a piece of paper with the address of a house written on it. a , b , and c are all references. So when you say

you're building a house with 1, 2, 3, 4, and 5 in it; and a is a piece of paper with the address of that house.

b is another reference, which means it's another piece of paper. But it has the address of the same house on it.

Now we build a new house and put 6, 7, and 8 into it. c will be a piece of paper with the address of the new house. When we say a = c , then the slip of paper that used to be a is thrown out, and we make a new piece of paper with the address of the new house. That's the new value of a .

But b was a separate piece of paper. It hasn't changed. Nothing we've done has changed it.

References are like that.

ajb's user avatar

When you assigned value of a to b, it means b is referring to same space allocated to array a. This means b will pick up any changes made to the array a, but if any changes made to the variable a. If a is made to refer to new array, b will still refer the old a reference.

Nipun's user avatar

When you do b=a b references to a. However when you to a=c a is referring to c, but still b refers to the old object (address of this object as value been assigned and it is constant) a that you assigned because that is what it contains when you assigned.

Unless you reassign it, it won't change.

Suresh Atta's user avatar

This is why:

What is Object Reference Variable?

You have 2 objects (the arrays) and 3 references (a, b, c) to the objects. You're just swapping around where things are pointed.

Tim's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java arrays reference or ask your own question .

  • The Overflow Blog
  • At scale, anything that could fail definitely will
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • How to survive 40c while golfing
  • Can Ontario municipal zoning by-laws prohibit site-built tiny homes?
  • Does strong convergence of operators imply pointwise convergence of their unbounded inverses?
  • Maximizing the common value of both sides of an equation (part 2)
  • Difference between 失敬する and 盗む
  • Is it safe to install programs other than with a distro's package manager?
  • How do I apologize to a lecturer
  • Is consciousness a prerequisite for knowledge?
  • quantulum abest, quo minus . .
  • What is Zion's depth in the Matrix?
  • Proof of the principle of explosion
  • Hip pain when cycling (experienced cyclist)
  • Strange variable scope behavior when calling function recursivly
  • Best way to explain the thinking steps from x² = 9 to x=±3
  • How to substitute URLs?
  • Boost Converter Efficiency Input Current
  • Why does each state get two Senators?
  • Multiple alien species on Earth at the same time: one species destroys Earth but the other preserves a small group of humans
  • How many ways can you make change?
  • Find the radius of a circle given 2 of its coordinates and their angles.
  • How can coordinates be meaningless in General Relativity?
  • What is the translation of a code monkey in French?
  • Help writing block matrix
  • What would happen if the voltage dropped below one volt and the button was not hit?

what is assignment array

IMAGES

  1. Data Structure: Introduction to Arrays

    what is assignment array

  2. PPT

    what is assignment array

  3. PPT

    what is assignment array

  4. Array Assignment Help Online From Logical Programming Experts

    what is assignment array

  5. Array Type Assignment: Explained And Illustrated

    what is assignment array

  6. Array Assignments and Comparing Arrays

    what is assignment array

VIDEO

  1. SGD 113 Array Assignment

  2. Learn to program with c

  3. SGD Array Assignment

  4. How to Assign and Re-assign Values to Arrays in C++

  5. Assignment Array SC025 Sir Farid Class

  6. Q1 to Q 10 ll Trigonometry objective Assignment solution ll Er.Shravan Sir ll Array Maths ll

COMMENTS

  1. C Arrays

    Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more.

  2. What is Array?

    Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of same data type stored at contiguous memory locations. For simplicity, we can think of an array as a flight of stairs where on each step is placed a value (let's say one of your friends). Here, you can identify the location of any ...

  3. How do you assign all elements of an array at once?

    There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++. Here is what you can do: #include <algorithm>. int array [] = {1,3,34,5,6}; int newarr [] = {34,2,4,5,6}; std::ranges::copy(newarr, array); // C++20.

  4. Arrays in C

    An array in C is a collection of data items of similar data type. One or more values same data type, which may be primary data types (int, float, char), or user-defined types such as struct or pointers can be stored in an array. In C, the type of elements in the array should match with the data type of the array itself.

  5. C Arrays (With Examples)

    Access Array Elements. You can access elements of an array by indices. Suppose you declared an array mark as above. The first element is mark[0], the second element is mark[1] and so on. Declare an Array Few keynotes: Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.

  6. Array Data Structure Guide

    An array is a collection of items of the same variable type that are stored at contiguous memory locations. It's one of the most popular and simple data structures and is often used to implement other data structures. Each item in an array is indexed starting with 0 . Each element in an array is accessed through its index.

  7. How to Work With Arrays: Declaring and Initializing

    The above assignment statement creates an int array with ten elements. Of course, there's no reason why the declaration and assignment can't happen in one statement: float[] floatArray = new float[10]; Arrays are not limited to primitive data types. Arrays of objects can be created:

  8. Arrays in C

    Arrays in C - Declare, initialize and access. Array is a data structure that hold finite sequential collection of homogeneous data. To make it simple let's break the words. Array is a collection - Array is a container that can hold a collection of data. Array is finite - The collection of data in array is always finite, which is ...

  9. Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)

    Arrays. An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the "Hello World!" application.

  10. Array declaration

    A declaration of the form T a [N];, declares a as an array object that consists of N contiguously allocated objects of type T.The elements of an array are numbered 0 , …, N -1, and may be accessed with the subscript operator [], as in a [0], …, a [N -1].. Arrays can be constructed from any fundamental type (except void), pointers, pointers to members, classes, enumerations, or from other ...

  11. C++ Arrays

    Properties of Arrays in C++. An Array is a collection of data of the same data type, stored at a contiguous memory location. Indexing of an array starts from 0. It means the first element is stored at the 0th index, the second at 1st, and so on. Elements of an array can be accessed using their indices.

  12. C++ Arrays (With Examples)

    C++ Arrays. In C++, an array is a variable that can store multiple values of the same type. For example, Suppose a class has 27 students, and we need to store all their grades. Instead of creating 27 separate variables, we can simply create an array: double grade[27]; Here, grade is an array that can hold a maximum of 27 elements of double type.

  13. Java Array (With Examples)

    An array is a collection of similar types of data. For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names. String[] array = new String[100]; Here, the above array cannot store more than 100 names. The number of values in a Java array is always fixed.

  14. Java Arrays

    Java Arrays. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets: We have now declared a variable that holds an array of strings. To insert values to it, you can place the values in a comma-separated list, inside ...

  15. Python Arrays

    Python Variables Variable Names Assign Multiple Values Output Variables Global Variables Variable Exercises. ... An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: ...

  16. JavaScript Arrays

    Creating an Array. Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [ item1, item2, ... ]; It is a common practice to declare arrays with the const keyword. Learn more about const with arrays in the chapter: JS Array Const.

  17. Array Variable Assignment in Java

    Array Variable Assignment in Java. An array is a collection of similar types of data in a contiguous location in memory. After Declaring an array we create and assign it a value or variable. During the assignment variable of the array things, we have to remember and have to check the below condition. 1.

  18. Arrays in Java

    Do refer to default array values in Java. Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.

  19. Using arrays (VBA)

    In this article. You can declare an array to work with a set of values of the same data type.An array is a single variable with many compartments to store values, while a typical variable has only one storage compartment in which it can store only one value. Refer to the array as a whole when you want to refer to all the values it holds, or you can refer to its individual elements.

  20. Array assignment and reference in Java

    1. When you assigned value of a to b, it means b is referring to same space allocated to array a. This means b will pick up any changes made to the array a, but if any changes made to the variable a. If a is made to refer to new array, b will still refer the old a reference.