Tag Archive for tutorial

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 #10 — Loop logic / intro


Topics Discussed: While loops, do_while loops, counter controlled loops, loop syntax, loop scoping

Source Code Available Here


Loops
In this video I discuss two or the most important constructs in the entire language of java. In the next lesson I talk a bit more about for loops, which seem to be used a little more than while and do_while which we discussed here.


While loops
While loops are statements that will be repeated until either a break statement is reached, or until the condition is no longer true. Here’s a few examples of loops using while:


//syntax while(condition){ //do stuff }
//Examples below

int i=0;
while(i < 9){
     //do stuff
     i++; //increment i-- if you remove this statement, the loop will run infinitely.
}

boolean isTrue=true;
i=0; //reset 0 before the loop

while(isTrue){//while the boolean is true
     if(i > 10){
          isTrue = false;
}//end if
     i++; // increment i
}//End loop

i=0;//reset 0 before the loop
while (i < 10){
     System.out.println(i); //output the value of i each time through the loop
     i++; // increment i each time through the loop
}

In the examples above you’ll notice that we always have a ‘way out’ of the loop, that’s because there is a common error known as an ‘infinite loop’ in which your code executes endlessly because your loop is unable to exit.

Do_while loops
Do_while loops are the same basic idea as while loops, except that they execute the contents of the loop once before checking the conditional. These are very useful in making users enter certain values for their input, as seen below:


int aValue=0;
do{ // do these instructions
System.out.println("Enter a value 1 or greater for the variable: ");
aValue= input.nextInt();
}while(aValue < 1);//until this condition is no longer true.


Incrementing numbers
Any number that is of a type that can hold a whole number value can be incremented or decremented. In MOST cases you will be using “post-incrementing” which is seen as varName++; however, there are other ways of incrementing numbers:


++i; // pre-increment
i++; // post-increment (most-common)
--i; // pre-decrement
i--; // post-decrement (common while decrementing)

Each time you hit the statement i++;, you increase the value of i by the value of 1.

Java Tutorial #15.1 / 15.2 — Introduction to and using arrays


Topics Discussed: Arrays, subscripts, iterating through arrays

Source Code Below

15.2

Topics discussed: Same as above

Source Code Available Here
Homework is here


Arrays
Arrays are the most basic multi-variable container made available in java. The syntax is pretty simple, but the implementation can be confusing if you don’t have a programming background. The basic specifications of an array is that it’s a basic, 0-indexed, template’d, data structure that can be created with either explicit values or in an empty state.


int anArray[] = new int[7]; // Creates an array that can hold 7 ints.
for(int i=0; i< anArray.length(); i++){
    anArray[i] = i; // sets the array equal to it's index based off the iteration in a loop.
}

Arrays can be iterated through easily with loops, especially by for loops.

The Subscript
The subscript is the way that we access a certain part of an array. anArray[0] would refer to the ‘first’ (remember, 0-indexed) location in the array. Therefore the subscript in this case would be 0. Changing the subscript from within a loop is fairly common practice in Object oriented programming.

Java Tutorial #17 — Encapsulating programs // including more than 1 file

Topics discussed: Encapsulation by separating methods into new files.
Source Code Available Here


Program encapsulation
The concept of program encapsulation is simple: break things down into their component parts so when something breaks, it’s easy to track, and easier to fix. The more ‘parts’ you break your program into (via methods) the easier this becomes. But as you increase the number of methods, the length of a single file becomes unmanageable and huge. Somewhere around 100-400 lines, a file becomes “hard” to read, so keeping it below that level is optimal (in my opinion) if at all possible.


Adding in additional files
In netbeans we will select a new file, and then simply add a new java class file to an existing project. The only thing that really changes in terms of code is that when we call a method from another file, we need to include the class name in the call to that method. Something like this:

//main.java
//Normal header here

int x=0;
x= HandleX.addfive(x);

//HandleX.java

public class{

public static int addfive(int x){

return (x+5);

}//End method

}// End class

In the example above you’ll notice that the method is called by it’s filename first when we are in another file. This happens because we need to tell the compiler where to find the method that we’re trying to use.

Java Tutorial #18 — Access Modifiers; Working with / around them


Topics discussed: Access modifiers, public, private, static
Source Code Available Here


Access modifiers
Access modifiers are our way of sectioning off our program and making it harder to accidentally use / misuse methods not contained within the calling class. There are 4 access modifiers and they basically work like this:

  1. Public: Public as an access modifier means that the ANYTHING can call on your class / function. This means that anyone / any function can call it for any reason, we’ll see why that’s a problem later on.
  2. Protected: Protected is the exact same as public except that it cannot be called by anything, only things that exist in the same package / class / subclass as where the call originated from.
  3. not specified: Only accepts calls from the class / package and no subclasses.
  4. Private: Only accepts calls from within the class.

  5. Using public as an access modifier
    When we use public as an access modifier, the entire program (or any other program) can call upon our methods / objects if they are familiar with our interface. We might get into external calls at a much later lesson but for now let’s look at internal same-project calls:

    /////  Javafile.java /////
    
    int x= 1, y=7;
    //the syntax to call a public method in another file is methodFile.methodName
    sum = methodFile.sum(x,y)
    
    /////methodFile.java/////
    
    public static int sum(int x, int y){
    return (x+y);//Will return the sum of x+y to Javafile.java
    }
    


    Using private as a modifier
    If you’re in doubt about whether or not you should be using private as a modifier, you should be using private as a modifier. When we get into larger programs in the future with 4 or 5 different files, data will be moving all over the place, and controlling the flow of that data is extremely important. The only way to ensure that nothing gets passed incorrectly is to safeguard methods / classes that we want to keep safe.