-4

My program is using the following code

String mobile="";
if(mobile!="")
System.out.println("++++++");
System.out.println("------");

But if statement always set true. how it is possible? how to correct the code to get false for if condition?

Ashish
  • 735
  • 1
  • 6
  • 15
Pinky
  • 683
  • 1
  • 9
  • 20
  • What output do you get? It looks like you might want some braces there, and possibly an `else` clause. – user2357112 Oct 28 '13 at 06:52
  • [why doesnt == work on string](http://stackoverflow.com/questions/17443201/why-doesnt-work-on-string/17443215#17443215) – Suresh Atta Oct 28 '13 at 06:56
  • In this case, with the given code, both strings are interned; however, first start with `equals`, and then ask a different question using this revised approach if problems persist. – user2864740 Oct 28 '13 at 06:56
  • You have to see [this example](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java?lq=1) – chintan Oct 28 '13 at 07:01
  • In the example you give `mobile != ""` is always false. i.e. you have provided you own example of when it is false. Most likely you have left out some important details. – Peter Lawrey Oct 28 '13 at 07:28
  • if(mobile != null && (!"".equals(mobile.trim()))){ //code here.. } this code working correclty for me. thanks for all. – Pinky Oct 28 '13 at 07:42

2 Answers2

0

try this way

if(!(mobile.equals("")))

there are difference between == and .equals() As whoAmI has suggested its better to

if(!("".equals(mobile)))

because it can handle mobile as null

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

you can't use "!=" on strings. This only compares the references of the strings. If you want to compare the content of the strings you need to use equals

if(!("".equals(mobile)))
Markus
  • 1,649
  • 1
  • 22
  • 41
  • There are no pointers in Java. – user2864740 Oct 28 '13 at 06:55
  • You are right my friend.But It is just half truth. Pointer is not available for user. But Java use pointer for memory allocation. You got my point? – chintan Oct 28 '13 at 06:58
  • @chintan No. I do not. The JLS does not talk about pointers. And there are are Java VMs written in languages that *do not* have pointers. Thus, Java *does not* have pointers and Java/JVM implementations *need not have* pointers. (`NullPointerException` is just poorly named legacy.) – user2864740 Oct 28 '13 at 07:02
  • @user2864740 I have read some where i don't remember. I can get this code. can you explain me how is it work? Object p1, p2; p1 = new Object; p2 = p1; p1 = null; – chintan Oct 28 '13 at 07:13