Compound Assignment Operators

There are various compound assignment operators, however it is only necessary to know the 4 basic compound assignment operators for the exam, being as follows:

  1. += (Addition compound)
  2. -= (Subtraction compound)
  3. *= (Multiplication compound)
  4. /= (Division compound)

Essentially, they’re just a lazy way for developers to cut down on a few key strokes when typing their assignments. Consider the following examples that I’ve created to demonstrate this:

package operators;

public class AssignmentsOperator
{
    public static void main(String[] args)
    {
        int x = 5;

        // This is the "longhand" way of adding 5 to x
        x = x + 5;
        // You could use the compound assingment as follows, to achieve the same outcome
        x += 5;


        // Lets look at the other 3...
        // This...
        x = x - 1;
        // ...is the same as
        x -= 1;

        // This...
        x = x * 10;
        // ...is the same as
        x *= 10;

        // This...
        x = x / 10;
        // ...is the same as
        x /= 10;

    }
}

That is it! Any suggestions, please let me know!

Happy coding.

Static members…

Statics are a rather strange beast, they belong to no instance of a class, they have no fixed abode, other than their class..

Consider the following example :

package declarations;

public class StaticMembers
{
    private static String message = "hello";
    private String instanceMessage = "hello from the instance!";
    
    
    public static void main(String[] args)
    {
        // You "can" create a new instances and call the static member, but its a bit redundant....
        StaticMembers staticMembers = new StaticMembers();
        System.out.println(staticMembers.message);

        // ..Since you can just call it directly, as statics don't belong to any instances
        System.out.println(StaticMembers.message);
        
        // You can't do this, since how would the static know which "copy" of the instance method to get?
        System.out.println(instanceMessage);
        
        // ..But you can do this, since you have an instance..
        System.out.println(staticMembers.instanceMessage);
        
    }
}

Statics don’t belong to any instance, they belong to the class itself. So there is only ever one copy of a static member (method or variable). Statics can’t ever access an instance variable directly, why not? Think about it, if a static wants to obtain an instance member variable, there may be hundreds, how would it know which one to get? You can however, declare and initialise an instance member from a static, and then access its members, as we’ve done in the example above.

Take my example, and have a play with it, statics are actually quite straightforward once you understand how they behave, but be careful, the exam will try and trick you out with statics accessing instance members directly!

Happy coding!

Local Variables, as far as the SCJP is concerned

Local variables are variables that are declared locally, funny that eh? This one should be nice and easy, lets have a look at a quick example :

package scope.localvariables;

public class LocalVariables
{
    private String instanceString;

    public void doSomething()
    {
        // local variable called 'localS', initialised
        String localS = "hello";
        // Another initialised local variable, with the final modifier so it can't be changed once initialised
        final String localS2 = "hello again";

        localS = "I've changed, since I'm not final";

        System.out.println(localS);
        System.out.println(localS2);
    }

    public void doSomethingElse()
    {
        String localS;
        // Compiler won't like this, since you haven't initialised 's' with anything
        System.out.println(localS);
    }
}

Some really easy things to remember, local variables don’t ever get initialised automatically, so you have to do that yourself. The method above, doSomethingElse, the variable gets declared, but never assigned a value. The compiler won’t assign a default value like it does for an instance varible, so the compiler will complain on the line which tries to print the value to system out. So whatever you do, if you declare a local variable but don’t assign it a value, make sure that you DO assign it a value before you try to use it.

Since variables are declared within a method, they can only be accessed, and actually only live for the duration that method is executing. So if you declare a variable inside a method, but try to access it elsewhere, your code will fail to compile since its scope is only available to the method the declaration resides in. Careful of this one, there are a lot of questions in the exam which will try to catch you out with this!

Local variables can take the final modifier if required, so that once assigned a value it can’t be changed.

Also note, that local variables live on the stack, and not the heap.

Lastly, it is possible to have local variables with the same names as instance variables, this is known as shadowing. You’ve probably seen this countless times before without actually realising, since its quite popular with constructors (with may also have local variables)

package scope.localvariables;

public class MyClass
{
    private String name;
    private int age;

    // Overridden constructor, with 2 local variables that shadow instance variables
    public MyClass(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args)
    {
        MyClass myClass = new MyClass("James", 25);
        System.out.println("Name is : " + myClass.name + " Age is : " + myClass.age);
    }
}

Thats it, hope you’ve enjoyed the show folks, please leave comments or improvement suggestions!

Thanks!

Other modifiers, for members…

We’ve already touched upon various modifiers, for classes (both access and non-access), but there are also some more modifiers for members, as detailed here.

We have the following modifiers for members :

  • final – Can’t be overridden
  • abstract – No implementation specified, subclass must implement
  • synchronized – Only a single thread of execution can pass through at a given time
  • native – Implemented by a 3rd party piece of code (C++ for example)
  • strictfp – Enforces foating point precision and doesn’t let the JVM do its own way

To make things easier, you don’t actually need to know how the strictfp or native work for the exam, but you’ll need to be aware of them. Strictfp guarantees precision on floating point calculations (otherwise the JVM implements precision however it feels), and the native is used for external implementations, such as implementing methods in C++.
All you must remember with these, is that the native modifier applies only to methods, but the strictfp modifier applies to both classes and methods. So lets have a look at a brief example then pass aside on these two and focus on the ones that matter.

package modifiers;

// The class can be marked as strictfp too!
public strictfp class NativeAndStrictfp
{
    // A normal method
    public String giveMeAString()
    {
        return "hello";
    }
    
    // strictfp method
    public float giveMeAFloat()
    {
        return 123.123f;
    }
    
    // pretend its abstract, we don't provide implementation so use a semi colon not braces!
    public native String doSomeNativeCodingAndReturnAString();
}

As with classes, the final modifier does the same thing, it states that the particular method can’t ever be overridden in a subclass, simple as that.

The same applies to the abstract modifier, abstract methods are declared with a signature, a return type, an optional throws clause, but are not actually implemented. The first concrete subclass to extend from the class has to override that method and provide its implementation.

Consider the following example :

package modifiers;

// Don't forget, that since we have one abstract method, the whole class must be marked abstract!
public abstract class OtherMemberModifiers
{
    // I'll get inherited, since I'm public, but I can't be overridden.
    public final String giveMeAString()
    {
        return "hello";
    }

    // Remember, semi colon, no braces!!
    public abstract String giveMeAnotherString();
}

class ClassThatExtends extends OtherMemberModifiers
{
    // I'm the overridden abstract method above!
    @Override
    public String giveMeAnotherString()
    {
        return "another string";
    }
}

Remember, abstract methods can’t be private or final, otherwise how would it ever be overridden? Think about it!

Lets cover the synchronized modifiers. Synchronized means that only one thread of execution can pass through that method at a given time, and you can use the modifier just like any other, they can also be marked as final, to prevent subclasses from overriding your implementation. Lets have a look :

package modifiers;


public class SyncModifiers
{
    // Just a synchronized method ;)
    public synchronized String giveMeAString()
    {
        return "hello";
    }

    // I can't be overridden by a subclass
    public final synchronized String giveMeAnotherString()
    {
        return "hello again!";
    }
}

The synchronized modifier can also be used on code blocks, but we’ll cover that more in the threading posts.

Well thats it! I hope I’ve explained things well, if you find any mistakes or want to suggest improvements, please let me know!

Happy coding!

Class Modifiers (non-access)

In addition to class access modifiers, classes can also be marked with non-access modifiers. These modifiers imply rules on a class, but are not necessarily linked to access rights.

The following non-access modifiers are available:

  • final – The class can’t be extended.
  • abstract – The class has to be extended, and can’t be instantiated on its own.
  • strictfp – Ensures that you always get exactly the same results from your floating point calculations on every platform your application runs on. If you don’t use strictfp, the JVM implementation is free to use extra precision where available.

Lets make things easier, its worth knowing what strictfp is, but its not on the SCJP exam so you don’t need to know how to use it, so you can almost brush that aside after remembering the information above.

Final classes can’t be extended / subclassed. Thats great, for those times when you don’t want people extending your classes, mark them private. Take the String class for example, that is private, as they didn’t want developers extending it and altering the way Strings behave, that would cause nightmares for all sorts of applications!

The other non-access modifier is the abstract modifier. There may be times when you don’t want people to instantiate your class. Say that you had a class Car, but you didn’t want people to start creating Car objects all over the place, you want them to extend your Car class and create their own functionality, you might choose to make Car abstract, like the following example:

package declarations;

public abstract class Car
{
    public void doSomething()
    {
        
    }
}

class SportsCar extends Car
{
    public static void main(String[] args)
    {
        // do SportsCar stuff here
    }
}

Don’t forget, that a class can’t be both final and abstract, as the contradict each other, one can’t be subclassed, yet the other must be subclassed, it just won’t work!

We’ll touch more upon abstract classes in the interfaces sections, as interfaces are essentially 100% abstract classes, but more about that later :)

Class Access Modifiers

Class access modifiers define who can see the class, you use it on a daily basis, have a look at the following :

public class ClassAccessModifierExample
{
    public static void main(String[] args)
    {
        // do something!
    }
}

There you go, you said “public class”, thats you saying that this class is public, and anything can access it.

It is important to note, that even though a class may be declared as public, you can still have private members within that class. The class access modifier merely states who can gain access to the class.

There are 3 class access modifiers, in other words there are 3 keywords that you can use :

  1. public – any class can import and use your class.
  2. protected – any class in the same package as yours can import and use your class, additionally, any class that resides in another package, can extend and use your class. This is only really useful for inner classes.
  3. private – no other top level class can import and use your class. This is a bit of an odd situation but is useful for inner classes, detailed in another post.

Those are your 3 keywords, however there is actually a 4 level of access, called default. The default access level doesn’t use a keywork, so it would be used like follows :

class ClassAccessModifierExample
{
    public static void main(String[] args)
    {
        // do something!
    }
}

So our 4th access level is :

  • (default) – also called “package-private”, this class is only visible to classes in the same package.

So what is all the fuss about visibility about? Well it lets classes do various things,such as :

  1. Create an instance of the class
  2. Extend, sublass that class
  3. Access members of that class

One last thing to remember, is that a source file can only ever have one public or default class, it can’t have more than one of those. Also, private and protected can’t be at the top level.

  • You can’t have a private top level class, its useless.
  • You can’t have a protected top level class, since it goes against the principle of the protected access.

Consider the following valid example

// I'm public, and my name matches that of the source file
public class ClassAccessModifierExample
{
    public static void main(String[] args)
    {
        // do something!
    }


    // You can have as many protected classes as you want, accessible
    // to any classes that extend from the top level class, ClassAccessModifierExample
    protected class MyProtectedClass
    {

    }

    // Have as many private classes as you want, they are only accessible to the top level class,
    // ClassAccessModifierExample
    private class InnerClassThatIsPrivate
    {

    }
    
    // Nothing wrong with having a public inner either!
    public class PublicInner
    {
        
    }
}
// Default class here
class TopLevelDefaultClass
{

}

Thats it! If you’ve got any suggestions on how to improve this, please leave a comment :)

Varargs, for those times when you’re not sure how many parameters you’ll have…

As of Java 5, methods are now able to accept from 0 to many arguments. Sounds confusing, but you could actually be using it already without knowing, how about looking at your main methods?

public static void main(String... args)

As we can see above, var args are declared as TYPE… NAMEOFVARIABLE. Lets take a look at a basic example I’ve created :

public class MethodsWithVarArgs
{
    public static void main(String... args)
    {
        // print out various numbers, just 'cos we can
        printNumbers();
        printNumbers(1);
        printNumbers(1, 2, 3, 4);

        // Print out information on various dice.
        printDieTypeAndItsNumbers("Die with no numbers on it");
        printDieTypeAndItsNumbers("Dodgy die that could never exist...", 1);
        printDieTypeAndItsNumbers("D6", 1, 2, 3, 4, 5, 6);
        printDieTypeAndItsNumbers("D9", 1, 2, 3, 4, 5, 6, 7, 8, 9);
    }

    public static void printNumbers(int... numbers)
    {
        for (int i : numbers)
        {
            System.out.println(i);
        }
        if (numbers.length == 0)
        {
            System.out.println("I didn't get passed in anything... :(");
        }
    }

    public static void printDieTypeAndItsNumbers(String dieType, int... numbersOnTheDie)
    {
        System.out.println("Die : " + dieType + " has the following numbers on it...");
        for (int numberOnDie : numbersOnTheDie)
        {
            System.out.println(numberOnDie);
        }
    }
}

As we can see in both methods, both accept a vararg input parameter. We can invoke these methods with no ints, or many ints, the methods are totally accepting of it!

In effect, the varargs are being treated as arrays, but we don’t have the hassle of getting our hands dirty creating the arrays, which is always a bonus.

One important thing to notice, is that you can only ever, EVER have one vararg parameter, and it must be the last one. The following are all invalid:

public static void invalidBecauseMoreThanOneVarArg(String... first, String... second) {}
public static void invalidBecauseVarArgNotAtEnd(String... varargs, String message) {}

For the above, they are invalid, why? Think of it this way, if you had 2 vararg input parameters, how would you know where one ends, and the other begins?

So, feel free to use varargs, but make sure you only have one, and its at the end of all your input parameters.

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!