java输出变量数据类型

tech2023-02-26  95

java输出变量数据类型

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.

在SitePoint,我们一直在寻求扩大我们涵盖的主题范围。 最近,我们将目光投向了探索Java的世界。 如果您是一名强大的Java开发人员,想为我们的报道做出贡献,请与您想写的文章的一些想法保持联系 。

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.

Java变量使程序员能够存储单个数据点和信息位,以备后用。 为了提高以后使用的效率,Java变量具有类型。 这些类型被称为数据类型,因为它们使我们分别为了方便和可预测性而存储不同类型的数据。 任何Java程序员都必须先了解Java中变量和数据类型的基础,然后再转向更高级的主题。

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变量如何工作,让我们想象一个照片共享应用程序。 该应用程序将存储有关我们的应用程序状态及其用户共享的照片的所有信息:用户数量,共享的照片数量以及共享的评论总数。 必须存储该数据,以便我们在必要时进行操作并将其显示给我们的用户。 输入Java变量。

Java变量 (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.

变量可以保存数据,并且可以在程序的生命周期内更改数据。 变量必须具有类型,名称,并提供某种数据来保存。 Java中使用最广泛的数据类型是字符串,由Java的String类表示。 诸如“ SitePoint”之类的String只是String类的一个实例。

命名变量 (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 $.

您必须遵循一些规则,而您应该遵循一些规则。 Java的变量名区分大小写,并且可以是字母和数字的任意数量。 但是,变量名必须以字母,下划线字符_或美元符号$开头。

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.

在Java中创建变量时,最好遵循使用描述变量目的的数字和完整单词的约定,同时避免使用下划线字符和美元符号。 最后,变量应使用小写驼峰,这是一种流行的编程约定,规定第一个单词的第一个字母应小写,随后的单词应大写。

使用变量 (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:

让我们创建应用程序主类的框架,以了解如何在String变量中存储有关应用程序的上述每个数据点:

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.

那到底是怎么回事? 让我们跳到该Java代码块的第三行。 在每一行上,我们创建一个String类型的新变量来存储有关我们应用程序的单点信息。 观察到要在Java中创建一个变量,首先要说明要存储在该变量中的数据的类型,然后是小写驼峰变量的名称,然后是赋值运算符= ,最后是要存储的数据在变量中。

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.

在main方法的第一行中,我们将应用程序的名称存储在nameOfApp String变量中,并且其中存储的数据为“ SitePointGram”。 下一行有一个String变量,它将存储我们应用程序上的用户数。 请注意,它存储了一个空字符串"" 。 当我们移至下两行时,请保持该思想。

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.

Java中的每个变量都有一个默认值。 String变量的默认值为null ,即“ nothing”。 如果在声明时不知道变量的值,则可以省略使用值显式初始化它,并允许Java隐式为其提供适当的默认值。 这正是我们使用numberOfPhotos变量进行的操作。 同样,在第四行中,尽管不必这样做,但我们将numberOfComments String变量显式初始化为null 。 重要的是要理解一个空字符串是一个实际的字符串,尽管它是一个空字符串,而null表示变量尚没有有效数据。 让我们继续。

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

SitePointGram变得越来越流行,人们蜂拥而至。 让我们代表我们的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.

初始化我们的String变量后,现在很明显,我们的应用程序有500个用户,1600张共享照片,以及这些照片上总共有2430条评论。 我们做得很好,所以现在该学习如何在Java中使用数据类型了。

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.

我们目前将所有数据点存储在String变量中,即使其中一些是数字。 字符串非常适合表示诸如文本之类的字符串,但是当我们想要表示数字和其他类型的数据(并对这些数据执行操作)时,我们可以使用Java提供的数据类型或创建自己的数据类型。

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.

远离原始的main方法,我们有了一个新的代码块,其中包含具有适当数据类型的新变量。 在main方法主体的第一行中,保存应用程序名称的变量现在更加精确:我们使用appName代替了nameOfApp 。 在下一行,我们有一个boolean变量,用于存储应用程序的状态。 boolean只能是true或false ,因此,当您要存储表示有效性的数据点时, boolean是最好的; 在我们的情况下,确实是我们的应用程序仍然存在,直到需要关闭它进行维护之前。 接下来的三个变量的类型为int 。 int数据类型表示Java中的整数值。 遵循与appName相同的模式,而不是像numberOfX命名我们的数字变量,我们应该在保持可读性的同时做numX以便精确。

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.

数据类型int , boolean和double是Java八种原始数据类型中的三种 。 原始数据类型是特殊值,而不是Java提供的从类构造的对象。 请记住,字符串是String类的实例,因此它们是对象,而不是基元。 数字数据类型的默认值为0 , boolean值的默认值为false 。

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:

与以前的main方法不同,我们的新变量集适当地存储了数字,因此我们能够按预期操作它们。 将我们的数值数据点存储在代表数字的类型的变量中,我们可以对它们执行数学运算:

//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.

我们main方法中的最后一个变量包含每个用户的平均照片数量的浮点值,这由double数据类型表示。 我们通过将照片数量除以用户数量来获得此结果。 注意,我们将第一个数字乘以1.0,这样结果就不会四舍五入到最接近的整数。 我们可以将浮点数存储为float或double ; 唯一的区别是, double精度数(64位)可以容纳比float (32位)大得多的数字范围,并且由于这个原因,它的使用频率更高。

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:

虽然很容易像使用user1那样使一堆字符串包含有关用户的信息,但最好创建一个类来从以下对象构造用户对象:

自定义Java数据类型(类) (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.

在那里,我们有一个名为User的类。 此类仅定义通过其创建的实例可以显示的属性和行为。 此类的属性只是不同数据类型的变量,这些变量将保存有关我们应用程序中用户的信息。 User类的实例可以具有有关其自身的信息(从其标识号到其用户名),并且其在线状态保存在boolean变量中,可以在用户登录或注销时进行更新。 创建用户或登录或注销用户后,我们会将这些信息打印到控制台。

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:

每次在我们的应用程序中创建一个新用户时, numUsers变量的值都会增加一,以便我们的应用程序始终知道有多少个用户。 您可以通过添加更多实例变量来向此类添加更多信息。 现在,让我们在应用程序的主要方法中创建新数据类型User的实例:

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.

在那段代码中,我们再次更改了main方法。 前两行保持不变,但是我们现在有了三行。 方法的第三行创建一个新的User实例或对象,并将其存储在名为“ lincoln”的变量中,下一行将lincoln从我们的应用程序中注销,而下一行则通过以下方式打印出我们应用程序中的User实例数从User类访问public static numUsers变量。 重要的是要注意,类的static变量属于该类,而不属于该类的实例,因此我们不需要User实例即可访问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.

而已! 现在,您已经了解了有关Java变量和数据类型的所有知识,从而可以开始构建自己的数据类型或类。 在我们的GitHub存储库上查看本教程的源代码,并了解如何在此基础上构建。

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

参考: 有关Java字符串的 Oracle文档有关Java的原始数据类型的Oracle文档

翻译自: https://www.sitepoint.com/understanding-java-variables-and-data-types/

java输出变量数据类型

最新回复(0)