Top Posts
Reliance Jio launches streaming platform JioGamesWatch
Microsoft Teams down for thousands of users
Carbon: Google programming language as a C++ successor
JavaScript MCQs II
JavaScript MCQs I
Problem Solving Approach
Terms related to Network Security
Set in C++STL
Computer network attack (CNA)
Indexing in DBMS
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
  • HIRE US
  • BEST COURSES
Java Tutorial

Arrays in Java

by anupmaurya January 20, 2022
written by anupmaurya 0 comment

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

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.

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;
Code language: CSS (css)
  • 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;
Code language: CSS (css)

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];
Code language: JavaScript (javascript)

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];
Code language: JavaScript (javascript)

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};
Code language: JavaScript (javascript)

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;
Code language: JavaScript (javascript)

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]
Code language: PHP (php)

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]); } } }
Code language: JavaScript (javascript)

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); } }
Code language: JavaScript (javascript)

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+" "); } } }
Code language: JavaScript (javascript)

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(); } } }
Code language: JavaScript (javascript)

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)); } }
Code language: JavaScript (javascript)

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 works at 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

Java Flow Control Statements

How to create an Object in Java

Applet in Java

Java Event Handling

Difference between abstract class and interface

Arguments in Java with Examples

Bitwise operators in Java

DriverManager class

ResultSet interface

PreparedStatement interface

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[])
  • 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

  • Reliance Jio launches streaming platform JioGamesWatch

    August 6, 2022
  • Microsoft Teams down for thousands of users

    July 21, 2022
  • Carbon: Google programming language as a C++ successor

    July 19, 2022

EDUCATIONAL

  • 5+ Best Humanoid Robots In The World

  • 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

  • HTML Cheatsheet

  • C++ Programming language Cheatsheet

  • Git and Github 2022 Cheat Sheet

  • ReactJs Cheatsheet

  • Linux Commands Cheat Sheet

  • C Programming language Cheatsheet

  • Scala Cheatsheet

PROJECTS

  • Python text to Speech

  • StopWatch using Python

  • Python Rock Paper Scissors Game

  • Currency Converter in Python

  • Alarm clock GUI application with tkinter

  • Print emojis using python without any module

  • Country Date and Time using Python

  • Covid-19 Tracker Application Using Python

  • Python | GUI Calendar using Tkinter

  • Python: Shutdown Computer with Voice

  • Python GUI Calculator using Tkinter

  • Convert an Image to ASCII art using Python

TUTORIALS

  • JAVA TUTORIAL
  • COMPUTER NETWORK
  • DBMS TUTORIAL
  • E-COMMERCE TUTORIAL
  • KNOWLEDGE MANAGEMENT
  • C++ PROGRAMMING
  • COMPUTER NETWORK SECURITY
  • AMAZON WEB SERVICES

TECH NEWS

  • Reliance Jio launches streaming platform JioGamesWatch

  • Microsoft Teams down for thousands of users

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

  • 5+ Best Humanoid Robots In The World

TERMS & POLICY

  • PRIVACY POLICY
  • TERMS AND CONDITIONS

COMPILERS

  • JAVA COMPILER
  • PYTHON COMPILER
  • JS COMPILER
  • C++ COMPILER
  • C COMPILER

JOBS AND INTERNSHIPS

  • TCS off-campus hiring 2022 for software engineers- 2019, 2020, & 2021 Batches

    February 27, 2022
  • Deloitte Recruitment For Any Graduates as Learning Operations Associate Analyst

    February 18, 2022
  • HP Recruitment For Tech Support Intern Position

    February 16, 2022
  • EY Hiring- PAS Global Immigration Advanced Analyst

    February 14, 2022
  • Amazon Recruitment Drive for Virtual Customer Support Associate Position

    February 12, 2022
Join Us On Telegram

@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
  • HIRE US
  • BEST COURSES