Friday, November 15, 2013

Random Java Tips (1)

This series of blog posts consists of various Java tips and language features that are illusive to normal programmers.

Throwing of exceptions
In Java, there are two types of exceptions, checked exception and unchecked exception. Checked exception, such as FileNotFoundException, must be either caught or re-thrown. However, for unchecked exception, you do not need to do that. But it is still syntactically OK to declare the throwing of them. In fact, you can add "throws X" to any method if X is subclass of Throwable, even if X is an unchecked exception, or if X is an checked exception that is not really thrown at all.

Initialization of arrays
In Java, an array can be declared and initialized at the same time, in the following syntax:
int[] a = new int[] {1, 2, 3, 4}
or
int[] a = {1, 2, 3, 4}  // short-hand of previous one

However, if you can not initialize and designate array size at the same time. I.e. you can not write
int[] a = new int[4] {1, 2, 3, 4}

Syntax for array type
When denoting a variable a of array of type X in Java, you can write either 'X[] a' or 'X a[]'.

For example we can write
int a [] = {1, 2, 3, 4}
But this is not preferred and thought as less readable by most programmers.



No comments:

Post a Comment