user2228777
user2228777

Reputation: 117

Java String Limit

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?

Upvotes: 4

Views: 21705

Answers (7)

Andremoniy
Andremoniy

Reputation: 34920

In this case annotation mechanism can be useful, if, of course, you know what this is.

You can create your own annotation, something like:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MaxLength {
    int value();
}

And use it like:

@MaxLength(6)
private String username;

Then you have to post-process such objects in a special post-processor, which you have to create manually.

Upvotes: 0

Bhargav
Bhargav

Reputation: 425

SubString() won't be suitable for this. If the length of input string is less than limit StringIndexOutOfBoundsException will be thrown. I think you can use StringBuilder for this.

StringBuilder buider = new StringBuilder(username);
builder.setLength(6);
String restName = builder.toString().trim();

Upvotes: 0

ivan
ivan

Reputation: 41

example to cut the length of URL

if (getURLitem.length() >= 15) {
                int stringLimit = 15;
                final String smallURL = getURLitem.substring(0, stringLimit);
                //show short string in textview...

                TextView urlLink = (TextView) findViewById(R.id.url_link);
                urlLink.setText(smallURL);

                // Set On click listener and open URL below
                ...........
            } else {
                //show full string in textview...
                TextView urlLink = (TextView) findViewById(R.id.url_link);
                urlLink.setText(getURLitem);

                // Set On click listener and open URL below
                ...........
            }    

Upvotes: -2

eis
eis

Reputation: 53543

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.

Upvotes: 4

Deepak Bala
Deepak Bala

Reputation: 11185

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.

Upvotes: 2

Achintya Jha
Achintya Jha

Reputation: 12843

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;
 }

Upvotes: 1

stevenelberger
stevenelberger

Reputation: 1368

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"

Upvotes: 1

Related Questions