Variables and types

Last Updated on

Time needed: 20 minutes

In the previous tutorial we've already used a variable. It was the args visible in a construction below.

public static void main(String[] args)

A word that precedes the variable name is called a type. In that case, String[] was a type, and args was a variable name. In Java, there are primitive types and object types. An object is a very important concept in Java, an object oriented language after all, but we'll skip them for now and focus on primitive types, which are also widely used but much easier to understand. String is an example of an object which represents a string of characters.

Lowercase types are all primitive types, they're the basic building block of any Java application. There are 8 of them:

TypeSize (bytes)Minimum valueMaximum value
byte1-128127
short2-32,76832,767
int4 -2,147,483,648 2,147,483,647
long8-9,223,372,036,854,775,8089,223,372,036,854,775,807
float4 1.4 E-45 3.402,823,5 E+38
double8 4.9 E-324 1.797,693,134,862,315,7 E+308
char20 65535
booleanundefined----

In next tutorials I'll go into the details of each these data types. Some of them represent whole numbers (byte, short, int, long) some of them can have a decimal point (float, double), char represents alphanumeric characters, while boolean can be either true or false. Let's modify the HelloWorld example and write some practical examples.

public class HelloWorld {
    public static void main(String[] args) {
        int value = 10;
        System.out.println(value);
        value = 20;
        System.out.println(value);
    }
}

In line 3 we declare a new variable, named val, and we assign a number 10 to it. In line 5 the val is given a new value, 20. It would be illegal to declare a variable with the same name inside same scope, so we have to reuse the old one. Or we can declare another variable:

public class HelloWorld {
    public static void main(String[] args) {
        int value = 10;
        System.out.println(value);
        int anotherValue = 20;
        System.out.println(anotherValue);
    }
}

Variable names

Variable names must follow some rules:

  • A variable name has to begin with a letter, a dollar sign "$" or an underscore sign "_".
  • Variable names can contain any combination of characters, numbers, dollar signs and underscores.
  • It cannot be a keyword or reserved word.

These rules are compulsory, that is, your program will not compile if you do not follow them. That is, you can't name your variable "123", but you can name it "_1$2$3$". I've chosen that name on purpose, because people rarely use such names. But just because it compiles it doesn't mean that it's a good.

Variable naming conventions in Java

Variables names usually follow some conventions accepted by the majority of Java programmers. I have loosely ordered them by my subjective order of importance.

  • Variable names should be self-explanatory and clear. What's more descriptive: "v1", "v2", "a", or "weight", "height", and "age"?
  • Variable names should match their type. Imagine that someone wants to keep an information whether a given person is an adult, so he creates an "age" variable of boolean type, that is either true or false. That's would be rather poor choice, because unless you have the secret knowledge about the meaning of this variable, other people will be clueless what "age = true" means. This will either lead to bugs, or wasted time on code analysis. A good choice would be, for example, "isAdult".
  • Variable names should not start with a dollar or an underscore. There's hardly a reason to name your variable "_name", only because "name" was already in use.
  • Do not use dollar sign at all. It's permitted, but it's rarely useful. Such code is usually produced by software that automatically generates code, or code obfuscators, that shorten your variable names and change them to meaningless ones, so that it's harder to analyse it by reverse engineering.
  • Start your variables from lowercase letters, and use so called camel-case notation to join next words. Examples would be "expectedIncome", "informationRatio", or "messagesPerSecond". The only exceptions are constants, that is, values that are used throughout the application that never change. They should follow a different schema: all letters are uppercase, and words are separated by underscores. Examples: "DEFAULT_FILE_LOCATION", "DELIMITER".
  • Avoid creating multiple variables that only differ by a number. Let's say that you want to represent ten phones inside your application, so you name your variables "phone1", "phone2", "phone3"... That's a sign of a poor design and a possible source of bugs, because a single typo can change how your program works, and what's worse - it might not be so easy to find it.
  • Use English names. Because the overwhelming majority of libraries and tools are written in English, it would be a bad idea to write code in your native language. Almost every project relies on some kind of external dependencies, or is meant to be a library itself. Standard Java classes are all English, too. If you break that convention, your program will turn into a multi-language mess due to external dependencies, people from other countries won't understand the meaning of your variables, and other projects won't adapt your library.
  • Try not to include the type of your data in the variable name. Let's say that you want to represent a group of animals inside your project. You've decided to keep them in an array, so they look like that: "Animals[]" and your variable is called "animalArray". If you change that to a List, then you should rename it to "animalList". If you want to make it even more generic, and use a Collection, then you should rename it again to an "animalCollection". IDEs can easily show you the type of a variable, whenever you need it, so it's unnecessary. It's better to name your variables independently of what they represent. In this case, "animals" would be perfect.

Java 10 var keyword

The final part of the tutorial explains a new feature added in Java 10. If you're using an older JDK to compile your programs, you will not be able to use it.

Well, let's take a look at the following application, which declares few variables and prints them.

public class HelloWorld {
    public static void main(String[] args) {
        String shapeName = "rectangle";
        int x = 10;
        int y = 20;
        System.out.println("A " + shapeName + " has an area of: " + x * y);
        char favouriteLetter = 'k';
        System.out.println("My favorite letter is: " + favouriteLetter);

        long time = System.currentTimeMillis();
        System.out.println("Current time is: " + time);
    }
}

In each variable assignment we tell the compiler whether the value is a long, int, char or String. But in many cases it's unnecessary, the assignment from the third line should be obvious, because this syntax is used only by String literals (we'll mention them more extensively in next tutorials).

Such process is called type inference. It means that the compiler has enough information to figure out what the type is, and so we don't need to provide it.

Java 10 added a "var" keyword that does that. It can be understood to be a placeholder for a type that can be inferred from context. The program can be rewritten in the following way and it will work as before.

public class HelloWorld {
    public static void main(String[] args) {
        var shapeName = "rectangle";
        var x = 10;
        var y = 20;
        System.out.println("A " + shapeName + " has an area of: " + x * y);

        var favouriteLetter = 'k';
        System.out.println("My favorite letter is: " + favouriteLetter);

        var time = System.currentTimeMillis();
        System.out.println("Current time is: " + time);
    }
}

Keep in mind that it doesn't mean the type can change. It cannot.

var time = System.currentTimeMillis();
time = "time";

This will not compile because the assignment in the second line (String) does not match the type that was inferred in the first line (long).

Var is not a keyword

JEP 286 (Java Enchantment Proposal 286) states that var is not a keyword, but a reserved type name. In practice it means that the code that uses var as a variable name will not be affected, but it cannot be used as a type name, because it would be ambiguous to the compiler.

Thus, the following code snippet is perfectly valid and will print true.

   int var = 123;
   var number = 123;
   System.out.println(var == number);

Leave a Reply