Tricky example with polymorphism
Can you predict the output of the following code?
class SubTest extends Test { public int aNumber; public SubTest() { aNumber = 17; } public void doubleANumber() { System.out.println("Inside SubTest.doubleANumber()"); aNumber *= 2; } } public class Test { public int aNumber; public Test() { aNumber = 6; } public void doubleANumber() { System.out.println("Inside Test.doubleANumber()"); aNumber *= 2; } public…
java.util.IllegalFormatConversionException when using System.out.format()
A few weeks ago I described how to format output using System.out.printl()
and System.out.println()
methods…
Try to run the code below:
double avgAge = 245 / 34; System.out.format("Average age is %d.", avgAge);
Without doubts you’ll get an exception thrown at runtime:
Average age is Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source) at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source) at java.util.Formatter$FormatSpecifier.print(Unknown…
Collections – sorting and searching
In order to sort a Collection
, one should use java.util.Collections
class as follows (assuming ArrayList
will be used):
List another object
- the drawback: there’s only one way of sorting
Example of the class implementing Comparable
interface:
class Book implements Comparable { private String title; public String getTitle() { return title; } public void setTitle(String title_p) { title = title_p;…
Generics
Mixing generics with legacy code
List<Stringwords = new ArrayList<String();
words.add("house");
words.add("book");
addSth(words);
private void addSth(List list) {
list.add(new Integer(6));
}
- the above code compiles (but with warnings) and can work fine, at least to the place of addition (if the object was later retrieved from the
List
it could break down, e.g. words would be treated asList<String>
Java: == might work the same as equals()
It’s a rule that ==
is used to compare references, not values. To compare values for equality equals()
method should be used.
However, as of Java 5, you can also use ==
to check if two objects’ values are the same… But it works only for the following wrapper objects, if their primitive counterparts’ values are the same:
- Boolean
- Byte
Formatting output
Usually to print some ouptut you’d use System.out.printl()
or System.out.println()
method. It’s easy to use but you can face some difficulties in providing output formatted in a specific way.
To format output you can use either of the following methods (they work the same)
System.out.format(String format, Object... args)
System.out.format(Locale l, String format, Object... args)
System.out.printf(String format, Object... args)
System.out.printf(Locale l,
Unreachable catch block
Always contruct try-catch blocks in a way that assumes catching Exceptions from more detailed to more generic.
Example
try { String [] tab = null; System.out.println(tab[3]); } catch (Exception e) { System.out.println("Exception"); } catch (NullPointerException e) { System.out.println("NullPointerException"); }
The above presented snippet will cause compilation error:
…Unreachable catch block for NullPointerException. It is already handled by the catch block
Sun Certified Java Programmer
Okay, I’ve been working with Java for a few years now, starting from academia and ending with business solutions. So yeah, I think I can say I know Java and some of those technologies like J2SE, J2EE or J2ME, with their own standards and solutions. Therefore, I’ve decided I’d take Sun Certified Java Programmer (SCJP) in a few months.
If …
What if you extend an abstract class and implement an interface when both define a method with the same name?
Imagine you need to implement a class that extends an abstract class and implements an interface when both define a method with the same name – test().
Example
interface Implementable { public void test(); } abstract class Superclass { public abstract void test(); } public class Test extends Superclass implements Implementable { /* definition of load method(s)..... */ }
The …
Exeptions and Errors in Java
In the diagram below I present the hierarchy of most common Exceptions and Errors:
Object
|
|_ Throwable
|
|_ Error
| |
| |_ AssertionError
| |
| |_ LinkageError
| | |
| | |_ ExceptionInInitializerError
| | |
| | |_ NoClassDefFoundError
| | |
| |_ VirtualMachineError
| |
| |_ StackOverflowError
|
|_ Exception
|
… - 1
- 2