Thursday 27 May 2010

JavaFX introduction to variables

JavaFX variables are a bit different from other languages e.g. Java and C++. They are more like in PHP. You do not need declare the type of the variable. The compiler is clever enough to do it for you. So there are two ways in which you declare variables.
First of them, which allows you to declare variable that you will be able to change during the course of application:

var myVar;
var myVar = 0;

Second of them, which allows you to declare the variables that cannot be changed (something like final in Java):

def myVar;
def myVar = 0;

Above I sad that variables with def cannot be changed. It is not entirely true. JavaFX provides mechanism called binding, which allows two variables to be connected. I'll not discuss it in here. It'll be described soon in the future.

At the beginning I wrote that you do not need to declare the type of the variable. You can do it if you want. Here is the way you do it:

var myInteger: Integer;
def myInteger: Integer = 0;

In that case the myInteger is declared to hold Integer value.
Similarly to other languages JavaFX has the following data types:
Boolean
Short
Byte
Integer
Number
Double
String
Character
Duration
etc.

If you want in depth description of them, you should consult JavaFX API:

http://java.sun.com/javafx/1.3/docs/api/

I would point your attention to the Number type. In the current version of the language this type behaves the same as Java's Float. The other type is Duration, which stores values like:
60s
5m
1h
They represent the time duration. Once again it is wise to search the API for in depth description.

The same as Java, JavaFX assigns default values to variables which haven't been initialized with a value. Number gets 0.0, String "", Integer 0 and any reference type is initialized with null.

Cheers

No comments:

Post a Comment