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

Sorry about that.

Related Tutorials

Java Tutorial

Java Library

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.

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

last modified February 23, 2024

In this article we cover 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.

A scalar variable can hold only one item at a time. Arrays can hold multiple items. These items are called elements of the array. Arrays store data of the same data type . Each element can be referred to by an index. Arrays are zero based. The index of the first element is zero.

Array definition

Arrays are used to store data of our applications. We declare arrays to be of a certain data type. We specify their length. And we initialize arrays with data. We have several methods for working with arrays. We can modify the elements, sort them, copy them or search for them.

We have three array declarations. The declaration consists of two parts: the type of the array and the array name. The type of an array has a data type that determines the types of the elements within an array ( int , String , float in our case) and a pair of square brackets [] . The brackets indicate that we have an array.

Collections serve a similar purpose like arrays. They are more powerful than arrays. They will be described later in a separate chapter.

Initializing arrays

There are several ways how we can initialize an array in Java. In the first example, an array is created and initialized in two steps.

We create and initialize a numerical array. The contents of the array are printed to the console.

Here we create an array which can contain five elements. The statement allocates memory for five integers. The square brackets are used for declaring an array, the type ( int in our case) tells us what type of values the array will hold. An array is an object and therefore it is created with the new keyword.

We initialize the array with some data. This is assignment initialization. The indexes are in the square brackets. Number 1 is going to be the first element of the array, number 2 is the second etc.

The Arrays class is a helper class which contains various methods for manipulating arrays. The toString method returns a string representation of the contents of the specified array. This method is helpful in debugging.

We can declare and initialize an array in one statement.

This is a modified version of the previous program.

An array is created and initialized in one step. The elements are specified in curly brackets. We did not specify the length of the array. The compiler will do it for us.

The one step creation and initialization can be further simplified by only specifying the numbers between the curly brackets.

An array of integers is created using the most simple way of array creation.

The new int[] construct can be omitted. The right side of the statement is an array literal notation. It resembles the C/C++ style of array initialization. Even if we drop the new keyword, the array is created the same way as in previous two examples. This is just a convenient shorthand notation.

Accessing array elements

After the array is created, its elements can be accessed by their index. The index is a number placed inside square brackets which follow the array name.

In the example, we create an array of string names. We access each of the elements by its index and print them to the terminal.

An array of strings is created.

Each of the elements of the array is printed to the console. With the names[0] construct, we refer to the first element of the names array.

Running the example we get the above output.

It is possible to change the elements of an array. The elements are not immutable.

We have an array of three integers. Each of the values will be multiplied by two.

An array of three integers is created.

Using the element access, we multiply each value in the array by two.

Traversing arrays

We often need to go through all elements of an array. We show two common methods for traversing an array.

An array of planet names is created. We use the for loop to print all the values.

In this loop, we utilize the fact that we can get the number of elements from the array object. The number of elements is stored in the length constant.

An enhanced for keyword can be used to make the code more compact when traversing arrays or other collections. In each cycle, the planet variable is passed the next value from the planets array.

Passing arrays to methods

In the next example, we pass an array to a method.

The example reorders the elements of an array. For this task, a reverseArray method is created.

The reverseArray method takes an array as a parameter and returns an array. The method takes a copy of the passed array.

Inside the body of the method, a new array is created; it will contain the newly ordered elements.

In this for loop, we fill the new array with the elements of the copied array. The elements are reversed.

The newly formed array is returned back to the caller.

We print the elements of the original and the reversed array.

Multidimensional arrays

So far we have been working with one-dimensional arrays. In Java, we can create multidimensional arrays. A multidimensional array is an array of arrays. In such an array, the elements are themselves arrays. In multidimensional arrays, we use two or more sets of brackets.

In this example, we create a two-dimensional array of integers.

Two pairs of square brackets are used to declare a two-dimensional array. Inside the curly brackets, we have additional two pairs of curly brackets. They represent two inner arrays.

We determine the length of the outer array that holds other two arrays and the second inner array.

Two for loops are used to print all the six values from the two-dimensional array. The first index of the twodim[i][j] array refers to one of the inner arrays. The second index refers to the element of the chosen inner array.

In a similar fashion, we create a three-dimensional array of integers.

A variable that holds a three-dimensional array is declared with three pairs of square brackets. The values are place inside three pairs of curly brackets.

Three-dimensional array n3 is created. It is an array that has elements which are themselves arrays of arrays.

We get the length of all three dimensions.

We need three for loops to traverse a three dimensional array.

Irregular arrays

Arrays that have elements of the same size are called rectangular arrays. It is possible to create irregular arrays where the arrays have a different size. In C# such arrays are called jagged arrays .

This is an example of an irregular array.

This is a declaration and initialization of an irregular array. The three inner arrays have 2, 3, and 4 elements.

The enhanced for loop is used to go through all the elements of the array.

Array methods

The Arrays class, available in the java.util package, is a helper class that contains methods for working with arrays. These methods can be used for modifying, sorting, copying, or searching data. These methods that we use are static methods of the Array class. (Static methods are methods that can be called without creating an instance of a class.)

In the code example, we present five methods of the Arrays class.

We will use the shorthand notation for the Arrays class.

We have an array of five integers.

The sort method sorts the integers in an ascending order.

The toString method returns a string representation of the contents of the specified array.

The fill method assigns the specified integer value to each element of the array.

The copyOf method copies the specified number of elements to a new array.

The equals method compares the two arrays. Two arrays are equal if they contain the same elements in the same order.

Comparing arrays

There are two methods for comparing arrays. The equals method and the deepEquals method. The deepEquals method also compares references to arrays inside arrays.

The example explains the difference between the two methods.

We have two arrays of integers.

The c array has two inner arrays. The elements of the inner arrays are equal to the a and b arrays.

The d array contains references to a and b arrays.

Now the c and d arrays are compared using both methods. For the equals method, the arrays are not equal. The deepEquals method goes deeper in the referenced arrays and retrieves their elements for comparison. For this method, the c and d arrays are equal.

Searching arrays

The Arrays class has a simple method for searching elements in an array. It is called the binarySearch . The method searches for elements using a binary search algorithm. The binarySearch method only works on sorted arrays.

In the example, we search for the "Earth" string in an array of planets.

Since the algorithm only works on sorted arrays, we must sort the array first.

We will be searching for the "Earth" element.

The binarySearch method is called. The first parameter is the array name, the second the element we are looking for. If the element is found, the return value is greater or equal to zero. In such a case, it is the index of the element in the sorted array.

Depending on the returned value, we create a message.

Download image

In the next example, we show how to download an image.

The example downloads a small favicon.ico image.

An image is an array of bytes. We create an empty array of byte values big enough to hold the icon.

We read the binary data and write it to the file.

Java arrays - tutorial

In this article we worked with arrays.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java tutorials .

array assignment statement java

How to Declare and Initialize an Array in Java

array assignment statement java

  • Introduction

In this tutorial, we'll take a look at how to declare and initialize arrays in Java .

We declare an array in Java as we do other variables, by providing a type and name:

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax:

Or, you could generate a stream of values and assign it back to the array:

To understand how this works, read more to learn the ins and outs of array declaration and instantiation!

  • Array Declaration in Java
  • Array Initialization in Java
  • IntStream.range()
  • IntStream.rangeClosed()
  • IntStream.of()
  • Java Array Loop Initialization

The declaration of an array object in Java follows the same logic as declaring a Java variable. We identify the data type of the array elements, and the name of the variable, while adding rectangular brackets [] to denote its an array.

Here are two valid ways to declare an array:

The second option is oftentimes preferred, as it more clearly denotes of which type intArray is.

Note that we've only created an array reference. No memory has been allocated to the array as the size is unknown, and we can't do much with it.

To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size:

This allocates the memory for an array of size 10 . This size is immutable.

Java populates our array with default values depending on the element type - 0 for integers, false for booleans, null for objects, etc. Let's see more of how we can instantiate an array with values we want.

The slow way to initialize your array with non-default values is to assign values one by one:

In this case, you declared an integer array object containing 10 elements, so you can initialize each element using its index value.

The most common and convenient strategy is to declare and initialize the array simultaneously with curly brackets {} containing the elements of our array.

The following code initializes an integer array with three elements - 13, 14, and 15:

Keep in mind that the size of your array object will be the number of elements you specify inside the curly brackets. Therefore, that array object is of size three.

This method work for objects as well. If we wanted to initialize an array of three Strings, we would do it like this:

Java allows us to initialize the array using the new keyword as well:

It works the same way.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Note : If you're creating a method that returns an initialized array, you will have to use the new keyword with the curly braces. When returning an array in a method, curly braces alone won't work:

If you're declaring and initializing an array of integers, you may opt to use the IntStream Java interface:

The above code creates an array of ten integers, containing the numbers 1 to 10:

The IntStream interface has a range() method that takes the beginning and the end of our sequence as parameters. Keep in mind that the second parameter is not included, while the first is.

We then use the method toArray() method to convert it to an array.

Note: IntStream is just one of few classes that can be used to create ranges. You can also use a DoubleStream or LongStream in any of these examples instead.

If you'd like to override that characteristic, and include the last element as well, you can use IntStream.rangeClosed() instead:

This produces an array of ten integers, from 1 to 10:

The IntStream.of() method functions very similarly to declaring an array with some set number of values, such as:

Here, we specify the elements in the of() call:

This produces an array with the order of elements preserved:

Or, you could even call the sorted() method on this, to sort the array as it's being initialized:

Which results in an array with this order of elements:

One of the most powerful techniques that you can use to initialize your array involves using a for loop to initialize it with some values.

Let's use a loop to initialize an integer array with values 0 to 9:

This is identical to any of the following, shorter options:

A loop is more ideal than the other methods when you have more complex logic to determine the value of the array element.

For example, with a for loop we can do things like making elements at even indices twice as large:

In this article, we discovered the different ways and methods you can follow to declare and initialize an array in Java. We've used curly braces {} , the new keyword and for loops to initialize arrays in Java, so that you have many options for different situations!

We've also covered a few ways to use the IntStream class to populate arrays with ranges of elements.

You might also like...

  • Java: Finding Duplicate Elements in a Stream
  • Spring Boot with Redis: HashOperations CRUD Functionality
  • Spring Cloud: Hystrix
  • Java Regular Expressions - How to Validate Emails

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

I am a very curious individual. Learning is my drive in life and technology is the language I speak. I enjoy the beauty of computer science and the art of programming.

In this article

Make clarity from data - quickly learn data visualization with python.

Learn the landscape of Data Visualization tools in Python - work with Seaborn , Plotly , and Bokeh , and excel in Matplotlib !

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013- 2024 Stack Abuse. All rights reserved.

Java Array Declaration – How to Initialize an Array in Java with Example Code

Kolade Chris

Arrays are an important part of the fundamental data structures in Java. And they are incredibly useful in solving a lot of programming problems.

What is an array?

By definition, an array is a collection of data of the same type.

An array is usually declared so you can have multiple values in the same memory – unlike variables where you can only have one value in the memory.

So, arrays let you create one variable that holds different values together, instead of declaring a variable for each value.

The position of a particular data point in the array is called its index, while the data itself is called an element.

In this tutorial, I will show you how to declare an array, initialize it, and loop through it with the for loop and enhanced for loop. Then you can start using it in your Java projects.

I will be using the intelliJIDEA IDE to write the code. You can use it if you want, or you can also use any IDE of your choice.

How to Declare and Intialize an Array in Java

There are two ways you can declare and initialize an array in Java. The first is with the new keyword, where you have to initialize the values one by one. The second is by putting the values in curly braces.

How to initialize an array with the new keyword

You can declare the array with the syntax below:

dataType : the type of data you want to put in the array. This could be a string, integer, double, and so on. [ ] : signifies that the variable to declare will contain an array of values nameOfArrary : The array identifier.

With the above information, you have only declared the array – you still need to initialize it.

The basic syntax for initializing an array in this way looks like this:

The size is usually expressed with a numberic value. It signifies how many values you want to hold in the array. Its value is immutable, meaning you won’t be able to put more than the number specified as the size in the array.

You can now go ahead and put values in the array like this:

In the code snippet above, I initialized an array of strings called names (the identifier). The size is 3, so it can only hold three values.

There are 3 indexes in total:

  • The value, Quincy is at index 0
  • The value Abbey is at index 1
  • The value Kolade is at index 2

Don’t be confused by the numbers 0, 1, 2. Arrays are zero-indexed, so counting starts from 0, not 1.

In the array above, if you add extra data – for example, names[3] = “Chris” – you would get an error because you have specified that the array should only contain 3 values. If you want to add more values, you have to increase the size of the array.

error-1

To print the array to the console, you can use the inbuilt toString() method:

names-print

2. How to initialize an array in one line

You can initialize an array in one line with the basic syntax below:

With this method, you don’t need to specify the size of the array, so you can put any number of values you want in it.

Check out the example in the code snippet below:

names-print-2

How to Loop Through an Array in Java

You can loop through an array in Java with the for loop and enhanced for loop. With the for loop, you have access to the index of the individual values, but with the enhanced for loop, you don’t.

How to loop through an array with the for loop

In Java, you can use the for loop with the basic syntax below:

You can then loop through the namesTwo array like this:

for-loop

How to loop through an array with the enhanced for loop

The enhanced for loop is a cleaner version of the for loop. The downside is that with it, you don’t have access to the index of the individual values in the array.

The basic syntax of the enhanced for loop looks like this:

enhanced-for-loop

In this tutorial, you learned how to declare and initialize an array in two different ways – with the new keyword and using curly braces.

You also learned how to loop through arrays with the for loop and enhanced for loop, so you don’t just initialize an array and do nothing with it.

Thank you for reading, and keep coding.

Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, 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 curly braces:

To create an array of integers, you could write:

Access the Elements of an Array

You can access an array element by referring to the index number.

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

Try it Yourself »

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Array Element

To change the value of a specific element, refer to the index number:

Array Length

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

Test Yourself With Exercises

Create an array of type String called cars .

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.

Javatpoint Logo

Java Object Class

Java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

clear sunny desert yellow sand with celestial snow bridge

1.7 Java | Assignment Statements & Expressions

An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java.

After a variable is declared, you can assign a value to it by using an assignment statement . In Java, the equal sign = is used as the assignment operator . The syntax for assignment statements is as follows:

An expression represents a computation involving values, variables, and operators that, when taking them together, evaluates to a value. For example, consider the following code:

You can use a variable in an expression. A variable can also be used on both sides of the =  operator. For example:

In the above assignment statement, the result of x + 1  is assigned to the variable x . Let’s say that x is 1 before the statement is executed, and so becomes 2 after the statement execution.

To assign a value to a variable, you must place the variable name to the left of the assignment operator. Thus the following statement is wrong:

Note that the math equation  x = 2 * x + 1  ≠ the Java expression x = 2 * x + 1

Java Assignment Statement vs Assignment Expression

Which is equivalent to:

And this statement

is equivalent to:

Note: The data type of a variable on the left must be compatible with the data type of a value on the right. For example, int x = 1.0 would be illegal, because the data type of x is int (integer) and does not accept the double value 1.0 without Type Casting .

◄◄◄BACK | NEXT►►►

What's Your Opinion? Cancel reply

Enhance your Brain

Subscribe to Receive Free Bio Hacking, Nootropic, and Health Information

HTML for Simple Website Customization My Personal Web Customization Personal Insights

DISCLAIMER | Sitemap | ◘

SponserImageUCD

HTML for Simple Website Customization My Personal Web Customization Personal Insights SEO Checklist Publishing Checklist My Tools

Top Posts & Pages

The Best Keyboard Tilt for Reducing Wrist Pain to Zero

  • Watch & Listen
  • Oracle University

Previous in the Series: Creating Primitive Type Variables in Your Programs

Next in the Series: Using the Var Type Identifier

Creating Arrays in Your Programs

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 8 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 6th element, for example, would therefore be accessed at index 5.

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 discussed in the Classes 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 java.util.Arrays method of the java.util.Arrays class, as you can see in the ArrayCopyOfDemo example. The difference is that using the java.util.Arrays 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 java.util.Arrays 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:

Wrapping-up Variables and Arrays

The Java programming language uses both "fields" and "variables" as part of its terminology. Instance variables (non-static fields) are unique to each instance of a class. Class variables (static fields) are fields declared with the static modifier; there is exactly one copy of a class variable, regardless of how many times the class has been instantiated. Local variables store temporary state inside a method. Parameters are variables that provide extra information to a method; both local variables and parameters are always classified as "variables" (not "fields"). When naming your fields or variables, there are rules and conventions that you should (or must) follow.

The eight primitive data types are: byte , short , int , long , float , double , boolean , and char . The java.lang.String class represents character strings. The compiler will assign a reasonable default value for fields of the above types; for local variables, a default value is never assigned.

A literal is the source code representation of a fixed value. 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.

More Learning

In this tutorial.

Last update: August 27, 2022

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • Sort an array of Strings in JavaScript ?
  • Alternative of Array splice() method in JavaScript
  • JavaScript Program to Rearrange Array Alternately
  • How to shuffle an array using JavaScript ?
  • Sort a string in JavaScript
  • Bubble Sort algorithm using JavaScript
  • How to Sort Numeric Array using JavaScript ?
  • Sort a string alphabetically using a function in JavaScript
  • How to get the longest string in an array using JavaScript ?
  • How to convert Object's array to an array using JavaScript ?
  • How to sort an array on multiple columns using JavaScript ?
  • JavaScript Array sort() Method
  • Sort an array of objects using Boolean property in JavaScript
  • How to sort an HTML list using JavaScript ?
  • Insertion Sort Visualization using JavaScript
  • Median of 2 Sorted Arrays of Equal Size using JavaScript
  • How to sort rows in a table using JavaScript ?
  • JavaScript Get all non-unique values from an array
  • Javascript Program For Sorting An Array Of 0s, 1s and 2s

Alternative Sorting of an Array using JavaScript

Alternative sorting means we have to arrange the elements of an array in such a way that the first element is the first maximum and the second element is the first minimum, the third element is the second maximum, the fourth element is the second minimum, and so on.

Below are the approaches for Alternative sorting of an array using JavaScript:

Table of Content

Sorting and Rearranging

Using two arrays.

In this approach, sort an array and then rearranges it in an alternating high-low order in JavaScript . It first sorts the array in ascending order, then uses a while loop to alternately push the largest remaining element and the smallest remaining element to a new array. The final array is returned and logged.

Example: The example below shows Alternative sorting of an array using Sorting and Rearranging.

Time complexity: O(n log n)

Space complexity: O(n)

Sort the array in ascending order. Divide the sorted array into two halves where maxArray, containing elements from the middle index to the end, reversed and minArray, containing elements from the start to the middle index. Create an empty result array. Iterate over maxArray and minArray alternately, pushing elements into the result array. If one array has fewer elements, handle them appropriately. Return the result array.

Example: The example below shows Alternative sorting of an array using Two Arrays.

Time complexity: O(n log n).

Space complexity: O(n).

Please Login to comment...

Similar reads.

  • JavaScript-Program
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. An Introduction to Java Arrays

    array assignment statement java

  2. Java

    array assignment statement java

  3. Java 1

    array assignment statement java

  4. How to create a String or Integer Array in Java? Example Tutorial

    array assignment statement java

  5. Java Assignment Operators

    array assignment statement java

  6. Programming Model

    array assignment statement java

VIDEO

  1. Chapter 7 Arrays and Arraylist Part 1

  2. SGD Programming 1 : Array Assignment

  3. Java Arrays: Part1

  4. Bouncing Balls in Java Console

  5. Java Bangla Tutorials 74 : Assignment 18

  6. Java: review of arrays, loops, conditionals

COMMENTS

  1. Java array assignment (multiple values)

    Java does not provide a construct that will assign of multiple values to an existing array's elements. The initializer syntaxes can ONLY be used when creation a new array object. This can be at the point of declaration, or later on. But either way, the initializer is initializing a new array object, not updating an existing one.

  2. Array Variable Assignment in Java

    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. Element Level Promotion. Element-level promotions are not applicable at the array level. Like a character can be promoted to integer but a character array type ...

  3. Java Array (With Examples)

    To define the number of elements that an array can hold, we have to allocate memory for the array in Java. For example, // declare an array double[] data; // allocate memory. data = new double[10]; 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 ...

  4. 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.

  5. How do I declare and initialize an array in Java?

    Static Array: Fixed size array (its size should be declared at the start and can not be changed later) Dynamic Array: No size limit is considered for this. (Pure dynamic arrays do not exist in Java. Instead, List is most encouraged.) To declare a static array of Integer, string, float, etc., use the below declaration and initialization statements.

  6. Arrays in Java: A Reference Guide

    It's also possible to create the stream only on a subset of the array: Stream<String> anotherStream = Arrays.stream(anArray, 1, 3 ); Copy. This will create a Stream<String> with only "Tomato" and "Chips" Strings (the first index being inclusive while the second one is exclusive). 9. Sorting Arrays.

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

    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.

  8. Java array

    The contents of the array are printed to the console. int[] a = new int[5]; Here we create an array which can contain five elements. The statement allocates memory for five integers. The square brackets are used for declaring an array, the type ( int in our case) tells us what type of values the array will hold.

  9. How to Declare and Initialize an Array in Java

    Java Array Loop Initialization; Array Declaration in Java. The declaration of an array object in Java follows the same logic as declaring a Java variable. We identify the data type of the array elements, and the name of the variable, while adding rectangular brackets [] to denote its an array. Here are two valid ways to declare an array:

  10. Java Array Declaration

    How to initialize an array with the new keyword. You can declare the array with the syntax below: dataType [ ] nameOfArray; dataType: the type of data you want to put in the array. This could be a string, integer, double, and so on. [ ]: signifies that the variable to declare will contain an array of values.

  11. 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 ...

  12. Java Array

    Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on. Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator. In Java, array is an object of a dynamically generated class.

  13. Java Assignment Operators with Examples

    variable operator value; Types of Assignment Operators in Java. The Assignment Operator is generally of two types. They are: 1. Simple Assignment Operator: The Simple Assignment Operator is used with the "=" sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

  14. 1.7 Java

    An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java. After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal sign = is used as the assignment operator. The syntax for assignment statements is as follows: variable ...

  15. Creating Arrays in Your Programs

    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 java.util.Arrays method of the java.util.Arrays class, as you can see in the ArrayCopyOfDemo example.

  16. Multidimensional Arrays in Java

    Array-Basics in Java Multidimensional Arrays can be defined in simple words as array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Syntax: data_type[1st dimension] [2nd dimension] [].. [Nth dimension] array_name = new data_type[size1] [size2]…. [sizeN]; where:

  17. Java Array exercises: Array Exercises

    Java Array Exercises [79 exercises with solution] [ An editor is available at the bottom of the page to write and execute the scripts. Go to the editor] 1. Write a Java program to sort a numeric array and a string array. Click me to see the solution. 2. Write a Java program to sum values of an array. Click me to see the solution.

  18. java

    133. You still need to create the array, even if you do not assign it to a variable. Try this: public int[] getData() {. return new int[] {a,b,c,d}; } Your code sample did not work because the compiler, for one thing, still needs to know what type you are attempting to create via static initialization {}. answered Feb 17, 2012 at 16:24.

  19. How does assignment work in multi-dimensional arrays in java?

    1. Length is 4 because you're initializing i to 4 in the line before inizializing the array. So replacing i with actual values you're doing. int ia[][][] = new int[4][3][3]; Also, i'd consider assigning i a new value at the same time as initializing the array to be bad practice (readability). Furhthermore, ia doesn't "have 3 arrays" it's a ...

  20. String Arrays in Java

    Time Complexity: O(N), where N is length of array. Auxiliary Space: O(1) So generally we are having three ways to iterate over a string array. The first method is to use a for-each loop. The second method is using a simple for loop and the third method is to use a while loop. You can read more about iterating over array from Iterating over Arrays in Java ...

  21. String Array Assignment in Java

    An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values. Java Specification

  22. Alternative Sorting of an Array using JavaScript

    Alternative sorting means we have to arrange the elements of an array in such a way that the first element is the first maximum and the second element is the first minimum, the third element is the second maximum, the fourth element is the second minimum, and so on. Example: Input: array = [5, 6, 2, 4, 3, 1] Output: array = [6, 1, 5, 2, 4, 3 ...