Reputation: 549
my question is if intern is working with string and string having a SPC(string pool constant) for it and intern concept also working with integer also, so is there any integer pool constant?if not then how its working?
class InternExample
{
public void print()
{
Integer i=10;
Integer j=10;
String c="a";
String s="a";
System.out.println(i==j);// prints true
System.out.println(c==s);//prints true
}
public static void main(String args[])
{
new InternExample().print();
}
}
Upvotes: 1
Views: 821
Reputation: 5321
Beware of your "equality assumptions". For example, with integers:
Integer a = 69;
Integer b = 69;
System.out.println(a == b); // prints true
Integer c = 1000;
Integer d = 1000;
System.out.println(c == d); // prints false
This is due to the internal implementation of Integer, having pre-existing objects for integer for small values (from -127 to 128 i think). However, for bigger integers, a distinct object Integer will be created each time.
Same goes for your Strings, literal strings in your source code will all be linked to the same object by the compiler ...he's smart enough to do that. However, when you'll read a string from a file, or create/manipulate some string at runtime, they will not be equal anymore.
String a = "x";
String b = "x";
String c = new String("x");
System.out.println(a == b); // prints true
System.out.println(a == c); // prints false
Upvotes: 4
Reputation: 63688
Added to @Joachim Sauer's answer, we can change the upper bound cache value.
Some of the options are
Link : Java Specialist
Upvotes: 7
Reputation: 308001
Auto-boxing uses a cache of common values, as defined in § 5.1.7 Boxing Conversion of the JLS:
If the value
p
being boxed istrue
,false
, abyte
, achar
in the range\u0000
to\u007f
, or anint
orshort
number between -128 and 127, then letr1
andr2
be the results of any two boxing conversions ofp
. It is always the case thatr1 == r2
.
Note that this is not called "interning", however. That term is only used for what is done to String
literals and what can explicitly be done using String.intern()
.
Upvotes: 5