Java; the for-each loop, perfect for fondling collections and arrays

The for loop is great, but is it really that nice when you want to iterate over an array or collection? You’d have to do something like the following :

import java.util.ArrayList;
import java.util.List;

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        List<String> myList = new ArrayList<String>();
        myList.add("Hello");
        myList.add("James");
        myList.add("Elsey");

        for (int i = 0; i < myList.size(); i++)
        {
            System.out.println(myList.get(i));
        }
    }
}

Works fine doesn’t it? Looks a bit messy doesn’t it? No need for the index since we only ever use it to get the current value out of the list. Lets have a look at the for-each loop (often called the enhanced for loop) and how it can help

for (String s : myStrings)
{
   // do stuff with "s"
}

Essentially, what the for each loop does, is allow you to loop through each item in the collection or array. The above example, in plain English means : “for each String in myStrings, assign it to s and do something with it”.

Now lets look at a real example

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        List<String> myList = new ArrayList<String>();
        myList.add("Hello");
        myList.add("James");
        myList.add("Elsey");

        for (String s : myList)
        {
            System.out.println(s);
        }
    }
}

Thats great! How much cleaner and easier to read is that?! Since there is no boolean expression involved with this type of looping, it is always assumed that the loop will iterate through every item in the array or collection.

Lets have a look at another few examples to get your understanding up to scratch

import java.util.ArrayList;
import java.util.List;

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        List<String> myList = new ArrayList<String>();
        myList.add("Hello");
        myList.add("James");
        myList.add("Elsey");
        for (String s : myList)
        {
            System.out.println(s);
        }
        
        char[] myChars = new char[]{'a','b','c'};
        for (char c : myChars)
        {
            System.out.println("char is : " + c);
        }
        
        int[] myInts = new int[]{1,2,3,4};
        for (int i : myInts)
        {
            System.out.println("int is : " + i);   
        }
    }
}

I hope I’ve explained it well, if I can improve, please let me know!

Happy looping!

The do-while loop, always executes at least once…

As I’ve covered in a previous post regarding the while loop, the do-while, often refered to as the do loop is very similar. Lets have a look at the psuedo code.

do
{
    //do stuff in here
}
while (boolean_expression);

So as we can see, the actual body of the loop gets executed at least once before the boolean expression is ever evaluated. Now lets have a look at a real example :

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        do
        {
            System.out.println("Inside the loop!");
        }
        while (3 > 4);
    }
}

What the above does, is to print out Inside the loop! once, then it checks the boolean expression in the while statement, if it is true then the loop will be repeated, if it is false, in this case it will be since 3 is not greater than 4, then the loop is done and the code will continue.

Thats it really, nothing too fancy here, this loop is really suited to situations where you must do something at least once, but possibly multiple times.

Anything I’ve missed please let me know!

Happy coding.

Using while loops, for when you don’t know how long the piece of string is…

Just another bitesize SCJP post here, looking at the while loop in Java.

There may be times, where you need to continually iterate over a code block for an unknown number of times. What you can do, is to loop through a code block while a condition is true, something else might change that condition, and when this happens, you can exit out of the loop.

In a psuedo-code way, this is how the while loop operates :

while (boolean_expression)
{
  //do stuff here
}

The boolean_expression, as the name suggests must equal a boolean value. All of the following examples are valid

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        int x = 2;
        while (x == 2)
        {
            System.out.println("Inside the loop!");
            x = 3;
        }

        String myString = "James";
        while (myString.equals("James"))
        {
            System.out.println("Inside the loop!");
            myString = "Elsey";
        }

        while (3 > 2)
        {
            System.out.println("You'll only see this once, then we'll break out of the loop");
            break;
        }

        while (true)
        {
            System.out.println("You'll only see this once, then we'll break out of the loop");
            break;
        }

        System.out.println("Done with our looping samples");
    }
}

For the first 2 examples, we check to see if a variable is a certain value, if that is true (in which it is) then we drop into the loop and print out a value. For the first 2 examples, during the first iteration we actually modify that variable, so when the loop ends and we re-check the boolean expression it now evaluates to true, so we don’t drop in for another iteration.

The last 2 examples can be considered as continual, or never-ending loops, since the evaluates will always be true. For example, 3 will always be greater than 2, nothing except the laws of physics and maths can ever change that, true will always be true, always! This means that the loop will continually iterate over and over again, until the end of time or when you pull the plug. The only way to get out of this type of loop is to use the break keyword, this essentially bails out of the loop.

Lets have a look at one more example :

public class MonkeySniffer
{
public static void main(String[] args)
{
int x = 0;
while (x < 10)
{
System.out.println("Inside the loop!");
x++;
}
}
}

This behaviour is very similar to that of the standard for loop, a condition is met and the loop is entered, until that condition can no longer be met.

To be honest, there is very little to the while loop, so I think I’ve covered it all here! If theres anything I’ve missed, please leave me some comments!

Happy coding.,

Playing with the For loop in Java…

The for loop is an extremely flexible and powerful way of iterating over a code block for a set number of times. Generally speaking, this type of loop is great for situations when you need to repeat code for a definitive number of times, for example you know that your shopping basket contains 10 items, so you need to repeat the loop body 10 times, to iterate through each item and print it onto the screen.

In order to use this loop, you must first create the for loop, and then specify the code block that is used for iteration. Lets take a look at a brief bit of psuedo code.

for(initialization; Boolean_expression; update)
{
   //Statements
}

So there are 3 things that happen inside the for loop delcaration, lets have a look at those too.

  • Initialisation – This is where you can setup any control variables for the loop, normally you would set up an int to hold the position you have in the loop. Technically this part isn’t required, you can just leave it blank, but most of the time you would use it.
  • Boolean expression – This boolean expression is evaluated before each cycle of the loop to determine if another iteration should be performed. Before the body of the loop is executed, this expression is evaluated, if it equals true, then the loop body executes, if it is false, then it goes to the next line of code after the loop body.
  • Update – After the body of the loop has execute, the update section will occur. This allows you to update any of the control variables that were setup in the initialisation block. This part isn’t mandatory, so you could just leave the semi colon.

Enough talk, lets actually have a look at a real life for loop.

public class MonkeySniffer
{
    public static void main(String[] args)
    {
         for (int i = 0; i < 10; i++)
         {
             System.out.println(i);
         }
         System.out.println("Done with the loop");
    }
}

Just before we get into what actually happens, you might be thinking that the “for” line looks a little complex, so how do you know where the initialisation ends and the boolean expression starts? Easy, look for the semi-colon. The semi-colon is the delimiter between the 3 sections.

So lets think about this above example a little more. We can see that during the initialisation block we create a new int called i, and assign it the value of 0. Thats our control variable. Next the boolean expression, before each iteration of the loop we will check to make sure that i is smaller than 10. If i is less than 10, we’ll run the loop body, otherwise we’ll continue to the next line of code after the loop. Since we have just initialised i to be 0, it is of course less than 10 so we run the code body.

The code body will simply output the value of i to the system console. After the code body is complete, we run the update section of the loop, in this case we increment i. At this stage i would then become 1.

That is just one iteration, we then attempt another. Remember from earlier, that we only run the initialisation once. We do this only once, otherwise we would then reset i back to 0 and the loop would never get anywhere. So for the second iteration we evaluate the expression again, in our case we just set i to be 1, so it still matches the expression, and we continue into the code body.

This happens over and over again, until we get to a stage where i isn’t smaller than 10, its actually 11. The boolean expression fails, so we don’t enter the loop body, we’re done, finished, fín, finito. We move onto the next line, being a print of “Done with the loop”.

Lets have a look at another example, this time we’ll count downwards instead of upwards :

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        for (int i = 10; i > 0; i--)
        {
            System.out.println(i);
        }
        System.out.println("Done with the loop");
    }
}

This time, we start off “i” as 10. Then we loop through while “i” is greater than 0. After each iteration we decrement i by 1. So in plain English, we start off at 10, and count downwards by 1 until we reach 0.

Getting the hang of it? Well lets throw some gas on the fire, and count both ways, at the same time :

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        for (int i = 0, j = 10; i < 10 && j > 0; i++, j--)
        {
            System.out.println("i is " + i + " and j is " + j);
        }
        System.out.println("Done with the loop");
    }
}

So what we are doing here, is setting up i as 0, and j as 10. Then while both i is less than 10, and j is greater than 0, continue with the loop. After each iteration, increment i, and decrement j. During each iteration we print out the current value of i and j.

Avoid the continuous loop..

As I said earlier in the post, the statements inside the for loop declaration are not mandatory, you could choose not to provide them. Since you don’t provide a boolean expression, the loop will never know when to exit, so will continue over and over again, have a look at the following :

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        for (;;)
        {
            System.out.println("Someone make me a cup of tea!");
        }
        // the below is unreachable, since the above is a continuous loop
        // System.out.println("Done with the loop");
    }
}

Of course, its not very pretty, but it does the job. There may be times when you do need to keep repeating something continuosly, but personally the following option is far cleaner :

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        while (true)
        {
            System.out.println("Someone make me a cup of tea!");
        }
        // the below is unreachable, since the above is a continuous loop
        // System.out.println("Done with the loop");
    }
}

Further Reading
Oracle Tutorial on the for loop

Overriding and Overloading, a n00bs explanation…

This is easily one of the most confusing concepts to a n00b, but to be honest its relatively simple. The most confusing part is that both start with the letter ‘O’. You’ll really need to understand this if you plan to get anywhere as a programmer, as you can bet you’ll be asked “what is the difference between overriding and overloading” during a technical interview.

Heres a brief heads up on what each one means, to get us started :

  • Overriding – Your a subclass, you inherit some of your parent classes methods, but you don’t quite like them, so you override them with your own implementation. (Or, you are a concrete class extending an abstract class, you’re forced to implement the abstract methods so this is technically overriding them. More on this later)
  • Overloading – You have several methods that have the same method name and return parameter, but take different input parameters.

So what is the difference between the two?
Overriding is when a class provides its own implementation of a method which is inherited from its superclass, or when a concrete class implements abstract methods from its abstract superclass. Overloading is when two or more methods have the same name, but different input parameters.

Each deserves their own explanation, so I’ll tackle these in separate posts.

Static Imports, how they could and should be used

One of the new features of Java 5 is the static import, its quite simple in nature. You have probably done something like the following many times before :

public class Runner
{
    public static void main(String[] args) 
    {
        System.out.println("hello");
        Math.max(1,2);                
    }
}

Nothing too complex, you’re refering to static methods on the System and Math classes. If you use a lot of static methods from other classes, you might decide that typing the class name is wasted effort. In this case we can use a static import.

The static import allows you to import the Math and System classes, and then you can call their static methods without having to reference the class name, such as :

import static java.lang.Math.*;
import static java.lang.System.*;

public class Runner
{
    public static void main(String[] args)
    {
        out.println("hello");
        max(1,2);
    }
}

So as you can see, since we’ve imported the class as a static import, we no longer need to reference the class name before calling a static member.

Of course, there are some drawbacks from taking this approach. Say for example you are performing static imports from multiple classes, that coincidently happen to have methods with the same signature (names and input parameters), how does the class behave in such situation? Consider the following :

package com.test.static1;

public class StaticClassOne 
{
    public static String hello()
    {
        return "hello";
    }
}

package com.test.static2;

public class StaticClassTwo
{
    public static String hello()
    {
        return "hello";
    }
}

package com.test;

import static com.test.static1.StaticClassOne.*;
import static com.test.static2.StaticClassTwo.*;
import static java.lang.System.*;

public class Runner
{
    public static void main(String[] args) 
    {
        out.println(hello());               
    }
}

From this example, we are performing 2 static imports, the static method which we are referencing appears in both imports, so the compiler is unable to know which one it should be using, you would get the following compiler error

reference to hello is ambiguous, both method hello() in 
com.test.static2.StaticClassTwo and method hello() 
in com.test.static1.StaticClassOne match

This does leave room for error, and no developer is perfect. This makes me side slightly towards not using static imports unless absolutely necessary, or in situations where I can be sure there won’t be a conflict. Personally, I actually find it easier to prefix static methods with their class names, so I can immediately see which class the static member belongs to. Continue reading “Static Imports, how they could and should be used”

Declaration Rules in Java

Another one of my short and sweet posts in my SCJP study guide section. This one is quite straightforward, so we’ll keep it quick, since I know you’d much rather be facebooking or watching cats do strange things on youtube…

Declaration rules, in regards to the class files themselves, meaning what you can and can’t do. Consider the following simple example:


public class MonkeySniffer
{
   public static void main(String[] args)
   {
      System.out.printf("I smell a Gibbon!");
   }
}

Thats a simple class that will just print out some text. Notice that I didn’t include any package or import statements, as they are completely optional. Also note that the java.lang.* package is imported automatically, so you don’t need to manually import String for example.

Here are some other things that you must take into consideration when declaring your source files.

  1. If you have a package statement, it must be the first “code” line in the source file (you can have comments above it though).
  2. If you have any import statements, they must come after the package statement (or at the start of the file if there is no package statement) and must come before the class declaration.
  3. Package and import statements will apply to all classes in the source file, whether you like it or not.
  4. A source file can only have one package statement, but you can have as many imports as you require.
  5. A source code can only have one public class.
  6. A file can have more than one non-public class; for example you can declare private inner classes, this might be useful if you have a POJO that is exclusively used in your class.
  7. If the source file contains a public class, the name of the source file must match (in my example above, since I have a public class called MonkeySniffer, the source file must be named MonkeySniffer.java).
  8. If your source file doesn’t have a public class, i.e., it has only private classes, then there are no naming restrictions on the source file.

Have a look at the following example, it covers some of the above points.

// You can make comments before the package statement if you wish
package com.jameselsey.zoo;

/*
    Import statements (if there are any) must come after the package
    and before the class declaration.
 */
import java.util.ArrayList;
import java.util.List;

public class MonkeySniffer
{
    public static void main(String[] args)
    {
        List<String> myList = new ArrayList<String>();
        myList.add("Gibbon");
        System.out.println("I smell a " + myList.get(0));

        MonkeyInners monkeyInners = new MonkeyInners();
        System.out.println(monkeyInners.inners);
    }
}

class MonkeyInners
{
    String inners = "This is an inner!";
}

So there you have it, brielfy touched on the declaration rules (regarding classes). Next stop should be Class Access Modifiers, check out my SCJP/OCJP page for more details.

As always, comments greatly welcomed!

Happy coding :)

Identifiers and JavaBeans

Identifiers are what we use to identify parts of our code, whether this is a class, method or a variable. There are some ground rules on the names we can give to these identifiers, and it is good to understand the ground rules regarding these.

There are 3 levels, or aspects of identifiers, and are summarised as follows

Legal Identifiers – Java has keywords which the compiler uses, and also other rules on what can be used as an identifier, so in order to get your code compiling (and hopefully running too) you’ll need to make sure the names you choose for your variables/classes/methods are legal, more on this below

Suns’ Java Code conventions – Technically, you only really need to adhere to the legal identifier rules, but Sun has its own conventions on identifiers and it is good practice to follow suit. You should really familiarise yourself with these and try to follow their conventions where at all possible.

JavaBeans naming standards – A further set of recommended indentifier rules. Once again you’re not forced to follow these, but it is good practice to do so, and makes your code more clear and readable to other users.

As I mentioned above, you only have to follow the legal identifier naming rules, but it is good practice to follow the conventions in place as it will make your code a lot neater and easier to read for others. Think of it like this, if you need some help with your coding, and you post some samples to a forum, you’ll get much better responses if people can understand what your code is doing.

Legal Identifiers

OK, so legal identifiers, your variable names will either be legal (this is good!) or illegal (Bad, very bad, compiler will throw its toys out of the pram). In order to be a legal identifier, you must follow the following rules

  1. First letter must be a letter (a, b, c etc), or a currency character ($ for example), or one of the connecting characters such as the underscore (_)
  2. First letter must NOT be a number
  3. After the first character, things get more relaxed, and you are able to use any combinations of letters, numbers, currency characters or connecting strings (underscores etc)
  4. You can’t use a Java keyword as an indentifier, this would make it illegal
  5. Identifiers are case sensitive, that means that the variable myVariable is different to MYVARIABLE

Here are some perfectly legal identifiers

  • String _s;
  • String $s;
  • String ______s;
  • String _$;
  • String this_isAnIncredibly_long_but_perfectly_valid_identifier;

And here are some illegal identifiers, using these will throw an error so memorise the rules and steer clear!

  • String ::;
  • String s#
  • String .myString;
  • String 1s;
  • String -s;

Suns’ Java Code Conventions

Wouldn’t it be great if every Java developer was writing code that followed a set of rules for naming conventions? That would be ideal wouldn’t it? Well in the real world its not going to just happen, but Sun have taken a good step toward achieving this by releasing the Java Code Conventions. This is a short, brief set of guidelines that Sun has produced to help steer developers onto a best practice track of naming our identifiers. It recommends some of the following approaches

Classes
For naming your classes, Sun recommend that you start off with a capital letter, and if you have multiple words then you concatenate them making the first letter of each word a capital, a term often refered to as CamelCase. Classes should also typically be nouns, being names of things, the following are good examples

  • Person
  • Student
  • TextBook

Interfaces
Interfaces should follow the same rules as classes, except the name should typically be an adjective instead of a noun, this helps a coder to indentify them as an interface or a contract easier. A few good examples are

  • Runnable
  • Drawable
  • Serializable
  • Throwable

Methods
The first letter of the method name should be lower case, then the usual camelCase rules should apply, some examples are as follows

  • getColor
  • isAvailable
  • doSomething

Variables
Same as with methods, the first letter should be lower case, then camelCase. Some examples are as follows

  • myString
  • myCar
  • player
  • studentReferenceNumber

Constants
Contants should be named in upper case, using the underscore as the connecting character between words. Constants are created by declaring the variable as static and final. Some examples are as follows

  • HOST_NAME
  • PORT_NUMBER
  • MAX_WIDTH

JavaBeans Naming Standards

When you become more involved in your Java development, you will most likely come across the notion of JavaBeans, these are like objects which have instance properties. Typically these properties will be set as private, and you will be using accessor methods to obtain or set them.

Imagine that you have a class called Person, which may have properties such as name and age. The indentifiers I’ve already mentioned just now follow the Sun code convention, however you may wish to make them private, meaning you will most likely need to provide accessor methods, which would follow the Sun conventions, such as

getName
setAge

Ideally, for setting a variable you should create a method prefixed with set, and for getting a variable you should prefix with get.
With booleans, is it good practice to prefix with is, such as isAvailable

Summary

So there you have it, I’ve hopefully explained the basics that you need to know for identifiers. Just remember that your identifiers must at least be legal, but it is also good practice to follow the Sun and JavaBeans naming conventions where at all possible. Please see the following links for further reading. Any comments/suggestions greatly appreciated!