TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java Char Lookup Table

Use a char lookup table to instantly convert characters with array element accesses.
Char lookup table. Character transformations can be slow. We can have elaborate logic in them. With a lookup table, we can instantly map characters.
For ASCII chars, like ABC, we can use a small lookup table of 128 chars. Then we can use char values (like "A") as the index, and store chars in each slot.
Example code. Let us begin with this simple example. We use a char table of 128 elements to store the result of toUpperCase. We store uppercased versions of all chars.

Then: We can transform chars with a simple table lookup. No call to Character.toUpperCase is needed.

Java program that uses char lookup table public class Program { static char[] table = new char[128]; public static void main(String[] args) { // Set up the lookup table. for (int i = 0; i < 128; i++) { // Get character for this int. char c = (char) i; // Convert to uppercase. char result = Character.toUpperCase(c); // Store in lookup table field. table[c] = result; } // Loop over string characters. String name = "Carrot123"; for (int i = 0; i < name.length(); i++) { // Get char from lookup table based on string char. char result = table[name.charAt(i)]; // Write results. System.out.println(name.charAt(i) + "/" + result); } } } Output C/C a/A r/R r/R o/O t/T 1/1 2/2 3/3
Some performance notes. Character lookup tables are an optimization in many programs. They help the most on slow operations—toUpperCase is too fast to show much benefit from a table.
For a cipher, like ROT13 or a Caesar cipher, a char lookup table can show more improvement. And lookup tables (a form of memoization) are excellent for mathematical computations as well.ROT13Caesar Cipher
Some limitations, summary. Char lookup tables must accommodate all characters, or use a range check for values. This ensures no exceptions are thrown.Exceptions
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf