gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
How to store intergers and strings in an array java
- User
How to store intergers and strings in an array java
- Assistant
To store integers and strings in an array in Java, you can create an array that is capable of storing both types of data using the Object data type.
Here is an example code snippet that demonstrates how to do this:
// Create an array to store integers and strings Object[] arr = new Object[5]; // Assign values to the array arr[0] = 123; // Integer arr[1] = "hello"; // String arr[2] = 456; // Integer arr[3] = null; // Null value arr[4] = "world"; // String // Access the values in the array System.out.println(arr[0]); // Output: 123 System.out.println(arr[1]); // Output: hello System.out.println(arr[2]); // Output: 456 System.out.println(arr[3]); // Output: null System.out.println(arr[4]); // Output: worldAs you can see, the array is created using the Object data type so it can store both integers and strings. The values are assigned to the array using the index notation, and the values can be accessed using the same notation.