Int to BigInteger

Hello does anybody have any idea how to create BigInteger form integer (int) value???thx

int num = 100;
BigInteger bignum = new BigInteger(""+num);

Similar Messages

  • Error in Decryption

    Dear All,
    This is my first post. Require your help in the resolving the following issue.
    I have an encrypter and corresponding decrypter using DES algorithm compiled using Sun JDK. Now the encrypter is being used in IBM JRE environment. The file is getting encrypted, but when I try to decrypt it using Sun JDK, it is looking for the ibm classes (com.ibm.provider.DESKey) and is not able to decrypt the file. Can anyone help, why is the decrypter looking for the ibm classes.
    The JRE versions of both IBM and Sun are 1.4.2.
    Thanks in advance for the help...

    The decrypter class
    // Decompiled by Jad v1.5.8f. Copyright 2001 Pavel Kouznetsov.
    // Jad home page: http://www.kpdus.com/jad.html
    // Decompiler options: packimports(3)
    // Source File Name:   Decrypter.java
    package icici.matrix.utils;
    import java.io.FileInputStream;
    import java.io.PrintStream;
    import java.math.BigInteger;
    import java.util.Properties;
    public class Decrypter
        static class Params
            BigInteger p;
            BigInteger q;
            BigInteger n;
            BigInteger d;
            BigInteger e;
            BigInteger phi;
            BigInteger max;
            Params()
                p = new BigInteger("0");
                q = new BigInteger("0");
                n = new BigInteger("0");
                d = new BigInteger("0");
                e = new BigInteger("15");
                phi = new BigInteger("0");
        public Decrypter()
        public String decrypt()
            Params par = new Params();
            String password = "";
            String propFile = "app.properties";
            try
                Properties prop = new Properties();
                FileInputStream finput = new FileInputStream(propFile);
                prop.load(finput);
                password = (String)prop.get("password");
                System.out.println(password);
            catch(Exception e)
                e.printStackTrace();
            String cipherText = password;
            String cipherTextTemp = "";
            String decipheredText = "";
            String outputText = "";
            boolean flag = cipherText.startsWith("P");
            if(flag)
                cipherText = cipherText.substring(1, cipherText.length());
            int blockSize = 4;
            if(blockSize % 2 != 0)
                System.out.println("blockSize must be even");
                System.exit(1);
            String maxEncodedString = "";
            for(int cnt = 0; cnt < blockSize; cnt += 2)
                maxEncodedString = maxEncodedString + "94";
            par.max = new BigInteger(maxEncodedString);
            par.p = par.max.divide(new BigInteger("502"));
            Decrypter obj = new Decrypter();
            obj.getKeys(par, blockSize);
            decipheredText = obj.doRSA(cipherText, par.d, par.n, blockSize);
            System.out.println("decipheredText\n" + decipheredText);
            outputText = obj.decode(decipheredText);
            if(flag)
                outputText = outputText.substring(0, outputText.length() - 1);
            System.out.println("outputText\n" + outputText);
            return outputText;
        void getKeys(Params par, int blockSize)
            BigInteger bigOne = new BigInteger("1");
            for(; !par.p.isProbablePrime(1000); par.p = par.p.add(bigOne));
            String firstQ = par.p.subtract(bigOne);
            par.q = new BigInteger(firstQ);
            for(par.n = par.p.multiply(par.q); par.n.toString().length() > blockSize; par.n = par.p.multiply(par.q))
                par.q = par.q.divide(new BigInteger("2"));
            for(par.q = par.q.divide(new BigInteger("2")); !par.q.isProbablePrime(1000); par.q = par.q.subtract(bigOne));
            for(par.n = par.p.multiply(par.q); par.n.compareTo(par.max) <= 0; par.n = par.p.multiply(par.q))
                for(par.q = par.q.add(bigOne); !par.q.isProbablePrime(1000); par.q = par.q.add(bigOne));
            if(par.n.toString().length() > blockSize || par.n.compareTo(par.max) <= 0)
                System.out.println("Required conditions are not met");
                System.exit(1);
            BigInteger pPrime = par.p.subtract(bigOne);
            BigInteger qPrime = par.q.subtract(bigOne);
            for(par.phi = pPrime.multiply(qPrime); !par.e.gcd(par.phi).equals(bigOne); par.e = par.e.add(bigOne));
            par.d = par.e.modInverse(par.phi);
            if(blockSize > 6)
                System.exit(0);
        String decode(String encodedText)
            String temp = "";
            String decodedText = "";
            for(int cnt = 0; cnt < encodedText.length(); cnt += 2)
                temp = encodedText.substring(cnt, cnt + 2);
                int val = Integer.parseInt(temp) + 32;
                decodedText = decodedText + String.valueOf((char)val);
            return decodedText;
        String doRSA(String inputString, BigInteger exp, BigInteger n, int blockSize)
            String temp = "";
            String outputString = "";
            for(int cnt = 0; cnt < inputString.length(); cnt += blockSize)
                temp = inputString.substring(cnt, cnt + blockSize);
                BigInteger block = new BigInteger(temp);
                BigInteger output = block.modPow(exp, n);
                for(temp = output.toString(); temp.length() < blockSize; temp = "0" + temp);
                outputString = outputString + temp;
            return outputString;
        public String decrypt(String password)
            Params par = new Params();
            String cipherText = password;
            String cipherTextTemp = "";
            String decipheredText = "";
            String outputText = "";
            boolean flag = cipherText.startsWith("P");
            if(flag)
                cipherText = cipherText.substring(1, cipherText.length());
            int blockSize = 4;
            if(blockSize % 2 != 0)
                System.out.println("blockSize must be even");
                System.exit(1);
            String maxEncodedString = "";
            for(int cnt = 0; cnt < blockSize; cnt += 2)
                maxEncodedString = maxEncodedString + "94";
            par.max = new BigInteger(maxEncodedString);
            par.p = par.max.divide(new BigInteger("502"));
            Decrypter obj = new Decrypter();
            obj.getKeys(par, blockSize);
            decipheredText = obj.doRSA(cipherText, par.d, par.n, blockSize);
            System.out.println("decipheredText\n" + decipheredText);
            outputText = obj.decode(decipheredText);
            if(flag)
                outputText = outputText.substring(0, outputText.length() - 1);
            System.out.println("outputText\n" + outputText);
            return outputText;
    }

  • Question about multiple class files

    I just started learning JAVA a couple of days ago and the first program I wrote had two classes in one file. here is the program :
    class fib_num {
    public int value;
    public boolean is_even;
    class Fibonacci {
    /** Print the Fibonacci sequence for values < MAX and mark even numbers with an asterick */
    private static final int MAX = 50;
    private static final String Title = "The Fibonacci sequence for values less than " + MAX + ":";
    private static fib_num[] fib = new fib_num[MAX];//This is actually an array of object
    //references to objects of the fib_num class
    public static void main(String[] args) {
    System.out.println(Title);
    //We must initialize each element of the array also !!!!
    for (int i = 0; i < fib.length; i += 1) {
    fib = new fib_num();
    int lo = 1, hi = 1;
    fib[0].value = lo;
    fib[0].is_even = false;
    fib[1].value = hi;
    fib[1].is_even = false;
    for (int i = 2; i < fib.length; i += 1) {
    //create the next Fibonacci number and then save the previous Fibonacci number
    hi = lo + hi;
    lo = hi - lo;
    fib.value = hi;
    //now indicate if the Fibonacci number is even/odd
    if (fib.value % 2 == 0) {
    fib.is_even = true;
    }else {
    fib.is_even = false;
    print (fib);
    //This method prints an array of Fibonacci numbers
    public static void print(fib_num[] array) {
    if (array == null || array.length == 0)
    throw new IllegalArgumentException();
    String mark;
    for (int i = 0; array.value < MAX; i += 1) {
    if (array.is_even) {
    mark = "*";
    }else {
    mark = "";
    System.out.println((i + 1) + ": " + array.value + mark);
    I ran the program and everything went fine. But today I started to write another program with two classes. However the file will not compile and I get an error about interfacing or something. here is the program:
    Note: it's not nearly complete.
    class enumerate {
    //print out all permutations of a list of integers
    public static final int MAX = 4;
    public static int[] initialize(int[] nums) {
    for (int i = 0; i < nums.length; i++) {
    nums = i + 1;
    return nums;
    public static void print(int[] nums) {
    for (int i = 0; i < nums.length; i++) {
    System.out.print(nums);
    System.out.println("");
    public static void swap (int[] nums, int i, int j) {
    int temp = nums;
    nums = nums[j];
    nums[j] = temp;
    public static void main (String[] args) {
    int[] list = new int[MAX];
    list = initialize(list);
    PermutationGenerator x = new PermutationGenerator(5);
    // Systematically generate permutations.
    import java.math.BigInteger;
    public class PermutationGenerator {
    private int[] a;
    private BigInteger numLeft;
    private BigInteger total;
    // Constructor. WARNING: Don't make n too large.
    // Recall that the number of permutations is n!
    // which can be very large, even when n is as small as 20 --
    // 20! = 2,432,902,008,176,640,000 and
    // 21! is too big to fit into a Java long, which is
    // why we use BigInteger instead.
    public PermutationGenerator (int n) {
    if (n < 1) {
    throw new IllegalArgumentException ("Min 1");
    a = new int[n];
    total = getFactorial (n);
    reset ();
    // Reset
    public void reset () {
    for (int i = 0; i < a.length; i++) {
    a = i;
    numLeft = new BigInteger (total.toString ());
    // Return number of permutations not yet generated
    public BigInteger getNumLeft () {
    return numLeft;
    // Return total number of permutations
    public BigInteger getTotal () {
    return total;
    // Are there more permutations?
    public boolean hasMore () {
    return numLeft.compareTo (BigInteger.ZERO) == 1;
    // Compute factorial
    private static BigInteger getFactorial (int n) {
    BigInteger fact = BigInteger.ONE;
    for (int i = n; i > 1; i--) {
    fact = fact.multiply (new BigInteger (Integer.toString (i)));
    return fact;
    // Generate next permutation (algorithm from Rosen p. 284)
    public int[] getNext () {
    if (numLeft.equals (total)) {
    numLeft = numLeft.subtract (BigInteger.ONE);
    return a;
    int temp;
    // Find largest index j with a[j] < a[j+1]
    int j = a.length - 2;
    while (a[j] > a[j+1]) {
    j--;
    // Find index k such that a[k] is smallest integer
    // greater than a[j] to the right of a[j]
    int k = a.length - 1;
    while (a[j] > a[k]) {
    k--;
    // Interchange a[j] and a[k]
    temp = a[k];
    a[k] = a[j];
    a[j] = temp;
    // Put tail end of permutation after jth position in increasing order
    int r = a.length - 1;
    int s = j + 1;
    while (r > s) {
    temp = a[s];
    a[s] = a[r];
    a[r] = temp;
    r--;
    s++;
    numLeft = numLeft.subtract (BigInteger.ONE);
    return a;
    I thought the error had somethin to do with only having one class per .java file since the compiler creates a .class file. But how come my first program had two classes and it was OK. Is it b/c the second class was merely a collection of fields, almost like a simple struct in C?
    Any help would be appreciated. Thanks

    Move the import java.math.BigInteger line to the start of the file.
    Use the "[ code ] [ /code ]" tags around your code when you post, it makes reading it a lot easier.

  • Urgent ! writing a java card applet -APDU problem

    hi
    i'm fairly new to the java programming language. i'm trying to write an RSA java card applet to run on a java card simulator.
    I am not sure at all what code i need to write for the CLA byte in the command APDU and what code i need to write for the INS byte in the command APDU, and where exactly to put it in my program.
    if anybody knows please could you help me out.
    So far i have written the code below.
    thanx
    louise
    import javacard.framework.*;
    import java.math.*;
    import java.util.*;
    /*the public key is the public part of the key. Anyone
    can have it. It can only encrypt data, not decrypt.*/
    public class publickey extends Applet{
    //code of the CLA byte in the command APDU header
    final static byte publickey_CLA = (byte)0x00;
    //max number of characters for text message is 60
    final static char MAX_TXT_MSG = 0x3c;
    //MAX number of tries (3) before PIN is blocked
    final static byte PIN_TRY_LIMIT = (byte)0x03;
    //size of PIN must be 4 digits long
    final static byte PIN_SIZE = (byte)0x04;
    //below status word(SW) values are returned by applet
    //in certain circumstances:
    //signal that the PIN verification failed
    final static short SW_PIN_VERIFICATION_FAIL = 0x6300;
    //signal that PIN validation required for txt msging
    final static short SW_PIN_VERIFICATION_REQUIRED = 0x630;
    //instance variables declaration
    OwnerPIN pin; //variable for holding owners pin
    BigInteger n,e;
    String owner;//variable for holding owners name
    /*make a public key. Do not do it yourself, but
    make a public key from a private key.*/
    publickey(String iowner,BigInteger in,BigInteger ie){
    owner=iowner;
    n=in;
    e=ie;
    public void process (APDU apdu) {
    byte[] buffer = apdu.getBuffer();
    //check Select APDU command
    if((buffer[ISO7816.OFFSET_CLA] ==0) &&
    (buffer[ISO7816.OFFSET_INS] ==(byte) (0xA4)) )
    return;
    if(buffer[ISO7816.OFFSET_CLA] !=publickey_CLA)
    ISOException.throwIt
    (ISO7816.SW_CLA_NOT_SUPPORTED);
    /*read the key back from a string.*/
    publickey(String from){
    StringTokenizer st=new StringTokenizer(from," ");
    owner=st.nextToken();
    n=readBI(st.nextToken());
    e=readBI(st.nextToken());
    /*use the key to encrypt a 'message' m. m should be a
    number from 1 to n (n not included).
    use makemessage to convert your message to a BigInteger.
    BigInteger encrypt(BigInteger m){
    return m.modPow(e,n);
    /*make a string from this key.*/
    public String toString(){
    return owner+" "+printBI(n)+" "+printBI(e);
    /*help methods for reading and writing:*/
    final static int radix=36;
    static String printBI(BigInteger b){
    return b.toString(radix);
    static BigInteger readBI(String s){
    return new BigInteger(s,radix);
    /* these methods convert an arbitrary message,
    in the form of an array of bytes, to a message
    suitable for encryption. To do this random bits
    are added (this is needed to make cracking of the
    system harder), and it is converted to a BigInteger.*/
    BigInteger makemessage(byte[] input){
    /*to understand this part of the program,
    read the description of the BigInteger constructor
    (in the standard java help). */
    if(input.length>128 ||
    input.length*8+24>=n.bitLength())
    return new BigInteger("0"); //error! message to long.
    byte[] paddedinput=new byte[n.bitLength()/8-1];
    for(int i=0;i<input.length;i++)
    paddedinput[i+1]=input;
    paddedinput[0]=(byte)input.length;
    for(int i=input.length+1;i<paddedinput.length;i++)
    paddedinput[i]=(byte)(Math.random()*256);
    return new BigInteger(paddedinput);
    /*the inverse of makemessage.*/
    static byte[] getmessage(BigInteger b){
    byte[] paddedoutput=b.toByteArray();
    byte[] output=new byte[paddedoutput[0]];
    for(int i=0;i<output.length;i++)
    output[i]=paddedoutput[i+1];
    return output;
    class privatekey{
    /*the data of a key*/
    BigInteger n,e,d;
    String owner;
    int bits;
    Random ran;
    /*unimportant things, needed for calculations:*/
    static int certainty=32;
    static BigInteger one=new BigInteger("1"),
    three=new BigInteger("3"),
    seventeen=new BigInteger("17"),
    k65=new BigInteger("65537");
    /*make a new key. supply the name of the owner of the
    key, and the number of bits.
    owner: all spaces will be replaced with underscores.
    bits: the more bits the better the security. Every
    value above 500 is 'safe'. If you are a really paranoid
    person, you should use 2000.*/
    privatekey(String iowner,int ibits){
    BigInteger p,q;
    bits=ibits;
    owner=iowner.replace(' ','_');//remove spaces from owner name.
    ran=new Random();
    p=new BigInteger(bits/2,certainty,ran);
    q=new BigInteger((bits+1)/2,certainty,ran);
    n=p.multiply(q);
    BigInteger fi_n=fi(p,q);
    e=chooseprimeto(fi_n);
    d=e.modInverse(fi_n);
    /*read the key back from a string*/
    privatekey(String from){
    StringTokenizer st=new StringTokenizer(from," ");
    st.nextToken();
    n=readBI(st.nextToken());
    e=readBI(st.nextToken());
    d=readBI(st.nextToken());
    /*some help methods:*/
    static BigInteger fi(BigInteger prime1,BigInteger prime2){
    return prime1.subtract(one).multiply(prime2.subtract(one));
    static BigInteger BI(String s)
    {return new BigInteger(s);}
    BigInteger chooseprimeto(BigInteger f){
    /*returns a number relatively prime to f.
    this number is not chosen at random, it first
    tries a few primes with few 1's in it. This
    doesn't matter for security, but speeds up computations.*/
    if(f.gcd(three).equals(one))
    return three;
    if(f.gcd(seventeen).equals(one))
    return seventeen;
    if(f.gcd(k65).equals(one))
    return k65;
    BigInteger num;
    do{
    num=new BigInteger(16,ran);
    }while(!f.gcd(num).equals(one));
    return num;
    final static int radix=36;
    static String printBI(BigInteger b){
    return b.toString(radix);
    static BigInteger readBI(String s){
    return new BigInteger(s,radix);
    /*returns the public key of this private key.*/
    publickey getpublickey(){
    return new publickey(owner,n,e);
    /*the same encryption that the public key does.*/
    BigInteger encrypt(BigInteger m){
    return m.modPow(e,n);
    /*decryption is the opposite of encryption: it
    brings the original message back.*/
    BigInteger decrypt(BigInteger m){
    return m.modPow(d,n);
    public String toString(){
    return owner+" "+printBI(n)+" "+printBI(e)+" "+printBI(d);
    /*this main demonstrates the use of this program.*/
    public static void main(String[] ps){
    say("************ make key:");
    privatekey priv=new privatekey("sieuwert",92);
    publickey pub=priv.getpublickey();
    say("the public key:"+priv);
    say("************ encrypt message:");
    byte[] P="RUOK?".getBytes();
    BigInteger Pc=pub.makemessage(P);
    say("converted:\t"+printBI(Pc));
    BigInteger C=pub.encrypt(Pc);
    say("coded message: "+printBI(C));
    say("************ decrypt message:");
    BigInteger Pc2=priv.decrypt(C);
    say("decoded:\t"+printBI(Pc2));
    byte[] P2=publickey.getmessage(Pc2);
    say("deconverted: "+new String(P2));
    static void say(String s){
    System.out.println(s);

    Command APDU is not written in your source code, rather it is sent from PC or programmed Card Acceptance Device/ Card Reader/ Terminal.
    The code installed in the Java Card should be able to handle the Command APDU received and process it accordingly, and finally your code should be able to send out response APDU.
    You may think your code as a decoder, to retrieve each byte (CLA, INS, P1, P2, DATA, LC) using the Java Card API, you should be able to do it.
    Also, I notice in your code that you want to work out with strings, but Java Card does not support strings, chars, long, float, double ...
    to send out reponse APDU, there are certain steps that you can use, not just simply print like ordinary J2SE may use.
    hope this will help u

  • What Is Wrong With This Picture??

    Hi All,
    I have been working on an RSA encryption program that allows the user to enter a message 'M'.
    This message undergoes a series of permutations based on two prime numbers that have been randomly generated in order to encrypt the message.
    The message is then decrypted using similar calculations.
    The problem is it only returns the correct value some of the time! I'm sure it has to do with the final calculations, because if I use a calculator to do the functions I get the expected result 100% of the time.
    Can anyone solve this problem?
    // Perform calculation on M to encrypt the message
         double cipherText;
         cipherText = (double) Math.pow (encryption[0], e) % n;     
         System.out.println("CIPHERTEXT = " + cipherText );     
    // Decrypt the message
         double decryption [] = new double [1];
         double plainText;
         decryption [0] = cipherText ++;          
         plainText = (double) Math.pow (decryption[0], d) % n;     
         System.out.println("PLAINTEXT = " + plainText );

    You don't need to use the BigInteger everywhere... you can create some convenience methods to replace the spots where the numbers get as large as you say and hide the BigInteger's existence from the world...Let's say like this:
    public static int getCipherText(int codedChar, int exponent, int modulo)
      BigInteger theBigOne = new BigInteger(""+codedChar).pow(exponent).mod(new BigInteger(""+modulo));
      return theBigOne.intValue();
    }and just use the metod everywhere...
    HTH,
    Fredrik

  • Incompatible Types... NOT!

    Why am I getting incompatible types in this method?
    C:\jdk1.3\src\CalcBusinessDays.java:53: incompatible types
    found : java.util.Date
    required: Date
              Date covDate = sdf.parse(dt, pos);^ <-- carat is at end of line
         public Date dateConvert(String dt) {
              SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy");
              ParsePosition pos = new ParsePosition(0);
              Date covDate = sdf.parse(dt, pos);
              return covDate;
         }     //dateConvert
    Thanks in advance.

    Actually I'm in Hartford, CT, where NJ sends its rain! I used to live in Staten Island which is close to NJ as you know. Also worked in Parsippany for a while.
    I think "Date" needs to be changed to "java.util.Date" in three places. See comments below where changes are marked. I could not compile or test because I don't have Domino / Notes.
    By the way, in case you get similar problems with another class (Calendar?), I believe that the lotus.domino classes are AgentBase, AgentContext, Session and DateTime. The others should be standard Java classes. Good Luck.
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import lotus.domino.*;
    public class CalcBusinessDays extends AgentBase {
        public void NotesMain() {
            DateTime startTime = null, endTime = null;
            String startTimeStr, endTimeStr, result;
            try {
                Session session = getSession();
                AgentContext agentContext = session.getAgentContext();
                startTimeStr = "04/12/2000";
                endTimeStr = "05/04/2000";
                startTime = session.createDateTime(startTimeStr);
                endTime = session.createDateTime(endTimeStr);
                result = diffInWeekdays(startTime, endTime, startTimeStr,
                endTimeStr);
                System.out.println("Result = " + result);
            } catch(Exception e) {
                e.printStackTrace();
        } //NotesMain
        public String diffInWeekdays(DateTime startTime, DateTime endTime, String startTimeStr, String endTimeStr) {
            String res = "";
            try {
                Date firstDate = null, secondDate = null;
                int diffInt = endTime.timeDifference(startTime);
                int diffIntDays = (diffInt / 86400 + 1);
                BigInteger sev = BigInteger.valueOf(7);
                BigInteger minusTwo = BigInteger.valueOf(-2);
                BigInteger bis = BigInteger.valueOf(getWeekday(firstDate = dateConvert(startTimeStr)));
                BigInteger bie = BigInteger.valueOf(getWeekday(secondDate = dateConvert(endTimeStr)));
                int strtDay = bis.mod(sev).intValue();
                int endDay = bie.mod(sev).intValue();
                int max = minusTwo.max(BigInteger.valueOf(strtDay * -1)).intValue();
                int min = BigInteger.valueOf(1).min(bie.mod(sev)).intValue();
                int result = (diffIntDays - endDay + strtDay - 8) * 5 / 7 - max - min + 5 - strtDay + endDay;
                //o.println("result =\t" + result);
                res = Integer.toString(result);
            } catch (Exception e) {
                e.printStackTrace();
            return res;
        } //diffInWeekdays
        public java.util.Date dateConvert(String dt) {          // *** changed
            SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy");
            ParsePosition pos = new ParsePosition(0);
            java.util.Date covDate = sdf.parse(dt, pos);       // *** changed
            return covDate;
        } //dateConvert
        public int getWeekday(java.util.Date cdt) {            // *** changed
            Calendar cal = Calendar.getInstance();
            cal.setTime(cdt);
            return cal.get(Calendar.DAY_OF_WEEK);
        } //getWeekday
    } //CalcBusinessDays

  • One to many mappings and combination generation

    Please help folks,
    I want to perform one to many mapping i.e a single row of data will be taken from a single table Table 'A' into Hashtable A and it has to be matched with 'n' number of rows from another table Table 'B' taken into Hashtable B. The no. of rows selected from B can be 1/2.... upto n. For performing this mapping iam using a Combination Generator Code which will Key nos. to be selected for checking whether they can be mapped and then further processing is done on these key nos. returned by the combination generator. The code for combination generator is given below.
    The issue is say if there are about 50 rows in table B then no of combinations possible are 2 ^ 50, which is just too much for the PC to handle i.e the code takes about 4-5 days of processing time. 256 MB RAM, P4. The mapping has to be done in 30 minutes!!!! Ne ideas folks????
    // Systematically generate combinations.
    import java.math.BigInteger;
    public class CombinationGenerator {
    private int[] a;
    private int n;
    private int r;
    private BigInteger numLeft;
    private BigInteger total;
    // Constructor
    public static void main(String[] args)
    String[] elements = {"a", "b", "c", "d", "e", "f", "g"};
    int[] indices;
    CombinationGenerator x = new CombinationGenerator (elements.length, 3);
    StringBuffer combination;
    while (x.hasMore ()) {
    combination = new StringBuffer ();
    indices = x.getNext ();
    for (int i = 0; i < indices.length; i++) {
    combination.append (elements[indices[i]]);
    System.out.println (combination.toString ());
    public CombinationGenerator (int n, int r) {
    if (r > n) {
    throw new IllegalArgumentException ();
    if (n < 1) {
    throw new IllegalArgumentException ();
    this.n = n;
    this.r = r;
    a = new int[r];
    BigInteger nFact = getFactorial (n);
    BigInteger rFact = getFactorial (r);
    BigInteger nminusrFact = getFactorial (n - r);
    total = nFact.divide (rFact.multiply (nminusrFact));
    reset ();
    // Reset
    public void reset () {
    for (int i = 0; i < a.length; i++) {
    a[i] = i;
    numLeft = new BigInteger (total.toString ());
    // Return number of combinations not yet generated
    public BigInteger getNumLeft () {
    return numLeft;
    // Are there more combinations?
    public boolean hasMore () {
    return numLeft.compareTo (BigInteger.ZERO) == 1;
    // Return total number of combinations
    public BigInteger getTotal () {
    return total;
    // Compute factorial
    private static BigInteger getFactorial (int n) {
    BigInteger fact = BigInteger.ONE;
    for (int i = n; i > 1; i--) {
    fact = fact.multiply (new BigInteger (Integer.toString (i)));
    return fact;
    // Generate next combination (algorithm from Rosen p. 286)
    public int[] getNext () {
    if (numLeft.equals (total)) {
    numLeft = numLeft.subtract (BigInteger.ONE);
    return a;
    int i = r - 1;
    while (a[i] == n - r + i) {
    i--;
    System.out.println("inside while");
    a[i] = a[i] + 1;
    for (int j = i + 1; j < r; j++) {
    a[j] = a[i] + j - i;
    numLeft = numLeft.subtract (BigInteger.ONE);
    return a;

    Next time you post, see the formatting guidelines [url http://forum.java.sun.com/features.jsp#Formatting]here. //--------------------------------------
    // Systematically generate combinations.
    import java.math.BigInteger;
    public class CombinationGenerator {
    private int[] a;
    private int n;
    private int r;
    private BigInteger numLeft;
    private BigInteger total;
    // Constructor
    public static void main(String[] args)
    String[] elements = {"a", "b", "c", "d", "e", "f", "g"};
    int[] indices;
    CombinationGenerator x = new CombinationGenerator (elements.length, 3);
    StringBuffer combination;
    while (x.hasMore ()) {
    combination = new StringBuffer ();
    indices = x.getNext ();
    for (int i = 0; i < indices.length; i++) {
    combination.append (elements[indices]);
    System.out.println (combination.toString ());
    public CombinationGenerator (int n, int r) {
    if (r > n) {
    throw new IllegalArgumentException ();
    if (n < 1) {
    throw new IllegalArgumentException ();
    this.n = n;
    this.r = r;
    a = new int[r];
    BigInteger nFact = getFactorial (n);
    BigInteger rFact = getFactorial (r);
    BigInteger nminusrFact = getFactorial (n - r);
    total = nFact.divide (rFact.multiply (nminusrFact));
    reset ();
    // Reset
    public void reset () {
    for (int i = 0; i < a.length; i++) {
    a = i;
    numLeft = new BigInteger (total.toString ());
    // Return number of combinations not yet generated
    public BigInteger getNumLeft () {
    return numLeft;
    // Are there more combinations?
    public boolean hasMore () {
    return numLeft.compareTo (BigInteger.ZERO) == 1;
    // Return total number of combinations
    public BigInteger getTotal () {
    return total;
    // Compute factorial
    private static BigInteger getFactorial (int n) {
    BigInteger fact = BigInteger.ONE;
    for (int i = n; i > 1; i--) {
    fact = fact.multiply (new BigInteger (Integer.toString (i)));
    return fact;
    // Generate next combination (algorithm from Rosen p. 286)
    public int[] getNext () {
    if (numLeft.equals (total)) {
    numLeft = numLeft.subtract (BigInteger.ONE);
    return a;
    int i = r - 1;
    while (a == n - r + i) {
    i--;
    System.out.println("inside while");
    a = a + 1;
    for (int j = i + 1; j < r; j++) {
    a[j] = a + j - i;
    numLeft = numLeft.subtract (BigInteger.ONE);
    return a;
    }

  • Generating symmetric key with RSA

    Hello,
    I have a problem. I want to generate symmetric keys with the use of RSA. But RSA is not supported by Java 1.4.2 except for the signature class.
    My question is can I generate symmetric keys using RSA and Bouncy Castle provider??? Or is there a way around ???
    Thanks a lot,
    Ravi

    Or write your own RSA. here is some working code:
    ///////////////// class BigIntegerRSA /////////////////
    import java.math.*;
    import java.util.*;
    public class BigIntegerRSA {
      int bits;
      BigInteger p, q, n, nPrime, e, d;
      public BigIntegerRSA(int _bits, BigInteger _p, BigInteger _q) {
        bits=_bits;
        p=_p;
        q=_q;
        n = p.multiply(q);
        nPrime = p.subtract(BigInteger.ONE).multiply( q.subtract(BigInteger.ONE));
        e=BigInteger.ZERO;
        BigInteger TEN=new BigInteger(""+10);
        for( e = nPrime.divide(TEN); !BigIntegerUtil.gcd( e, nPrime ).equals(BigInteger.ONE); e=e.add(BigInteger.ONE)){
        d = BigIntegerUtil.inverse( e, nPrime );
      public static BigIntegerRSA generate(int _bits) {
        BigIntegerRSA rsa= null;
        boolean verified=false;
        while(!verified){
          BigInteger p=BigInteger.probablePrime(_bits/2+1,new Random(System.currentTimeMillis()));
          BigInteger q=BigInteger.probablePrime(_bits/2+1,new Random(System.currentTimeMillis()));
          rsa= new BigIntegerRSA(_bits,p,q);
          verified= rsa.verify();
        return rsa;
      public BigIntegerRSAPublicKey getPublicKey(){
        return new BigIntegerRSAPublicKey(bits,e,n);
      public BigIntegerRSAPrivateKey getPrivateKey(){
        return new BigIntegerRSAPrivateKey(bits,d,n);
      public boolean verify() {
        //e * d % ( nPrime ) == 1
        BigInteger multiplied=e.multiply(d).mod(nPrime);
        if(!multiplied.equals(BigInteger.ONE)){
          return false;
        //test random
        BigIntegerRSAPublicKey pub=getPublicKey();
        BigIntegerRSAPrivateKey priv=getPrivateKey();
        BigInteger message, encoded, decoded;
        //random
        message=new BigInteger(bits-2, new Random(System.currentTimeMillis()));
        encoded=pub.code(message);
        decoded=priv.decode(encoded);
        if(!message.equals(decoded)){
          System.out.println("Failed to encode and decode "+message);
          return false;
        return true;
      public static void main( String [ ] args ){
        BigIntegerRSA rsa=BigIntegerRSA.generate(512);
        BigIntegerRSAPublicKey pub=rsa.getPublicKey();
        BigIntegerRSAPrivateKey priv=rsa.getPrivateKey();
        BigInteger message=new BigInteger("2938798723423429020");
        System.out.println( "message: " + message );
        BigInteger code = pub.code(message);
        BigInteger decode = priv.decode(code);
        System.out.println( "Code: " + code );
        System.out.println( "Decode: " + decode );
    ///////////////// class BigIntegerRSAPublicKey /////////////////
    import java.math.*;
    import java.util.*;
    public class BigIntegerRSAPublicKey{
      int bits;
      BigInteger e,n;
      public BigIntegerRSAPublicKey(int _bits, BigInteger _e, BigInteger _n) {
        bits=_bits;
        e=_e;
        n=_n;
      public BigInteger code(BigInteger message) {
        if(message.bitLength()>bits){
          return null;//"Cannot encode anything with more bits than bits while message had message.bitLength() bits
        return message.modPow(e,n);
    ///////////////// class BigIntegerRSAPrivateKey /////////////////
    import java.math.*;
    import java.util.*;
    public class BigIntegerRSAPrivateKey {
      int bits;
      BigInteger d, n;
      public BigIntegerRSAPrivateKey(int _bits, BigInteger _d, BigInteger _n) {
        bits=_bits;
        d=_d;
        n=_n;
      public BigInteger decode(BigInteger code)  {
        if(code.compareTo(n)>0){
          return null;//Cannot decode anything greater than n while code was code
        return code.modPow(d,n);
    ///////////////// class BigIntegerUtil /////////////////
    import java.math.*;
    import java.util.*;
    public class BigIntegerUtil {
      // Internal variables for fullGcd
      private static BigInteger x;
      private static BigInteger y;
      public static BigInteger gcd( BigInteger a, BigInteger b )
        if( b.equals(BigInteger.ZERO) )
          return a;
        else
          return gcd( b, a.mod(b) );
      public static BigInteger inverse( BigInteger a, BigInteger n )
        fullGcd( a, n );
        return x.compareTo(BigInteger.ZERO)>0 ? x : x.add(n);
      private static void fullGcd( BigInteger a, BigInteger b )
        BigInteger x1, y1;
        if( b.equals(BigInteger.ZERO) )
          x = BigInteger.ONE;
          y = BigInteger.ZERO;
        else
          fullGcd( b, a.mod(b) );
          x1 = x; y1 = y;
          x = y1;
          y = x1.subtract(( a.divide(b) ).multiply(y1));
    }And since BigInteger has the methods .toByteArray() and new BigInteger(byte[] b) this is perfect for encrypting and decrypting anything, eg a DES key or some other symmetric encryption

  • Nth digit term of the fibonacci series

    hi everyone i want to find the nth digit term of the fibonacci series like 144 is the 12th term and is the 1st term to contain 3 digits
    so i made the following code
    import java.math.*;
    class FibNew
    BigInteger d=new BigInteger("1");
    BigInteger a=new BigInteger("5");
    BigInteger b=new BigInteger("8");
    BigInteger e=new BigInteger("1");
    BigInteger c=new BigInteger("1");
    int count=1,i;
              FibNew()
              while(count!=3)//To calculate the first number with 3 digits
                        c=a.add(b);
                        a=b.multiply(d);     //assiging a=b
                        b=c.multiply(d);     //assiging b=c               
                        e=c.divide(BigInteger.valueOf(10));               
                        System.out.println(e);
                           if(e.equals("0")==false)
                               for(i=1;i<=10;i++)
                                  e=e.divide(BigInteger.valueOf(10));
                                  if(e.equals("0")==false)
                                            count++;
                   }//ending of while loop
               }//ending of constructor
              public static void main(String args[])
              FibNew f=new FibNew();
    }i cant find whats wrong with this it should print the value of e,but it doesnt
    i used BigINtegers as i want to also find the first nth term with 1000 digits,the series starts from 5,8,13,21.........
    Message was edited by:
    Code-x

    Use this instead. It reroutes the error stream to a text file because
    it will always be too long to read in any command window.
    I also added a timer.
    This is the error i get after 985:
    Exception in thread "main" java.lang.StackOverflowError
         at java.math.MutableBigInteger.leftShift(MutableBigInteger.java:367)
         at java.math.MutableBigInteger.divide(MutableBigInteger.java:844)
         at java.math.BigInteger.toString(BigInteger.java:2641)
         at java.math.BigInteger.toString(BigInteger.java:2688)
         at FibonacciSequence2.getNumberOfDigits(FibonacciSequence2.java:97)
         at FibonacciSequence2.findFibNum(FibonacciSequence2.java:82)
         at FibonacciSequence2.findFibNum(FibonacciSequence2.java:89)
    import java.io.*;
    import java.math.BigInteger;
    public class FibonacciSequence2{
    public static void main(String[] args){
         new FibonacciSequence2();
    public FibonacciSequence2(){
         start();
    public void start(){
         System.out.println("\n===FIBONACCI'S SEQUENCE===\n");
         try{
         PrintStream errorStream = new PrintStream(new File("ErrorLog.txt"));
         System.setErr(errorStream);
         br = new BufferedReader(new InputStreamReader(System.in));
         while(true){
         prompt();
         } catch(Exception e){
         e.printStackTrace();
    public void prompt() throws Exception{
         System.out.print("Find Digit Size: ");
         String line = br.readLine();
         int digitSize = parseString(line);
         if(digitSize > 0){
         BigInteger n1 = new BigInteger("0");
         BigInteger n2 = new BigInteger("1");
         answer = BigInteger.ZERO;
         position = 0;
         long startTime = System.currentTimeMillis();
         findFibNum(n1, n2, digitSize, 1);
         long stopTime = System.currentTimeMillis();
         System.out.println("Time: " + (stopTime - startTime) + " ms");
         System.out.println("Position: " + position);
         System.out.println("Value: " + answer.toString());
         System.out.println();
    public int parseString(String number){
         try{
         int n = Integer.parseInt(number);
         return n;
         } catch(Exception e){
         System.out.println("Error: Invalid Number");
         return 0;
    public void findFibNum(BigInteger n1, BigInteger n2, int digitSize, int iter){
         iter ++;
         BigInteger sum = n1.add(n2);
         if(getNumberOfDigits(sum) >= digitSize){
         position = iter;
         answer = sum;
         } else {
         findFibNum(n2, sum, digitSize, iter);
    public int getNumberOfDigits(BigInteger bi){
         return (bi.toString()).length();
         BufferedReader br;
         BigInteger answer = BigInteger.ZERO;
         int position = 0;
    }

  • Efficient mixed use of BigInteger and int ?

    I need to calculate a cost, which can be arbitrary large. To calculate this cost,
    I need to do very small steps, each small step has a cost within [1,10000].
    Is it a good idea to use the following strategy. Are there any better ones ?
    BigInteger calculateCost() {
    1__ BigInteger totalCost = BigInteger.ZERO;
    2__ int smallCost = 0;
    3__ while(model.step()) { //keep on stepping until done
    4_____ smallCost += model.getStepCost();
    5_____ if ((smallCost & 0x40000000) > 0) { //look if second bit is set
    6________ totalCost = totalCost.add(BigInteger.valueOf(smallCost));
    7________ smallCost = 0;
    8_____ }
    9__ }
    10_ totalCost = totalCost.add(BigInteger.valueOf(smallCost));
    11_ return totalCost;
    jpwinne

    Well, if it were me coding it, I'd eliminate the
    "smallCost" variable and simply add each item to the
    BigInteger. I mean, it seems the only reason you're
    doing it that way is for performance. But if you're
    so concerned about performance, why is the
    system/component coded in java in the first place?Just because you are using Java it is not a good reason to ignore performance altogether. For many appliances, the differance between the Java and other languages aint that big as other unchangable overheads comes into play (network congestion, databases, user interaction), but if performance is ignored, this could radically change. The choice of selecting good algorithm is still a very valid consideration, or as I usually told my students in the old days "If you code a sucky bubblesort in C and an efficient quicksort in Java, does that mean Java is faster than C?". Any application that disregards performance adds to the "Java is so slow" image that it honestly does not deserve for most applications.
    For "better" alternatives, I would think there is only one, and that is to use a long as remistigri suggested. Not sure thou from the context if this is a viable solution for you, since you will limit yourself to values under Long.MAX_VALUE. Double could also be an alternative, but with the known drawbacks of precision loss.
    You peaked my interest on what you are doing to be honest as I yet have not been involved in an application needing the use of BigInteger, if I exclude crypthograph applications.
    Regards,
    Peter Norell

  • Type cast of BigInteger to Int

    Hi All,
       I am working on Email Web Service with Web dynpro.
    I am getting an error in type casting BigInterger(which was declared in WSDL) to Int. Java is not recognizing this BigInteger. Can any one help me??
    Regards,
    Theja

    Thejaswi,
    Where exactly this happens?
    I mean, if you can control this part of code why not to do:
    BigInteger bigInt = <...>;
    int int = bigInt.intValue();
    VS

  • Outputting BigInteger Results one line at a time

    hi all,
    im new to this. im havin problems with my code. i was to read into two Bigintegers and multi[ply them.. but with the multiplication i want to show each line as it is being done and send it to the screen. as u can see from the code i was hopin to do it in two parts. the first gettin the result and the second just workin it out line by line. is this a good way to do it?  i was tryin to read the last digit and work up to the work up to the first but i cant do it. here is a snippet of the calucatations.. i really hope someone can help cause im really stuck at this point
    thanks a million
    al.
    BigInteger num1 = new BigInteger(textAreaNum1.getText());
        BigInteger num2 = new BigInteger(textAreaNum2.getText());
        result = num1.multiply(num2);
        totalDigit = num2;
        currDigit= num2;
        for (BigInteger ix = BigInteger.ZERO; ix.compareTo(totalDigit) < 0; ix = currDigit.add(BigInteger.ONE))
          currResult = currDigit.multiply(num1);
          textAreaCalculation.setText("" + num1 + "" + zeroAdder);
    textAreaResult.setText(""+ result);
    // the resultin screen should look like
    // 234
    // *123
    // 702
    // 4680
    // 23400
    // 28782

    this is my program as it stands but with another class callin the frame.. so u want me to change the textfield to jtextfield?
    package Mulitply;
    import java.awt.*;
    import java.awt.event.*;
    import java.math.BigInteger;
    import javax.swing.JTextArea.*;
    * Title: Mulitplier of Large Numbers
    * Description: This class extends the application class and add all
    * all the data below to it. it basically sets up the frame
    * in terms of look,feel and action.
    * Copyright: Copyright (c) 2004
    * Company:
    * author
    * version 1.0
    class CalcFrame extends Frame implements ActionListener{
    Button btnMult;
    TextField textAreaNum1, textAreaNum2, textAreaCalculation, textAreaResult;
    public CalcFrame() {
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    setSize(1000, 300);
    setTitle("Mulitpler");
    setLayout(new FlowLayout());
    setBackground(Color.lightGray);
    Panel pnlNums = new Panel();
    Panel pnlBtns = new Panel();
    Panel pnlCalculation = new Panel();
    Panel pnlResult = new Panel();
    setLayout(new GridLayout(3, 1));
    textAreaNum1 = new TextField(50);
    textAreaNum2 = new TextField(50);
    pnlNums.add(textAreaNum1);
    pnlNums.add(textAreaNum2);
    btnMult = new Button("*");
    btnMult.addActionListener(this);
    pnlBtns.add(btnMult);
    textAreaCalculation = new TextField(50);
    textAreaResult = new TextField(50);
    pnlResult.add(textAreaResult);
    pnlCalculation.add(textAreaCalculation);
    add(pnlNums);
    add(pnlBtns);
    add(pnlCalculation);
    add(pnlResult);
    public void actionPerformed(ActionEvent e) {
    String str1 = textAreaNum1.getText().trim();
    String str2 = textAreaNum2.getText().trim();
    int len1 = str1.length();
    int len2 = str2.length();
    if ( (len1 == 0) || (len2 == 0))
    return;
    BigInteger num1 = new BigInteger(str1);
    BigInteger num2 = new BigInteger(str2);
    BigInteger result = num1.multiply(num2);
    String resultStr = result.toString();
    int resultLen = resultStr.length();
    textAreaCalculation.setText("");
    textAreaCalculation.append(str1 + "\n");
    textAreaCalculation.append("*" + str2 + "\n");
    textAreaCalculation.append(pad(resultLen, "--") + "\n");
    BigInteger ten = new BigInteger("10");
    for (int i = (len2 - 1); i >= 0; i--) {
    BigInteger curNum = new BigInteger(str2.substring(i, i + 1));
    BigInteger curRes = curNum.multiply(num1);
    for (int j = 0; j < len2 - 1 - i; j++)
    curRes = curRes.multiply(ten);
    String curResStr = curRes.toString();
    int curResLen = curResStr.length();
    textAreaCalculation.append(pad(resultLen - curResLen, "--") + curResStr + "\n");
    textAreaCalculation.append(pad(resultLen, "--") + "\n");
    textAreaCalculation.append(resultStr + "\n");
    String pad(int n, String s) {
    String ret = "";
    for (int i = 0; i < n; i++)
    ret += s;
    return ret;
    }

  • BigInteger toByteArray Question

    Hi all,
    I want to convert BigInteger into byte array using toByteArray method.
    However, some errors occur. The length of byte i get from conversion is not same as the original byte length. some are less than original but some are larger.
    I have read a 100 byte from a file each time and then convert the byte array into BigInteger for some modulus operation. Finally, i am able to get back the original BigInteger. when i try to convert these BigInteger into byte array, problem arise. some byte array length is 99, some are 100 and some are 101.
    Why these happen?
    and how to make the conversion successfully?
    Thanks

    yes.
    // Convert the 100 byte array to BigInteger
    // open file
    byte[] fileByte = MyUtil.openFile("2.jpg");
    // New Add Implementation RSA Block
    int fileSize = fileByte.length;
    int lastBlockSize = fileSize % blockSize;
    int numBlock = fileSize / blockSize;
    if (lastBlockSize > 0)
    numBlock++;
    System.out.println("num Block "+numBlock);
    System.out.println("last Block Size " + lastBlockSize);
    BigInteger[] fileBI = new BigInteger[numBlock];
    int j = 0;
    for (int i=0; i<numBlock; i++)
         byte[] RSABlock = null;
         // copy the 100 fileByte into RSABlock
         if (i==numBlock-1)
         RSABlock = new byte[lastBlockSize];
         System.arraycopy(fileByte,j, RSABlock,0,lastBlockSize);
         else
         RSABlock = new byte[blockSize];
         System.arraycopy(fileByte,j, RSABlock,0,blockSize);
         j=j+blockSize;
         fileBI[i] = new BigInteger(1,RSABlock); // absolute BigInteger
         System.out.println("Original " + i + " " + fileBI);
    // Convert the BigInteger to byte array
    for (int i=0; i<customerDe.length; i++ )
    if (customerDe[i].compareTo(BigInteger.ZERO) <0 )
    System.out.print("NEGATIVE NUMBER");
         if (customerDe[i].compareTo(fileBI[i]) != 0)
         System.out.println("Not Match " + i);
         System.out.println("diff: "+customerDe[i].subtract(fileBI[i]));
         System.exit(1);
         byte[] decryptSigned = customerDe[i].toByteArray();
         byte[] decryptUnsigned = null;
         // if the decryptSigned doesn't have leading Sign || the length is one
         if (decryptSigned[0] != 0x00 || decryptSigned.length == 1)
         System.out.println("UNSigned BYTE "+i);
         decryptUnsigned = decryptSigned;
         System.out.println(i + " len "+ decryptUnsigned.length);
         else if (decryptSigned[0] == 0x00)
         System.out.println("Signed BYTE "+i);
         decryptUnsigned = new byte[decryptSigned.length-1];
         System.arraycopy(decryptSigned,1,decryptUnsigned,0,decryptUnsigned.length);
         System.out.println(i + " len "+ decryptUnsigned.length);
         if (decryptSigned.length == blockSize-1)
         decryptUnsigned = new byte[decryptSigned.length+1];
         System.arraycopy(decryptSigned,0,decryptUnsigned,1,decryptSigned.length);
         baos.write(decryptUnsigned,0,decryptUnsigned.length);

  • Convert from BigInteger object to BigInteger[]????

    hi all,
    I have some list of integers as string and I change them to BigInteger object like:
    BigInteger myint=new BigInteger(mytext);
    Now I need to pass myint to a function which accpets BigInteger[] as argument.
    public static String Decrypt(BigInteger[] ciphertext)
    how can i change BigInteger object to BigInteger[] (is it an array??)???
    urs all

    Array is an object but you cannot cast or convert to it from what you have.
    What you need to do is declare a BigInteger array and add the BigIntegers to it
    int ARRAY_SIZE = 10;
    BigInteger []myArray = new BigInteger[ARRAY_SIZE];
    for (int i=0; i<ARRAY_SIZE; i++)
    myArray[i] = new BigInteger(mytext);
    If you can figure out the size of the array, then you are golden.

  • Conversion of long and int: strange result and no warning

    Why does Java allow this?
    long l = Long.MAX_VALUE / 10;
    System.out.println(l); // result 922337203685477580
    int i = (int)l;
    System.out.println(i); // result -858993460The compiler accepts it and the runtime accepts it. Why? Complete nonsense is the result!
    The same happens with using a Long object and calling the intValue() method.
    Can someone explain it to me?

    What do you think of operator overloading?Well, I don't have much influence -:) But this is what Guy Stele, SUN Fellow, say:
    Overloaded operators are still a subject of controversy. They are almost indispensable for certain kinds of mathematical work, but people who oppose adding them to the Java language point out, quite rightly, that the feature was badly abused in C++ for nonmathematical purposes, making code much harder to read than necessary. Most Java applications are nonmathematical in nature. One could make a good argument that commercial applications have no need for operator overloading, except that commercial applications do use (or should use) BigDecimal arithmetic, and it would be really nice to be able to use + and - and * and / with BigDecimal numbers. Much the same can be said of so-called "lightweight classes": their greatest value would lie in supporting numerical concepts such as complex numbers and interval arithmetic.
    We have an interesting decision to make that is more a political or business question than a technical one: should the Java language be extended to support the needs of mathematical applications? If so, then I would argue strongly for introducing operator overloading and lightweight classes -- I'm pretty sure such facilities would also get used for other purposes. If not, then maybe we should just make + and - and * and / work for the BigInteger and BigDecimal classes as a special case, much the same way that + is already a special case for the String class.

Maybe you are looking for