# Solved: java arrayIndexOutOfBounds



## redivivus (Mar 30, 2006)

Hi i keep getting an error about arrayIndexOutOfBounds in this function. The number it gives seems to be 5, regardless of the length of the strings it is called with.

Not sure why. Here is the code snippet...

If you see why i would be getting this error can you please point it out... i must be blind or not know how to use getBytes properly. 


```
String s = a.decrypt("string1","my1timepad");
```


```
public String decrypt(String kp3,String otcode)
    {
        byte chats[] = new byte[kp3.length()];
        int r = kp3.length()-1;
        kp3.getBytes(0,r,chats,0);
        while (otcode.length()<kp3.length())
        {
            otcode=otcode+otcode;
        }
        byte code[] = new byte[otcode.length()];
        int q = otcode.length()-1;
        otcode.getBytes(0,q,code,0);
        String returnz="";
        for (int p=0;p<=r;p++)
        {
            returnz=returnz+(char)((chats[p]-code[p]) % 126);
        }
        return returnz;
    }
```
Thanks for looking.


----------



## Chicon (Jul 29, 2004)

Hi redivivus,

The method you're using to convert a string into an array of bytes is deprecated. 
Link : http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html

The following code should work considering that kp3 and otcode are not null or empty.


```
[SIZE=2]

   public String decrypt(String kp3,String otcode)
    {
        byte chats[] = new byte[kp3.length()];
        chats = kp3.getBytes();
        while (otcode.length()<kp3.length())
        {
            otcode=otcode+otcode;
        }
        byte code[] = new byte[otcode.length()];
        code = otcode.getBytes();
        String returnz="";
        for (int p=0;p<kp3.length();p++)
        {
            returnz=returnz+(char)((chats[p]-code[p]) % 126);
        }
        return returnz;
    }
[/SIZE]
```


----------



## redivivus (Mar 30, 2006)

Thanks, the new getBytes looks much easier to use lol. :up:


----------



## redivivus (Mar 30, 2006)

To make a long story short, getBytes worked :up: but became unsuitable because i could not transfer any chars of byte 0-31 or 126+ without losing them.

So i adapted and now im getting this error, whenever the string being encrypted or decrypted (String a) is longer than 5 characters... otherwise it works perfectly.

Exception in thread "Thread-15" java.lang.OutOfMemoryError: Java heap space

Dont know how to make it use less memory... thought it was already pretty decent lol. 


```
String result = a.decrypt("hello!","codelessthan18long");
```


```
public String decrypt(String a,String b)
    {
        int r=a.length();
        int q=b.length();
        int a1[] = new int[r];
        a1 = gbs(a);
        while (q<r)
        {
            b+=b;
        }
        int b1[] = new int[q];
        b1 = gbs(b);
        for (int i=0;i<=r-1;i++)
        {
            a1[i]=((a1[i]-b1[i]) % 94);
        }
        String sss=gcs(a1,r);
        return sss;
    }

    public String encrypt(String a,String b)
    {
        int r=a.length();
        int q=b.length();
        int a1[] = new int[r];
        a1 = gbs(a);
        while (q<r)
        {
            b+=b;
        }
        int b1[] = new int[q];
        b1 = gbs(b);
        for (int i=0;i<=r-1;i++)
        {
            a1[i]=((a1[i]+b1[i]) % 94);
        }
        String sss=gcs(a1,r);
        return sss;
    }
    
    private int[] gbs(String sss)
    {
        int r=sss.length();
        int[] blah = new int[r];
        for(int i=0;i<=r-1;i++)
        {
            blah[i]=gb(sss.charAt(i));
        }
        return blah;
    }
    
    private String gcs(int[] blah, int q)
    {
        String sss="";
        for (int i=0;i<=q-1;i++)
        {
            sss=sss+gc(blah[i]);
        }
        return sss;
    }
    
    private int gb(char a)
    {
        return ((byte)(a)-32);
    }

    private char gc(int a)
    {
        return ((char)(a+32));
    }
```
Any ideas guys? Thanks.


----------



## Chicon (Jul 29, 2004)

I've tested your piece of coding : it works nicely on my IDE. It is not the source of the error you get.
You probably need to set the Heap size of the Java VM : just learn about *Specifying Heap Size Values*.
Also, make sure of the way you're using the class where the coding is located to avoid each instantiation of the class being stacked in the memory.


----------



## Chicon (Jul 29, 2004)

For info :


```
[SIZE=2]How to remove an instance of a Java class from the memory
---------------------------------------------------------
There are two possibilities :
---------------------------
a) from within the class itself

with the command [COLOR=Red]System.gc()[/COLOR]
   the method [I]gc[/I] from the [I]System[/I] class invokes the [I]garbage collector[/I]

Beware : this command may be used as a last statement of a method,
         therefore it doesn't apply to methods that return values

b) from outside the class

Example :

[COLOR=Blue]MyClass mc = New MyClass();
.
.
.[/COLOR]
[COLOR=Red]mc = null;[/COLOR]
   that command will force the [I]garbage collector[/I] to remove the class [I]mc[/I] from
the memory.[/SIZE]
```


----------



## redivivus (Mar 30, 2006)

Thanks for this info Chicon.

As it is right now the class is running until the applet closes, but it is needed every 20 seconds to 1 minute. There are also a few other functions in the class that are needed every couple seconds. I will try making a new, smaller class for these functions and call it every time it is needed, then remove it, to see if it fixes the error. :up:


----------



## redivivus (Mar 30, 2006)

Note: If you are not bored and looking to help hopeless ppl, you can ignore this and il figure it out sooner or later. 

---

Hmm... this thread is almost solved lol.

It half works. :-\ I added debugging info.... This is just to show the strange difference that happens when the thread is called in the exact same fashion from 2 different areas... one when its recieved and one when its outgoing. I have checked and none of the values used are null, and the object has been initiated prior to the call.



decrypt said:


> cUp invoked
> a=HELLO
> b=GeT2KnOwMe
> crypt called!
> ...





encrypt said:


> cUp invoked
> a=ttest
> b=abc
> crypt called!
> ...


If you havent given up hope on me yet, here is the class that i made. The code is almost the same as before. Debug info is in red.


```
chatMsg = new myCC(this);
```


```
chatMsg.cUp(string1,string2);
string1=chatMsg.crypt(0); //decrypt
chatMsg.cUp(string1,string2);
string1=chatMsg.crypt(1); //encrypt
```


```
import java.util.*;
import java.io.*;

class myCC
{
    
    public myCC(clientrun clientrun1)
    {
        [COLOR="Red"]System.out.println("myCC imp in");[/COLOR]
        a="";
        b="";
        parent=clientrun1;
    }
    
    public void cUp(String x,String y)
    {
        [COLOR="red"]System.out.println("cUp invoked");[/COLOR]
        a=x;
        b=y;
        [COLOR="red"]System.out.println("a="+a);
        System.out.println("b="+b);[/COLOR]
    }
    
    public String crypt(int g)
    {
        [COLOR="red"]System.out.println("crypt called!");[/COLOR]
        int r=a.length();
        int q=b.length();
        int a1[] = new int[r];
        [COLOR="red"]System.out.println("calling gbs, a="+a);[/COLOR]
        a1 = gbs(a);
        while (q<r)
        {
            b=b+b;
        }
        int b1[] = new int[q];
        [COLOR="red"]System.out.println("calling gbs, b="+b);[/COLOR]
        b1 = gbs(b);
        if (g==0) // decrypt
        {
            [COLOR="red"]System.out.println("decrypting! r:"+r);[/COLOR]
            for (int i=0;i<=r-1;i++)
            {
                a1[i]=((a1[i]-b1[i]) % 94);
                [COLOR="red"]System.out.println("a1["+i+"]="+a1[i]);[/COLOR]
            }
            [COLOR="red"]System.out.println("decrypt complete.");[/COLOR]
        }
        if (g==1) // encrypt
        {
            [COLOR="red"]System.out.println("encrypting!");[/COLOR]
            for (int i=0;i<=r-1;i++)
            {
                a1[i]=((a1[i]-b1[i]) % 94);
                [COLOR="red"]System.out.println("a1["+i+"]="+a1[i]);[/COLOR]
            }
            [COLOR="red"]System.out.println("encrypt complete.");[/COLOR]
        }
        [COLOR="red"]System.out.println("about to get chars");[/COLOR]
        String sss=gcs(a1,r);
        [COLOR="red"]System.out.println("about to return sss:"+sss);[/COLOR]
        return sss;
    }
    
    private int[] gbs(String sss)
    {
        [COLOR="red"]System.out.println("gbs called");[/COLOR]
        int r=sss.length();
        int[] blah = new int[r];
        for(int i=0;i<=r-1;i++)
        {
            blah[i]=gb(sss.charAt(i));
        }
        return blah;
    }
    
    private String gcs(int[] blah, int q)
    {
        [COLOR="red"]System.out.println("gcs called");[/COLOR]
        String sss="";
        for (int i=0;i<=q-1;i++)
        {
            sss=sss+gc(blah[i]);
        }
        return sss;
    }
    
    private int gb(char a)
    {
        [COLOR="red"]System.out.println("gb called");[/COLOR]
        return ((byte)(a)-32);
    }

    private char gc(int a)
    {
        [COLOR="red"]System.out.println("gc called");[/COLOR]
        return ((char)(a+32));
    }
    
    String a;
    String b;
    clientrun parent;
}
```


----------



## redivivus (Mar 30, 2006)

Thanks to that post i found my error when reading it through. :up: (forgot to update q! grrr )


----------



## Chicon (Jul 29, 2004)

redivivus said:


> Thanks to that post i found my error when reading it through. :up: (forgot to update q! grrr )


:up: Such things also happen to me ! Sometimes, we have to remove the dust from our eyes.


----------



## redivivus (Mar 30, 2006)

Chicon said:


> :up: Such things also happen to me ! Sometimes, we have to remove the dust from our eyes.


Yep. 

Wow. Check out my other error... they are all negative. 

encrypting!
a1[0](-39)-b1[0](84) % 94=-123
a1[1](-18)-b1[1](87) % 94=-105
a1[2](-10)-b1[2](79) % 94=-89
a1[3](0)-b1[3](84) % 94=-84
a1[4](-82)-b1[4](82) % 94=-164
a1[5](12)-b1[5](65) % 94=-53
a1[6](2)-b1[6](67) % 94=-65
a1[7](-75)-b1[7](75) % 94=-150
a1[8](-18)-b1[8](83) % 94=-101
a1[9](0)-b1[9](84) % 94=-84
a1[10](-87)-b1[10](87) % 94=-174
a1[11](-20)-b1[11](79) % 94=-99
a1[12](-67)-b1[12](84) % 94=-151
a1[13](-63)-b1[13](82) % 94=-145
a1[14](-48)-b1[14](65) % 94=-113
a1[15](-55)-b1[15](67) % 94=-122
a1[16](-56)-b1[16](75) % 94=-131
a1[17](-66)-b1[17](83) % 94=-149
a1[18](-23)-b1[18](84) % 94=-107
encrypt complete.
about to get chars
gcs called
gc -29 = 
gc -11 = 
gc -89 = ?
gc -84 = ?
gc -70 = ?
gc -53 = ?
gc -65 = ?
gc -56 = ?
gc -7 = 
gc -84 = ?
gc -80 = ?
gc -5 = 
gc -57 = ?
gc -51 = ?
gc -19 =

gc -28 = 
gc -37 = ?
gc -55 = ?
gc -13 = 
about to return sss:??????????
??

I just did a quick google and apparently java modulus doesnt work with negative numbers. I thought that (-int) % x was supposed to add x as many times as needed to make it positive.  Has anyone come across this? Do i need to make a custom modulus function?


----------



## Chicon (Jul 29, 2004)

There are some explanations about the % operator here :

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3

I've never tested modulus on negative values.


----------



## redivivus (Mar 30, 2006)

Chicon said:


> There are some explanations about the % operator here :
> 
> http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3
> 
> I've never tested modulus on negative values.





> 5%3 produces 2 (note that 5/3 produces 1)
> 5%(-3) produces 2 (note that 5/(-3) produces -1)
> (-5)%3 produces -2 (note that (-5)/3 produces -1)
> (-5)%(-3) produces -2 (note that (-5)/(-3) produces 1)


Yea this is peculiar. In a wikipedia example (of what im trying to use) it shows -int%x returning a positive value, as it works in C++. The reason my thing isnt working must be because (char)(-int) doesnt work too well.


----------



## redivivus (Mar 30, 2006)

Time to marked solved.  Had a - opperator rather than a + in one spot, and accidentally added 2 bytes to the beginning of the string i was trying to decrypt. 

It works now.  Imagine that! Praise the Giant Teapot (and Chicon ))


----------

