java - Declaration of a variable of type String -


this question has answer here:

class demo { string title; private int num; } 

string class, when declare title, treated object or variable? know basic thing, need help. in advance.

title, num, instance variable (sometimes called instance field), because it's part of instance of demo (as opposed static field or class field, part of demo class itself).

variables declared object types string don't directly contain object, unlike ones primitive types int, such num variable. instead, contain reference object, or null if don't contain reference (e.g. don't refer object). instance, in case, title contain null because haven't assigned it. unlike primitive-typed variales num, contain primitive (your num default 0, instance).

so initially, demo, if created instance yo'd have in memory:

 +−−−−−−−−−−−−−−−−−−−+ |  (demo instance)  | +−−−−−−−−−−−−−−−−−−−+ | title: null       | | num: 0            | +−−−−−−−−−−−−−−−−−−−+ 

in constructor or instance method within demo, assign object title, , might assign other value num well:

this.title = "this title"; this.num = 42; 

then, you'd have this:

 +−−−−−−−−−−−−−−−−−−−+ |  (demo instance)  | +−−−−−−−−−−−−−−−−−−−+    +−−−−−−−−−−−−−−−−−−−−−+ | title: <ref1132>  |−−−>|      (string)       | | num: 42           |    +−−−−−−−−−−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−−−−+    | "this title" |                          +−−−−−−−−−−−−−−−−−−−−−+ 

notice title doesn't directly contain string; string exists elsewhere. title refers it. (you can think of object reference number tells jvm object in memory. that's not is, it's useful conceptually.)


i should note string objects, specifically, special in java, couple of reasons:

  • they're 1 of few objects have literal notation ("this string"). create object via new, never strings. see answers this question, this one, , this one.
  • the compiler , jvm work minimize having same string repeated in memory having special handling strings created literals (more generally, constant expression in code; "foo" + "bar" constant expression 2 literals; compiler can [and does] combine them single string). (the compiler puts them in section of class file called "constant pool," , jvm automatically interns them when loading class.) more interning in the spec , this question's answers.

other that, they're objects other objects, differences can confuse people.


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -