In Java, what are the types of variables ‘p’ and ‘q’ in the declarations…
2019
In Java, what are the types of variables ‘p’ and ‘q’ in the declarations below?
int r[ ], p;
int [ ] t, q;Answer: C. p is int variable and q is int array. — ConceptIn Java, a variable’s declared type is formed from the type written before the declarator list together with any [] written after that variable’s…
- A.
p and q are integers.
- B.
p and q are arrays.
- C.
p is int variable and q is int array.
- D.
p is int array and q is int variable.
Attempted by 3 students.
Show answer & explanation
Correct answer: C
Concept
In Java, a variable’s declared type is formed from the type written before the declarator list together with any [] written after that variable’s identifier. Brackets in the shared type apply to every variable in that declaration, while brackets after one identifier apply only to that variable.
Application
In
int r[], p;, the shared type isint. The[]afterrapplies only tor, whilephas no bracket suffix; thereforephas typeint.In
int[] t, q;,[]is part of the shared type before the declarator list. It applies to bothtandq; thereforeqhas typeint[].
Cross-check
The first declaration can be rewritten as
int[] r; int p;.The second declaration can be rewritten as
int[] t; int[] q;.
Result
Hence p is an int variable and q is an int[] variable.