This question already has answers here:
a confusion about java String literal pool and String's concatenation
(4 answers)
When should we use intern method of String on String literals
(14 answers)
Closed 6 years ago.
Here is my code and I am now quite confuse about String pool and
Heap storage by this output.
public class String1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "abcd";
String str1 = "" ;
str1=str1+"abcd";
if(str.equals(str1))
System.out.println("True");
else
System.out.println("False");
if(str == str1)
System.out.println("True");
else
System.out.println("False");
}
}
Now, I am creating String str and will be stored in string pool (Correct me if I am getting wrong!).
Now after concat str1 with string "abcd" they both have same value.
So, I think str and str1 should have same reference in String pool and So, 2nd if statement should print true but it prints false.
So, my question why str and str1 not getting same reference ?
Java automatically interns (means, puts them into the String pool) String literals, not newly created Strings. See also https://stackoverflow.com/a/1855183/1611055.
Remember that Strings are immutable, so the + operator must create a new String - it can not append to the existing one. Internally, the + operator uses a StringBuilder to concatenate the strings. The final result is retrieved through StringBuilder.toString() which essentially does return new String(value, 0, count);.
This newly created String is not automatically put into the String pool.
Hence the str1 reference is different from str even though the strings have the same content. str points to a location in the string pool, while str1 points to a location on the heap.
If you add
str1 = str1.intern();
after str1 = str1 + "abcd"; to explicitly intern the newly created String, your second if statement returns true.
Alternatively, str1 = (str1 + "abcd").intern(); would have the same effect.
In case of strings to compare the values we should use equals method as it compares values that are present in the string variables.
But when we choose to compare string variables using == it compares the addresses of the String object not the values so it will return false even if they have same values in it.
you are right that the strings get added to the string pool. but == checks if both the objects are pointing to the same reference (to make it simpler pointing to the same memory location) in the string pool or not. whereas .equals() method check if the value of the both the object are same or not.
Related
String s1="Hello";
s1=s1.concat("World");
String s2="HelloWorld";
System.out.println(s1);
System.out.println(s2);
System.out.println(s2==s1); //false
As after concatenating, the "HelloWorld" string is created in the string constant pool and we are making another string with the same word "HelloWorld" then it is already present in the string constant pool hence it returns the existed reference.
So, why my code is giving false in the output?
String s1="Hello";
String s2="HelloWorld";
s1=s1.concat("World");
System.out.println(s1);
System.out.println(s2);
System.out.println(s2==s1);//false
String s1="Hello";
s1=s1+"World";
String s2="HelloWorld";
System.out.println(s1);
System.out.println(s2);
System.out.println(s2==s1);//false
why false??
why they are pointing to different ref.
As the word is already present in the string constant pool. then if we forming a new string object with the same value then it should point to the already present object.
The strings have not an equal identity by default. A string from the string pool is only returned if the string is interned.
All String values or String concatenations whose results are solely from constant expressions are interned automatically. A constant expression is an expression whose value is known at compile time. That includes:
literals; and
final variables of primitive types or the String class.
Examples:
String a = "Hello" + "World"; // 'HelloWorld'
String b = "Hi" + 23 + "There"; // 'Hi23There'
final int i = 47 + 100;
String c = "Number" + i + '!'; // 'Number147!'
This is defined in the Java Language Specification, § 15.28.
Your use case does not fulfill these requirements, so your result is false. You can trigger string interning by calling Strings intern() method. If you had written s1 = s1.concat("World").intern(); instead, then the result would be true.
You need to use equals instead of == , so your code must look like System.out.println(s2.equals(s1))
We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
You are creating two objects s1 and s2 . So when you do
s2==s1
you are comparing references of those 2 objects, which will always return false as both objects are seperate.
If comparing contents of a string , try implementing the .equals() method.
s2.equals(s1)
s1 and s2 are 2 different references pointing towards 2 different addresses. Therefore s1==s2 will return false always (since different addresses).
This is because the concat() method returns a new String object
public String concat(String str) {
if (str.isEmpty()) {
return this;
}
return StringConcatHelper.simpleConcat(this, str);
}
If you used the "+" operator instead this will result in your expected output:
String s1 = "Hello" + "World";
String s2 = "HelloWorld";
System.out.println(s1 == s2); // true
Hope this helps for your understanding,
but for real world usage always stick to .equals() when comparing String values:
System.out.println(s1.equals(s2));
public static void main(String[] args) {
String str1 = new StringBuilder("计算机").append("软件").toString();
System.out.println(str1.intern() == str1);
String str2 = new StringBuffer("ja").append("va").toString();
System.out.println(str2.intern() == str2);
}
Results:
true
false
First one prints true, and the second prints false. Why are the results different?
The difference in behavior is unrelated to the differences between StringBuilder and StringBuffer.
The javadoc of String#intern() states that it returns
When the intern method is invoked, if the pool already contains a
string equal to this String object as determined by the equals(Object)
method, then the string from the pool is returned. Otherwise, this
String object is added to the pool and a reference to this String
object is returned.
The String created from
String str2 = new StringBuffer("ja").append("va").toString();
is a brand new String that does not belong to the pool.
For
str2.intern() == str2
to return false, the intern() call must have returned a different reference value, ie. the String "java" was already in the pool.
In the first comparison, the String "计算机软件" was not in the string pool prior to the call to intern(). intern() therefore returned the same reference as the one stored in str2. The reference equality str2 == str2 therefore returns true.
Because your assignments don't re-read from the intern pool and Java String(s) are immutable. Consider
String str1 = new StringBuilder("计算机").append("软件").toString();
String str1a = new String(str1); // <-- refers to a different String
str1 = str1.intern();
str1a = str1a.intern();
System.out.println(str1a == str1);
String str2 = new StringBuffer("ja").append("va").toString();
String str2a = new String(str2); // <-- refers to a different String
str2 = str2.intern();
str2a = str2a.intern();
System.out.println(str2a == str2);
The output is (as you might expect)
true
true
Lots of answer before mentioned about the pool and explained really clearly with the Oracle link docs.
I just would like to point out the way we can check when debugging code.
String str1 = new StringBuilder("计算机").append("软件").toString();
System.out.println(str1.intern() == str1);//the str1.intern() returns the same memory address the str1
String str2 = new StringBuffer("ja").append("va").toString();
System.out.println(str2.intern() == str2);//the str2.intern() does not return the same memory address the str2
You can use any IDE and debug to check the actual address that the str1 and str1.intern()/str2 and str2.intern().
let me add something more interesting:
the OpenJDk 8 is true,true;
Oracle JDK 6 is true,true;
so I think the right answer is :
diffrent vendor's jvm or jvm versions may have diffrent implemention(the language specification don't force the how to)
In Oracle JDK 8(I guess u using):
String “java” already in pool(loaded by java.lang.Version#laucher_name) and String pool only stores the refrence,not the object.
But in OpenJDK the laucher_name is "openJDK";In Oracle JDK 6 and below ,the string pool will copy the string object to itslef.
I recently learned that in Java: == compares the object references, not the content, which is why:
String str1 = "hell";
String str2 = "o";
String str3 = str1 + str2;
String str4 = "hello";
str3 == str4; // False
So far so good. However when I do the following:
String str5 = "hello";
str5 == str4; // True
Does this mean that str5 and str4 reference the same memory object? How does this work?
The String str5 = "hello"; creates a pooled String value hello, which is why str5 == str4 returns true.
On the other hand, str1 + str2 works like this:
An instance of the StringBuilder class is created (behind the scenes)
The + operator actually invokes the StringBuilder#append(String s) method
When the appending is done, a StringBuilder.toString() method is invoked, which returns a brand new String object. This is why str3 == str4 is actually false.
More info:
How do I compare Strings in Java?
How Java do the string concatenation using “+”?
Yes. str5 and str4 refer the same memory object. As Strings are immutable when you change the value of some string its produce an different object. If two String objects have the same value then second one is not created, JVM just give the reference of the first object.
When the value of String changed different object created for some security and other usefull purpose read these link:
Immutability of Strings
wiki Immutable object
When some string are created like
String str1="hello";
JVM creates an immutable object when again you try to create some string with same value
String str2="hello"
JVM use the same procedure to create an object as see's that this object is already created then its return the object of the str1 to reduce duplicate object creation.
This will be useful string pool in the jvm
Yes, when you create and assign a String value eg String s1="hello"; , it gets added in the String pool. Now if you assign the same String value to another reference like this:-
String s2="hello";
The variable s2 will point to the same String object hello , present in String pool.
However you can force and create a new String object for the same values like this:-
String s3= new String("hello");
This will add and create new object for hello even though it is already present in the String pool.
Hence it can be summarised as:-
s1==s2; //return true
s1==s3; //return false
s2==s3; //returns false
Strings are pooled by the JVM once they are created, that's why those variables refer to the same instance in the String pool.
And the idea behind having a String pool is to avoid unnecessary object creation.
Strings are immutable objects. This is why str1 and str2 combined are not equal to str3.
Ya,its gives true for str5 ==str4 becoz it uses"string pool area" to store."this time also it
compares object references" but these strings has same object reference as string pool area has one object id.
In first case strings are not created in string pool area thats why it gives false.
A private pool of string literals is maintained by String class. All literal strings and string-valued constant expressions are added to this pool during program start up. So all string literals with same value will point to same object.
When a new string object is created(e.g. by concatenating two string objects) it does not belong to the String pool, so comparing it with another string literal will return false. Any string object can be added to String pool by invoking intern() method on that string object, now the object will point to a string literal from the pool which have same value as this object. Now any string comparison of this object with same string literal will yield true.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java Strings: “String s = new String(”silly“);”
If i write
String s= new String("how many object b created by this method ");
how many reference objects and objects will be created in comparison to doing it this way:
Sting s1="Is this method is good as compare to upper";
Using String s= new String("how many object b created by this method "); creates a new object 's' of String class, and you are passing the string "how many object b created by this method" to its constructor.
In String s1="Is this method is good as compare to upper"; 's1' is a string literal. On string literals:
Each time your code
create a string literal, the JVM
checks the string literal pool first.
If the string already exists in the
pool, a reference to the pooled
instance returns. If the string does
not exist in the pool, a new String
object instantiates, then is placed in
the pool. Java can make this
optimization since strings are
immutable and can be shared without
fear of data corruption.
source
The above concept is related to string interning; all literal strings and string-valued constant expressions are interned in Java [source]. So basically, using String s1="Is this method is good as compare to upper"; will create a new object only if "Is this method is good as compare to upper" is not already in the pool.
Using String s1="some string" doesn't create new String object. There is existing String object for every String literal already.
String literals with same values are represented with single String object, so if you use String s1="some string"; String s2="some string"; both s1, s2 refer to same "some string" object.
new String("...") creates one new String object, which uses same data as String object for value "..." passed to constructor.
Consider:
String s1 = new String("hi");
String s2 = new String("hi");
System.out.println(s1 == s2);
Will print false.
However
String s1 = "hi";
String s2 = "h1";
System.out.println(s1 == s2);
Will print true.
And
String s1 = "hi";
String s2 = new String("hi");
System.out.println(s1 == s2);
Will print false.
This is why you should always use String.equals when comparing Strings instead of ==.
But don't take my word for it... Check this excerpt from the Java Language Specification JLS 3.10:
Thus, the test program consisting of the compilation unit (§7.3):
package testPackage;
class Test {
public static void main(String[] args) {
String hello = "Hello", lo = "lo";
System.out.print((hello == "Hello") + " ");
System.out.print((Other.hello == hello) + " ");
System.out.print((other.Other.hello == hello) + " ");
System.out.print((hello == ("Hel"+"lo")) + " ");
System.out.print((hello == ("Hel"+lo)) + " ");
System.out.println(hello == ("Hel"+lo).intern());
}
}
class Other { static String hello = "Hello"; }
and the compilation unit:
package other;
public class Other { static String hello = "Hello"; }
produces the output:
true true true true false true
This example illustrates six points:
Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
Literal strings within different classes in the same package represent references to the same String object.
Literal strings within different classes in different packages likewise represent references to the same String object.
Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
Strings computed by concatenation at run time are newly created and therefore distinct.
The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.
There are two ways to create a String object in Java:
Using the new operator. For example,
String str = new String("Hello");
Using a string literal or constant expression). For example,
String str="Hello"; (string literal) or
String str="Hel" + "lo"; (string constant expression).
String Literal Pool :
String allocation, like all object
allocation, proves costly in both time
and memory. The JVM performs some
trickery while instantiating string
literals to increase performance and
decrease memory overhead. To cut down
the number of String objects created
in the JVM, the String class keeps a
pool of strings. Each time your code
create a string literal, the JVM
checks the string literal pool first.
If the string already exists in the
pool, a reference to the pooled
instance returns. If the string does
not exist in the pool, a new String
object instantiates, then is placed in
the pool.
Creating a String object using NEW keyword always creates an object in the heap containing the desired string and the reference of the created object in the heap is returned.
Creating a String object without NEW keyword (using literal) first checks for an existing string with the same data in the String literal pool, if found, the same reference from the String literal pool is returned, else, a new one is created in the String literal pool and its reference is returned.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working?
public static void main(String...aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos = "Jorman 14988611";
StringTokenizer tokens = new StringTokenizer(strDatos, " ");
int nDatos = tokens.countTokens();
String[] datos = new String[nDatos];
int i = 0;
while (tokens.hasMoreTokens()) {
String str = tokens.nextToken();
datos[i] = str;
i++;
}
//System.out.println (usuario);
if ((datos[0] == usuario)) {
System.out.println("WORKING");
}
}
Use the string.equals(Object other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.
if (usuario.equals(datos[0])) {
...
}
NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.
Meet Jorman
Jorman is a successful businessman and has 2 houses.
But others don't know that.
Is it the same Jorman?
When you ask neighbours from either Madison or Burke streets, this is the only thing they can say:
Using the residence alone, it's tough to confirm that it's the same Jorman. Since they're 2 different addresses, it's just natural to assume that those are 2 different persons.
That's how the operator == behaves. So it will say that datos[0]==usuario is false, because it only compares the addresses.
An Investigator to the Rescue
What if we sent an investigator? We know that it's the same Jorman, but we need to prove it. Our detective will look closely at all physical aspects. With thorough inquiry, the agent will be able to conclude whether it's the same person or not. Let's see it happen in Java terms.
Here's the source code of String's equals() method:
It compares the Strings character by character, in order to come to a conclusion that they are indeed equal.
That's how the String equals method behaves. So datos[0].equals(usuario) will return true, because it performs a logical comparison.
It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()) during compilation - so when you write for example "hello world" in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal") and second is constructed during runtime ie. with "new" keyword like new String("i am string literal"), the == (equality) operator returns false, because both of them are different instances of the String class.
Only right way is using .equals() -> datos[0].equals(usuario). == says only if two objects are the same instance of object (ie. have same memory address)
Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language
The == operator checks if the two references point to the same object or not.
.equals() checks for the actual string content (value).
Note that the .equals() method belongs to class Object (super class of all classes). You need to override it as per you class requirement, but for String it is already implemented and it checks whether two strings have the same value or not.
Case1)
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s1; // true
s1.equals(s2); // true
Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
Case2)
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2; // false
s1.equals(s2); // true
Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.
equals() function is a method of Object class which should be overridden by programmer. String class overrides it to check if two strings are equal i.e. in content and not reference.
== operator checks if the references of both the objects are the same.
Consider the programs
String abc = "Awesome" ;
String xyz = abc;
if(abc == xyz)
System.out.println("Refers to same string");
Here the abc and xyz, both refer to same String "Awesome". Hence the expression (abc == xyz) is true.
String abc = "Hello World";
String xyz = "Hello World";
if(abc == xyz)
System.out.println("Refers to same string");
else
System.out.println("Refers to different strings");
if(abc.equals(xyz))
System.out.prinln("Contents of both strings are same");
else
System.out.prinln("Contents of strings are different");
Here abc and xyz are two different strings with the same content "Hello World". Hence here the expression (abc == xyz) is false where as (abc.equals(xyz)) is true.
Hope you understood the difference between == and <Object>.equals()
Thanks.
== tests for reference equality.
.equals() tests for value equality.
Consequently, if you actually want to test whether two strings have the same value you should use .equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning).
== is for testing whether two strings are the same Object.
// These two have the same value
new String("test").equals("test") ==> true
// ... but they are not the same object
new String("test") == "test" ==> false
// ... neither are these
new String("test") == new String("test") ==> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" ==> true
// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st" ==> true
// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false
It is important to note that == is much cheaper than equals() (a single pointer comparision instead of a loop), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing with interned strings) it can present an important performance improvement. However, these situations are rare.
Instead of
datos[0] == usuario
use
datos[0].equals(usuario)
== compares the reference of the variable where .equals() compares the values which is what you want.
Let's analyze the following Java, to understand the identity and equality of Strings:
public static void testEquality(){
String str1 = "Hello world.";
String str2 = "Hello world.";
if (str1 == str2)
System.out.print("str1 == str2\n");
else
System.out.print("str1 != str2\n");
if(str1.equals(str2))
System.out.print("str1 equals to str2\n");
else
System.out.print("str1 doesn't equal to str2\n");
String str3 = new String("Hello world.");
String str4 = new String("Hello world.");
if (str3 == str4)
System.out.print("str3 == str4\n");
else
System.out.print("str3 != str4\n");
if(str3.equals(str4))
System.out.print("str3 equals to str4\n");
else
System.out.print("str3 doesn't equal to str4\n");
}
When the first line of code String str1 = "Hello world." executes, a string \Hello world."
is created, and the variable str1 refers to it. Another string "Hello world." will not be created again when the next line of code executes because of optimization. The variable str2 also refers to the existing ""Hello world.".
The operator == checks identity of two objects (whether two variables refer to same object). Since str1 and str2 refer to same string in memory, they are identical to each other. The method equals checks equality of two objects (whether two objects have same content). Of course, the content of str1 and str2 are same.
When code String str3 = new String("Hello world.") executes, a new instance of string with content "Hello world." is created, and it is referred to by the variable str3. And then another instance of string with content "Hello world." is created again, and referred to by
str4. Since str3 and str4 refer to two different instances, they are not identical, but their
content are same.
Therefore, the output contains four lines:
Str1 == str2
Str1 equals str2
Str3! = str4
Str3 equals str4
You should use string equals to compare two strings for equality, not operator == which just compares the references.
It will also work if you call intern() on the string before inserting it into the array.
Interned strings are reference-equal (==) if and only if they are value-equal (equals().)
public static void main (String... aArguments) throws IOException {
String usuario = "Jorman";
String password = "14988611";
String strDatos="Jorman 14988611";
StringTokenizer tokens=new StringTokenizer(strDatos, " ");
int nDatos=tokens.countTokens();
String[] datos=new String[nDatos];
int i=0;
while(tokens.hasMoreTokens()) {
String str=tokens.nextToken();
datos[i]= str.intern();
i++;
}
//System.out.println (usuario);
if(datos[0]==usuario) {
System.out.println ("WORKING");
}
Generally .equals is used for Object comparison, where you want to verify if two Objects have an identical value.
== for reference comparison (are the two Objects the same Object on the heap) & to check if the Object is null. It is also used to compare the values of primitive types.
== operator compares the reference of an object in Java. You can use string's equals method .
String s = "Test";
if(s.equals("Test"))
{
System.out.println("Equal");
}
If you are going to compare any assigned value of the string i.e. primitive string, both "==" and .equals will work, but for the new string object you should use only .equals, and here "==" will not work.
Example:
String a = "name";
String b = "name";
if(a == b) and (a.equals(b)) will return true.
But
String a = new String("a");
In this case if(a == b) will return false
So it's better to use the .equals operator...
The == operator is a simple comparison of values.
For object references the (values) are the (references). So x == y returns true if x and y reference the same object.
I know this is an old question but here's how I look at it (I find very useful):
Technical explanations
In Java, all variables are either primitive types or references.
(If you need to know what a reference is: "Object variables" are just pointers to objects. So with Object something = ..., something is really an address in memory (a number).)
== compares the exact values. So it compares if the primitive values are the same, or if the references (addresses) are the same. That's why == often doesn't work on Strings; Strings are objects, and doing == on two string variables just compares if the address is same in memory, as others have pointed out. .equals() calls the comparison method of objects, which will compare the actual objects pointed by the references. In the case of Strings, it compares each character to see if they're equal.
The interesting part:
So why does == sometimes return true for Strings? Note that Strings are immutable. In your code, if you do
String foo = "hi";
String bar = "hi";
Since strings are immutable (when you call .trim() or something, it produces a new string, not modifying the original object pointed to in memory), you don't really need two different String("hi") objects. If the compiler is smart, the bytecode will read to only generate one String("hi") object. So if you do
if (foo == bar) ...
right after, they're pointing to the same object, and will return true. But you rarely intend this. Instead, you're asking for user input, which is creating new strings at different parts of memory, etc. etc.
Note: If you do something like baz = new String(bar) the compiler may still figure out they're the same thing. But the main point is when the compiler sees literal strings, it can easily optimize same strings.
I don't know how it works in runtime, but I assume the JVM doesn't keep a list of "live strings" and check if a same string exists. (eg if you read a line of input twice, and the user enters the same input twice, it won't check if the second input string is the same as the first, and point them to the same memory). It'd save a bit of heap memory, but it's so negligible the overhead isn't worth it. Again, the point is it's easy for the compiler to optimize literal strings.
There you have it... a gritty explanation for == vs. .equals() and why it seems random.
#Melkhiah66 You can use equals method instead of '==' method to check the equality.
If you use intern() then it checks whether the object is in pool if present then returns
equal else unequal. equals method internally uses hashcode and gets you the required result.
public class Demo
{
public static void main(String[] args)
{
String str1 = "Jorman 14988611";
String str2 = new StringBuffer("Jorman").append(" 14988611").toString();
String str3 = str2.intern();
System.out.println("str1 == str2 " + (str1 == str2)); //gives false
System.out.println("str1 == str3 " + (str1 == str3)); //gives true
System.out.println("str1 equals str2 " + (str1.equals(str2))); //gives true
System.out.println("str1 equals str3 " + (str1.equals(str3))); //gives true
}
}
The .equals() will check if the two strings have the same value and return the boolean value where as the == operator checks to see if the two strings are the same object.
Someone said on a post higher up that == is used for int and for checking nulls.
It may also be used to check for Boolean operations and char types.
Be very careful though and double check that you are using a char and not a String.
for example
String strType = "a";
char charType = 'a';
for strings you would then check
This would be correct
if(strType.equals("a")
do something
but
if(charType.equals('a')
do something else
would be incorrect, you would need to do the following
if(charType == 'a')
do something else
a==b
Compares references, not values. The use of == with object references is generally limited to the following:
Comparing to see if a reference is null.
Comparing two enum values. This works because there is only one object for each enum constant.
You want to know if two references are to the same object
"a".equals("b")
Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.
Use Split rather than tokenizer,it will surely provide u exact output
for E.g:
string name="Harry";
string salary="25000";
string namsal="Harry 25000";
string[] s=namsal.split(" ");
for(int i=0;i<s.length;i++)
{
System.out.println(s[i]);
}
if(s[0].equals("Harry"))
{
System.out.println("Task Complete");
}
After this I am sure you will get better results.....