DATA TYPE
A Data Type is a classification that precisely specifies a homogeneous set of values and the operations that can be applied to these values. For example, if we take integers as the Data Type, that is, the set of those numbers that do not have a decimal part, the operations we can perform on this set of values are arithmetic operations. Although Java is an Object-Oriented programming language, it is critical to understand that not all values we can express in Java are realized as objects.
PRIMITIVE TYPES AND REFERENCE TYPES
Primitive types are handled individually as values; they are not instances of a particular class. All other types, that is, for example, Java’s default classes and types that we create are reference types. Let us now list the primitive types with a figure.
PRIMITIVE DATA TYPE
WHOLE NUMBERS.
Starting with integers, Java defines four variants, which we see represented in the figure. All integer types are signed; therefore, they range from a certain negative number to a positive number. For example, the type byte contained in eight bits ranges from -128 to + 127. In fact, with 28 we can represent 256 different possible combinations.
FLOATING POINT TYPES
Let us now look at types having a decimal part, float and double. Double is the type that is most commonly used given its high accuracy.
CHAR AND BOOLEAN TYPES
The type char is used to represent alphanumeric characters according to the standard Unicode. The type boolean admits only two possible values, true or false.
NUMERICAL LITERALS
A literal is the explicit form with which we can represent primitive types. Let us observe this issue:
250
Obviously we have no difficulty in recognizing that it is an integer, said in the form of a programming language this representation is called literal which besides being directly understandable to us humans, it is also understandable to a compiler. We can represent numbers according to certain bases, that of decimal, hexadecimal, octal and binary.
I remind you that the hexadecimal base includes the numbers 0 through 9 and the letters A through F. Must begin with the characters 0X to let the compiler know that the literal is expressed in hexadecimal form. What you are seeing is the representation of the number 250.
Octal numbers use eight symbols from 0 to 7; it must be preceded by a 0 to let the compiler know that the literal is expressed in base eight. Finally, we can use binary notation, The number must be preceded by the prefix 0b so that the compiler treats it as a binary number. Regardless of the literal format Java and thus the JVM treat numbers exclusively in the binary form. Sometimes large numbers to be better understood by human beings can be broken down in the following way:
250000000 -> 250_000_000
The underscore is simply ignored by the compiler.
LITERAL NUMERIC FLOATING POINT
A floating point number is a number that possesses an integer part and a decimal part.
250.13
The dot is used to separate the integer part from the decimal part; there is also the possibility of representing a literal floating point with so-called exponential notation.
In the example you are seeing the exponent is a power of ten; therefore, wanting to get the floating point number we have to multiply the number by 100 getting 250.13. The exponent can also be negative, so in this case the number is divided by the power of ten.
6.7e-2 -> 0.067
Another important thing to know is that Java by default considers a floating point number to be a double. We can specify in plain text that we intend to use a double by adding an uppercase or lowercase letter d to the end of the number.
250.13d
However, if we want to force the compiler to use a float we must specify the letter f.
250.13f
I LITERALS FOR THE CHARACTERS
Let us first define what is meant by a character in Java.
By alphabet we must think of the characters provided by the Unicode standard, our own but not limited to. Characters in Java occupy 16 bits and are unsigned numbers216 = 65536 possible combinations. They rely on a standard conversion table called Unicode. Characters are enclosed within a pair of single superscripts: ‘A’. Particular escape sequences beginning with a backslash can be specified:
THE LITERAL BOOLEAN
The literal boolean admits only two possible values, true and false. It is a type we will often use especially in control structures and loops.
SUMMARY TABLE
LITERALS FOR STRINGS
Strings are sequences of characters that fit within a pair of double quotes, for example: “This is a string.” Strings are actually objects, in fact they are reference types as we will see later.
package it.corso.java.datatype; public class DataType { public static void TypeInference(){ var myVar = 250; System.out.println("Il tipo di myVar è " + ((Object) myVar).getClass().getSimpleName()); } public static void ScientificNotation(){ float f1 = 35e3f; double d1 = 12E4d; System.out.println("Value of 35e3f " + f1); System.out.println("Value of 12E4d " + d1); } public static void DisplayChar(){ char myVar1 = 65, myVar2 = 66, myVar3 = 67; System.out.println("Codice ASCII 65 " + myVar1); System.out.println("Codice ASCII 66 " + myVar2); System.out.println("Codice ASCII 67 " + myVar3); } public static void DisplayString(){ String txt = "Hello World"; System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD" System.out.println(txt.toLowerCase()); // Outputs "hello world" System.out.println(txt.indexOf( "World" )); // Outputs 6 } }
VARIABLES
A variable is a name that we are going to assign to an area of memory within which we are going to store a value. Subsequently over time we can change this value. In addition to naming, the declaration of variables in Java involves assigning a particular Data Type, so that the compiler can verify that the values we enter in memory conform to the Data Type.
The value 250 can be changed while the variable name and its Data Type are immutable. Before using a variable in Java, it must first be declared with the following syntax:
data_type identifier;
Example:
int myVar;
myVar is the identifier that must follow certain definition rules that we now see.
Keywords are the reserved words of the Java language. After declaration a variable must be initialized, that is, you must fill that area of memory with the following syntax:
data_type identifier = value;
The equal symbol represents the assignment operator, while the value can be a literal type or it can also be the result of an expression. If desired, multiple variables can be declared and initialized with a single instruction.
If we look closely at an initialization, which is then an assignment made at declaration time, one might think that it is superfluous to indicate the Data Type since the compiler from the value ten might infer the type of the variable. Type inference was introduced in Java 10. Type inference cannot be used all the time but only with local variables.
INSTANCE VARIABLES
Instance variables are those variables that are defined within a class, but outside the methods of that class.
public class Numbers {
public int numberX;
public int numberY;
}
the variables “numberX” and “numberY” are thus instance variables. Instance variables will be deallocated from memory as soon as the object, an instance of the class, does not end its existence for example as soon as the application flow is terminated.
LOCAL VARIABLES
Local variables are all those variables that are declared and used within the methods of a class.
public int subtraction (int x, int y) {
int subtraction;
subtraction=x-y;
return subtraction;
}
the variable “subtraction” will therefore be a local variable. It is important to specify that the visibility of local variables is relative to the method in which it is declared. For example, if I wrote another method within the class and referenced the variable “subtraction” I would get an error message from the compiler requesting that I declare the variable because, for that method, it does not in fact exist. A local variable is deallocated as soon as the method returns and then returns to the main main method of the class.
THE CONSTANTS
We can consider constants always having a name as the variables pointing to a particular area of memory, only in this case the memory is read-only, the constant once assigned can no longer be changed.
final data_type identifier = value;
to create a constant value the keyword final is prefixed.
final double PIGRECO = 3.14169;
Having the identifier all uppercase is not mandatory, it is a convention derived from the C language that also serves at a glance to avoid confusing variables and constants. We can like variables defer declaration from assignment, this is a permissible thing.
EXECUTION OF THE EXAMPLE CODE
- Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.
java -jar –enable-preview CourseJava.jar
- Or run the main found in the file CorsoJava.java.
package it.corso.java.variabili; public class TestVariabili { protected String nome = "Marco"; /* Variabile di istanza. Vediamo con un esempio * perchè viene chiamata variabile di istanza, * guardando il metodo VariabileIstanza(). */ /* Variabile di classe. Tale variabile non appartiene ad una * specifica istanza, ma appartiene alla classe stessa. Questo * perchè abbiamo usato il modificatore static. Si possono avere * sia variabili che metodi statici (appartenenti alla classe * e non alle istanze). */ public static int myNumber = 100; public void MyMethod() { int a = 100;/*Variabile locale viene creata quando viene invocato il metodo, e distrutta quando la variabile esce dal suo ambito di visibilità, ossia quando il metodo termina. */ System.out.println(a); System.out.println("myNumber vale: " + TestVariabili.myNumber); } public void VariabileIstanza(){ /*Creiamo un oggetto di tipo TestVariabili o * più precisamente ne creiamo due istanze. La OOP sarà * spiegata approfonditamente più avanti nel corso, per * ora ti basta sapere che una classe è un pò come un prototipo * da cui vengono creati oggetti, detti appunto istanze della * classe. L'oggetto viene creato attraverso l'operatore new * che alloca la memoria necessaria per contenere la struttura * dati della classe. * */ TestVariabili t1 = new TestVariabili(); t1.nome = "Anna";//Variabile nome di istanza t1 TestVariabili t2 = new TestVariabili(); t2.nome = "Luca";//Variabile nome di istanza t2 System.out.println("Nome istanza t1:" + t1.nome); System.out.println("Nome istanza t2:" + t2.nome); /*OGNI ISTANZA MANTIENE LA PROPRIA COPIA DI VARIABILI */ } public void TestParametri(String nome, String cognome, int anni){ System.out.println("Persona: " + nome + " " + cognome + " anni " + anni ); } }
package it.corso.java; import it.corso.java.variabili.*; import it.corso.java.datatype.*; public class CorsoJava { public static void main(String[] args) { CorsoJava.Variabili(); CorsoJava.DataType(); } public static void Variabili(){ TestVariabili.myNumber = 10; TestVariabili test = new TestVariabili(); test.MyMethod(); test.VariabileIstanza(); test.TestParametri("Marco", "Albasini", 54); } public static void DataType(){ DataType.DisplayChar(); DataType.TypeInference(); DataType.ScientificNotation(); DataType.DisplayString(); } }
Leave A Comment