Array index in Java | Find Array indexof an element in Java

I hope you did a study about Java Array, This tutorial is covering Advanced Array indexing. Array index in Java basic and main concept where every element has it’s own index number.

Indexing in Array is started from 0. In this tutorial, you will learn about Java Array indexing and find the Array index of an element.

Array index in Java example Find Array indexof an element in Java

Basic of Array index in Java:

Array indexing starts from 0, see this example. Print array with index number program.

A simple hack here we used, running a for loop used an array length. Then print the loop varible and value of the element. You can do it same with other Java Controle statements.

Output: 0 Index number Element is 1
1 Index number Element is 9
2 Index number Element is 0

Let’s Start Find Array indexof an element in Java

Java ArrayList has an indexOf method. Where in Java Arrays have no such method? So With programming, you can get it done.

An Upper example is just simply running a loop and printing index with the element. But what if you want to access a particular element index number in Java Array. Let’s See many methods (way to achieve) of it.

  • Linear Search
  • Stream API
  • Convert to List (ArrayList)
  • Binary search
  • Guava

Linear Search

Finding an Array Element index with Linear search algorithm complexity – O(N).

Example for Primitive Array.

Output: 1

Stream API

The stream is a new abstract layer introduced in Java 8.

Output: 2

Convert to List (ArrayList)

Why converting? Because List has method indexof, which find an index of the element.

Output: 4

Binary search

You can use a Binary Search Algorithm but can only be used in the array is sorted. Check this example to find the Array index with the implementation of Binary search.

Complexity – O(log n)

Output: 2

Guava Library

Guava is an open source library developed by Google which is based on Java.

The utility class has an indexOf() method which returns the index of the first appearance element in the array.

Output: 3

Q: How to find the index of an element in integer array in java?

Answer: It can be your Interview Question like this: “Given an array of N elements and an element K, find the index of an array element in Java”

The Upper all methods are a way to do it.

Do comment if you have a new way to do it or any doubt.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java Array index Examples are in Java 11, so it may change its different from Java 9 or 10 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.