Runtime constant pool - is filled up by variables created in runtime? - java

I'm not sure about some properties of runtime constant pool.
Runtime constant pool, is filled up by the data from constant pool (from .class files, during class loading). But is it also filled up by variables created in runtime? Or are they converted during compilation to literals, and stored in constant pool?
For example:
Integer i = new Integer(127);
is treated like literal, because of conversion to:
Integer i = Integer.valueOf(127);
during compilation, and stored in constant pool?
If it's not working like that, is there any runtime mechanics for runtime constant pool?
And second question: I have found this sentence in many articles: "every class got Runtime constant pool", but what does it mean? Is there a single RCP, that contains all application objects of (for example) Integer type, or is there a single RCP for every class, that contains all constant objects, that occured in this class? (for example: Person, got age = Integer(18), and isAdult = Boolean(true)).

First, there is no conversion of
Integer i = new Integer(127);
to
Integer i = Integer.valueOf(127);
These constructs are entirely different. new Integer(127) is guaranteed to produce a new instance every time it is evaluated, whereas Integer.valueOf(127) is guaranteed to produce the same instance on every evaluation, as Integer.valueOf guarantees for all values in the -128 … +127 range. This is handled by the implementation of the Integer.valueOf(int) and not related to constant pools in any way. Of course, it is implementation specific, but the OpenJDK implementation handles this by simply filling an array with references to these 256 instance the first time, this cache is accessed.
While it is correct that every class has a constant pool in its class file, it might be misleading to say that every class will have a runtime constant pool (on its own). That’s again a JVM implementation detail. While it is possible to map each class constant pool 1:1 to a runtime constant pool, it obviously makes sense to merge the constant pools of classes living in the same resolve context (i.e. defined by the same class loader) into one pool, so that identical constants don’t need to be resolved multiple times. Though, conceptionally, every class has a runtime representation of its pool, even if they do not materialize in this naive form. So the statement “every class has a runtime constant pool” is not wrong, but it doesn’t necessarily imply that there will be such a data structure for every class.
This affects classes, members, MethodType, MethodHandle and String instances, referenced by the constant pools of the classes, but not wrapper types like Integer or Boolean, as there are no such entries in a constant pool. Integer values in the pool are primitive values and boolean values do not exist at all.
This must not be confused with the global String pool references all String instances for literals and the results of intern() calls.

Problem 1 - Anwser: No
Integeral wrapper types are cached, not stored in the constant pool. They are just ordinary objects in the heap. Integer or Byte caching is a runtime optimization, not a VM optimization, nor a compile time optimization. They are not magically replaced with the cached one when their constructor is invoked to create a new one.
First, your translation from new Integer(127) to Integer.valueOf(127) is not correct at all as explained in this post. If you do some runtime verifications, like System.out.println(Integer.valueOf(127) == new Integer(127)); (prints false), you will quickly come to the conclusion that no matter what object you are constructing, using new operator always creates a new, uncached object. (Even Strings, who's actually in the runtime constant table, need being interned to get a reference to the canonical one.)
What i variable hold is just reference pointing to a Integer object in the heap. It will be cached if you are using valueOf and vice versa.
Problem 2 - Anwser: There a single RCP for every class but they are all in the same memory region
The RCPs are all stored in method area. Personally I don't know how JVM is implemented, but JVMS has stated:
The Java Virtual Machine maintains a per-type constant pool (§2.5.5), a run-time data structure that serves many of the purposes of the symbol table of a conventional programming language implementation.
Nevertheless, this doesn't matter even from a performance tuning view, as long as you don't plan to apply for a job in Oracle.

Related

Compiler behavior with String literals to Create String Constant Pool

After reading these discussions - question 1, question 2, article
I have the below understanding of Java String Constant Pool (Please correct me, If I am wrong):
When the source code is compiled, compiler look for all the string literals (The ones put into double quotes) in our program and create distinct(No duplicates) objects in the heap area and maintain their references in a special memory area called String Constant Pool (An area inside method area). Any other string objects are created at run time.
Suppose our code has the following statements:
String a = "abc"; //Line 1
String b = "xyz"; //Line 2
String c = "abc"; //Line 3
String d = new String("abc"): //Line 4
When the above code is compiled,
Line 1: a String object "abc" is created in heap and this object is referenced by variable a and String Constant Pool.
Line 2: Compiler searches String Constant Pool for any existing reference to the object "xyz". But does not find one. So, it creates object "xyz" and puts its reference in String Constant Pool.
Line 3: This time compiler finds the object in String Constant Pool and does not make any additional entry in pool or heap. Variable c just refers to existing object which is also referred by a.
Line 4: The literal in Line 4 is present in String Constant Pool. So, no more entry is made in pool. At run time however another String object is created for "abc" and its reference is stored in variable d.
Now I have the following questions/doubts:
Is that what happens exactly which is described above?
How does the compiler creates object? As per my knowledge, objects
are created at Run time and heap is a Run time memory area. So, how
and where does String objects are created at the time of
compilation!
Source code can be compiled in one machine and run in a different
machine. Or, even in the same machine they can be compiled and run in
different time. Then how those objects (created in compile time) are
recovered?
What happens when we intern a String.
Is that what happens exactly which is described above?
Yes, conceptually, however, the constant pool and string pool are different things.
The constant pool is a part of a .class file that contains all constants used in this class.
The string pool is a runtime concept - interned strings and string literals are stored here.
Here's the JVM specification on the constant pool. It is part of the section on the .class format.
How does the compiler creates object? As per my knowledge, objects are created at Run time and heap is a Run time memory area. So, how and where does String objects are created at the time of compilation!
How/when exactly this happens, I believe, is a JVM implementation-specific detail (correct me if I am wrong), but the basic explanation is that whenever the JVM decides to load a class, any strings found in the constant pool are automatically placed into the runtime string pool, and any duplicates are made to refer to the same instance.
In one of the linked answers' comments, Paŭlo Ebermann says:
when the classes are loaded in the VM, the string constants will get copied to the heap, to a VM-wide string pool
so it seems this is at least how Sun's VM implemented the string pool.
Prior to JDK 7/HotSpot interned strings were stored in the permanent generation space - now they are stored in the main heap.
Source code can be compiled in one machine and run in a different machine. Or, even in the same machine they can be compiled and run in different time. Then how those objects (created in compile time) are recovered?
Constants are stored in the compiled files. Therefore they are retrievable whenever the JVM decides to load this class.
What happens when we intern a String.
This is answered here:
doing String.intern() on a series of strings will ensure that all strings having same contents share same memory

JVM architecture: Runtime constant pool in Method area is per-class

By reading Oracle JVM architecture document:
https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html
A run-time constant pool is a per-class or per-interface run-time
representation of the constant_pool table in a class file (§4.4).
I understand that for each class, it has a runtime constant pool (please correct me if I am wrong).
However, what I am confused is that if I have two different classes A and B and each class has a private String variable say String value = "abc".
if I compare A.value with B.value using == rather than equals, I will get a true which make me think that "abc" in both A and B are in the same runtime constant pool? Could someone point me out where I am wrong ?
This is a preemptive optimization that the JLS superimposes.
From JLS 7, §3.10.5 (formatting mine)
Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
However, note that this is only true of String literals and constant expressions. Dynamically constructed strings (e.g. x + y for Strings x and y) are not automatically interned to share the same unique instances. As a result, you will still have to use .equals in general unless you can guarantee that your operands are constant expressions.
This is because '==' is comparing references. Objects of both A and B have different String value variables (and so each class' constant pool has a separate entry for it); but they are both initialized to the same value. The compiler/JVM is most likely optimizing for space by having them both point to the same compile-time constant value in the bytecode. The '==' operator is NOT comparing constant pool locations.
Edit: to clear up some confusion, this does NOT mean that "==" can be used for string comparison. All I was saying was that it cannot be used to compare constant pool location either. It is for one thing and one thing only: comparing whether two references point to the same object. The situation in the question will SOMETIMES result in == returning true, but sometimes not. It depends on decisions the compiler and JVM make (or depending on what the JSL says as an astute answerer has said).

What happens when JVM executes new key word to create an object?

I know JVM uses stack and heap for allocation of memory for object reference, object value and memory for methods. But I am confused about the terminologies: METHOD AREA, HEAP and JAVA STACK and I have few question's.
When we say "ClassName obj = new ClassName()", new creates an object on the HEAP(the instance variables and static variables too) and what is returned to the reference(obj)? Some people use to say it is CLASS TYPE, does it mean the hash code?
When new creates the object on the heap, at the same time: i)the methods,corresponding to that object ii)local variables and iii)the reference to that object are stored as part of STACK( is it JAVA STACK?). If so, then what does METHOD AREA do? Or am I wrong?
What is the amount of memory allocated for that object?
i. for object reference
ii. for object values(it depends on the local variables)
iii. will there be a memory allocated to point the object's methods?( because the non-static members are not shared among the objects and a separate copy is maintained for each objects including the methods).
By the way, where does static methods are stored?
When we say "ClassName obj = new ClassName()", new creates an object
on the HEAP(the instance variables and static variables too) and what
is returned to the reference(obj)? Some people use to say it is CLASS
TYPE, does it mean the hash code?
Yes new creates Object on the HEAP. Heap is a memory place where the objects and its instance variable are stored. Not static variables since static variables doesn't belong to Object it belongs to class so are stored on PermGem Sections (class related data, not instance related).
What is Returned : the reference(pointer/memory address) i.e hashcode
When new creates the object on the heap, at the same time: i)the
methods,corresponding to that object ii)local variables and iii)the
reference to that object are stored as part of STACK( is it JAVA
STACK?). If so, then what does METHOD AREA do? Or am I wrong?
since All threads share the same method area methods don't corresponds to Objects it belongs to class
what does METHOD AREA do :The method area stores per-class information, like Run Time Constant Pool, Method code, The method's return type (or void) etc
What is the amount of memory allocated for that object? i. for object
reference ii. for object values(it depends on the local variables)
iii. will there be a memory allocated to point the object's methods?(
because the non-static members are not shared among the objects and a
separate copy is maintained for each objects including the methods).
Amount of Memory for Object Reference: it depends as on many VMs the size of a reference is the native pointer size and for (iii) above point already cleared that
I know JVM uses stack and heap for allocation of memory for object reference
correct.
object value
I assume you means the object's header and fields.
and memory for methods.
Methods are not stored in the heap, or stack. When you profiler the heap usage or set the maximum heap size, the use of methods makes no difference as they are not on the heap in the Oracle or OpenJDK JVM.
They are stored in the PermGen or MetaSpace or some other space depending on which JVM you are using.
But I am confused about the terminologies: METHOD AREA,
From Method Area in Java
The Java Virtual Machine has a method area that is shared among all Java Virtual Machine threads. The method area is analogous to the storage area for compiled code of a conventional language or analogous to the "text" segment in an operating system process. It stores per-class structures such as the run-time constant pool, field and method data, and the code for methods and constructors, including the special methods (§2.9) used in class and instance initialization and interface initialization.
HEAP
Shared space for storing objects. This is usually one continuous region of native memory managed by the JVM.
and JAVA STACK
The thread's stack which is actually a native thread stack on most JVM.
When we say "ClassName obj = new ClassName()", new creates an object on the HEAP(the instance variables and static variables too)
It might, but it can also eliminate the object with escape analysis, placing the fields on the stack, and possibly eliminating those.
and what is returned to the reference(obj)?
Correct, Java only has references and primitives (if you ignore the void type which is neither)
Some people use to say it is CLASS TYPE,
The reference is defined by giving the type of the reference which is a class or interface.
does it mean the hash code?
A hash code is a hash value for the object. It is not releated to anything else you have mentioned.
When new creates the object on the heap,
When you create a new object on the heap, you just create space for the header of the object (which points to the class and it's methods) and space for it's fields. (Those the JVM doesn't optimise away)
at the same time: i)the methods
The methods are loaded/compiled in various stages. The methods are loaded as they are needed for the first time and later if they are compiled.
corresponding to that object ii)local variables
Local variables are on the stack, not on the heap, not in the object.
iii)the reference to that object are stored as part of STACK( is it JAVA STACK?).
The Java Stack, is the Stack, is the native stack.
If so, then what does METHOD AREA do?
Store the code for the methods.
What is the amount of memory allocated for that object?
About 8-12 bytes per header, space for each primitive field and reference and alignment padding of 8 or 16 bytes (32 GB - 64 GB heaps).
i. for object reference
Typically this is 32-bit on 64-bit JVMs (With compressed oops). If you have more than 64 GB heap it will be 64 -bit.
ii. for object values(it depends on the local variables)
Local variables are on the heap not the object.
iii. will there be a memory allocated to point the object's methods?
Method memory usage is not visible to you. It is not on the heap, nor something you can measure on a per method basis. I don't know of a profiler which will even show you this.
( because the non-static members are not shared among the objects and a separate copy is maintained for each objects including the methods).
That sounds like an insane waste of space, and it is, which is why the JVM does do that. There is only one copy for a method, regardless of the number of instances.
By the way, where does static methods are stored?
With all the other methods. There is no difference between a static method and a non-static method except a non-static method must take an instance as it's first argument at the JVM level. (And there is a bit in the modifiers to say whether it is static or not)

Do uninitialized primitive instance variables use memory?

In Java, does it cost memory to declare a class level instance variable without initializing it?
For example: Does int i; use any memory if I don't initialize it with i = 5;?
Details:
I have a huge super-class that many different (not different enough to have their own super classes) sub-classes extend. Some sub-classes don't use every single primitive declared by the super-class. Can I simply keep such primitives as uninitialized and only initialize them in necessary sub-classes to save memory?
All members defined in your classes have default values, even if you don't initialize them explicitly, so they do use memory.
For example, every int will be initialized by default to 0, and will occupy 4 bytes.
For class members :
int i;
is the same as :
int i = 0;
Here's what the JLS says about instance variables :
If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value (§4.12.5) as part of each newly created object of class T or of any class that is a subclass of T (§8.1.4). The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object (§12.6) has been completed.
Yes, memory allocates though you are not assigning any value to it.
int i;
That takes 32 bit memory (allocation). No matter you are using it or not.
Some sub-classes don't use every single primitive declared by the super-Class. Can I simply keep such primitives as uninitialized and only initialize them in necessary sub-classes to save memory?
Again, no matter where you initialized, the memory allocates.
Only thing you need to take care is, just find the unused primitives and remove them.
Edit:
Adding one more point that unlike primitive's references by default value is null, which carries a a memory of
4 bytes(32-bit)
8 bytes on (64-bit)
The original question talks about class level variables and the answer is that they do use space, but it's interesting to look at method scoped ones too.
Let's take a small example:
public class MemTest {
public void doSomething() {
long i = 0; // Line 3
if(System.currentTimeMillis() > 0) {
i = System.currentTimeMillis();
System.out.println(i);
}
System.out.println(i);
}
}
If we look at the bytecode generated:
L0
LINENUMBER 3 L0
LCONST_0
LSTORE 1
Ok, as expected we assign a value at line 3 in the code, now if we change line 3 to (and remove the second println due to a compiler error):
long i; // Line 3
... and check the bytecode then nothing is generated for line 3. So, the answer is that no memory is used at this point. In fact, the LSTORE occurs only on line 5 when we assign to the variable. So, declaring an unassigned method variable does not use any memory and, in fact, doesn't generate any bytecode. It's equivalent to making the declaration where you first assign to it.
Yes. In your class level variables will assign to its default value even if you don't initialize them.
In this case you int variables will assign to 0 and will occupied 4 bytes per each.
Neither the Java Language Specification nor the Java Virtual Machine Specification specifies the answer to this because it's an implementation detail. In fact, JVMS §2.7 specifically says:
Representation of Objects
The Java Virtual Machine does not mandate any particular internal structure for objects.
In theory, a conformant virtual machine could implement objects which have a lot of fields using set of bit flags to mark which fields have been set to non-default values. Initially no fields would be allocated, the flag bits would be all 0, and the object would be small. When a field is first set, the corresponding flag bit would be set to 1 and the object would be resized to make space for it. [The garbage collector already provides the necessary machinery for momentarily pausing running code in order to relocate live objects around the heap, which would be necessary for resizing them.]
In practice, this is not a good idea because even if it saves memory it is complicated and slow. Access to fields would require temporarily locking the object to prevent corruption due to multithreading; then reading the current flag bits; and if the field exists then counting the set bits to calculate the current offset of the wanted field relative to the base of the object; then reading the field; and finally unlocking the object.
So, no general-purpose Java virtual machine does anything like this. Some objects with an exorbitant number of fields might benefit from it, but even they couldn't rely on it, because they might need to run on the common virtual machines which don't do that.
A flat layout which allocates space for all fields when an object is first instantiated is simple and fast, so that is the standard. Programmers assume that objects are allocated that way and thus design their programs accordingly to best take advantage of it. Likewise, virtual machine designers optimize to make that usage fast.
Ultimately the flat layout of fields is a convention, not a rule, although you can rely on it anyway.
In Java, when you declare a class attribute such as String str;, you are declaring a reference to an object, but it is not pointing yet to any object unless you affect a value to it str=value;. But as you may guess, the reference, even without pointing to a memory place, consumes itself some memory.

Difference between new operator in C++ and new operator in java

As far as I know, the new operator does the following things: (please correct me if I am wrong.)
Allocates memory, and then returns the reference of the first block of the
allocated memory. (The memory is allocated from heap, obviously.)
Initialize the object (calling constructor.)
Also the operator new[] works in similar fashion except it does this for each and every element in the array.
Can anybody tell me how both of these operators and different in C++ and Java:
In terms of their life cycle.
What if they fail to allocate memory.
In C++, T * p = new T;...
allocates enough memory for an object of type T,
constructs an object of type T in that memory, possibly initializing it, and
returns a pointer to the object. (The pointer has the same value as the address of the allocated memory for the standard new, but this needn't be the case for the array form new[].)
In case the memory allocation fails, an exception of type std::bad_alloc is thrown, no object is constructed and no memory is allocated.
In case the object constructor throws an exception, no object is (obviously) constructed, the memory is automatically released immediately, and the exception is propagated.
Otherwise a dynamically allocated object has been constructed, and the user must manually destroy the object and release the memory, typically by saying delete p;.
The actual allocation and deallocation function can be controlled in C++. If there is nothing else, a global, predefined function ::operator new() is used, but this may be replaced by the user; and if there exists a static member function T::operator new, that one will be used instead.
In Java it's fairly similar, only that the return value of new is something that can bind to a Java variable of type T (or a base thereof, such as Object), and you must always have an initializer (so you'd say T x = new T();). The object's lifetime is indeterminate, but guaranteed to be at least as long as any variables still refer to the object, and there is no way to (nor any need to) destroy the object manually. Java has no explicit notion of memory, and you cannot control the interna of the allocation.
Furthermore, C++ allows lots of different forms of new expressions (so-called placement forms). They all create dynamic-storage objects which must be destroyed manually, but they can be fairly arbitrary. To my knowledge Java has no such facilities.
The biggest difference is probably in use: In Java, you use new all the time for everything, and you have to, since it's the one and only way to create (class-type) objects. By contrast, in C++ you should almost never have naked news in user code. C++ has unconstrained variables, and so variables themselves can be objects, and that is how objects are usually used in C++.
In your "statement", I don't think "returns a reference to the first block of allocated memory is quite right. new returns a pointer (to the type of the object allocated). This is subtly different from a reference, although conceptually similar.
Answers to your questions:
In C++ an object stays around in memory (see note) until it is explicitly deleted with delete or delete [] (and you must use the one matching what you allocated with, so a new int[1];, although it is the same amount of memory as new int; can not be deleted with delete (and vice versa, delete [] can't be used for a new int). In Java, the memory gets freed by the garbage collector at some point in the future once there is "no reference to the memory".
Both throw an exception (C++ throws std::bad_alloc, Java something like OutOfMemoryError), but in C++ you can use new(std::nothrow) ..., in which case new returns NULL if there isn't enough memory available to satisfy the call.
Note: It is, as per comment, technically possible to "destroy" the object without freeing it's memory. This is a rather unusual case, and not something you should do unless you are REALLY experienced with C++ and you have a VERY good reason to do so. The typical use-case for this is inside the delete operator corresponding to a placement new (where new is called with an already existing memory address to just perform the construction of the object(s)). Again, placement new is pretty much special use of new, and not something you can expect to see much of in normal C++ code.
I don't know about details in Java, but here is what new and new[] do in C++:
Allocate memory
When you have an expression new T or new T(args), the compiler determines which function to call for getting memory
If the type T has an appropriate member operator new that one is called
Otherwise, if the user provided an appropriate global operator new that one is called.
If operator new cannot allocate the requested memory, then it calls a new handler function, which you can set with set_new_handler. That function may free some space so the allocation can succeed, it may terminate the program, or it may throw an exception of type std::bad_alloc or derived from that. The default new handler just throws std::bad_alloc.
The same happens for new T[n] except that operator new[] is called for memory allocation.
Construct the object resp. objects in the newly allocated memory.
For new T(args) the corresponding constructor of the object is called. If the constructor throws an exception, the memory is deallocated by calling the corresponding operator delete (which can be found in the same places as operator new)
For new T it depends if T is POD (i.e. a built-in type or basically a C struct/union) or not. If T is POD, nothing happens, otherwise it is treated like new T().
For new T[n] it also depends on whether T is POD. Again, PODs are not initialized. For non-PODs the default constructor is in turn called for each of the objects in order. If one object's default constructor throws, no further constructors are called, but the already constructed objects (which doesn't include the one whose constructor just threw) are destructed (i.e. have the destructor called) in reverse order. Then the memory is deallocated with the appropriate operator delete[].
Returns a pointer to the newly created object(s). Note that for new[] the pointer will likely not point to the beginning of the allocated memory because there will likely be some information about the number of allocated objects preceding the constructed objects, which is used by delete[] to figure out how many objects to destruct.
In all cases, the objects live until they are destroyed with delete ptr (for objects allocated with normal new) or delete[] ptr (for objects created with array new T[n]). Unless added with a third-party library, there's no garbage collection in C++.
Note that you also can call operator new and operator delete directly to allocate raw memory. The same is true for operator new[] and operator delete[]. However note that even for those low-level functions you may not mix the calls, e.g. by deallocating memory with operator delete that you allocated with operator new[].
You can also copnstruct an object in allocated memory (no matter how you got that) with the so-called placement new. This is done by giving the pointer to the raw memory as argument to new, like this: new(pMem) T(args). To destruct such an explicitly constructed object, you can call the object's destructor directly, p->~T().
Placement new works by calling an operator new which takes the pointer as additional argument and just returns it. This same mechanism can also be used to provide other information to operator new overloads which take corresponding additional arguments. However while you can define corresponding operator delete, those are only used for cleaning up when an object throws an exception during construction. There's no "placement delete" syntax.
One other use of the placement new syntax which is already provided by C++ is nothrow new. That one takes an additional parameter std::nothrow and differs from normal new only in that it returns a null pointer if allocation fails.
Also note that new is not the only memory management mechanism in C++. On the one hand, there are the C functions malloc and free. While usually operator new and operator new[] just call malloc, this is not guaranteed. Therefore you may not mix those forms (e.g. by calling free on a pointer pointing to memory allocated with operator new). On the other hand, STL containers handle their allocations through allocators, which are objects which manage the allocation/deallocation of objects as well as construction/destruction of objects in containers.
And finally, there are those objects whose lifetime is controlled directly by the language, namely those of static and automatic lifetime. Automatic lifetime objects are allocated by simply defining a variable of the type at local scope. They are automatically created when execution passes that line, and automatically destroyed when execution leaves the scope (including it the scope is left through an exception). Static lifetime objects are define at global/namespace scope or at local scope using the keyword static. They are created at program startup (global/namespace scope) or when their definition line is forst executed (local scope), and they live until the end of the program, when they are automatically destroyed in reverse order of construction.
Generally, automatic or static variables are to be preferred to dynamic allocation (i,e, everything you allocate with new or allocators), because there the compiler cares for proper destruction, unlike dynamic allocation where you have to do that on your own. If you have dynamically allocated objects, it's desirable to have their lifetime managed by automatic/static objects (containers, smart pointers) for the same reason.
You seem to have the operation of new correct in that it allocates and initializes memory.
Once the new completes successfully, you, the programmer, are responsible for deleteing that memory. The best way to make sure that this happens is to never use new directly yourself, instead preferring standard containers and algorithms, and stack-based objects. But if you do need to allocate memory, the C++ idiom is to use a smart pointer like unique_ptr from C++11 or shared_ptr from boost or C++11. That makes sure that the memory is reclaimed properly.
If an allocation fails, the new call will throw an exception after cleaning up any portion of the object that has been constructed prior to the failure. You can use the (nothrow) version of new to return a null pointer instead of throwing an exception, but that places even more burden of cleanup onto the client code.
The new keyword
The new operator is somewhat similar in the two languages. The main difference is that every object and array must be allocated via new in Java. (And indeed arrays are actually objects in Java.) So whilst the following is legal in C/C++ and would allocate the array from the stack...
// C/C++ : allocate array from the stack
void myFunction() {
int x[2];
x[0] = 1;
...
}
...in Java, we would have to write the following:
// Java : have to use 'new'; JVM allocates
// memory where it chooses.
void myFunction() {
int[] x = new int[2];
...
}
ref:https://www.javamex.com/java_equivalents/new.shtml

Categories