27

Code example:

public class StringHolder{
    public static final String ONE = "ONE";
    public static final String TWO = "TWO";
    public static final String THREE = "THREE";

    public static void main (String[] args){
        String someVariable = ONE + TWO + THREE;
    }
}

How I can evaluate String value from static constants?. For example, with Intellij Idea I can run program in debug, put break point, press "ctrl+alt+f8" on the expression and see expression value. So is that possible to evaluated this with static analyzer with out compile code and run program? The key point is the value calculated from static constants not from function parameter, so analyzer just "go" to the constant value, concatenate them and show me value in pop-up window.

Another situation when I have a block and "just initialized" variables:

{
    final String a = "a";
    final String b = "b"
    final String c = "c"
    String result = a+b+c;
}

P.S. Did you understand me? :)

1
  • See it where? Your question is incomplete.
    – Perception
    Commented Mar 11, 2013 at 9:44

3 Answers 3

39

It is easy with intellij idea 14:

  1. just put cursor on the string concatenation
  2. Press alt + enter
  3. Select "Copy String concatenation text into clipboard"
  4. Paste result somewhere.
2
  • 1
    thanks, be aware that you can only use final variables and literals. Otherwise, you'll get ? as value Commented Jun 30, 2017 at 14:45
  • Thanks. Useful shortcut. Note that in a very rare cases the concatenation is not true. For example String text = 'A' + 1 + ""; this shortcut will copy to clipboard "A1" instead of the real value of text (66). IntelliJ version 2016.3
    – elirandav
    Commented Jan 28, 2018 at 22:30
4

You would be able to see the compile-time concatenated string "ONETWOTHREE" by decompiling the bytecode:

javap -c StringHolder

and looking at the first assignment.

The concatenation for first + second + third will still be done at execution time rather than compile-time, so I'd expect to see code using StringBuilder or StringBuffer, and there'll be no "result" of that string concatenation without running the code.

-1
public static final String ONE = "ONE";
public static final String TWO = "TWO";
public static final String THREE = "THREE";

are compile time constants and will be inlined during compile time.

So you can see the result in the .class file generated by decompiling. The other one result will not be visible until runtime.

For someVariable you will see something like someVariable = "ONETWOTHREE"; in the decompiled code. The compiler does this for optimization so is visible.

1
  • They will not be inlined. They will be pooled, which is exactly the opposite.
    – user207421
    Commented Oct 4, 2019 at 0:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.