• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Interview Questions
  • Java
  • Java Programs
  • Selenium
  • Selenium Programs
  • Manual Testing
  • Test Cases
  • Difference
  • Tools
  • SQL
  • Contact Us
  • Search
SoftwareTestingo » Java » Java Tutorial » How to Declare and Initialize Array in Java

How to Declare and Initialize Array in Java

Last Updated on: May 18, 2022 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • What is a Java array?
  • Initialize Array in Java
  • Declaring a Java Array Variable
  • Declare and Initialize Array
  • Primitive Datatype Array
  • Initialize Array After Declaration
  • Object Datatype Array
  • Multidimensional Array in Java
  • Initialize Java Array With Shorthand Syntax
  • Passing Arrays to Methods
  • Returning Arrays from Methods

Declare and Initialize Array in Java: Java is an incredibly powerful programming language where everything is an object – from classes and variables to arrays. Arrays offer a unique way of working with data that can be grouped together. They’re truly invaluable tools!

This post will cover initializing an array and the various ways to do so. You will see some code examples showcasing array initialization syntax using each approach. You will also learn about the caveats of array initialization using each of the methods discussed.

Post On:Declare and Initialize Array in Java
Post Type:Java Tutorials
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:SoftwareTestingo Telegram Group

What is a Java array?

Arrays can be used to store multiple values of similar types in a single variable, which is helpful when you need to store a lot of data. Arrays are an often used object in Java and can accommodate many purposes, such as storing text strings, numbers, boolean values, and other arrays. They are a part of the Java Collection Framework.

The array object uses an index to keep track of each element inside it. The index of an element is determined by its position in the array, and arrays start counting indexes at zero. Therefore, each element’s location is one number higher than its index. So, in an array, the first element is located at index zero, the second at index one, and so on.

Java Tutorial
  • Java List
  • Java Set
  • Java ArrayList
  • SortedSet In Java
  • Java HashSet
  • Java String split() Method
  • Java String compareTo() Method

Great, now that we have reviewed the basics of arrays, let’s move on and learn how to create and Initialize an Array in Java.

Initialize Array in Java

Initializing an array in Java can be done in a few different ways, each with its own benefits and drawbacks. In this section, we’ll show some code examples for each method and give some pointers on how to avoid common initialization mistakes.

Declaring a Java Array Variable

The syntax for declaring a Java array is very simple, as you can see below. However, it’s important to remember that just because you’ve declared an array doesn’t mean it’s been initialized.

datatype[] arrayName;

There are three notable parts to the syntax mentioned above:

datatype: To declare an array, you will need to specify the datatype that the array will hold. Some examples of acceptable data types are int, char, String, and Boolean.

[] – It indicates that the variable will hold an array object.

arrayName – It is simply the name of the array.

Declare and Initialize Array

You can use the declared array in your code by initializing it. This is where the fun starts. There are a few ways to initialize the array: The first way is by using the new keyword. Let’s look at an example of declaring and initializing an array of primitive and object datatypes.

There is only a small syntax difference between the two data types. The object datatype’s keyword is written in full word format with a capital letter. Other than that, the syntax is almost exactly the same as for primitive datatype array initialization.

Here is the basic syntax for initializing an array:

dataType [] nameOfArray = new dataType [size]

Primitive Datatype Array

int[] nums = new int[5];

The code above declares a primitive array of five unspecified int values. The default value is different based on the data types used, but in this example, the array will have five default values of zero.

Note: When creating an array with the new keyword, you must specify how many elements it will have to avoid getting an error.

Initializing an array without assigning values:

package com.SoftwareTestingO.Array;
public class DefaultInitilizeArray 
{
	public static void main(String[] args)
	{
		//Initializing array
		int[] array = new int[5];
		//Printing the elements of array
		for (int i =0;i < 5;i++)
		{
			System.out.println(array[i]);
		}	
	}
}

Initializing an array and assigning values:

package com.SoftwareTestingO.Array;
public class DefaultInitilizeArray3 
{
	public static void main(String[] args)
	{
		int[] array = {11,12,13,14,15};
		//Printing the elements of array
		for (int i =0;i < 5;i++)
		{
			System.out.println(array[i]);
		}
	}
}

Note: When assigning values to an array during initialization, the size is not specified.

Initialize Array After Declaration

You can declare an array without assigning values to it, and you can assign values to it later in your code. This is very useful when declaring an array before you have its values.

/* Declare */
int[] array;

/* Initialize */
array = new int[5];

Note: When initializing an array after its declaration, the new keyword must be used, or it will result in unpredictable behavior and or an error.

Initializing an array after a declaration:

package com.SoftwareTestingO.Array;
public class DefaultInitilizeArray2 
{
	public static void main(String[] args)
	{
		//Array Declaration
		int[] array;
		//Array Initialization
		array = new int[]{1,2,3,4,5};
		//Printing the elements of array
		for (int i =0;i < 5;i++)
		{
			System.out.println(array[i]);
		}
	}
}

Note: When assigning an array to a declared variable, the new keyword must be used.

Object Datatype Array

String[] strArr = new String[4];

Declaring and initializing an array of the object data types is similar to declaring and initializing an array of a primitive data type. The only difference is that the keywords for the object data type look different from those for a primitive data type. For example, above there is a simple example of declaring and initializing an object datatype array. In this case, the array would start with four default values of the String data types, each value being null.

Multidimensional Array in Java

It is possible to create multidimensional arrays in Java. These are not actually multidimensional arrays, but rather arrays containing other arrays (known as nested arrays). For example:

int[][] multiArray= new int[2][];

You can specify the size of one of the arrays within a multidimensional array by targeting it with an index, just like you would for a standard Java array. You will need to initialize the entire array structure before using it in your code.

multiArray[1] = new int[3];
package com.SoftwareTestingO.Array;
public class MultiDArray 
{
	public static void main(String[] args) 
	{
		// declaring and initializing 2D array
		int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };

		// printing 2D array
		for (int i=0; i< 3 ; i++)
		{
			for (int j=0; j < 3 ; j++)
				System.out.print(arr[i][j] + " ");

			System.out.println();
		}
	}
}

Initialize Java Array With Shorthand Syntax

Arrays can be declared and initialized in Java using a shorthand syntax which can simplify the process. This same syntax can also be used for multidimensional arrays. The code snippet below provides an example of this shorthand array declaration and initialization syntax.

int[] nums = {1,2,3};

If you’re looking to create an array quickly and assign values at the same time, shorthand syntax is the way to go! The curly braces wrapped around the numbers indicate that they should be added as elements of the array. So, for example, if your first array consists of three numbers – one, two, and three – they would be stored at indexes zero, one, and two respectively.

When creating a multidimensional array, you don’t have to make sure that each inner array is the same size – this is called a symmetric matrix. To initialize it, you’ll need to wrap your values in curly braces and then put those insides of another set of curly braces.

To get a better understanding of this syntax, let’s take a look at the code snippet below.

int[][] multiArray= ;

Passing Arrays to Methods

We can also pass arrays to methods, just like variables. For example, the program below passes the array to method sum in order to calculate the sum of all the values in the array.

package com.SoftwareTestingO.Array;
public class SumArray 
{
	public static void main(String[] args) 
	{
		int arr[] = {3, 1, 2, 5, 4};

		// passing array to method m1
		sum(arr);
	}
	public static void sum(int[] arr)
	{
		// getting sum of array values
		int sum = 0;

		for (int i = 0; i < arr.length; i++)
			sum+=arr[i];

		System.out.println("sum of array values : " + sum);
	}
}

Returning Arrays from Methods

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

package com.SoftwareTestingO.Array;
public class ReturnArray 
{
	public static void main(String[] args) 
	{
		int arr[] = method1();

		for (int i = 0; i < arr.length; i++)
			System.out.print(arr[i]+" ");
	}
	public static int[] method1()
	{
		// returning  array
		return new int[]{1,2,3};
	}
}

Conclusion:

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!

If you have implement some other process for Initialize Array then let us know in the comment section.

    Filed Under: Java Tutorial

    Reader Interactions

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Copyright © 2022 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers