Here you can find the source of toShort(String str, short defaultValue)
Convert a String
to an short
, returning a default value if the conversion fails.
Parameter | Description |
---|---|
str | the string to convert, may be null |
defaultValue | the default value |
public static short toShort(String str, short defaultValue)
//package com.java2s; /*// w ww.j a v a 2 s . c om * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class Main { /** * <p> * Convert a <code>String</code> to a <code>short</code>, returning * <code>zero</code> if the conversion fails. * </p> * * <p> * If the string is <code>null</code>, <code>zero</code> is returned. * </p> * * <pre> * NumberUtils.toShort(null) = 0 * NumberUtils.toShort("") = 0 * NumberUtils.toShort("1") = 1 * </pre> * * @param str * the string to convert, may be null * @return the short represented by the string, or <code>zero</code> if * conversion fails * @since 2.5 */ public static short toShort(String str) { return toShort(str, (short) 0); } /** * <p> * Convert a <code>String</code> to an <code>short</code>, returning a * default value if the conversion fails. * </p> * * <p> * If the string is <code>null</code>, the default value is returned. * </p> * * <pre> * NumberUtils.toShort(null, 1) = 1 * NumberUtils.toShort("", 1) = 1 * NumberUtils.toShort("1", 0) = 1 * </pre> * * @param str * the string to convert, may be null * @param defaultValue * the default value * @return the short represented by the string, or the default if conversion * fails * @since 2.5 */ public static short toShort(String str, short defaultValue) { if (str == null) { return defaultValue; } try { return Short.parseShort(str); } catch (NumberFormatException nfe) { return defaultValue; } } }