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.

Coupling and Cohesion, what you need to know for SCJP…

Coupling and cohesion are two terms that often get mixed up, however they are actually really simple concepts, and the bonus is, they don’t just apply to Java.

Coupling

Coupling, in its purest terms, means “the degree to which one class knows about another class”. If one class uses another class, that is coupling. Coupling is everywhere, but the level of coupling varies.

Consider the following example of a tightly coupled set of classes:

public class TightlyCoupledClass
{
    public static void main(String[] args)
    {
        ExampleClass exampleClass = new ExampleClass();
        exampleClass.message += "James";
        System.out.println(exampleClass.message);
    }
}

class ExampleClass
{
    public String message = "hello ";
}

TightlyCoupledClassuses ExampleClass, therefore there is some coupling. The level of coupling is high as TightlyCoupledClassdirectly alters the message variable on ExampleClass. It’ll compile and run perfectly fine, but if you slip this little nugget into production code, you’re colleagues will bash you for eternity, because its poor design.

Think of it this way, what if ExampleClass was used in hundreds of classes, or what if ExampleClass was maintained by someone else; what would happen if they decide to change the scope of message, or to change its data type? It’ll break anything that uses it, since it is tightly coupled.

From the perspective of TightlyCoupledClass, it needs to get a message, and set a message, it should not care about how ExampleClass maintains that. When a class knows too much about another classes’ implementation, that is also tight coupling.

What we need, is encapsulation, this is another OO concept that shields a classes state and exposes it with accessor methods, meaning that a class can still be coupled, but loosely.

You should, be aiming for loosely coupled classes, lets re-visit the above sample but this time we’ll move from a tightly coupled set of classes, to a loosely coupled set of classes, using encapsulation.

public class TightlyCoupledClass
{
    public static void main(String[] args)
    {
        ExampleClass exampleClass = new ExampleClass();
        String ourUpdatedMessage = exampleClass.getMessage() + "James";
        exampleClass.setMessage(ourUpdatedMessage);
        System.out.println(exampleClass.getMessage());
    }
}

class ExampleClass
{
    private String message = "hello ";

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }
}

Cohesion

Cohesion is another OO concept like coupling, however cohesion refers to the degree in which a class has a single, well defined purpose. If you had a class called Car, it would maintain state such as numberOfWindows, numberOfWheels, and have behaviour (methods) such as drive(), brake(), stop() etc. That would indicate that the class is cohesive, meaning that it serves a single, defined purpose.

Now, exploring a little, if the Car class suddenly decided to have methods such as switchOnTheTV(), or hangTheWashingOut(), then its not really doing Car-like behaviour. If a class is trying to do more than one thing, it is considered a low cohesive class.

Consider the following, highly cohesive class

package ooconcepts;

public class Car
{
    private String make = "Aston Martin";
    private int numberOfWindows = 5;
    
    public void drive()
    {
        // do some driving!
    }
    
    public void brake()
    {
        // slow down!
    }
    
    public void stop()
    {
        // STOP!!!!
    }      
}

Conclusion

These are the important bullet points to take away from this page:

  • Coupling refers to the degree in which one class knows about another, or makes use of another classes’ members
  • Loose coupling is GOOD as classes are well encapsulated to minimise references to each other
  • Tight coupling is BAD because a class shouldn’t know about the workings of another
  • Cohesion refers to the degree in which a class has a single, well defined purpose
  • High cohesion is GOOD as a class does only what it should
  • Low cohesion is BAD because a class is trying to solve everything and not just its specific purposes

Further Reading

  1. Why couplig is always bad
  2. Java Boutique

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!