0

I have below multiple variables.

JSONObject one = new JSONObject();
JSONObject two = new JSONObject();
JSONObject three = new JSONObject();

I tried below way

JSONObject one, two, three;
one = two = three = new JSONObject();

It is giving error when I am trying to write on those objects.

[UPDATE]

    JSONObject one = null, two = null , three = null ;
    one = two = three = new JSONObject();
    
    one.put("test", 1);
4
  • 1
    There is no way in Java Commented Aug 7, 2020 at 9:57
  • Really @NikolaiShevchenko. There is no way? I can't believe. Commented Aug 7, 2020 at 9:59
  • Perhaps you should say what error you are getting. Commented Aug 7, 2020 at 10:04
  • JSONObject one = null, two = null , three = null ; Note that the java compiler will initialize the variables to null. Explicitly initializing them to null actually adds more operations because you are initializing each variable twice. What is the motivation behind your question? Are you trying to save two lines of source code? Commented Aug 7, 2020 at 10:13

2 Answers 2

2

According to your [UPDATE] section you can do like this:

JSONObject one = null, two = null, three = null;
Stream.of(one, two, three).forEach(it -> it = new JSONObject());

But it's still not a single-statement initialization.

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

1 Comment

@Abra, no you are wrong. code.sololearn.com/cVRUy2BwauK8/#java
1

It depends on what you want to achieve. The code you posted yourself works.

one = two = three = new JSONObject();

However, you need to keep in mind that it creates only 1 object and assigns it to 3 different variable. If that object is mutable then you need to be careful. It is basicly equal to this:

JSONObject one = new JSONObject();
JSONObject two = one;
JSONObject three = two;

If you want to create 3 different objects and assign it to 3 different variable then it is not possible.

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.