Number, String and Array

JavaJavaBeginner
Practice Now

Introduction

In Java and other object-oriented languages, objects are collections of related data that come with a set of methods. These methods operate on the objects, performing computations and sometimes modifying the object’s data. Here we introduce three simple but important Java built-in object types: Number, String and Array.

Number

Basically, we use primitive number types such as byte, int, double etc. However, sometimes we need to use objects instead of primitive data types. Java provides wrapper classes for primitive data types. They are Byte, Short, Long, Integer, Double, Float etc. A wrapper object can be converted back to a primitive data type. This process is called unboxing. The Number class is part of the java.lang package. Packages will be talked about later.

Following is a list of some of the common class methods that the subclasses of the Number class implement:

  • xxxValue(): Converts the value of this Number object to the xxx data type and returns it.
  • compareTo(): Compares this Number object to the argument.
  • equals(): Determines whether this Number object is equal to the argument.
  • valueOf(): Returns an Integer object holding the value of the specified primitive.
  • toString(): Returns a String object representing the value of a specified int or Integer.
  • parseInt(): This method is used to get the primitive int type from a certain String value.
  • abs(): Returns the absolute value of the argument.
  • ceil(): Returns the smallest integer that is greater than or equal to the argument. Returned as a double.
  • floor(): Returns the largest integer that is less than or equal to the argument. Returned as a double.
  • pow(): Returns the value of the first argument raised to the power of the second argument.
  • round(): Returns the long or int closest, as indicated by the method's return type, to the argument.

Example:

Write the following code in the /home/labex/project/numberTest.java file:

public class numberTest
{
    public static void main(String[] args){
        Integer x = 1;    // boxes int to an Integer object
        x = x + 1;        // unboxes the Integer to an int
        System.out.println(Integer.parseInt("10"));  // parse int from a string
        System.out.println( "x = " + x);
    }
}

Output:

Run the numberTest.java file using the following command:

javac /home/labex/project/numberTest.java
java numberTest

See the output:

10
x = 2

String

Strings are objects, so you might ask: “What is the data contained in a String object?” and “What are the methods we can invoke on String objects?” The components of a String object are characters. Not all characters are letters; some are numbers, some others are special symbols and the rest are other classes of characters. For simplicity, we call all of them characters. There are many string methods in String class, but we will use only a few of them. The rest can be referred to in the documentation at the official website.

Note: The String class is immutable, so once created a String object cannot be modified. If there is a necessity to make a lot of modifications to Strings of characters, then you should use StringBuffer and StringBuilder classes.

Following is a list of some of the common methods of the String, StringBuffer and StringBuilder classes:

  • char charAt(int index): The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
  • void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): Characters are copied from this string buffer into the destination character array dst.
  • int indexOf(String str): Returns the index within this string of the first occurrence of the specified substring.
  • int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
  • int lastIndexOf(String str): Returns the index within this string of the rightmost occurrence of the specified substring.
  • int lastIndexOf(String str, int fromIndex): Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
  • int length(): Returns the length (character count) of this string buffer.
  • String substring(int start): Returns a new String that contains a subsequence of characters currently contained in this StringBuffer. The substring begins at the specified index and extends to the end of the StringBuffer.
  • String substring(int start, int end): Returns a new String that contains a subsequence of characters currently contained in this StringBuffer.

Example:

Write the following code in the /home/labex/project/stringTest.java file:

public class stringTest
{
    public static void main(String[] args){
        String greeting = "Hello world!";
        String hello = new String("Hello !");
        System.out.println("greeting is: "+ greeting);
        System.out.println("hello is: "+ hello);
        System.out.println("length of greeting: " + greeting.length());
        System.out.println("first char of greeting: " + greeting.charAt(0));
        System.out.println("index of 'e' in hello: "+ hello.indexOf('e'));
        System.out.println("substring of greeting: "+ greeting.substring(6));  //substr: world

    }
}

Output:

Run the stringTest.java file using the following command:

javac /home/labex/project/stringTest.java
java stringTest

See the output:

greeting is: Hello world!
hello is: Hello !
length of greeting: 12
first char of greeting: H
index of 'e' in hello: 1
substring of greeting: world!

Array

An array structure is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of a single type. Instead of declaring individual variables, such as number0, number1,..., number99, you declare one array variable numbers and use numbers[0], numbers[1], ..., numbers[99] to represent individual variables. The first element of array is at an index of 0.

Following is a list of some of the common methods that arrays have:

  • public static int binarySearch(Object[] a, Object key): Searches the specified array for the specified value using the binary search algorithm. The array must be sorted prior to calling this method. This returns the index of the search key, if it is contained in the array; otherwise it returns (–(insertion point + 1)).
  • public static boolean equals(long[] a, long[] a2): Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. The same method could be used by other primitive data types (byte, short, int etc.) also.
  • public static void fill(int[] a, int val): Assigns the specified int value to each element of the specified array of ints. The same method could be used by other primitive data types (byte, short etc.) also.
  • public static void sort(Object[] a): Sorts the specified array of objects in ascending order according to the natural ordering of its elements. The same method could be used by primitive data types (byte, short, int etc.) also.

Example:

Write the following code in the /home/labex/project/arrayTest.java file:

public class arrayTest
{
    public static void main(String[] args){
        // you can use new to initialize an empty array.
        String[] nameArray1 = new String[5];
        // fill the empty nameArray1 items with same name "abc"
        java.util.Arrays.fill(nameArray1,"abc");
        // the for loop can also be used to iterate an Array
        for (String name:nameArray1){
            System.out.println(name);
        }
        // you can use some value to initialize the array.
        String[] nameArray2 = {"Candy", "Fancy", "Ann", "Ella", "Bob"};
        // you can get the length of the array
        System.out.println("Length of nameArray2: " + nameArray2.length);
        // you can get value by index
        System.out.println("The last item of nameArray2 is " + nameArray2[4]);
        // sort an array object
        java.util.Arrays.sort(nameArray2);
        System.out.println("Sorted nameArray2 by alphabet:");
        for(String name:nameArray2){
            System.out.println(name);
        }
    }
}

Output:

Run the arrayTest.java file using the following command:

javac /home/labex/project/arrayTest.java
java arrayTest

See the output:

abc
abc
abc
abc
abc
Length of nameArray2: 5
The last item of nameArray2 is Bob
Sorted nameArray2 by alphabet:
Ann
Bob
Candy
Ella
Fancy

Summary

Most of the tasks are to manipulate data like numbers and strings, so using Java built-in classes to perform the tasks is easy and efficient. For advanced usage, you can read official documentation.

Other Java Tutorials you may like