Whats wrong with my program?

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

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?

Recommended Answers

All 2 Replies

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.

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.