问题
I saw this sentence in some matrials:
"In Java, simple data types such as int and char operate just as in C."
I am wondering that actually they are different in Java & C++?
In C++, simple variables like the primitives in Java are assigned a memory address as well, so these primitive types in C++ can have a pointer as well. However primitives in Java are not assigned a memory address like Objects are.
Am I correct?
Thanks!
回答1:
Almost.
In java primitives are assigned memory as well, but this happens internally and you cannot get the reference.
Thre reason was to provide security on memory management.
回答2:
There are a few differences between Java and C++ when it comes to simple types. The memory allocation is different as Java hides the concept of explicit pointers and references. You just create the simple type and assign a value. Another difference is that Java uses standardized memory footprints for each simple type check Java Simple Types. C++ on the other hand is dependent on the platform that it is compiled on. Another point (and I don't know if it is a difference or not) is that assignment into simple types is Thread safe. I've not done any multi-threaded programming in C++ so I'm not certain if this is a consideration.
回答3:
For most basic stuff, they work the same, but there is a ton of detail differences.
- There are no unsigned numerical types in Java (except char, which technically but not semantically numerical)
- Java's "primitive types" can only live on the stack (as local variables) or inside objects on the heap, but not directly on the heap.
- The char type is very different - in C, it's defined to contain one byte (the byte may or may not have 8 bits), whereas in Java, it's defined to be 16 bit.
回答4:
Correct.
In java you cannot pass a reference(pointer) to a primitive type. //Infact there is no such thing as pointers in Java.
A primitive type can only be passed by value in Java. There is a way around it, but it isnt usually recommended unless your situation demands it. You can use a wrapper class. When to use wrapper class and primitive type
Only objects are passed by reference.
Also Primitive types are allocated on the stack and Objects are allocated on the heap.
回答5:
Primitives are stored onto the Stack and are passed by value.
int x = 5;
int y = x;
y++;
// y = 6
// x = 5
Objects are stored onto the heap and are passed by reference.
Object a = new Object();
Object b = a;
b.someAction();
// A and B point to the same object and both have had the 'someAction()' performed
I've no idea if this is what your asking, but I'm bored and wish to post something
来源:https://stackoverflow.com/questions/338772/simple-variables-in-java-c