Reputation: 31
I am trying to run below code. It is giving me error
The operator + is undefined for the argument type(s) String, void
public class CompStrings{
String s1=null;
String s2=null;
public void testMethod(){
s1 = new String("Hello");
s2 = new String("Hello");
String str3="abc";
String str4 ="abc";
/**
* ==
*/
if(str3==str4){
System.out.println("str3==str4 is true");
}else{
System.out.println("str3==str4 is false");
}
if(str3.equals(str4)){
System.out.println("str1.equals(str2) is true");
}else{
System.out.println("str1.equals(str2) is false");
}
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
/*Integer i1 = new Integer(10);
Integer i2 = new Integer(10);
System.out.println(i1.hashCode());
System.out.println(i2.hashCode());
1)String s1="hello";
String s2="hello";
2)String s1 = new String("Hello");
String s2 = new String("Hello");
3)String s1="hello";
string s2=s1;
**/
}
public static void main(String argv[]){
CompStrings obj= new CompStrings();
// \System.out.println("Calling My Method"+ obj.testMethod());
System.out.println("Hashcode for emp1 = " + obj.testMethod());// Here it gives Error
}
public boolean equals(Object o){
String s = (String) o;
if (s1.equals(s) ){
return true;
}else{
return false;
}
}
public int hashCode(){
return s1.hashCode();
}
}
Upvotes: 3
Views: 182
Reputation: 12696
testMethod()
should return String
instead of void
.
Or, don't put the call to testMethod()
inside System.out.println()
Upvotes: 0
Reputation: 3520
First, it would be more clean to write like that
String s1 = "Hello"; String s2 = "Hello";
But the problem is that testMethod() does not return a string.... it returns nothing!
Upvotes: 0
Reputation: 5006
Your obj.testMethod()
return nothing (void
)... so you can't concat it with a String.
Try this instead:
System.out.println("Hashcode for emp1 = ");
obj.testMethod();
Upvotes: 1
Reputation: 3594
Your testMethod()
has no return type, if you wish to use it in this way it must return either a String or another Object. I say Object because all objects in Java inherit from Object, and hence will have a toString() implementation.
Upvotes: 1
Reputation: 41510
testMethod()
obviously doesn't return anything, that's why there's nothing to print.
Upvotes: 4
Reputation: 1499770
testMethod()
doesn't return anything - so what would you expect the result to be when you try to use the value of the expression testMethod()
for any reason? (In this case you happen to be using it in string concatenation, but you couldn't assign it to a variable, pass it as an argument etc either.)
It sounds like you really want it to return a hash code, given the rest of the System.out.println
call. Alternatively:
System.out.println("Calling testMethod");
obj.testMethod();
System.out.println("testMethod finished");
Upvotes: 3