4

I am not able to assign a String variable to a String Array. My code is :

//Declaring a String array 
public String [] fileWrite = new String [10]; 

//assigning a variable 

String value = String.valueOf(aChar1);
fileWrite[0] = value;

But when I try to print the array, it gives null. I checked the value of variable value but that is ok. I cant understand the reason of array being null.

2
  • 2
    I fear that too much information is missing here. Please show how you print the array, and tell us just what aChar1 is. Commented May 16, 2012 at 18:55
  • Can you provide a short, complete, compilable example program that ehibits your issue? Commented May 16, 2012 at 18:55

4 Answers 4

6

Firstly, you need to know that "printing an array" in java is somewhat "broken": You need to use Arrays.toString(array) to print an array (you can't rely on array.toString() - it isn't useful).

Try this code:

public static void main(String[] args) {
    String[] fileWrite = new String[10];
    char aChar1 = 'x';
    String value = String.valueOf(aChar1);
    fileWrite[0] = value;
    System.out.println(Arrays.toString(fileWrite));
}

Output:

[x, null, null, null, null, null, null, null, null, null]
Sign up to request clarification or add additional context in comments.

Comments

1
public String[] fileWrite = new String[10];
fileWrite[0] = aChar1 + "";

Try this

1 Comment

What could this possibly do to help?
0

The assign is correct. Maybe the variable aChar1 is null or the string "null"

Comments

0

To assign a variable to an array try

    String[] fileWrite = new String[10];
    Arrays.fill(fileWrite, aChar1);
    System.out.println(Arrays.toString(fileWrite));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.