Java/Data Type/Character

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

All static information about a character

   <source lang="java">
    

public class Classify {

 public static void main(String[] args) throws java.io.IOException {
   char c = "\u0beb"; // Tamil digit.
   System.out.println("Character = " + (int) c);
   System.out.println("Defined = " + Character.isDefined(c));
   System.out.println("Digit = " + Character.isDigit(c));
   System.out.println("Ignorable = " + Character.isIdentifierIgnorable(c));
   System.out.println("ISO control = " + Character.isISOControl(c));
   System.out.println("Java identifier part = " + Character.isJavaIdentifierPart(c));
   System.out.println("Java identifier start = " + Character.isJavaIdentifierStart(c));
   System.out.println("Letter = " + Character.isLetter(c));
   System.out.println("Letter or digit = " + Character.isLetterOrDigit(c));
   System.out.println("Lowercase = " + Character.isLowerCase(c));
   System.out.println("Space = " + Character.isSpaceChar(c));
   System.out.println("Titlecase = " + Character.isTitleCase(c));
   System.out.println("Unicode identifier part = " + Character.isUnicodeIdentifierPart(c));
   System.out.println("Unicode identifier start = " + Character.isUnicodeIdentifierStart(c));
   System.out.println("Uppercase = " + Character.isUpperCase(c));
   System.out.println("White space = " + Character.isWhitespace(c));
   byte[] types = { Character.ruBINING_SPACING_MARK, Character.CONNECTOR_PUNCTUATION,
       Character.CONTROL, Character.CURRENCY_SYMBOL, Character.DASH_PUNCTUATION,
       Character.DECIMAL_DIGIT_NUMBER, Character.ENCLOSING_MARK, Character.END_PUNCTUATION,
       Character.FORMAT, Character.LETTER_NUMBER, Character.LINE_SEPARATOR,
       Character.LOWERCASE_LETTER, Character.MATH_SYMBOL, Character.MODIFIER_SYMBOL,
       Character.NON_SPACING_MARK, Character.OTHER_LETTER, Character.OTHER_NUMBER,
       Character.OTHER_PUNCTUATION, Character.OTHER_SYMBOL, Character.PARAGRAPH_SEPARATOR,
       Character.PRIVATE_USE, Character.SPACE_SEPARATOR, Character.START_PUNCTUATION,
       Character.SURROGATE, Character.TITLECASE_LETTER, Character.UNASSIGNED,
       Character.UPPERCASE_LETTER };
   String[] typeNames = { "Combining spacing mark", "Connector punctuation", "Control",
       "Currency symbol", "Dash punctuation", "Decimal digit number", "Enclosing mark",
       "End punctuation", "Format", "Letter number", "Line separator", "Lowercase letter",
       "Math symbol", "Modifier symbol", "Non spacing mark", "Other letter", "Other number",
       "Other punctuation", "Other symbol", "Paragraph separator", "Private use",
       "Space separator", "Start punctuation", "Surrogate", "Titlecase letter", "Unassigned",
       "Uppercase letter" };
   int type = Character.getType(c);
   for (int i = 0; i < types.length; i++)
     if (type == types[i]) {
       System.out.println("Type name = " + typeNames[i]);
       break;
     }
   System.out.println("Unicode block = " + Character.UnicodeBlock.of(c));
 }

} /*Character = 3051 Defined = true Digit = true Ignorable = false ISO control = false Java identifier part = true Java identifier start = false Letter = false Letter or digit = true Lowercase = false Space = false Titlecase = false Unicode identifier part = true Unicode identifier start = false Uppercase = false White space = false Type name = Decimal digit number Unicode block = TAMIL

  • /



 </source>
   
  
 
  



Character array convert and find

   <source lang="java">
 

// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.

/**

* Various character and character sequence utilities.
*/
class CharUtil {
 // ---------------------------------------------------------------- to byte array
 /**
  * Converts char array into byte array by stripping high byte.
  */
 public static byte[] toByteArray(char[] carr) {
   if (carr == null) {
     return null;
   }
   byte[] barr = new byte[carr.length];
   for (int i = 0; i < carr.length; i++) {
     barr[i] = (byte) carr[i];
   }
   return barr;
 }
 /**
  * Converts char array to byte array using provided encoding.  
  */
 public static byte[] toByteArray(char[] carr, String charset) throws Exception{
   return new String(carr).getBytes(charset);
 }
 /**
  * Converts char array into ASCII array.
  * @see #toAscii(char) 
  */
 public static byte[] toAsciiArray(char[] carr) {
   if (carr == null) {
     return null;
   }
   byte[] barr = new byte[carr.length];
   for (int i = 0; i < carr.length; i++) {
     barr[i] = (byte) toAscii(carr[i]);
   }
   return barr;
 }
 /**
  * Converts char sequence into byte array. Chars are truncated to byte size.
  */
 public static byte[] toByteArray(CharSequence charSequence) {
   if (charSequence == null) {
     return null;
   }
   byte[] barr = new byte[charSequence.length()];
   for (int i = 0; i < barr.length; i++) {
     barr[i] = (byte) charSequence.charAt(i);
   }
   return barr;
 }
 /**
  * Converts char sequence into ASCII array.
  */
 public static byte[] toAsciiArray(CharSequence charSequence) {
   if (charSequence == null) {
     return null;
   }
   byte[] barr = new byte[charSequence.length()];
   for (int i = 0; i < barr.length; i++) {
     barr[i] = (byte) toAscii(charSequence.charAt(i));
   }
   return barr;
 }
 // ---------------------------------------------------------------- to char array
 /**
  * Converts byte array to char array by simply extending.
  */
 public static char[] toCharArray(byte[] barr) {
   if (barr == null) {
     return null;
   }
   char[] carr = new char[barr.length];
   for (int i = 0; i < barr.length; i++) {
     carr[i] = (char) barr[i];
   }
   return carr;
 }
 /**
  * Converts byte array of specific encoding to char array.
  */
 public static char[] toCharArray(byte[] barr, String charset) throws Exception {
   return new String(barr, charset).toCharArray();
 }
 /**
  * Returns ASCII value of a char. In case of overload, 0x3F is returned.
  */
 public static int toAscii(char c) {
   if (c <= 0xFF) {
     return c;
   } else {
     return 0x3F;
   }
 }
 // ---------------------------------------------------------------- find
 /**
  * Match if one character equals to any of the given character.
  *
  * @return true if characters match any character from given array,
  *         otherwise false
  */
 public static boolean equalsOne(char c, char[] match) {
   for (char aMatch : match) {
     if (c == aMatch) {
       return true;
     }
   }
   return false;
 }
 /**
  * Finds index of the first character in given array the matches any from the
  * given set of characters.
  *
  * @return index of matched character or -1
  */
 public static int findFirstEqual(char[] source, int index, char[] match) {
   for (int i = index; i < source.length; i++) {
     if (equalsOne(source[i], match) == true) {
       return i;
     }
   }
   return -1;
 }
 /**
  * Finds index of the first character in given array the matches any from the
  * given set of characters.
  *
  * @return index of matched character or -1
  */
 public static int findFirstEqual(char[] source, int index, char match) {
   for (int i = index; i < source.length; i++) {
     if (source[i] == match) {
       return i;
     }
   }
   return -1;
 }
 /**
  * Finds index of the first character in given array the differs from the
  * given set of characters.
  *
  * @return index of matched character or -1
  */
 public static int findFirstDiff(char[] source, int index, char[] match) {
   for (int i = index; i < source.length; i++) {
     if (equalsOne(source[i], match) == false) {
       return i;
     }
   }
   return -1;
 }
 /**
  * Finds index of the first character in given array the differs from the
  * given set of characters.
  *
  * @return index of matched character or -1
  */
 public static int findFirstDiff(char[] source, int index, char match) {
   for (int i = index; i < source.length; i++) {
     if (source[i] != match) {
       return i;
     }
   }
   return -1;
 }
 // ---------------------------------------------------------------- is char at
 public static boolean isCharAtEqual(char[] source, int index, char match) {
   if ((index < 0) || (index >= source.length)) {
     return false;
   }
   return source[index] == match;
 }
 public static boolean isCharAtEqual(CharSequence source, int index, char match) {
   if ((index < 0) || (index >= source.length())) {
     return false;
   }
   return source.charAt(index) == match;
 }
 // ---------------------------------------------------------------- is
 /**
  * Returns true if character is a white space.
  * White space definition is taken from String class (see: trim()
  */
 public static boolean isWhitespace(char c) {
   return c <= " ";
 }
 /**
  * Returns true if specified character is lowercase ASCII.
  * If user uses only ASCIIs, it is much much faster.
  */
 public static boolean isLowercaseLetter(char c) {
   return (c >= "a") && (c <= "z");
 }
 /**
  * Returns true if specified character is uppercase ASCII.
  * If user uses only ASCIIs, it is much much faster.
  */
 public static boolean isUppercaseLetter(char c) {
   return (c >= "A") && (c <= "Z");
 }
 public static boolean isLetter(char c) {
   return ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z"));
 }
 public static boolean isDigit(char c) {
   return (c >= "0") && (c <= "9");
 }
 public static boolean isLetterOrDigit(char c) {
   return isDigit(c) || isLetter(c);
 }
 public static boolean isWordChar(char c) {
   return isDigit(c) || isLetter(c) || (c == "_");
 }
 public static boolean isPropertyNameChar(char c) {
   return isDigit(c) || isLetter(c) || (c == "_") || (c == ".") || (c == "[") || (c == "]");
 }
 // ---------------------------------------------------------------- conversions
 /**
  * Uppers lowercase ASCII char.
  */
 public static char toUpperAscii(char c) {
   if (isLowercaseLetter(c)) {
     c -= (char) 0x20;
   }
   return c;
 }
 /**
  * Lowers uppercase ASCII char.
  */
 public static char toLowerAscii(char c) {
   if (isUppercaseLetter(c)) {
     c += (char) 0x20;
   }
   return c;
 }

}


 </source>
   
  
 
  



Character class creates primitives that wrap themselves around data items of the char data type

   <source lang="java">
     

public class MainClass {

 public static void main(String[] args) {
   char c = "*";
   Character c2 = new Character(c);
   System.out.println(c2.charValue());
 }

}



 </source>
   
  
 
  



Char is Int

   <source lang="java">
    

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. All rights
* reserved. Software written by Ian F. Darwin and others. $Id: LICENSE,v 1.8
* 2004/02/09 03:33:38 ian Exp $
* 
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. 2. 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.
* 
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee cup"
* logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

public class CharIsInt {

 public static void main(String[] argv) {
   char a = "A";
   System.out.println("a is " + a);
   int i = a;
   System.out.println("i is " + i);
   char n = (char) -a;
   System.out.println("n is " + n);
   int z = n;
   System.out.println("z is " + z);
   // Now: is char signed or unsigned?
   // char neg = -1; // WON"T COMPILE
   // System.out.println("neg is " + neg);
 }

}




 </source>
   
  
 
  



Check if a character representing an alphabet

   <source lang="java">
    

public class Main {

 public static void main(String[] args) {
   String nama = "Java Java";
   if (Character.isLetter(nama.charAt(5))) {
     System.out.println("The fifth character is an alphabet!");
   }
 }

}



 </source>
   
  
 
  



Check if a character representing a number

   <source lang="java">
    

public class Main {

 public static void main(String[] args) {
   String numbers = "1234567890";
   for (int i = 0; i < numbers.length(); i++) {
     if (Character.isDigit(numbers.charAt(i))) {
       System.out.println(numbers.charAt(i) + " is a number.");
     } else {
       System.out.println(numbers.charAt(i) + " not a number.");
     }
   }
 }

}



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



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 to hex

   <source lang="java">
    

public class Convert {

 public static void main(String[] args) {
   int i = 0, num = 23658;
   char[] digits = new char[8];
   do {
     digits[i++] = Character.forDigit(num % 16, 16);
     num /= 16;
   } while (num != 0);
   for (int j = 7; j >= 0; j--)
     System.out.println(digits[j]);
   char[] hex = { "f", "3", "6", "0" };
   num = 0;
   for (int j = 0; j < hex.length; j++) {
     num <<= 4; 
     num += Character.digit(hex[j], 16);
   }
   System.out.println(num);
 }

}



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



Count the number of bytes included in the given char[].

   <source lang="java">
  

import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /*

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

 private static final int CHAR_ONE_BYTE_MASK = 0xFFFFFF80;
 private static final int CHAR_TWO_BYTES_MASK = 0xFFFFF800;
 private static final int CHAR_THREE_BYTES_MASK = 0xFFFF0000;
 private static final int CHAR_FOUR_BYTES_MASK = 0xFFE00000;
 private static final int CHAR_FIVE_BYTES_MASK = 0xFC000000;
 private static final int CHAR_SIX_BYTES_MASK = 0x80000000;
 
 /**
  * Count the number of bytes included in the given char[].
  * 
  * @param chars
  *            The char array to decode
  * @return The number of bytes in the char array
  */
 public static final int countBytes( char[] chars )
 {
     if ( chars == null )
     {
         return 0;
     }
     int nbBytes = 0;
     int currentPos = 0;
     while ( currentPos < chars.length )
     {
         int nbb = countNbBytesPerChar( chars[currentPos] );
         // If the number of bytes necessary to encode a character is
         // above 3, we will need two UTF-16 chars
         currentPos += ( nbb < 4 ? 1 : 2 );
         nbBytes += nbb;
     }
     return nbBytes;
 }
 
 
 /**
  * Return the number of bytes that hold an Unicode char.
  * 
  * @param car
  *            The character to be decoded
  * @return The number of bytes to hold the char. TODO : Should stop after
  *         the third byte, as a char is only 2 bytes long.
  */
 public static final int countNbBytesPerChar( char car )
 {
     if ( ( car & CHAR_ONE_BYTE_MASK ) == 0 )
     {
         return 1;
     }
     else if ( ( car & CHAR_TWO_BYTES_MASK ) == 0 )
     {
         return 2;
     }
     else if ( ( car & CHAR_THREE_BYTES_MASK ) == 0 )
     {
         return 3;
     }
     else if ( ( car & CHAR_FOUR_BYTES_MASK ) == 0 )
     {
         return 4;
     }
     else if ( ( car & CHAR_FIVE_BYTES_MASK ) == 0 )
     {
         return 5;
     }
     else if ( ( car & CHAR_SIX_BYTES_MASK ) == 0 )
     {
         return 6;
     }
     else
     {
         return -1;
     }
 }

}


 </source>
   
  
 
  



Count the number of chars included in the given byte[].

   <source lang="java">
  

import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /*

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

 private static final int UTF8_MULTI_BYTES_MASK = 0x0080;
 private static final int UTF8_TWO_BYTES_MASK = 0x00E0;
 private static final int UTF8_TWO_BYTES = 0x00C0;
 private static final int UTF8_THREE_BYTES_MASK = 0x00F0;
 private static final int UTF8_THREE_BYTES = 0x00E0;
 private static final int UTF8_FOUR_BYTES_MASK = 0x00F8;
 private static final int UTF8_FOUR_BYTES = 0x00F0;
 private static final int UTF8_FIVE_BYTES_MASK = 0x00FC;
 private static final int UTF8_FIVE_BYTES = 0x00F8;
 private static final int UTF8_SIX_BYTES_MASK = 0x00FE;
 private static final int UTF8_SIX_BYTES = 0x00FC;
 /**
  * Count the number of bytes needed to return an Unicode char. This can be
  * from 1 to 6.
  * 
  * @param bytes
  *            The bytes to read
  * @param pos
  *            Position to start counting. It must be a valid start of a
  *            encoded char !
  * @return The number of bytes to create a char, or -1 if the encoding is
  *         wrong. TODO : Should stop after the third byte, as a char is only
  *         2 bytes long.
  */
 public static final int countBytesPerChar( byte[] bytes, int pos )
 {
     if ( bytes == null )
     {
         return -1;
     }
     if ( ( bytes[pos] & UTF8_MULTI_BYTES_MASK ) == 0 )
     {
         return 1;
     }
     else if ( ( bytes[pos] & UTF8_TWO_BYTES_MASK ) == UTF8_TWO_BYTES )
     {
         return 2;
     }
     else if ( ( bytes[pos] & UTF8_THREE_BYTES_MASK ) == UTF8_THREE_BYTES )
     {
         return 3;
     }
     else if ( ( bytes[pos] & UTF8_FOUR_BYTES_MASK ) == UTF8_FOUR_BYTES )
     {
         return 4;
     }
     else if ( ( bytes[pos] & UTF8_FIVE_BYTES_MASK ) == UTF8_FIVE_BYTES )
     {
         return 5;
     }
     else if ( ( bytes[pos] & UTF8_SIX_BYTES_MASK ) == UTF8_SIX_BYTES )
     {
         return 6;
     }
     else
     {
         return -1;
     }
 }
 
 /**
  * Count the number of chars included in the given byte[].
  * 
  * @param bytes
  *            The byte array to decode
  * @return The number of char in the byte array
  */
 public static final int countChars( byte[] bytes )
 {
     if ( bytes == null )
     {
         return 0;
     }
     int nbChars = 0;
     int currentPos = 0;
     while ( currentPos < bytes.length )
     {
         currentPos += countBytesPerChar( bytes, currentPos );
         nbChars++;
     }
     return nbChars;
 }
 

}


 </source>
   
  
 
  



Create Character objects and compare them

   <source lang="java">
     

class MainClass {

 public static void main(String[] args) {
   Character c1 = new Character("6");
   Character c2 = new Character("7");
   char c3 = c1.charValue();
   char c4 = c2.charValue();
   if (c3 < c4)
     System.out.println(c3 + " is less than " + c4);
   if (c1.rupareTo(c2) < 0)
     System.out.println(c1 + " is less than " + c4);
 }

}



 </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"); // true
 }
 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>
   
  
 
  



Escape Sequence Characters

   <source lang="java">
    

\t tab \b backspace \n newline \r carriage return \" single quote \" double quote \\ backslash



 </source>
   
  
 
  



if a character is lowercase

   <source lang="java">
    

public class Main {

 public static void main(String[] args) {
   char a = "a";
   if (Character.isLowerCase(a)) {
     System.out.println(a + " is a lowercase character.");
   }
 }

}



 </source>
   
  
 
  



If a character is uppercase

   <source lang="java">
    

public class Main {

 public static void main(String[] args) {
   char c = "A";
   if (Character.isUpperCase(c)) {
     System.out.println(c + " is an uppercase character");
   }
 }

}



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



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

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



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>
   
  
 
  



String based on char array

   <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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org.  For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/

/**

* This class is used as a structure to pass text contained in the underlying
* character buffer of the scanner. The offset and length fields allow the
* buffer to be re-used without creating new character arrays.
*

* Note: Methods that are passed an XMLString structure * should consider the contents read-only and not make any modifications * to the contents of the buffer. The method receiving this structure * should also not modify the offset and length if this structure (or * the values of this structure) are passed to another method. * <p> * Note: Methods that are passed an XMLString structure * are required to copy the information out of the buffer if it is to be * saved for use beyond the scope of the method. The contents of the * structure are volatile and the contents of the character buffer cannot * be assured once the method that is passed this structure returns. * Therefore, methods passed this structure should not save any reference * to the structure or the character array contained in the structure. * * @author Eric Ye, IBM * @author Andy Clark, IBM * * @version $Id: XMLString.java 515 2008-03-17 21:02:23Z jfrederic.clere@jboss.ru $ */ public class XMLString { // // Data // /** The character array. */ public char[] ch; /** The offset into the character array. */ public int offset; /** The length of characters from the offset. */ public int length; // // Constructors // /** Default constructor. */ public XMLString() { } // <init>() /** * Constructs an XMLString structure preset with the specified * values. * * @param ch The character array. * @param offset The offset into the character array. * @param length The length of characters from the offset. */ public XMLString(char[] ch, int offset, int length) { setValues(ch, offset, length); } // <init>(char[],int,int) /** * Constructs an XMLString structure with copies of the values in * the given structure. * <p> * Note: This does not copy the character array; * only the reference to the array is copied. * * @param string The XMLString to copy. */ public XMLString(XMLString string) { setValues(string); } // <init>(XMLString) // // Public methods // /** * Initializes the contents of the XMLString structure with the * specified values. * * @param ch The character array. * @param offset The offset into the character array. * @param length The length of characters from the offset. */ public void setValues(char[] ch, int offset, int length) { this.ch = ch; this.offset = offset; this.length = length; } // setValues(char[],int,int) /** * Initializes the contents of the XMLString structure with copies * of the given string structure. * <p> * Note: This does not copy the character array; * only the reference to the array is copied. * * @param s */ public void setValues(XMLString s) { setValues(s.ch, s.offset, s.length); } // setValues(XMLString) /** Resets all of the values to their defaults. */ public void clear() { this.ch = null; this.offset = 0; this.length = -1; } // clear() /** * Returns true if the contents of this XMLString structure and * the specified array are equal. * * @param ch The character array. * @param offset The offset into the character array. * @param length The length of characters from the offset. */ public boolean equals(char[] ch, int offset, int length) { if (ch == null) { return false; } if (this.length != length) { return false; } for (int i=0; i<length; i++) { if (this.ch[this.offset+i] != ch[offset+i] ) { return false; } } return true; } // equals(char[],int,int):boolean /** * Returns true if the contents of this XMLString structure and * the specified string are equal. * * @param s The string to compare. */ public boolean equals(String s) { if (s == null) { return false; } if ( length != s.length() ) { return false; } // is this faster than call s.toCharArray first and compare the // two arrays directly, which will possibly involve creating a // new char array object. for (int i=0; i<length; i++) { if (ch[offset+i] != s.charAt(i)) { return false; } } return true; } // equals(String):boolean // // Object methods // /** Returns a string representation of this object. */ public String toString() { return length > 0 ? new String(ch, offset, length) : ""; } // toString():String } // class XMLString </source>

StringBuffer based on char array

   <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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org.  For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/

/**

* XMLString is a structure used to pass character arrays. However,
* XMLStringBuffer is a buffer in which characters can be appended
* and extends XMLString so that it can be passed to methods
* expecting an XMLString object. This is a safe operation because
* it is assumed that any callee will not modify
* the contents of the XMLString structure.
* <p> 
* The contents of the string are managed by the string buffer. As
* characters are appended, the string buffer will grow as needed.
* <p>
* Note: Never set the ch, 
* offset, and length fields directly.
* These fields are managed by the string buffer. In order to reset
* the buffer, call clear().
* 
* @author Andy Clark, IBM
* @author Eric Ye, IBM
*
* @version $Id: XMLStringBuffer.java 515 2008-03-17 21:02:23Z jfrederic.clere@jboss.ru $
*/

public class XMLStringBuffer

   extends XMLString {
   //
   // Constants
   //
   /** Default buffer size (32). */
   public static final int DEFAULT_SIZE = 32;
   //
   // Constructors
   //
   /**
    * 
    */
   public XMLStringBuffer() {
       this(DEFAULT_SIZE);
   } // <init>()
   /**
    * 
    * 
    * @param size 
    */
   public XMLStringBuffer(int size) {
       ch = new char[size];
   } // <init>(int)
   /** Constructs a string buffer from a char. */
   public XMLStringBuffer(char c) {
       this(1);
       append(c);
   } // <init>(char)
   /** Constructs a string buffer from a String. */
   public XMLStringBuffer(String s) {
       this(s.length());
       append(s);
   } // <init>(String)
   /** Constructs a string buffer from the specified character array. */
   public XMLStringBuffer(char[] ch, int offset, int length) {
       this(length);
       append(ch, offset, length);
   } // <init>(char[],int,int)
   /** Constructs a string buffer from the specified XMLString. */
   public XMLStringBuffer(XMLString s) {
       this(s.length);
       append(s);
   } // <init>(XMLString)
   //
   // Public methods
   //
   /** Clears the string buffer. */
   public void clear() {
       offset = 0;
       length = 0;
   }
   /**
    * append
    * 
    * @param c 
    */
   public void append(char c) {
       if (this.length + 1 > this.ch.length) {
                   int newLength = this.ch.length*2;
                   if (newLength < this.ch.length + DEFAULT_SIZE)
                       newLength = this.ch.length + DEFAULT_SIZE;
                   char[] newch = new char[newLength];
                   System.arraycopy(this.ch, 0, newch, 0, this.length);
                   this.ch = newch;
       }
       this.ch[this.length] = c;
       this.length++;
   } // append(char)
   /**
    * append
    * 
    * @param s 
    */
   public void append(String s) {
       int length = s.length();
       if (this.length + length > this.ch.length) {
           int newLength = this.ch.length*2;
           if (newLength < this.length + length + DEFAULT_SIZE)
               newLength = this.ch.length + length + DEFAULT_SIZE;
           char[] newch = new char[newLength];            
           System.arraycopy(this.ch, 0, newch, 0, this.length);
           this.ch = newch;
       }
       s.getChars(0, length, this.ch, this.length);
       this.length += length;
   } // append(String)
   /**
    * append
    * 
    * @param ch 
    * @param offset 
    * @param length 
    */
   public void append(char[] ch, int offset, int length) {
       if (this.length + length > this.ch.length) {
           char[] newch = new char[this.ch.length + length + DEFAULT_SIZE];
           System.arraycopy(this.ch, 0, newch, 0, this.length);
           this.ch = newch;
       }
       System.arraycopy(ch, offset, this.ch, this.length, length);
       this.length += length;
   } // append(char[],int,int)
   /**
    * append
    * 
    * @param s 
    */
   public void append(XMLString s) {
       append(s.ch, s.offset, s.length);
   } // append(XMLString)

} // class XMLStringBuffer /*

* 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 software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org.  For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/

/**

* This class is used as a structure to pass text contained in the underlying
* character buffer of the scanner. The offset and length fields allow the
* buffer to be re-used without creating new character arrays.
* <p>
* Note: Methods that are passed an XMLString structure
* should consider the contents read-only and not make any modifications
* to the contents of the buffer. The method receiving this structure
* should also not modify the offset and length if this structure (or
* the values of this structure) are passed to another method.
* <p>
* Note: Methods that are passed an XMLString structure
* are required to copy the information out of the buffer if it is to be
* saved for use beyond the scope of the method. The contents of the 
* structure are volatile and the contents of the character buffer cannot
* be assured once the method that is passed this structure returns.
* Therefore, methods passed this structure should not save any reference
* to the structure or the character array contained in the structure.
*
* @author Eric Ye, IBM
* @author Andy Clark, IBM
*
* @version $Id: XMLString.java 515 2008-03-17 21:02:23Z jfrederic.clere@jboss.ru $
*/

class XMLString{

   //
   // Data
   //
   /** The character array. */
   public char[] ch;
   /** The offset into the character array. */
   public int offset;
   /** The length of characters from the offset. */
   public int length;
   //
   // Constructors
   //
   /** Default constructor. */
   public XMLString() {
   } // <init>()
   /**
    * Constructs an XMLString structure preset with the specified
    * values.
    * 
    * @param ch     The character array.
    * @param offset The offset into the character array.
    * @param length The length of characters from the offset.
    */
   public XMLString(char[] ch, int offset, int length) {
       setValues(ch, offset, length);
   } // <init>(char[],int,int)
   /**
    * Constructs an XMLString structure with copies of the values in
    * the given structure.
    * <p>
    * Note: This does not copy the character array;
    * only the reference to the array is copied.
    *
    * @param string The XMLString to copy.
    */
   public XMLString(XMLString string) {
       setValues(string);
   } // <init>(XMLString)
   //
   // Public methods
   //
   /**
    * Initializes the contents of the XMLString structure with the
    * specified values.
    * 
    * @param ch     The character array.
    * @param offset The offset into the character array.
    * @param length The length of characters from the offset.
    */
   public void setValues(char[] ch, int offset, int length) {
       this.ch = ch;
       this.offset = offset;
       this.length = length;
   } // setValues(char[],int,int)
   /**
    * Initializes the contents of the XMLString structure with copies
    * of the given string structure.
    * <p>
    * Note: This does not copy the character array;
    * only the reference to the array is copied.
    * 
    * @param s
    */
   public void setValues(XMLString s) {
       setValues(s.ch, s.offset, s.length);
   } // setValues(XMLString)
   /** Resets all of the values to their defaults. */
   public void clear() {
       this.ch = null;
       this.offset = 0;
       this.length = -1;
   } // clear()
   /**
    * Returns true if the contents of this XMLString structure and
    * the specified array are equal.
    * 
    * @param ch     The character array.
    * @param offset The offset into the character array.
    * @param length The length of characters from the offset.
    */
   public boolean equals(char[] ch, int offset, int length) {
       if (ch == null) {
           return false;
       }
       if (this.length != length) {
           return false;
       }
       for (int i=0; i<length; i++) {
           if (this.ch[this.offset+i] != ch[offset+i] ) {
               return false;
           }
       }
       return true;
   } // equals(char[],int,int):boolean
   /**
    * Returns true if the contents of this XMLString structure and
    * the specified string are equal.
    * 
    * @param s The string to compare.
    */
   public boolean equals(String s) {
       if (s == null) {
           return false;
       }
       if ( length != s.length() ) {
           return false;
       }
       // is this faster than call s.toCharArray first and compare the 
       // two arrays directly, which will possibly involve creating a
       // new char array object.
       for (int i=0; i<length; i++) {
           if (ch[offset+i] != s.charAt(i)) {
               return false;
           }
       }
       return true;
   } // equals(String):boolean
   //
   // Object methods
   //
   /** Returns a string representation of this object. */
   public String toString() {
       return length > 0 ? new String(ch, offset, length) : "";
   } // toString():String

} // class XMLString


 </source>
   
  
 
  



switch with char value

   <source lang="java">
     

import java.util.Scanner; public class MainCLass {

 static Scanner sc = new Scanner(System.in);
 public static void main(String[] args) {
   System.out.print("Enter the package code: ");
   String s = sc.next();
   char p = s.charAt(0);
   String details = "";
   switch (p) {
   case "E":
   case "e":
     details += "\tE...\n";
   case "D":
   case "d":
     details += "\tD...\n";
   case "C":
   case "c":
     details += "\tC...\n";
   case "B":
   case "b":
     details += "\tB...\n";
   case "A":
   case "a":
     details += "\tA.\n";
     break;
   default:
     details = "That"s";
     break;
   }
   System.out.println(details);
 }

}



 </source>
   
  
 
  



Use Character.isDigit to check the if a char is a digit

   <source lang="java">
     

class MainCLass {

 public static void main(String[] args) {
   System.out.println("Is the Latin symbol 6 a digit? " + Character.isDigit("6"));
   System.out.println("Is the Tamil symbol corresponding to "
       + "Unicode value "\\u0beb" a digit? " + Character.isDigit("\u0beb"));
   System.out.println("Is the Greek symbol Omega a digit? " + Character.isDigit("\u03a9"));
   System.out.println("Is the Latin symbol A a digit? " + Character.isDigit("A"));
 }

}



 </source>
   
  
 
  



Use Character.isLetter to check if a char is a letter

   <source lang="java">
     

class MainClass {

 public static void main(String[] args) {
   System.out.println("Is the Greek symbol Omega a letter? " + Character.isLetter("\u03a9"));
   System.out.println("Is the Latin symbol z a letter? " + Character.isLetter("z"));
 }

}



 </source>
   
  
 
  



Use Character.isLowerCase, Character.isUpperCase to check the letter case

   <source lang="java">
     

class MainClass {

 public static void main(String[] args) {
   System.out.println("Is the Latin symbol z a lowercase letter? " + Character.isLowerCase("z"));
   System.out.println("Is the Latin symbol a an uppercase letter? " + Character.isUpperCase("a"));
 }

}



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