Browse by Domains

Java Super Keyword and Wrapper Class

Introduction

Java is an object-oriented programming language that uses objects, classes and multiple keywords. One such is ‘super’ the name as it suggests means that a user creates a bridge between the child class and the parent class (superclass). Talking about Wrapper classes these are the classes that are specially designed to convert the primitive data types of java into objects and vice versa.

Super Keyword in Java

Prerequisites

Keywords are the reserved words of java that have a special meaning for them. There are 48 known keywords in java and one of them is super. There are two kinds of classes in java superclass and subclass. A class that is derived from another class is called a subclass or derived class. A class that is used to derive the subclass is known as a superclass or parent class.

What is the super keyword?

The super keyword is used in Java when the subclasses want to acquire the superclass members. When an instance of a base class is created, an instance of the superclass is created too which can be referred to by the super keyword. An instance follows the syntax:

 <object name> instance of <name of a class>

Why do we use the super keyword?

The following are some of the cases where we need to use super keyword:

1] Super keyword is used as a reference for the super class instance variable.

For example the following code:-

class Rainbow {                                                                                                                        
String color="Indigo";                                                                                                                         }                                                                                                                                                  
class Colorful extends Rainbow {                                                                                             
String color="Red";                                                                                                                 
void printColor() {                                                                           
System.out.println(color); // prints color of Colorful class   
System.out.println(super.color); // prints color of Rainbow class                                                 
}                                                                                                                                                        
}                                                                                                                                                       
class TestSuper1{                                                                                                                         
public static void main(String args[]){                                                                            
Colorful d=new Colorful();                                                                                       
d.printColor();                                                                                                                    
} 
}  

Output:

Red

Indigo

You may be wondering what is happening in the above example. Let me clear this. In the above example, Rainbow and Colorful both classes have a common characteristic color. If we print color property, it will print the color of the Rainbow class by default. To print for the Colourful class (base class) we need to access properties from the Rainbow class (superclass) using the keyword super.

2] Super keyword can also be used when we invoke a superclass method

For example the following code:-

class Rainbow{                                                                                                                        
void rain() 
{ System.out.println("raining..."); }                                                                                 
}                                                                                                                                              
class Colorful extends Rainbow {                                                                                              
void rain() {System.out.println("raining heavily...");}                                                           
void sun() {System.out.println("bright sun shining...");}                                                       
void work() {                                                                                                                   
super.rain();  // Calling super class method                                                                                                                        
sun();                                                                                                                                             
}                                                                                                                                                                                              
}                                                                                                                                                   
class TestSuper {                                                                                                                 
public static void main(String args[]){                                                                                            
Colorful d=new Colorful();                                                                                              
d.work();                                                                                                                                        
} }

Output:- 

raining . . .                                                                                                                 bright sun shining . . .                                                                                               

In this example Rainbow and Colorful both classes have rain() method if we call the rain() method from Colorful class, it will call the rain() method of Colorful class by default because priority is given to local. To call the superclass method, we need to use the super keyword. Only if the method is overridden super keyword is used.

3] Super keyword can also invoke a superclass constructor 

Following is the code:-

class Rainbow {                                                                     
Rainbow(){System.out.println("Rainbow is mesmerizing");}                                                                
}                                                                                                                                              
class Colorful extends Rainbow {                                                                                         
Colorful() {                                                                                                                           
super();  // invoking a super class constructor                                                                                               
System.out.println("Colors are amazing");                                                                                      
}  }                                                                                                                                             
class TestSuper {                                                                                                                                  
public static void main(String args[]){                                                                              
Colorful d=new Colorful();                                                                                                               
}                                                                                                                                                           
}

Output –

Rainbow is mesmerizing                                                                                               Colors are amazing

*Sometimes the compiler implicitly adds super( ) to our code.

Wrapper Classes in Java  

Prerequisites

Primitive data types: These are the inbuilt data types that serve as the basic types for the derived (reference types). For example byte, int, float, short, boolean etc.

What is wrapper class?

The wrapper class converts the primitive data type into objects. Some of the wrapper classes are Byte, Short, Integer, Long, Float, Double, Character and Boolean. Primitive data types are themselves wrapped up by java classes. Such classes are called Wrapper classes or type wrappers. It is helpful in creating objects of these classes that will be similar to the primitive data types. This concept is also termed autoboxing or boxing and the reverse of this is unboxing.

Some Primitive data types that represent the wrapper classes.

Primitive Data TypeWrapper Class
ByteByte
ShortShort
IntInteger
LongLong
FloatFloat
DoubleDouble
CharCharacter 
BooleanBoolean 

We can use certain methods to get the value which is associated with the wrapper objects.  They are intValue( ), byteValue( ), shortValue( ), longValue( ), floatValue( ), doubleValue( ), charValue( ), booleanValue( ). 

Let’s have a look on the following code that explains these conversions –

public class Main {                                                                                                               
public static void main(String[] args) {                                                                             
Integer myInt = 6;                                                                                                                 
Double myDouble = 7.58;                                                                                      
Character myChar = 'Y';                                                                                                      
Boolean myBoolean = (9==8);                                                
System.out.println(myInt);                                                  
System.out.println(myDouble);                                                    
System.out.println(myChar);                                                  
System.out.println(myBoolean);                                                                                                     
}                                                                                                                                                       
}

Output:

6                                                                                                                                7.58                                                                                                                          Y                                                                                                                               false

We can also try the toString( ) method to convert the wrapper object to string.

Following is the code-

public class Main {                                                                                                      
public static void main(String[] args) {                                                                            
Integer myInt = 3456;                                                                                                            
String mySent = "sanandreas";                                                                                            
String myString = myInt.toString();   // Here we are converting integer to string                     
System.out.println(myString.length());  // Printing length of 3456 
System.out.println(mySent.length());   // Printing length of sanandreas                                                                                                   
}                                                                                                                                                             
}

Output:                                                                                                                                       4                                                                                                                                10

Note – .length( ) function (stores the length of a string) of the above code has been explained in the upcoming table.

Some predefined functions of the string class are as follows:

FunctionsUse
length( )Calculates the length of a string and returns an integer value.                    Eg String x=”Apple”;                                 int l= x.length( );              System.out.println(l);Output : 5The counting of character starts from 1. 
charAt( )Used to extract character from a specified position.                                         Eg String x=”Apple”;                                 int l= x.charAt(4);              System.out.println(l);Output: eThe index value of the character starts from 0.
equals( )Checks whether two strings are exactly the same or not and returns a boolean value.                                       Eg String a=”Apple”, b=”apple”;                             boolean l= a.equals(b);              System.out.println(l);Output : false
equalsIgnoreCase( )Checks whether two strings are exactly the same ignoring the case of the strings and return a boolean value true or false.                                       Eg String a=”Apple”, b=”apple”;                             boolean l= a.equalsIgnoreCase(b);              System.out.println(l);Output: true

Conversion of string objects to numeric objects using valueOf method:

Conversion of string to integer- int x = Integer.valueOf(str);                                    Conversion of string to long-  long x = Long.valueOf(str);                                               Conversion of string to float- float x = Float.valueOf(str);                                       Conversion of string to double- double x = Double.valueOf(str);

valueOf( ) – Converts the string representation value to any primitive data type. Example String x= “12”;                                                                                              int a = Integer.valueOf(x);                                                                                           double = Double.valueOf(x);                                                                                        System.out.println(a);                                                                                                System.out.println(b);                                                                                                Output :                                                                                                                    12                                                                                                                              12.0

Conversion of numeric strings to primitive number data type using parsing methods:

Conversion of string to integer- int x = Integer.parseInt(str);                                    Conversion of string to long-  long x = Long. parseLong(str);                                         Conversion of string to float- float x = Float. parseFloat(str);                                       Conversion of string to double- double x = Double.parseDouble(str);

Str – In the above statements, str is a string variable that is either initialized a numeric value or gets a numeric value inputted from the user.

Example- String str = “123”;

Predefined Functions of the character wrapper class.

Wrapper classUse
toUpperCase()Converts the character which is passes as parameter into uppercase.     char a=’b’; a=Character.toUpperCase(a);  System.out.println(a);Output: B
toLowerCase()Converts the character which is passes as parameter into lowercase.     char a=’A’; a=Character.toLowerCase(a);  System.out.println(a);Output: a

The following ones return value in Boolean true or false –

isUpperCase()Checks whether the parameter passed is an uppercase alphabet or not and returns value true or false.                                                         char a=’x’;                                                   boolean b= Character.isUpperCase(a);  System.out.println(b);Output: false
isLowerCase()Checks whether the parameter passed is an lowercase alphabet or not and returns value true or false.                                                         char a=’x’;                                                   boolean b= Character.isLowerCase(a);  System.out.println(b);Output: true
isDigit()Checks whether the parameter passed is a digit alphabet or not and returns value true or false.                                                         int a=20;                                                   boolean b= Character.isDigit(a);  System.out.println(b);Output: true
isWhiteSpace()Checks whether the parameter passed is a blank space / white space and returns value true or false.                                                         char a = ’e’;                                                   boolean b = Character.isWhiteSpace(a);  System.out.println(b);Output: false
IsLetterOrDigit()Checks, whether the parameter passed, is an alphabet or digit and returns the value true or false.                                                         Int a= 20;                                                   boolean b= Character.isLetterOrDigit(a);  System.out.println(b);Output: true

When is the wrapper class used?

It is used when we are working with a collection of objects like ArrayList these lists don’t store primitive data types, they store only objects

The syntax is as follows:

ArrayList<Character> myAlphabets = new ArrayList<Character>( );

The following code shows how to use this syntax-

import java.util.ArrayList;
public class Main {                                                                                                                    
public static void main(String[] args) {                                                                                                     
ArrayList<Character> myAlphabets = new ArrayList<Character>();                           
myAlphabets.add(‘c’);                                                                                
myAlphabets.add(‘d’);                                                                                   
myAlphabets.add(‘e’);                                                                              
myAlphabets.add(‘f’);                                                                                                                 
for (char i : myAlphabets) {                                                                                 
System.out.println(i);                                                                                                                        
} 
} 
}       

Output:                                                                                                                    c                                                                                                                               d                                                                                                                                e                                                                                                                               f

Conclusion

Now that we know the super keyword we can easily connect the base class and superclass and increase the efficiency of our code. Looking at wrapper classes you would have got a deep insight into how useful these are and how many of these are present in Java. These various wrapper classes let us do so much more with our code and make it easy to jump from one data type to another in getting output in another data type. Overall, both the ‘super’ keyword and wrapper classes are a unique feature of Java that enables the programmers to extend their knowledge of coding. 

Take up a free Java Programming course at Great Learning Academy now.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top