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

  • Prev Class
  • Next Class
  • No Frames
  • All Classes
  • Summary: 
  • Nested | 
  • Field | 
  • Constr | 
  • Detail: 

Class Arrays

  • java.lang.Object
  • java.util.Arrays

Method Summary

Methods inherited from class java.lang. object, method detail, parallelsort, parallelprefix, binarysearch, copyofrange, deephashcode, deeptostring, parallelsetall, spliterator.

Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation . That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. Copyright © 1993, 2024, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms . Also see the documentation redistribution policy .

Scripting on this page tracks web page traffic, but does not change the content in any way.

  • 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 java

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

Trending Articles on Technical and Non Technical topics

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Assigning arrays in Java.

While creating variables first of all we will declare them, initialize them, assign/re-assign values to them.

Similarly, while creating arrays −

You can declare an array just like a variable −

You can create an array just like an object using the new keyword −

You can initialize the array by assigning values to all the elements one by one using the index −

Assigning values to an array

When we assign primitive values of one type to a variable of other (datatype) implicitly they are converted.

But, when you try to assign a higher datatype to lower, at the time of compilation you will get an error saying “incompatible types: possible lossy conversion”

Therefore while assigning values to the elements of an array you can assign any value which will be cast implicitly.

But, if you try to assign incompatible types (higher types) to a variable a compile-time error will be generated saying “possible lossy conversion”.

 Live Demo

Compile-time error

If you have an array of objects while assigning values to the elements of it, you need to make sure that the objects you assign should be of the same or, a subtype of the class (which is the type of the array).

But to an array of objects if you assign a value which is neither the declared type nor its subtype a compile-time error will be generated.

If you have created an array of objects of an interface type you need to make sure that the values, you assign to the elements of the array are the objects of the class that implements the said interface.

Maruthi Krishna

Related Articles

  • Assigning values to static final variables in java\n
  • Assigning long values carefully in java to avoid overflow\n
  • Final Arrays in Java
  • String Arrays in Java
  • Most Profit Assigning Work in C++
  • Assigning function to variable in JavaScript?
  • Compare Two Java int Arrays in Java
  • How to process Arrays in Java?
  • What is length in Java Arrays?
  • Sort arrays of objects in Java
  • Dump Multi-Dimensional arrays in Java
  • Intersection of two arrays in Java
  • Merge two sorted arrays in Java
  • Streams on Arrays in Java 8
  • Merge k sorted arrays in Java

Kickstart Your Career

Get certified by completing the course

To Continue Learning Please Login

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Java Tutorial

Overview of Java

  • Introduction to Java
  • The Complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works - JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted Output in Java using printf()
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples
  • Java Assignment Operators with Examples
  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java

Multidimensional Arrays in Java

  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • 'this' reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Singleton Method Design Pattern in Java
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Java Try Catch Block
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • Regex Tutorial - How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

JDBC - Java Database Connectivity

  • Introduction to JDBC (Java Database Connectivity)
  • JDBC Drivers
  • Establishing JDBC Connection in Java
  • Types of Statements in JDBC
  • JDBC Tutorial
  • Java 8 Features - Complete Tutorial

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

data_type [1st dimension][2nd dimension][]..[Nth dimension] array_name = new data_type [size1][size2]….[sizeN];
  • data_type : Type of data to be stored in the array. For example: int, char, etc.
  • dimension : The dimension of the array created. For example: 1D, 2D, etc.
  • array_name : Name of the array
  • size1, size2, …, sizeN : Sizes of the dimensions respectively.

Size of multidimensional arrays : The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. 

For example: The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements. Similarly, array int[][][] x = new int[5][10][20] can store a total of (5*10*20) = 1000 elements.

Application of Multi-Dimensional Array

● Multidimensional arrays are used to store the data in a tabular form. For example, storing the roll number and marks of a student can be easily done using multidimensional arrays. Another common usage is to store the images in 3D arrays. 

● In dynamic programming questions, multidimensional arrays are used which are used to represent the states of the problem. 

● Apart from these, they also have applications in many standard algorithmic problems like:  Matrix Multiplication, Adjacency matrix representation in graphs, Grid search problems

Two – dimensional Array (2D-Array)

Two – dimensional array is the simplest form of a multidimensional array. A two – dimensional array can be seen as an array of one – dimensional array for easier understanding. 

Indirect Method of Declaration:

  • Declaration – Syntax:
  • Initialization – Syntax:

Example: Implementing 2D array with by default values with 4*4 matrix

Explanation:.

  • The number of rows and columns are specified using the variables rows and columns. The 2D array is created using the new operator, which allocates memory for the array. The size of the array is specified by rows and columns.  

Direct Method of Declaration: Syntax:

Example:  

Accessing Elements of Two-Dimensional Arrays

Elements in two-dimensional arrays are commonly referred by x[i][j] where ‘i’ is the row number and ‘j’ is the column number. 

For example:

The above example represents the element present in first row and first column. Note : In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual row number is 2+1 = 3. Example:  

Representation of 2D array in Tabular Format:

A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3 rows and 3 columns is shown below: 

two-d

  Print 2D array in tabular format:  

To output all the elements of a Two-Dimensional array, use nested for loops. For this two for loops are required, One to traverse the rows and another to traverse columns.

Example:  Implementation of 2D array with User input

  • This code prompts the user to enter the number of rows and columns for the 2-dimensional array. The Scanner class is used to read the user input. Then it creates a 2-dimensional array of integers with the specified number of rows and columns, and assigns each element of the array with i*j.
  • If you want to create a multidimensional array with more than two dimensions, you can use the same approach of creating an array of arrays. For example, to create a 3-dimensional array, you can create an array of 2-dimensional arrays.

Three – dimensional Array (3D-Array)

Three – dimensional array is a complex form of a multidimensional array. A three-dimensional array can be seen as an array of two – dimensional array for easier understanding. 

Accessing Elements of Three-Dimensional Arrays

Elements in three-dimensional arrays are commonly referred by x[i][j][k] where ‘i’ is the array number, ‘j’ is the row number and ‘k’ is the column number. 

The above example represents the element present in the first row and first column of the first array in the declared 3D array. 

Note : In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual row number is 2+1 = 3. 

Representation of 3D array in Tabular Format:  

A three-dimensional array can be seen as a table of arrays with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A three – dimensional array with 3 array containing 3 rows and 3 columns is shown below: 

array assignment java

  Print 3D array in tabular format:  

To output all the elements of a Three-Dimensional array, use nested for loops. For this three for loops are required, One to traverse the arrays, second to traverse the rows and another to traverse columns. 

Inserting a Multi-dimensional Array during Runtime:  

This topic is forced n taking user-defined input into a multidimensional array during runtime. It is focused on the user first giving all the input to the program during runtime and after all entered input, the program will give output with respect to each input accordingly. It is useful when the user wishes to make input for multiple Test-Cases with multiple different values first and after all those things are done, program will start providing output. As an example, let’s find the total number of even and odd numbers in an input array. Here, we will use the concept of a 2-dimensional array. 

Here are a few points that explain the use of the various elements in the upcoming code:

  • Row integer number is considered as the number of Test-Cases and Column values are considered as values in each Test-Case.
  • One for() loop is used for updating Test-Case number and another for() loop is used for taking respective array values.
  • As all input entry is done, again two for() loops are used in the same manner to execute the program according to the condition specified.
  • The first line of input is the total number of TestCases.
  • The second line shows the total number of first array values.
  • The third line gives array values and so on.

Implementation:  

Please Login to comment...

Similar reads.

author

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, java arraylist toarray() method.

❮ ArrayList Methods

Get an array from an ArrayList :

Try it Yourself »

Definition and Usage

The toArray() method returns an array containing all of the items in the list.

If no argument is passed then the type of the returned array will be Object . If an array is passed as an argument then this method will return an array with the same data type.

If the array in the argument is large enough to contain all of the list items then this method will return the argument itself after writing the list items into it.

One of the following:

T refers to the data type of items in the list.

Parameter Values

Technical details, more examples.

Specify the return type of toArray() :

Related Pages

Java Arrays Tutorial

Java ArrayList Tutorial

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.

IMAGES

  1. The Arrays Class in Java (Part 1)

    array assignment java

  2. How to create a char array in Java?

    array assignment java

  3. Java Arraylist Example: How to Use Arraylists in Java

    array assignment java

  4. String to char array java

    array assignment java

  5. Java Program to Count Array Duplicates

    array assignment java

  6. Two Dimensional Array Example in Java

    array assignment java

VIDEO

  1. Chapter 7 Arrays and Arraylist Part 1

  2. Infosys Springboard Lex Assignment Answers

  3. Bouncing Balls in Java Console

  4. Java project

  5. Java Arrays: Part1

  6. What is an Array in Java?

COMMENTS

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

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

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

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

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

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

  7. Arrays (Java Platform SE 8 )

    Class Arrays. This class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists. The methods in this class all throw a NullPointerException , if the specified array reference is null, except where noted.

  8. Java array

    In the code example, we present five methods of the Arrays class. import java.util.Arrays; We will use the shorthand notation for the Arrays class. int[] a = { 5, 2, 4, 3, 1 }; We have an array of five integers. Arrays.sort(a); The sort method sorts the integers in an ascending order.

  9. How To Use Arrays in Java

    password = Arrays.copyOf ( password, 10); In the preceding example, you reassign the value of password to a new array. This new array is the result of copying the old password array to a new array with a length of 10 elements. To copy it, you used the method Arrays.copyOf(), which accepts two arguments.

  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. Assigning arrays in Java.

    Advertisements. Assigning arrays in Java - While creating variables first of all we will declare them, initialize them, assign/re-assign values to them.Similarly, while creating arrays −You can declare an array just like a variable −int myArray [];You can create an array just like an object using the new keyword −myArray = new int [5];Yo.

  12. 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:

  13. Creating a Generic Array in Java

    a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); Notice how it makes use of Array#newInstance to build a new array, like in our previous stack example. We can also see that parameter a is used to provide a type to Array#newInstance. Finally, the result from Array#newInstance is cast to T[] to create a generic ...

  14. How to make an array of arrays in Java

    String[][] arrays = new String[][] { array1, array2, array3, array4, array5 }; (The latter syntax can be used in assignments other than at the point of the variable declaration, whereas the shorter syntax only works with declarations.) answered Jan 24, 2011 at 10:54. Jon Skeet.

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

  16. java

    4. You need to provide the type of array. Use this: arrayOfIntegers = new int[] {11,12,15,17}; From JLS Section 10.6: 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. If you are trying to re-assign array ...

  17. Problem with assigning an array to other array in Java

    If you want to make a copy, you could use val1.clone() or Arrays.copyOf(): int[] val2 = Arrays.copyOf(val1, val1.length); Objects (including instances of collection classes, String, Integer etc) work in a similar manner, in that assigning one variable to another simply copies the reference, making both variables refer to the same object.

  18. Java ArrayList toArray() Method

    Definition and Usage. The toArray() method returns an array containing all of the items in the list. If no argument is passed then the type of the returned array will be Object. If an array is passed as an argument then this method will return an array with the same data type. If the array in the argument is large enough to contain all of the ...

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