Saturday, December 3, 2011

Java's character and assorted string classes support text-processing - 3


Character-oriented utility methods
Character serves as a repository for character-oriented utility methods. Examples of those methods include:
  • public static boolean isDigit(char c), which returns a Boolean true value if c's character is a digit. Otherwise, false returns.
  • public static boolean isLetter(char c), which returns a Boolean true value if c's character is a letter. Otherwise, false returns.
  • public static boolean isUpperCase(char c), which returns a Boolean true value if c's character is an uppercase letter. Otherwise, false returns.
  • public static char toLowerCase(char c), which returns the lowercase equivalent of c's character if it is uppercase. Otherwise c's character returns.
  • public static char toUpperCase(char c), which returns the uppercase equivalent of c's character if it is lowercase. Otherwise c's character returns.

The following code fragment demonstrates those five methods:
System.out.println (Character.isDigit ('4')); // Output: true
System.out.println (Character.isLetter (';')); // Output: false
System.out.println (Character.isUpperCase ('X')); // Output: true
System.out.println (Character.toLowerCase ('B')); // Output: b
System.out.println (Character.toUpperCase ('a')); // Output: A

Another useful utility method is Character's public static char forDigit(int digit, int radix), which converts digit's integer value to its character equivalent in the number system that radix specifies and returns the result. However, if digit identifies an integer less than zero or greater than or equal to radix's value, forDigit(int digit, int radix) returns the null character (represented in source code as Unicode escape sequence '\u0000'). Similarly, if radix identifies an integer less than Character's MIN_RADIX constant or greater than Character's MAX_RADIX constant, forDigit(int digit, int radix) returns the null character. The following code demonstrates that method:

Create Number counter in an Applet using Thread

package org.best.example;

    /*
            Create Number counter in an Applet using Thread Example
            This Java example shows how to create number counter using Java Thread and
            Applet classes.
    */
    
    
    import java.applet.Applet;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    
    /*
    <applet code = "UsingRepaintAndThreadExample" width = 500 height = 300>
    </applet>
    */
    
    /*
            Using paint() method we can draw strings, shapes or images.
            But when applets that use threads commonly need to update the display
            (ex. Animation or simulation).
          
            You cannot invoke the paint method directly to update the display.
            The reason is that the JVM schedules a number of important tasks. Updating
            the dispaly is one of these. The JVM decides when the screen can be updated.
          
            Therefore, your applet must invoke the repaint() method to request
            an update of the applet display. When the JVM determines that it is
            appropriate to perform this work, it calls the update method.
          
            The default implementation of the update() method clears the applet
            display with the background color and then invokes the paint() method.
    */    
    
    public class UsingRepaintAndThreadExample extends Applet implements Runnable{
            int counter;
            Thread t;
          
            public void init(){
                  
                    counter = 0;
                    t = new Thread(this);
                    t.start();
            }
          
            public void run(){
                  
                    try{
                          
                            while(true){
                                    repaint();
                                    Thread.sleep(1000);
                                    ++counter;
                            }
                    }
                    catch(Exception e){
                    }
            }
          
            public void paint(Graphics g){
                  
                    g.setFont(new Font("Serif",Font.BOLD,30));
                    FontMetrics fm = g.getFontMetrics();
                    String s = "" + counter;
                    Dimension d = getSize();
                    int x = d.width/2 - fm.stringWidth(s)/2;
                    int y = d.height/2;
                    g.drawString(s,x,y);
            }
    }

Friday, December 2, 2011

Basic Java Applet Example

package org.best.example;

    /*
            Basic Java Applet Example
            This Java example shows how to create a basic applet using Java Applet class.
    */
    
    import java.applet.Applet;
    import java.awt.Graphics;
    
    /*
            <applet code = "BasicAppletExample" width = 200 height = 200>
            </applet>
    */
    public class BasicAppletExample extends Applet{
          
            public void paint(Graphics g){
                    //write text using drawString method of Graphics class
                    g.drawString("This is my First Applet",20,100);
            }
    }

Java's character and assorted string classes support text-processing - 2


Character supplies three methods that compare Character objects for ordering or other purposes. The public int compareTo(Character anotherCharacter) method compares the contents of two Characters by subtracting anotherCharacter's value field from the current Character's value field. The integer result returns. If the result is zero, both objects are the same (based on the value field only). If the result is negative, the current Character's value is numerically less than the anotherCharacter-referenced Character's value. Finally, a positive result implies that the current Character's value field is numerically greater than anotherCharacter's value field. A second overloaded public int compareTo(Object o) method works the same as compareTo(Character anotherCharacter) (and returns the same result), but compares the current Character and the o-referenced object (which must be of type Character, or the method throws a ClassCastException object). compareTo(Object o) allows Java's Collections Framework to sort Characters according to natural order. (A future article will discuss that method, sorting, and natural order.) Finally, the public final boolean equals(Object o) method compares the contents of the value field in the current Character with the contents of the value field in o. A Boolean true value returns if o is of type Character and if both value fields contain the same contents. Otherwise, false returns. To see the compareTo(Character anotherCharacter) and equals(Object o) methods in action, examine the following code fragment:
 
Character c1 = new Character ('A');
Character c2 = new Character ('B');
Character c3 = new Character ('A');
System.out.println ("c1.compareTo (c2): " + c1.compareTo (c2));
System.out.println ("c1.equals (c2): " + c1.equals (c2));
System.out.println ("c1.equals (c3): " + c1.equals (c3));

System.out.println ("c1.compareTo (c2): " + c1.compareTo (c2)); outputs -1 because A is (numerically) less than B. System.out.println ("c1.equals (c2): " + c1.equals (c2)); outputs false because the Characters that c1 and c2 reference contain different characters (A and B). Finally, System.out.println ("c1.equals (c3): " + c1.equals (c3)); outputs true because, although c1 and c3 reference different Characters, both objects contain the same character (A).

Thursday, December 1, 2011

Applet Life Cycle

package org.best.example;

    /*
            Applet Life Cycle Example
            This java example explains the life cycle of Java applet.
    */
    
    import java.applet.Applet;
    import java.awt.Graphics;
    
    /*
     *
     * Applet can either run by browser or appletviewer application.
     * Define <applet> tag within comments as given below to speed up
     * the testing.
     */
    
    /*
    <applet code="AppletLifeCycleExample" width=100 height=100>
    </applet>
    */
    
    
    public class AppletLifeCycleExample extends Applet{
    
          
            /*
             * init method is called first.
             * It is used to initialize variables and called only once.
             */
            public void init() {
                    super.init();
            }
          
            /*
             * start method is the second method to be called. start method is
             * called every time the applet has been stopped.
             */
            public void start() {
                    super.start();
            }
          
            /*
             * stop method is called when the the user navigates away from
             * html page containing the applet.
             */
            public void stop() {
                    super.stop();
            }
          
            /* paint method is called every time applet has to redraw its
             * output.
             */
            public void paint(Graphics g) {
                    super.paint(g);
            }
          
            /*
             * destroy method is called when browser completely removes
             * the applet from memeory. It should free any resources initialized
             * during the init method.
             */
            public void destroy() {
                    super.destroy();
            }
    
    }

Java's character and assorted string classes support text-processing - 1


Explore Character, String, StringBuffer, and StringTokenizer
Text can represent a combination of digits, letters, punctuation, words, sentences, and more. Computer programs that process text need assistance (from their associated languages) to represent and manipulate text. Java provides such assistance through the Character, String, StringBuffer, and StringTokenizer classes. In this article, you'll create objects from these classes and examine their various methods. You'll also receive answers to three mysteries: why Java regards a string literal as a String object, why String objects are immutable (and how immutability relates to string internment), and what happens behind the scenes when the string concatenation operator concatenates two strings into a single string.
Note
Future articles will cover the Character, String, StringBuffer, and StringTokenizer methods that I omit in this discussion.

The Character class
Though Java already has a character type and char keyword to represent and manipulate characters, the language also requires a Character class for two reasons:
  1. Many data structure classes require their data structure objects to store other objects—not primitive type variables. Because directly storing a char variable in these objects proves impossible, that variable's value must wrap inside a Character object, which subsequently stores in a data structure object.
  2. Java needs a class to store various character-oriented utility methods—static methods that perform useful tasks and do not require Character objects; for example, a method that converts an arbitrary character argument representing a lowercase letter to another character representing the uppercase equivalent.

Character objects
The java.lang.Character class declares a private value field of character type. A character stores in value when code creates a Character object via class Character's public Character(char c) constructor, as the following code fragment demonstrates:
Character c = new Character ('A');

The constructor stores the character that 'A' represents in the value field of a new Character object that c references. Because the Character object wraps itself around the character, Character is a wrapper class.
By calling Character's public char charValue() method, code extricates the character from the Character object. Furthermore, by calling Character's public String toString() method, code returns the character as a String object. The following code, which builds on the previous fragment, demonstrates both method calls:
System.out.println (c.charValue ());
String s = c.toString ();

System.out.println (c.charValue ()); returns value's contents and outputs those contents (A) to the standard output device. String s = c.toString (); creates a String object containing value's contents, returns the String's reference, and assigns that reference to String variable s.