Basic Java Language: Difference between revisions
wikademia>Lurkingfate →Asking the user: Cleaned up code examples. |
wikademia>Lurkingfate →Assignment Operators: Cleaned up code examples. |
||
| Line 161: | Line 161: | ||
The assignment operator, "=", sets the variable on its left equal to the value on its right. This code creates the variable ''a'' and sets it equal to 5 | The assignment operator, "=", sets the variable on its left equal to the value on its right. This code creates the variable ''a'' and sets it equal to 5 | ||
< | <source lang="java">int a; | ||
a = 5;</ | a = 5; | ||
</source> | |||
Fairly simple, right? Here is where it can get a slightly more tricky. | Fairly simple, right? Here is where it can get a slightly more tricky. | ||
< | <source lang="java"> | ||
int a; | |||
int b; | int b; | ||
b = 6; | b = 6; | ||
a = b; //a equals 6</ | a = b; //a equals 6 | ||
</source> | |||
At first glance, you might think that the last statement is setting ''a'' equal to the letter "b", but instead it is setting ''a'' equal to the ''value'' of ''b'', which is 6. Essentially, a holds the value of 6. You can also set a variable and declare it on the same line: | At first glance, you might think that the last statement is setting ''a'' equal to the letter "b", but instead it is setting ''a'' equal to the ''value'' of ''b'', which is 6. Essentially, a holds the value of 6. You can also set a variable and declare it on the same line: | ||
< | <source lang="java"> | ||
int a = 6; | int a = 6; | ||
</ | </source> | ||
However, you can't say <code>char myChar = y;</code> to set a character to 'y'. That would set the character variable <code>myChar</code> to the value stored in the character variable <code>y</code>. To set <code>myChar</code> equal to the character <i>y</i>, use a '''character literal''' — a technical term for "a character in single-quotes": <code>char myChar = 'y';</code>. Note that a <code>char</code> primitive can only hold a single character. <code>char myChar = 'Yo';</code> is illegal. | However, you can't say <code>char myChar = y;</code> to set a character to 'y'. That would set the character variable <code>myChar</code> to the value stored in the character variable <code>y</code>. To set <code>myChar</code> equal to the character <i>y</i>, use a '''character literal''' — a technical term for "a character in single-quotes": <code>char myChar = 'y';</code>. Note that a <code>char</code> primitive can only hold a single character. <code>char myChar = 'Yo';</code> is illegal. | ||