Java

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

0

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

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

0

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

Share

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

0

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 :

Share

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

1

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

Share

Playing with the For loop in Java…

3

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.

Share

Binding your buttons to your activity, the easy way!

5

OK, so you have several buttons on your view, all linked into the same activity. Sounds simple enough, you probably have something that looks like the following :

Share

Overriding and Overloading, a n00bs explanation…

1

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 :

Share

Static Imports, how they could and should be used

1

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.

Declaration Rules in Java

0

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.

Share

Android or Standard Java; Mapping your XML onto POJOs easily, and vice versa

0

I’ve listed this post under Android, but to be honest this could apply to both J2SE and J2EE, its not really specific to Android but it was part of a requirement I was working with for a recent Android project.

The problem I had, was that I was getting an XML String as a response from a web service call. The String contained one long String representation of an XML object and I needed to get some data out of that. I could have manipulated the String manually and substring’d out what I required, but that would be incredibly poor and I would likely face verbal punishment from my peers.

Share
Go to Top