How come you don't need to use the new keyword or the parentheses when using BigInteger?

StackOverflow https://stackoverflow.com/questions/20481851

  •  30-08-2022
  •  | 
  •  

Question

How come whenever you make an instance of a class in Java you use:

Class nameOfClass = new Class();

which creates an object then you can call its methods by adding a period after the object name. How come you dont need to use the new keyword or the parentheses when using BigInteger, and can make a new object this way:

BigInteger first = BigInteger.valueOf(1);

I have poured through the documentation here, as well as, many google searches to find out why this is so to no avail.

Was it helpful?

Solution

This is a static factory method, which returns an instance of BigInteger.

public static BigInteger valueOf(long val) 
{
         if (val == 0)
             return ZERO;

         if (val > 0 && val <= MAX_CONSTANT)
             return posConst[(int) val];

         else if (val < 0 && val >= -MAX_CONSTANT)
             return negConst[(int) -val];

         return new BigInteger(val);
}

See, it's either returning a new BigInteger(val) or going through BigInteger array instance members to return an already existing BigInteger. For reference, here's the static block which creates the arrays:

private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1]
static 
{
    for (int i = 1; i <= MAX_CONSTANT; i++) 
    {
        int[] magnitude = new int[1];
        magnitude[0] = i;

        posConst[i] = new BigInteger(magnitude,  1);
        negConst[i] = new BigInteger(magnitude, -1);
     }
}

OTHER TIPS

That's called a factory method. A static method that creates and returns a new object for you.

They're handy when you have loads of ways of creating objects but don't really want to overload the method signature too much (i.e. have loads of different constructors)

That is a static factory method. A static method which is used to create and return a new object. So you can create a static method that internally calls new operation

This is because the BigInteger.valueOf method is a static factory method. That means that the method itself is simply used to create individual instances of BigInteger. This link gives a good description of when to use static methods: Java: when to use static methods

BigInteger uses the factory method pattern to create new instances with more meaningful method names. The factory method also allows the JVM to reuse the same instance of commonly reusable values (such as 1) to save memory.

By the way, you CAN use the new keyword to construct new instances but the constructors take many parameters or Strings which may be confusing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top