Learn Java practically and Get Certified .

Popular Tutorials

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

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

Java Fundamentals

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

Java Flow Control

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

Java for-each Loop

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

Java Arrays

Java Multidimensional Arrays

Java Copy Arrays

Java OOP(I)

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

Java OOP(II)

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

Java OOP(III)

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

Java I/o Streams

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

Java Reader/Writer

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

Additional Topics

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

Java Tutorials

Java Math max()

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

An array is a collection of similar types of data.

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

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

  • How to declare an array in Java?

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

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

For example,

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

But, how many elements can array this hold?

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

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

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

  • How to Initialize Arrays in Java?

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

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

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

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

Elements are stored in the array

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

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

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

Example: Access Array Elements

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

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

  • Looping Through Array Elements

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

Example: Using For Loop

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

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

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

Example: Using the for-each Loop

  • Example: Compute Sum and Average of Array Elements

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

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

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

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

  • Multidimensional Arrays

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

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

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

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

Table of Contents

  • Introduction

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

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

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

Sorry about that.

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

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Java Tutorial

Java Library

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.

How to Declare and Initialize an Array in Java

java assignment of array

  • 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

java assignment of array

Monitor with Ping Bot

Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.

OpenAI

Vendor Alerts with Ping Bot

Get detailed incident alerts about the status of your favorite vendors. Don't learn about downtime from your customers, be the first to know with Ping Bot.

Supabase

© 2013- 2024 Stack Abuse. All rights reserved.

  • Trending Categories

Data Structure

  • 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
  • Streams on Arrays in Java 8
  • How to process Arrays in Java?
  • What is length in Java Arrays?
  • Intersection of two arrays in Java
  • Merge two sorted arrays in Java
  • Sort arrays of objects in Java
  • Dump Multi-Dimensional arrays in Java
  • Merge k sorted arrays in Java

Kickstart Your Career

Get certified by completing the course

How to Create an Array in Java – Array Declaration Example

freeCodeCamp

By Shittu Olumide

Creating and manipulating arrays is an essential skill for any Java programmer. Arrays provide a way to store and organize multiple values of the same type, making it easier to work with large sets of data.

In this article, we will provide a step-by-step guide on how to create an array in Java, including how to initialize or create an array. We will also cover some advanced topics such as multi-dimensional arrays, array copying, and array sorting.

Whether you're new to Java programming or an experienced developer looking to refresh your skills, this article will provide you with the knowledge you need to become proficient in working with Java arrays.

What is an Array in Java?

In Java, an array is a data structure that can store a fixed-size sequence of elements of the same data type. An array is an object in Java, which means it can be assigned to a variable, passed as a parameter to a method, and returned as a value from a method.

Arrays in Java are zero-indexed, which means that the first element in an array has an index of 0, the second element has an index of 1, and so on. The length of an array is fixed when it is created and cannot be changed later.

Java arrays can store elements of any data type, including primitive types such as int, double, and boolean, as well as object types such as String and Integer. Arrays can also be multi-dimensional, meaning that they can have multiple rows and columns.

Arrays in Java are commonly used to store collections of data, such as a list of numbers, a set of strings, or a series of objects. By using arrays, we can access and manipulate collections of data more efficiently than using individual variables.

There are several ways to create an array in Java. In this section, we will cover some of the most common approaches to array declaration and initialization in Java.

How to Declare and Initialize and Array in Java in a Single Statement

Array declaration and initialization in a single statement is a concise and convenient way to create an array in Java. This approach allows you to declare and initialize an array using a single line of code.

To create an array in a single statement, you first declare the type of the array, followed by the name of the array, and then the values of the array enclosed in curly braces, separated by commas.

Here's an example:

In this example, we declare an array of integers named numbers and initialize it with the values 1, 2, 3, 4, and 5. The type of the array is int[] , indicating that it is an array of integers.

You can also create an array of a different data type, such as a string array. Here's an example:

In this example, we declare an array of strings named names and initialize it with the values "John", "Mary", "David", and "Sarah".

When using this approach, you don't need to specify the size of the array explicitly, as it is inferred.

How to Declare and Initialize an Array in Java in Separate Statements

Array declaration and initialization in separate statements is another way to create an array in Java. This approach involves declaring an array variable and then initializing it with values in a separate statement.

To create an array using this approach, you first declare the array variable using the syntax datatype[] arrayName , where datatype is the type of data the array will hold, and arrayName is the name of the array.

In this example, we declare an array of integers named numbers , but we haven't initialized it with any values yet.

To initialize the array with values, we use the new keyword followed by the type of data the array will hold, enclosed in square brackets, and the number of elements the array will contain. Here's an example:

In this example, we initialize the numbers array with the values 1, 2, 3, 4, and 5. Note that we use the syntax {value1, value2, ..., valueN} to specify the values of the array.

You can also initialize the array with values in separate statements, like this:

In this example, we declare a string array named names and initialize it with the values "John", "Mary", "David", and "Sarah" in a separate statement.

Using this approach, you can also initialize the array with default values by omitting the values in the initialization statement. For example:

In this example, we declare a boolean array named flags and initialize it with 5 elements. Since we haven't specified any values, each element is initialized with the default value of false .

How to Declare an Array in Java with Default Values

Array declaration with default values is a way to create an array in Java and initialize it with default values of the specified data type. This approach is useful when you need to create an array with a fixed size, but you don't have specific values to initialize it with.

To create an array with default values, you first declare the array variable using the syntax datatype[] arrayName = new datatype[length] , where datatype is the type of data the array will hold, arrayName is the name of the array, and length is the number of elements the array will contain. Here's an example:

In this example, we declare an array of integers named numbers with a length of 5. Since we haven't specified any values, each element in the array is initialized with the default value of 0.

You can also create an array of a different data type and initialize it with default values. For example:

In this example, we declare an array of booleans named flags with a length of 3. Since we haven't specified any values, each element in the array is initialized with the default value of false .

When using this approach, it's important to note that the default values of an array depend on its data type. For example, the default value of an integer is 0, while the default value of a boolean is false . If the array holds objects, the default value is null .

Array declaration with default values is useful when you need to create an array with a fixed size, but you don't yet have specific values to initialize it with. You can later assign values to the elements of the array using indexing.

Multi-Dimensional Arrays in Java

A multi-dimensional array is an array that contains other arrays. In Java, you can create multi-dimensional arrays with two or more dimensions. A two-dimensional array is an array of arrays, while a three-dimensional array is an array of arrays of arrays, and so on.

To create a two-dimensional array in Java, you first declare the array variable using the syntax datatype[][] arrayName , where datatype is the type of data the array will hold, and arrayName is the name of the array. Here's an example:

In this example, we declare a two-dimensional array of integers named matrix , but we haven't initialized it with any values yet.

To initialize the array with values, we use the new keyword followed by the type of data the array will hold, enclosed in square brackets, and the number of rows and columns the array will contain. Here's an example:

In this example, we initialize the matrix array with 3 rows and 4 columns. Note that we use the syntax new datatype[rows][columns] to specify the dimensions of the array.

Here's another example of declaring a two-dimensional array of integers:

You can also create a multi-dimensional array with default values by omitting the values in the initialization statement. For example:

In this example, we declare a two-dimensional array of booleans named flags with 2 rows and 3 columns. Since we haven't specified any values, each element in the array is initialized with the default value of false .

Multi-dimensional arrays are useful when you need to store data in a table or grid-like structure, such as a chess board or a spreadsheet.

Creating arrays is a fundamental skill in Java programming. In this article, we covered four different approaches to array declaration and initialization in Java, including single-statement declaration and initialization, separate declaration and initialization, default values, and multi-dimensional arrays.

Understanding these different techniques will help you write more effective Java code and work more effectively with Java arrays.

Let's connect on Twitter and on LinkedIn . You can also subscribe to my YouTube channel.

Happy Coding!

Learn to code. Build projects. Earn certifications—All for free.

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

Initializing Arrays in Java

Last updated: June 26, 2024

java assignment of array

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Download the E-book

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page .

You can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.

To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).

These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:

Improve Java application performance with CRaC support

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.

Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.

Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.

The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:

>> Become an efficient full-stack developer with Jmix

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

Download the E-book

Do JSON right with Jackson

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Get started with Spring and Spring Boot, through the Learn Spring course:

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

1. Overview

An array is a data structure that allows us to store and manipulate a collection of elements of the same data type. Arrays have a fixed size, determined during initialization, which cannot be altered during runtime .

In this tutorial, we’ll see how to declare an array. Also, we will examine the different ways we can initialize an array and the subtle differences between them.

Further reading:

Arrays in java: a reference guide, array operations in java, java list initialization in one line, 2. understanding arrays.

In Java, arrays are objects that can store multiple elements of the same data type. We can access all elements in an array through their indices, which are numerical positions starting from zero. Also, the length of an array represents the total number of elements it can hold:

Represenation of array element and indices

In the image above, we have a one-dimensional array of eight items.

Notably, if we try to access an element outside the valid index range of the array, it throws ArrayIndexOutOfBoundsException .

3. Declaring and Initializing One-Dimensional Arrays

We can easily declare an array by specifying its data type followed by square brackets and the array name :

In the code above, we declare an uninitialized array of int type.

Alternatively, we can place the square brackets after the array name, but this approach is less common :

Furthermore, we must initialize an array to use it . Initialization involves allocating memory using the new keyword and specifying the array length:

In the code above, we initialize a numbers array to hold seven elements of int type.

After initialization, we can assign values to individual elements using their indices:

Here, we add 10  and 20  to indices 0 and 1 , respectively.

Furthermore, we can retrieve an element value by using its index:

In the code above, we assert that the element in index one is 20 .

It’s possible to declare and initialize an array in a single step :

Notably, the length of an array is always fixed and cannot be extended after initialization.

Alternatively, we can specify the length of an array using a variable:

Here, we declare a variable used as the length of the array. Importantly, length  can only be of type int .  Any other type apart from int  throws an incompatible type error.

4. Declare Array of Unknown Size

When we declare an array, knowing the size is unnecessary. We can either assign an array to null or an empty array :

But we need to know the size when we initialize it because the Java virtual machine must reserve the contiguous memory block for it. As we discussed earlier, we can initialize an array with the new keyword:

If we want to resize the array, we can do it by creating an array of larger size and copying the previous array elements to the new array:

If we’re allowed to use ArrayList , then for dynamic resizing we should always use ArrayList :

ArrayList internally uses an array and System.arrayCopy()  to support dynamic resizing.

5. Default Values for Array Elements

Upon initialization, the elements of an array are automatically assigned default values based on the data type of the array . These values represent the array elements’ initial state before we explicitly assign any values.

Arrays of int , short , long , float , and double data types set all elements to zero by default:

Furthermore, for boolean arrays, the default value for all elements is false :

Finally, for arrays of object types, such as String , the default value for all elements is set to null :

Notably, when we use or access an element of an array without explicitly assigning a value, we are automatically using or accessing the default value.

6. Initializing Arrays With Values

Also, we can assign values to an array during initialization. This is often called array literals :

In the code above, we initialize a string array with five brand names. The total number of elements within the curly braces determines the length/size of the array.

Furthermore, we can omit the array type for primitive data types:

Additionally, when using the var keyword for type inference, we cannot initialize an array literal without the new keyword :

The code above results in a compilation error.

To use the var keyword with array literals, we must introduce the new keyword, allowing the compiler to infer the type from the right-hand side of the assignment:

Here, the compiler can infer it’s an array of integers.

7. Adding Values to Arrays Using Arrays.fill()

The java.util.Arrays class has several methods named fill() that accept different types of arguments and fill the whole array with the same value:

This method can be useful when we need to update multiple elements of an array with the same value.

The method also has several alternatives that set a given range of an array to a particular value:

Here, the fill()  method accepts the initialized array, the index to start the filling, the index to end the filling (exclusive), and the value itself respectively as arguments. The first three elements of the array are set to -50 and the remaining elements retain their default value which is zero.

Notably, if the range between the start and the end index is greater than the size of the array, it throws ArrayIndexOutOfBoundsException .

8. Copying Arrays Using Arrays.copyOf()

The method Arrays.copyOf() creates a new array by copying elements from an existing array. The method has many overloads, which accept different types of arguments.

Let’s see a quick example:

There are a few things to note in this example:

  • The method accepts two arguments –  the source array and the desired length of the new array to be created.
  • If the length is greater than the length of the array to be copied, then the extra elements will be initialized using their type’s default value.
  • If the source array hasn’t been initialized, then a NullPointerException is thrown.

9. Adding Values to Arrays Using Arrays.setAll()

The method Arrays.setAll() sets all elements of an array using a generator function . This method can be useful when we need to add values that follow a specific pattern or logic to an array.

Let’s see an example using the Arrays.setAll() method:

In the code above, we create an array of int data types and use the setAll()  method to populate it with even numbers.

Here’s another example that demonstrates a more complex generator function:

Here, the generator function sets the first ten elements of the array to their respective indices and sets the remaining elements to zero.

If the generator function is null, then a NullPointerException is thrown.

10. Cloning an Array Using ArrayUtils.clone()

Let’s utilize the ArrayUtils.clone() API from Apache Commons Lang 3 , which initializes an array by creating a direct copy of another array:

Note that this method is overloaded for all primitive types .

11. Declaring and Initializing Two-Dimensional Arrays

Moreover, let’s see how to declare a two-dimensional array:

In the code above, we declare a two-dimensional array of int data type by specifying two sets of square brackets. Let’s initialize the array and specify the number of rows and columns:

We can think of this as an array with two rows and five columns.

Let’s assign value to the individual elements using nested indices, where the first index represents the row and the second index represents the column :

We can retrieve the value in a two-dimensional array by specifying its row and column indices:

In the code above, we retrieve the value of an array at row 0 and column 1 .

Alternatively, we can initialize a two-dimensional array using a less frequently used syntax:

Also, we can initialize a two-dimensional array with literals using nested curly brackets:

In the code above, we initialized a two-dimensional array of int type containing two one-dimensional arrays, which represent the two rows of our array.

12. Adding Values to an Array Using a for Loop

We can assign values to each element of an array individually using a loop. This approach can be useful when we need to populate an array based on specific conditions or calculations.

Let’s look at an example that uses a loop-based approach:

In the example above, we use a loop to assign values to each element. In this case, we assign the value i + 2 to the element at index i .

For multi-dimensional arrays, we can use nested loops to iterate over each dimension and assign values to the elements:

Here, we use nested for loops to iterate over the rows and columns, respectively. We assign each element the value i * 4 + j , which is calculated based on the row and column indices.

13. Initializing an Array Using the Stream API

The Stream API provides convenient methods for creating arrays from streams of elements, including methods such as Arrays.stream() , IntStream.of() , DoubleStream.of() , and many others. These methods allow us to initialize arrays with specified values.

Let’s see an example that uses the Instream.of()  method to initialize and populate an array:

Here, we create an IntStream with five values and use the toArray() method to convert it to an array of integers.

Moreover, we can initialize a higher-dimensional array using the Stream API. Let’s use this approach to initialize a two-dimensional array :

First, we generate a stream of integers using IntStream.range(0, 3), corresponding to the indices of the rows in the matrix . Next, we use the mapToObj()  method to convert each integer in the original stream into an array of integers. Then, we generate another stream of integers corresponding to the indices of the columns in each row of our matrix .

Finally, we convert the stream of integer arrays into a two-dimensional array using the toArray(int[][]::new) method, which is a method reference that creates a new two-dimensional array.

14. Higher-Dimensional Arrays

Furthermore, we can have arrays of more than two dimensions. Depending on the specific use case, we can have a three-dimensional array, a four-dimensional array, and so on. The number of square brackets determines the dimensions.

Let’s see how to declare and initialize a three-dimensional array:

In the code above, we have three square brackets to indicate this is a three-dimensional array. The first square bracket [3]  represents the depth of the array . It indicates the number of two-dimensional arrays that the three-dimensional array contains. In this case, we have three two-dimensional arrays in the three-dimensional array.

Let’s add an element to the first 2D array:

Here, the first index [0] indicates the first 2D array within the 3D array, the second index [0] represents the first row of the first 2D array, and the third index [1] represents the second column in the first column of the first 2D array.

Additionally, let’s add an element to the second 2D array:

First, we indicate the second 2D array via its index [1] . Then, we add an element to the first column of the first row of that 2D array.

Simply put, a three-dimensional array is an array of two-dimensional arrays .

Finally, a four-dimensional array is essentially an array of three-dimensional arrays.

15. Conclusion

In this article, we explored different ways of initializing arrays in Java. We also learned how to declare and allocate memory to arrays of any type, including one-dimensional and multi-dimensional arrays.

Additionally, we saw different ways to populate arrays with values, including assigning values individually using indices, and initializing arrays with values at the time of declaration.

As always, the full version of the code is available over on GitHub .

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

RWS Course Banner

  • ▼Java Exercises
  • ▼Java Basics
  • Basic Part-I
  • Basic Part-II
  • ▼Java Data Types
  • Java Enum Types
  • ▼Java Control Flow
  • Conditional Statement
  • Recursive Methods
  • ▼Java Math and Numbers
  • ▼Object Oriented Programming
  • Java Constructor
  • Java Static Members
  • Java Nested Classes
  • Java Inheritance
  • Java Abstract Classes
  • Java Interface
  • Java Encapsulation
  • Java Polymorphism
  • Object-Oriented Programming
  • ▼Exception Handling
  • Exception Handling Home
  • ▼Functional Programming
  • Java Lambda expression
  • ▼Multithreading
  • Java Thread
  • Java Multithreading
  • ▼Data Structures
  • ▼Strings and I/O
  • File Input-Output
  • ▼Date and Time
  • ▼Advanced Concepts
  • Java Generic Method
  • ▼Algorithms
  • ▼Regular Expressions
  • Regular Expression Home
  • ▼JavaFx Exercises
  • JavaFx Exercises Home
  • ..More to come..

Java Array: Exercises, Practice, Solution

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.

3. Write a Java program to print the following grid.

Expected Output :

4. Write a Java program to calculate the average value of array elements.

5. Write a Java program to test if an array contains a specific value.

6. Write a Java program to find the index of an array element.

7. Write a Java program to remove a specific element from an array.

8. Write a Java program to copy an array by iterating the array.

9. Write a Java program to insert an element (specific position) into an array.

10. Write a Java program to find the maximum and minimum value of an array.

11. Write a Java program to reverse an array of integer values.

12. Write a Java program to find duplicate values in an array of integer values.

13. Write a Java program to find duplicate values in an array of string values.

14. Write a Java program to find common elements between two arrays (string values).

15. Write a Java program to find common elements between two integer arrays.

16. Write a Java program to remove duplicate elements from an array.

17. Write a Java program to find the second largest element in an array.

18. Write a Java program to find the second smallest element in an array.

19. Write a Java program to add two matrices of the same size.

20. Write a Java program to convert an array to an ArrayList.

21. Write a Java program to convert an ArrayList to an array.

22. Write a Java program to find all pairs of elements in an array whose sum is equal to a specified number.

23. Write a Java program to test two arrays' equality.

24. Write a Java program to find a missing number in an array.

25. Write a Java program to find common elements in three sorted (in non-decreasing order) arrays.

26. Write a Java program to move all 0's to the end of an array. Maintain the relative order of the other (non-zero) array elements.

27. Write a Java program to find the number of even and odd integers in a given array of integers.

28. Write a Java program to get the difference between the largest and smallest values in an array of integers. The array must have a length of at least 1.

29. Write a Java program to compute the average value of an array of integers except the largest and smallest values.

30. Write a Java program to check if an array of integers is without 0 and -1.

31. Write a Java program to check if the sum of all the 10's in the array is exactly 30. Return false if the condition does not satisfy, otherwise true.

32. Write a Java program to check if an array of integers contains two specified elements 65 and 77.

33. Write a Java program to remove duplicate elements from a given array and return the updated array length. Sample array: [20, 20, 30, 40, 50, 50, 50] After removing the duplicate elements the program should return 4 as the new length of the array. 

34. Write a Java program to find the length of the longest consecutive elements sequence from an unsorted array of integers. Sample array: [49, 1, 3, 200, 2, 4, 70, 5] The longest consecutive elements sequence is [1, 2, 3, 4, 5], therefore the program will return its length 5. 

35. Write a Java program to find the sum of the two elements of a given array equal to a given integer. Sample array: [1,2,4,5,6] Target value: 6. 

36. Write a Java program to find all the distinct triplets such that the sum of all the three elements [x, y, z (x ≤ y ≤ z)] equal to a specified number. Sample array: [1, -2, 0, 5, -1, -4] Target value: 2. 

37. Write a Java program to create an array of its anti-diagonals from a given square matrix. 

Example: Input : 1 2 3 4 Output: [ [1], [2, 3], [4] ]

38. Write a Java program to get the majority element from an array of integers containing duplicates.  

Majority element: A majority element is an element that appears more than n/2 times where n is the array size.

39. Write a Java program to print all the LEADERS in the array.   Note: An element is leader if it is greater than all the elements to its right side.

40. Write a Java program to find the two elements in a given array of positive and negative numbers such that their sum is close to zero.  

41. Write a Java program to find the smallest and second smallest elements of a given array.  

42. Write a Java program to separate 0s and 1s in an array of 0s and 1s into left and right sides.  

43. Write a Java program to find all combinations of four elements of an array whose sum is equal to a given value.  

44. Write a Java program to count the number of possible triangles from a given unsorted array of positive integers.   Note: The triangle inequality states that the sum of the lengths of any two sides of a triangle must be greater than or equal to the length of the third side.

45. Write a Java program to cyclically rotate a given array clockwise by one.  

46. Write a Java program to check whether there is a pair with a specified sum in a given sorted and rotated array.  

47. Write a Java program to find the rotation count in a given rotated sorted array of integers.  

48. Write a Java program to arrange the elements of an array of integers so that all negative integers appear before all positive integers.  

49. Write a Java program to arrange the elements of an array of integers so that all positive integers appear before all negative integers.  

50. Write a Java program to sort an array of positive integers from an array. In the sorted array the value of the first element should be maximum, the second value should be a minimum, third should be the second maximum, the fourth should be the second minimum and so on.  

51. Write a Java program that separates 0s on the left hand side and 1s on the right hand side from a random array of 0s and 1.  

52. Write a Java program to separate even and odd numbers from a given array of integers. Put all even numbers first, and then odd numbers.  

53. Write a Java program to replace every element with the next greatest element (from the right side) in a given array of integers. There is no element next to the last element, therefore replace it with -1. 

54. Write a Java program to check if a given array contains a subarray with 0 sum.  

Example: Input : nums1= { 1, 2, -2, 3, 4, 5, 6 } nums2 = { 1, 2, 3, 4, 5, 6 } nums3 = { 1, 2, -3, 4, 5, 6 } Output: Does the said array contain a subarray with 0 sum: true Does the said array contain a subarray with 0 sum: false Does the said array contain a subarray with 0 sum: true

55. Write a Java program to print all sub-arrays with 0 sum present in a given array of integers.  

Example: Input : nums1 = { 1, 3, -7, 3, 2, 3, 1, -3, -2, -2 } nums2 = { 1, 2, -3, 4, 5, 6 } nums3= { 1, 2, -2, 3, 4, 5, 6 } Output: Sub-arrays with 0 sum : [1, 3, -7, 3] Sub-arrays with 0 sum : [3, -7, 3, 2, 3, 1, -3, -2] Sub-arrays with 0 sum : [1, 2, -3] Sub-arrays with 0 sum : [2, -2]

56. Write a Java program to sort a binary array in linear time.   From Wikipedia, Linear time: An algorithm is said to take linear time, or O(n) time, if its time complexity is O(n). Informally, this means that the running time increases at most linearly with the size of the input. More precisely, this means that there is a constant c such that the running time is at most cn for every input of size n. For example, a procedure that adds up all elements of a list requires time proportional to the length of the list, if the adding time is constant, or, at least, bounded by a constant. Linear time is the best possible time complexity in situations where the algorithm has to sequentially read its entire input. Therefore, much research has been invested into discovering algorithms exhibiting linear time or, at least, nearly linear time. This research includes both software and hardware methods. There are several hardware technologies which exploit parallelism to provide this. An example is content-addressable memory. This concept of linear time is used in string matching algorithms such as the Boyer–Moore algorithm and Ukkonen's algorithm.

Example: Input : b_nums[] = { 0, 1, 1, 0, 1, 1, 0, 1, 0, 0 } Output: After sorting: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]

57. Write a Java program to check if a sub-array is formed by consecutive integers from a given array of integers.  

Example: Input : nums = { 2, 5, 0, 2, 1, 4, 3, 6, 1, 0 } Output: The largest sub-array is [1, 7] Elements of the sub-array: 5 0 2 1 4 3 6

58. Given two sorted arrays A and B of size p and q, write a Java program to merge elements of A with B by maintaining the sorted order i.e. fill A with first p smallest elements and fill B with remaining elements.  

Example: Input : int[] A = { 1, 5, 6, 7, 8, 10 } int[] B = { 2, 4, 9 } Output: Sorted Arrays: A: [1, 2, 4, 5, 6, 7] B: [8, 9, 10]

59. Write a Java program to find the maximum product of two integers in a given array of integers.  

Example: Input : nums = { 2, 3, 5, 7, -7, 5, 8, -5 } Output: Pair is (7, 8), Maximum Product: 56

60. Write a Java program to shuffle a given array of integers.  

Example: Input : nums = { 1, 2, 3, 4, 5, 6 } Output: Shuffle Array: [4, 2, 6, 5, 1, 3]

61. Write a Java program to rearrange a given array of unique elements such that every second element of the array is greater than its left and right elements.  

Example: Input : nums= { 1, 2, 4, 9, 5, 3, 8, 7, 10, 12, 14 } Output: Array with every second element is greater than its left and right elements: [1, 4, 2, 9, 3, 8, 5, 10, 7, 14, 12]

62. Write a Java program to find equilibrium indices in a given array of integers.  

Example: Input : nums = {-7, 1, 5, 2, -4, 3, 0} Output: Equilibrium indices found at : 3 Equilibrium indices found at : 6

63. Write a Java program to replace each element of the array with the product of every other element in a given array of integers.  

Example: Input : nums1 = { 1, 2, 3, 4, 5, 6, 7} nums2 = {0, 1, 2, 3, 4, 5, 6, 7} Output: Array with product of every other element: [5040, 2520, 1680, 1260, 1008, 840, 720] Array with product of every other element: [5040, 0, 0, 0, 0, 0, 0, 0]

64. Write a Java program to find the Longest Bitonic Subarray in a given array.  

A bitonic subarray is a subarray of a given array where elements are first sorted in increasing order, then in decreasing order. A strictly increasing or strictly decreasing subarray is also accepted as bitonic subarray.

Example: Input : nums = { 4, 5, 9, 5, 6, 10, 11, 9, 6, 4, 5 } Output: The longest bitonic subarray is [3,9] Elements of the said sub-array: 5 6 10 11 9 6 4 The length of longest bitonic subarray is 7

65. Write a Java program to find the maximum difference between two elements in a given array of integers such that the smaller element appears before the larger element.  

Example: Input : nums = { 2, 3, 1, 7, 9, 5, 11, 3, 5 } Output: The maximum difference between two elements of the said array elements 10

66. Write a Java program to find a contiguous subarray within a given array of integers with the largest sum.  

In computer science, the maximum sum subarray problem is the task of finding a contiguous subarray with the largest sum, within a given one-dimensional array A[1...n] of numbers. Formally, the task is to find indices and with, such that the sum is as large as possible.

Example: Input : int[] A = {1, 2, -3, -4, 0, 6, 7, 8, 9} Output: The largest sum of contiguous sub-array: 30

67. Write a Java program to find the subarray with the largest sum in a given circular array of integers.  

Example: Input : nums1 = { 2, 1, -5, 4, -3, 1, -3, 4, -1 } nums2 = { 1, -2, 3, 0, 7, 8, 1, 2, -3 } Output: The sum of subarray with the largest sum is 6 The sum of subarray with the largest sum is 21

68. Write a Java program to create all possible permutations of a given array of distinct integers.  

Example: Input : nums1 = {1, 2, 3, 4} nums2 = {1, 2, 3} Output: Possible permutations of the said array: [1, 2, 3, 4] [1, 2, 4, 3] .... [4, 1, 3, 2] [4, 1, 2, 3] Possible permutations of the said array: [1, 2, 3] [1, 3, 2] ... [3, 2, 1] [3, 1, 2]

69. Write a Java program to find the minimum subarray sum of specified size in a given array of integers.  

Example: Input : nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10} Output: Sub-array size: 4 Sub-array from 0 to 3 and sum is: 10

70. Write a Java program to find the smallest length of a contiguous subarray of which the sum is greater than or equal to a specified value. Return 0 instead.  

Example: Input : nums = {1, 2, 3, 4, 6} Output: Minimum length of a contiguous subarray of which the sum is 8, 2

71. Write a Java program to find the largest number from a given list of non-negative integers.  

Example: Input : nums = {1, 2, 3, 0, 4, 6} Output: Largest number using the said array numbers: 643210

72. Write a Java program to find and print one continuous subarray (from a given array of integers) that if you only sort the said subarray in ascending order then the entire array will be sorted in ascending order.  

Example: Input : nums1 = {1, 2, 3, 0, 4, 6} nums2 = { 1, 3, 2, 7, 5, 6, 4, 8} Output: Continuous subarray: 1 2 3 0 Continuous subarray: 3 2 7 5 6 4

73. Write a Java program to sort a given array of distinct integers where all its numbers are sorted except two numbers.  

Example: Input : nums1 = { 3, 5, 6, 9, 8, 7 } nums2 = { 5, 0, 1, 2, 3, 4, -2 } Output: After sorting new array becomes: [3, 5, 6, 7, 8, 9] After sorting new array becomes: [-2, 0, 1, 2, 3, 4, 5]

74. Write a Java program to find all triplets equal to a given sum in an unsorted array of integers.  

Example: Input : nums = { 1, 6, 3, 0, 8, 4, 1, 7 } Output: Triplets of sum 7 (0 1 6) (0 3 4)

75. Write a Java program to calculate the largest gap between sorted elements of an array of integers.  

Example: Original array: [23, -2, 45, 38, 12, 4, 6] Largest gap between sorted elements of the said array: 15

76. Write a Java program to determine whether numbers in an array can be rearranged so that each number appears exactly once in a consecutive list of numbers. Return true otherwise false.  

Example: Original array: [1, 2, 5, 0, 4, 3, 6] Check consecutive numbers in the said array!true

77. Write a Java program that checks whether an array of integers alternates between positive and negative values.  

Example: Original array: [1, -2, 5, -4, 3, -6] Check the said array of integers alternates between positive and negative values!true

78. Write a Java program that checks whether an array is negative dominant or not. If the array is negative dominant return true otherwise false.  

Example: Original array of numbers: [1, -2, -5, -4, 3, -6] Check Negative Dominance in the said array!true

79. Write a Java program that returns the missing letter from an array of increasing letters (upper or lower). Assume there will always be one omission from the array.  

Example: Original array of elements: [p, r, s, t] Missing letter in the said array: q

Java Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Java Tutorial

Java methods, java classes, java file handling, java how to's, java reference, java examples, java arraylist.

The ArrayList class is a resizable array , which can be found in the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:

Create an ArrayList object called cars that will store strings:

If you don't know what a package is, read our Java Packages Tutorial .

The ArrayList class has many useful methods. For example, to add elements to the list, use the add() method:

Try it Yourself »

You can also add an item at a specified position by referring to the index number:

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

Access an Item

To access an element in the ArrayList , use the get() method and refer to the index number:

Advertisement

Change an Item

To modify an element, use the set() method and refer to the index number:

Remove an Item

To remove an element, use the remove() method and refer to the index number:

To remove all the elements in the ArrayList , use the clear() method:

ArrayList Size

To find out how many elements an ArrayList have, use the size method:

Loop Through an ArrayList

Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run:

You can also loop through an ArrayList with the for-each loop:

Other Types

Elements in an ArrayList are actually objects. In the examples above, we created elements (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class : Integer . For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

Create an ArrayList to store numbers (add elements of type Integer ):

Sort an ArrayList

Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically:

Sort an ArrayList of Strings:

Sort an ArrayList of Integers:

Complete ArrayList Reference

For a complete reference of ArrayList methods, go to our Java ArrayList Reference .

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.

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

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

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: 

java assignment of array

  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:  

author

Please Login to comment...

Similar reads.

  • Best Twitch Extensions for 2024: Top Tools for Viewers and Streamers
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • Full Stack Developer Roadmap [2024 Updated]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Assigning values of an array in a for loop java

Im still starting out in java - and any guidance would be great on this. I'm basically hoping to create an array, then assign values to that array in a for loop. The code I have at the moment is:

All i wanna do is make an array with each entry the number of the iteration (using this method) I know its really simple, but I feel as if I have missed something important during learning the basics! Thanks!

Michael M's user avatar

  • What's wrong with your current code? It looks fine to me. –  Antimony Commented Jul 15, 2012 at 20:01

5 Answers 5

Everything is fine except the stop condition:

Since your array is of size 50, and indices start at 0, the last index is 49.

You should reduce the scope of i , avoid hard-coding the length everywhere (don't repeat yourself principle), and respect the camelCase naming conventions:

JB Nizet's user avatar

  • Read the error messages and try to understand what they mean, instead of just treating them as an error flag. The error message probably said: ArrayOutOfBoudsException, and probably told you the index you tried to access, but was out of bounds. –  JB Nizet Commented Jul 15, 2012 at 20:07

Your array has 50 elements, and your loop goes over 51 elements (0 to 50).

Just change the code to:

lhlmgr's user avatar

  • Also, you can move the declaration of i into the for loop, rather than outside of the loop. –  Kevin Welker Commented Jul 15, 2012 at 20:03

Use length of the array instead of hard-coding 50.

kjp's user avatar

Program to input elements in an array in java using for loop

David Buck's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

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

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Filtering polygons by name in one column of QGIS Attribute Table
  • How to make my latex code to be continuously showing my big table in the next pages
  • Is there a way to prove ownership of church land?
  • Humans are forbidden from using complex computers. But what defines a complex computer?
  • What prevents random software installation popups from mis-interpreting our consents
  • Why does the guardian who admits guilt pay more than when his guilt is established by witnesses?
  • Topos notions coming from topology and uniqueness of generalizations
  • Where is this railroad track as seen in Rocky II during the training montage?
  • Best approach to make lasagna fill pan
  • Could they free up a docking port on ISS by undocking the emergency vehicle and letting it float next to the station for a little while
  • Fundamental Question on Noise Figure
  • Is my magic enough to keep a person without skin alive for a month?
  • What is the missing fifth of the missing fifths?
  • Can population variance from multiple studies be averaged to use for a sample size calculation?
  • How does registration work in a modern accordion?
  • What are the most common types of FOD (Foreign Object Debris)?
  • What was the typical amount of disk storage for a mainframe installation in the 1980s?
  • Nothing to do with books but everything to do with "BANGS"!
  • Direction of centripetal acceleration
  • Do US universities invite faculty applicants from outside the US for an interview?
  • Can you move between an attack and the attack granted by Horde Breaker?
  • Applying to faculty jobs in universities without a research group in your area
  • Somebody used recommendation by an in-law without disclosure – should I report it?
  • Are others allowed to use my copyrighted figures in theses, without asking?

java assignment of array

IMAGES

  1. An Introduction to Java Arrays

    java assignment of array

  2. What are Arrays in Java?

    java assignment of array

  3. The Arrays Class in Java (Part 1)

    java assignment of array

  4. Array Copy in Java

    java assignment of array

  5. Array in Java

    java assignment of array

  6. How to Sort an Array in Java Without Using the sort() Method

    java assignment of array

VIDEO

  1. Chapter 7 Arrays and Arraylist Part 1

  2. Java Practice Assignment 5

  3. Rearrange Array Elements by Sign Solved in java

  4. NPTEL Programming in Java Week-1 Assignment Solution #nptelcourseanswers

  5. Selenium 10

  6. Java Arrays Explained: Understanding Arrays in Java Programming

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

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

  3. Arrays in Java

    Arrays in Java

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

  5. Java Array (With Examples)

    Java Array (With Examples)

  6. Java Arrays

    Java Arrays - W3Schools ... Java Arrays

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

    Arrays - Learning the Java Language

  8. Java Assignment Operators with Examples

    Java Assignment Operators with Examples

  9. How to Declare and Initialize an Array in Java

    How to Declare and Initialize an Array in Java

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

  11. Java Array Declaration

    Java Array Declaration - How to Initialize an Array in Java ...

  12. Java Array

    Java Array - How to Declare and Initialize an ...

  13. How to Create an Array in Java

    How to Create an Array in Java - Array Declaration Example

  14. Initializing Arrays in Java

    Initializing Arrays in Java

  15. Java Array exercises: Array Exercises

    Java Array exercises: Array Exercises

  16. How to add an element to an Array in Java?

    How to add an element to an Array in Java?

  17. Java ArrayList

    Java ArrayList - W3Schools ... Java ArrayList

  18. Multidimensional Arrays in Java

    Multidimensional Arrays in Java

  19. java

    The best way is probably to just declare and assign all values at once. As shown here. Java will automatically figure out what size the array is and assign the values to like this. int contents[][] = { {1, 2} , { 4, 5} }; Alternatively if you need to declare the array first, remember that each contents[0][0] points to a single integer value not ...

  20. Directly setting values for an ArrayList in Java

    @Uri, @Sean, @ColinD, I think you need to read the question more carefully. There is no int[] array (it's Integer[].) The problem is the braces. Using a different method to create the list will not help. Also the OP is probably a Java newbie and would not benefit from adding another large library to his project. -

  21. Assigning values of an array in a for loop java

    Having problems utilizing Arrays and for loops in a Java assignment. 0. put some values in a for loop in an array. 0. Assign values of array from for loop java. 0. How to assign values in one array to another in java. Hot Network Questions