Java Tutorial/Data Type/Character Data Type

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

ASCII character handling functions

   <source lang="java">

/*

*  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.
*/

/**

* This class implements some basic ASCII character handling functions.
*
* @author dac@eng.sun.ru
* @author James Todd [gonzo@eng.sun.ru]
*/

public final class Ascii {

   /*
    * Character translation tables.
    */
   private static final byte[] toUpper = new byte[256];
   private static final byte[] toLower = new byte[256];
   /*
    * Character type tables.
    */
   private static final boolean[] isAlpha = new boolean[256];
   private static final boolean[] isUpper = new boolean[256];
   private static final boolean[] isLower = new boolean[256];
   private static final boolean[] isWhite = new boolean[256];
   private static final boolean[] isDigit = new boolean[256];
   /*
    * Initialize character translation and type tables.
    */
   static {
       for (int i = 0; i < 256; i++) {
           toUpper[i] = (byte)i;
           toLower[i] = (byte)i;
       }
       for (int lc = "a"; lc <= "z"; lc++) {
           int uc = lc + "A" - "a";
           toUpper[lc] = (byte)uc;
           toLower[uc] = (byte)lc;
           isAlpha[lc] = true;
           isAlpha[uc] = true;
           isLower[lc] = true;
           isUpper[uc] = true;
       }
       isWhite[ " "] = true;
       isWhite["\t"] = true;
       isWhite["\r"] = true;
       isWhite["\n"] = true;
       isWhite["\f"] = true;
       isWhite["\b"] = true;
       for (int d = "0"; d <= "9"; d++) {
           isDigit[d] = true;
       }
   }
   /**
    * Returns the upper case equivalent of the specified ASCII character.
    */
   public static int toUpper(int c) {
       return toUpper[c & 0xff] & 0xff;
   }
   /**
    * Returns the lower case equivalent of the specified ASCII character.
    */
   public static int toLower(int c) {
       return toLower[c & 0xff] & 0xff;
   }
   /**
    * Returns true if the specified ASCII character is upper or lower case.
    */
   public static boolean isAlpha(int c) {
       return isAlpha[c & 0xff];
   }
   /**
    * Returns true if the specified ASCII character is upper case.
    */
   public static boolean isUpper(int c) {
       return isUpper[c & 0xff];
   }
   /**
    * Returns true if the specified ASCII character is lower case.
    */
   public static boolean isLower(int c) {
       return isLower[c & 0xff];
   }
   /**
    * Returns true if the specified ASCII character is white space.
    */
   public static boolean isWhite(int c) {
       return isWhite[c & 0xff];
   }
   /**
    * Returns true if the specified ASCII character is a digit.
    */
   public static boolean isDigit(int c) {
       return isDigit[c & 0xff];
   }
   /**
    * Parses an unsigned integer from the specified subarray of bytes.
    * @param b the bytes to parse
    * @param off the start offset of the bytes
    * @param len the length of the bytes
    * @exception NumberFormatException if the integer format was invalid
    */
   public static int parseInt(byte[] b, int off, int len)
       throws NumberFormatException
   {
       int c;
       if (b == null || len <= 0 || !isDigit(c = b[off++])) {
           throw new NumberFormatException();
       }
       int n = c - "0";
       while (--len > 0) {
           if (!isDigit(c = b[off++])) {
               throw new NumberFormatException();
           }
           n = n * 10 + c - "0";
       }
       return n;
   }
   public static int parseInt(char[] b, int off, int len)
       throws NumberFormatException
   {
       int c;
       if (b == null || len <= 0 || !isDigit(c = b[off++])) {
           throw new NumberFormatException();
       }
       int n = c - "0";
       while (--len > 0) {
           if (!isDigit(c = b[off++])) {
               throw new NumberFormatException();
           }
           n = n * 10 + c - "0";
       }
       return n;
   }
   /**
    * Parses an unsigned long from the specified subarray of bytes.
    * @param b the bytes to parse
    * @param off the start offset of the bytes
    * @param len the length of the bytes
    * @exception NumberFormatException if the long format was invalid
    */
   public static long parseLong(byte[] b, int off, int len)
       throws NumberFormatException
   {
       int c;
       if (b == null || len <= 0 || !isDigit(c = b[off++])) {
           throw new NumberFormatException();
       }
       long n = c - "0";
       long m;
       
       while (--len > 0) {
           if (!isDigit(c = b[off++])) {
               throw new NumberFormatException();
           }
           m = n * 10 + c - "0";
           if (m < n) {
               // Overflow
               throw new NumberFormatException();
           } else {
               n = m;
           }
       }
       return n;
   }
   public static long parseLong(char[] b, int off, int len)
       throws NumberFormatException
   {
       int c;
       if (b == null || len <= 0 || !isDigit(c = b[off++])) {
           throw new NumberFormatException();
       }
       long n = c - "0";
       long m;
       while (--len > 0) {
           if (!isDigit(c = b[off++])) {
               throw new NumberFormatException();
           }
           m = n * 10 + c - "0";
           if (m < n) {
               // Overflow
               throw new NumberFormatException();
           } else {
               n = m;
           }
       }
       return n;
   }

}</source>





Assign int value to char variable

   <source lang="java">

public class MainClass {

 public static void main(String args[]) {
   char ch1, ch2;
   ch1 = 88; // code for X
   ch2 = "Y";
   System.out.print("ch1 and ch2: ");
   System.out.println(ch1 + " " + ch2);
 }

}</source>



ch1 and ch2: X Y


Character: is Lower Case

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   char symbol = "A";
   if (Character.isLowerCase(symbol)) {
     System.out.println("true");
   }else{
     System.out.println("false");
   }
 }

}</source>



false


Character: is Upper Case

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   char symbol = "A";
   if (Character.isUpperCase(symbol)) {
     System.out.println("true");
   }else{
     System.out.println("false");
   }
 }

}</source>



true


char variables behave like integers

   <source lang="java">

public class MainClass {

 public static void main(String args[]) {
   char ch1;
  
   ch1 = "X";
   System.out.println("ch1 contains " + ch1);
  
   ch1++; // increment ch1
   System.out.println("ch1 is now " + ch1);
 }

}</source>



ch1 contains X
ch1 is now Y


Checks if the string contains only ASCII printable characters.

   <source lang="java">

/*

* 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 {

 /**
  * Checks if the string contains only ASCII printable characters.
  * 
  * null will return false.
  * An empty String ("") will return true.
  * 
*
   * StringUtils.isAsciiPrintable(null)     = false
   * StringUtils.isAsciiPrintable("")       = true
   * StringUtils.isAsciiPrintable(" ")      = true
   * StringUtils.isAsciiPrintable("Ceki")   = true
   * StringUtils.isAsciiPrintable("ab2c")   = true
   * StringUtils.isAsciiPrintable("!ab-c~") = true
   * StringUtils.isAsciiPrintable("\u0020") = true
   * StringUtils.isAsciiPrintable("\u0021") = true
   * StringUtils.isAsciiPrintable("\u007e") = true
   * StringUtils.isAsciiPrintable("\u007f") = false
   * StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
   * 
  *
  * @param str the string to check, may be null
  * @return true if every character is in the range
  *  32 thru 126
  * @since 2.1
  */
 public static boolean isAsciiPrintable(String str) {
     if (str == null) {
         return false;
     }
     int sz = str.length();
     for (int i = 0; i < sz; i++) {
         if (isAsciiPrintable(str.charAt(i)) == false) {
             return false;
         }
     }
     return true;
 }
 
 /**
  * Checks whether the character is ASCII 7 bit printable.
  *
*
   *   CharUtils.isAsciiPrintable("a")  = true
   *   CharUtils.isAsciiPrintable("A")  = true
   *   CharUtils.isAsciiPrintable("3")  = true
   *   CharUtils.isAsciiPrintable("-")  = true
   *   CharUtils.isAsciiPrintable("\n") = false
   *   CharUtils.isAsciiPrintable("©") = false
   * 
  * 
  * @param ch  the character to check
  * @return true if between 32 and 126 inclusive
  */
 public static boolean isAsciiPrintable(char ch) {
     return ch >= 32 && ch < 127;
 }

}</source>





Checks whether the character is ASCII 7 bit.

   <source lang="java">

/**

* 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.
*/

/**

* Operations on char primitives and Character objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/

public class Main {

 //--------------------------------------------------------------------------
 /**
  * Checks whether the character is ASCII 7 bit.
  *
*
   *   CharUtils.isAscii("a")  = true
   *   CharUtils.isAscii("A")  = true
   *   CharUtils.isAscii("3")  = true
   *   CharUtils.isAscii("-")  = true
   *   CharUtils.isAscii("\n") = true
   *   CharUtils.isAscii("©") = false
   * 
  * 
  * @param ch  the character to check
  * @return true if less than 128
  */
 public static boolean isAscii(char ch) {
     return ch < 128;
 }

}</source>





Checks whether the character is ASCII 7 bit alphabetic.

   <source lang="java">

/**

* 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.
*/

/**

* Operations on char primitives and Character objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/

public class Main {

 /**
  * Checks whether the character is ASCII 7 bit alphabetic.
  *
*
   *   CharUtils.isAsciiAlpha("a")  = true
   *   CharUtils.isAsciiAlpha("A")  = true
   *   CharUtils.isAsciiAlpha("3")  = false
   *   CharUtils.isAsciiAlpha("-")  = false
   *   CharUtils.isAsciiAlpha("\n") = false
   *   CharUtils.isAsciiAlpha("©") = false
   * 
  * 
  * @param ch  the character to check
  * @return true if between 65 and 90 or 97 and 122 inclusive
  */
 public static boolean isAsciiAlpha(char ch) {
     return (ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z");
 }

}</source>





Checks whether the character is ASCII 7 bit alphabetic lower case.

   <source lang="java">

/**

* 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.
*/

/**

* Operations on char primitives and Character objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/

public class Main {

 /**
  * Checks whether the character is ASCII 7 bit alphabetic lower case.
  *
*
   *   CharUtils.isAsciiAlphaLower("a")  = true
   *   CharUtils.isAsciiAlphaLower("A")  = false
   *   CharUtils.isAsciiAlphaLower("3")  = false
   *   CharUtils.isAsciiAlphaLower("-")  = false
   *   CharUtils.isAsciiAlphaLower("\n") = false
   *   CharUtils.isAsciiAlphaLower("©") = false
   * 
  * 
  * @param ch  the character to check
  * @return true if between 97 and 122 inclusive
  */
 public static boolean isAsciiAlphaLower(char ch) {
     return ch >= "a" && ch <= "z";
 }

}</source>





Checks whether the character is ASCII 7 bit alphabetic upper case.

   <source lang="java">

/**

* 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.
*/

/**

* Operations on char primitives and Character objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/

public class Main {

 /**
  * Checks whether the character is ASCII 7 bit alphabetic upper case.
  *
*
   *   CharUtils.isAsciiAlphaUpper("a")  = false
   *   CharUtils.isAsciiAlphaUpper("A")  = true
   *   CharUtils.isAsciiAlphaUpper("3")  = false
   *   CharUtils.isAsciiAlphaUpper("-")  = false
   *   CharUtils.isAsciiAlphaUpper("\n") = false
   *   CharUtils.isAsciiAlphaUpper("©") = false
   * 
  * 
  * @param ch  the character to check
  * @return true if between 65 and 90 inclusive
  */
 public static boolean isAsciiAlphaUpper(char ch) {
     return ch >= "A" && ch <= "Z";
 }

}</source>





Checks whether the character is ASCII 7 bit control.

   <source lang="java">

/**

* 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.
*/

/**

* Operations on char primitives and Character objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/

public class Main {

 /**
  * Checks whether the character is ASCII 7 bit control.
  *
*
   *   CharUtils.isAsciiControl("a")  = false
   *   CharUtils.isAsciiControl("A")  = false
   *   CharUtils.isAsciiControl("3")  = false
   *   CharUtils.isAsciiControl("-")  = false
   *   CharUtils.isAsciiControl("\n") = true
   *   CharUtils.isAsciiControl("©") = false
   * 
  * 
  * @param ch  the character to check
  * @return true if less than 32 or equals 127
  */
 public static boolean isAsciiControl(char ch) {
     return ch < 32 || ch == 127;
 }

}</source>





Checks whether the character is ASCII 7 bit numeric.

   <source lang="java">

/**

* 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.
*/

/**

* Operations on char primitives and Character objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/

public class Main {


 /**
  * Checks whether the character is ASCII 7 bit numeric.
  *
*
   *   CharUtils.isAsciiNumeric("a")  = false
   *   CharUtils.isAsciiNumeric("A")  = false
   *   CharUtils.isAsciiNumeric("3")  = true
   *   CharUtils.isAsciiNumeric("-")  = false
   *   CharUtils.isAsciiNumeric("\n") = false
   *   CharUtils.isAsciiNumeric("©") = false
   * 
  * 
  * @param ch  the character to check
  * @return true if between 48 and 57 inclusive
  */
 public static boolean isAsciiNumeric(char ch) {
     return ch >= "0" && ch <= "9";
 }

}</source>





Checks whether the character is ASCII 7 bit numeric and character.

   <source lang="java">

/**

* 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.
*/

/**

* Operations on char primitives and Character objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/

public class Main {


 /**
  * Checks whether the character is ASCII 7 bit numeric and character.
  *
*
   *   CharUtils.isAsciiAlphanumeric("a")  = true
   *   CharUtils.isAsciiAlphanumeric("A")  = true
   *   CharUtils.isAsciiAlphanumeric("3")  = true
   *   CharUtils.isAsciiAlphanumeric("-")  = false
   *   CharUtils.isAsciiAlphanumeric("\n") = false
   *   CharUtils.isAsciiAlphanumeric("©") = false
   * 
  * 
  * @param ch  the character to check
  * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive
  */
 public static boolean isAsciiAlphanumeric(char ch) {
     return (ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z") || (ch >= "0" && ch <= "9");
 }

}</source>





Checks whether the character is ASCII 7 bit printable.

   <source lang="java">

/**

* 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.
*/

/**

* Operations on char primitives and Character objects.
*
* This class tries to handle null input gracefully.
* An exception will not be thrown for a null input.
* Each method documents its behaviour in more detail.
* 
* @author Stephen Colebourne
* @since 2.1
* @version $Id: CharUtils.java 437554 2006-08-28 06:21:41Z bayard $
*/

public class Main {

 /**
  * Checks whether the character is ASCII 7 bit printable.
  *
*
   *   CharUtils.isAsciiPrintable("a")  = true
   *   CharUtils.isAsciiPrintable("A")  = true
   *   CharUtils.isAsciiPrintable("3")  = true
   *   CharUtils.isAsciiPrintable("-")  = true
   *   CharUtils.isAsciiPrintable("\n") = false
   *   CharUtils.isAsciiPrintable("©") = false
   * 
  * 
  * @param ch  the character to check
  * @return true if between 32 and 126 inclusive
  */
 public static boolean isAsciiPrintable(char ch) {
     return ch >= 32 && ch < 127;
 }

}</source>





Compare Two Java char Arrays

   <source lang="java">

import java.util.Arrays; public class Main {

 public static void main(String[] args) {
   char[] a1 = new char[] { "a", "b", "c", "d" };
   char[] a2 = new char[] { "a", "b", "c", "d" };
   System.out.println(Arrays.equals(a1, a2));
 }

}</source>





compare two objects of Character

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

public class CharacterDemo {

 public static void main(String args[]) {
   Character a = new Character("a");
   Character a2 = new Character("a");
   Character b = new Character("b");
   int difference = a.rupareTo(b);
   if (difference == 0) {
     System.out.println("a is equal to b.");
   } else if (difference < 0) {
     System.out.println("a is less than b.");
   } else if (difference > 0) {
     System.out.println("a is greater than b.");
   }
   System.out.println("a is " + ((a.equals(a2)) ? "equal" : "not equal")
       + " to a2.");
   System.out.println("The character " + a.toString() + " is "
       + (Character.isUpperCase(a.charValue()) ? "upper" : "lower") + "case.");
 }

}</source>





Convert character to digit with Character.digit

   <source lang="java">

public class MainClass {

 public static void main(String args[]) {
   System.out.printf( "Convert character to digit: %s\n",
       Character.digit( "2", 1 ) );
 }

}</source>





Convert from ASCII code to String

   <source lang="java">

public class Main {

 public static void main(String[] args) throws Exception {
   int i = 64;
   String aChar = new Character((char) i).toString();
 }

}</source>





Convert from integer to ASCII code (byte)

   <source lang="java">

public class Main {

 public static void main(String[] args) throws Exception {
   char c = "A";
   int i = (int) c; // i == 65 DECIMAL
 }

}</source>





Convert string to char array

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   String literal = "Examples";
   char[] temp = literal.toCharArray();
   for (int i = 0; i < temp.length; i++) {
     System.out.print(temp[i]);
   }
 }

}</source>





Copy char array to string

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   char[] data = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
   String text = String.valueOf(data);
   System.out.println(text);
   text = String.copyValueOf(data, 3, 5);
   System.out.println(text);
 }

}</source>





Count letters in a String

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   String str = "12345";
   int counter = 0;
   for (int i = 0; i < str.length(); i++) {
     if (Character.isLetter(str.charAt(i)))
       counter++;
   }
   System.out.println(counter + " letters.");
 }

} //0 letters.</source>





Demonstrate several Is... methods.

   <source lang="java">

class IsDemo {

 public static void main(String args[]) {
   char a[] = { "a", "b", "5", "?", "A", " " };
   for (int i = 0; i < a.length; i++) {
     if (Character.isDigit(a[i]))
       System.out.println(a[i] + " is a digit.");
     if (Character.isLetter(a[i]))
       System.out.println(a[i] + " is a letter.");
     if (Character.isWhitespace(a[i]))
       System.out.println(a[i] + " is whitespace.");
     if (Character.isUpperCase(a[i]))
       System.out.println(a[i] + " is uppercase.");
     if (Character.isLowerCase(a[i]))
       System.out.println(a[i] + " is lowercase.");
   }
 }

}</source>





Determines if the specified string is permissible as a Java identifier.

   <source lang="java">

/*

* Copyright 2005 Joe Walker
*
* Licensed 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.
*/

import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream;

/**

* @author Joe Walker [joe at getahead dot ltd dot uk]
*/

public class Main {

 /**
  * Determines if the specified string is permissible as a Java identifier.
  * Returns true if the string is non-null, non-zero length with a Java
  * identifier start as the first character and Java identifier parts in all
  * remaining characters.
  * @param test the string to be tested.
  * @return true if the string is a Java identifier, false otherwise.
  * @see java.lang.Character#isJavaIdentifierPart(char)
  * @see java.lang.Character#isJavaIdentifierStart(char)
  */
 public static boolean isJavaIdentifier(String test)
 {
     if (test == null || test.length() == 0)
     {
         return false;
     }
     if (!Character.isJavaIdentifierStart(test.charAt(0)) && test.charAt(0) != "_")
     {
         return false;
     }
     for (int i = 1; i < test.length(); i++)
     {
         if (!Character.isJavaIdentifierPart(test.charAt(i)) && test.charAt(i) != "_")
         {
             return false;
         }
     }
     return true;
 }

}</source>





Determining a Character"s Unicode Block

   <source lang="java">

public class Main {

 public static void main(String[] argv) throws Exception {
   char ch = "\u5639";
   Character.UnicodeBlock block = Character.UnicodeBlock.of(ch);
 }

}</source>





Determining If a String Is a Legal Java Identifier

   <source lang="java">

public class Main {

 public static void main(String[] argv) throws Exception {
   boolean b = isJavaIdentifier("my_var"); 
 }
 public static boolean isJavaIdentifier(String s) {
   if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) {
     return false;
   }
   for (int i = 1; i < s.length(); i++) {
     if (!Character.isJavaIdentifierPart(s.charAt(i))) {
       return false;
     }
   }
   return true;
 }

}</source>





Display printable Characters

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   for (int i = 32; i < 127; i++) {
     System.out.write(i);
     // break line after every eight characters.
     if (i % 8 == 7)
       System.out.write("\n");
     else
       System.out.write("\t");
   }
   System.out.write("\n");
 }

}</source>



! " # $ % & "
  ( ) * + , - . /
  0 1 2 3 4 5 6 7
  8 9 : ; < = > ?
  @ A B C D E F G
  H I J K L M N O
  P Q R S T U V W
  X Y Z [ \ ] ^ _
  ` a b c d e f g
  h i j k l m n o
  p q r s t u v w
  x y z { | } ~


Escape Sequence Characters

   <source lang="java">

\t tab \b backspace \n newline \r carriage return \" single quote \" double quote \\ backslash</source>





Is character a digit, letter, white space, lower case or upper case character

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   char a[] = { "a", "b", "5", "?", "A", " " };
   for (int i = 0; i < a.length; i++) {
     if (Character.isDigit(a[i]))
       System.out.println(a[i] + "is a digit ");
     if (Character.isLetter(a[i]))
       System.out.println(a[i] + "is a letter ");
     if (Character.isWhitespace(a[i]))
       System.out.println(a[i] + "is a White Space ");
     if (Character.isLowerCase(a[i]))
       System.out.println(a[i] + "is a lower case ");
     if (Character.isLowerCase(a[i]))
       System.out.println(a[i] + "is a upper case ");
   }
 }

}</source>





isDigit(): true if the argument is a digit (0 to 9), and false otherwise.

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   char symbol = "A";
   if (Character.isDigit(symbol)) {
     System.out.println("true");
   }else{
     System.out.println("false");
   }
 }

}</source>



false


isLetterOrDigit(): true if the argument is a letter or a digit, and false otherwise.

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   char symbol = "A";
   if (Character.isLetterOrDigit(symbol)) {
     System.out.println("true");
   }else{
     System.out.println("false");
   }
 }

}</source>



true


isLetter(): true if the argument is a letter, and false otherwise.

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   char symbol = "A";
   if (Character.isLetter(symbol)) {
     System.out.println("true");
   }else{
     System.out.println("false");
   }
 }

}</source>



true


is White space

isWhitespace():true if the argument is whitespace.

which is any one of the following characters:

space (" "), tab ("\t"), newline ("\n"), carriage return ("\r"),form feed ("\f")



   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   char symbol = "A";
   if (Character.isWhitespace(symbol)) {
     System.out.println("true");
   }else{
     System.out.println("false");
   }
 }

}</source>



false


Java char: char is 16 bit type and used to represent Unicode characters. Range of char is 0 to

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   char ch1 = "a";
   char ch2 = 65;
   System.out.println("Value of char variable ch1 is :" + ch1);
   System.out.println("Value of char variable ch2 is :" + ch2);
 }

} /* Value of char variable ch1 is :a Value of char variable ch2 is :A

  • /</source>





Max and Min values of datatype char

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   System.out.println((int) Character.MIN_VALUE);
   System.out.println((int) Character.MAX_VALUE);
 }

} //0 //65535</source>





Plus one to char variable

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   char a = "A";
   char b = (char) (a + 1);
   System.out.println(a + b);
   System.out.println("a + b is " + a + b);
 }

}</source>





Store unicode in a char variable

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   int x = 75;
   char y = (char) x;
   char half = "\u00AB";
   System.out.println("y is " + y + " and half is " + half);
 }

}</source>





Storing Characters

Variables of type char

  1. store a single character code.
  2. occupy 16 bits, or 2 bytes,
  3. all characters in Java are stored as Unicode.



   <source lang="java">

public class MainClass{

 public static void main(String[] arg){
    char myCharacter = "X";
    
    System.out.println(myCharacter);
 }

}</source>



X


Thansform an array of ASCII bytes to a string. the byte array should contains only values in.

   <source lang="java">

import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.List; import java.util.Map; /*

*  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. 
*  
*/

/**

* Various string manipulation methods that are more efficient then chaining
* string operations: all is done in the same buffer without creating a bunch of
* string objects.
* 
* @author 
*/

public class Main {

 /**
  * Thansform an array of ASCII bytes to a string. the byte array should contains
  * only values in [0, 127].
  * 
  * @param bytes The byte array to transform
  * @return The resulting string
  */
 public static String asciiBytesToString( byte[] bytes )
 {
     if ( (bytes == null) || (bytes.length == 0 ) )
     {
         return "";
     }
     
     char[] result = new char[bytes.length];
     
     for ( int i = 0; i < bytes.length; i++ )
     {
         result[i] = (char)bytes[i];
     }
     
     return new String( result );
 }

}</source>





To extract Ascii codes from a String

   <source lang="java">

public class Main {

 public static void main(String[] args) throws Exception {
   String test = "ABCD";
   for (int i = 0; i < test.length(); ++i) {
     char c = test.charAt(i);
     System.out.println((int) c);
   }
 }

} /* 65 66 67 68

  • /</source>





Utility methods for ASCII character checking.

   <source lang="java">

/**

* Utility methods for ASCII character checking.
*/

public class ASCIIUtil {

 /**
  * Checks whether the supplied character is a letter or number.
  */
 public static boolean isLetterOrNumber(int c) {
   return isLetter(c) || isNumber(c);
 }
 /**
  * Checks whether the supplied character is a letter.
  */
 public static boolean isLetter(int c) {
   return isUpperCaseLetter(c) || isLowerCaseLetter(c);
 }
 /**
  * Checks whether the supplied character is an upper-case letter.
  */
 public static boolean isUpperCaseLetter(int c) {
   return (c >= 65 && c <= 90); // A - Z
 }
 /**
  * Checks whether the supplied character is an lower-case letter.
  */
 public static boolean isLowerCaseLetter(int c) {
   return (c >= 97 && c <= 122);  // a - z
 }
 /**
  * Checks whether the supplied character is a number
  */
 public static boolean isNumber(int c) {
   return (c >= 48 && c <= 57); // 0 - 9
 }

}</source>





Validate if a String contains only numbers

   <source lang="java">

public class Main {

 public static boolean containsOnlyNumbers(String str) {
   for (int i = 0; i < str.length(); i++) {
     if (!Character.isDigit(str.charAt(i)))
       return false;
   }
   return true;
 }
 public static void main(String[] args) {
   System.out.println(containsOnlyNumbers("123456"));
   System.out.println(containsOnlyNumbers("123abc456"));
 }

} /* true false

  • /</source>