Learning Java/Basic Java Language: Difference between revisions

Content deleted Content added
→‎Assignment Operators: Moving section before mathematical operators.
→‎Operators: Sectional move.
Line 156:
== Operators ==
Operators are the symbols defining a certain operation to be performed.
 
=== Assignment Operators ===
An assignment operator assigns a value to a certain variable after evaluating the expression to be assigned. You have seen one of them in numerous examples so far, can you pick it out?
 
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
<pre>int a;
a = 5;</pre>
Fairly simple, right? Here is where it can get a slightly more tricky.
 
<pre>int a;
int b;
b = 6;
a = b; //a equals 6</pre>
 
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:
 
<pre>
int a = 6;
</pre>
 
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.
 
Finally, what's so special about <code>float</code>s and <code>double</code>s? Doubles and floats can have decimals: <code>float myFloat = 5.1;</code>. (The term "float" is short for "floating-point number," referring to the decimal point.)
 
Now, why would you want to set a variable? You would need to set a variable for further use, i.e., to access at a later time.
 
=== Addition Operator '+' ===