Java String comparison. The difference between == and equals().

24 Comments

javaString1 300x297 Java String comparison. The difference between == and equals().Many Java beginners find it difficult to differentiate between == operator and the “equals()” method when comparing String variables in Java. They assume that both operations perform the same function and either one can be used to compare two string variables. I have even seen many experienced programmers committing the mistake of using “==” to compare the values of two strings.

So what is the difference between “==” and “equals()” and what is the correct method of comparing two string variables?
More

article clipper vert Java String comparison. The difference between == and equals().
 

Best way to check if a Java String is a number.

2 Comments

One of the routine tasks in many Java applications is to convert a string to a number. For instance, you may have a form where user submits his or her age. The input will come to your Java application as a String but if you need the age to do some calculation you need to convert that String into a number.
More

article clipper vert Best way to check if a Java String is a number.
 

Extract substring from end of a Java String

1 Comment

Today I’ll show you how to extract last few characters (a substring) from a string in Java. Here is the code to do this.

public class SubStringEx{
/**
 Method to get the substring of length n from the end of a string.
 @param   inputString - String from which substring to be extracted.
 @param   subStringLength- int Desired length of the substring.
 @return lastCharacters- String
 @author Zaheer Paracha

*/
public String getLastnCharacters(String inputString,
                                 int subStringLength){
    int length = inputString.length();
	if(length <= subStringLength){
	  return inputString;
	}
	int startIndex = length-subStringLength;
	return inputString.substring(startIndex);
  }
}

Let's say you want to get the last four digits from a Social Security number. Here is how you will do this by calling the method declared above.

 public static void main(String args[]){
  String ssn ="123456789";
  SubStringEx subEx = new SubStringEx();
   String last4Digits = subEx.getLastnCharacters(ssn,4);
   System.out.println("Last 4 digits are " + last4Digits); //will print 6789
 }

This method is useful in scenarios where you don't know the length of a string. For example a variable that holds credit card number may have variable length. If you want to extract the last four digits of the credit card this method will come in handy.

Enjoy.

article clipper vert Extract substring from end of a Java String