Hi all,

I am very new to Java Programming and am currently trying to write a program to return the last character of a string, entered by the user.

So far I have this:

import java.util.Scanner;

public class lastString
	public static void main (String[] args)
		String string1;
		Scanner keyboard = new Scanner (System.in);
		System.out.print("Enter a String: ");
		string1 = keyboard.nextLine(); 
		System.out.println("String Length = ");
		System.out.println("The last Character is:");


I understand you have to use the length() and charAT methods, but do not know how to return only the last character. (Currently the program returns the first character).

Thanks for looking :)

7 Years
Discussion Span
Last Post by EmbeddedHelp

Well, string1.length returns the length of the string yes?
lets say you enter: hello
The length is 5(there are 5 letters). But, if you count the number of letters starting from 0, you get: 0,1,2,3,4... As you can see, even though there are 5 numbers here, the last number is 4. Therefore, the last letter will be at position string1.length()-1.
i.e. 5-1..which is 4!

So, using the same method you are trying to use, replace position 0 with the string1.length()-1.

Edited by Akill10: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.