The Conditional (ternary) operator, cleaning up if-else assignments since 1996…

The conditional operator, or ternary operator as it is otherwise known is a great way for assigning variables based on boolean tests. For example you may have seen the following :

public class MonkeySniffer
{
    public static void main(String[] args)
    {

        int x = 5;
        String s;

        if (x < 10)
        {
            s = "Its less than 10";
        }
        else
        {
            s = "its greater than 10";
        }
        System.out.println(s);
    }
}

Pretty simple right? However that if-else statement is a bit messy considering all we’re doing is checking a condition and then using the output of that to assign a literal to our String reference.

A ternary operator allows us to perform the conditional check AND the assignment all in one line, it looks a bit like this in its psuedo code format

condition ? value if true : value if false 

Lets modify the above sample to use the ternary operator. In plain English, we say that s is going to be assigned from either the true or the false condition based on the condition.

public class MonkeySniffer
{
    public static void main(String[] args)
    {

        int x = 5;
        String s;
        s = x < 10 ? "Its less than 10" : "its greater than 10";
        System.out.println(s);
    }
}

How much neater is that?! What happens is, the condition is evaluated, i.e., the “x < 10" part. If this equates to true then we assign s the first value, if its false, we assign s the second value. That is pretty much all there is to it, lets have a look at some other examples, paste the following into your IDE and have a play. [sourcecode language="java"] public class MonkeySniffer { public static void main(String[] args) { int x = 5; String s; s = x < 10 ? "Its less than 10" : "its greater than 10"; System.out.println(s); s = x == 5 ? "x is 5" : "x is not 5"; System.out.println(s); s = (x > 0 && x < 10) ? "bigger than zero, but less than 10" : "smaller than 0 or bigger than 10"; System.out.println(s); } } [/sourcecode] Thats it, if you've got any comments please let me know! Happy coding! Further Reading :
Wikipedia conditional operator

Looping in Java, a brief look at the various loops and how they can be applied

One of the great features of any programming language is the ability to repeat blocks of code, sometimes indefinately, sometimes until a certain condition is met, or for a set number of iterations.

Luckily, Java comes with several flavours of loops, let have a brief look at our options

  • The “for” loop – The for loop is generally used when you know in advance how many iterations the loop must execute. The for loop enables you to setup a repeatable code block with access to the index(es)
  • The “for-each” loop (also known as the enhanced for loop) – Introduced in Java 5, the enhanced for loop is primarily used for iterating through arrays
  • The “while” loop – A boolean expression is evaluated, if the outcome is true, then the code in the following block will be executed, and the expression will be evaluated again. This cycle will continue until the expression evaluates to false.
  • The “do-while” loop – This loop is very similar to the while loop. However, one drawback of the while loop is that it will only execute if the expression evaluates to true. What if you wanted to run the iteration always once to begin with, and then start checking for further iterations? Well we have some news, the do-while loop saves the day.

I’ve linked each of the above into a separate post, please have a look at those, I’ve tried to explain it as much as I can in accordance to the SCJP exam guidelines.

Happy coding!

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 :)