Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Why doesn == work when comparing Strings?

comparing strings
0
Posted

Why doesn == work when comparing Strings?

0

In Java, the equality operator == is (primarily) used in comparisons between primitive data types such as integers. It is bad practice to use it to compare objects like Strings or Points because it just tests whether or not the two objects occupy the same space, i.e. it determines if your two names are just aliases for the same object. If you want to compare the contents of two distinct objects to see if they are equivalent, then you must use the equals methods provided by the class. For example, the following code will print the Yum message, String dinner = “hot dog”; if (dinner.substring(0, 3).equals(“hot”)) System.out.println(“Yum…”); but this code will not print anything: String dinner = “hot dog”; if (dinner.substring(0, 3) == “hot”) System.out.println(“Yum…”); There is an equals method defined for all of the graphical objects: Point origin = new Point(); if (origin.equals(new Point(0, 0))) System.out.println(“This message WILL be printed!”); • I think my diskette is full beca

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123