Tutorial : Ruby vs. Java

by toy

Ruby Instance Variables

Example:

1
@foobar

A variable whose name begins with ‘@’ is an instance variable of self. An instance variable belongs to the object itself. Uninitialized instance variables have a value of

Java Instance Variables

Example:

1
2
A a = new A();
a.variable = 0; //<-- instance variable; a variable that belong to each object.

Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in “non-static fields”, that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.
Reference http://java.sun.com/docs/books/tutorial/java/nutsandbolts/variables.html

Ruby Class Variables

Example:

1
@@foobar

Java Class Variables
Example:

1
private static int variable = 0; // <-- class variable, the variable that belongs to the class

Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.
Reference http://java.sun.com/docs/books/tutorial/java/nutsandbolts/variables.html

Ruby Global Variables

Example:

1
$foobar

A variable whose name begins with ‘$’ has a global scope; meaning it can be accessed from anywhere within the program during runtime.

Java Global Variables
Don’t have it. It is like a variable that has been declared outside all of the methods.

Ruby Constants
Example

1
FOOBAR

A variable whose name begins with an uppercase letter (A-Z) is a constant. A constant can be reassigned a value after its initialization, but doing so will generate a warning. Every class is a constant.

Trying to substitute the value of a constant or trying to access an uninitialized constant raises the NameError exception.

Java Constants

1
private final int variable = 0; // <-- final variable, the value of the variable cannot be changed.