3

I wish to accomplish:

    String []beef = new String[3];
    beef[0] = "Water";
    beef[1] = "Chicken";
    beef[2] = "Paper";

    String empo = Arrays.toString(beef);

    if (empo.isEmpty()){
        empo = "Nothing";
        System.out.println(empo);
    }else{
        System.out.println(empo);
    }

without having to create the string.


Something like:

    String []beef = new String[3];
    beef[0] = "Water";
    beef[1] = "Chicken";
    beef[2] = "Paper";

    Arrays.toString(beef);  //change beef to just a plain string

    if(beef.isEmpty()||beef==""){
    no = "Nothing";

    System.out.println(beef);

How would one go about doing this?

2
  • You could use a for loop to print each letter in the array in the order it needs to be in. Commented Mar 20, 2013 at 23:09
  • Yea? However, what does that have to do with changing the array type, as per the main intent of my question. Commented Mar 20, 2013 at 23:21

2 Answers 2

8

You can't.

Java is a strongly and statically typed language. That means you have to tell it what type a thing will be when you declare it (strong typing), and you can't ever change it's type after that (static typing).

You will just have to create a new String.

Sign up to request clarification or add additional context in comments.

4 Comments

So, more broadly, can you convert any data type to another without declaring a new variable?
@House no. Java is statically typed.
Is there an example of an un-statically typed programming language or something?
@House Javascript (and it's called "dynamically-typed")
1

You can create substrings with the same backing memory as the original string, but you can't create a string with the same backing memory as an array of strings. They're not stored in the same order so it's impossible to view the same memory both ways.

10 Comments

No you can't. Strings are immutable.
Strings being immutable has nothing to do with it. The documentation for String.substring clearly states "The returned string shares this string's backing array."
But it creates a new String. You can't manipulate a String without making a new one.
The array doesn't go away until it's garbage-collected, and an array of strings and a string aren't stored in the same order in memory, so there's no way to reuse that memory.
Yea...way over my head. I'm just a bit ocd when it comes to java and thus I really like to keep things clean and efficient. By using the least amount of "typage" to do the job, without compromising anything of course. Guess in this case, it was over-optimization haha.
|

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.