Best java questions in June 2012

Why is processing a sorted array faster than an unsorted array?

1088 votes

Here is a piece of code that shows some very peculiar performance. For some strange reason, sorting the data miraculously speeds up the code by almost 6x:

#include <algorithm>
#include <ctime>
#include <iostream>

int main()
{
    // generate data
    const unsigned arraySize = 32768;
    int data[arraySize];

    for (unsigned c = 0; c < arraySize; ++c)
        data[c] = std::rand() % 256;


    // !!! with this, the next loop runs faster
    std::sort(data, data + arraySize);


    // test
    clock_t start = clock();
    long long sum = 0;

    for (unsigned i = 0; i < 100000; ++i)
    {
        // primary loop
        for (unsigned c = 0; c < arraySize; ++c)
        {
            if (data[c] >= 128)
                sum += data[c];
        }
    }

    double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;

    std::cout << elapsedTime << std::endl;
    std::cout << "sum = " << sum << std::endl;
}
  • Without std::sort(data, data + arraySize);, the code runs in 11.54 seconds.
  • With the sorted data, the code runs in 1.93 seconds.

Initially I thought this might be just a language or compiler anomaly. So I tried it Java...

import java.util.Arrays;
import java.util.Random;

public class Main
{
    public static void main(String[] args)
    {
        // generate data
        int arraySize = 32768;
        int data[] = new int[arraySize];

        Random rnd = new Random(0);
        for (int c = 0; c < arraySize; ++c)
            data[c] = rnd.nextInt() % 256;


        // !!! with this, the next loop runs faster
        Arrays.sort(data);


        // test
        long start = System.nanoTime();
        long sum = 0;

        for (int i = 0; i < 100000; ++i)
        {
            // primary loop
            for (int c = 0; c < arraySize; ++c)
            {
                if (data[c] >= 128)
                    sum += data[c];
            }
        }

        System.out.println((System.nanoTime() - start) / 1000000000.0);
        System.out.println("sum = " + sum);
    }
}

with a similar but less extreme result.


My first thought was that sorting brings the data into cache, but my next thought was how silly that is because the array was just generated.

What is going on? Why is a sorted array faster than an unsorted array? The code is summing up some independent terms, the order should not matter.

You are the victim of branch prediction fail.


What is Branch Prediction?

Consider a railroad junction:

enter image description here Image by Mecanismo, from Wikimedia Commons: http://commons.wikimedia.org/wiki/File:Entroncamento_do_Transpraia.JPG

Now for the sake of argument, suppose this is back in the 1800s - before long distance or radio communication.

You are the operator of a junction and you hear a train coming. You have no idea which way it will go. You stop the train to ask the captain which direction he wants. And then you set the switch appropriately.

Trains are heavy and have a lot of momentum. So they take forever to start up and slow down.

Is there a better way? You guess which direction the train will go!

  • If you guessed right, it continues on.
  • If you guessed wrong, the captain will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.

If you guess right every time, the train will never have to stop.
If you guess wrong too often, the train will spend a lot of time stopping, backing up, and restarting.


Consider an if-statement: At the processor level, it is a branch instruction:

enter image description here

You are a processor and you see a branch. You have no idea which way it will go. What do you do? You halt execution and wait until the previous instructions are complete. Then you continue down the correct path.

Modern processors are complicated and have long pipelines. So they take forever to "warm up" and "slow down".

Is there a better way? You guess which direction the branch will go!

  • If you guessed right, you continue executing.
  • If you guessed wrong, you need to flush the pipeline and roll back to the branch. Then you can restart down the other path.

If you guess right every time, the execution will never have to stop.
If you guess wrong too often, you spend a lot of time stalling, rolling back, and restarting.


This is branch prediction. I admit it's not the best analogy since the train could just signal the direction with a flag. But in computers, the processor doesn't know which direction a branch will go until the last moment.

So how would you strategically guess to minimize the number of times that the train must back up and go down the other path? You look at the past history! If the train goes left 99% of the time, then you guess left. If it alternates, then you alternate your guesses. If it goes one way every 3 times, you guess the same...

In other words, you try to identify a pattern and follow it. This is more or less how branch predictors work.

Most applications have well-behaved branches. So modern branch predictors will typically achieve >90% hit rates. But when faced with unpredictable branches with no recognizable patterns, branch predictors are virtually useless.

Further Reading: http://en.wikipedia.org/wiki/Branch_predictor


As hinted from above, the culprit is this if-statement:

if (data[c] >= 128)
    sum += data[c];

Notice that the data is evenly distributed between 0 and 255. When the data is sorted, roughly the first half of the iterations will not enter the if-statement. After that, they will all enter the if-statement.

This is very friendly to the branch predictor since the branch consecutively goes the same direction many times. Even a simple saturating counter will correctly predict the branch except for the few iterations after it switches direction.

Quick visualization:

T = branch taken
N = branch not taken

data[] = 0, 1, 2, 3, 4, ... 126, 127, 128, 129, 130, ... 250, 251, 252, ...
branch = N  N  N  N  N  ...   N    N    T    T    T  ...   T    T    T  ...

       = NNNNNNNNNNNN ... NNNNNNNTTTTTTTTT ... TTTTTTTTTT  (easy to predict)

However, when the data is completely random, the branch predictor is rendered useless because it can't predict random data. Thus there will probably be around 50% misprediction. (no better than random guessing)

data[] = 226, 185, 125, 158, 198, 144, 217, 79, 202, 118,  14, 150, 177, 182, 133, ...
branch =   T,   T,   N,   T,   T,   T,   T,  N,   T,   N,   N,   T,   T,   T,   N  ...

       = TTNTTTTNTNNTTTN ...   (completely random - hard to predict)

So what can be done?

If the compiler isn't able to optimize the branch into a conditional move, you can try some hacks if you are willing to sacrifice readability for performance.

Replace:

if (data[c] >= 128)
    sum += data[c];

with:

int t = (data[c] - 128) >> 31;
sum += ~t & data[c];

This eliminates the branch and replaces it with some bitwise operations.

(Note that this hack is not strictly equivalent to the original if-statement. But in this case, it's valid for all the input values of data[].)

Benchmarks: Core i7 920 @ 3.5 GHz

C++ - Visual Studio 2010 - x64 Release

//  Branch - Random
seconds = 11.777

//  Branch - Sorted
seconds = 2.352

//  Branchless - Random
seconds = 2.564

//  Branchless - Sorted
seconds = 2.587

Java - Netbeans 7.1.1 JDK 7 - x64

//  Branch - Random
seconds = 10.93293813

//  Branch - Sorted
seconds = 5.643797077

//  Branchless - Random
seconds = 3.113581453

//  Branchless - Sorted
seconds = 3.186068823

Observations:

  • With the Branch: There is a huge difference between the sorted and unsorted data.
  • With the Hack: There is no difference between sorted and unsorted data.
  • In the C++ case, the hack is actually a tad slower than with the branch when the data is sorted.

A general rule of thumb is to avoid data-dependent branching in critical loops. (such as in this example)


Update :

  • GCC 4.6.1 with -O3 or -ftree-vectorize on x64 is able to generate a conditional move. So there is no difference between the sorted and unsorted data - both are fast.

  • VC++ 2010 is unable to generate conditional moves for this branch even under /Ox.

  • Intel Compiler 11 does something miraculous. It interchanges the two loops, thereby hoisting the unpredictable branch to the outer loop. So not only is it immune the mispredictions, it is also twice as fast as whatever VC++ and GCC can generate! In other words, ICC took advantage of the test-loop to defeat the benchmark...

  • If you give the Intel Compiler the branchless code, it just out-right vectorizes it... and is just as fast as with the branch (with the loop interchange).

This goes to show the even the mature modern compilers can vary wildly in their ability to optimize code...

When should null values of Boolean be used?

58 votes

Java boolean allows values of true and false while Boolean allows true, false, and null. I have started to convert my booleans to Booleans. This can cause crashes in tests such as

Boolean set = null;
...
if (set) ...

while the test

if (set != null && set) ...

seems contrived and error-prone.

When, if ever, is it useful to use Booleans with null values? If never, then what are the main advantages of the wrapped object?

UPDATE: There has been such a lot of valuable answers that I have summarised some of it in my own answer. I am at best an intermediate in Java so I have tried to show the things that I find useful. Note that the question is "incorrectly phrased" (Boolean cannot "have a null value") but I have left it in case others have the same misconception

Use boolean rather than Boolean every time you can. This will avoid many NullPointerExceptions and make your code more robust.

Boolean is useful, for example

  • to store booleans in a collection (List, Map, etc.)
  • to represent a nullable boolean (coming from a nullable boolean column in a database, for example). The null value might mean "we don't know if it's true or false" in this context.
  • each time a method needs an Object as argument, and you need to pass a boolean value. For example, when using reflection or methods like MessageFormat.format().

Benefit of Polymorphism

51 votes

When I started to look for the benefits of polymorphism, I found with this question here. But here I was unable to find my answer. Let me tell what I want to find. Here I have some classes:

class CoolingMachines{
    public void startMachine(){
        //No implementationion
    }
    public void stopMachine(){
        //No implementationion
    }
}

class Refrigerator extends CoolingMachines{
    public void startMachine(){
        System.out.println("Refrigerator Starts");
    }
    public void stopMachine(){
        System.out.println("Refrigerator Stop");
    }
    public void trip(){
        System.out.println("Refrigerator Trip");
    }
}

class AirConditioner extends CoolingMachines{
    public void startMachine(){
        System.out.println("AC Starts");
    }
    public void stopMachine(){
        System.out.println("AC Stop");
    }
}

public class PolymorphismDemo {
    CoolingMachines cm = new Refrigerator();
    Refrigerator rf = new Refrigerator();
}

Now here I created two objects in the Demo class and are references of Refrigerator. I have completely understood that from the rf object I am able to call the trip() method of Refrigerator, but that method will be hidden for the cm object. Now my question is why should I use polymorphism or why should I use

CoolingMachines cm = new Refrigerator();

when I am OK with

Refrigerator rf = new Refrigerator();

Is polymorphic object's efficiency is good or light in weight? What is the basic purpose and difference between both of these objects? Is there any difference between cm.start(); and rf.start()?

It is useful when you handle lists... A short example:

List<CoolingMachines> coolingMachines = ... // a list of CoolingMachines 
for (CoolingMachine current : coolingMachines) {
    current.start();
}

Or when you want to allow a method to work with any subclass of CoolingMachines

Case sensitivity of Java class names

41 votes

If one writes two public Java classes with the same case-insensitive name in different directories then both classes are not usable at runtime. (I tested this on Windows, Mac and Linux with several with several versions of the HotSpot JVM. I would not be surprised if there other JVMs where they are usable simultaneously.) For example, if I create a class named a and one named A like so:

// lowercase/src/testcase/a.java
package testcase;
public class a {
    public static String myCase() {
        return "lower";
    }
}

// uppercase/src/testcase/A.java 
package testcase;
public class A {
    public static String myCase() {
        return "upper";
    }
}

Three eclipse projects containing the code above are available from my website.

If try I calling myCase on both classes like so:

System.out.println(A.myCase());
System.out.println(a.myCase());

The typechecker succeeds, but when I run the class file generate by the code directly above I get:

Exception in thread "main" java.lang.NoClassDefFoundError: testcase/A (wrong name: testcase/a)

In Java, names are in general case sensitive. Some file systems (e.g. Windows) are case insensitive, so I'm not surprised the above behavior happens, but it seems wrong. Unfortunately the Java specifications are oddly non-commital about which classes are visible. The Java Language Specification (JLS), Java SE 7 Edition (Section 6.6.1, page 166) says:

If a class or interface type is declared public, then it may be accessed by any code, provided that the compilation unit (§7.3) in which it is declared is observable.

In Section 7.3, the JLS defines observability of a compilation unit in extremely vague terms:

All the compilation units of the predefined package java and its subpackages lang and io are always observable. For all other packages, the host system determines which compilation units are observable.

The Java Virtual Machine Specification is similarly vague (Section 5.3.1):

The following steps are used to load and thereby create the nonarray class or interface C denoted by [binary name] N using the bootstrap class loader [...] Otherwise, the Java virtual machine passes the argument N to an invocation of a method on the bootstrap class loader to search for a purported representation of C in a platform-dependent manner.

All of this leads to four questions in descending order of importance:

  1. Are there any guarantees about which classes are loadable by the default class loader(s) in every JVM? In other words, can I implement a valid, but degenerate JVM, that won't load any classes except those in java.lang and java.io?
  2. If there are any guarantees, does the behavior in the example above violate the guarantee (i.e. is the behavior a bug)?
  3. Is there any way to make HotSpot load a and A simultaneously? Would writing a custom class loader work?

  • Are there any guarantees about which classes are loadable by the bootstrap class loader in every JVM?

The core bits and pieces of the language, plus supporting implementation classes. Not guaranteed to include any class that you write. (The normal JVM loads your classes in a separate classloader from the bootstrap one, and in fact the normal bootstrap loader loads its classes out of a JAR normally, as this makes for more efficient deployment than a big old directory structure full of classes.)

  • If there are any guarantees, does the behavior in the example above violate the guarantee (i.e. is the behavior a bug)?
  • Is there any way to make "standard" JVMs load a and A simultaneously? Would writing a custom class loader work?

Java loads classes by mapping the full name of the class into a filename that is then searched for on the classpath. Thus testcase.a goes to testcase/a.class and testcase.A goes to testcase/A.class. Some filesystems mix these things up, and may serve the other up when one is asked for. Others get it right (in particular, the variant of the ZIP format used in JAR files is fully case-sensitive and portable). There is nothing that Java can do about this (though an IDE could handle it for you by keeping the .class files away from the native FS, I don't know if any actually do and the JDK's javac most certainly isn't that smart).

However that's not the only point to note here: class files know internally what class they are talking about. The absence of the expected class from the file just means that the load fails, leading to the NoClassDefFoundError you received. What you got was a problem (a mis-deployment in at least some sense) that was detected and dealt with robustly. Theoretically, you could build a classloader that could handle such things by keeping searching, but why bother? Putting the class files inside a JAR will fix things far more robustly; those are handled correctly.

More generally, if you're running into this problem for real a lot, take to doing production builds on a Unix with a case-sensitive filesystem (a CI system like Jenkins is recommended) and find which developers are naming classes with just case differences and make them stop as it is very confusing!

Java Synchronization Not Working as Expected

34 votes

I have a "simple" 4 class example that reliably shows unexpected behavior from java synchronization on multiple machines. As you can read below, given the contract of the java sychronized keyword, Broke Synchronization should never be printed from the class TestBuffer.

Here are the 4 classes that will reproduce the issue (at least for me). I'm not interested in how to fix this broken example, but rather why it breaks in the first place.

Sync Issue - Controller.java

Sync Issue - SyncTest.java

Sync Issue - TestBuffer.java

Sync Issue - Tuple3f.java

And here is the output I get when I run it:

java -cp . SyncTest
Before Adding
Creating a TestBuffer
Before Remove
Broke Synchronization
1365192
Broke Synchronization
1365193
Broke Synchronization
1365194
Broke Synchronization
1365195
Broke Synchronization
1365196
Done

UPDATE: @Gray has the simplest example that breaks thus far. His example can be found here: Strange JRC Race Condition

Based on the feedback I've gotten from others, it looks like the issue may occur on Java 64-bit 1.6.0_20-1.6.0_31 (unsure about newer 1.6.0's) on Windows and OSX. Nobody has been able to reproduce the issue on Java 7. It may also require a multi-core machine to reproduce the issue.

ORIGINAL QUESTION:

I have a class which provides the following methods:

  • remove - Removes the given item from the list
  • getBuffer - Iterates over all the items in the list

I've reduced the problem down to the 2 functions below, both of which are in the same object and they're both synchronized. Unless I am mistaken, "Broke Synchronization" should never be printed because insideGetBuffer should always be set back to false before remove can be entered. However, in my application it is printing "Broke Synchronization" when I have 1 thread calling remove repeatedly while the other calls getBuffer repeatedly. The symptom is that I get a ConcurrentModificationException.

See Also:

Very strange race condition which looks like a JRE issue

I think you are indeed looking at a JVM bug in the OSR. Using the simplified program from @Gray (slight modifications to print an error message) and some options to mess with/print JIT compilation, you can see what is going on with the JIT. And, you can use some options to control that to a degree that can suppress the issue, which lends a lot of evidence to this being a JVM bug.

Running as:

java -XX:+PrintCompilation -XX:CompileThreshold=10000 phil.StrangeRaceConditionTest

you can get an error condition (like others about 80% of the runs) and the compilation print somewhat like:

 68   1       java.lang.String::hashCode (64 bytes)
 97   2       sun.nio.cs.UTF_8$Decoder::decodeArrayLoop (553 bytes)
104   3       java.math.BigInteger::mulAdd (81 bytes)
106   4       java.math.BigInteger::multiplyToLen (219 bytes)
111   5       java.math.BigInteger::addOne (77 bytes)
113   6       java.math.BigInteger::squareToLen (172 bytes)
114   7       java.math.BigInteger::primitiveLeftShift (79 bytes)
116   1%      java.math.BigInteger::multiplyToLen @ 138 (219 bytes)
121   8       java.math.BigInteger::montReduce (99 bytes)
126   9       sun.security.provider.SHA::implCompress (491 bytes)
138  10       java.lang.String::charAt (33 bytes)
139  11       java.util.ArrayList::ensureCapacity (58 bytes)
139  12       java.util.ArrayList::add (29 bytes)
139   2%      phil.StrangeRaceConditionTest$Buffer::<init> @ 38 (62 bytes)
158  13       java.util.HashMap::indexFor (6 bytes)
159  14       java.util.HashMap::hash (23 bytes)
159  15       java.util.HashMap::get (79 bytes)
159  16       java.lang.Integer::valueOf (32 bytes)
168  17 s     phil.StrangeRaceConditionTest::getBuffer (66 bytes)
168  18 s     phil.StrangeRaceConditionTest::remove (10 bytes)
171  19 s     phil.StrangeRaceConditionTest$Buffer::remove (34 bytes)
172   3%      phil.StrangeRaceConditionTest::strangeRaceConditionTest @ 36 (76 bytes)
ERRORS //my little change
219  15      made not entrant  java.util.HashMap::get (79 bytes)

There are three OSR replacements (the ones with the % annotation on the compile ID). My guess is that it is the third one, which is the loop calling remove(), that is responsible for the error. This can be excluded from JIT via a .hotspot_compiler file located in the working directory with the following contents:

exclude phil/StrangeRaceConditionTest strangeRaceConditionTest

When you run the program again, you get this output:

CompilerOracle: exclude phil/StrangeRaceConditionTest.strangeRaceConditionTest
 73   1       java.lang.String::hashCode (64 bytes)
104   2       sun.nio.cs.UTF_8$Decoder::decodeArrayLoop (553 bytes)
110   3       java.math.BigInteger::mulAdd (81 bytes)
113   4       java.math.BigInteger::multiplyToLen (219 bytes)
118   5       java.math.BigInteger::addOne (77 bytes)
120   6       java.math.BigInteger::squareToLen (172 bytes)
121   7       java.math.BigInteger::primitiveLeftShift (79 bytes)
123   1%      java.math.BigInteger::multiplyToLen @ 138 (219 bytes)
128   8       java.math.BigInteger::montReduce (99 bytes)
133   9       sun.security.provider.SHA::implCompress (491 bytes)
145  10       java.lang.String::charAt (33 bytes)
145  11       java.util.ArrayList::ensureCapacity (58 bytes)
146  12       java.util.ArrayList::add (29 bytes)
146   2%      phil.StrangeRaceConditionTest$Buffer::<init> @ 38 (62 bytes)
165  13       java.util.HashMap::indexFor (6 bytes)
165  14       java.util.HashMap::hash (23 bytes)
165  15       java.util.HashMap::get (79 bytes)
166  16       java.lang.Integer::valueOf (32 bytes)
174  17 s     phil.StrangeRaceConditionTest::getBuffer (66 bytes)
174  18 s     phil.StrangeRaceConditionTest::remove (10 bytes)
### Excluding compile: phil.StrangeRaceConditionTest::strangeRaceConditionTest
177  19 s     phil.StrangeRaceConditionTest$Buffer::remove (34 bytes)
324  15      made not entrant  java.util.HashMap::get (79 bytes)

and the problem does not appear (at least not in the repeated attempts that I've made).

Also, if you change the JVM options a bit, you can cause the problem to go away. Using either of the following I cannot get the problem to appear.

java -XX:+PrintCompilation -XX:CompileThreshold=100000 phil.StrangeRaceConditionTest
java -XX:+PrintCompilation -XX:FreqInlineSize=1 phil.StrangeRaceConditionTest

Interestingly, the compilation output for both of these still show the OSR for the remove loop. My guess (and it is a big one) is that delaying the JIT via the compilation threshold or changing the FreqInlineSize cause changes to the OSR processing in these cases that bypass a bug that you are otherwise hitting.

See here for info on the JVM options.

See here and here for information on the output of -XX:+PrintCompilation and how to mess with what the JIT does.

Difference between java.util.Random and java.security.SecureRandom

33 votes

My team got handed over some server side code (in Java) that generates random tokens and I have a question regarding the same -

The purpose of these tokens is fairly sensitive - used for session id, password reset links etc. So they do need to be cryptographically random to avoid somebody guessing them or brute force them feasibly. The token is a "long" so it is 64 bits long.

The code currently uses the java.util.Random class to generate these tokens. The documentation (http://docs.oracle.com/javase/7/docs/api/java/util/Random.html) for java.util.Random clearly states the following:

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.

However, the way the code is currently using java.util.Random is this - It instantiates the java.security.SecureRandom class and then uses the SecureRandom.nextLong() method to obtain the seed that is used for instantiating the java.util.Randomclass. Then it uses java.util.Random.nextLong() method to generate the token.

So my question now - Is it still insecure given that the java.util.Random is being seeded using java.security.SecureRandom? Do I need to modify the code so that it uses java.security.SecureRandom exclusively to generate the tokens?

Regards

EDIT: Re @Tom's question - Currently the code seed's the Random once at startup

The standard Oracle JDK 7 implementation uses what's called a Linear Congruential Generator to produce random values in java.util.Random.

Taken from java.util.Random source code (JDK 7u2), from a comment on the method protected int next(int bits), which is the one that generates the random values:

This is a linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in The Art of Computer Programming, Volume 3: Seminumerical Algorithms, section 3.2.1.

Predictability of Linear Congruential Generators

Hugo Krawczyk wrote a pretty good paper about how these LCGs can be predicted ("How to predict congruential generators"). If you're lucky and interested, you may still find a free, downloadable version of it on the web. And there's plenty more research that clearly shows that you should never use an LCG for security-critical purposes. This also means that your random numbers are predictable right now, something you don't want for session IDs and the like.

How to break a Linear Congruential Generator

The assumption that an attacker would have to wait for the LCG to repeat after a full cycle is wrong. Even with an optimal cycle (the modulus m in its recurrence relation) it is very easy to predict future values in much less time than a full cycle. After all, it's just a bunch of modular equations that need to be solved, which becomes easy as soon as you have observed enough output values of the LCG.

The security doesn't improve with a "better" seed. It simply doesn't matter if you seed with a random value generated by SecureRandom or even produce the value by rolling a dice several times.

An attacker will simply compute the seed from the output values observed. This takes significantly less time than 2^48 in the case of java.util.Random. Disbelievers may try out this experiment, where it is shown that you can predict future Random outputs observing only two(!) output values in time roughly 2^16. It takes not even a second on a modern computer to predict the output of your random numbers right now.

Conclusion

Replace your current code. Use SecureRandom exclusively. Then at least you will have a little guarantee that the result will be hard to predict. If you want the properties of a cryptographically secure PRNG (in your case, that's what you want), then you have to go with SecureRandom only. Being clever about changing the way it was supposed to be used will almost always result in something less secure...

Regex with -, ::, ( and )

28 votes

I need to split the string

(age-is-25::OR::last_name-is-qa6)::AND::(age-is-20::OR::first_name-contains-test)

into

string[0] = (age-is-25::OR::last_name-is-qa6)

string[1] = AND

string[2] = (age-is-20::OR::first_name-contains-test)

I tried writing so many regex expressions, but nothing works as expected.

Using the following regex, Matcher.groupCount() which returns 2 but assigning results to an arraylist returns null as the elements.

Pattern pattern = Pattern.compile("(\\)::)?|(::\\()?");

I tried to split it using ):: or ::(.

I know the regex looks too stupid, but being a beginner this is the best I could write.

You can use positive lookahead and lookbehind to match the first and last parentheses.

String str = "(age-is-25::OR::last_name-is-qa6)::AND::(age-is-20::OR::first_name-contains-test)";

for (String s : str.split("(?<=\\))::|::(?=\\()"))
    System.out.println(s);

Outputs:

(age-is-25::OR::last_name-is-qa6)
AND
(age-is-20::OR::first_name-contains-test)

Just a note however: It seems like you are parsing some kind of recursive language. Regular expressions are not good at doing this. If you are doing advanced parsing I would recommend you to look at other parsing methods.

Why use `return x == 5 ? true : false;`?

22 votes

I can not see the advantage of this coding practice. The project I'm working with now is full of these statements so it is not a single mistake.

Another example:

return getNumberOfBooks() > 5 ? true : false;

And another:

return isRed() ? true : false;

There is absolutely no reason to do this.

It is redundant and makes the code harder to read.

The following are far easier to read:

return ( getNumberOfBooks() > 5 );

return isRed();

Java: Can creating an object "return" a null reference?

21 votes

While looking through some old code I came across this gem:

MyObject o = new MyObject("parameter");
if (o == null) o = new MyObject("fallback parameter");

The second line is marked in eclipse as dead code, and I understand why. No exception seems to be explicitly thrown, and it isn't possible for the MyObject constructor to throw any kind of exception (such as NullPointerExceptions).

My question is why this is there? Was it previously possible in an old version of Java for a constructor to return null? Or is this simply useless and dead code?

Thanks!

The code is dead in any version of java. It's not possible for a constructor to return null and even if an exception would be thrown from the constructor, the next line won't be called.

Java and c++ encrypted results not matching

21 votes

I have a existing c++ code which will encrypt a string. Now I did the same encryption in . Some of the encrypted strings are matching . Some are mismatching in one or two characters.

I am unable to figure out why it is happening. I ran both the codes in debug mode until they call their libraries both have the same key, salt, iv string to be encrypted.

I know that even if a single byte padding change will modify encrypted string drastically. But here I am just seeing a one or two characters change. Here is a sample (Bold characters in between stars is the part mis matching)

java:

U2FsdGVkX18xMjM0NTY3OGEL9nxFlHrWvodMqar82NT53krNkqat0rrgeV5FAJFs1vBsZIJPZ08DJVrQ*Pw*yV15HEoyECBeAZ6MTeN+ZYHRitKanY5jiRU2J0KP0Fzola

C++:

U2FsdGVkX18xMjM0NTY3OGEL9nxFlHrWvodMqar82NT53krNkqat0rrgeV5FAJFs1vBsZIJPZ08DJVrQ*jQ*yV15HEoyECBeAZ6MTeN+ZYHRitKanY5jiRU2J0KP0Fzola

I am using AES encryption. provider is SunJCE version 1.6. I tried changing provider to Bouncy Castle. Even then result is same.

Added One More sample:

C++:

U2FsdGVkX18xMjM0NTY3O*I*/BMu11HkHgnkx+dLPDU1lbfRwb+aCRrwkk7e9dy++MK+/94dKLPXaZDDlWlA3gdUNyh/Fxv*oF*STgl3QgpS0XU=

java:

U2FsdGVkX18xMjM0NTY3O*D*/BMu11HkHgnkx+dLPDU1lbfRwb+aCRrwkk7e9dy++MK+/94dKLPXaZDDlWlA3gdUNyh/Fxv*j9*STgl3QgpS0XU=

UPDATE:

As per the comments I feel base 64 encryption is the culprit. I am using Latin-1 char set in both places. Anything else that I can check

Sigh!!

The problem almost certainly is that after you encrypt the data and receive the encrypted data as a byte string, you are doing some sort of character conversion on the data before sending it through Base-64 conversion.

Note that if you encrypt the strings "ABCDEFG" and "ABCGEFG", the encrypted output will be completely different starting with the 4th character, and continuing to the end. In other words, the Base-64 outputs would be something like (using made-up values):

U2FsdGVkX18xMj

and

U2FsdGXt91mJpz

The fact that, in the above examples, only two isolated Base-64 characters (one byte) are messed up in each case pretty much proves that the corruption occurs AFTER encryption.

The output of an encryption process is a byte sequence, not a character sequence. The corruption observed is consistent with erroneously interpreting the bytes as characters and attempting to perform a code page conversion on them, prior to feeding them into the Base-64 converter. The output from the encryptor should be fed directly into the Base-64 converter without any conversions.

You say you are using the "Latin-1 char set in both places", a clear sign that you are doing some conversion you should not be doing -- there should be no need to muck with char sets.

Is it possible in Java to catch two exceptions in the same catch block?

20 votes

I need to catch two exceptions because they require the same handling logic. I would like to do something like:

catch (Exception e, ExtendsRuntimeException re) {
    // common logic to handle both exceptions
}

Is it possible to avoid duplicating the handler code in each catch block?

Java 7

Multiple-exception catches are supported in Java 7.

The syntax is:

try {
     // stuff
} catch (Exception1 | Exception2 ex) {
     // Handle both exceptions
}

The static type of ex is the most specialized common supertype of the exceptions listed. There is a nice feature where if you rethrow ex in the catch, the compiler knows that only one of the listed exceptions can be thrown.


Java 6 and earlier

Prior to Java 7, there are ways to handle this problem, but they tend to be inelegant, and to have limitations.

Approach #1

try {
     // stuff
} catch (Exception1 ex) {
     handleException(x);
}
catch (Exception2 ex) {
     handleException(x);
}

public void handleException(SuperException ex) {
     //
}

This gets messy if the exception handler needs to access local variables declared before the try. And if the handler method needs to rethrow the exception (and it is checked) then you run into serious problems with the signature. Specifically, handleException has to be declared as throwing SuperException ... which potentially means you have to change the signature of the enclosing method, and so on.

Approach #2

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     } else {
         throw ex;
     }
}

Once again, we have a potential problem with signatures.

Approach #3

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     }
}

If you leave out the else part (e.g. because there are on other subtypes of SuperException at the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without an else may end up silently eating exceptions!

What is the gain from declaring a method as static

20 votes

I've recently been looking through my warnings in eclipse and come across this one:

static warning

It will give a compiler warning if the method can be declared as static.

Yes I know I can turn it off, but I want to know the reason for turning it on?

Why would it be a good thing to declare every method possible as static?

Will this give any performance benefits? (in a mobile domain)

Pointing out a method as static, I suppose is showing that you don't use any instance variables therefore could be moved to a utils style class?

At the end of the day should I just turn this off 'ignore' or should I fix the 100+ warnings it has given me?

Do you think this is just extra keywords that dirty the code, as the compiler will just inlines these methods anyway? (kind of like you don't declare every variable you can final but you could).

Whenever you write a method, you fulfill a contract in a given scope. The narrower the scope is, the smaller are the chances that you write a bug.

When a method is static, you can't access non-static members, hence your scope is narrower. So, if you don't need non-static member to fulfill your contract, why give access to these fields to your method ? Declaring the method static will in this case will let the compiler check that you don't use members that you are not supposed to use.

And moreover, it will help people reading your code understand the nature of the contract.

That's why it's considered good do declare a method static when it's actually implementing a static contract.

Thread-safe circular buffer in Java

18 votes

Consider a few web server instances running in parallel. Each server holds a reference to a single shared "Status keeper", whose role is keeping the last N requests from all servers.

For example (N=3):

Server a: "Request id = ABCD"        Status keeper=["ABCD"]
Server b: "Request id = XYZZ"        Status keeper=["ABCD", "XYZZ"] 
Server c: "Request id = 1234"        Status keeper=["ABCD", "XYZZ", "1234"]
Server b: "Request id = FOO"         Status keeper=["XYZZ", "1234", "FOO"]
Server a: "Request id = BAR"         Status keeper=["1234", "FOO", "BAR"]

At any point in time, the "Status keeper" might be called from a monitoring application that reads these last N requests for an SLA report.

What's the best way to implement this producer-consumer scenario in Java, giving the web servers higher priority than the SLA report?

CircularFifoBuffer seems to be the appropriate data structure to hold the requests, but I'm not sure what's the optimal way to implement efficient concurrency.

Buffer fifo = BufferUtils.synchronizedBuffer(new CircularFifoBuffer());

What's this generics usage in Java? X.<Y>method()

17 votes

I've read the whole SCJP6 book Sierra and Bates book, scored 88% the exam.

But still, i never heard of how this kind of code works as it's not explained in the generics chapter:

Collections.<TimeUnit>reverseOrder()

What is this kind of generics usage? I discovered it in some code but never read anything about it. It seems to me it permits to give some help to type inference. I've tried to search about that but it's not so easy to find (and it's not even in the SCJP book/exam!)

So can someone give me a proper explaination of how it works, which are all the usecases etc?

Thanks


Edit Thanks for the answers but i expected more details :) so if someone want to add some extra informations:

What about more complex cases like

  • Using a type declared in class , can i do something like Collections.<T>reverseOrder() for exemple?
  • Using extends, super?
  • Using ?
  • Giving the compiler only partial help (ie O.manyTypesMethod<?,MyHelpTypeNotInfered,?,?,?,?,?>() )

It is explicit type specification of a generic method. You can always do it, but in most cases it's not needed. However, it is required in some cases if the compiler is unable to infer generic type on its own.

See an example towards the end of the tutorial page.

Update: only the first of your examples is valid. The explicit type argument must be, well, explicit, so no wildcards, extends or super is allowed there. Moreover, either you specify each type argument explicitly or none of them; i.e. the number of explicit type arguments must match the number of type parameters of the called method. A type parameter such as T is allowed if it is well defined in the current scope, e.g. as a type parameter of the enclosing class.

when should I override Equals function?

Asked on Wed, 13 Jun 2012 by MBZ java
17 votes

Possible Duplicate:
Java: Always override equals?

should I override equals function for any class that I create?

even for very simple classes which only contains some very simple attributes and by equals I need every single attribute of it to be equal?

should I override equals function for any class that I create?

Override equals if (and only if) the object "represents some data", i.e. if it models something such as Person, Car or RecipieIngredient (these typically end up in collections etc). Don't override equals for other types of classes, for example LoginServlet or DatabaseUtil.

Remember to always override hashCode whenever you override equals.

(A natural follow-up question:) What happens if I don't override equals and hashCode?

Any two objects will be considered unequal unless they are the exact same object.

[...] I need every single attribute of it to be equal?

Typically yes. It depends on how you define your notion of equality. Note that for reference types, you can reuse/delegate to that objects implementation of equals (and hashCode) when implementing your own.

Related questions:

Difference between a.getClass() and A.class?

16 votes

In Java what pros/cons exist surrounding the choice to use a.getClass() or A.class? Either can be used wherever a Class<?> is expected, but I imagine that there would be performance or other subtle benefits to using both in different circumstances (just like there are with Class.forName() and ClassLoader.loadClass(). Thanks in advance.

I wouldn't compare them in terms of pros/cons since they have different purposes and there's seldom a "choice" to make between the two.

  • a.getClass() returns the runtime type of a. I.e., if you have A a = new B(); then a.getClass() will return the B class.

  • A.class evaluates to the A class statically, and is used for other purposes often related to reflection.

In terms of performance, there may be a measurable difference, but I won't say anything about it because in the end it is JVM and/or compiler dependent.

string literals as argument to methods

15 votes

Any String literal in Java is a constant object of type String and gets stored in the String literal pool.

Will String literals passed as arguments to the methods also get stored in the String literal pool?

For example when we write,

System.out.println("Hello");

OR

anyobj.show("Hello");

will a String "Hello" be created and stored in the String literal pool?

Is there any way to print the contents of the String literal pool?

Every time you use a String literal in your code (no matter where) the compiler will place that string in the symbol table and reference it every time it encounters the same string somewhere in the same file. Later this string will be placed in the constant pool. If you pass that string to another method, it still uses the same reference. String are immutable so it is safe to reuse them.

Take this program as an example:

public class Test {

    public void foo() {
        bar("Bar");
    }

    public void bar(String s) {
        System.out.println(s.equals("Bar"));
    }

}

After decompiling with javap -c -verbose you'll find out the following:

const #2 = String   #19;    //  Bar
//...
const #19 = Asciz   Bar;


public void foo();
    //...
    1:  ldc #2; //String Bar


public void bar(java.lang.String);
    //...
    4:  ldc #2; //String Bar

There are two entries in constant pool: one for String (#2) referencing the actual characters (#19).

Why aren't getters preferred when accessing variables between activities?

14 votes

Daily there are many questions of the following type on SO:

How do I get a variable from another Activity?

The answers usually recommend to use SharedPreferences or Intent.putExtra().

To me, a getter method is what would be an approach to access a variable from another class. After all, the Activity that is under consideration is a class, and it's variables are class members.

Why aren't getter methods preferred to approaches like SharedPreferences or Intent extras?

I'm talking about simple situations that require accessing a variable between activities, for example this one:

class OneClass extends Activity {
    int a;

    ..
    // some changes to a
    ..
}

And then in another class(Activity):

class SomeOtherClass extends Activity {
    ..
    // trying to access a here
    ..
}

Is a getter method a correct approach here, or not?

Again - I'm not talking about scenarios where these things are actually the right way to go. SharedPreferences for persistent storage of small amount of data, extras as the documentation says : This can be used to provide extended information to the component. For example, if we have a action to send an e-mail message, we could also include extra pieces of data here to supply a subject, body, etc.


As some of the answers have likely indicated that there are certain scenarios like no guarantee of the other Activity being alive, I guess there are more probable and correct reasons as to why people suggest going for intents and shared preferences.

The answer to your question is two fold:

  • For the meta aspect, which belongs on meta SO anyway, many newbie programmers see Android, want to write apps, and suck at Java.
  • For the other quesiton, typically using a getter and setter won't work, because you can't pass objects between Activities in a straightforward way. While you can technically do this with a Parcelable, it's not recommended, and the better way is to use an intent to pass data between application components.
  • Another point this highlights is that Android apps should keep a minimal amount of state inside components. I think this has been a big success of Android. If you look at apps out there, there is on average a lot less global state than typical programs written in java. The programs are also smaller, which is to be expected, but the fact that an atomic activity can represent the state of a single screen, and the fact that any single screen won't typically be persisting that much state across the entire app, leads to an good logical separation between app components.

Error in KSOAP Parsing :- java.lang.ClassCastException: org.ksoap2.SoapFault

10 votes

I have a little knowledge in ksoap Parsing. When i am parsing some data it gives Error :

java.lang.ClassCastException: org.ksoap2.SoapFault

I can see the response for that method in SoapUI but when i parsing that method in android it gives an error as like above.

Here is Request parameter as input in SoapUI

        <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
        <soapenv:Header/>
        <soapenv:Body>
           <tem:SaveChangePasswordForExternalUser>
              <tem:userId>Test123</tem:userId>
              <!--Optional:-->
              <tem:oldPassword>TestTest</tem:oldPassword>
              <!--Optional:-->
              <tem:newPassword>Test</tem:newPassword>
              <!--Optional:-->
              <tem:retypedNewPassword>Test</tem:retypedNewPassword>
           </tem:SaveChangePasswordForExternalUser>
        </soapenv:Body>
     </soapenv:Envelope>

Here Is Response i got in SoapUI

 <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body>
      <s:Fault>
         <faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</faultcode>
         <faultstring xml:lang="en-US">Old Password was incorrectly entered. Remember that passwords are case-sensitive.</faultstring>
         <detail>
            <ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
               <HelpLink i:nil="true"/>
               <InnerException i:nil="true"/>
               <Message>Old Password was incorrectly entered. Remember that passwords are case-sensitive.</Message>       
               <Type>System.Web.Services.Protocols.SoapException</Type>
            </ExceptionDetail>
         </detail>
      </s:Fault>
   </s:Body>
</s:Envelope>

This how i try to get the response by code in android

public void getData()
    {

        private static final String NAMESPACE = "http://tempuri.org/"; //
        private static final String URL = "http://173.203.136.194:99/LeaseWave.MobileApplication.Service/MobileApplicationService.svc/basic";
        private static final String SOAP_ACTION = "http://tempuri.org/IMobileApplicationService/SaveChangePasswordForExternalUser";
        private static final String METHOD_NAME = "SaveChangePasswordForExternalUser";

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("userId", "Test123");
        request.addProperty("oldPassword", "TestTest");
        request.addProperty("newPassword", "Test");
        request.addProperty("newPassword", "Test");

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

        try {

            androidHttpTransport.call(SOAP_ACTION, envelope);
            SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

            Log.i("Long...", "Response  ------ "+resultsRequestSOAP);


        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }

but i don't get success in that. Anyone have any kind of hint or solution for this?

This sort of code can solve your problem,

    if (envelope.bodyIn instanceof SoapFault) {
        String str= ((SoapFault) envelope.bodyIn).faultstring;
        Log.i("", str);

        // Another way to travers through the SoapFault object
    /*  Node detailsString =str= ((SoapFault) envelope.bodyIn).detail; 
        Element detailElem = (Element) details.getElement(0) 
                     .getChild(0); 
        Element e = (Element) detailElem.getChild(2);faultstring; 
        Log.i("", e.getName() + " " + e.getText(0)str); */
    } else {
        SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
        Log.d("WS", String.valueOf(resultsRequestSOAP));
    }

Android Activity ClassNotFoundException - tried everything

8 votes

I've just refactored an app into a framework library and an application, but now when I try and start the app in the emulator I get the following error stack trace:

06-02 18:22:35.529: E/AndroidRuntime(586): FATAL EXCEPTION: main
06-02 18:22:35.529: E/AndroidRuntime(586): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.matthewrathbone.eastersays/com.matthewrathbone.eastersays.EasterSimonSaysActivity}: java.lang.ClassNotFoundException: com.matthewrathbone.eastersays.EasterSimonSaysActivity in loader dalvik.system.PathClassLoader[/data/app/com.matthewrathbone.eastersays-1.apk]
06-02 18:22:35.529: E/AndroidRuntime(586):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
06-02 18:22:35.529: E/AndroidRuntime(586):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-02 18:22:35.529: E/AndroidRuntime(586):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-02 18:22:35.529: E/AndroidRuntime(586):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-02 18:22:35.529: E/AndroidRuntime(586):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 18:22:35.529: E/AndroidRuntime(586):  at android.os.Looper.loop(Looper.java:123)
06-02 18:22:35.529: E/AndroidRuntime(586):  at android.app.ActivityThread.main(ActivityThread.java:4627)
06-02 18:22:35.529: E/AndroidRuntime(586):  at java.lang.reflect.Method.invokeNative(Native Method)
06-02 18:22:35.529: E/AndroidRuntime(586):  at java.lang.reflect.Method.invoke(Method.java:521)
06-02 18:22:35.529: E/AndroidRuntime(586):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-02 18:22:35.529: E/AndroidRuntime(586):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-02 18:22:35.529: E/AndroidRuntime(586):  at dalvik.system.NativeStart.main(Native Method)
06-02 18:22:35.529: E/AndroidRuntime(586): Caused by: java.lang.ClassNotFoundException: com.matthewrathbone.eastersays.EasterSimonSaysActivity in loader dalvik.system.PathClassLoader[/data/app/com.matthewrathbone.eastersays-1.apk]
06-02 18:22:35.529: E/AndroidRuntime(586):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
06-02 18:22:35.529: E/AndroidRuntime(586):  at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
06-02 18:22:35.529: E/AndroidRuntime(586):  at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
06-02 18:22:35.529: E/AndroidRuntime(586):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
06-02 18:22:35.529: E/AndroidRuntime(586):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
06-02 18:22:35.529: E/AndroidRuntime(586):  ... 11 more

Usually this means that the manifest file is wrong in some way, but I've double checked everything I can think of.

Here is my activity class:

package com.matthewrathbone.eastersays;

import android.os.Bundle;

import com.rathboma.simonsays.Assets.Season;
import com.rathboma.simonsays.SeasonPicker;
import com.rathboma.simonsays.SimonSaysActivity;

    public class EasterSimonSaysActivity extends SimonSaysActivity {

      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      }

      @Override
      protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
      }

      @Override
      public SeasonPicker getSeasonPicker() {
       return new SeasonPicker(){
        @Override
        public Season getSeason() {
          // TODO Auto-generated method stub
          return Season.EASTER;
        }
       };
      }
    }

As you can see, it's listed correctly in the manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.matthewrathbone.eastersays"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".EasterSimonSaysActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I have no idea how to fix this, and would appreciate any help. I've scanned many similar questions on SO without seeing this particular behavior.

More info:

  • I've checked inside the generated APK and the class has an entry in the classes.dex file
  • I've tried cleaning/building the project in eclipse
  • I've tried using a totally new device image that doesn't have a copy of the APK on it already
  • I've changed the library project into a regular java, then changed back into an android project, no difference
  • Adding the abstract SimonSaysActivity to the manifest makes no difference.
  • I've tried making every dependency an android library project, and syncing the android version that they require, it did not help

Found the solution (see below). To everyone that posted an answer / comment: You all rock, thanks for helping me work through the problems!

Looks like this is introduced by an SDK tools upgrade. Thanks to @Nick below in the comments for this link: http://iqadd.com/item/noclassdeffounderror-adt-fix

I spent some time play with my own project, and I am able to replicate your problem and get exactly the same exception stack trace when trying to run my main project, so I think this could be the cause:

Just like what I thought, it is all about how you reference your Android library project in the Android main project, a simple Eclipse configuration settings.

The Wrong Way:
Right click main project, choose Properties -> Java Build Path -> Projects -> Add..., this add the Android library Project as a dependency project in Android main project's build path, this does not work. If all required Android-related resources are defined in main project, you will not get any error at compile time, but when run the application, you get the exception described in the question.

The Correct Way:
Right click main project, choose Properties -> Android, in the Library section, add your Android library project here. Check out official dev guide Referencing a library project. This should fix all your problem. Also note that you have to use relative path reference the actual Android library project, as stated in the Library Project - Development considerations.

Hope this helps.