String[] myStringArray = {"Car", "Plane", "Bike", "Train"}; String stringToLocate= "Bike"; boolean found = false; for (String element:myStringArray ) { if ( element.equals( stringToLocate)) { found = true; System.out.println( "The value is found!"); } } if (!found) { System.out.println( "The value is not found!" ); }
A small pitfall we need to be careful about is to use the equals method and not the == operator. The code will output:
The value is found!
We may refactor it to be a function, for example:
public static boolean checkIfExists(String[] myStringArray, String stringToLocate) { for (String element:myStringArray ) { if ( element.equals( stringToLocate)) { return true; } } return false; } public static void main( String[] args ) { boolean found = checkIfExists(new String[] {"Car", "Plane", "Bike", "Train"}, "Bike"); if (found) { System.out.println( "The value is found!" ); } else { System.out.println( "The value is not found!" ); } }
Another way of testing or checking if a String Array contains a specific value in Java is to convert the data structure into a list. Below is an example of converting the code above:
String[] myStringArray = {"Car", "Plane", "Bike", "Train"}; boolean found = Arrays.asList( myStringArray ).contains( "Bike" ); if (found) { System.out.println( "The value is found!" ); } else { System.out.println( "The value is not found!" ); }
And converting to a function makes it much shorter
public static boolean checkIfExists(String[] myStringArray, String stringToLocate) { return Arrays.asList( myStringArray ).contains( stringToLocate ); } public static void main( String[] args ) { boolean found = checkIfExists(new String[] {"Car", "Plane", "Bike", "Train"}, "Bike"); if (found) { System.out.println( "The value is found!" ); } else { System.out.println( "The value is not found!" ); } }