Results 1 to 2 of 2
  1. #1
    Estrex is offline Member
    Join Date
    Dec 2012
    Rep Power

    Default Help with method class value?

    So, this is what I coded:

    public char getInitials()
    return firstName.charAt(0)+lastName.charAt(0);

    I thought this would work since the method type char is the same as the return type, but it says possible loss of precision, required char, found int on the lastName.charAt(0) line. Can someone please tell me what I may do to correct this?

  2. #2
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Bali, Indonesia
    Rep Power

    Default Re: Help with method class value?

    In your code you got that error because by default in Java the integer addition operator (+) will give you a result in an int data type. That is where the possible loss precision error comes from. It is because the value of int is much bigger than char.

    But in you case as the initial will contain two characters you can't use the char data type as a return type there. Because a char only store a single character. If you want a string that have more than one character use the String object. If you are using the charAt() method you need to convert it first into string using the valueOf() method of the string class. Instead you can use String's substring() method to get the first letter from the firstname and the lastname.

Similar Threads

  1. Replies: 5
    Last Post: 07-12-2012, 08:44 PM
  2. Replies: 8
    Last Post: 04-18-2012, 04:58 PM
  3. Replies: 0
    Last Post: 12-07-2011, 12:55 PM
  4. Replies: 1
    Last Post: 10-17-2011, 01:00 AM
  5. Replies: 5
    Last Post: 01-26-2011, 07:38 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts