+

Search Tips   |   Advanced Search

Char/String data in Java versus JavaScript Strings

Both Java and JavaScript provide a String object. Although these two types of String objects behave in a similar fashion and offer a number of analogous functions, they differ in significant ways. For example, each object type provides a different mechanism for returning the length of a string. With Java Strings you use the length() method. JavaScript Strings on the other hand have a length variable.

var jStr_1 = new java.lang.String( "Hello, World" ); // Java String
task.logmsg( "the length of jStr_1 is " + jStr_1.length() );
	
var jsStr_A = "Hello, World"; // JavaScript String
task.logmsg( "the length of jsStr_A is " + jsStr_A.length );
This subtle difference can lead to baffling syntax errors. Trying to call jsStr_A.length() will result in a runtime error, since this object has no length() method.

Even more confounding mistakes can occur with string comparisons.

var jsStr_A = "Hello, World"; // JavaScript String
var jsStr_B = "Hello, World"; // JavaScript String

if ( jsStr_A == jsStr_B )
	task.logmsg( "TRUE" );
else
	task.logmsg( "FALSE" );
As expected, you will get a result of "TRUE" from the above snippet. However, things work a little differently with Java Strings.
var jStr_1 = java.lang.String( "Hello, World" ); // Java String
var jStr_2 = java.lang.String( "Hello, World" ); // Java String

if ( jStr_1 == jStr_2 )
	task.logmsg( "TRUE" );
else
	task.logmsg( "FALSE" );
This will result in "FALSE", since the equivalency operator above will be comparing to see if both variables reference the same object in memory, instead of matching their values. To compare Java String values, you must use the appropriate String method:
if ( jStr_1.equals( jStr_2 ) ) ...
But wait, there's more. This next snippet of code will get you a result of "TRUE":
var jsStr_A = "Hello, World"; // JavaScript String
var jStr_1 = java.lang.String( "Hello, World" ); // Java String

if ( jsStr_A == jStr_1 )
	task.logmsg( "TRUE" );
else
	task.logmsg( "FALSE" );
Since JavaScript cannot operate on an unknown type like a Java String object, it first converts jStr_1 to an equivalent JavaScript String in order to perform the evaluation.

In summary, be aware of the types of objects you are working with. And remember that Security Directory Integrator functions always return Java Objects. Keeping these factors in mind will help minimize errors in your script code.


Parent topic:

Java + Script ≠ JavaScript