26

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? :)

Cherry
  • 31,309
  • 66
  • 224
  • 364

3 Answers3

38

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.
agnul
  • 12,608
  • 14
  • 63
  • 85
Cherry
  • 31,309
  • 66
  • 224
  • 364
  • 1
    thanks, be aware that you can only use final variables and literals. Otherwise, you'll get ? as value – Daniel Pinyol Jun 30 '17 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 Jan 28 '18 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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
-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.

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120