I am new to java (previously only worked with sql) and I am attempting to set a length limit for my string variable. Basically I have a username field that can only be 6 characters long.

I am trying the following:

private String username (6);

I am assuming this is not the correct format. Does anyone know how i can do this in java correctly?


Some other answers have claimed that "There is no way to limit Strings in java to a certain finite number through inbuilt features", and suggested rolling ones own. However, Java EE validations API is meant for just this. An example:

import javax.validation.constraints.Size;

public class Person {
      @Size(max = 6)
      private String username;
}

Further info on how to use Validation API, see this thread for example. Hibernate validator is the reference implementation (usage).

In short, when annotating an object as @Valid, validations done in annotations will be enforced.


What you suggested is not the correct way to do what you want. Try using:

private int stringLimit = 6;
// Take input from user
private String username = inputString.substring(0,stringLimit);

For example:

inputString = "joelspolsky";
private String username = inputString.substring(0,stringLimit);
// username is "joelsp"

There is no way to limit Strings in java to a certain finite number through inbuilt features. Strings are immutable and take the value that you provide in their constructor. You will need to write code manually to do this.

Use the length() function to determine the length of the String and do not allow lengths greater than 6.

if( username.length() > 6 )
{
    throw new RuntimeException("User name too long");
}

One of the options you have is to throw an exception and then handle it elsewhere. Or you can display an alert to the user immediately after you encounter the problem.


You can try soemthing like this:Take input from user then validate that string by using following function.

String output ="";
public boolean set(String str, int limit){
      if(str.length() <= limit){
            output= str;
            return true;
      }
      else
        return false;
 }