dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Apr 28, 2021

Initializing Multiple Variables in Java

How to Initialize Multiple Variables in Java

This Java tip and tutorial shows you how to initialize multiple variables all at once versus one at a time. Includes code samples using the Java programming language.

While declaring multiple variables all in one go is technically possible using Java, most developers tend to frown upon the act, as it goes against the philosophy of having your program and code being “visually simple”and is against normal Java programming conventions.

Still, there may be times when you wish to initialize multiple variables, so I have provided some sample code below that will help you achieve this goal.

Java Code Sample for Multiple Variables:

*/

public class InitialisingMultipleVars {
    public static void main(String []args)
    {
        Object firstObj = null;
        Object secondObj = null;

        System.out.println("Before initializing...");
        System.out.println("firstObj: " + firstObj);
        System.out.println("secondObj: " + secondObj);
        
        firstObj = secondObj = new String("Hello");
        
        System.out.println("\nPost initializing...");
        System.out.println("firstObj: " + firstObj);
        System.out.println("secondObj: " + secondObj);
    }
}

/*

The following is the output for our Java code showing the initialization of multiple variables:

$java InitialisingMultipleVars
Before initializing...
firstObj: null
secondObj: null

Post initializing...
firstObj: Hello
secondObj: Hello

*/
MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date