Reading:  

Quick introduction to Java Programming language - Part 1


Working with Characters and Strings

To work with characters, we normally use char of primitive data types. Char is used to store the single letter, it also supports for array.

Example:

char grade='b'; // an array of chars

char[] alphabetArray={'d','a','b','c','h'};

In some situations we need to use objects instead of primitive data types. To achieve this, Java has wrapper class Character for primitive type char.

We can create anobjectof Character:

Character ch=new Character('Z'); 

The Character class provides many useful class static methods for characters operation.

The Java compiler has the capability to create a Character object for under some circumstances. For example: if a primitive char is argument of a method which accepts an object, the java compiler converts automatically the char to a Character. This process is called unboxing.

* Information below is collected from oracle.com docs for Java SE

Escape Sequences

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The following table shows the Java escape sequences:

 
Escape SequenceDescription
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a formfeed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.

The compiler will interpret an escape sequence correctly when encountered in a print statement.

Here is an example to print a string with escape sequence characters

I said "Hi!".

Above string if you like to use in a program should be used as 

System.out.println("I said \"Hi!\".");

 

Character Methods:

Here is the list of the important instance methods that all the subclasses of the Character class implement:


Methods

Description

Parameter

Return Value

Syntax

toUpperCase()

To convert the given char into upper case form

Primitive character type

Returns the uppercase form of the given char value.

char toUpperCase(char name)
Example:

System.out.println(Character.toUpperCase('l'));//returns L
System.out.println(Character.toUpperCase('A'));//returns A 
isUpperCase()

To check the given char value is in Upper case form or not.

Primitive character type

Returns Boolean value True/False

booleanisUpperCase(char city)
Example:
System.out.println(Character.isUpperCase('a'));//returns False
System.out.println(Character.isUpperCase('A'));//returns True

toLowerCase()

To convert the given char into Lower case form

Primitive character type

Returns the Lowercase form of the given char value.

chartoLowerCase(charcityname)

Example:

System.out.println(Character.toLowerCase('T')); //returns t 
System.out.println(Character.toLowerCase('r')); //returns r 
isLowerCase()

To check the given char value is in Lower case form or not.

Primitive character type

Returns Boolean value True/False

booleanisLowerCase(char city)

Example:
System.out.println(Character.isUpperCase('a'));//returns True
System.out.println(Character.isUpperCase('A'));//returns False

isLetter()

To check the given char value is a letter or not.

Primitive character type

Returns Boolean value True/False

boolean isLetter(char a) 

Example:

System.out.println(Character.isLetter('6')); //returns False 
System.out.println(Character.isLetter('u')); //returns True 
toString()

Returns a String object representing the given character,one-character string.

Primitive character type

Returns String object

StringtoString(charch)

Example:

System.out.println(Character.toString('A'));//returns A
System.out.println(Character.toString('a'));//returns a
 
isWhitespace()

The method checks the given char is a white space, which includes space, new line or tab

Primitive character type

Returns Boolean value True/False

boolean isWhitespace(char name)
 
Example:
 
System.out.println(Character.isWhitespace(' ')); //returns True
System.out.println(Character.isWhitespace('a'));//returns False
 
 

 

isDigit()

To checks the given char is a digit or not.

Primitive character type

Returns Boolean value True/False
boolean isDigit(char city)
 
Example: 
System.out.println(Character.isDigit('8')); //returns True
System.out.println(Character.isDigit('a')); //returns False
 

 

String Class

Strings are a group of characters. In the Java language, strings are objects.Javaprovides the String class for creation and manipulation of strings

Creating Strings:

To create a string:

String msg="Java World!”;

Whenever there is a string literal in java code, the java compiler creates a String object with its value in this case, "Java World!'.

Similar to other objects, String object can be created by using new Keyword. The String class provides eleven constructors to give value of string from different source or array of characters.

public class DemoString{
   public static void main(String args[]){
		char[]ArrayExample = {‘J’,’A’,’V’,’A’};
		StringJavaString = new String(ArrayExample);  
		System.out.println(JavaString);
   }  
}

Output: JAVA

 

Some of String Methods:


Method Name

Example

char charAt(int index) 
Returns character at specified index.

public class Example {
   public static void main(String args[]) {
      String temp = "Java";
      char result = s.charAt(3);
System.out.println(result);
   }
}
OutPut : a

intcompareTo(Object o)
Compares two string objects. Return 0 if they are equal

public class Example {
   public static void main(String args[]) {
      String temp = "Java";
      String temp1 = "Java";
int result = temp.compareTo( temp1 );
System.out.println(result);
   }
}
Output : 0 

String concat(String str)
Concatenates specified string to end of string.

public class Example {
   public static void main(String args[]) {
      String s = "JAVA";
      s = s.concat("is good");
System.out.println(s);
   }
}
output:
JAVA is good 

int length() 
Returns length of string.

public class Example{
   public static void main(String args[]){
      String Str = new String("JAVA");    
System.out.println(Str.length());
   }
}
 
OUTPUT:
4 

char[] toCharArray() 
Converts string to  new character array

public class Example{
   public static void main(String args[]){
      String St = new String("JAVA");
System.out.println(St.toCharArray() );
   }
}
 
OUTPUT:
JAVA 

String trim()
Returns  copy of string removing whitespace leading and  trailing

public class Example{
   public static void main(String args[]){
      String Str = new String(" JAVA is good  ");
str = str.trim();      
System.out.println(str);     
   }
}
Output :
JAVA is good 

String toUpperCase()
Converts all characters in String to upper case

public class Example{
   public static void main(String args[]){
      String Str = new String("java");
str = str.toUpperCase();      
System.out.println(str);   
   }
}
Output :
JAVA 

String toLowerCase()
Converts all characters in String to lower case

public class Example{
   public static void main(String args[]){
   String Str = new String("JAVA");
str = str.toLowerCase();      
System.out.println(str);   
   }
}
Output :
java 

String replace(char oldChar, char newChar)
Returns a new string by replacing all occurrences of oldChar in string with newChar.

public class Example{
   public static void main(String args[]){
      String Str = new String("JAVA");
System.out.println(Str.replace('J', 'C'));   
   }
}
OUTPUT:CAVA 

String[] split(String regex) 
Splits string around matches of given regular expression.

public class Example{
   public static void main(String args[]){
      String Str = new String("JAVA is good");
        for (String retval: Str.split("-", 2)){
System.out.println(retval);
      }
   }
}
Output :
JAVA is
- good 

 

Description

This tutorial is targetted for beginers seeking a quick get on with guide on Java programming language. 3 parts include 

  1. Java basics
  2. Object oriented programming
  3. Advance concepts

Each part is subdivided in multiple chapters.

Java basics has the following chapters

  1. Introduction
  2. Environment Setup
  3. Basic Syntax
  4. Objects and Classes
  5. Basic Data Types
  6. Variable Types
  7. Modifier Types
  8. Basic Operators
  9. Loops
  10. Decision Making
  11. Numbers Class
  12. Character and String Class
  13. Arrays
  14. Date and Time
  15. Regular Expression
  16. Methods
  17. Streams, Files and I/O
  18. Exceptions Handling

Thanks for reading and as always, your feedback is very important to us. Let us know how we can improve and if you found any issues with this write up, send us a correction.



Audience

Beginners or students seeking a refresher on Java language

Author: Subject Coach
Added on: 9th Mar 2015

You must be logged in as Student to ask a Question.

None just yet!