about intern in java
Asked Answered
S

3

1

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();  
}  
}
Scaleboard answered 1/6, 2011 at 9:40 Comment(2)
read this devx.com/tips/Tip/42276 for IntegerNegatron
Loosely related: here's a nasty exploit of auto-boxing in Java, studying it may help you understand auto-boxing better: thedailywtf.com/Articles/Disgruntled-Bomb-Java-Edition.aspxAmylaceous
G
7

Added to @Joachim Sauer's answer, we can change the upper bound cache value.

Some of the options are

  1. -Djava.lang.Integer.IntegerCache.high=value
  2. -XX:AutoBoxCacheMax=value
  3. -XX:+AggressiveOpts

Link : Java Specialist

Gehring answered 1/6, 2011 at 9:53 Comment(0)
M
5

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 is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == 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().

Motionless answered 1/6, 2011 at 9:47 Comment(0)
H
4

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
Homochromatic answered 1/6, 2011 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.