[java] How to print multiple variable lines in Java

I'm trying to print the test data used in webdriver test inside a print line in Java

I need to print multiple variables used in a class inside a system.out.print function (printf/println/whatever).

public String firstname;
public String lastname;

firstname = "First " + genData.generateRandomAlphaNumeric(10);
driver.findElement(By.id("firstname")).sendKeys(firstname);

lastname = "Last " + genData.generateRandomAlphaNumeric(10);
driver.findElement(By.id("lastname")).sendKeys(lastname);

I need those print in a print statement as:
First name: (the variable value I used)
Last name: (the variable value I used)

Using something like below gives the exact result.
But I need to reduce the number of printf lines and use a more efficient way.

System.out.printf("First Name: ", firstname);
System.out.printf("Last Name: ", lastname);

Thanks!

This question is related to java printf println

The answer is


System.out.println("First Name: " + firstname);
System.out.println("Last Name: " + lastname);

or

System.out.println(String.format("First Name: %s", firstname));
System.out.println(String.format("Last Name: %s", lastname));

Or try this one:

System.out.println("First Name: " + firstname + " Last Name: "+ lastname +".");

Good luck!


You can create Class Person with fields firstName and lastName and define method toString(). Here I created a util method which returns String presentation of a Person object.

This is a sample

Main

public class Main {

    public static void main(String[] args) {
        Person person = generatePerson();
        String personStr = personToString(person);
        System.out.println(personStr);
    }

    private static Person generatePerson() {
        String firstName = "firstName";//generateFirstName();
        String lastName = "lastName";//generateLastName;
        return new Person(firstName, lastName);
    }

    /*
     You can even put this method into a separate util class.
    */
    private static String personToString(Person person) {
        return person.getFirstName() + "\n" + person.getLastName();
    }
}

Person

public class Person {

    private String firstName;
    private String lastName;

    //getters, setters, constructors.
}

I prefer a separate util method to toString(), because toString() is used for debug. https://stackoverflow.com/a/3615741/4587961

I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.


Suppose we have variable date , month and year then we can write it in the java like this.

int date=15,month=4,year=2016;
System.out.println(date+ "/"+month+"/"+year);

output of this will be like below:

15/4/2016