When writing an assignment statement, one rule we have to follow is that
the data type of the richt-hand value (rvalue)
has to match the data type of the left-hand value (lvalue).
Sometimes this rule can cause
problems, for instance when we get input. Let's suppose we want to have
the user enter a numerical value, then use it to perform mathematical
calculations.
When we get input, the data is of type String, but mathematical
calculations require numerical primitives like int or double. What we need to
do is convert the data from String to int
or String to double.
In Java, the primitive data
types each have a corresponding class that begins with an upper-case letter. For
instance, the primitive type int has a corresponding class called
Integer
and the primitive type double has a corresponding class called
Double. These classes can be used to convert String data to primitives.
They are called type-wrapper classes.
Look at the assignment statment that gives num1 a value.
This statement converts the object s1 to an int
and stores it in the integer primitive num1.
Notice this form of
dot-notation uses class.method(arg), where the class is Integer,
the method name is parseInt, and the argument is s1.
Next, look at the assignment statment that gives num2 a value.
This statement converts the object s2 to a double
and stores it in the double primitive num2.
Notice this also uses
the same form of dot-notation as the parseInt() method call. In this
statement the class is Double,
the method name is parseDouble, and the argument is s2.
Now the values are in primitive objects they can be manipulated in mathematical
formulas.
In later versions of Java, arithmetic operations can be done with objects of the type-wrapper classes (like Double).