Tag Archive for Tutorials

Java Tutorial #0 — Setting up the Netbeans IDE


Topics Discussed: Setting up our IDE.

No source code for this lesson

Java Tutorial #1 — “Hello World”, Simple i/o


Topics Discussed: In the most abstract fashion possible, I explain what we need to include and write to output text to the screen using java.

Source Code Available Here


In this video we talk a little bit about the structure of a normal java file.
Essentially, every java file (while we’re learning) will start with the words:

public class *filename*{

}//end class anything after // is considered a comment

The basic idea behind this line is that the compiler needs to know the name of the class in which things are being executed. We’ll talk a bit more about what the public means in this statement.


public static void main(String args[]){
//contents of main

}

The primary confusion from this statement is that it’s a LOT of different stuff all in one place. An access modifier, lifetime modifier, command line arguments and other stuff. For now the only thing that you need to know about this statement is that it denotes where the main part of your program will be executing. There will be times when we operate outside of ‘main’, but that won’t be for some time.


Including and setting up Scanner:


import java.util.Scanner; // at the top of the program
Scanner input = new Scanner(System.in);

This code includes an external library called “Scanner” which is used to take in input from our user. The code where we say ‘new’ allows us to use the word input as a way to take in user data. We’ll talk more about how this works a lot later in the tutorials.

Declaring variables are done like this:


Type Name;
(examples)
int itemCost;//an integer with the name itemCost
char c; // A character with the name "c"-- mind you, this character CAN store characters other than the letter C, as C is JUST a name

Variables are declared to store some kind of data, and the type of data they can store is based on how they are declared. About I mentioned ints, which store integers, or ‘non-decimal numbers’.

Outputting data in java is pretty easy. We use the following code:


System.out.println(a); // This would print out the variable a
System.out.println("Hello World"); // This would output the words "Hello World" exactly as they appear in the quotation marks.
System.out.println("Hello World" + a);//This would output Hello World followed by the contents of a

With that being said, we’ll talk a bit more about the syntax of outputting more later on in the series.

Lastly, we’re going to talk about commenting:


// This is a single line comment, anything you put after this is treated as a 'note' 
/*
this is inside a multi - line comment
* as is this many people put a * at the beginning of each line in a multi-line comment to show that it's a comment to readers of the code
The end of this line ends the multi line comment */

Comments are notes that you and readers of your code can use to better understand the functions being carried out by your code are. I highly recommend commenting code heavily.

Java Tutorial #2 — New data types, variable naming and arithmetic.


Topics Discussed: Introduced new data types, when to use said data types, variable naming schemes, and how the java compiler handles arithmetic

Source Code Available Here

Style
At first I introduce the idea of style, which is going to be important for you to understand and develop as you progress in your learning. The essential bits of style that I want you to understand are as follows:

  • The more comments you have in your code, the better off you’ll be.
  • Every line should be ending with either an {, or a ; at this point in your programming if possible. Splitting output across multiple lines is bad, and I actually won’t be teaching you how to do so.
  • Giving your variables meaningful names will pay dividends later on when you come back to a program that you finished and want to revise. “itemCost” will make a lot more sense to you than “x”.


There are a few popular types of variable naming schemes out there. The most popular two out there are Hungarian notation, and Camelback notation. Hungarian notation isn’t as widely used in java, so I won’t really get into that here. Camelback notation on the otherhand seems to be everywhere on java forums, stackoverflow, etc. The basic idea is that any variable with more than one word in it’s name (itemCost, itemsOnHand, taxRate, etc. etc.) start with a lower-case letter and have the first letter in each word thereafter capitalized for additional readability.


New Data Types
As for new data types, I didn’t introduce every data type out there, but here’s a few that we’ll be using throughout this course

  • int- Integer numbers, somewhat small storage (16 bit in many cases, but can vary in some systems), non-decimal numbers.
  • float- Similar to int, float is the small-version of a number that can hold a decimal point if needed
  • double- Similar to float, but has a larger amount of storage, at the cost of taking up more space (32 bits vs 16 I believe)
  • char- A variable that holds a single character
  • String- A variable that holds a string of characters, whitespace included. Can hold multiple words.
  • The items below are used slightly less than the above but many are still very useful

  • short- Similar in part to int, but with even less storage
  • long- The exact opposite of short, same idea as int but with more storage.
  • unsigned (char/int/long/short/float/ double)- These can tend to hold larger numbers than their non-unsigned counterparts, however these variables cannot have a negative value applied to them.


Order of Operations
In java the order of operations is as follows:

  1. Parenthesis
  2. Multiplication / Division (equal priority, evaluates left to right).
  3. Addition and Subtraction (equal priority, evaluates left to right).

Due to the nature of how exponents are calculated in java (see: using a function), they are not considered in the order of operations. The code we can use to calculate some arithmetic is as follows.


int x=6, y=7;
System.out.println(x*y); // this would output 42
System.out.println(6*7); //this would also output 42
x+=6; // adds 6 to the current value of x, making it 12
int k = x-y; // assigns a value of 5 to k

Java Tutorial #3 — Simple calculations, bank interest problem.


Topics Discussed: Using java to compute simple calculations, such as bank interest.

Source Code Available Here

Homework: Write a ‘financial goal’ calculator, this calculator can take in a variety of inputs so long as it provides the unknown inputs via equation / logic. Example: allow input for Time invested / rate / how much money you want in the end — determine starting amount of money. Or Starting money, rate, and goal money, determine how long it would take. Etc. If you need help with this formula, or with posting your code to ideone, please let me know.

Compound operations
A compound operation is any time where we’re doing in one statement what might have otherwise taken more than one operation to state. There are actually 3 operations in this lesson that I would consider to be compound operations for varying reasons, lets take a look at each of them.

  1. double principle = input.nextDouble();
  2. The reason that I consider this to be a compound operation is because it would be more basic to have this as two statements, stated something like this:
    double principle;  principle = input.nextDouble();
    But as you can see, we are able to declare this in one statement.

  3. rate /= 100;
  4. The reason this is a compound operator is because of the special /= arithmetic operator. There are actually a few of those as follows:

    
    +=, -=, /=, *=, 
    

    All of these are handled in the same way. When you append them to a variable they have this basic syntax: “variable =variable(operation) number;”

  5. System.out.println("\nThe total amount of money in the account after: " + Time + " years is: " + (principle * (1+rate*Time)));
  6. The reason why this is a compound operation should be pretty apparent. Rather than using a variable named “total” to store the total amount of money, we’re actually computing it using math in the println statement.


Java Tutorial #4 — Working with the debugger: Errors happen!


Topics Discussed: Using the built in debugger to show us what is happening within our programs

Source Code Available Here

In this lesson we look at some of the most common errors that we’ll be running into throughout learning to code.

Common error messages:

; expected
This one is fairly simple it means that at some point you left out a semicolon
} expected
This is the same basic idea as above.

Using the built-in-debugger:
Using the debugger to better understand how our programs are running behind the scenes will teach us a lot about how the program acts, but also how our code handles things. To run the debugger, go up to the debug menu, and simply select “step into / step over”

Below is a cheat sheet on what each thing in the debugger means.


Step over- Go to the next line (and execute it)
Step over expression- Step over individual expressions within a statement
Step into: Go into a method
Step into next method:  Run everything to the next method.
Run to cursor: Compile normally until when they insertion point is reached.

Java Tutorial #5 — Calculating seconds


Topics Discussed: Using what we’ve learned so far to calculate how many seconds are in a user-defined amount of time

Source Code Available Here

In this lesson I show you guys the power of using compound operators, as well as including a good amount of variables in a single print statement.
Compound operators
Throughout this lesson I combine a lot of statements in order to avoid using a ‘total’ variable, here’s the example:


       hours += (days*24); //line 1
       minutes += (hours*60);// line 2
       seconds += (minutes*60); // line 3

These three lines do the following things:
Line 1: Starts by taking the current value of hours and adds the value of days * 24 (meaning that days * 24 = number of hours in a day). So in one statement we count the number of hours in a day, and add that value to days
Line 2: Like the above, we are converting “downward”. We multiply hours by 60 and add the total to minutes. For reference this adds the amount of hours in days, and the amount of hours we had to begin with
Line 3: Similarly to the lines above, this takes minutes and converts / adds them to seconds.


Without compound statements the code would look something like this:


       days = days * 24;
       hours= hours + days;
       hours = hours *24;
       minutes = hours + minutes;
       minutes = minutes * 60;
       seconds = seconds + minutes;


Maximum combination
As you can see the above doesn’t do anything to help us out. There is another way we could have done this… but it’s a bit more contrived. With a little bit of our calculator we can learn that there are 86,400 seconds in a day, 3600 seconds in an hour, and 60 seconds in a minute. Thus we can get rid of everything but the println statement.


System.out.println("The number of seconds in " + days + " days " + hours + " hours " + minutes + " minutes and " + seconds + " seconds is: " + ((days*86400)+(hours*3600)+(minutes*60)+seconds));

This sort of coding is technically proper, but can be confusing when you’re using more complex variables, so it’s generally avoided.

Using a total variable
Although I avoided using one here, there are times where it will be inappropriate to change the values of variables so we’ll declare a total variable to hold all of our variables. The code would to use a total variable in place of our existing variables would look like this:


       total += (days*86400);
       total += (hours*3600);
       total += (minutes*60);
       total += seconds;

You’ll notice that instead of using our existing variables we use total to hold the value of each converted variable.

Java Tutorial #6 — Intro to if/else logic


Topics Discussed: If/Else logic and structure, if “conditionals”

Source Code Available Here

If statements
An if statement has two essential elements, the condition under which it will run (the conditional) and the payload that it will run when the condition is true. Let’s examine each part in a bit more depth:

If conditional: The if conditional is the part of the if statement where we tell the if under which conditions it will be operating. Here’s an example of an if conditional:


     if ( a ==7 ){
          //do stuff here
     }

In this case the contents of the brackets will be executed under the condition that the variable a is equal to 7. In the event that it’s not, nothing will happen here, however if you added the code:

     else{
          //do stuff
     }

You would have the option to add something to happen when a did NOT equal 9.

Boolean conditionals
The basic idea behind a statement evaluating to either ‘true’ or ‘false’ like the above conditions is known as ‘boolean’ logic. With that being said, there are things called ‘boolean operators’ that allow us to compare our variables to other constructs. The main boolean operators we will be using throughout these videos are as follows:


<     // Less Than
>     // Greater than
<=    // Less than or equal to
>=    // Greater than or equal to
!     // Not or is not
!=    // Is not equal to (very similar to above)
==    // is equal to
||    // Or
&&    // And
true  // will evaluate to true
false // will evaluate to false

Using the above statements we can make complex comparisons with relative ease, like this:

if (a < =6 && a > b || a < c && a > x){
     //do stuff
}
else{
     //do other stuff
}

In the next lesson we talk about boolean variables which always evaluate to either true or false. But what is true or false, and how to if statements actually resolve themselves?

If resolution
One of the more misunderstood areas of if statements is how they work internally, and the basic idea is something like this. If a statement evaluates to 0, then it is false, if a statement evaluates to 1, it is true. Let me show you an example where you can overlook this, then one where it’s in your face.


int a = 1;
if ( a ==1 ){ //this evaluates to 1, or true
     //do stuff
}

In this case, the contents being if (1) doesn’t really matter all that much. But in the following example, it might make sense why I’m teaching this at all:

int a =6, b=7, c=8;

if (c> b > a){ if 6 < 7< 8
     System.out.println("Expected output");
}
else{
     System.out.println("Unexpected output");
}

In this case the ‘unexpected output’ would appear on our screen, but why? Remember how a few lessons ago I mentioned that arithmetic evaluates from left – to – right in cases where items have the same precedence? That’s exactly what’s happening here. We are comparing c(8) to b(7) and seeing if c is > b. In this case c > bis true, so c > b becomes “1″ (true). The remaining statement is 1 > a(where a is equal to 6), therefore the entire thing evaluates to 0, because 1 is less than 6. The proper way to write the above statement would be something like this:

if (c > b && c >a){
   //do stuff
}

Java Tutorial #7 — Nested If / else structure and logic

*Note*: My apologies for the volume being somewhat screwed up, Starcraft II turned up microphone boost on its own. This gets fixed in a few videos.

Topics Discussed: The structure behind using nested if statements effectively and how easy it is to get them confused!

Source Code Available Here

Nested if structure
In this video I give you a fairly simple example as to why we should avoid nested if statements whenever we possibly can. The primary reason behind this is because they syntax is overwhelming, and it simply becomes very difficult to read / understand.

The syntax of a nested if is exactly the same as a normal if / else statement, except that it takes place in the ‘payload’ of an existing if / else statement.


There isn’t really too much to write up about this lesson, as it built off of what we covered in the lesson before now. Just watch your syntax and you should be able to grasp this almost immediately.

Java Tutorial #8-1 / 8-2 — Using math functions with if logic

Apologies about this being a two-part video, AND for my mic volume being weird, in future videos this is fixed. I’ll consider re-recording this later


Topics Discussed: Using math functions with if-based logic to choose the output of a program

Source Code Available Here

8-2 Here


Topics discussed: Same as above

Source Code Available Here

In these videos I talk a little bit about java.lang.Math; An include that allows us to do some simple mathematical calculations in our code in conjunction with the if-statements we’ve been talking about.


java.lang.Math functions

There are a LOT of different constructs in the java.lang.Math library, but the ones we use in this lesson seem to be the most common of them. Raising a number to a power, and taking the square root of a number. The code for each of these is as follows: (assuming you have the import in your code)


Math.pow(numberOrVariable, powerRaisingTo);
Example:
Math.pow(x, 3); // raises x to the 3rd power.

Math.sqrt(x); //Takes the square root of x.

Java Tutorial #9 — Boolean logic / operators


Topics Discussed: Boolean Logic / Operators

Source Code Available Here

HomeWork Available Here


Boolean operators
Boolean operators are variables which have two states, “true” or “false” (default is false if you use a simple declaration). These can be used in a variety of ways, but are most typically seen when you need to confirm that something happened in an if statement or a loop (in later lessons). Here’s an example:


int empPay1=0;
boolean isChanged;//ischanged defaults to false
System.out.println("Enter the income for employee 1 that is greater than 0.");
empPay1= input.nextInt(); // Enter pay

if (empPay1 > 0){// if the value is > 0, meaning it's been changed
     isChanged=true;
}

if(isChanged){//if the value has been changed (by the if above)
     System.out.println("empPay has been changed");
}
//You could just use an else here, but instead you could use the following:

if(!isChanged){
     System.out.println("empPay has not been changed");
}


In the above example I show that booleans can be used in place of the standard if conditionals and used as a simple true / false that is set as part of another conditional. At present these must seem convoluted, but in the future when our variables change around a bit more it will make more sense to use these than other pieces of code.