Objects in java

  • Thread starter prasoonthegreat
  • Start date
P

prasoonthegreat

I am a beginner to java.....

My question is ......Can objects in java only be created
dynamically????

Suppose i create an object of the String class

String x="PRASOON";

In this case is the object x of the String class is dynamically
created.....?????

And the other thing .......
Can x in the above case considered as reference to String object or an
object itself........?????
 
Joined
Jun 9, 2009
Messages
5
Reaction score
0
>My question is ......Can objects in java only be created
> dynamically????

Yes, all the object creation are done using the key word 'new'

>String x="PRASOON";
>In this case is the object x of the String class is dynamically
>created.....?????

Yes for the first time, but compiler does a optimisation of creating only one object with value "PRASOON" so that any further initialisation of references with same string value to use this only reference.


>Can x in the above case considered as reference to String object or an
object itself........?????

x is is only a reference to string object and not a value it self.

Regards,
Raja Nagendra Kumar,
C.T.O
tejasoft.com
-Java Product Development, Refactoring and Unit Testing Specialists
 
P

prasoonthegreat

The following responses all apply:
1. Yes.
2. No.
3. Possibly.
4. The question makes no sense.

In more details: Java source code expresses instructions which
manipulates objects. The source code is processed by the Java compiler
which turns it into a bunch of class files. The class files are then
given to the Java Virtual Machine, which sets things up so that the
instructions can be executed and find things "initialized". In the code
above, when the program starts up, the String instance (of contents
"PRASOON") already exists; it was created by the JVM when it loaded the
class files.


In Java, values are references: a value (such as the one which is held
in the "x" variable above) points to an instance, but is not the instance
itself. Thus:

   String y = x;

... stores in "y" (another variable) a reference to the same instance.

        --Thomas Pornin

Wat about the first question???

Can objects in java only be created dynamically ....can't we create
objects at compile time?????
 
L

lord.zoltar

Wat about the first question???

Can objects in java only be created dynamically ....can't we create
objects at compile time?????

No. Your program can only create objects when it runs, not when it is
compiled.
 
L

Lew

No. Your program can only create objects when it runs, not when it is
compiled.

Sort of. Constants, namely static final variables pointing to primitives or
Strings, are created at compile time in the class files. They are loaded into
the JVM at class initialization time. This can cause trouble when a constant
is redefined and only the defining class is recompiled. Classes that refer to
the constant also need recompilation when it changes. Otherwise the constant
doesn't change, it remains ... constant.
 
M

Mark Space

Wat about the first question???

Can objects in java only be created dynamically ....can't we create
objects at compile time?????


While Thomas has a point, I think lord zoltar is correct, for the
broadest definitions of "dynamic" and "correct."

Java objects are always created dynamically, even if they are held in a
static reference. For example:

public class Main {
private final static String VERSION = "1.0";

//...
}

contains one static variable "VERSION" which is still created
dynamically at runtime. The string itself is referred to as a "literal"
not static.

Note that primitives usually follow the same pattern:

private final static int COUNT = 20;

I'd call COUNT a static variable, and 20 a literal. Primitives do
approach static creation in their implementation however.
 
L

Lew

While Thomas has a point, I think lord zoltar is correct, for the
broadest definitions of "dynamic" and "correct."

Java objects are always created dynamically, even if they are held in a
static reference.  For example:

public class Main {
   private final static String VERSION = "1.0";

   //...

}

contains one static variable "VERSION" which is still created
dynamically at runtime.  The string itself is referred to as a "literal"
not static.

Since 'VERSION' is a constant, as defined by the JLS, that constant
gets compiled into the class bytecode and is not created as a variable
at runtime, but as a literal.
Note that primitives usually follow the same pattern:

   private final static int COUNT = 20;

I'd call COUNT a static variable, and 20 a literal.  Primitives do
approach static creation in their implementation however.

Likewise. The variable 'COUNT' will not actually exist in the
bytecode but be replaced by its literal.

This is why a class that uses a public static final primitive or
String from another class has to be recompiled after the other class
is recompiled with a new value for the constant.
 
A

Arne Vajhøj

Lew said:
Sort of. Constants, namely static final variables pointing to
primitives or Strings, are created at compile time in the class files.

No. They are not really objects when in the class file.
They are loaded into the JVM at class initialization time.

Yes. Then they become objects.

Arne
 
P

Prasoon

Suppose when we write

int x=5;

The memory is allocated for 'x' at compile time by the compiler or at
the run time by the jvm????
 
J

John B. Matthews

Prasoon said:
Suppose when we write

int x=5;

The memory is allocated for 'x' at compile time by the compiler or at
the run time by the [JVM]?

Let's see:

$ cat Allocate.java ; javac Allocate.java ; javap -c Allocate
public class Allocate {
public static void main(String[] args) {
int x = 5;
}
}
Compiled from "Allocate.java"
public class Allocate extends java.lang.Object{
public Allocate();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static void main(java.lang.String[]);
Code:
0: iconst_5
1: istore_1
2: return

}

I don't see any memory allocated "for 'x' at compile time." At run time,
the literal integer constant 5, whose size was known at compile time, is
stored in the 1st local variable of method main(). See section 3.11:

<http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html>
 
P

Prasoon

At run time,
So while creating objects (using new) is the size of an object known
at compile time or it is also decide at run time...

In C++ new is used to create objects (allocate memory) at run-time and
that even holds for primitive data types but in java everytime the
memory is allocated at run time (for objects as well for primitive
data types) so why is "new" needed in JAVA???
 
J

John B. Matthews

Prasoon said:
So while creating objects (using new) is the size of an object known
at compile time or it is also decide at run time.

I don't understand your inference: the integer constant 5 is not an
object, it's a constant.
In C++ new is used to create objects (allocate memory) at run-time
and that even holds for primitive data types but in [J]ava everytime
the memory is allocated at run time (for objects as well for
primitive data types) so why is "new" needed in [Java]?

In Java, the keyword "new" signifies the instantiation of a class by
invoking the appropriate constructor. Absent an explicit call to the
superclass constructor, the compiler implicitly calls the parent's
constructor, super(). The process is recursive, ending with the class
Object, which has no superclass. Appropriate initialization takes place
at each level. The effect is seen in the example above: Allocate has no
constructor; it implicitly extends Object; Object's constructor is called
implicitly.

More on initialization may be found here:

<http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.5>
 
L

Lew

Prasoon said:
So while creating objects (using new) is the size of an object known
at compile time or it is also decide at run time...

Run time.

Only one period is needed to signify a declarative sentence.
In C++ new is used to create objects (allocate memory) at run-time and
that even holds for primitive data types but in java [sic] everytime the
memory is allocated at run time (for objects as well for primitive
data types) so why is "new" needed in JAVA [sic]??? [sic]

Only one question mark is needed to signify an interrogative sentence.

The keyword "new" signifies invocation of a constructor rather than a method.
 
M

markspace

Prasoon said:
So while creating objects (using new) is the size of an object known
at compile time or it is also decide at run time...

Both.

Object o = new Object(); // known at compile time
int[] arr = new int[aSize]; // depends on int value "aSize"
In C++ new is used to create objects (allocate memory) at run-time and

"New" is used for the same thing in Java.
that even holds for primitive data types

Not really. I don't think you can "new" an int, for example. I don't
recall primitives in C++ being first class objects. You can malloc
memory the size of an int in C++, sure, but direct allocation of memory
buffers is something Java tries to avoid.
but in java everytime the
memory is allocated at run time

No, not for primitives.
(for objects as well for primitive
data types) so why is "new" needed in JAVA???


The same reason it's used in C++. Using "malloc" would be really ugly.

There maybe a few cases in Java where the compiler literally could not
distinguish memory allocation from other syntax:

Arrays.toString( new int[10] );

Might be a little rough if the "new" weren't there.

Also, constructors in Java are effectively static methods. You don't
need an object to call them, for example. A syntax like:

Object o = Object.Object(); // ugh

seems clumsier than than just using "new Object()," at least to me.
 
R

Roedy Green

The memory is allocated for 'x' at compile time by the compiler or at
the run time by the jvm????

for a local variable the slot on the stack in allocated by the
compiler, but he space itself is allocated at run time.

For a field, the index is assigned by the compiler, but the memory
itself is allocated at run time.

To understand this more deeply you need to understand a bit about how
byte code works.

see http://mindprod.com/jgloss/jasm.html
http://mindprod.com/jgloss/jvm.html
--
Roedy Green Canadian Mind Products
http://mindprod.com

"Out of 135 criminals, including robbers and rapists, 118 admitted that when they were children they burned, hanged and stabbed domestic animals."
~ Ogonyok Magazine 1979.
 
E

Eric Sosman

Roedy said:
for a local variable the slot on the stack in allocated by the
compiler, but he space itself is allocated at run time.

For a field, the index is assigned by the compiler, but the memory
itself is allocated at run time.

To understand this more deeply you need to understand a bit about how
byte code works.

see http://mindprod.com/jgloss/jasm.html
http://mindprod.com/jgloss/jvm.html

It seems to me that the O.P. has asked a nebulous question
because he has not yet understood Java's execution model. The
missing link (I think) is that there's no "link" in Java, no
pre-execution phase that gathers together all the components
of a program, resolves references, assigns addresses, and so on.
Java's execution is entirely dynamic (well, after a little
indispensable kernel of bootstrap, perhaps): The JVM is told the
name of a class it is to run, loads that class, finds its main()
method, and calls it. That main() method in turn refers to other
classes, and the JVM loads them as needed -- and only *if* needed.
It's all demand-driven; only the essential classes that the JVM
itself requires to come to life are preordained.

... which means that essentially *all* memory is allocated
at run-time. Static fields are allocated when the JVM finds it
necessary to load their classes, and deallocated when and if the
JVM decides to allow the garbage collector to reclaim the classes.
Instance variables are allocated when the program does a `new',
and deallocated when and if the GC reclaims their objects. Method
variables (warning: loose language) are allocated when the method
is called (loose language) and deallocated when the method
terminates. *Everything* is a run-time allocation of one kind
or another.

(Methinks the O.P. has some other misconceptions about Java,
too, as witness his use of an `int' to exemplify an object.)
 
R

RedGrittyBrick

markspace said:
....
constructors in Java are effectively static methods. You don't
need an object to call them, for example. A syntax like:

Object o = Object.Object(); // ugh

seems clumsier than than just using "new Object()," at least to me.

Some languages have the equivalent of
Object o = Object.new();

instead of
Object o = new Object();

I don't feel there's a huge difference between those two.
 
R

Roedy Green

(Methinks the O.P. has some other misconceptions about Java,
too, as witness his use of an `int' to exemplify an object.)

Java makes a lot more sense once you understand the class structure
and the way the byte code machine works. OP would sounds like the he
would enjoy reading one of the books about it. Some people, myself
included, find it very difficult to use a black box, without at least
some model of how it works inside. Once I have a models, huge amounts
of trivia become obvious consequences of the model. Then I only have
to memorise the exceptions.

--
Roedy Green Canadian Mind Products
http://mindprod.com

"Out of 135 criminals, including robbers and rapists, 118 admitted that when they were children they burned, hanged and stabbed domestic animals."
~ Ogonyok Magazine 1979.
 
E

Eric Sosman

Roedy said:
(Methinks the O.P. has some other misconceptions about Java,
too, as witness his use of an `int' to exemplify an object.)

Java makes a lot more sense once you understand the class structure
and the way the byte code machine works. [...]

I guess the choice is whether to learn Java on its own
terms, or to learn it by fitting (forcing?) it into another
already-known framework.

Someone who has written programs in a dozen or fifteen
languages, ranging from assemblers through interpreters to
Fortran and C and Lisp and beyond, may well find a useful
shortcut to understanding Java by studying how Java executes,
noting that different byte codes are used to manipulate
primitives, to invoke static methods, to invoke virtual
methods, and so on. There is nothing wrong, as far as I can
see, with taking such a shortcut.

But Java -- pretty much any full-fledged programming
language, for that matter -- ought also to be understandable
on its own terms, without reference (or without too much
reference) to the implementation techniques that bridge the
gap between the language and the silicon. Putting it perhaps
a little too simplistically, one ought to be able to learn
Java from the JLS without the JVMS. If the learner does not
already have a (fairly extensive) store of prior experience,
appealing to the implementation techniques rather than to Java
itself is not likely to be a shortcut. Rather, it's going to
be more like the trip around Robin Hood's Barn: circuitous,
wearying, and lacking central focus.

It seems to me, reading between the lines of his questions,
that the O.P. is a relative newcomer to programming, and is
unlikely to possess an accumulated store of experience with
which to form useful analogies. I'd therefore encourage him
to approach Java as Java, just as I'd encourage him to approach
Algol as Algol or Scheme as Scheme, and to leave questions of
"Yes, but *how*?" for another day.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top