Archived

This topic is now archived and is closed to further replies.

yves032784

[java] what does the '%' identifier do?

Recommended Posts

in an operation what does the ''%'' identifier do? i''ve also seen this used with a string, e.g
 int y=137;
String x="";
while (y>0)
{
     x+=(y % 10);
     y/=10;
}
 

Share this post


Link to post
Share on other sites
% is an operator, not an identifier. It is, in fact, an arithmetic operator called the modulus operator; it returns the remainder of an integer division (i.e. 10/3=3, 10%3=1). One very simple and common application is to check whether a number is odd or even; if(n%2 == 0), it is even; else it is odd.

Share this post


Link to post
Share on other sites
The thing with the String is that Java automatically converts numbers to a String if they are added to a String. So:

x="My ";
x+=1;
System.out.println("x="+x);

gives you:

x=My 1





First make it work,
then make it fast.

--Brian Kernighan

The problems of this world cannot possibly be solved by skeptics or cynics whose horizons are limited by the obvious realities. We need men and women who can dream of things that never were. - John Fitzgerald Kennedy(35th US President)

Do not interrupt your enemy when he is making a mistake. - Napolean Bonaparte

Share this post


Link to post
Share on other sites
quote:
Original post by CaptainJester
The thing with the String is that Java automatically converts numbers to a String if they are added to a String.


And they say Java has no operator overloading

--
AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.
[Project site] [Blog] [RSS] [Browse the source] [IRC channel]

Share this post


Link to post
Share on other sites
The listed code should fill a string with the digits of the number in reverse order. Any number modulus 10 will return the digit in the ones place. Think about it for a while and it should make sense.

______________________________________________________________
The Phoenix shall arise from the ashes... ThunderHawk -- ¦þ
MySite
______________________________________________________________

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
shouldn''t it use a do { ... } while instead? otherwise 0 will generate an empty string.

Share this post


Link to post
Share on other sites
quote:
Original post by Arild Fines
And they say Java has no operator overloading



Very little. The main thing is that programmers cannot create their own overloaded operations.



First make it work,
then make it fast.

--Brian Kernighan

The problems of this world cannot possibly be solved by skeptics or cynics whose horizons are limited by the obvious realities. We need men and women who can dream of things that never were. - John Fitzgerald Kennedy(35th US President)

Do not interrupt your enemy when he is making a mistake. - Napolean Bonaparte

Share this post


Link to post
Share on other sites