Thursday, 28 July 2011

Java: Comparison and Comments

Often, you'll need to compare 2 variables to each other to decide what to do next, such as a statement like (In pseudo code):

if (currentValue is larger than baseValue) { Lower currentValue }

Comparison statements result in a boolean value (either true or false), so in the above example, if currentValue > baseValue, True is returned, otherwise, False.

To compare 2 strings, say "test string" and "test string 2", we use the .equals() function. For ease, lets put these strings inside variables, test_1 and test_2, at which point we have:

if ( test_1.equals(test_2) ) { ... }

But for other things, numerical values, we can use (some) normal math operators:

if ( a == 2 ) ... Use 2 equals to test for equality. This is because a single equals sign is already used for assignment

if ( a != 2 ) ... The exclamation point in front of the equals means "not", so this statement only returns false if 'a' holds the value '2'

if ( a > 2 ) ... This is simply the greater than operator

if ( a < 2 ) ... Likewise, this is the simple less than operator if ( a <= 2 ) ... This, as you can guess, means less than, or equal to if ( a >= 2 ) ... And lastly, this is the greater than/equal to


Comments are used in the source code of a program as...commentary. It allows a programmer to go back to earlier work and get the gist of a line or paragraph without having to read it, or allows another programmer to do the same. Place "//" somewhere on a line to make the rest of the line a comment.

int i = 9; // This variable holds the number of employees....

If you want a comment spanning more than 1 line though, surround it with "/* ... */"

/* this is a
multi line comment
Normally used for documentation */

Monday, 25 July 2011

Java: Variables (Initializing and Named Constants)

Still technically Monday!

This one will be short, so let's get to it. Last post, I talked about initializing the variables already, but just to clarify, the first time you declare a variable to exist in a program, you need to first name its type, then the variables name. At this point you can either end the statement for now and give it a value later, or immediately give that variable a value.

int x;
String s = "This is a string!";
double g;
g = 9.8;

Note that String is capitalized, while int and double are not. This is because String is not a primitive variable type, it's closer to a char list, with each character in the String being a new char in a new position.

Constant Variables, such as pi, can be declared once as final variables. This stops the variable from being able to change at a later point in the program, and it removes the need to type out "3.1415..." constantly.

final double pi = 3.141592; In the case of pi, cut it off when you get to a desirable accuracy

Now, at any point in the program you can call pi, it will count as the double you finalized it as. If you now try to change the value, the compiler will throw an error at you.

Thursday, 21 July 2011

Java: Variables (Assignment)

Changing the value of a variable, or giving it it's initial value, is known as assignment. Assigning a variable that already has a value overwrites its current value. Doing this changes the value contained by the variable, not the variable itself.

Further, you must declare variables as some type before trying to assign them to let the computer know how to read it. Some simple types are:


int being integer, double (sometimes referred to as floating point numbers) being decimal point numbers, String being a collection of characters, words or otherwise ("program", "asjdfbsf", "23"), char being single characters ('g', 'l') and boolean being a simple True/False value.

int x; //This declares a variable, named "x" to be an integer.
x = 1; //This assigns the value 1 to x.
x = 2; //Without changing the name of the variable x, this is changing its contained value to 2
x= "nope" //This just can't happen. x has already been declared as an integer, and here, we try to assign a string to it. We would need a new variable to do this.

Assignment can happen with expressions (on the right hand side of the equation only, since the left is reserved for the one variable being assigned a value), such as:

x = y*2 + z;

...which itself can use other, already assigned variables. Most of the operators remain the same as they do in regular arithmetic,+, -, /, *, but when we get to it later, we'll see some differences in other functions. However, a useful function not worth putting off is the ability to have a line of code such as:

x = x + 1;

Which adds 1 to the current value of x. (So if x was 3, after the above line, its new value would be 4).

That's all, folks!

Monday, 18 July 2011

Java: Variables (Naming)

Going to start updating Mo and Th just so I can have shorter posts each day. If they seem like too little info per week, or the posts are too long, I'll change to a MWF schedule. We'll see. Anyway...

Variables in Java are given names, allowing statements in programs to refer to them easily. An example of this is:

result = 2 + k;

This places the value attained from 2+k (k itself being another variable), and places it inside the result variable, which can, at this point, be used in another statement. There are few constraints in naming a variable, first of which is, a variable must begin with an upper or lower case letter. For simplicity, give each variable a unique name, though this isn't technically a rule.

As with all text in Java programming, variables are case sensitive, so be careful how you name them! A common way to name variables is to be in lower case, unless there is more than 1 word, such as "myResult", in which case, the second and further words have their first letter capitalized.

Another guideline is to make variables concise and simple to understand. Don't name a variable holding the width measurement of some object "a" or "bottle", just name it "width".

That's all for now, we'll see how these shorter updates work out.

Monday, 11 July 2011

Java: Fundamentals Cont'd

The last thing we have within the iteration statements thus far is the do statement, also known as a do-while loop. This kind of statement begins with "do", and when the body is completed, the "while" is written to give a condition. This forces the body to be completed at least 1 time, since the condition is checked only after each iteration.

do {
} while ( piece.canMoveForward() );

Be careful to always have something within the body change something within the condition, though. If the condition does not change, and it's evaluated as true, the loop will never cease running, and the program will not terminate on its own. This will take up resources on your computer at best, at worst your program will fail to ever complete its task.

Now, say for instance we had a puzzle that could be solved by taking a left turn whenever possible, otherwise moving straight ahead. Now, we don't have the quite-so-simple program as before, which was to just keep moving forward. We need to make a selection. To do so, there is such a thing as an if-else statement.

if ( piece.canMoveLeft() ) {
else {

The else just means if no previous condition is met, take this as the default action.

We would then put this inside a while loop with the destination being reached as the condition. But what if the piece has to move right if there is no left, and only move forward if no other option is available? Now there are 3 options, so we have an else-if portion to our code.

if ( piece.canMoveLeft() ) {
else if ( piece.canMoveRight() ) {
else {

Order does matter, so in the above case, the program will first look for a left turn before trying a right, there is then no danger of a right turn being taken if a left one is available.

That's it for today, see all 0 of you next time.

Sunday, 3 July 2011

Java: Off to a Good Start

I missed last week! But as of yet I have no followers, so I guess it doesn't matter. Moving into Java, since I have an actual basis for writing about it now!

Java is an object oriented programming language. This means that it focuses on using objects (duh) to create apps with. Abstraction is key. Abstraction is basically having a general idea of what constitutes some object in question. Let's use the popular chair example. Everyone knows what a chair is. It's got to have a back (Or its just a stool), a seat and legs (or wheels, just something to elevate it from the ground). Chairs differ greatly from one to the other, color, texture, number of legs, padded or not, adjustable or not etc. However, they're all chairs, and thus the idea of a chair is an abstract concept, as opposed to a specific instance of a chair, "That red school chair".

In much the same way, classes are snippets of code that define a specific object and its general components. These classes are then used to create specific instances of said object in the programmer's code, eliminating the need to create an object wholly from scratch each time you want to use it. Think mass production.

But we need to know how to write this code in the first place, so now we know what abstraction is, and the point of object oriented programming, we should start with the basics.

A program is written through a sequence of statements, composed of functions, classes and function calls. Each statement is further composed of expressions, which are like the building blocks of the language.

Objects and their functions are defined by their class. For example, a chess piece object would have a move function, defined in the general class for pieces. Or more specifically, assume this hypothetical piece class had a function named forward. This function would take no parameters and would simply move the selected piece forward 1 square. To do this, you would need:


"piece." informs the program which specific object to use the function on.
"forward()" informs the program which function is being used, and the empty brackets indicate that it takes no parameters.
";" The semicolon is used at the end of almost every statement, allowing the computer to know when it is complete. Not caring about whitespace, this is the only way to tell.

Suppose now you wanted the piece to move forward several squares, until it could move no further, using only the above function. It would be tedious to type out...


...especially since it would require a different amount of lines depending on where the piece starts, and therefore a different program based on the piece's starting position. We would much rather use an algorithm. In pseudocode (general purpose "coding" that hasn't been fleshed out):

while ( piece isn't at the endpoint )
move piece forward

As you may have guessed, there is a "while loop" present in Java (and a lot of other programming languages). This loop continually executes a statement, or series of statements while some given condition is true. Over each iteration of this loop, the condition is checked again to see if there has been a change.
For the sake of this exercise, assume there is a function available to the piece object, canMoveForward(), which returns a value of true or false depending on whether the piece can move forward or not. Then our loop will look like:

while ( piece.canMoveForward() ) {

Within the brackets directly after "while", we have the condition. In this case, if the piece can move forward. After the condition is an opened curly brace, this opens the set of statements for the while loop to enact if it's condition is true. This allows multiple lines with a clear cutoff point with a closed curly brace. On a newline (purely for aesthetic reasons, it's easier to read this way), we have the statement(s) to enact, in our case, move the piece. Note the semicolon to tell the computer where each individual statement ends. Also note that there is no semicolon after the while loop is closed. Simply closing this is enough to tell the computer that this is where the while statement ends.

Well, that's all for now, longer than I plan to normally do these, but I had to make up for missing a week.