how to print two variables in same line in java

htt‮p‬s://www.lautturi.com
how to print two variables in same line in java

To print two variables in the same line in Java, you can use the print or printf methods of the PrintStream class, which are part of the System class.

Here is an example of how you can print two variables in the same line in Java:

public class VariablePrinter {
    public static void main(String[] args) {
        int number = 42;
        String message = "Hello, World!";

        System.out.print("The number is " + number + " and the message is " + message);
        System.out.printf("The number is %d and the message is %s", number, message);
    }
}

In this example, the main method declares an integer variable and a string variable and uses the print method and the printf method to print them in the same line. The print method concatenates the variables using the + operator, while the printf method uses placeholders to specify the values to be printed.

This code will print the following output:

The number is 42 and the message is Hello, World!The number is 42 and the message is Hello, World!

The print method prints the argument without a new line, while the printf method allows you to use placeholders to specify the format of the output. You can use these methods to print strings, numbers, and other types of data in the same line.

Keep in mind that this is just one way to print two variables in the same line in Java. You can use different techniques and data structures to achieve the same result, such as using the format method of the String class or the StringJoiner class.

Created Time:2017-11-01 20:42:59  Author:lautturi