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…

  1. A.

    p and q are integers.

  2. B.

    p and q are arrays.

  3. C.

    p is int variable and q is int array.

  4. 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

  1. In int r[], p;, the shared type is int. The [] after r applies only to r, while p has no bracket suffix; therefore p has type int.

  2. In int[] t, q;, [] is part of the shared type before the declarator list. It applies to both t and q; therefore q has type int[].

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.

Explore the full course: Uppsc Computer Operator Grade B

Loading lesson…