Basic Java Language: Difference between revisions

wikademia>Geonautika
wikademia>Wikademia
m Text replace - '[[Topic:' to '[['
 
(27 intermediate revisions by 7 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 30: Line 30:
A class with ''public'' modifier is visible by all other classes. Class with no modifier has package level protection. It means that only other classes within the same package can see it.  
A class with ''public'' modifier is visible by all other classes. Class with no modifier has package level protection. It means that only other classes within the same package can see it.  


Member access levels control visibility of member data or methods from it's own class, within package, subclass, or the world. See table below for the summary.  
Member access levels control visibility of member data or methods from its own class, within package, subclass, or the world. See table below for the summary.  


However, in order to get started without being bogged down by choosing one, just declare all of your classes as <code>public</code>. The idea behind protection is that, if only the class itself can make changes to the data stored within itself, the other parts of the program do not need to know where the data is coming from or how it is stored. This is great for two reasons, firstly, it is easy to rewrite the structure of a class without changing the external application, and secondly it allows the class to make assumptions about the data, and do slightly less exception handling. You should know that if your code tried to break the protection of a class, the java compiler will stop and report an error.
However, in order to get started without being bogged down by choosing one, just declare all of your classes as <code>public</code>. The idea behind protection is that, if only the class itself can make changes to the data stored within itself, the other parts of the program do not need to know where the data is coming from or how it is stored. This is great for two reasons, firstly, it is easy to rewrite the structure of a class without changing the external application, and secondly it allows the class to make assumptions about the data, and do slightly less exception handling. You should know that if your code tried to break the protection of a class, the java compiler will stop and report an error.
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 69: Line 66:


Comments are written using two forward slashes  
Comments are written using two forward slashes  
<pre>// This is a comment</pre>
<source lang="java">// This is a comment</source>
Comments can be written at the end of a line  
Comments can be written at the end of a line  
<pre>System.out.println("I love comments"); // This is also a comment</pre>
<source lang="java">System.out.println("I love comments"); // This is also a comment</source>
Comments can also be written on multiple lines by starting with '''/*''' and ending with'''*/'''.
Comments can also be written on multiple lines by starting with '''/*''' and ending with'''*/'''.


Line 90: Line 87:
</source>
</source>


is called a '''javadoc comment'''. As a general rule, don't use these unless you mean to run the javadoc program on your code. We won't worry about these kind of comments for now.
is called a '''[[Wikipedia:Javadoc |Javadoc comment]]'''. These comments are used to generate documentation for your code, and they generally appear at the beginning of a class or a method definition.  A special program (also named javadoc) can be used to automatically create documentation from the Javadoc comments, usually in the form of a set of HTML files.  It is generally good practice to fully document your code by using Javadoc comments, but it is not required. We will use comments to document and explain our code from now on.
 
We will use comments to document and explain our code from now on.


== Variables ==
== Variables ==
Line 158: 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 176: 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 183: 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.
=== 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?
==== Equals ====
The equals 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.


==== Plus-equals ====
==== Plus-equals ====
Line 225: 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 316: 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 341: Line 343:
   }
   }
}
}
</pre>
</source>


== Compiling and running your program ==
== Compiling and running your program ==
Line 350: 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.
<source lang="java">
import java.util.Scanner;
Public class GettingStringInput
{
  Public static void main(String[]args)
  {
      String yourinput = new String;
      Scanner scan1 = new Scanner(System.in);
      System.out.print("Please enter a string: ");
      yourinput = scan1.nextLine();
  }
}
</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 379: 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]]