Computer Science 212 - Tutorial 1
Some Java basicsCopyright © 2005 by Dorothy L. Nixon. All rights reserved.
Table of contents
- Kinds of data types in Java: primitives, arrays, and objects defined by classes
- Methods in Java: instance vs. static
- Command-line arguments
- Strings in Java (vs. C++)
- Some instance methods of class String
- JOptionPane Dialog boxes
- Inputting numbers
- Console input
- Wrapper classes for the primitive data types
- Some advantages of Java syntax
- Floating-point literals, and integer vs. floating-point division
- More about characters and strings in Java
Example files (download as ZIP file here)
- AverageOf3.java
- CharactersInString.java
- CharactersInString2.java
- ClassifyChar1.java
- ClassifyChar2.java
- ClassifyChar3.java
- ClassifyChar4.java
- CommandLineDemo1.java
- CommandLineDemo2.java
- Compare3.java
- ConsoleInput.java
- ConsoleInputTest.java
- DoubleDiv.java
- FloatDiv.java
- IntDivision.java
- JOptionPaneDemo.java
- StringMethodsDemo.java
- compare3.cpp
The example files may be downloaded in a ZIP file here.
Tutorial on some Java basics
- Kinds of data types in Java: primitives, arrays, and objects defined by classes
Java is in many ways similar to C++, though there are some differences too.
Java has three kinds of data types:
- Primitive data types. A variable of a primitive data type holds a single, simple value, such as a single number or character. Example include int, float, double, char, and boolean.
- Arrays, which hold an indexed sequence of data items, all of one data type. The items in the sequence are known as the array's elements.
- Objects defined by classes: the fanciest data types. Unlike arrays, which can store data elements of only one type, objects can store data items of possibly different types. Moreover, not only can objects store data, but they can also have behaviors defined for them via functions, known in Java as methods. Some classes are defined in the Java library, and others can be defined by the programmer.
- Methods in Java: instance vs. static
In both Java and C++, a class is a programming construct used to define objects.
In C++, classes are used only to define objects and for no other purpose. In C++, many functions - including the main function - are written as stand-alone blocks of code, not part of any larger curly-brace-enclosed block. Also in C++, groups of related functions and global variables are sometimes placed in larger blocks known as namespaces, which are not the same thing as classes but are just a way to organize functions and variables.
On the other hand, in Java, classes are used not only to define objects, but also as all-purpose program blocks. In Java, every method (function), including even the main method, must be defined inside a class block, regardless of whether the method is being used to define a behavior of an object of the class.
So, in Java, we need to distinguish between (1) methods which define behaviors of objects and (2) methods which don't define behaviors of objects but which are defined inside a class block merely because every method in Java is required to be defined inside a class block. Methods which define behaviors of objects are known as instance methods. Methods which do NOT define behaviors of objects are known as static methods.
So that the compiler can tell the difference between an instance method and a static method, all static methods must have the keyword static in their method headings. No special keyword is needed to mark an instance method.
In a large object-oriented program, most of the code will be devoted to defining behaviors of objects. Thus, the majority of functions/methods will be instance methods. However, in your first programming project for this course, you will be defining static methods only. Also, the majority of the library methods used in the examples in this tutorial will be static methods.
Below is a simple example program which just prints out the word "Hello!":
// Hello.java public class Hello { public static void main(String[] args) { System.out.println("Hello!"); } // method main } // class HelloSince the main method begins running before any objects are created, it must be a static method. Therefore, its heading contains the keyword static. The main method is void because it does not return a value.
You'll learn later what the word "public" means. Don't worry about it for now.
In Java, every file must contain at most one public class, and the name of the file must match the name of the public class. Thus, the name of the file containing a definition of public class Hello must be Hello.java. Remember that Java is case-sensitive.
The main method takes an array of strings as a parameter. The purpose of this array is to accommodate any command-line arguments, as explained below.
- Command-line arguments
When you type commands in a DOS (Command Prompt) window like the following:
cd Tutorial-1-examples copy Z:*.* H: javac CommandLineDemo1.javaNote that you are typing a command itself followed by one or more other strings, separated by spaces. These strings are known as command-line arguments.
Java programs can accommodate command-line arguments. As an example, let's consider the program CommandLineDemo1.java.
After first making sure your DOS (Command Prompt) window is looking at the directory containing your example programs for Tutorial 1, compile the example program CommandLineDemo1.java by typing:
javac CommandLineDemo1.javaand then run it by typing:
java CommandLineDemo1 firstname middlename lastnamereplacing "firstname," "middlename," and "lastname" with your actual first, middle, and last names. (If you don't have a middle name, make one up. Make sure you type a total of three names.) For example:
java CommandLineDemo1 Dorothy L. NixonIn the above case, the output in your DOS window will be:
Hello, Dorothy L. Nixon.Below is the program itself:
// CommandLineDemo1.java // Demonstrates command-line arguments // Expects the user to type: // // java CommandLineDemo1 firstname middlename lastname // // using one's actual first, middle, and last names. // Displays ugly message if the user does not type // enough command-line arguments. public class CommandLineDemo1 { public static void main(String[] args) { String name; name = args[0] + " " + args[1] + " " + args[2]; System.out.println("Hello, " + name + "."); } // method main } // class CommandLineDemo1Note that the array args contains the command-line arguments, where args[0] contains the first name, args[1] contains the middle name, and args[2] contains the last name.
Now let's see what happens when you type fewer than three command-line arguments. You get the following ugly error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at CommandLineDemo1.main(CommandLineDemo1.java:16)To a programmer, this isn't too bad. At least it does tell you what the problem is -- array index out of bounds. The problem is that you tried to access an array element that doesn't exist because it would be beyond the end of the array. For example, if you typed fewer than three command-line arguments, then args[2] doesn't exist, but only args[0] and args[1].
But, to the average user, the above message would be very ugly and scary. So, let's figure out how to make the program print a more user-friendly error message.
Compile CommandLineDemo2.java and run it with fewer than three command-line arguments. This program succeeds in printing a more user-friendly message but does not yet succeed in removing the ugly message. The output is as follows:
This program will echo your name if you type it as three command-line arguments. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at CommandLineDemo2.main(CommandLineDemo2.java:22)The program contains the following if block, just after the main method heading:
if ( args.length < 3 ) { System.out.print("This program will echo your "); System.out.println("name if you type it as"); System.out.println("three command-line arguments."); } // ifThus the indicated message is printed out if the array args contains fewer than three elements. The expression args.length has a value equal to the length (number of elements) of array args. Note that Java arrays, unlike C++ arrays, can remember their own length.
However, after the if block is finished executing, the program continues running and eventually tries to access the nonexistent array element args[2]. Hence the ugly "ArrayIndexOutOfBoundsException" message again.
So, to avoid printing out the ugly message, we need the program to stop somehow when we reach the end of the if block. One way to accomplish this would be to put, at the end of the if block, a call to the static exit method of library class System, as follows:
if ( args.length < 3 ) { System.out.print("This program will echo your "); System.out.println("name if you type it as"); System.out.println("three command-line arguments."); System.exit(0); } // ifAnother way to accomplish the same result would be with a return statement:
if ( args.length < 3 ) { System.out.print("This program will echo your "); System.out.println("name if you type it as"); System.out.println("three command-line arguments."); return; } // ifSystem.exit(0) makes the entire program quit, whereas return makes just the individual method quit. Since the method happens to be the main method and the program has only one thread, the two statements are equivalent in this case.
- Strings in Java (vs. C++)
In C++, there are two kinds of strings:
- C-strings,
arrays of characters terminated by a null character.
- Objects of the string class
in the C++ library.In Java, it is assumed that all strings will be objects of Java library class String. You can still create null-terminated arrays of characters if you want to; but, in Java, there are no standard library routines to handle null-terminated arrays of characters as strings.
In C++, the command-line arguments are C-strings (arrays of characters), and so too are string literals (strings hard-coded into a program, enclosed in quote marks). In Java, string literals and the command-line arguments are both objects of class String.
In the two programs we looked at previously, observe the use of plus signs ("+") for String concatenation:
String name; name = args[0] + " " + args[1] + " " + args[2]; System.out.println("Hello, " + name + ".");Concatenation means the joining of two or more strings together to form one string.
- Some instance methods of class String
In a DOS (Command Prompt) window, after first making sure that it is looking at the directory containing the example programs for this tutorial, compile StringMethodsDemo.java by typing:
javac StringMethodsDemo.javaand run it by typing:
java StringMethodsDemoThis program calls several instance methods of class String. First it calls the length method, which tells us the number of characters in a string. In our present example, the length method is called for String object text within the heading of a for loop:
for ( int i = 0; i < text.length(); i++ )The length method is an instance method because it is called for a specified individual String object, in this case text. Note that the length of one string may be different from the length of another string.
Note that when you call the length method of a String object, the word "length" is always followed by an empty pair of parentheses, because method calls always contain parentheses. On the other hand, in our previous example, the length of the array of command-line arguments was denoted args.length, with no parentheses, because the length of an array is NOT obtained via a method call. An array is not an object defined by a class. To determine the length of any array, simply use an expression of the form b>arrayName.length, without parentheses.
Back to our example program. Within the body of the for loop, there is a call to the charAt method to access individual characters in the string:
for ( int i = 0; i < text.length(); i++ ) if ( text.charAt(i) == 'e' ) ecount++;Note that the charAt method is another instance method. It takes an argument of type int and returns a value of type char. The argument is the index of a location within the String object, and the returned value is the character stored at that location.
In C++, one can use array-like notation to access characters in a string object. For example, if text were a C++ string object, the character at location i could be accessed using the expression text[i]. However, Java does not have operator overloading, a C++ feature which allows the programmer to define behaviors of objects using operators. In Java, behaviors of objects are defined ONLY vis methods, not via operators. (The one exception is string concatenation, which, as we have seen, can be done using the plus sign.) Therefore, in Java, we don't use square brackets for indices of locations in String objects. Instead, we must use a method for that purpose, namely the charAt method.
The following statement uses the substring method to obtain a substring consisting of the first five characters in the original string:
System.out.println("The first five characters are: " + text.substring(0, 5));The arguments 0 and 5 mean that the substring will consist of 5 consecutive characters beginning at index 0 in the string text.
The following statement uses the toUpperCase method to obtain an uppercase version of the original string:
System.out.println("Uppercase version: " + text.toUpperCase());Note the syntax of a call to an instance method:
objectName.methodName(arguments)whereas a call to a static method has the following syntax:
ClassName.methodName(arguments)To make it easier to tell these apart, it is recommended that you follow the convention that class names always begin with capital letters, whereas variable names, including object names, begin with lowercase letters. The compiler does not enforce this, but it's a commonly accepted style standard among Java programmers.
- JOptionPane Dialog boxes
We have seen one way to input strings in Java, namely via command-line arguments. In Java, we can input strings in many other ways too.
Let's now look at a program which inputs strings via dialog boxes. Compile JOptionPaneDemo.java and run it (without any command-line arguments). It will pop up dialog boxes asking for your first and last name and will then pop up another dialog box which says hello to you. After you click "OK" on that final dialog box, the program quits.
The two input dialog boxes are popped up via calls to showInputDialog, a static method of class JOptionPane in the Java library:
String firstName = JOptionPane.showInputDialog(null, "What is your first name?" ); String lastName = JOptionPane.showInputDialog(null, "What is your last name?" );And then the final dialog box, which says "Hello" to the user, is popped up via a call to showMessageDialog, another static method of class JOptionPane:
JOptionPane.showMessageDialog(null, "Hello, " + firstName + " " + lastName + ".");Note the syntax for calling a static method:
ClassName.methodName( arguments )The program ends with a call to exit, a static method of class System:
System.exit( 0 ); // terminate the programYou might be wondering why do we need a call to exit, since we have reached the end of the program anyway. The reason for this is backward compatibility with older versions of Java, in which, without the call to exit, a program using JOptionPane would NOT stop running after you close the last dialog box. Instead, your DOS window would appear to be frozen, requiring the user to type [Ctrl]-C to un-freeze it.
At the top of the program, note the following import statement:
import javax.swing.JOptionPane;This allows the compiler to access class JOptionPane in the javax.swing package in the Java library. You can think of import statements as being somewhat like include statements in C++, though they are not exactly the same in terms of what they do. (Details will not be discussed here.)
Some very frequently-used Java library classes, such as String and System, are automatically accessible in every Java program, even without an explicit import statement. These classes are in Java library package java.lang, which is imported automatically into every Java program. Thus our previous programs did not need an import statement.
- Inputting numbers
So far, we have seen two ways to input strings of characters. What if we want to input numbers into variables of numeric data types such as int or float?
Compile IntDivision.java and run it, entering two integers as command-line arguments. This program performs integer division. The two command-line arguments, which are objects of class String, are converted to int values using the static parseInt method of class Integer, which is defined in the java.lang package in the Java library:
int dividend = Integer.parseInt(args[0]); int divisor = Integer.parseInt(args[1]);The parseInt method takes an argument of type String and returns a value of type int. It does not matter where the String argument comes from. In the above case, the strings are command-line arguments. But they could have come from somewhere else, such as a JOptionPane dialog box.
Look now at FloatDiv.java, which demonstrates floating-point division and inputs the numbers using JOptionPane dialog boxes. The JOptionPane dialog boxes input strings as follows:
// read in first number from user as a string String dividendText = JOptionPane.showInputDialog( "Enter dividend (floating-point)" ); // read in second number from user as a string String divisorText = JOptionPane.showInputDialog( "Enter divisor (floating-point)" );and then the strings are converted to numeric values of type float as follows, using the static parseFloat method of the Float class in the java.lang package in the Java library::
float dividend = Float.parseFloat( dividendText ); float divisor = Float.parseFloat( divisorText );The parseFloat method takes a string as an argument and returns a float value.
- Console input
In C++, you are probably accustomed to doing input using cin, which performs interactive input in the console window. (Alternatively, you might have used the C library function scanf for this purpose.)
The nearest equivalent thing in Java (especially Java 1.4 and earlier) is a bit complicated. To simplify it somewhat, we have created for you the file ConsoleInput.java, containing class ConsoleInput, which contains some static methods you can use for relatively simple input from the console.
Note that class ConsoleInput does not contain a main method and thus is not a program. Nor does class ConsoleInput define behaviors of objects. It just contains some routines you can use for inputting strings typed by the user in the console window.
One of the static methods of class ConsoleInput is readline, which reads a line of text typed by the user and returns it as an object of class String. For an example of its use, see ConsoleInputTest.java, in which readLine is called in three different parts of the program:
andSystem.out.print("Enter a line of text:>"); String line = ConsoleInput.readLine();andSystem.out.print("Enter an integer:>"); int number1 = Integer.parseInt(ConsoleInput.readLine());System.out.print("Enter a floating-point number:>"); float number2 = Float.parseFloat(ConsoleInput.readLine());Observe that each call to readLine is preceded by a System.out.print statement in order to prompt the user.
Another of the static methods of class ConsoleInput is ask, which both (1) prompts the user and then (2) returns, as a String object, the line of text typed by the user. Because it combines these two tasks, there is no need for the call to ask to be preceded by a separate System.out.print statement to prompt the user. For an example of a program using the ask method, see DoubleDiv.java, which also exemplifies the use of the parseDouble method of class Double in the java.lang package in the Java library.
To enable you to use methods of class ConsoleInput in your program, all you must do is put a copy of the file ConsoleInput.java in the same directory where your program file is. Then, when you compile a program that uses class ConsoleInput, the file ConsoleInput.java will automatically be compiled too.
Note that you do NOT need to use an import statement for class ConsoleInput. The Java compiler can automatically find any class defined in any *.java file in the same directory as your program file.
For now, you are NOT expected to understand how any of the methods of class ConsoleInput work. For now, you are expected only to learn how to use two of the methods og class ConsoleInput, namely the readLine and ask methods.
- Wrapper classes for the primitive data types
You have seen examples of the use of static methods of classes Integer, Float, and Double. These classes are known as wrapper classes for the primitive data types int, float, and double, respectively. The wrapper classes contain methods which perform various common tasks involving the corresponding primitive data types.
There is also a wrapper class Character for the primitive data type char. However, there is no parseChar method. Instead, individual characters in a string must be accessed via the String object's charAt method. If the string contains only one character, use the charAt method to access the character at location 0 in the string.
- Some advantages of Java syntax
The Java compiler is in many ways stricter than a C++ compiler. Java's rules of syntax are in various ways stricter than the rules of C++ syntax. Java's rules are designed to prevent some of the most common programming errors in C++, resulting in fewer hard-to-debug runtime errors.
One difference is that Java has strong typing, meaning that a Java compiler is stricter than a C++ compiler about allowing automatic conversions from one data type to another. For example, the C++ compiler allows if statements with conditions like the following, as examplified below:
if ( x = 3 ) doWhatever();Most likely, the programmer meant to type the following:
if ( x == 3 ) doWhatever();C++ allows an assignment expression such as x = 3 (with a single equals sign) as the condition of an if statement, because (1) the assignment expression is itself an expression with a numeric value (in this case 3), and (2) numeric values in C++ convert automatically to boolean values, where zero represents "false" and any nonzero value is considered to represent "true."
On the other hand, Java does not allow conversion from numeric data types to boolean. Thus, a numeric assignment is not allowed as a condition.
Another example of Java's strictness is the program Compare3.java, which does not compile, whereas the very similar C++ program compare3.cpp does compile but contains a very subtle, hard-to-debug runtime error.
Both programs attempt to find the largest of three numbers of type float. Both contain the following code:
// Find the largest of the first two numbers: float largest; if ( number1 > number2 ) largest = number1; if ( number1 < number2 ) largest = number2; // Find the largest of all three numbers: // by comparing the third number to the // largest of the first two: if ( number3 > largest ) largest = number3;In C++, this program works most of the time, except for some cases when the first two numbers are equal. In that case, largest is not assigned a value in either of the first two if statements. Thus, largest still contains garbage, i.e. whatever was sitting there in memory before the program began. So the third if statement compares number3 to garbage, with unpredictable results.
In C++, the runtime error can be eliminated by ensuring that the equality case is covered by one of the first two if statements. For example, the second if condition could be modified as follows:
if ( number1 <= number2 )But this still wouldn't compile in Java. In your collection of example files, try to compile Compare3.java. Observe the resulting error message.
Note that the meaning of the word "initialization" is different in C++ and Java. In C++, to initialize a variable means to combine a declaration and assignment of the variable in one statement, such as the following:
int n = 10;On the other hand, in Java, to initialize a variable means simply to give the variable its first value, regardless of whether this is done in the same statement as the declaration.
The Java compiler is very fussy about ensuring that a variable is initialized (given their first value) before the variable is used in any way which assumes that the variable already has a value. Thus, for example, the Java compiler requires that the variable largest must have been given a value, in all possible cases, before largest is compared to another value.
However, the Java compiler ensures this only by looking at the structure of the program. It does not look at the details of conditions to ensure that every possible case is covered. Thus, although the above-described fix to our C++ program does ensure that the first two if statements do assign a value to largest in every possible case, the Java compiler does not recongnize this.
In Java, one way to fix the problem would be by replacing the first two if statements with an if/else statement, as follows:
// Find the largest of the first two numbers: float largest; if ( number1 > number2 ) largest = number1; else largest = number2; // Find the largest of all three numbers: // by comparing the third number to the // largest of the first two: if ( number3 > largest ) largest = number3;Note that an else automatically covers every possible case that is not covered by the corresponding if. Hence, by assigning largest a value in each branch of the if/else statement, you can thereby assure that it receives a value in every possible case. The Java compiler recognizes this.
Another possible fix is the following:
// Find the largest of the first two numbers: float largest = number1; if ( number2 > largest ) largest = number2; // Find the largest of all three numbers: // by comparing the third number to the // largest of the first two: if ( number3 > largest ) largest = number3;Initializing a variable as soon as it is declared is another way to ensure that it has a value in every possible case.
- Floating-point literals, and integer vs. floating-point division
Compile AverageOf3.java and run it using three command-line arguments as follows:
java AverageOf3 3 4 6The program gives an incorrect average of the three numbers as 4.0. The problem is that the following statement performs integer division instead of the desired floating-point division:
average = (number1 + number2 + number3) / 3;Integer division is the kind of division you were taught first in elementary school before you were taught about fractions and decimal places. Integer division yields an integer quotient and a remainder. For an example of how to obtain both the integer quotient and the remainder, see IntDivision.java On the other hand, floating-point division is the kind of division you have used most often since elementary school, where the quotient has both an integer part and a fractional part, usually written as a single number using a decimal point.
In both C++ and Java, the division operator (/) can perform either integer division or floating-point division, depending the kinds of values on each side. If the expressions on both sides of the slash have integer values, then the division operator performs integer division. If at least one of the expressions immediately next to the slash has a floating-point value, then the division operator performs floating-point division.
So, we must fix the above statement so that there is an expression of type float on at least one side of the slash. One way is by casting (number1 + number2 + number3) to type float:
average = (float) (number1 + number2 + number3) / 3;Another way is to change the 3 from an integer literal to a floating-point literal. In C++ this would be done as follows:
average = (number1 + number2 + number3) / 3.0;This doesn't work in Java. In Java, a literal containing a decimal point is assumed by the compiler to be of type double, not float, and is therefore not allowed to be assigned to a variable of type float. So that the Java compiler will recognize a numeric literal as being of type float, we must put a lowercase f after it, as follows:
average = (number1 + number2 + number3) / 3.0f;In general, the Java compiler tends to be fussier about data types and data type conversions than the C++ compiler is. Java is a strongly typed language, whereas C++ is more weakly typed.
- More about characters and strings in Java
Compile CharactersInString.java and run it by typing:
java CharactersInStringThis program lists the Unicode values of characters. Unicode is a way of representing characters in memory using 16 bits per character, allowing a total of 65536 possible different characters. Java uses Unicode (16 bits) to represent characters, whereas C++ uses bytes (8 bits), in which only 256 possible different characters can be stored. In Unicode it is possible to represent characters in many different languages, including thousands of Chinese characters. The first 256 characters are the ISO Latin characters, of which the first 128 characters are the ASCII characters.
This program calls two instance methods of class String: the length method, which tells us the number of characters in the string, and the charAt method, which tells us what character is at a given location within the string. The length method is called for String object text within the heading of a for loop:
for ( int i = 0; i < text.length(); i++ )Within the body of the for loop, there is a call to the charAt method to access individual characters in the string:
char x = text.charAt(i);This program also calls a static method, the toString method of class Integer:
String positionText = Integer.toString(i);As mentioned in earlier sections of this tutorial, class Integer contains methods that perform various routine chores involving the primitive data type int. For example, the toString method gives us the String representation of an int value.
CharactersInString.java displays the characters in only one specific hard-coded string. A more flexible program is CharactersInString2.java, which displays the characters in a string that has been entered as a command-line argument.
Compile CharactersInString2.java and run it. First, run it without command-line arguments. Then try running it with a command-line argument containing more than 15 characters. Then run it with a single command-line argument containing no more than 15 characters, as instructed by the message you saw the previous two times you ran the program.
The program begins with the following if block:
if ( args.length == 0 || args[0].length() > 15 ) { System.out.println("This program displays Unicode values " + "of characters in a single"); System.out.println("command-line argument no more than " + "15 characters long."); System.exit(0); } // if user errorLook at the condition of the if block. Note that the double vertical bar (|| means "or." The condition is true if at least one of the following is true: (1) the user did not type a command-line argument (hence the length of the array of command-line arguments is zero), or (2) the command-line argument contains more than 15 characters.
Note that args is an array, whereas args[0] is an element in that array. Recall that, in Java, the command-line arguments are objects of class String. Thus, args is an array of String objects, and args[0] is an individual String object.
Note the further difference between the expressions args.length (without a pair of parentheses at the end) and the expression args[0].length() (with a pair of parentheses at the end). Because args[0] is an object of class String, its length (i.e. number of characters) can be determined by calling the length method, hence the parentheses. On the other hand, one does not call a method to determine the length of an array, because an array is not an object defined by a class.
Compile ClassifyChar1.java and run it, and look at its source code. Run it using a single command-line argument between 1 and 15 characters long, where the characters are of various kinds including uppercase letters, lowercase letters, digits, punctuation marks, and control characters (gotten, for example, by holding down the Ctrl key while typing some letter). This program displays a listing of the characters and indicates whether each character is an uppercase letter, a lowercase letter, a digit, or a nonalphanumeric character. The classification is done using appropriate static methods of class Character, the wrapper class for the primitive data type char. Note that the isUpperCase method will recognize an uppercase letter in any of the many languages that can be represented in Unicode, not just English. Similarly the isLowerCase method will recognize a lowercase letter in any language, and likewise the isDigit method will recognize a digit in any language.
Compile ClassifyChar2.java and run it, and look at its source code. This program also classifies characters, but in a different way. All non-ASCII charaters are lumped into one category. Only the ASCII characters are classified as letters, digits, punctuation marks, control characters, etc.
To generate a non-ASCII character, hold down the [Alt] key while typing a number between 128 and 255 using the numeric keypad.
ClassifyChar2.java is similar to ClassifyChar1.java except that it (1) tests the values of characters directly rather than by using methods of class Character, and (2) tests for letters and digits only within the ASCII range. Unlike the isLetter and isDigit methods of class Character, ClassifyChar2.java does NOT test for letters and digits in the many non-English languages represented in the Unicode character set.
The ASCII codes for the uppercase letters are consecutive and in alphabetical order. Thus, an ASCII (English) uppercase letter can be recognized via the following boolean expression:
x >= 'A' && x <= 'Z'where x is a variable of type char. Likewise the ASCII codes for the lowercase letters are consecutive and in alphabetical order too, so that an ASCII lowercase letter can be recognized as follows:
x >= 'a' && x <= 'z'An ASCII letter is either uppercase or lowercase. Thus, an ASCII letter can be recognized by the following boolean expression:
(x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z')which is used as a condition in one branch of the nested if/else in our example program.
Similarly, ASCII digits can be recognized as follows:
x >= '0' && x <= '9'The programs ClassifyChar3.java and ClassifyChar4.java are similar to ClassifyChar2.java except that they use console input and dialog boxes rather than a command-line argument. With console input or a dialog box, the entered string can include spaces, which are not allowed as part of a command-line argument since the command-line arguments are separated by spaces.