DreddTrekkiter February 2016

What is a constant in Java

I have been looking all over the web, StackExchange, Wikipedia, YouTube, random sites, everywhere but I haven't got a simple answer, or it's been different from what others have said.

Some resources have said, in Java, Constants are variables whose value cannot be changed.

Other have said Constants are objects whose name cannot be changed.

And more have said Constants are variables whose name cannot be changed.

Please could someone tell me in English exactly what a Constant is, which parts can/cannot be changed and maybe an example where constants would be used instead of a normal variable.

Thanks in advance!

Answers


Hackerdarshi February 2016

A constant is something of which everything is constant. Name, value whatever you call it. It cannot be changed. Some also call it a literal.

eg:

  • 9 is an integer constant. You cannot change 9. It's name is 9, you call it nine, it value value is 9.
  • "ABC" is a String constant.
  • 9.7 is a floating point constant.
  • true is a boolean constant.
  • 'a' is a character constant.


TheLostMind February 2016

A constant is value that cannot be changed. For example 5, 0.5 , "abcd" etc.

Lets consider Java :

int i = 5; // Here 5 is constant but the reference (i) can change and point to 6. i.e, the value 5 is immutable, but the reference (i) is mutable.

Adding the final keyword to the above statement :

final int i = 5; // Here the keyword final ensures that the reference cannot point to any other value. 

Thus i becomes a compile time constant and its value is passed in the byte-code itself.

Note that a reference could point to a constant value (immutable object ) or a mutable value.

Technically speaking, immutable values aren't same as constants in case of reference types (except String).

Post Status

Asked in February 2016
Viewed 1,879 times
Voted 13
Answered 2 times

Search




Leave an answer