现实世界中有许多价值观是永远不会改变的。正方形总是有四条边,小数点后三位的圆周率总是3.142,一天总是有24小时。这些值保持不变。在编写程序时,以同样的方式表示它们是有意义的,因为这些值一旦分配给变量就不会被修改。这些变量称为常量。
在声明变量时,我们展示了为int变量赋值很容易:
int numberOfHoursInADay = 24;我们知道这个值在现实世界中永远不会改变,所以我们确保它在程序中不会改变。这是通过添加关键字修饰符来完成的
final final int NUMBER_OF_HOURS_IN_A_DAY = 24;除了
finalkeyword you should have noticed that the case of the variable name has changed to be uppercase as per the standard Java naming conventionIf we now try and change the value of
NUMBER_OF_HOURS_IN_A_DAY final int NUMBER_OF_HOURS_IN_A_DAY = 24; NUMBER_OF_HOURS_IN_A_DAY = 36;we will get the following error from the compiler:
cannot assign a value to final variable NUMBER_OF_HOURS_IN_A_DAYThe same goes for any of the other primitive data type variables. To make them into constants just add the
finalIf it’s used by more than one method then declare it at the top of the class definition:
public class AllAboutHours{ private static final int NUMBER_OF_HOURS_IN_A_DAY = 24; public int calculateHoursInDays(int days) { return days * NUMBER_OF_HOURS_IN_A_DAY; } public int calculateHoursInWeeks(int weeks) { final int NUMBER_OF_DAYS_IN_A_WEEK = 7; return weeks * NUMBER_OF_DAYS_IN_A_WEEK * NUMBER_OF_HOURS_IN_A_DAY; } }Notice how I’ve also added the keyword modifiers
privateand staticto the variable declaration of NUMBER_OF_HOURS_IN_A_DAY. This means that the constant can only be used by its class (hence the privatescope) but you could just as easily make it a publicconstant if you want other classes to have access to it. The statickeyword is to allow the value of the constant to be shared amongst all instances of an object. As it's the same value for every object created, it only needs to have one instanceIt’s very important to realize that when it comes to objects, Java does not support constants as you might expect. If you assign a variable to an object using the
final...Buffer和stringbuilder是Java中的类。字符串在Java编程中被广泛使用。一旦创建了字符串对象,就不可能更改它们。每次字符串发生更改时,它都会创建一个新字符串。即使是连接到现有字符串,它也会创建一个新字符串。这会导致内...
...间的关键区别在于static用于定义可以独立于类的任何对象使用的类成员,而final用于声明常量变量或无法重写的方法或无法继承的类。 目录 1. 概述和主要区别 2. Java中什么是静态的 3. Java中的final是什么 4. Java中static和final的相似...
...机器可理解的格式。机器可理解的代码被称为机器代码。使用C语言将整个机器代码转换为C语言。有些编程语言将源代码转换为中间代码,然后将中间代码转换为机器代码。在这个过程中,中间代码被称为字节码。本文讨论源代...
... 在本文中,您将了解什么是异常,它们为什么重要,如何使用它们,以及要避免的常见错误。大多数现代语言都有某种类型的异常处理,因此如果您从Java开始,您可以随身携带这些技巧...
...许您将JavaScript或Python的概念引入Haskell。如果你想更多地了解这门语言,学习Haskell是一个受欢迎的起点。 ...
...趣的例子。 什么是幻数(magic numbers)? 大多数编程语言使用32位整数类型来表示后台的某些类型的数据—在内部,数字存储在RAM中或由CPU用作32个1和0,但在源代码中,它将以常规十进制格式或十六进制格式写入,后者使用数字0...
...ava是一种面向对象的编程语言,其中OOP用于定义类。可以使用单个类创建许多对象。尽管这两种语言都面向特定的编程风格,但仍然可以用Java编写过程风格,用C编写面向对象风格。然而,在每种情况下,编程时语言都会以某种...
...用程序用途。虽然这两个术语可能是同义词,但不能互换使用。 两者之间有显著差异。虽然默认情况下接口方法是抽象的,但抽象可以同时包含抽象方法和非抽象方法。好吧,因为Java8,接口也有方法实现,它们可以有Java中的...
...在我们开始讨论c***t和readonly之间的区别之前,让我们先了解一下关键字以及它们在程序中的用法。这两个都是C#编程中最常用的关键字,基本上用途相同。然而,这两个关键词是非常不同的彼此。C***t是一个保留字,用于表示常...
...可以与实例变量、局部变量,甚至与参数方法的变量一起使用。通过将变量声明为final,您向每个人显示,在存在期间变量将具有相同的值。更重要的是,编译器将检测到更改声明变量值的每次尝试,并将其报告为错误。至于Java...