A basic fundamental on the usage of arrays is search an element in java array. Basic code on how to search an element in java array as usual will be presented below in order to strengthen your knowledge on the usage and declaration of arrays. Our main goal is to provide a mechanism to search a value through an array of strings. Moreover on our example java code we will be presenting as well on how to declare an array, how to find how many objects does the array have, and usage of for loop in java. For reference of wide range of java array examples.
Instructions on searching through a java array
Declare an array of String with contents “one, two, three, four, five”. After which, we search for a value “two” and provide the array index in which the location string is located.
Search an element in java array example source code
package com.javatutorialhq.tutorial; /** * This java sample source code that shows * search an element in java array * Property of javatutorialhq.com * Feel free to modify for your own personal use * All Rights Reserved * Version 1.0 * 07/08/2013 */ public class ArraySearch { public static void main(String[] args) { //this is a java array sample declaration String[] arrayString = new String[] { "one","two","three","four","five"}; String searchString = "two"; //Loop until the length of the array for(int index = 0; index < arrayString.length;index++){ if(arrayString[index].equals(searchString)){ //Print the index of the string on an array System.out.println("Found on index "+index); } } } }
Running the java source code provided will give you the following results
Found on index 1