×

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives.

An array is a collection of values which are heap memory addresses.

In the case of primitive, it stores direct value, and in case of an object, it stores references to the object.

An array stores its object in a continuous fashion which results in improved access speed.

Example:

int[] ArrayNum = new int[] { 1,2,0 };
String[] ArrayObj = new String[] { "Ram", "Mohan", "Roy","INDIA" };
   

Array Initialization

int array[] // deceleration
array[] = new int [2]; //allocation
for (int i=0; i<array .length; i++) {    // initialization using loop
array[i] = i + 5;
}

Some valid array:

1.  String array[] = {"AA","BB","ss"};

2.  int[] a = new int []{1,2,3,4,5};

3.  String array2[] = new String[5];

array2[1]= "ZZ";

array2[2]= "SS";

array2[3]= "FF";

4. int intArray2[] = new int[]{0, 1};

5. String[] strArray2 = new String[]{"Summer", "Winter"};

6. int multiArray2[][] = new int[][]{ {0, 1}, {3, 4, 5}};

Another important point to note is that if we declare and initialize an array using two separate lines of code, we’ll use the keyword new to initialize the values. The following lines of code are correct:

int intArray[];
intArray = new int[]{0, 1};

But you can’t miss the keyword new and initialize your array as follows:

int intArray[];
intArray = {0, 1};

Passing Arrays to Methods

As we can pass primitive type values to methods, we can also pass arrays to methods.

For example, the following method displays the elements in an int array.

Example:

public class MyClass {
public static void main(String[] args) {
printArray(new int[]{1,2,3,4,5,6});
}
public static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
      System.out.print(array[i] + " ");
  }
}
}

Output:

1 2 3 4 5 6

printArray(new int[]{1,2,3,4,5,6}); statement invokes the printArray method to display 1,2,3,4,5,6.

Returning an Array from a Method

A method may also return an array. For example, the following method returns an array that is the reversal of another array:

Example:

public class MyClass {
public static void main(String[] args) {
int array[] = {1,2,3,4,5,6};
for(int x:reverse(array)) {
System.out.print(x+", " );
}
}
public static int[] reverse(int[] list) {
  int[] result = new int[list.length];
  for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
      result[j] = list[i];
  }
  return result;
}
}

Output:

6, 5, 4, 3, 2, 1,

Related Topics

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.