Home >Technology peripherals >It Industry >Understanding Java Variables and Data Types

Understanding Java Variables and Data Types

Jennifer Aniston
Jennifer AnistonOriginal
2025-02-18 12:07:08658browse

Understanding Java Variables and Data Types

Core points

  • Java variables are used to store a single data point or piece of information for later use. They must have a type, name, and some kind of data to be saved. The most widely used data type in Java is a character string, which is represented by Java's String class.
  • Variables in Java can hold data that may change during the life of the program. Each Java variable has a default value; for String variables, it is null. If the value of a variable is not known at the time of declaration, Java can implicitly provide it with an appropriate default value.
  • Java provides different data types to represent different types of data. For example, the int data type represents an integer value, boolean can only be true or false, and double represents a floating point number. These are several of the eight basic data types provided by Java.
  • In Java, you can create custom data types or classes. A class defines the properties and behaviors that can be displayed from the instances it creates. An instance of a class may have information about itself, which is stored in variables of various data types. Static variables of a class belong to a class, not an instance of that class.

Java variables enable programmers to store individual data points and information fragments for later use. To improve efficiency, Java variables have types. These types are called data types because they allow us to store different types of data separately for convenience and predictability. Before learning more advanced topics, any Java programmer must understand the basics of Java variables and data types. To illustrate how Java variables work, let's imagine a photo sharing application. The app will store a lot of information about the application status and the photos shared by users: the number of users, the number of photos shared, and the total number of shared comments. In order to manipulate this data when needed and display it to the user, it must be stored. This is what Java variables do.

Java variables

Variables can save data, and these data can be changed over the life of the program. A variable must have a type, a name, and provide some kind of data to hold. The most widely used data type in Java is character strings, represented by Java's String class. Strings like "SitePoint" are just instances of the String class.

Variable Naming

There are some rules you must follow, and there are some rules you should follow. Java variable names are case sensitive and can be an infinite number of letters and numbers. However, variable names must start with letters, underscore characters_, or dollar sign $. When creating variables in Java, it is best to follow the convention of using numbers and full words that describe the purpose of variables while avoiding underscore characters and dollar signs. Finally, variables should use the small camel nomenclature, a popular programming convention that stipulates that the first letter of the first word should be lowercase and the subsequent words should be uppercase.

Understanding Java Variables and Data Types

Using variables

Let's create a framework for the main class of the application and see how we store each data point above about the application in a String variable:

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

So what happened there? Let's jump to the third line of that Java code. In each row, we create a new String type variable to store a single point of information about the application. Note that to create a variable in Java, we first declare the type of data to be stored in the variable, then the variable name named in the camel, 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 the application in the nameOfApp String variable, where the stored data is "SitePointGram". The next line has a String variable that will store the number of users on our application. Note that it stores an empty string "". Keep this in mind as we move on to the next two lines. Each Java variable has a default value; the default value of the String variable is null, "nothing". If we don't know the value of the variable when declared, we can omit explicitly initialize it with the value and allow Java to implicitly provide it with appropriate default values. This is exactly what we do with the numberOfPhotos variable. Again, in the fourth line, we explicitly initialize the numberOfComments String variable to null, although we don't have to. It is important to understand that an empty string is an actual character string, although it is an empty string, and null means that the variable does not have valid data yet. Let's continue. SitePointGram became popular and people flocked to it. Let's use Java to represent the growth of an application:

<code class="language-java">public static void main(String[] args) {
    //...
    numberOfUsers = "500";
    numberOfPhotos = "1600";
    numberOfComments = "2430";
    //..
}</code>

After initializing our String variable, it is now obvious that our application has 500 users, 1600 shared photos, and a total of 2430 comments for these photos. We did a great job, so now is the time to learn how to use data types in Java.

Java data type

We currently store all data points in String variables, even if some of them are numbers. Strings are suitable 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 data types. Let's see how we can store numerical data points in variables more appropriately so that we can use them as expected:

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

Far from our original main method, we have a new piece of code that contains new variables for the appropriate data type. In the first line of our main method body, the variable that holds our application name is now more precise: we use appName instead of nameOfApp. In the next line, we have a Boolean variable that stores the state of our application. boolean can only be true or false, so it fits best when you want to store data points representing validity; in our case our application is active until we need to close it for maintenance. The next three variables are type int. The int data type represents an integer value in Java. Following the same pattern as appName, we should use numX instead of numberOfX to name our numeric variables so that it is more precise while remaining readable. int, boolean and double are three of the eight basic data types in Java. Basic data types are special values ​​provided by Java, not objects constructed from classes. Remember that strings are instances of String classes, so they are objects, not primitives. The default value of numeric data type is 0, and the default value of boolean is false. Unlike our previous main method, our new set of variables stores the numbers appropriately, so we can manipulate them as expected. By storing numerical data points in variables of the type representing numbers, we can perform mathematical operations on them:

<code class="language-java">public static void main(String[] args) {
    //...
    numberOfUsers = "500";
    numberOfPhotos = "1600";
    numberOfComments = "2430";
    //..
}</code>

The last variable in our main method holds a floating point number of the average number of photos per user, which is represented by the double data type. We get this value by dividing the number of photos by the number of users. Note that we multiply the first number by 1.0 so that the result is not rounded to the nearest integer. We can store floating point numbers as float or double; the only difference here is that double (64-bit) can accommodate a larger range of numbers than float (32-bit) and is more commonly used for this reason. The last thing to do is see how we represent our data in our own data types.

<code class="language-java">public static void main(String[] args) {
    String appName = "SitePointGram";
    boolean appIsAlive = true;

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

While it is easy to make many strings that hold user information like in user1, it is best to create a class to construct user objects from it:

Custom Java data types (classes)

<code class="language-java">//一个新用户加入,将用户数量增加1
numUsers += 1;
//将照片数量乘以2
numPhotos = numPhotos * 2;
//通过除法得到每位用户的平均照片数量
double avgPhotosPerUser = 1.0 * numPhotos / numUsers;</code>

There, we have a class called User. This class simply defines the properties and behaviors that can be displayed from the instances it creates. The properties of this class are just variables of various data types that will hold information about the users 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 stored in a boolean variable that can be updated when the user logs in or logs out. When creating a user or logging in or logging out, we print that information to the console. Every time a new user is created in our application, the value of the numUsers variable is increased by 1 so that our application always knows how many users there are. You can add more information to this class by adding more instance variables. Now let's create an instance of the new data type User in the main method of the application:

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

In that code, we changed our main method again. The first two lines remain the same, 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 named "lincoln", the next line logs lincoln from our application, and the next line accesses the User class The public static numUsers variable is used to print out the number of User instances in our application. It should be noted that the static variables of the class belong to the class, not the instance of the class, so we do not need the instance of the User to access numUsers.

Conclusion

That's it! You have now learned all the knowledge about Java variables and data types you need to start building your own data type or class. Check out the source code for this tutorial in our GitHub repository to see how you can build on this.

References:

  • Oracle documentation on Java strings
  • Oracle documentation on basic Java data types

FAQs (FAQ)

What is the difference between local variables and instance variables in Java?

In Java, variables are divided into local variables, instance variables and class variables. Local variables are declared within methods, constructors, or blocks and are accessible only within the scope of their declaration. They have no default values ​​and must be initialized before use. On the other hand, instance variables are declared in the class, but outside the method. They are object-specific and get memory every time an object is created. Unlike local variables, instance variables have default values ​​based on their data type.

How does Java handle type conversion?

Java handles type conversions in two ways: implicit conversions and explicit conversions. Implicit conversion, also known as automatic type conversion, occurs when two types are compatible and the target type is larger than the source type. Explicit conversion, also known as casting, is a case where we manually convert one data type to another. This is necessary when the target type is smaller than the source type or the type is incompatible.

What is the default value of variables in Java?

In Java, instance variables and class variables are automatically initialized to default values ​​if not explicitly initialized. The default value depends on the data type. For example, byte, short, int, and long defaults to 0, float and double defaults to 0.0, char defaults to 'u0000', and boolean defaults to false. Non-base data types (such as arrays and classes) default to null.

What is the meaning of the 'final' keyword in variables in Java?

The 'final' keyword in Java is used to declare constant variables, which means that once assigned, its value cannot be changed. It can be applied to basic data types, objects, and methods. For example, 'final int x = 10;' means that the value of x will always be 10 and cannot be modified.

How does Java handle string variables?

In Java, strings are not basic data types, but special classes. Strings are immutable, meaning that once created, their values ​​cannot be changed. Instead, a new string object is created. Java provides a special string pool area in heap memory, which attempts to maintain unique string values ​​to optimize memory usage.

What is the difference between '==' and 'equals()' in Java?

In Java, '==' is a relational operator that compares the memory locations of two objects, while 'equals()' is a method that compares the contents of two objects. For basic data types, '==' check whether the values ​​are equal. But for objects it checks whether they refer to the exact same memory location, not their contents.

What is the type enhancement in Java?

Type promotion in Java is to automatically convert one basic data type to another to prevent data loss. When operand types are different, it usually occurs in expression or method calls. Smaller types are promoted to larger types. For example, if int and float are used in expressions, int is promoted to float.

What is the scope of variables in Java?

The scope of a variable in Java refers to the part of the code that can access the variable. Local variables can only be accessed within their declared methods or blocks. An instance variable can be accessed by all methods in the class unless the method is static. Class variables or static variables can be accessed by all methods in the class, and if they are public, they can even be accessed outside the class.

What is the difference between static variables and non-static variables in Java?

In Java, static variables, also called class variables, belong to classes, not to individual objects. They are only initialized once at the beginning of the execution and share the same value between all objects of the class. Non-static variables, also known as instance variables, belong to a single object, and each object has its own copy of the variable.

How does Java handle arrays?

In Java, arrays are objects that store multiple variables of the same type. They are dynamically allocated and can store primitives or objects. The length of the array is determined when creating the array and cannot be changed. The array has a 'length' attribute which returns the number of elements in the array. Elements in an array are accessed through their indexes, starting from 0.

The above is the detailed content of Understanding Java Variables and Data Types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn