Java Tutorial - Part II
Written by pergesu
Graciously hosted by RRFN (www.promodtecnologies.com)
Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.
Table of Contents
-------------------------
1) Brief intro
2) Data types
3) Mathematical operators
4) Relational operators
5) Decision structures
a) If
b) If...else
c) else if
d) switch()
e) A final word about decision structures
6) Loops
a) while
b) do...while
c) for
d) A little more on loops
7) Wrap up
--------------------------
Section 1
Brief Intro
---------------------------
Awesome! Welcome to the next part of the series; glad you're here. If you're reading this, I assume you've already read my first tutorial or have some knowledge of Java. In the last tutorial, you learned how to do basic input and output, and using integers that the user input. You're gonna do some more complex stuff in this tutorial. We'll be looking at control structures, which involve decision structures and loops. To use them, you need to know about mathematical operators and relational operators. Read on...
---------------------------
Section 2
Data types
---------------------------
You learned about integers in the last tutorial. They are not the best data type in the world, because they can only represent integers, and are limited in their range. Sometimes we want to use a decimal, and for this, int is inappropriate. Here's a list of the other primitive data types:
char - A single character
float - A floating point value
double - A floating point value; more precise than float
bool - A boolean value. Either true or false (1 or 0)
Each primitive type has a corresponding parse*() method. So for double, it would be Double.parseDouble(userstring). Try them out in a program.
------------------------------
Section 3
Math ops
-------------------------------
. In all the programming you do, you will do an incredible amount of mathematical operations. If you've ever gone to sixth grade, you should get this without any trouble. You just need to know the different operators there are to use. Here's a table:
Operation Operator Expression
-------------- ------------- -----------------
Addition + a + 7
Subtraction - b - 3
Multiplication * c * d
Division / e / f
Modulus % g % h
In case you don't know, modulus yields the remainder of integer division. Thus 16 % 5 is equal to 1. Standard algebraic order of evaluation applies. First parentheses; then multiplication, division, or modulus; then addition and substraction.
You can easily modify the value of a variable, assuming you want to begin with the current value. Let's say you want to add 6 to num1. You could use:
num1 = num1 + 6;
However, a simpler, more compact way is to use:
num1 += 6;
They do the same thing. You can do that with any mathematical operator: +=, -=, *=, /=, %=.
A way to increment or decrement the value of a variable is with the increment and decrement operators.
a++; // Increases value of a by 1
b--; // Decreases value of b by 1
The above increments the variable after you do something with it, called post-incrementing. You can also increment the variable before you do anything with it- pre-incrementing. To make it more clear, here's a code block.
int num1 = 5;
int num2 = 12;
JOptionPane.showMessageDialog(num1++); // Displays 5, but new value of num1 is 6
JOptionPane.showMessageDialog(num1); // Displays 6
JOptionPane.showMessageDialog(--num2); // Decrements num2, so it is now 12. Displays 12
JOptionPane.showMessageDialog(num2); // Displays 12
------------------------------
Section 4
Relational ops
------------------------------
You will often compare different values in your programming. You do this all the time in real life (Which cup has more coke? Which class period is shorter?). Of course you'll need to use it in programming, too. Relational operators are used to compare values. They don't change any values, they simple return true or false based on the condition. You'll understand when we start writing code. Here's a table of the Java relational operators.
Operator Example Meaning
------------- ------------- ------------
== x == y x is equal to y
!= a != b a is not equal to b
> c > d c is greater than d
< e < f e is less than f
>= g >= h g is greater than or equal to h
<= i <= j i is less than or equal to j
--------------------------------
Section 5
Decision structures
---------------------------------
You're gonna learn about decision structures here. Basically, what these do is determine a different path of execution based on certain conditions in the program. You want to one thing for one input value, and a different thing for a different value.
----------------------------------
Section 5a
If
----------------------------------
The simplest decision structure is the if structure. If a certain condition is true, then do something. Here's a quick example:
// If.java
import javax.swing.JOptionPane;
public class If
{
public static void main(String args[])
{
int num1, num2;
String number1, number2;
number1 = JOptionPane.showInputDialog("Enter the first integer");
number2 = JOptionPane.showInputDialog("Enter the second integer");
num1 = Integer.parseInt(number1);
num2 = Integer.parseInt(number2);
if(num1 > num2)
{
JOptionPane.showMessageDialog("num1 > num2");
}
System.exit(0);
}
}
There's really nothing you haven't learned, except for the if test. Let's examine it a bit:
if(num1 > num2)
What this does is test the condition in the parentheses. If the condition is true, then the code inside the next block (delimited by the curly braces) will execute. If not, then nothing happens. Pretty simple. Note that there's no semicolon after the if test. Don't ever put one there, because then the following code will execute no matter what. Also note the curly braces after it. The code in the curly braces is the code you want to execute if the condition is true. If you only have one statement, as we have here, you may ommit the braces. I included them for clarity in this example.
---------------------------------
Section 5b
If...else
---------------------------------
At some point we might want to do something if the condition is false, as well. We could do this:
// IfIf.java
import javax.swing.JOptionPane;
public class IfIf
{
public static void main(String args[])
{
int num1, num2;
String number1, number2;
number1 = JOptionPane.showInputDialog("Enter the first integer");
number2 = JOptionPane.showInputDialog("Enter the second integer");
num1 = Integer.parseInt(number1);
num2 = Integer.parseInt(number2);
if(num1 > num2)
JOptionPane.showMessageDialog("num1 > num2");
if(num1 < num2)
JOptionPane.showMessageDialog("num1 < num2");
System.exit(0);
}
}
That works just fine, so why do anything else? Well consider this: Each time the program runs through, it checks both conditions. This isn't a problem here, but when we have to test a lot of conditions in larger programs, it becomes quite time consuming! So we have the if...else structure. Check it:
// IfElse.java
import javax.swing.JOptionPane;
public class IfElse
{
public static void main(String args[])
{
int num1, num2;
String number1, number2;
number1 = JOptionPane.showInputDialog("Enter the first integer");
number2 = JOptionPane.showInputDialog("Enter the second integer");
num1 = Integer.parseInt(number1);
num2 = Integer.parseInt(number2);
if(num1 > num2)
JOptionPane.showMessageDialog("num1 > num2");
else
JOptionPane.showMessageDialog("num1 < num2");
System.exit(0);
}
}
Else works sort of the same as if. If the condition in the if test is false, then the stuff following the else statement gets executed (hey, that sound like an if...else!). The same rules for curly braces apply: You need them for multiple statements, ya don't need em for singles. The thing about the if...else is that if the stuff in the condition is true, then it never looks at the else. There aren't two conditions tested. Keep in mind that an else statement must have a corresponding if statement. If you don't have one, the compiler will choke.
---------------------------------
Section 5c
else if
---------------------------------
That if...else thing is pretty cool. But what about if we want to test a whole bunch of conditions? We could use a number of if statements, but then they'd all be evaulated. We'd like to evaluate only as many as we need. This is where the else if comes in handy. Let's see an example, and then I'll explain it a bit.
// ElseIf.java
import javax.swing.JOptionPane;
public class ElseIf
{
public static void main(String args[])
{
int num1, num2;
String number1, number2;
number1 = JOptionPane.showInputDialog("Enter the first integer");
number2 = JOptionPane.showInputDialog("Enter the second integer");
num1 = Integer.parseInt(number1);
num2 = Integer.parseInt(number2);
if(num1 > num2)
JOptionPane.showMessageDialog("num1 > num2");
else if(num1 < num2)
JOptionPane.showMessageDialog("num1 < num2");
else
JOptionPane.showMessageDialog("num2 == num1");
System.exit(0);
}
}
Here's what we're doing... We check to see if num1 is greater than num2. If it is, we say so. If not, we check to see if num1 is less than num2. If it is, then we say so. If it's neither of them, then they must be equal, so we say that. The great thing about this is that if num1 is greater than num2, then it just skips all the other stuff and heads straight to System.exit(). Pretty cool, huh? You can put as many else if's together as you like. The else if works almost exactly like the if. Syntax is else if(condition) { code to execute }.
-------------------------------
Section 5d
switch
-------------------------------
It's possible that we want to perform a certain action for a number of specific values of a variable. We could use a bunch of else if statements together. However, it's a bit cleaner to use the switch structure. Here's an example program:
// Switch.java
import javax.swing.JOptionPane;
public class Switch
{
public static void main(String args[])
{
int num;
String number;
number = JOptionPane.showInputDialog("Enter an integer");
num = Integer.parseInt(number);
switch(num)
{
case 1:
JOptionPane.showInputDialog("Number is 1");
break;
case 6:
JOptionPane.showInputDialog("Number is 6");
break;
case 237:
JOptionPane.showInputDialog("Number is 6");
break;
default:
JOptionPane.showInputDialog("Number is somethin else");
break;
}
System.exit(0);
}
}
Wanna know what this does? Well first off, the variable inside the parentheses of switch() is the variable to test. When you run the program, the structure examines the value of num1. It then compares it to the first case you have listed. The cases are meerly possible values for the variable, it's not a list or anything. If the value is equal to the first condition, then it executes the statements up to the break, and then skips everything else in the structure. If the value does not equal any case, then the code under default: is executed. You don't have to have a default:, it's just nice in case the value matches nothing else.
A couple of important things here. Everything dealing with the switch structure is enclosed in a set of curly braces. Also, each case must be ended with a colon. When a case is true, then all the statements up to the next break executed. This means that if you forget a break, then some code may execute that you didn't want. Of course, you can also intentionally do this. Here's an example of a switch statements with piled up cases:
switch(num)
{
case 6:
case 12:
case 18:
JOptionPane.showMessageDialog("Number is divisible by 2 and 3");
break;
}
If the value of num is either 6, 12, or 18, then the message "Number is divisible by 2 and 3" is displayed.
--------------------------------
Section 5e
Final word
--------------------------------
Remember the syntax of all these structures.
if(condition) { code to execute }
if(condition { code to execute }
else { code to execute }
if(condition) { code to execute }
else if(condition) { code to execute }
else { code to execute }
switch(variable)
{
case value1:
code to execute
break;
}
We also have a few logical operators that can be used in conditions. Here's a table:
Operator Meaning Example
------------- ------------ -------------
&& and j == 10 && h > 6
|| or j == 10 || h > 6
They have two similar but very distinct uses. The and operator (&&), is true if both conditions are true. The or operator (||) is true if at least one of them is true. Examples:
if(j == 10 && h > 6) // Only executes if j equals 10 AND h is greater than 6
JOptionPane.showMessageDialog("j == 10 && h > 6");
if(j == 10 || h > 6) // Executes if j equals 10 OR h is greater than 6
JOptionPane.showMessageDialog("j == 10 || h > 6");
--------------------------------
Section 6
Loops
--------------------------------
You'll often find that you have to do something over and over. It gets pretty cumbersome typing up the same lines of code to do the same thing. Also, you might not know how many times you want to execute a particular statement or code block. This is where loops come in. Loops can also be called repetition structures.
--------------------------------
Section 6a
while
--------------------------------
This simplest loop is the while loop. Everything in the while loop will execute as long as a certain condition is met. A quick example:
// While.java
public class While
{
public static void main(String args[])
{
int num = 0;
while(num < 10)
{
System.out.print("*");
num++;
}
System.exit(0);
}
}
This sets num to 0, and then goes into the loop. The loop continues until the expression in parentheses is false. Since num is less than 10, the code in the block is executed. I increment num each time so that eventually the expression is false, and control continues onto System.exit(). If you don't change the value of the variable that's tested, then the loop continues forever- probably not what you want. Run the program, and you'll see how it all works. Try getting rid of num++ and see what happens.
--------------------------------
Section 6b
do...while
--------------------------------
The do...while loop comes in handy when we want to loop through a block of code at least once. With the while loop, the code is never executed if the expression is false. The do...while loop guarantees that the loop goes through at least one time.
// DoWhile.java
public class DoWhile
{
public static void main(String args[])
{
int num = 0;
String number;
do
{
number = JOptionPane.showInputDialog("Enter 6");
num = Integer.parseInt(number);
} (while num != 6);
System.exit(0);
}
}
The code in the loop executes at least one time, regardless of the value of num. The user is asked to input 6. If that happens, then the program finishes. If not, the user is asked to input 6 until he does so. Compile and run the program to see what I mean.
Sometimes you want a block of code to execute a number of times, but you don't know when you're writing it how many times it should execute. You want the user to determine it. I guess you could ask the user for the number of iterations (times through the loop) to do, and then set up a while loop to do that. However, that's inconvenient for the user. A much better alternative is to use a sentinel controlled loop. A sentinel is a value that tells the loop it should stop. I'll show you an example. It gets a bunch of numbers from the user, and finds the average.
// Sentinel.java
public class Sentinel
{
public static void main(String args[])
{
int num, sum = 0, counts = 0;
String number;
double average;
do
{
number = JOptionPane.showInputDialog("Enter a number (-1 to stop)");
num = Integer.parseInt(number);
sum += num;
counts++;
} while(num != -1);
average = (double) sum / --counts;
JOptionPane.showMessageDialog("Average is " + average);
}
}
This program will continue getting input from the user until he enters -1. We find the average of all the numbers.
You may be wondering about the line
average = (double) (sum / --counts);
First off, the (double) is called a type cast. We are dividing two integers, yet assigning the value to a double variable. We want to make sure that the double variable has double information, so that there's no data loss. When we use (double), sum and counts are temporarily converted to double so that it works smoothly. After the operation, they're int's again. Also, I decrement counts before it gets used. This is because we don't want the sentinel value counting as an iteration of the loop.
--------------------------------
Section 6c
for
--------------------------------
The for loop is another very useful loop. It creates a loop that iterates a certain number of times. The syntax is shown below:
for(initialize; control expression; step expression) { code to execute }
Note that the different parts of the for loop (initialize, control, and step) are separated by semicolons. Don't put a semicolon after the step expression, though.
It might look confusing at first, but it's pretty simple. Here's a quick demo program:
// For.java
public class For
{
public static void main(String args[])
{
for(int i = 1; i <= 10; i++)
JOptionPane.showInformationMessage("This is iteration " + i);
System.exit(0);
}
}
This loop will execute 10 times, and each time will display what iteration it's on. As with all loops, you put whatever code you want to execute inside some curly braces. In all loops again, if there's only one statement, you may ommit the braces.
Examination of the for loop:
for(int i = 1; i <= 10; i++)
int i = i; This declares the variable i, and sets the value to 1
i <= 10; Keep looping as long as i is less than or equal to 10
i++; Increment i for each iteration of the loop
You can use whatever expressions you want. Here are some examples:
for(int j = 65; j > 3; j--)
for(in bubba = 32; bubba < forrest; bubba += 26)
--------------------------------
Section 6d
A little more
--------------------------------
There are two other things that you can use in any loop you write. They are the break and continue statements.
The break statement breaks out of the current loop, and goes onto the code after the loop. An example:
for(int i = 0; i < 10; i++)
{
if(i == 5)
break;
System.out.println(i);
}
This will print out
0
1
2
3
4
and nothing else
The continue statement skips the rest of the code in the loop and continues with the next iteration. An example:
for(int j = 0; j < 10; j++)
{
if(j == 7)
continue;
System.out.println(j);
}
This will print out
0
1
2
3
4
5
6
8
9
So break breaks out of the loop, and continue continues on to the next iteration. Pretty simple.
-----------------------
Section 7
Wrap up
-----------------------
Cool, so we got control structures done in this tutorial. You now have the ability to write much more complex programs. Go ahead and write a bunch of programs before you move on to the next tutorial. In the next one, I'll be going over methods, which are ways of organizing your programs and promoting reuse. If you've got some spare time, head on over to
http://www.promodtecnologies.com to check out some cool stuff. Thanks for reading.
pergesu