Data TypesTo create a variable in Java you must first decide on the most appropriate data type. Variables which store a small amount of data ( e.g. a number, a character) normally use a primitive data type such as int.
Variables which store multiple pieces of data use non primitive data types. This includes Strings which are used to store multiple chars ( letters). Non primative data types are often created by a programmer such as a class. |
Creating a Variable
Create a variable by stating the data type, a name and assigning a value:
string name = "Bart";
int age = 12;
string name = "Bart";
int age = 12;
Converting between data types
It is often necessary to convert a value stored in a variable from one data type to another. For example data retrieved from the keyboard will be stored as a string, but you may need to get a number from your user.
Convert a string to an integer:
string numAsText = "99" int i=Integer.parseInt(numAsText); Convert a string to an float: string numAsText = "99" Float f = Float.parseFloat(numAsText ) Convert a string to an boolean: string boolAsText = "true" boolean b=Boolean.parseBoolean(boolAsText ); |
Convert an integer to a String:
Convert a float to a String:
Convert a boolean to a String:
|
Casting
Casting is converting between similar data types:
Cast an int to a char:
Cast an int to a char:
- int a=65;
- char c=(char)a;
Constants
Constants in Java are used to define values that should not be changed throughout the execution of a program. They are typically declared using the final keyword, indicating that their value cannot be altered once initialised. Constants enhance the readability of a program as they are created with meaningful names (e,g, pi) often at the top of the class. This is better than hard coded numbers used throughout your program, which can be difficult to decipher.
final float pi = 3.14f;
( When representing a float data type in Java, append the letter f to the end of the data type; otherwise it will save as double).
final float pi = 3.14f;
( When representing a float data type in Java, append the letter f to the end of the data type; otherwise it will save as double).