Java charAt() – The Method, its Uses, and its Implications

javaguitutorialSo you’ve just started learning Java. You understand the principles of object-oriented programming, classes and behavior, data types and variables; now you’re ready to do something more complicated, like getting the computer to say more than “Hello world!” to you. Again.

Learning the basics of Java can be an amusing project on its own, though it’s sometimes easy to lose sight of the larger power behind it and coding in general. This post aims to refresh and perhaps open possibilities you missed on the first pass: starting with a simple example, the Java method charAt(), I  introduce you to the Java libraries and the huge amount of possibilities available in programming, even for beginners. Feel free to follow along and test any code examples using your favorite IDE.

But first, some strings.

You are likely familiar with “strings”: in programming, they refer to any string of letters or numbers. Your very first class likely used a string:

System.out.println(“Hello World!”);

What you might not know is that strings themselves are treated as objects, of the class “String.” This class is actually built into the Java programming language, and comes with its own methods.

These methods in their entirety can be found in the official Java documentation for the class String. Resist clicking the link for now as it can be quite an info dump. For now, let’s consider the first method:

charAt( int index )
@Returns the char value at the specified index

If you know your basics, you may already see the implications: like objects of a class you custom-make, objects of class String have methods. These methods can be called to perform predetermined operations. And like most well-designed methods, the charAt()

method is relatively simple; its usability lies in how it can be creatively combined with other methods, classes, and logic to create results.

Results?

At its most basic, we can use charAt() as specified. For example, the following code:

String s = new String(“Hello World!”);
char result = s.charAt(6);
return result;

will return the following result:

W

Combining charAt() with another String method, we can get the final character of any String, regardless of length:

String s = new String(“What a long, strange trip it’s been.”);
char result = s.charAt(s.length()-1);
return result;

will return a period:

.

Warning/Explanation:

length() returns the actual length of the String; to get the last index, you must decrement the output of length(). Strings are arrays of characters, and the method is based on counting these. Other methods that ask to access the String’s contents via its array structure, however, need an index. Java arrays in particular are zero-indexed; forgetting this has led to errors and exceptions for both beginner and veteran programmers. Whichever camp you fall into, such intermediate, core Java topics are worth brushing up on occasionally, to save a few hours of frustration!

Count (From) Zero

This next snippet using charAt() perhaps best illustrates the Java zero-index, and you will likely use it a lot:

String s = new String(“Omnia vincit amor.”);
char result = s.charAt(0);
return result;

This method returns the first letter:

O

Combine this with another String method, toLowerCase(), another class called Scanner, and some knowledge of loops: you now have a reliable way to respond to user input:

public static void main (String args[]) {
   Scanner sc = new Scanner(System.in);
   String HELP_STRING = new String( “Descriptions of Options Here.” );
   String ERROR_STRING = new String( “Excuse me, what was that?” );
   String EXIT_STRING = new String( “Cheers!” );

   menu:
   while(true) {
      System.out.println( “Options: A, B, help, quit” );
      String response = sc.next();
      char aChar = response.toLowerCase().charAt(0);

      if ( aChar == ‘a’ ) {
        System.out.println( “Option A selected.” );
        // TODO Option A operations here
      }
      elsif ( aChar == ‘b’ ) {
         System.out.println( “Option B selected.” );
         //TODO Option B operations here
      }

      elsif ( aChar == ‘h’ ) {
         System.out.println(HELP_STRING);
         }

      elsif ( aChar == ‘q’ ){
         System.out.println(EXIT_STRING);
         break menu;
         }
      else {
         System.out.println(ERROR_STRING);
         }
       } //end menu while-loop

sc.close(); //close scanner to prevent memory leak
} //end method

And about that documentation…

Returning again to the official documentation, you might notice that not only are there dozens of methods for the String class, but lots and lots of classes, and packages of classes, each with their own methods. This ought to be both exhilarating and overwhelming. In fact, once upon a time, Java was specifically developed to be more efficient with memory, and utilize a relatively small library whose packages and classes all saw frequent use. As you might have guessed, Java got popular and expanded considerably.

Further Warning:

Another String method, startsWith(), can be confused with the function of charAt(0). The difference lies in the result of either method: charAt(0) will return a character, whereas startsWith() is a test, returning a boolean.

Thankfully, it’s very unlikely that you will be expected to know each and every method and class front and back to land a job. The most you will likely see use of include (of course) Strings, along with the collections framework. This framework provides common data structures and algorithms that are universal to programming and computer science in general. These advanced Java topics take time and more than a short while of study. But in many ways, they can be approached using what you already know — much like the usage of a now very familiar and simple method.  Learn these, and you’ve broken into computer science proper, and learning new frameworks and other programming languages will seem less daunting. You’ll have mastered incredibly employable skills and knowledge, and you might even enjoy it!

Happy Hacking!

So the next time (likely very soon) you use charAt() in your programming, and get terribly frustrated at zero-indexing, or at why length() didn’t bother to adjust for arrays, think of the larger capabilities and effective power at your mind’s disposal and creativity. Very simple methods such as charAt() form the building blocks of effective, world-changing programs, as well as the portfolio of your wildly-successful development career on the verge. And if you’re itching to develop something with windows and clickable buttons, already, consider learning Swing. The toolkit, not the dance.

Speak Your Mind

*

Email