Java - If statement not working (comparing strings)

When I grab the IP address from my open socket as someone sent me a stream, I noticed that the IP address has a slash.

I just plan on just dropping it. But first, I want to check the first character in the string - this is a forward slash:

String dataSource = data.getAddress().toString(); if(dataSource.substring(0,1) == "/"){ System.out.println("trailing forward slash, delete it "); dataSource = dataSource.substring(1); } 

This IF statement is not detected.

Does anyone see what I'm doing wrong?

+4
source share
11 answers

To compare strings, use the equals method, since it is more reliable than using the == operator (it compares the content, and == compiles the links):

Try using the equals method:

 if(dataSource.substring(0,1).equals("/")){ 
+2
source

use .equals

 if("/".equals(dataSource.substring(0,1))){ System.out.println("trailing forward slash, delete it "); dataSource = dataSource.substring(1); } 

instead of ==

+2
source

If you only want to check the first character, you can try the method,

dataSource.charAt (0) == '/'

+2
source

you should use .equals to compare strings so

 if(dataSource.substring(0,1) == "/") 

it should be

 if ("/".equals(dataSource.substring(0,1))) 
+1
source

You are comparing strings with == , which means that you are checking to see if these two strings are literally the same string reference.

Use equal() to check if two strings contain the same characters.

See: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html

0
source

Use .equals(Object) or .equalsIgnoreCase(String) to compare strings.

0
source

You need to do dataSource.substring(0,1).equals("/") , which actually checks the contents of the strings. == checks if both sides are the same object.

0
source

try it

if (("some string to check"). equals (myString)) {do something (); }

0
source

Always use equals when comparing values. Having said that you can just use the indexOf method for your purpose

  if (dataSource.indexOf('/') == 0) { dataSource = dataSource.substring(1); } 
0
source
 String dataSource = "/hell"; if(dataSource.substring(0,1).equalsIgnoreCase("/")){ System.out.println("trailing forward slash, delete it "); dataSource = dataSource.substring(1); } 

run this program. it works.

0
source

Why use String? You just create this problem for yourself. Use the provided data type:

 InetAddress dataSource = data.getInetAddress(); 

or

 SocketAddress dataSource = data.getRemoteSocketAddress(); 

In both cases, you have a semantically clear .equals() method.

0
source

All Articles