Yet Another “Java Passes By Reference or By Value”?

This is a classic interview question which confuses novice Java developers. In this post I will use an example and some diagram to demonstrate that: Java is pass-by-value. 1. Some Definitions Pass by value: make a copy in memory of the actual parameter’s value that is passed in. Pass by reference: pass a copy of … Read more

How to Build Your Own Java library?

Code reuse is one of the most important factors in software development. It is a VERY good idea to put frequently-used functions together and build a library for yourself. Whenever some method is used, just simply make a method invocation. For Java, it’s straightforward to manage such a library. Here a simple example in Eclipse. The library will contain only one “add” method for demo purpose.

Step 1: Create a “Java Project” named as “MyMath”, and a simple “add” method under “Simple” class.

Package structure is as follows:

Read more

Declaration, Initialization and Scoping for Java

The following is a summary for showing Java declaration, initialization and scoping. Variables defined in try block are not visible in catch block. You cannot pass parameters when you implement an interface by an anonymous class. Constructors cannot return anything. Not even void. Every enum has a values() method that returns an array of all … Read more

Overriding vs. Overloading in Java

Overriding and Overloading are two very important concepts in Java. They are confusing for Java novice programmers. This post illustrates their differences by using two simple examples. 1. Definitions Overloading occurs when two or more methods in one class have the same method name but different parameters. Overriding means having two methods with the same … Read more

Diagram to show Java String’s Immutability

Here are a set of diagrams to illustrate Java String’s immutability. 1. Declare a string The following code initializes a string s. String s = "abcd";String s = "abcd"; The variable s stores the reference of a string object as shown below. The arrow can be interpreted as “store reference of”. 2. Assign one string … Read more