Archive for October, 2008

Initializing an object by reference

October 21, 2008

As everyone knows, in Java objects are passed to methods by reference (the only exclusion is String). But if the reference is null, the method does not know where to return the object.

So following code produces ‘Exception in thread “main” java.lang.NullPointerException’:

	public static void main(String[] args) {
		User u = null;
		initializeUser(u);
		System.out.println(u.getId());
	}

	private static void initializeUser(User u) {
		u = new User(1L);
	}

more, if you change the code to

	public static void main(String[] args) {
		User u = new User(2L);
		initializeUser(u);
		System.out.println(u.getId());
	}

	private static void initializeUser(User u) {
		u = new User(1L);
	}

The main method prints 2. Why the user isn’t initialized?