-1
public class ForTest{
    public static void main(String[] args)
    {
         String s;
         for(s="ha"; s!="haha"; s=s+"ha"){
            System.out.println(s);
          }
     }
}

In my opinion, this code should work which just print "ha", Because after one loop, s="ha" would become s="haha" and then it will stop the loop. However, it doesn't stop and shows infinite looping.

Could you help me to know what is the reason of it?

3 Answers3

1

I would rather use it like this:

public class ForTest{
    public static void main(String[] args)
    {
         String s;
         for(s="ha"; !s.equals("haha"); s=s+"ha"){
            System.out.println(s);
          }
     }
}
Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
0

Well, simply put ha + ha will not be == to haha. Use it like this :

    for (s = "ha"; (!s.equals("haha")); s = s + "ha") {
        System.out.println(s);
    }

== compares if 2 references point to the same object. equals() checks if 2 references point to objects with same values.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

If you have need you can do like this.

public class ForTest{
    public static void main(String[] args)
    {
         String s;
         for(s="ha"; !s.equals("haha"); s=s+"ha"){
            System.out.println(s);
          }
     }
}
praveen_programmer
  • 1,072
  • 11
  • 25