I was browsing the web for examples on how to partition in Java. I've got to this website that has a detailed example about Partitioning so I've tried to run it on my JCreator Pro.

I've only got one error, but I've tried all I can do to fix it ( Put BufferedReader, import java.io.*, throws IOException ), and It still wouldn't work.

Here's the Error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Partition.main(Partition.java:17)

Here's the Code:

public class Partition { 

    public static void partition(int n) {
        partition(n, n, "");
    public static void partition(int n, int max, String prefix) {
        if (n == 0) {
        for (int i = Math.min(max, n); i >= 1; i--) {
            partition(n-i, i, prefix + " " + i);
  public static void main(String args[]) { 
        int N=Integer.parseInt(args[0]);


Thank you very much!

7 Years
Discussion Span
Last Post by javaAddict

Look carefully the 17th line
int N = Integer.parseInt(args[0]);
this means that parse the input(command line argument) given to Wrapper class Integer.
So to run without exception you should compile like this
java Partition 2

Refer the following site to understand command line line arguments
Command line Argument
Hope you understand the Exception

Edited by new_programmer: html link error


I still don't get why the code won't work?
can you provide a newer version of the java program that works and doesn't have an error when you compile it?

Thank you!



There is no mistake in your code.
Problem is when you run that code.

so run the code like this

java Partition 2

Edited by new_programmer: grammer


When you put this in the code: int N=Integer.parseInt(args[0]); , you are supposed to pass arguments to your program when you run it. (args[0])

Don't expect to copy code from the internet and run it without putting any effort to understand it.

Have you tried the link new_programmer has provided?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.