Java: Find the index of an array element
6. Find index of an element in array
Write a Java program to find the index of an array element.
Pictorial Presentation:
Sample Solution:
Java Code:
Sample Output:
Index position of 25 is: 0 Index position of 29 is: 8
Note:
'java.util.OptionalInt' is a class introduced in Java 8 as part of the 'java.util' package. It is part of the broader 'java.util.Optional' family of classes, which includes 'OptionalInt', OptionalLong, and OptionalDouble for handling optional values of primitive types. The 'OptionalInt' class is designed to represent an optional 'int' value, meaning it can either contain an 'int' value or be empty. It is useful in cases where a method might not always produce a valid result. You want to make it clear that the results may not be available.
Some key methods provided by 'OptionalInt' include:
- of(int value): Returns an 'OptionalInt' with the specified value if it is non-null; otherwise, it throws a 'NullPointerException'.
- empty(): Returns an empty 'OptionalInt'.
- isPresent(): Returns 'true' if there is a value present; otherwise, returns 'false'.
- ifPresent(IntConsumer action): If a value is present, performs the given action with the value; otherwise, does nothing.
- orElse(int other): Returns the value if present; otherwise, returns the specified other value.
By using 'OptionalInt', we can avoid using special values like -1 to represent the absence of a result. This makes our code more expressive and reducing misinterpretation.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to find the index of the last occurrence of a specific element in an array.
- Write a Java program to find the index of the maximum element in an integer array.
- Write a Java program to find the index of the first vowel in an array of characters.
- Write a Java program to return the indices of two numbers in an array that add up to a given target.
Go to:
PREV : Check if array contains a specific value.
NEXT : Remove specific element from array.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.