Share
Java Programming

Course Outline

Week 1
Week 2
Week 3
Week 4
Week 5
Week 6

Characters, Strings, and the StringBuilder

  • Manipulating Characters
  • Declaring and Comparing String Objects
  • Comparing String Values
  • Converting Strings to Numbers
Week 7
Week 8

SponsoredAdvertise

Explanations to week content

Manipulating Characters

 

The char data type is used to hold any single character—for example, letters, digits, and punctuation marks. In addition to the primitive data type char, Java offers a Character class. The Character class contains standard methods for testing the values of characters.

 

The methods that begin with “is”, such as isUpperCase(), return a Boolean value that can be used in comparison statements; the methods that begin with “to”, such as toUpperCase(), return a

character that has been converted to the stated format.

 

Method Description
isUpperCase() Tests if character is uppercase
toUpperCase() Returns the uppercase equivalent of the argument; no change is made if the argument is not a lowercase letter
isLowerCase() Tests if character is lowercase
toLowerCase() Returns the lowercase equivalent of the argument; no change is made if the argument is not an uppercase letter
isDigit() Returns true if the argument is a digit (0−9) and false otherwise
isLetter() Returns true if the argument is a letter and false otherwise
isLetterOrDigit() Returns true if the argument is a letter or digit and false otherwise
isWhitespace() Returns true if the argument is whitespace and false otherwise; this includes the space, tab, newline, carriage return, and form feed

 

To use any of the above methods, you have to call the method in the Character class. Thus to use the isUpperCase() method, you have to write, Character.isUpperCase(). All the methods starting with the is….returns true or false hence we use the if condition to check if it is true or not.

 

Using The Above Methods

 

Write a program that asks the user to enter a character. Your program should display whether the character is an upper case or not, is a lower case or not, is a digit or not, is a letter or not, is a letter or digit or not and is a white space or not.

 

NOTE: 


The string method charAt is used to get the entered character. The data that is taken from the user is a String and the character is retrieved using the charAt(0) method of the String class.

 

Main.java


import java.util.Scanner;

public class Main
{

      public static void main(String[] args) {


            // TODO Auto-generated method stub

            String data;

            System.out.println("Enter a character");

            Scanner input = new Scanner(System.in);
            //Get the entered string

            data = input.nextLine();

            //Get the character at the 0 index

            char aChar = data.charAt(0);

            //Check the character

            if(Character.isUpperCase(aChar)){
                  System.out.println(aChar+ "is an upper case");
            }else{
                  System.out.println(aChar+ " is not an upper case");
            }
            if(Character.isLowerCase(aChar)){
                  System.out.println(aChar+ " is a lower case");

            }else{

                  System.out.println(aChar+ " is not a lower case");
            }
            if(Character.isDigit(aChar)){
                  System.out.println(aChar+ " is a digit");
            }else{
                  System.out.println(aChar+ " is not a digit");
            }
            if(Character.isLetter(aChar)){
                  System.out.println(aChar+ " is a letter");
            }else{
                  System.out.println(aChar+ " is not a letter");
            }
            if(Character.isWhitespace(aChar)){
                  System.out.println(aChar+ " is a white space");
            }else{
                  System.out.println(aChar+ " is not a white space");

            }
      }
}



Write a program that takes a character and converts the character to a lowercase and an uppercase.


Main.java


import java.util.Scanner;

public class Main
{
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            String data;
            System.out.println("Enter a character");
            Scanner input = new Scanner(System.in);
            //Get the entered string
            data = input.nextLine();
            //Get the character at the 0 index
            char aChar = data.charAt(0);
            System.out.println(aChar+" to upper case will be :"+Character.toUpperCase(aChar));
            System.out.println(aChar+" to lower case will be :"+Character.toLowerCase(aChar));
      }
}


Declaring and Comparing String Objects

 

A sequence of characters enclosed within doublequotation marks is a literal string.

 You can create a String object by using the keywordnew and the String constructor, just as you would create an object of any othertype.

 For example, the following statement defines an objectnamed aGreeting, declares it to be of type String, and assigns an initial valueof “Hello” to the String:

 

String aGreeting = new String("Hello");

 

This is the same as:


String aGreeting = “Hello”;

 

Comparing String Values

 

In Java, String is a class, and each created String is a class object. A String variable name is a reference; that is, a String variable name refers to a location in memory, rather than to a particular value.

 The distinction is subtle, but when you declare a variable of a basic, primitive type, such as int x = 10;, the memory address where x is located holds the value 10. If you later assign a new value to x, the new value replaces the old one at the assigned memory address. For example, if you code x = 45;,then 45 replaces 10 at the address of x.

 

In contrast, when you declare a String, such as String aGreeting = "Hello";,aGreeting does not hold the characters “Hello”; instead it holds a memory address where the characters are stored.

 

Because String references hold memory addresses, making simple comparisons between them often produces misleading results.


When you compare Strings with the == operator, you are comparing their memory addresses, not their values.

 

Furthermore, when you try to compare Strings using the less-than ( < ) or greater-than ( > ) operator, the program will not even compile.

 

Fortunately, the String class provides you with a number of useful methods. The String class equals() method evaluates the contents of two String objects to determine if they are equivalent. The method returns true if the objects have identical contents.

 

String Methods

 

Method Description
equals() Returns true if the objects have identical contents.
equalsIgnoreCase() Returns true if the objects have the same text and ignores case when determining if two Strings are equivalent
length() Returns the length of the string
charAt() Returns the character at the index specified in the argument
endsWith() Returns true if the String ends with the text passed in the argument
startsWith() Returns true if the String starts with the text passed in the argument
replace() allows you to replace all occurrences of some character within a String.
toString It converts any object to a String.
substring() Use to extract part of a String. takes two integer arguments—a start position and an end position—that are both based on the fact that a String’s first position is position zero
contains() Returns true if a String contains the text passed in the argument
isEmpty() Returns true if a String is empty
append() Takes in a string and add to the String object

 

You also can use concatenation to convert any primitive type to a String. You can join a simple variable to a String, creating a longer String using the + operator.

 

Example


int age = 25;

 

String sAge = “”+age;

 

Alternatively

 

String sAge = age.toString();

 

Example

 

Write an application to ask a user to enter his/her gender. If a user enters female, display You play ampe else if the user enters male, display You play football. The application should work irrespective of the cases the user used to enter the gender. Thus for a female for instance, if a user enters Female or fEmAle or FEMALE etc it should still display You play ampe. If the user enters any other text, display Incorrect gender

 

Main.java


import java.util.Scanner;

public class Main
{

      public static void main(String[] args) {
            // TODO Auto-generated method stub
            String gender;
            System.out.println("Enter your gender");
            Scanner input = new Scanner(System.in);
            //Get the entered string
            gender = input.nextLine();
            if(gender.equalsIgnoreCase("female")){
                  System.out.println("You play ampe");
            }else if(gender.equalsIgnoreCase("male")){
                  System.out.println("You play football");
            }else{
                  System.out.println("Incorrect gender");
            }
      }
}


Alternatively, you can convert the enteredstring to a lower case and compare to the lowercase of the genders using theequals method. You can as well convert the entered string to an upper case andcompare to the uppercase of the genders using the equals method.

 

Main.java


import java.util.Scanner;

public class Main
{
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            String gender;
            System.out.println("Enter your gender");
            Scanner input = new Scanner(System.in);
            //Get the entered string
            gender = input.nextLine();
            if(gender.toLowerCase().equals("female")){
                  System.out.println("You play ampe");
            }else if(gender.toUpperCase().equals("MALE")){
                  System.out.println("You play football");
            }else{
                  System.out.println("Incorrect gender");

            }
      }

}


CONVERT STRING TO NUMBERS

 

For int number we use Integer.parseInt(String variable to convert to number ) and for double we use Double.parseDouble(String variable to convert to number)


USING JOptionPane for input


To use the JOptionPane, you have to import the javax.swing.JOptionPane class.

 

To get the input from a user, you will usethe method showInputDialog which takes the arguments the parentcomponent and the String object to describe what the input is about. The parent component can be null.

 

e.g String name =JOptionPane.showInputDialog(null,”Enter your name”);

 

The showMessageDialog also displays themessage in a dialog. It also takes the arguments, the parentcomponent and themessage String.

 

e.g JOptionPane.showMessageDialog(null,”Welcome To Java Programming”);


Integer Example


Write a program that takes the age of a user using the JOptionPane dialog box. If the user is 18 and above, display your age is .... You are an adult so you can drink. Otherwise display your age is .... You are not an adult so you can't drink


Solution


import javax.swing.JOptionPane;
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        String sAge;
        sAge = JOptionPane.showInputDialog(null,"Enter your age");
        int age = Integer.parseInt(sAge);
        if(age>=18) {
        	JOptionPane.showMessageDialog(null,"You are "+age+" years old. You are an adult so you can drink");
        }else {
        	JOptionPane.showMessageDialog(null,"You are "+age+" years old. You are not an adult so you can't drink");
        }
	}
}


Double Example

 

Write a program that takes the total hoursworked in the month using the JOptionPane dialog box. The program shouldcalculate the salary for the month. The hourly rate is Ghc 8.5.

 

Solution

 

Main.java


import javax.swing.JOptionPane;

public class Main
{

      static final double HOURLY_RATE = 8.5;

      public static void main(String[] args) {
            // TODO Auto-generated method stub
            String hours;
            hours = JOptionPane.showInputDialog(null,"How many hours did you work this month?");
            double salary = Double.parseDouble(hours)*HOURLY_RATE;
            JOptionPane.showMessageDialog(null, "The salary for the " + hours + "hours at a rate of GHC " + HOURLY_RATE + " per hour" +"\n is GHC " + salary);
      }
}


ASSIGNMENT

 

Write an application that counts the total number of vowels contained in a String entered by the user.

 

Write a program that ask a user to enter an exams score using a dialogbox and grade the user using the Kings University Grading system and display the grade using a messagebox.

SponsoredAdvertise

Kuulchat Premium