Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java Problem

Options
  • 14-12-2005 3:40pm
    #1
    Closed Accounts Posts: 193 ✭✭


    int i=20;
    short s = 25;
    i = s;

    Why do i get "identifier expected" when i try to compile this.

    cheers


Comments

  • Closed Accounts Posts: 17,208 ✭✭✭✭aidan_walsh


    MiniMetro wrote:
    int i=20;
    short s = 25;
    i = s;

    Why do i get "identifier expected" when i try to compile this.

    cheers

    Short and int are datatypes of two different sizes. You'll have to cast the short as an int.
    int i = 20;
    short s = 25;
    
    i = (int)s;
    


  • Closed Accounts Posts: 193 ✭✭MiniMetro


    No that doesn't work, same problem.

    Also, the following code works, so its not a problem, you can fit a smaller data type in to a larger one e.g short into an int but not the other way round, thats when casting is necessary but it's not the solution to this problem.

    int i=20;
    short s = 25;
    int b = s;

    can anyone else help?


  • Registered Users Posts: 261 ✭✭HaVoC


    Can you please post the full error and maybe the method the problem is in


  • Registered Users Posts: 21,264 ✭✭✭✭Hobbes


    Where are you writing those lines of code?

    "i = s" has to be within a method. I suspect you have entered these outside of a method which would explain why "int b = s" works.

    You need to do something like.
    Class example {
      int i = 20;
      short s = 25;
      // i = s will not work here.
      int b = s;  // This will work here.
    
      public static void main(String[] args) { 
         i = s;
      }
    
      public static void thisWorksAsWell() {
         int i = 20;
         short s = 25;
         i = s;
         int b = s;
      }
    
    }
    


Advertisement