Basic Java Language: Difference between revisions

wikademia>Lurkingfate
→Assignment Operators: Moving section before mathematical operators.
wikademia>Wikademia
m Text replace - '[[Topic:' to '[['
 
(13 intermediate revisions by 3 users not shown)
Line 1: Line 1:
This lesson discusses the basics of the Java language, including variables, primitives, operators, statements and Java writing conventions.
This lesson discusses the basics of the Java language, including variables, primitives, operators, statements and Java writing conventions.
 
{{ntnes}}
== Touch on Classes ==
== Touch on Classes ==
Everything in Java is written in classes. A Class in this context is a section of code that can contain data (variables), and instructions for processing that data (methods). Returning to the Hello World example from the [[Introduction to Java]], the class is defined on the first line, and everything within the curly brackets is within that class.
Everything in Java is written in classes. A Class in this context is a section of code that can contain data (variables), and instructions for processing that data (methods). Returning to the Hello World example from the [[Introduction to Java]], the class is defined on the first line, and everything within the curly brackets is within that class.
Line 57: Line 57:
===Extends/Implements===
===Extends/Implements===


For the moment you can happily forget about this, it was included for completeness. For the object orientated experts, you will be pleased to know that this permits inheritance.
Extends/Implements not complete yet. Soon..
 
 
 


== Statements ==
== Statements ==
Line 156: Line 153:
== Operators ==
== Operators ==
Operators are the symbols defining a certain operation to be performed.
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.
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;
</source>
Fairly simple, right? Here is where it can get a slightly more tricky.
<source lang="java">
int a;
int b;
b = 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:
<source lang="java">
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.
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 '+' ===
=== Addition Operator '+' ===
Line 174: Line 199:
=== Subtraction '-', multiplication '*', division '/', and modulus '%' operators ===
=== Subtraction '-', multiplication '*', division '/', and modulus '%' operators ===
Just like the addition operator, the subtraction, multiplication, division, and modulus operators are used as follows:
Just like the addition operator, the subtraction, multiplication, division, and modulus operators are used as follows:
<pre>
<source lang="java">
int a = 9;
int a = 9;


Line 181: Line 206:
a*2; // evaluates to 18
a*2; // evaluates to 18
a%4; // evaluates to 1
a%4; // evaluates to 1
</pre>
</source>


Subtraction, multiplication, and division, you have seen before, but the modulus operator is much less commonly used. Actually, it is commonly used, but it known under a different name, the remainder. Nine divided by four gives a remainder of one, so therefore 9%4 (pronounced "9 mod 4") evaluates to 1.
Subtraction, multiplication, and division, you have seen before, but the modulus operator is much less commonly used. Actually, it is commonly used, but it known under a different name, the remainder. Nine divided by four gives a remainder of one, so therefore 9%4 (pronounced "9 mod 4") evaluates to 1.


When more than one of the operators are used in the same statement, for example:
When more than one of the operators are used in the same statement, for example:
<pre>
<source lang="java">
int a, b, c, d;
int a, b, c, d;
a = a-b/c*d;
a = a-b/c*d;
</pre>
</source>


the Java language would use the order-of-operations in this case.
the Java language would use the order-of-operations in this case.
Line 197: Line 222:


Example:
Example:
<pre>
<source lang="java">
int a = 6; // assigns the value 6 to variable a
int a = 6; // assigns the value 6 to variable a
a += 5; // adds 5 to a, and assigns that value back into a, now a is 11
a += 5; // adds 5 to a, and assigns that value back into a, now a is 11
</pre>
</source>


==== Minus-equals, multiply-equals, divide-equals, and mod-equals ====
==== Minus-equals, multiply-equals, divide-equals, and mod-equals ====
Line 288: Line 313:
Identifiers should also be meaningful, while maintaining practicality. If calculating the sum of a set of numbers, <code>sum<code> is better than <code>cumulativeTotal</code>, but <code>s</code> might be too short.
Identifiers should also be meaningful, while maintaining practicality. If calculating the sum of a set of numbers, <code>sum<code> is better than <code>cumulativeTotal</code>, but <code>s</code> might be too short.


== Using the Displayer with Variables ==
== System.out ==
This section is about printing to the console using <code>System.out.println();</code>.
It is often useful (and necessary) to view the output of your program, especially when you are just getting started or when you are debugging.  Java provides a way to do this.  System.out is a static member (don't worry about what this means for right now) which contains various methods which allow programmers to output text to the console. Two commonly used methods are System.out.print() and System.out.println().  The first allows you to print text without a line break, and the second inserts a new line after every call.  


Using System.out.println() is extremely simple, though C/C++ programmers may find it cumbersome to type up. The method println() takes one parameter, the variable you wish to print out.
Using System.out.println() is extremely simple, though C/C++ programmers may find it cumbersome to type up compared to simply typing printf(). The method println() takes one parameter, the variable you wish to output, and writes it to the console.


<code>System.out.println( myInt )</code>
<source lang="java">System.out.println( myInt );</source>


You can also print out multiple variables on the same line:
You can also print out multiple variables on the same line:
<code>System.out.println( false + " " + 54 )</code>
 
<source lang="java">System.out.println( false + " " + 54 );</source>


Note that this won't work for two literal numeric values:
Note that this won't work for two literal numeric values:
<code>System.out.println( 54 + 32 )</code>. The plus sign would be mistaken for the addition operator for adding numeric values. So to print out "5432", you would have to type:
 
<code>System.out.println( 54 + "" + 32 )</code>
<source lang="java">System.out.println( 54 + 32 );</source>.  
 
The plus sign would be mistaken for the addition operator for adding numeric values. So to print out "5432", you would have to type:
 
<source lang="java">System.out.println( 54 + "" + 32 );</source>


Now you can do calculations and print the result! For example, say you want to print 6*6*6*6. Here is the code:
Now you can do calculations and print the result! For example, say you want to print 6*6*6*6. Here is the code:
<pre>
<source lang="java">
public class Multiplying
public class Multiplying
{
{
Line 313: Line 343:
   }
   }
}
}
</pre>
</source>


== Compiling and running your program ==
== Compiling and running your program ==
Line 322: Line 352:
If, when running, it reports "invalid class file", the compiler might not have created a file. It should have given an error message at compile time.
If, when running, it reports "invalid class file", the compiler might not have created a file. It should have given an error message at compile time.


== Asking the user ==
== User Input ==


The first way to get user input is from the keyboard without using the swing gui. You must first import the Scanner package first like so. <code>import java.util.Scanner;</code> Once you have done that you will have to create a Scanner object. <code>Scanner scan1 = new Scanner(System.in);</code> Finally after the user has entered the input asked for you retrieve using your Scanner object. For example if we wanted a string as input we could use the following code.  
The first way to get user input is from the keyboard without using the swing gui. You must first import the Scanner package first like so. <code>import java.util.Scanner;</code> Once you have done that you will have to create a Scanner object. <code>Scanner scan1 = new Scanner(System.in);</code> Finally after the user has entered the input asked for you retrieve using your Scanner object. For example if we wanted a string as input we could use the following code.  
<pre>
<source lang="java">
import java.util.Scanner;
import java.util.Scanner;
Public class GettingStringInput
Public class GettingStringInput
Line 334: Line 364:
       Scanner scan1 = new Scanner(System.in);
       Scanner scan1 = new Scanner(System.in);
       System.out.print("Please enter a string: ");
       System.out.print("Please enter a string: ");
       yourinput = scan1.nextLine()
       yourinput = scan1.nextLine();
   }
   }
}
}
</pre>
</source>


''In order for the following to work properly, you must place the following code on the first line of your .java file. Importing packages will be explained later.''
''In order for the following to work properly, you must place the following code on the first line of your .java file. Importing packages will be explained later.''


<code>import javax.swing.JOptionPane;</code>
<source lang="java">import javax.swing.JOptionPane;</source>


Now, let's go on to asking the user to enter a number and doing calculations on it. Basically: <code>JOptionPane.showInputDialog( null, "Hello, enter something" )</code>. Try putting that in a class (in the main method, of course) and run it. Currently, we can't do anything with it because the value is deleted.
Now, let's go on to asking the user to enter a number and doing calculations on it. Basically: <source lang="java">JOptionPane.showInputDialog( null, "Hello, enter something" );</source>. Try putting that in a class (in the main method, of course) and run it. Currently, we can't do anything with it because the value is deleted.


Because what you enter can consist of letters OR numbers, and any length of them, what is "produced" by that is a String. The following will work: <code>String mine = JOptionPane.showInputDialog( null, "Now I can set a String!" );</code>. Now lets say that after you get the string you want to print it. Just like regularly, add the following line: <code>System.out.println( mine );</code>.
Because what you enter can consist of letters OR numbers, and any length of them, what is "produced" by that is a String. The following will work: <source lang="java">String mine = JOptionPane.showInputDialog( null, "Now I can set a String!" );</source>. Now lets say that after you get the string you want to print it. Just like regularly, add the following line: <source lang="java">System.out.println( mine );</source>.


Now you probably want to be able to enter a number. Java provides a method of changing a '''String''' to an <code>int</code>. It is <code>Integer.parseInt( String_Here );</code>. So lets say you want the user to enter a number and you print it. Do:
Now you probably want to be able to enter a number. Java provides a method of changing a '''String''' to an <code>int</code>. It is <source lang="java">Integer.parseInt( String_Here );</source>. So lets say you want the user to enter a number and you print it. Do:
<pre>
<source lang="java">
int mine = Integer.parseInt( JOptionPane.showInputDialog( null, "Now I can set an int!" ) );
int mine = Integer.parseInt( JOptionPane.showInputDialog( null, "Now I can set an int!" ) );
System.out.println( mine );
System.out.println( mine );
</pre>
</source>


And now, of course, you can do whatever you want with that...
And now, of course, you can do whatever you want with that...
Line 366: Line 396:
}}
}}
<br><br><hr>
<br><br><hr>
<!--[[Topic:Java|Back to Java Main Page]] | [[Introduction_to_Java|Previous Lesson]] | [[Java_Decision_Structures|Next Lesson]]-->
<!--[[Java|Back to Java Main Page]] | [[Introduction_to_Java|Previous Lesson]] | [[Java_Decision_Structures|Next Lesson]]-->
{{1lvlnav|[[Topic:Java|Java]]|[[Introduction to Java]]|[[Java Decision Structures]]}}
{{1lvlnav|[[Java|Java]]|[[Introduction to Java]]|[[Java Decision Structures]]}}


[[Category:Java]]
[[Category:Java]]
[[Category:Learning activities]]
[[Category:Learning activities]]
[[Category:Basics]]
[[Category:Basics]]