Category: Java

How to attach source or Javadoc to Java Enterprise Edition API in Eclipse

Eclipse is a great IDE. When you hover your mouse over a class name or method of the Java SE API you get a contextual help for that class or method. However if you do the same thing over a Java EE class, such as HttpServletRequest you might not get the same effect. This is because there’s is no source or Javadoc attached to that class. To attach the documentation to your J2EE class as well you can follow these steps:

Read more...

How to exclude subversion hidden directories (.svn) using Ant

Many Java developers already know that Ant is a great build tool. Besides a build tool you also need a good version control system to manage the various versions of your code. For this purpose I often use Subversion. Now, there might be time when you need to exclude the Subversion hidden directories from, for example, a backup Ant target you built. To do that you just need to use the following attribute to your zipfileset or other directory-based task:

Read more...

How to select any character across multiple lines in Java

You can do that using the following pattern in the compile static method of the java.util.regex.Pattern class. The pattern is (.|n|r)*? which means: any character (the .) or (the |) n or r. Zero or more times (the *) of the whole stuff.

Example: The following method strips the multiline comments (those between /* and */) from a string passed in and returns the resulting string:

 
import java.util.regex;

// ... other code 

// Strip multiline comments
public void deleteMultilineComments(String subject) {
  Pattern pattern = Pattern.compile("(/\\*(.|n|r)*?\\*/)");
  Matcher matcher = pattern.matcher(subject);
  return matcher.replaceAll("");
}

Note: rn works for Windows systems. n works for Unix-like systems. r works for Mac systems.

Read more...

Java passes EVERYTHING by value!

It’s a common misconception thinking (or worse teaching!) that, in Java, primitives are passed by value and objects by reference. Actually, everything in Java is passed by value as well as object references.

When a parameter is passed by value, an actual copy of it is really passed so that any change made will have only a local effect. For example:

   
public static void main(String[] args) {
  int a = 0;
  increment(a);
  System.out.println(a); //it prints 0 so increment didn't work as expected
}

public static int increment(int a) {
  ++a;
  System.out.println(a); //it prints 1
  return a;
}

As you can see the change made to the parameter passed to increment, that is a, affects only the local copy of it. This proves that Java passes primitives by value.

Read more...