TestingDocs.com
Software Testing website
  • Automation
    • Selenium
    • JBehave Framework
  • Tutorials
    • MySQL Tutorials
    • Testlink
    • Maven
    • Git
  • IDEs
    • IntelliJ IDEA
    • Eclipse
  • Flowcharts
    • Flowgorithm
    • Raptor
  • About

Java Tutorials

Java Arrays

Overview

In this tutorial, we will learn Java Arrays. In Java, an array is a data structure that stores values of the same data type. Each element in the array can be accessed using the index.

We can use the array data structure if we know the array size upfront. Array size is fixed.

Declare an array

We can declare an array using the following syntax:

datatype[]  arrayVariable;

For example, to declare an integer array:

int[] arr; // declare an integer array

Notice that the size of the array is not part of this declaration.

Create an array

We can create an array with the new operator.

arr = new int[3];

We have created an array with 3 elements.

Initialize array elements

We can initialize the array elements with the index. In Java, the array index starts with 0.

arr[0]=10;

arr[1]=20;

arr[2]=30;

Alternatively, we can use the below syntax to create an initialize the array elements.

int[] arr = {1,2,3,4,5};

Example

//Java Tutorials - www.TestingDocs.com
public class ArrayDemo {

 public static void main(String[] args) {
 int[] arr; //declare an integer array
 arr = new int[3]; // create an array of 3 elements

 //initialize array elements
 arr[0] = 10;
 arr[1] = 20;
 arr[2] = 30;

 //Access array elements
 System.out.println("Array element =" + arr[0]);
 System.out.println("Array element =" + arr[1]);
 System.out.println("Array element =" + arr[2]);
 }
}

 

Java Arrays Example Code

Example

Now, Let’s see how to declare array with String data type.

String[] strArray = new String[6];

OR

String[] strArray = {“Java”,”Eclipse”,”IntelliJ”,”J2EE”,”JMS”,”MySQL”};

—

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Related Posts

Download Greenfoot Windows

Java Tutorials /

Download & Install Greenfoot on Windows

Java Tutorials /

Java Static Code Analysis

Java Tutorials /

Java Testing Tools

Java Tutorials /

Handle Multiple Exceptions in Java

Exceptions_In_Java

Java Tutorials /

Exceptions in Java Programs

‹ Java Program to read a character from the keyboard› Java Relational Operators

Recent Posts

  • MS Access Data Types
  • Install RAPTOR Avalonia on CentOS
  • Download RAPTOR Avalonia Edition on Windows
  • npm doctor command
  • Build & Run CLion Project
  • Create New CLion C Project on Windows
  • Configure CLion Toolchains on Windows
  • Launch CLion IDE on Windows
  • Activate CLion IDE
  • CLion IDE for C/C++ Development

Back to Top

Links

  • Contact
  • Privacy Policy
  • Cookie Policy

www.TestingDocs.com

Go to mobile version