Session 1 |
Data types
Java is a strongly typed language. This means that all operations are type-checked by the compiler for type compatibility. The type of a value determines what operations are allowed on it. An operation allowed on one type might not be allowed on another. Illegal operations are not compiled (no executable file is created).
Java contains two general categories of built-in data types: object-oriented and non-object-oriented.
String
A string is any sequence of characters – letters, digits, spaces, punctuation, and other “special characters” placed between double quotes. The data type String is not a primitive data type in Java. It is an instance of class String
. Therefore, it is called an object-oriented data type.
A few examples of strings: "abc", "12345", "<}{>", "!", "".
To print something out, use one of the following statements:
//if a statement has to be printed and the cursor must be placed on a new line, use println System.out.println("Hello, world!") // if several print statements have to be printed on the same line, use print System.out.print("Hello, world!")
Non-printable and control characters can be represented by an escape sequence, which begins with a back-slash \
followed by a pattern. The commonly-used escape sequences are:
Escape sequence | Description |
\n | new line |
\r | carriage-return |
\t | tab |
\" | double-quote |
\' | single-quote |
\\ | back-slash |
Self-assessment
What is the output of the following program?
public class HelloWorld { public static void main(String[] args){ String word = "Hello"; System.out.println(word + ", World!"); System.out.println(word + 123); System.out.println(123 + "123" + 12 + 3); } }
Run the code in IntelliJ and check your answer!
At the core of Java are eight non-object-oriented or primitive (also called elemental, simple) types of data. The term primitive is used here to indicate that these types are rather normal binary values. All of Java other data types are constructed from these primitive types.
Java built-in primitive data types:
Data type | Range |
---|---|
byte | -128 to 127 |
short | -32 768 to 32 767 |
int | -231 to 231 |
long | -263 to 263 |
float | -3.4x1038 to 34x1038 |
double | -1.8x10308 to 1.8x10308 |
boolean | true or false |
char | any symbol represented in 16-bit Unicode from '\u0000' to '\uFFFF'. |
If there is a need to convert a double into an integer, use the following statement:
double b = 10.5; int a = (int) b;
Pay attention, the precision will be lost.
PS: Java strictly specifies a value range and behaviour for each primitive type.
Literals
In Java, a literal is a fixed value that is assigned to a variable in a program.
int num = 10;
Here value 10 is an integer literal.
char ch = 'A';
Here A is a char literal.
Session 1 |