How can I separate a string in Java from full name to last name, first name?

How would you take a string that you have input from the keyboard and rearrange it? For example, in my case I am asking the user to import a person’s name in “last name, first name” format. I then have to change that to “first name last name”.

Here is what I have so far:

private void setName() {
    Scanner in = new Scanner(;
    System.out.println("Please enter the last name followed by the first name of" +
            "a student: ");
    name = in.nextLine();


A simple solution would be to ask for each name separately, using two calls to Scanner’s nextLine() function.

import java.util.Scanner;

public class FirstNameLastName {
    public static void main(String[] args) {
        Scanner scan = new Scanner(;
        System.out.println("Please enter the student's last name: ");
        String lastName = scan.nextLine();

        System.out.println("Please enter the student's first name: ");
        String firstName = scan.nextLine();

        System.out.println("Hello, " + firstName + " " + lastName);

Leave a Reply

Your email address will not be published. Required fields are marked *