Tag Archive for 'scjp'

Page 2 of 2

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
  • Character for values: \u0000 (0) ÷ \u007f (127)
  • Byte and Integer for values: -128 ÷ 127

Generics

Mixing generics with legacy code

List<String> words = 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 as List<String> but Integer objects was retrieved) – this code is unsafe
  • generic code is only for the compiler purposes; JVM knows nothing about what really the List holds
  • at runtime both legacy and Java 5 code (with generics) look the same, like pre-generic version
List<String> words = new ArrayList<String>();
System.out.println(words instanceof List<String>);   // WON'T COMPILE

The above code won’t compile since all instances of a generic class have the same runtime class, regardless of their actual type parameters.

Instead, you should do as below:

List<String> words = new ArrayList<String>();
System.out.println(words instanceof List);   // OK

This is also worth a look:

Collection<String> words = new ArrayList<String>();
List<Integer> numbers = new ArrayList<Integer>();
System.out.println(words.getClass() == numbers.getClass()); // produces "true"

Continue reading ‘Generics’

Collections – sorting and searching

Sorting

In order to sort a Collection, one should use java.util.Collections class as follows (assuming ArrayList will be used):

List<String≫ words = new ArrayList<String>();
... //populate list of words 
Collections.sort(words);

It’s similar with arrays of objects.

In the above mentioned example the List contained obects of String type. Shall an own object type be used, special rules of sorting must be defined with Comparable or Comparator interfaces.

Continue reading ‘Collections – sorting and searching’

Assertions in Java

assert Expression1 : Expression2;
  • Expression1 is asserted to be true; otherwise AssertionError (that shouldn’t be handled) is thrown
  • Expression2 allows to produce some additional information
  • Expression2 MUST result in a value – it generates a String message
  • allow testing during the development and debugging
  • are disabled at runtime by default
  • can be enabled using -ea or -enableassertions flags and selectively disabled using -da or -disableassertions flags, e.g:
    • java -ea -da:MyClass NotMyClass – enable in general but disable for MyClass
    • java -ea -da:net.dobrzanski.util... MyClass – enable in general but disable for all classes from net.dobrzanski.util package and any of its subpackages
    • java -ea -dsa MyClass, which is shorter version of java -enableassertions -disablesystemassertions MyClass – enable in general but disable in system classes
  • DO NOT USE to validate arguments to public methods
  • DO NOT USE to validate command line arguments
  • USE to validate arguments to private methods
  • USE to validate that particular code block will never be reached (use assert false; in that case)
  • assert can be used as a key word (as of Java 1.4) or as an identifier, but never both at the same time
  • Examples:

    Shorter version:

    private void doSth() {
       ...
       assert (a < b);
       // in there, a is lower than b 
       ...
    }

    Longer version:

    private void doSth() {
       ...
       assert (a < b) : "a=" + a + ", b=" + b;
       // in there, a is lower than b 
       ...
    }

Collection classes in Java

Collections are very important on SCJP exam. It’s useful to remember the following…

collections thumb Collection classes in Java

Continue reading ‘Collection classes in Java’

Java: main method declaration

It’s good to remember that there are a few ways of defining the main() method in Java 5:

public static void main(String[] args) {}

or

public static void main(String args[]) {}

or

public static void main(String... args) {}

Sometimes, we don’t care and remeber of basic stuff, which can result in worse score on the exam icon smile Java: main method declaration

Useful links on SCJP

I’ve found a couple of links that may be useful while preparing to SCJP. Take a look at them, if you wish:

Should you have some other useful links, don’t hesitate to show me them (by replying to this post).

Java: overriding and overloading

Overriding and overloading are common concepts of Java and occur often on SCJP exam. Although I know the rules that apply for them, I happen to think twice (or more) on questions dealing with them. Thus, it’s a good idea to keep the following rules in mind…

Overriding

  • applies ONLY to inherited methods
  • is related to polymorphism
  • object type (NOT reference variable type) determines which overriden method will be used at runtime
  • overriding method MUST have the same argument list (if not, it might be a case of overloading)
  • overriding method MUST have the same return type; the exception is covariant return (used as of Java 5) which returns a type that is a subclass of what is returned by the overriden method
  • overriding method MUST NOT have more restrictive access modifier, but MAY have less restrictive one
  • overriding method MUST NOT throw new or broader checked exceptions, but MAY throw fewer or narrower checked exceptions or any unchecked exceptions
  • abstract methods MUST be overridden
  • final methods CANNOT be overridden
  • static methods CANNOT be overridden
  • constructors CANNOT be overridden

Overloading

  • overloading can take place in the same class or in the subclass
  • overloaded methods MUST have a different argument list
  • overloaded methods MAY change the return type (in case argument list is different)
  • overloaded methods MAY change the access modifier
  • overloaded methods MAY throw new or broader checked excpetions
  • reference type determines which overloaded method will be used at compile time
  • constructors MAY be overloaded
  • methods adjustment in connection with overloaded method’s arguments:
    • you cannot widen and then box (int -> Long)
    • you can box and then widen (int -> Object, via Integer)
    • you can combine var args with either widening (byte -> int) or boxing (int -> Integer):
      • widening is over boxing
      • widening is over var args
      • boxing is over var args

Finally, a few notes on polymorphism:

  • a refenrence variable is of an unchangeable type, but can refer to a subtype object
  • a single object can be referred to by reference variable of many differnet types (however, they MUST be the of same type or supertype of the object)
  • reference type determines which method will be called

Also, keep that in mind:
Reference type determines which overloaded method is used at compile time.
Object type determines which overriden method is used at runtime.

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 you know nothing about SCJP, read about it on the official SCJP website by Sun; there’s a lot of usefult information. By and large, it revises your knowledge of J2SE, currently on ver. 5.

So a couple of months ago I started readnig this book: SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) by Kathy Sierra and Bert Bates. I think it’s great though it takes much time to read it – with analysis and testing of all those examples presented there, not mentioning about things I’ve never come across during my ‘Java developer’ part of life icon wink Sun Certified Java Programmer Anyway, I recommend that book if you want to prepare for that exam.

While reading the book I made a lot of notes which now are not easy to search and read… So, I’ve decided I’d publish my notes, examples and thoughts regarding SCJP stuff so I have them in once place and they’re also accessible for others. So prepare for upcoming posts icon wink Sun Certified Java Programmer