• Unfortunately, we have experienced significant hard drive damage that requires urgent maintenance and rebuilding. The forum will be a state of read only until we install our new drives and rebuild all the configurations needed. Please follow our Facebook page for updates, we will be back up shortly! (The forum could go offline at any given time due to the nature of the failed drives whilst awaiting the upgrades.) When you see an Incapsula error, you know we are in the process of migration.

[Java] Switch on Strings in Java ^_^

Custom Title Activated
Loyal Member
Joined
Sep 28, 2005
Messages
1,226
Reaction score
66
Since you cant switch strings in java..someone made a funny bypass
(found it on worsethanfailure )
Code:
int helpArg = getHashValue("help");

int singleArg  = getHashValue("single");

int mutiArg = getHashValue("multi");



public static void  main (String args[])

{

    // Get a hash value for the first argument

    int hash = getHashValue(args[0].toCharArray());



    switch(hash)

    {

        case helpArg: 

            ...

            break;

        case singleArg: 

            ...

            break;

        case mutiArg: 

            ...

            break;

        // etc

    }

}

the orginal version
Code:
public static void  main (String args[])
{
    // Get a hash value for the first argument
    int hash = getHashValue(args[0].toCharArray());

    switch(hash)
    {
        case 972346: // The first argument was "help"
            ...
            break;
        case -91058: // The first argument was "single"
            ...
            break;
        case -4830672: // The first argument was "multi"
            ...
            break;
        // etc
    }
}

Attention: Some Strings can have the same hashcode but overall it should be secure to use this :)
 
Divine Celestial
Loyal Member
Joined
Jul 7, 2004
Messages
853
Reaction score
5
sage

A series of else if would work just as well, with no chance of collision.
 
Custom Title Activated
Loyal Member
Joined
Sep 28, 2005
Messages
1,226
Reaction score
66
sure it would work but its just an example how to use switch on strings :p
imagine 100 else conditions then this switch would look nicer :)
and it would work faster (the hash function takes up the speed you gain tough)

edit:
i wouldnt use it in a real project
its just a funny code snippet
 
Divine Celestial
Loyal Member
Joined
Jul 7, 2004
Messages
853
Reaction score
5
If all your strings are 4 or less characters in length, this is one way to switch (32-bit machine):
Code:
char strarray[4];
unsigned int *dordmaker = &strarray;
switch(*dordmaker) {
 case 542393671:
  ...
 case 1414745936:
  ...
 case 1145128264:
  ...
}
This gets even better on a 64-bit machine. 8 or less characters in length. Or you could use long ints on a 32-bit machine.
 
Back
Top