Top Posts
Intranet Application Case Studies
Electronic E-commerce and the Trade Cycle
Types of JDBC drivers
C++ Program to implements Constructor Overloading
C++ Program to implements Constructor
C++ Program to calculate the area using classes
C++ Class Program to Store and Display Employee...
Operator Overloading of Decrement — Operator
Postfix Increment ++ Operator Overloading
Top 8 Programming Languages That Will Rule in...
TECHARGE
  • HOME
  • BLOGS
  • TUTORIALS
    • ALL TUTORIALS
    • PROGRAMMING TUTORIALS
      • JAVA TUTORIALS
      • C++ TUTORIAL
      • C PROGRAMMING TUTORIALS
      • PYTHON TUTORIAL
      • KNOWLEDGE MANAGEMENT TUTORIALS
      • DATA STRUCTURE AND ALGORITHM TUTORIALS
      • PROGRAMMING EXAMPLES
        • CPP EXAMPLES
        • JAVA EXAMPLES
        • C++ GRAPHICS PROGRAM
    • PROJECTS
      • PYTHON PROJECTS
      • SWIFT PROJECT
    • PPROGRAMMING QUIZ
    • DBMS TUTORIALS
    • COMPUTER NETWORK TUTORIALS
    • COMPUTER NETWORK SECURITY TUTORIALS
    • E COMMERCE TUTORIALS 
    • AWS TUTORIAL
    • INTERNET OF THINGS
    • CHEATSHEET
  • MORE
    • JOBS AND INTERNSHIPS
    • INTERVIEW PREPARATION
    • TECH BOOK
    • TECH NEWS
    • INSTAGRAM GALLERY
    • UNIVERSITY PAPERS
    • MNC TWEETS
    • THINKECO INITIATIVES
    • WEB STORIES
    • CONTACT US
  • WRITE +
  • ABOUT US
Java Tutorial

Arrays in Java

by anupmaurya November 6, 2022
written by anupmaurya 0 comment
701

Table of Contents

  • Features of Arrays
  • How to declare an array in Java?
  • How to Initialize Arrays in Java?
  • How to Access Elements of an Array in Java?
  • Types of Arrays
  • Single Dimensional Arrays
      • Example: An example of single dimensional array in Java.
      • Example: A java program to find the maximum and minimum number in the arrays.
  • The foreach loop
      • Example: A simple program to understand the foreach loop.
  • Multidimensional Arrays
      • Example: A sample program to create a multidimensional array.
  • Copying Arrays
      • Example: Simple program to copy data from one array to another.

In this article, you will learn about arrays in java, Features of Arrays, Single Dimensional Arrays, Foreach loop and Multidimensional Arrays

An array is a container object that contains the similar type of data. It can hold both primitive and object type data.
Each item in an array is called an element and each element is accessed by its numeric index.

Arrays in Java
Arrays in Java

Features of Arrays

  • Retrieve and sort the data easily.
  • Arrays are created during runtime.
  • Arrays can hold the reference variables of other objects.
  • Arrays are fixed in size.

How to declare an array in Java?

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

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

For example,

double[] data;

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,

// declare an array
double[] data;

// allocate memory
data = new Double[10];

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

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

double[] data = new double[10];

How to Initialize Arrays in Java?

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

//declare and initialize and array
int[] age = {12, 4, 5, 2, 5};

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,

// declare an array
int[] age = new int[5];

// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;

Note:

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

// access array elements
array[index]

Types of Arrays

1. Single dimensional arrays
2. Multidimensional arrays

Single Dimensional Arrays

Declaration of Single Dimensional Arrays
Give the name and type to the arrays called declaration of the array.
For example,

  • int[ ] arr or int [ ]arr or int arr[ ];
  • byte[ ] arr;
  • short[ ] arr;
  • long[ ] arr;
  • char[ ] chr;
  • String[ ] str ect.

Creating, Initializing and Accessing an Array

int arr = new int[10];    // creation of integer array of size 10

Example: An example of single dimensional array in Java.

class ArrayDemo
{
   public static void main(String args[])
   {
      int arr[] = {2, 4, 5, 7, 9, 10};
      for(int i = 0; i < arr.length; i++)
      {
         System.out.println("arr["+i+"] = "+arr[i]);
      }
   }
}

Output

arr[0] = 2
arr[1] = 4
arr[2] = 5
arr[3] = 7
arr[4] = 9
arr[5] = 10

Example: A java program to find the maximum and minimum number in the arrays.


class MaxMinDemo
{
   static void max(int arr[])
   {
      int max = arr[0];
      for( int i = 1; i < arr.length; ++i)
      {
          if(arr[i] > max)
             max = arr[i];
      }
      System.out.println("Max value is: "+max);
   }
  static void min(int arr[])
  {
     int min = arr[0];
     for( int i = 1; i < arr.length; ++i)
     {
         if(arr[i] < min)
            min = arr[i];
     }
     System.out.println("Min value is: "+min);
  }
  public static void main(String args[])
   {
     int arr[] = {10, 2, 7 , 3, 16, 21, 9};
     max(arr);
     min(arr);
   }
}

Output

Max value is: 21
Min value is: 2

The foreach loop

The foreach loop introduced in JDK 1.5 provides the traverse the complete array sequentially without using index variable.

Example: A simple program to understand the foreach loop.

class ForEachDemo
{
   public static void main(String[] args)
   {
      int[] arr = {3, 5, 7, 11, 13, 17};
       for (int element: arr)
       {
           System.out.print(element+"  ");
       }
   }
}

Output

3  5  7  11  13  17

Multidimensional Arrays

In multidimensional array data is stored in form of rows and columns.

Declaration of Multidimensional Arrays

  • int arr[ ][ ], or int[ ][ ] arr, or int [ ][ ]arr.
  • char arr[ ][ ] or char[ ][ ] arr or char [ ][ ]arr
  • double arr[ ][ ] or double[ ][ ] arr or double [ ][ ]arr.

Example: A sample program to create a multidimensional array.

class MultiDimeDemo
{
   public static void main(String args[])
    {
       int arr[] [] = {{9,8,7},{6,5,4},{3,2,1}};
       for(int i = 0; i < 3; i++)
       {
           for(int j = 0; j < 3; j++)
           {
              System.out.print(arr[i][j]+" ");
           }
           System.out.println();
        }
    }
}

Output

9 8 7
6 5 4
3 2 1

Copying Arrays

System class has a method called arraycopy(), that is used to copy data from one array to another.

Example: Simple program to copy data from one array to another.


class Demo
{
public static void main(String[] args)
  {
   char[] source = { 'a', 'T', 'e', 'c', 'h', 'a', 'r','g', 'e' };
   char[] dest = new char[8];

   System.arraycopy(source, 1, dest, 0, 8 );
   System.out.println(new String(dest));
  }
}

Output:

Techarge

Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

2d arrayarrayarray examplesarray in javacharacter arrayhow to create an array in javainitializing an arrayjavaJAVA ARRAYJava programming
Share 1 FacebookTwitterLinkedinRedditWhatsappTelegramEmail
anupmaurya

Hey there, My name is Anup Maurya. I was born with love with programming and worked with TCS. One of best global (IT) services and consulting company as System Administrator . I also love graphics designing. It's my pleasure to have you here.

previous post
Types of Transmission Technologies
next post
Operators in Java

You may also like

Types of JDBC drivers

JDBC Architecture

Introduction to JDBC

Difference Between Applet and Servlet in Java

OOPs Concepts in Java

Constructors in Java

Extending Interface

Implementing Interfaces in Java

Interface in Java

Java AWT tutorial for beginners

Java Tutorial

  • Online Java Compiler
  • Introduction to Java Programming
  • How to Check version of Java installed in System ?
  • How to set Temporary and Permanent Paths in Java
  • Features of Java Programming
  • Java Comments
  • Java Keywords
  • Java Variables
  • Data Types in Java
  • Java Flow Control Statements
  • Bitwise operators in Java
  • Understanding public static void main(string args[]) in Java
  • Strings in Java
  • Final method in Java
  • Constructors in Java
  • Exception in JAVA
  • Exception Handling in Java
  • Arguments in Java with Examples
  • Difference between abstract class and interface
  • Interface in Java
  • Implementing Interfaces in Java
  • Java Event Handling
  • Extending Interface
  • Multithreading in Java
  • Threads in Java
  • Life cycle of a thread in Java
  • Java AWT tutorial for beginners
  • Introduction to JDBC
  • JDBC Components
  • Java Database Connections | JDBC Tutorial
  • DriverManager class
  • Connection interface
  • Statement interface
  • PreparedStatement interface
  • ResultSet interface
  • Java Database Connectivity with MySQL
  • Applet in Java
  • Difference Between Applet and Servlet in Java
  • Web Terminology
  • Servlets
  • Servlet Interface
  • Life Cycle of a Servlet (Servlet Life Cycle)
  • Servlet API
  • GenericServlet
  • HttpServlet
  • Steps to Create Servlet Application using tomcat server
  • Session Tracking Using Servlet
  • Introduction to JSP
  • The JSP API
  • The Lifecycle of a JSP
  • TAGS in JSP

Words from Readers

I Just go mad with this website I love the content and the way it you present I can easily understand anything from this Thank you everyone who are made this possible!

–Paras Singh Kaphalia

Recent Posts

  • Intranet Application Case Studies

    March 21, 2023
  • Electronic E-commerce and the Trade Cycle

    March 21, 2023
  • Types of JDBC drivers

    December 28, 2022

EDUCATIONAL

  • Top 8 Programming Languages That Will Rule in 2023

  • Difference between Google Cloud Platform, AWS and Azure

  • Google Apps You Should Be Using in 2022

  • Top Sites From Where You Can Learn

  • PyScript: Python in the Browser

  • Best Fake Email Generators (Free Temporary Email Address)

  • How to Find Out Who Owns a Domain Name

  • Mobile phone brands by country of origin

  • How to start a new YouTube Channel in 2022

  • Best way to use google search you won’t believe exist

CHEATSHEET

  • Git and Github 2022 Cheat Sheet

  • ReactJs Cheatsheet

  • Linux Commands Cheat Sheet

  • C Programming language Cheatsheet

  • Scala Cheatsheet

  • MySQL Cheatsheet

  • Javascript Cheatsheet

PROJECTS

  • Print emojis using python without any module

  • Country Date and Time using Python

  • Covid-19 Tracker Application Using Python

  • Python | GUI Calendar using Tkinter

  • Shutdown Computer with Voice Using Python

  • Python GUI Calculator using Tkinter

  • Convert an Image to ASCII art using Python

  • Python YouTube Downloader with Pytube

  • Tic-Tac-Toe using Python

  • Draw Indian Flag using Python

  • Drawing Pikachu with the Python turtle library

  • Word Dictionary using Tkinter

TECH NEWS

  • 5+ Best Humanoid Robots In The World

  • Reliance Jio launches streaming platform JioGamesWatch

  • Microsoft Teams down for thousands of users

  • Carbon: Google programming language as a C++ successor

JOBS AND INTERNSHIPS

  • Accenture Off Campus Hiring Drive | Associate Job | Program Project Management | 2019-2022 Batch| Apply Now

    September 1, 2022

@2019-21 - All Right Reserved. Designed and Developed by Techarge

TECHARGE
  • HOME
  • BLOGS
  • TUTORIALS
    • ALL TUTORIALS
    • PROGRAMMING TUTORIALS
      • JAVA TUTORIALS
      • C++ TUTORIAL
      • C PROGRAMMING TUTORIALS
      • PYTHON TUTORIAL
      • KNOWLEDGE MANAGEMENT TUTORIALS
      • DATA STRUCTURE AND ALGORITHM TUTORIALS
      • PROGRAMMING EXAMPLES
        • CPP EXAMPLES
        • JAVA EXAMPLES
        • C++ GRAPHICS PROGRAM
    • PROJECTS
      • PYTHON PROJECTS
      • SWIFT PROJECT
    • PPROGRAMMING QUIZ
    • DBMS TUTORIALS
    • COMPUTER NETWORK TUTORIALS
    • COMPUTER NETWORK SECURITY TUTORIALS
    • E COMMERCE TUTORIALS 
    • AWS TUTORIAL
    • INTERNET OF THINGS
    • CHEATSHEET
  • MORE
    • JOBS AND INTERNSHIPS
    • INTERVIEW PREPARATION
    • TECH BOOK
    • TECH NEWS
    • INSTAGRAM GALLERY
    • UNIVERSITY PAPERS
    • MNC TWEETS
    • THINKECO INITIATIVES
    • WEB STORIES
    • CONTACT US
  • WRITE +
  • ABOUT US