jocelyn_hamilton
jocelyn_hamilton 7d ago โ€ข 0 views

Java Array Examples: Declaring and Initializing with Primitive Types

Hey there! ๐Ÿ‘‹ Let's dive into Java arrays with primitive types. This guide and quiz will help you understand how to declare and initialize them like a pro! ๐Ÿง‘โ€๐Ÿซ
๐Ÿ’ป Computer Science & Technology

1 Answers

โœ… Best Answer

๐Ÿ“š Quick Study Guide

  • ๐Ÿ” An array is a collection of elements of the same type stored in contiguous memory locations.
  • ๐Ÿ’ก In Java, arrays are objects.
  • ๐Ÿ“ Primitive types in Java include `int`, `char`, `boolean`, `byte`, `short`, `long`, `float`, and `double`.
  • ๐Ÿ”ข To declare an array, use the syntax: `dataType[] arrayName;` or `dataType arrayName[];`
  • ๐Ÿ”จ To initialize an array, you can use: `arrayName = new dataType[arraySize];`
  • ๐Ÿงฎ You can also declare and initialize in one line: `dataType[] arrayName = {value1, value2, ...};`
  • โฑ๏ธ Array indices start at 0 and go up to arraySize - 1.

Practice Quiz

  1. Question 1: Which of the following is the correct way to declare an integer array named `numbers` in Java?
    1. int numbers;
    2. array numbers int;
    3. int[] numbers;
    4. numbers int[];
  2. Question 2: How do you initialize an integer array named `values` with a size of 5?
    1. int[] values = {1, 2, 3, 4, 5};
    2. int[] values = new int[5];
    3. int values = new int[5];
    4. int[5] values = new int[];
  3. Question 3: What is the index of the first element in an array?
    1. 1
    2. -1
    3. 0
    4. The size of the array
  4. Question 4: Which of the following is the correct way to declare and initialize a character array with the values 'a', 'b', and 'c'?
    1. char[] letters = {'a', 'b', 'c'};
    2. char letters[] = ("a", "b", "c");
    3. char[] letters = new char[3]; letters = {'a', 'b', 'c'};
    4. char letters = {'a', 'b', 'c'};
  5. Question 5: What is the default value of elements in an integer array after initialization with `new int[size]`?
    1. 1
    2. -1
    3. null
    4. 0
  6. Question 6: How can you find the length (number of elements) of an array named `myArray`?
    1. myArray.length()
    2. length(myArray)
    3. myArray.size()
    4. myArray.length
  7. Question 7: Which of the following is NOT a primitive data type in Java?
    1. int
    2. boolean
    3. String
    4. double
Click to see Answers
  1. C
  2. B
  3. C
  4. A
  5. D
  6. D
  7. C

Join the discussion

Please log in to post your answer.

Log In

Earn 2 Points for answering. If your answer is selected as the best, you'll get +20 Points! ๐Ÿš€