Java Wrapper class, Math, Character and String Class

  • Topic 1: Java Wrapper Class

    • The built-in primitive types are not objects, and they do not have methods. To bridge the gap between the built-in types and the objects, Java defines Wrapper Classes for each of the primitive types. The wrapper classes are objects encapsulating primitive Java types:

      • Autoboxing: Automatically converting primitive values to their matching wrapper class objects.

      • Unboxing: Converting an object of a wrapper type to its corresponding primitive value.

      • Primitive Type

        Wrapper Class

        boolean

        Boolean

        char

        Character

        byte

        Byte

        short

        Short

        int

        Integer

        long

        Long

        float

        Float

        double

        Double

  • Wrapper Class Examples

byte b = 100;
Byte bb = 100;
short s = 100;
Short ss = 100;
int i = 100;  // primitive data type
Integer ii = 100;  // literal method
Integer iii = new Integer(1000);  // new operator
long l = 100l;
Long ll = 100l;
float f = 100.0f;
Float ff = 21.24f;
double d = 546.32;
Double dd = 545.255;
char ch = 'a';
Character cha = 'a';
boolean bo = true;
Boolean boo = true;
  • Example - AutoBoxing and UnBoxing

  • The Character Class

    • Java provides a wrapper class named Character, which is an option for the variable's data type. The Character class object can hold a single character value just like a primitive char data type.

    • The Character class offers a number of useful methods for manipulating characters. All of the attributes, methods, and constructors of the Character class are specified by the Unicode Data file, which is maintained by the Unicode Consortium.

    • There are two ways to create a Character Class in Java:

      • Create a Character Literal: Character can be created by assigning a Character literal to a Character variable.

      • Use the new operator (Heap memory): JVM will create a new character object in normal (non-pool).

  • Example - Character and Char Data Type

    • In the below example, we are using both a Char primitive data type and a Wrapper class primitive data type.

  • Popular Methods in the Character Class

    • The Character class also provides several methods useful when manipulating, inspecting, or dealing with single-character data. Some popular methods of Character class are as follows:

    • Method

      Description

      isDigit(ch)

      Returns True if the specified character is a digit.

      isLetter(ch)

      Returns True if the specified character is a letter.

      isLetterOfDigit(ch)

      Returns True if the specified character is a letter or a digit.

      isLowerCase(ch)

      Returns True if the specified character is a lowercase letter.

      isUpperCase(ch)

      Returns True if the specified character is an uppercase letter.

      toLowerCase(ch)

      Returns the lowercase of the specified character.

      toUpperCase(ch)

      Returns the uppercase of the specified character.

      valueOf()

      valueOf(String s),

      valueOf(String s, int radix)

      The valueOf method returns the relevant Number Object holding the value of the argument passed. The argument can be a primitive data type, string, etc.

  • Example - Methods in the Character Class

    • This example demonstrates how to use, declare, and initialize data type as character type using Character Class.

public class characterclassdemo {
   public static void main(String[] args) {
       Character letter = 'A';
       System.out.println(letter);
       Character asciNumber = 97;
       System.out.println(asciNumber);
       Character uninumber = '\u0031';
       Character uninumber2 = '\u0032';
       System.out.println(uninumber);
       System.out.println(uninumber2);
       System.out.println("======compareTo========");
       Character Obj1 = '2';
       Character Obj2 = '2';
       int result =    Obj1.compareTo(Obj2);
       System.out.println(result);
       System.out.println("----equals() -------");
       boolean  result2 =    Obj1.equals(Obj2);
       System.out.println(result2);
       System.out.println("----isletter() -------");
       // isletter method determines wheather the specified char value is letter
       System.out.println(Obj1.isLetter(Obj2));
       System.out.println("----isDiggit() -------");
       // isDiggit() determin whether the specified char value is a digit
       System.out.println( Obj2.isDigit(Obj1));
       Obj1.valueOf('A');   // Obj1 = 'A'
       System.out.println("----compareTo-------");
       Character a = 'B';
       Character aa = 'B';
       System.out.println(a == aa);
       int rs =  a.compareTo(aa);
       System.out.println(rs);
   }}
  • Character Class - Escape Sequence

    • You cannot have a String literal break across lines. How do you include a line break?

      • Solution: An escape sequence is a two-character sequence that represents a single special character.

    • An escape sequence is a character preceded by a backslash (\), which gives a different meaning to the compiler. The following table shows the escape sequences in Java:

    • Escape Sequence

      Description

      Inserts a tab in the text at this point.

      \b

      Inserts a backspace in the text at this point.

      Inserts a new line in the text at this point.

      Inserts a carrier return in the text at this point.

      \f

      Inserts a form feed in the text at this point.

      \’

      Inserts a single quote character in the text at this point.

      \”

      Inserts a double quote character in the text at this point.

      \\

      Inserts a backslash in the text at this point.

  • Example: Escape Sequence

  • Overview of String Class

    • String is a sequence of characters. For example, “Hello” is a string of five characters.

    • String is immutable. An Immutable Object means that the state of the object cannot change after its creation. “String is immutable,” means that you cannot change the object itself, but you can change the reference to the object.

      • There are methods for inserting and replacing characters of a String, but these methods return a brand new String object and do not modify the String on which the method was called.

  • Initializing and Declaring Strings

    • There are two ways to create Strings in Java:

      • Using String Literal: Strings can be created by assigning a String literal to a String variable:

      • String s1 = “welcome”;

      • String s2 = “welcome”; //it does not create a new instance.

      • Each time we create a string literal, the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string does not exist in the pool, a new string instance is created and placed in the pool.

    • Using the new operator:

      • String s = new String(“welcome"); //creates two objects and one reference variable.

      • In such a case, JVM will create a new string object in normal (non-pool) heap memory, and the literal “welcome" will be placed in the string constant pool. The variables will refer to the object on the heap (non-pool). The String class defines multiple constructors.

    • Popular String Methods

      • Java String class provides various methods to perform different operations on Strings. We will look into some of the commonly used string operations.

    • Conversion From String to Number

      • We can use parseInt() and valueOf() methods for conversion.

    • Conversion From Number to String

      • A toString() is an in-built method in Java that returns the value given to it in a string format. Hence, any object that this method is applied to will be returned as a string object. The toString() method in Java has two implementations:

        • The first implementation is when it is called a method of an object instance. See the example below:

        • The second implementation is when you call the member method of the relevant class by passing the value as an argument. See the example below:

      • Advanced String Manipulation - StringBuffer

        • StringBuffer is a peer class of String that provides much of the functionality of strings.

        • StringBuffer class creates objects that hold a mutable sequence of characters.

        • Substrings are inserted anywhere in the StringBuffer.

        • StringBuffer class extends (or inherits from) Object class.

        • The String represents fixed-length, immutable character sequences, while StringBuffer represents growable and writable character sequences.

        • A String is immutable. If you try to alter its value, another object gets created. A StringBuffer is mutable so it can change its value.

    • StringBuffer - Constructors

      • new StringBuffer() → Creates an empty String buffer with the initial capacity of 16.

      • new StringBuffer​(int capacity) → Creates an empty String buffer with the specified capacity as length.

      • new StringBuffer​(String str) → Creates a String buffer with the specified string.

        • New StringBuffer(“Per Scholas”) → Room for given string and 16 additional characters.

    • Example One - StringBuffer

      • Create a class and add the code below to that class.

      • Example Two - StringBuffer

        • Create a class named StringbufferExampleTwo, and add the code below to that class.

      • Advanced String Manipulation - StringJoiner

        • StringJoiner is used to construct a sequence of characters separated by a delimiter; it optionally starts with a supplied prefix and ends with a supplied suffix.

        • Constructors.

          • New StringJoiner(“,”).

            • Creates StringJoiner that is comma-delimited (e.g., Mike, Bairon, and Erik).

          • new StringJoiner(“,”, “[“, “]”).

            • Creates StringJoiner that is comma-delimited, with each string surrounded by brackets (e.g., [Mike], [Bairon], [Erik]).

      • Example One - StringJoiner

        • Create a class named StringjoinnerDemoOne and add the code below to that class.

      • Example Two - StringJoiner

        • Create a class named StringjoinnerDemotwo and add the code below to that class.

      • Example Three - StringJoiner

        • Create a class named StringjoinnerDemothree and add the code below to that class.

      • Formatting Output on the Console

        • There are multiple ways to format Output in Java. Some of them are borrowed directly from old classics (e.g., printf from C), while others are more in the spirit of object-oriented programming (OOP).

        • Frequently used formatting ways include:

          • System.out.format().

          • System.out.printf().

          • String.format().

      • The printf() and format() Methods

        • Earlier, you saw the use of the print() and println() methods for printing strings to standard output (System.out). The Java programming language has other methods that allow you to exercise much more control over your print output when numbers are included. Those methods include:

          • System.out.printf(format, String... arguments);

          • System.out.format(format, String... arguments);

        • You can use format() or printf() anywhere in your code that previously used print or println.

        • Both methods are identical and behave similarly.

      • Examples One: format() Method Specifier

        • The Format Method Specifier expects at least one argument – the format string.

          • It can accept any number of additional arguments, and of any type.

          • The additional arguments are matched, in order to the format specifiers found within the format string.

          • The format specifiers must match the provided arguments; otherwise, an IllegalFormatException is thrown.

        • Examples Two: format() Method Specifier

          • This program shows some of the formatting that you can perform with format() methods.

          • The output is shown within the double quotes in the embedded comment:

        • Example One - printf() Method

          • If we have multiple printf() statements without a newline specifier:

        • Example Two - printf() Method

          • Create a new Java class and add the code below in that class:

        • Example Three - printf() Method

        • String.format() Method

        • Example - String.format()

        • Formatting Output on Console - DecimalFormat() Class

          • We often need to format numbers by taking two decimal places for a number or showing only the integer part of a number. Java provides a DecimalFormat class, which can help you to format numbers and use your specified pattern as quickly as possible.

          • DecimalFormat() class is actually designed to format any number in Java, be it integer, float or double.

        • Practice Problem: Monetary Units

          • Write a program that lets the user enter decimal dollars and cents, and outputs the monetary equivalent in single dollars, quarters, dimes, nickels, and pennies.

          • For example:

            Input: 3.87

            Output: 3 dollars

            3 quarters

            1 dime

            0 nickels

            2 pennies

public static void main(String[] args) {
    String money = "3.87";
    String[] moneyPart = money.split("\\.");
    int dollar = Integer.parseInt(moneyPart[0]);
    int rightPart = Integer.parseInt(moneyPart[1]);
    int quarter = rightPart / 25;
    int dim = rightPart % 25 / 10;
    int nickel = rightPart % 25 % 10 / 5;
    int pennie = rightPart % 25 % 10 % 5;
    System.out.println(dollar);
    System.out.println(quarter);
    System.out.println(dim);
    System.out.println(nickel);
    System.out.println(pennie);
}
  • Convert seconds to hh:mm:ss

public static void main(String[] args) {
    int second = 123456;
    int hour = second / 3600;
    int minute = second % 3600 / 60;
    int remainSecond = second % 3600 % 60;
    System.out.println(hour);
    System.out.println(minute);
    System.out.println(remainSecond);
}
  • The Math Class

    • Java provides many useful methods in the Math class for performing common mathematical functions.

    • Math class Methods Categories include:

      • Min, max, abs, and random methods.

      • Trigonometric methods.

      • Exponential methods.

      • Rounding methods.

    • We cannot create objects of the Java Math class because all of the variables and methods of Math class are ‘static.’

    • Math class contains two public static final variables, also called Constants:

      • PI.

      • E.

  • Example - Math Class Constant

    • The constants e and π are defined in the Math class.

    • By convention, names of constants are written in all uppercase: • Math.E and Math.PI

    • Create a class named MathDemo and write the code below in that class.

  • Overview of Min(), Max(), and Abs() Methods

  • Exponential and Logarithmic Methods

  • Example - Exponential Methods

  • Rounding Methods

    • The Math Class offers multiple methods to round off a number such as round(), ceil(), floor(), rint().

      • double ceil(double x).

        • x rounded up to its nearest integer. This integer is returned as a double value.

      • double floor(double x).

        • x is rounded down to its nearest integer. This integer is returned as a double value.

      • double rint(double x).

        • x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double.

      • int round(float x).

        • Return (int)Math.floor(x+0.5).

      • long round(double x).

        • Return (long)Math.floor(x+0.5).

  • Rounding Methods - Example One

    • Create a new class named “RoundingMethodDemo” and write the code below in that class.

public static void main(String[] args) {
  double d = 83.67;
  System.out.println(Math.ceil(d));  // return double & rounded up to its nearest integer
  System.out.println(Math.floor(d)); // return double and rounded down to its nearest integer
  System.out.println(Math.rint(d)); // return double but find the closest integers for these double numbers
  //Math.round() It is used to round of the decimal numbers to the nearest value.
  System.out.println(Math.round(d));  // 84; 
  double a = 1.878;
  System.out.println(Math.round(a));  // 2
  // value equals to 5 after decimal
  double b = 1.5;
  System.out.println(Math.round(b));  // 2
  // value less than 5 after decimal
  double c = 1.34;
  System.out.println(Math.round(c));  // 1
}
  • The Random Method

  • Example One: The Random Method

    • Create a new class named RandonMethodDemoOne and write the code below in that class.

      • This Java program will generate integer numbers between 1 to 100.

    • Example Two: The Random Method

      • Create a new class named RandonMethodDemoTwo and write the code below in that class.

        • Java program to generate number between 100 to 1000.

      • Trigonometric Methods

        • The Math class contains methods for trigonometric operations such as cos(), sin(), tan(), tanh(), cosh(), atan() and etc.

      • Knowledge Check?

        1. What are Wrapper Classes?

        2. What is Autoboxing and Unboxing?

        3. How do you declare a string in Java?

        4. Is String a primitive or derived type in Java?

        5. In Java, how can two Strings be compared?

        6. How can we convert char into a String?

      • Wrapper Classes: Wrapper classes in Java are classes that wrap the primitive data types such as int, double, boolean, etc. They provide a way to use primitive data types as objects. Wrapper classes are often used in situations where an object is required, for example, when using collections, generics, or reflection.

      • Autoboxing and Unboxing: Autoboxing is the automatic conversion of a primitive data type into its corresponding wrapper class. Unboxing is the reverse process of converting an object of a wrapper class to its corresponding primitive data type. Autoboxing and unboxing are automatically performed by the Java compiler, so you can write code that uses primitive types and wrapper classes interchangeably.

      • Declaring a String in Java: To declare a String in Java, you can use the following syntax:

        rustCopy codeString str = "Hello World";

        This creates a new String object with the value "Hello World" and assigns it to the variable str.

        • String buffer

        • new String

      • String as a primitive or derived type in Java: In Java, String is not a primitive data type. It is a derived data type or a class. String is a built-in class in Java that provides methods for working with strings of characters.

      • Comparing two Strings in Java: In Java, you can compare two strings using the equals() method, which compares the content of the strings, or the == operator, which compares the references to the strings. Here's an example:

        csharpCopy codeString str1 = "Hello";
        String str2 = "World";
        if (str1.equals(str2)) {
            System.out.println("The strings are equal.");
        } else {
            System.out.println("The strings are not equal.");
        }
      • Converting char to String in Java: To convert a char to a String in Java, you can use the valueOf() method of the String class, like this:

        rustCopy codechar c = 'a';
        String str = String.valueOf(c);

        This creates a new String object with the value "a" and assigns it to the variable str

Last updated