2

I've come across this piece of code in Java and I thought this wouldn't compile since variables a and s are not declared. Not only it compiles but also runs successfully and it prints "5". What am I missing here ?

public static void main(String[] args) {
     int j=5;
     long h = j++, s, a;
     System.out.println(h); 
 }
ernest_k
  • 44,416
  • 5
  • 53
  • 99
svs
  • 21
  • 1
  • 1
    You can declare multiple variables of the same type by separating their identifiers with a comma. Take a look at this: [Initializing multiple variables to the same value in Java](https://stackoverflow.com/questions/6202818/initializing-multiple-variables-to-the-same-value-in-java/31910261) – ernest_k Mar 15 '20 at 09:15
  • 2
    The line `long h = j++, s, a;` declares three variables: `h`, `s` and `a`. – Sweeper Mar 15 '20 at 09:22
  • Thanks , I'm assuming they are of type long . but what is the purpose of using this type of declaration , is it the same as (long s; , long a;)? , if yes then is it done to minimize length of code ? – svs Mar 15 '20 at 09:28
  • 1
    It's a rarely used syntax that you shouldn't pay too much attention to. You should usually define variables on their own lines, it's a lot clearer that way. – Kayaman Mar 15 '20 at 09:39

0 Answers0