Issue
class Student {
String name;
int age;
public void setInfo(String n, int a) {
this.name = n;
this.age = a;
}
public String getInfo() { // Notice the "String" data type in this function
return (this.name + " " + this.age); // "this.age" is a "int" data type but the function is supposed to be returning only "String" data type, right?
}
}
public class OOPS {
public static void main(String args[]) {
Student s1 = new Student();
s1.setInfo("John", 24);
System.out.println(s1.getInfo());
}
}
Here is the output: Click me to see the output
The next thing I tried to do was replace "String" with "int" in the function.
Like this:
public int getInfo() {
return (this.name + " " + this.age);
}
It throws this error: Click me to see the error
The question is why is it so?
Solution
The string concatenation in your code:
return ( this.name + " " + this.age );
… implicitly generates a string from your int
member field, this.age
.
That is equivalent to a call to String.valueof
:
return ( this.name + " " + String.valueOf( this.age ) );
See Converting Numbers to Strings in the Java Tutorials provided by Oracle free of cost.
Answered By - Basil Bourque
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.