Fundamentals‎ > ‎

Working with Strings

String is a fundamental value type in JavaFX. Similar to Java, the String type It is used to represent a text literals within a single or double quotes. Unlike Java, however, JavaFX string values have additional capabilities that go beyond simple text.  JavaFX Strings can be used to hold simple text a values:

var str1:String = "Hello World!";

var str2 = "Goodbye forever";

Embedding Simple Expressions in Strings

One of the interesting features of the String type in JavaFX is its ability to have expressions embedded directly in the string literal (similar to a templating languages) enclosed in curly braces:

var title = "King";

println ("The {title} has arrived!");

Embedding Complex Expressions in Strings

You can also have complex expressions embedded in your string literal values.  In the following example, the embedded expression contains a loop that traverses elements from variable evens and output the result from the nested string "{d + 1} " with each pass producing new string What are the odds 1 3 5 7 9:

var evens = [0, 2, 4, 6, 8];

println("What are the odds {for(d in evens) "{d + 1} "}");

// prints out

> What are the odds 1 3 5 7 9

Embedding Formatter Expressions in Strings

The JavaFX Sting type has the ability to process string formatting expressions based on Java's java.util.Formatter class. The code below uses format expression %,.2f to format variable amount which prints out Your house is worth $445,234.66:

var amount = 445234.66;

println ("Your house is worth ${%,.2f amount}");

// prints out

> Your house is worth $445,234.66

The materials on this website represent a small sample of content loosely based on the book JavaFX Application Development Cookbook.  The book offers far more content with over 80 recipes covering a range of topics from basics to advanced concepts.  

Buy the Book

You can get your copy of the book directly from the publisher. Click here to order!