Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialPhilip Schultz
11,437 Points@ 7:45 you compare two numbers, but one is a String and one is a int (integer). How does that work?
Can someone please explain how Craig was able to compare the Value of an integer and the value of a String? Also he says that the Integer.parseInt() is static method, what does he mean by static? Thank you.
1 Answer
Dan Johnson
40,533 PointsA static
method is a method that is associated with the class itself, rather than an instance of that class. This allows you to call it directly from the class, however it won't have access to any non-static variables.
parseInt being static
is why it can be called from the Integer
class without making a new instance.
parseInt takes a String
and attempts to create an Integer
from it assuming the String
contains appropriate values (e.g. digits, negative sign). So since the "30"
got converted there was no direct comparison between a String
and an Integer
.
Philip Schultz
11,437 PointsPhilip Schultz
11,437 PointsIm still confused why it is a String to began with. Where did he declare it a string? I believe he says
int age=Integer.parseInt("30");.
He could have said int age = 30; , right? Why would need to create a integer (age) and set it equal to a string that is being converted to an integer? In most cases you would put a variable in the parameters, right?
Dan Johnson
40,533 PointsDan Johnson
40,533 PointsIn the video it was purely for a demonstration of the method. Like you mention, it would be easier to just declare an
int
orInteger
as the appropriate type to start with.An example of a more viable use of the parseInt method was if you had a form field in an application that was read in as a
String
, but was expected to be treated as a numeric type. You could use parseInt to do the conversion for you.Philip Schultz
11,437 PointsPhilip Schultz
11,437 PointsOk I got it. Thank you Dan.