Results 1 to 2 of 2
Thread: Help with method class value?
- 12-16-2012, 05:59 AM #1
Member
- Join Date
- Dec 2012
- Posts
- 7
- Rep Power
- 0
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?
- 12-16-2012, 06:41 AM #2
Senior Member
- Join Date
- Jun 2007
- Location
- Bali, Indonesia
- Posts
- 696
- Rep Power
- 6
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.Website: Learn Java by Examples
Similar Threads
-
Using a variable from Class A, A method in B class B method
By delirek in forum New To JavaReplies: 5Last Post: 07-12-2012, 08:44 PM -
Calling overridden parent method of outter class from an inner class
By jlczuk in forum Advanced JavaReplies: 8Last Post: 04-18-2012, 04:58 PM -
How to get a compatible class of a template class? Return type of method is AClass<E>
By SKuypers in forum Advanced JavaReplies: 0Last Post: 12-07-2011, 11:55 AM -
Whats the different between package.class.method and super.method?
By Pojahn_M in forum New To JavaReplies: 1Last Post: 10-17-2011, 01:00 AM -
super class reference variable accesses overriding sub class method
By subith86 in forum New To JavaReplies: 5Last Post: 01-26-2011, 06:38 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks