What are variables in Java

Variables in Java

Javaschubla.de - Java as the first programming language

This lesson is about (primitive, local) variables.

Define variables

Perhaps you have already seen such a variable definition in another programming language (e.g. JavaScript):

var i;

In Java you don't need a keyword like var. Instead, you specify the type of the variable. For the beginning we use int. Int stands for integer, in Java these are positive and negative whole numbers that fit into 4 bytes, i.e. from -231 up to +231-1. You don't have to assign a value to the variable right away, but you have to do that before using it. (Exceptions where variables are automatically initialized are explained later.)

Example:

int i;

declares a variable named i of type int.

Allowed variable names:

  • begin with a letter (or a _, but this is not desirable)
  • otherwise only contain letters and digits and _ and $ ($ is also not desired)
  • Umlauts and ß are allowed (but can lead to problems in exchange with other operating systems)
  • Special characters like? ! + - etc. are not allowed because they are operators

It is a strict convention to write variable names in lower case, to start inner words in upper case and not to use _, e.g. DasIsEinVariablenName. This notation is called a camel case.

Back to the example

int i;

4 bytes of space are already reserved in the main memory for this variable. But it has not yet been initialized, i.e. it has not yet been assigned a value. So you can't use it yet. E.g.

System.out.println (i);

would cause an error message "i might not have been initialized" when compiling.

In Java (and related languages ​​such as C, C ++, C #, and JavaScript) variables are assigned a value using the equal sign.

i = 3;

That is not to be read as "i is equal to 3". There is no comparison! Possible readings are "set i to 3", "write 3 in i", "i results in 3", "i becomes 3".

A compilable example program:

class variables {public static void main (String [] args) {int i; i = 3; System.out.println (i); }}

As you can easily imagine, there are 3 in the DOS window or on the console.

Of course you can also change the value of the variable:

class variables {public static void main (String [] args) {int i; i = 3; System.out.println (i); i = 5; System.out.println (i); }}

Outputs 3 and one line below 5.

The definition of the variables and the initialization (first assignment of a value) can be done in one line:

int i = 3;

Sample program:

class variables {public static void main (String [] args) {int i = 3; System.out.println (i); i = 5; System.out.println (i); }}

But be careful not to write the second time. That would define a second variable called i. This is not possible. The compiler would output an error message stating that the variable i already exists.

class variables {public static void main (String [] args) {int i = 3; System.out.println (i); int i = 5; // Error, duplicate variable name System.out.println (i); }}

By the way, a begins with // commentthat goes to the end of the line. With / * ... * / you enclose a comment that can span several lines.

Of course you can do the usual calculations.

class variables {public static void main (String [] args) {int a = 17; int b = 3; int sum = a + b; System.out.print ("a + b ="); System.out.println (sum); int difference = a - b; System.out.print ("a-b ="); System.out.println (difference); int product = a * b; System.out.print ("a * b ="); System.out.println (product); int quotient = a / b; int rest = 17% 3; System.out.print ("a: b ="); System.out.print (quotient); System.out.print ("Rest"); System.out.println (rest); }}

Outputs:

a + b = 20 a-b = 14 a * b = 51 a: b = 5 remainder 2

This example shows:

  • Variables can be defined anywhere, not just at the beginning of the method (function).
  • / is an integer division when dividing two ints (whole numbers). Therefore 17/3 is 5.
  • % (Percentage sign, press Shift + 5) determines the remainder in the case of whole-number division. Therefore 17% equals 3 2.
    (The sign of the remainder depends on the sign of the dividend (= what is in front of the%, i.e. the number that is divided). 17% 3 and 17% -3 results in 2, -17% 3 and -17% -3 results in -2.)

Remarks:

You don't have to put spaces before and after the variable name. Since =, +, - etc. are not allowed symbols in variable names, the compiler knows that the variable name has ended there. E.g. is exactly the same as

As we saw in the concatenation chapter, there is no need to divide the output into two statements, e.g.

System.out.print ("a + b ="); System.out.println (sum);

but you can connect them with +:

System.out.println ("a + b =" + sum);

Here, too, as already mentioned, the spaces do not matter, they would be the same

All line breaks can also be omitted. If you want, you can write all the instructions one after the other on one line. Because of the semicolons, the compiler knows where the next one begins. But that is quite confusing, so you only write two short instructions, if at all, in one line.

Other data types

Let's get to a few other data types besides int. The primitive data types in Java are:

whole numbers
byte1 bytewhole numbers-27 up to 27-1 (-128 ... 127)
short 2 bytes whole numbers-215 up to 215-1 (-32768 .. 32767)
int 4 bytes whole numbers-231 up to 231-1 (approx. 2 billion)
long 8 bytes whole numbers-263 up to 263-1
Floating point numbers (decimal numbers, fractional numbers)
float 4 bytes Floating point numbers with single precision
double 8 bytes Floating point numbers with double precision
Truth values
boolean 1 byte Truth valuestrue or false
character
char 2 bytes characterUnicode

char stands for character, which in English means "character" (in the sense of letter, number, special character) (but also character, (novel / film / comic) figure).

It is usually not worth using byte, short or float to save memory space. You actually always use int, long and double because that's faster. A 32-bit computer can access 32 bits (4 bytes) the fastest; only using parts of it increases the access time.

Examples:

byte b = 5; short s = 400; int i = -17; long l = 100000000000L; float f = 0.123f; double d = 0.123; boolean w = true; boolean nw = false; char c = 'x';

It should be noted

  • that the point is used as a decimal point instead of a comma.
  • that individual characters (characters, chars) are enclosed in single quotation marks (Shift + # on German keyboards)
  • that the boolean literals true and false are written in lower case
  • that you have to write an L after long numbers and an f after float numbers (small or large does not matter, but it is difficult to distinguish a small L from a 1).

Casting (typecast)

You can make an assignment to a "higher" / "further" type without any problems:

short s = 300; int i = s;

But it doesn't work the other way around, even if the number would theoretically fit in:

int i = 500; short s = i; // causes an error

But you can force that by explicitly converting. This conversion is called casting.

int i = 500; short s = (short) i;

So you convert something to a different type by putting the type in front of it in parentheses.

Another example:

class IntToByte {public static void main (String [] args) {int i = 500; byte b = (byte) i; System.out.println (b); }}

That works too, but the result is not correct. byte only goes up to 127, so the 500 overflows, there is a loss of precision. 500-127 = 373 are still too many, they now start counting again from the bottom, i.e. from -128. That is still too much, 255 more counting steps later is the end, there are still 373-255 = 116 left. They start counting again from the bottom from -128, -128 + 116 = -12, so -12 is saved in b. Try it! -12 is output.

It is not possible, booleans Convert (truth values) to other types or other types to booleans.

Conversion of characters into numbers and vice versa

You can also cast between char and int.

char c = (char) 97; System.out.println (c);

outputs an a, because 97 is the ASCII and Unicode number of the lower case a. The conversion from char to int works in the same way:

int i = (int) 'A'; System.out.println (i);

outputs 97.

division

We already had above that 17/3 equals 5. It is not even rounded, it is simply cut off.

Let's take 7/2 as an example, because period 3 would be a bit time-consuming to write. 7/2 is 3. How can we force it to come out 3.5? Maybe it helps if we store the result in a double variable:

double d = 7/2; System.out.println (d);

No, unfortunately does not help. 7/2 is calculated, the result is 3, and only then is it stored in the double variable d. So 3.0 is output instead of 3.5.

So if dividing two int numbers always results in an int number, we simply have to convert at least one of the two numbers to double:

double d = 7.0 / 2; or double d = 7 / 2.0; or double d = 7.0 / 2.0;

everything leads to the desired success :-).

But what to do when the numbers are stored in variables?

int number1 = 7; int number2 = 2; double d = number1 / number2;

We're just using casting again!

double d = (double) number1 / number2; or double d = number1 / (double) number2; or double d = (double) number1 / (double) number2;

This gives us a 3.5 here too. :-)

An alternative is to multiply by 1.0. This automatically makes the result double because there is a double number in the multiplication. Even if the result only has 0 as a decimal place.

double d = 1.0 * number1 / number2; or double d = number1 * 1.0 / number2;

Wouldn't help

double d = number1 / number 2 * 1.0;

because then 7/2 would be calculated, it comes out 3, then 3 * 1.0 is calculated and it comes out 3.0. Would be wrong

double d = number1 / 1.0 * number2;

because then number1 (i.e. 7) would be divided by 1.0, resulting in 7.0, and that would then be multiplied by number2 instead of dividing by it, and you would get 14. This could be prevented by brackets like in mathematics:

double d = number1 / (1.0 * number2);

Abbreviations for operators

There are abbreviated notations for certain operations. E.g. one often wants to increase, decrease, multiply or divide a number by another. So e.g. instead of "" "". Remember that = is not a comparison. Of course, a is not equal to a + b (if b is not exactly 0), but b is added to the old value of a and the result is stored in a. E.g .:

int a = 5; int b = 7; a = a + b;

Now a is 12. The short notation is used for this +=.

a + = b;

means exactly the same as a = a + b;

There is also - =, * =, / = and% =.

Increment and decrement

Increasing or decreasing by 1 is particularly common; there are extra notations for this.

Instead of a = a + 1; you can't just a + = 1; but also write a ++ or ++ a. That means post or pre-increment (increment = increase by 1).

Instead of a = a - 1; you can't just a- = 1; but also write a-- or --a. That means post- or pre-decrement (decrement = decrease by 1).

If a ++ or ++ a stands alone in a statement, it makes no difference whether the ++ is in front or in the back:

int a = 3; a ++; // now a is 4 ++ a; // now a is 5

(As a reminder: a comment begins with // up to the end of the line.)

But if you use the result right away, it makes a difference.

int a = 3; int b = 0; b = a ++; // a is 4, but b is 3. The increment was executed afterwards. b = ++ a; // now a is 5 and b is also 5. The increment was executed before.

The same applies to --.

Constants

A constant is defined by adding final in front of the type. Constant names are written in ALL_CAPS, i.e. completely capitalized with underscores for subdivision.

class Konstantin {public static void main (String [] args) {final int MAXIMUM_SCHUELER_PRO_KLASSE = 30; System.out.println ("In each class there may be a maximum of" + MAXIMUM_SCHUELER_PRO_KLASSE + "students."); // MAXIMUM_SCHUELER_PRO_KLASSE = 33; would cause an error message}}

You should always replace all constants, whether for numbers or strings, with final variables. This is particularly important if they appear in several places in the source text, i.e. if, for example, it is checked more often in the program whether a maximum of 30 students have really been assigned to a class. Maybe the number increases to 31, then you would have to change it everywhere and maybe miss a point. With strings it is important to save them in final variables because most programs are translated into another language at some point. So you can find all texts to be translated quickly.

Multiple variables of the same type

Several variables of the same type can be declared at once:

int i, j, k; i = 14; j = -1; k = 5;

does the same as

You can even do the initializations at once:

int i = 14, j = -1, k = 5;

Exercise 1

Try the operators, especially division.

You would probably like to have the user enter two numbers and then print out the sum, difference, and so on. Unfortunately, reading in from the keyboard is a little more difficult than in other languages, so it comes later. As long as you set the numbers in the source code yourself and imagine that they will be entered by the user later.

exercise 2

Try out the different data types and the conversion between them. When is there an error message and what is it? When not?


The next lesson introduces comparisons and conditions.