Win a copy of Fixing your Scrum this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Rob Spoor
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Holloway
  • Piet Souris
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Himai Minh

What is the default value of long, 0 or 0L ?

 
Greenhorn
Posts: 4
Netbeans IDE Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

If i run the default value of long on the JVM the default value is 0 but the textbook says 0L. PLEASE can anyone help with clarity ?
 
Marshal
Posts: 8050
569
Mac OS X VI Editor BSD Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please quote the source so it could be double checked.

How did you verify your claim?
 
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Many will find this not that interesting, but for the OP and anyone else who wants to read (much) more about the issue, more was written in this thread:
https://coderanch.com/t/744763/certification/Unclear-default-initialization-values-OCP

And in another thread I linked to from there.

Mostly the confusion comes about from the fact that integral constants in code look differently from the way they print out, etc. but it is all in those two threads in its gory detail.

Enjoy/be warned.
 
Saloon Keeper
Posts: 24174
165
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Any variable defined as long is only going to contain long values.

Now technically, if you are coding something like this:

You are assigning an int value to a long property, but the language invokes constant widening automatically, so the actual value stored will be 0L and 4L.

It isn't a bad practice to say 0l when you MEAN 0L, and especially to induce value widening on more complex expressions, but the compiler understands if you take the shortcut.

Note that in the C language, "0" is actually a magic indicator. It gets interpreted as an int where an int expression applies, a long where a long expression applies and as a null pointer in pointer expressions.

Null pointers in C are very interesting, because while on most machines, they do, in fact, reference memory location 0, some of the quirkier machines may have other ideas, so although you're coding 0 for null, the actual internal value might be something completely different.

In Java, of course, there are no pointers, and "null" means a reference to no object.  What its internal value is is not given to us. So you cannot use "0" as a magic token for NullPointer.
 
Enthuware Software Support
Posts: 4571
45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Default values of all numeric types is "zeroes in all bits". Obviously, it is not practically possible to type 8, 16, 32 or 64 zeroes to convey the exact type of your variable whenever you want to tell that it holds a 0 value. So, it is correct to say just 0.
However, within Java code, you do need to convey the type information to the compiler and so, you write 0, 0.0, or 0L or 0.0f, depending on the type of the variable you want to assign the value to.

So, the default value of an int (or a long, float, double) variable is indeed zero. But writing int i = 0L; in Java code would be wrong.
 
Munyaradzi Matindike
Greenhorn
Posts: 4
Netbeans IDE Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Liutauras Vilda wrote:Please quote the source so it could be double checked.

How did you verify your claim?



RUN THIS CODE.

public class Munyaradzi{

long java;

public static void main(){

Munyaradzi mun=new Munyaradzi();
mun.java;
System.out.println(mun.java);

}

}
 
Tim Holloway
Saloon Keeper
Posts: 24174
165
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Cannot run. It won't compile.

Also please use Code tags. Loose Java code in messages is hard to read. Quoted loose Java code in messages is even harder to read.
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As explained in my post, linked thread, and the replies of others, what you see when you do System.out.println( myNumericVar ); does not necessarily match exactly to the legal syntax for writing a numeric constant literal of the same type.

When you want a numeric constant literal to be of type long, it must be suffixed by an L like 123L (or an 'l' if you want everyone to hate you, like 123l).
When you want a numeric constant literal to be of type float, it must be suffixed by an F like 1.23F or (1.23f).

When you print out a value of type long or float, you will not see any L or F suffix.

We beat this to death (at least I do) in some other linked threads, but the fact that you don't see the identifying suffix on the values upon printout does not mean that the value is only 32-bits.

There is no sizeof() method for primitives to demonstrate this in Java.

long is defined to be 64-bits in Java SE.  Everywhere.  Always.
int is defined to be 32-bits in Java SE.  Everywhere.  Always.

When you see this:
jshell> long story = 0
story ==> 0


here is what is happening.  0 is a numeric constant literal defined to be 32 0 bits.
Seeing that you are assigning it to a long, which is 64-bits, Java helpfully sign-extends it to now be 64 0 bits, which is the value of story.  The value that gets assigned is exactly the same as if you had typed:
long story = 0L;

When you print out story, or convert it to a String value, explicitly or implicitly, Java does NOT by convention print an L in the output.
Nevertheless, all long values are 64-bit, two's complement signed integers.

There are myriad ways you CAN see this.  You can look in a debugger, you can look at the Java Bytecode getting output from javap, etc.

99.9% of people would just say "Oh, okay" when people point out that a long value of 64 0-bits looks one way when you see it in source code (0L) and another when printed out (0) and same thing with float and the F.

We can blame the certification exam, which is so picky on details it feels like it was written by a lawyer who was still angry at you for stealing their girlfriend back at school.
Various preparation materials contain confusing or ambiguous material and questions on this topic.
They are some of the least enjoyable, most annoying parts of that entire process.
 
Tim Holloway
Saloon Keeper
Posts: 24174
165
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't have the actual Java spec details in front of me, but at the abstract level the value of a long, for example, is 2**63 bits plus sign (which is effectively boolean).

But thinking too closely in terms of bits - or worse yet - bytes - can be hazardous. Yes, if you apply shift and logical operations to Java integer types, they will behave just like an array of bits. But internally it's another story.

Most obvious is "endian-ness". Why DEC thought it was cool to use a bytewise-discontinuous means of storing integer values in RAM (and why Intel chose to copy it) is a mystery unknown to me. Other machines of the day did not. The more common ruie was bytewise-continuous, and that, in fact, is the format that even DEC/Intel used as long as the value was in a register, rather than in RAM. Some of the really wild architectures from early days might have things like 5-bit words, using BCD digits (4 bits) plus an explicitly visible parity bit (or 2). When DEC was in its prime, Prime computer (pun intended?) used a 16-bit bitwise-continuous word architecture (not byte-addressable) and it wasn't the only one. A lot of minicomputers did that.

Java, of course, is required to be immune to all these foibles. So what you are really dealing with is a virtual view of something that may not exactly match what's really in RAM. Or perhaps even on the internal JVM stack.

C has been touted as a "high-level assembly language", and is routinely expected to allow you to play tricks with its data types. Java, on the other hand, was designed to make such tricks and assumptions as difficult as possible.

So imagine that a long is 64 bits continuous, including sign. You might be right. Or maybe only virtually right.


Sorry about the edits. Whatever I started writing in the first paragraph got nuked, I think and I had to try and re-create it.
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OP: You probably don't need to read ANY of this now.  You should likely be satisfied and moving on, but...for Tim:

I agree that 99% of Java programmers should just be thinking of int and long as opaque types that magically hold a value between X and Y 99% of the time.

But the Integer and Long classes expose some interesting functionality these days that goes beyond "I have no idea what an int or long looks like, so glad I don't need to know!"

Witness:
static int bitCount​(int i)
Returns the number of one-bits in the two's complement binary representation of the specified int value.

static int highestOneBit​(int i)
Returns an int value with at most a single one-bit, in the position of the highest-order ("leftmost") one-bit in the specified int value.

static int lowestOneBit​(int i)
Returns an int value with at most a single one-bit, in the position of the lowest-order ("rightmost") one-bit in the specified int value.

static int numberOfLeadingZeros​(int i)
Returns the number of zero bits preceding the highest-order ("leftmost") one-bit in the two's complement binary representation of the specified int value.
static int numberOfTrailingZeros​(int i)
Returns the number of zero bits following the lowest-order ("rightmost") one-bit in the two's complement binary representation of the specified int value.

static int reverse​(int i)
Returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified int value.
static int
reverseBytes​(int i)
Returns the value obtained by reversing the order of the bytes in the two's complement representation of the specified int value.
static int rotateLeft​(int i, int distance)
Returns the value obtained by rotating the two's complement binary representation of the specified int value left by the specified number of bits.
static int
rotateRight​(int i, int distance)
Returns the value obtained by rotating the two's complement binary representation of the specified int value right by the specified number of bits.

None of these things were available in Java SE the first 9 years that I worked with people who scoffed at it "That's a toy language for kids!!  I need to deal with BITS!!  I am a REAL PROGRAMMER!!"
Look, it sounded legit then and maybe was.

All these things and these have long since been there tho:
static int BYTES
The number of bytes used to represent an int value in two's complement binary form.
static int MAX_VALUE
A constant holding the maximum value an int can have, 231-1.
static int MIN_VALUE
A constant holding the minimum value an int can have, -231.
static int SIZE
The number of bits used to represent an int value in two's complement binary form.

They are there, in Java SE on all platforms now, when we need them.  We usually don't.  But we have less excuse than ever before (and far less than in early Java days) to resort to native code.
All that stuff is now there, supported, tested and works everywhere, which is more than I can say about the accidentally non-portable C code I'd write to do the same things.
 
Tim Holloway
Saloon Keeper
Posts: 24174
165
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yup. As I said, the virtual view that Java presents may differ wildly from the machine-level view, but it's guaranteed consistent, And no doubt IBM is laughing, since it's essentially their version.

Whether bits, bytes and ints should have even been so interchangeable is a matter for debate - they are mainly holdouts from Java's C roots, after all, but they're there and at least we can rely on their write-once/run-anywhere behavior. Note that the DID break the interchangeability rule for boolean, though!

I don't think I've ever seen a specific C library for ALL the bit functions that Java supports. Although a friend of mine used to do horrible things to bits by abusing floating-point normalizations.

Still, you can standard header files that determine the limits of a given C compiler's numbers. In fact, it was essential when programming for the Commodore Amiga, since some treated it as a 16-bit computer and some treated it as a 32-bit computer and advanced compilers had option switches to specifically go one way of the other.
 
Paul Anilprem
Enthuware Software Support
Posts: 4571
45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Actually, the JLS in section 4.1 says so clearly:


The integral types are byte , short , int , and long , whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char , whose values are 16-bit unsigned integers representing UTF-16 code units (§3.1).


(emphasis is mine)

So, it is accurate to say that a long variable containing 0 is a series of 64 zeros.

Further, in section 4.2.1, JLS 11 says,


The values of the integral types are integers in the following ranges:
...


So, it is also perfectly accurate to say that the value of a long variable containing 0 is just 0.

Even though the two statements may seem contradictory but they are not. The first one defines the machine view and the second one defines the conceptual/virtual view.

So, I am now of the opinion that the statement "value of a long var containing 0 is 0L" is actually wrong  
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Paul, everyone knows that I love Enthuware and you personally, but that makes me want to ask you if we should say that:

jshell> Long.MAX_VALUE
$16 ==> 9223372036854775807

is 9223372036854775807 or 9223372036854775807L.

Why?
jshell> long myLong = 9223372036854775807
|  Error:
|  integer number too large
|  long myLong = 9223372036854775807;
|                ^

jshell> long myLong = 9223372036854775807L
myLong ==> 9223372036854775807

So there is legal format for a numerical literal constant. what Java will by default print as or convert to a String as, and the conceptual view of the bits, as well as a (possibly but unlikely) different internal representation that may or may not match the conceptual view of the bits.  The first three are to some extent or another in scope for the OCPJP exam, the last two are just good for Geek-offs between people who had been programming for many years before Java was a twinkle in Gosling's eye.

I already know how to program, but turn to JavaRanch to learn Java conventions and style and idioms, and turn to the Sybex books and Enthuware to tell me what is on that *&*$^%$ exam.

This has gone way, way past what the OP and most readers need to know for the exam, but is important for someone who truly wants to understand Java's full model for int and long and arithmetic on such types.
 
Tim Holloway
Saloon Keeper
Posts: 24174
165
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Anilprem wrote:
So, I am now of the opinion that the statement "value of a long var containing 0 is 0L" is actually wrong  



You would probably see it differently if things were more consistent. "0" is a numeric value. "0L" is an implementation-specific numeric value. If there were a corresponding "I" suffix, then 0I and 0L would be obviously 2 distinct implementation-specific values, whereas "0" is an abstract value. It's one of the reasons why I think basic Calculus is a good thing for every programmer to know - before you ever get to the manipulative stuff, they first hammer home the concepts of domain and range, thus indicating the difference between a universal space and a constrained one (in our case, constrained to set numbers of binary digits).

While we're at it, we use "bits" carelessly. In math terms, a bit is literally a binary digit - a Base-2 concept. But we flip-flop between thinking of bits in math terms and thinking of bits as the contents of a 2-state storage element. They're not actually the same thing.  And, incidentally, there are basic storage systems where more than 2 states can fit into an element. That was true decades before we started mucking around with quantum values.

Java has re-implemented char, incidentally. Originally it was a fixed 16-bit Unicode value, but modern JVMs will select between legacy and UTF forms internally. Most apps won't notice, but it does make a difference when accessing for codepoint value.
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Same deal for asking about MAX_VALUE and MIN_VALUE for float, but kind of the other way around:
jshell> Float.MAX_VALUE
$18 ==> 3.4028235E38

jshell> float myFloat = 3.4028235E38
|  Error:
|  incompatible types: possible lossy conversion from double to float
|  float myFloat = 3.4028235E38;
|                  ^----------^

jshell> float myFloat = 3.4028235E38F
myFloat ==> 3.4028235E38


Trickily worded questions with ambiguous answers regarding default or allowable values for int, long, double, float would be my candidate for worst questions to put on a mock or real certification exam.
Actually the worst ones are probably complex nested loops with non-trivial targeted continue or break, I find those take me five minutes to complete on an exam that only affords ~2 minutes per question...
 
Paul Anilprem
Enthuware Software Support
Posts: 4571
45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for the kind words, Jesse!
The keyword here, imho, is "say". If you want to say the value, say the value without the L.
If you want to write the value in Java code, then put the L because that is the rule of the language (that long values have to be written with the suffix L).

Having said that, we haven't seen anyone getting a question where you have to differentiate between 0 and 0L in past several years. I keep a watch on such things (forums and talking to our exam trainees) and I haven't heard it from any candidate.

HTH,
Paul.
 
Jesse Silverman
Master Rancher
Posts: 1005
27
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Paul, also in consideration for nomination for "Beating a Dead Moose" award, here is another more direct reason I would say it is better to think of the long value which is an identity for addition as 0L, not 0:

jshell> Long myLong = 0
|  Error:
|  incompatible types: int cannot be converted to java.lang.Long
|  Long myLong = 0;
|                ^

jshell> Long myLong = 0L
myLong ==> 0


I mentioned that in the other thread(s).
I am done now, really done.

Note that this tricky bit may actually be in scope for the OCJP exam, Paul can confirm.
You can box then widen, it is clear as Black and White.
You can't widen then box in one operation, the compiler Won't Budge.

jshell> Number myNumber = 9223372036854775807L
myNumber ==> 9223372036854775807

That's my dumb mnemonic for remembering these odd rules, which are ten million times better than the "twelve C compilers, twenty different behaviors counting compile options" world I came from.
The Rules are sometimes complex, but they are Rules, and work everywhere your Java goes.  So.   Much.  Easier!
 
Paul Anilprem
Enthuware Software Support
Posts: 4571
45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Holloway wrote:"0L" is an implementation-specific numeric value.


Wouldn't you agree that 0L is just a notation for writing a conceptual numeric value in Java code? It is not an actual value of any kind - neither a machine value nor a conceptual value.
 
Would you like to try a free sample? Today we are featuring tiny ads:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic