Java
Article

Understanding Java Variables and Data Types

By Lincoln Daniel

At SitePoint we’re always looking to expand the range of topics we cover. Lately, we’ve set our sights on exploring the world of Java. If you’re a strong Java developer who wants to contribute to our coverage, get in touch with a few ideas for articles you’d like to write.

Java variables enable programmers to store single data points, bits of information, for later use. For efficiency in later use, Java variables have types. Those types are referred to as data types because they allow us to store different types of data respectively for convenience and predictability. It’s necessary for any Java programmer to understand the basics of variables and data types in Java before moving on to more advanced topics.

To illustrate how Java variables work, let’s imagine a photo sharing application. The app would store a whole bunch of information about the state of our application and the photos its users share: the number of users, the number of photos shared, and the total number of comments shared. That data has to be stored in order for us to manipulate and display them to our users when necessary. Enter Java variables.

Java Variables

Variables can hold data and that data can be changed over the lifetime of our program. A variable must have a type, a name, and be provided some sort of data to hold. The most widely used type of data in Java is the character string, represented by Java’s String class. A string, such as “SitePoint” is simply an instance of the String class.

Naming Variables

There are a few rules you must follow and a few you should. Java’s variable names are case senstive and can be an unlimited number of letters and numbers. However, variable names must start with a letter, underscore character _ , or a dollar sign $.

When creating variables in Java, it is best to follow the convention of using numbers and full words that are descriptive of the purpose of the variable while avoiding use of the underscore character and dollar sign. Finally, variables should be in lower camel case, a popular programming convention that dictates that the first letter of the first word should be in lower case and the following words should be capitalized.

beans

Using Variables

Let’s create the skeleton of our application’s main class to see how we can store each of the aforementioned data points about our application in String variables:

public class SitePointGram {
    public static void main(String[] args) {
        String nameOfApp = "SitePointGram";
        String numberOfUsers = "";
        String numberOfPhotos;
        String numberOfComments = null;
        //...
    }
}

So what’s going on there? Let’s skip to the third line of that block of Java code. On each line, we create a new variable of type String to store a single point of information about our application. Observe that to create a variable in Java, we start by stating the type of the data to be stored in the variable, followed by the name of the variable in lower camel case, then the assignment operator =, and finally the data to be stored in the variable.

In the first line of our main method, we store the name of our application in the nameOfApp String variable and the data stored in it is “SitePointGram”. The next line has a String variable that will store the number of users on our application. Notice that it stores an empty string "". Hold that thought as we move to the next two lines.

Every variable in Java has a default value; the default value for String variables is null, “nothing”. If we don’t know the value of a variable at the time of declaration, we can omit explicitly initializing it with a value and allow Java to implicitly provide it an appropriate default value. That is exactly what we do with the numberOfPhotos variable. Similarly, on the fourth line, we initialize the numberOfComments String variable to null explicitly, although we do not have to. It’s important to understand that an empty string is an actual character string, albeit an empty one, while null means the variable does not yet have valid data. Let’s continue.

SitePointGram is becoming popular and people are flocking to it. Let’s represent the growth of our application in Java:

public static void main(String[] args) {
    //...
    numberOfUsers = "500";
    numberOfPhotos = "1600";
    numberOfComments = "2430";
    //..
}

After initializing our String variables, it is now apparent that our application has 500 users, 1600 shared photos, and a whopping 2430 total comments across those photos. We’re doing well, so it’s time we learn how to use data types in Java.

Java Data Types

We currently have all of our data points stored in String variables even though some of them are numbers. Strings are good for representing character strings such as text, but when we want to represent numbers and other types of data (and perform operations on that data), we can use the data types provided by Java or create our own.

Let’s see how we can more appropriately store our numerical data points in variables so we can use them as we would expect:

public static void main(String[] args) {
    String appName = "SitePointGram";
    boolean appIsAlive = true;

    int numUsers = 500;
    int numPhotos = 1600;
    int numComments = 2430;
    //...
}

Moving away from our original main method, we have a new block of code with new variables of appropriate data types. In the first line of our main method’s body, the variable holding our application’s name is now more precise: instead of nameOfApp, we have appName. On the next line, we have a boolean variable which stores the status of our application. A boolean can only be true or false and therefore is best when you want to store a data point that represents validity; in our case, it is true that our app is alive until we need to shut it down for maintenance. The next three variables are of type int. The int data type represents integer values in Java. Following the same pattern as appName, instead of naming our number variables along the lines of numberOfX, we should do numX to be precise while maintaining readability.

The data types int, boolean, and double are three of the eight primitive data types in Java. Primitive data types are special values, not objects constructed from a class, provided by Java. Remember that strings are instances of the String class and so they are objects, not primitives. The default value for numerical data types is 0 and false for the boolean.

Unlike in our previous main method, our new set of variables store numbers appropriately, so we are able to manipulate them as we would expect. With our numerical data points stored in variables of types that represent numbers, we can execute mathematical operations on them:

//a new user joined, increase the number of users by 1
numUsers += 1;
//multiply the number of photos by 2
numPhotos = numPhotos * 2;
//get the average number of photos by doing division
double avgPhotosPerUser = 1.0 * numPhotos / numUsers;

The last variable in our main method holds a floating point value of the average number of photos per user and this is represented by the double data type. We obtained this by dividing the number of photos by the number of users. Notice we multiplied the first number by 1.0 so that the result isn’t rounded to the nearest whole number. We can store a floating point number as either a float or a double; the only difference here is that a double (64 bit) can hold a much larger range of numbers than a float (32 bit) and is used more often for that reason.

The last thing to do is see how we can represent our data in our own data types.

String user1 = "id: 1, username: LincolnWDaniel, isOnline: true";

While it would be easy to make a bunch of strings that hold information about users like we have in user1, it would be better to create a class to construct user objects from:

Custom Java Data Types (Classes)

public class User {
    public static int numUsers = 0;

    private int id;
    private String username;
    private boolean isOnline;
    /*other information about this user,
    perhaps a list of associated photos*/

    public User(String username) {
        id = numUsers++;
        this.username = username;
        this.isOnline = true;
        System.out.println(username + " signed up!");
    }

    public void logOn() { 
        isOnline = true; 
        printOnlineStatus();
    }

    public void logOff() { 
        isOnline = false; 
        printOnlineStatus();
    }

    private void printOnlineStatus() {
        System.out.println(username + " is online: " + isOnline);
    }
    //...
}

There, we have a class called User. This class simply defines properties and behaviors instances created from it can exhibit. The properties of this class are simply variables of varying data types that will hold information about a user in our application. An instance of the User class can have information about itself from its identification number to its username, and its online status is held in a boolean variable that can be updated when the user logs on or off. When a user is created, or logs on or off, we print that information to the console.

Every time a new user is created in our application, the numUsers variable’s value is increased by one so that our application knows how many users there are at all times. You could add more information to this class by adding more instance variables. Now, let’s create an instance of our new data type, User, in our application’s main method:

public static void main(String[] args) {
    String appName = "SitePointGram";
    boolean appIsAlive = true;

    /*declare a new variable of type User 
    and store a new User instance with the name of "Lincoln" in it*/
    User lincoln = new User("Lincoln");

    //log lincoln off
    lincoln.logOff();

    //print out the number of users in our app
    System.out.println("Number of users: " + User.numUsers);
    //...
}

In that block of code, we changed up our main method again. The first two lines remained unchanged, but we now have three new lines. The third line in the method creates a new User instance, or object, and stores it in a variable called “lincoln”, the next line logs lincoln off our application, and the next line prints out the number of User instances in our application by accessing the public static numUsers variable from the User class. It’s important to note that static variables of a class belong to the class and not instances of that class, so we did not need an instance of User to access numUsers.

Conclusion

That’s it! You now know all you need to know about Java variables and data types to get started building your own data types, or classes. Take a look at the source code for this tutorial on our GitHub repository and see how you can build upon it.

References:
Oracle Documentation on Java Strings
Oracle Documentation on Java’s Primitive Data Types

More:

No Reader comments

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in Java, once a week, for free.