Whats wrong with my program?

class Hw7{
    public static void main (String args[]){
        String s = "Hello";
        int v = String s;

This is the error thats brought up:

--------------------Configuration: <Default>--------------------
C:\Users\Stephane\Documents\JCreator Programs\Hw7.java:5: ';' expected
        int v = String s;
C:\Users\Stephane\Documents\JCreator Programs\Hw7.java:5: not a statement
        int v = String s;

And this is the question that I have:
Write a program that creates a variable s of type String. Start s as “Hello”. Type cast s into a variable v of type int. Observe the output. Is automatic type conversion possible in this case?

Edited by Nick Evan: Fixed formatting

6 Years
Discussion Span
Last Post by WargRider

int v = String s;

This is NOT valid syntax for an assignment statement.
The values to the right of the = sign should be some kind of arithmetic expression.
"String s" is not an expression.
String is the name of a class.
s is was defined in the previous statement as a variable of type String.

Read your text about what " Type cast" means. Basically it tells the compiler to "convert" or "consider as" the type of the following variable to the new type.
Not all variables can be "type cast" to other types.
For example type casting a String to an int makes no sense. What int value would you convert "ABC" to?

In some cases the compiler will try to help you and will generate code to convert data from one type to another. This can be useful and it can be dangerous. I prefer to explicitly do all conversions so that I understand what is taking place.

Edited by NormR1: n/a


to Convert a string to an integer use: Integer.parseInt(string here);

Hope it helps ;) good luck and google first :D

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.