0

say I had an array (Hello,1,2,HI,1,2)

How would I check if index 1 was = to 'Hello' is a very simple question, but cannot find an answer.

This is what I have tried,it is inside a for loop, my array is of type string:

  if(array[i] == "Hello" ){
  // do something 
  }
j1234567
  • 19
  • 3
  • Reopened: this is not (necessarily) simply about comparing strings, but comparing an element of an array of objects to a string. (But will not lose sleep if re-closed). – Bathsheba Dec 15 '16 at 14:04
  • @Bathsheba : the question is not precise enough to know that it is not an array of strings. Maybe it should be edited to add details about that. – Arnaud Dec 15 '16 at 14:08
  • 1
    They just have and it rather ruins my answer. Such is life ;-( – Bathsheba Dec 15 '16 at 14:08

2 Answers2

2
if ("Hello".equals(array[i])){
    // do something
}

is, in many ways, the best way.

This will work

  1. If array[i] is null.

  2. If array[i] is a type other than a java.lang.String

I appreciate that you're a beginner and these yoda expressions are not to everyone's taste, but I couldn't resist.

(Note that a single = is an assignment rather than a test for equality, and == compares references rather than contents for non-primitive types in Java.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Should specify that `i` is just the index, and in his/her case: "check if index 1 was = to 'Hello'", `i` would be just 0 or 1 depending on their understanding of index – Honinbo Shusaku Dec 15 '16 at 14:10
  • So you re-opened this question to answer what the dupe already said? – Tom Dec 15 '16 at 14:12
  • Prior to the edit the question was notably different (and I had already answered: I, along with many folk, consider it poor form to gold hammer reopen in order to answer). It ain't now though. – Bathsheba Dec 15 '16 at 14:14
  • It was an assignment, instead of a comparison, but OP said that he likes to compare the array item with the literal :P. Oh and yes, you answered, before reopening. That was a misunderstanding on my part. *"I, along with many folk, consider it poor form to gold hammer reopen in order to answer"* Good to hear (in case the question really is a dupe; if closing was wrong, then opening and answering would be fine imo). – Tom Dec 15 '16 at 14:19
0

it depends on your array type. in your case it is String, so

if(array[i].equals("Hello") {
 // do something
}
javanoob
  • 243
  • 1
  • 10