Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about strings

 
Jacqueline Brown
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am currently studying for OCA 8 certification using Sybex Oracle Certification Study Guide.


I have a question is regarding strings and == operator.


I know that two objects are not equal.... ie. String a = new String ("a") String a="a" ( a == a is false).


However, String literals are confusing me .Not sure if I am understanding how Java handles them correctly.

Specifically, this question p. 156 Chapter 3 Test:


String a ="";
a + =2;
a + ='c'
a+ = false;

Why is (a == "2cfalse") a false statement.

My understanding is that Java creates a new object and reassigns to variable when cooncating, i.e. a ="" Then a = "2" ... a="2cfalse". So there would be a literal called "2cfalse", correct?

I also tested code and it also came out as false. But why?


Would this not be an equal object if the other objects are destroyed during garbage collection? Please help me understand why this is not a true statement. I am taking exam in two weeks.

Thanks so much for your help.

 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jacqueline Brown,

First of all, a warm welcome to CodeRanch!

Jacqueline Brown wrote:String a = new String ("a") String a="a" ( a == a is false).

That's not true! This code will give you a compiler error (duplicate local variable a) But indeed, this code will print false:


Jacqueline Brown wrote:However, String literals are confusing me .Not sure if I am understanding how Java handles them correctly.

You should definitely read this excellent article about Strings. It has a great explanation about strings, string literals, string constant/literal pool and their equality (both using equals() method and == operator). I even think you'll be able to answer your own question after you have read (and fully understood) this article.
So read the article and then try to answer your own question. If you still don't have a clue or it's not 100% correct, I'll definitely answer your question and clear your doubts.

Hope it helps!
Kind regards,
Roel
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jacqueline,

Did you already find the answer to your question(s)? And do you understand why the statement is false?

Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic