Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - valueOf() method



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.

This method is a static method. The method can take two arguments, where one is a String and the other is a radix.

Syntax

static Integer valueOf(int i) 
static Integer valueOf(String s) 
static Integer valueOf(String s, int radix)

Parameters

Here is the detail of parameters −

  • i − An int for which Integer representation would be returned.

  • s − A String for which Integer representation would be returned.

  • radix − This would be used to decide the value of returned Integer based on passed String.

Return Value

  • valueOf(int i) − This returns an Integer object holding the value of the specified primitive.

  • valueOf(String s) − This returns an Integer object holding the value of the specified string representation.

  • valueOf(String s, int radix) − This returns an Integer object holding the integer value of the specified string representation, parsed with the value of radix.

Example - Get Wrapper from a primitive

Following is an example of the usage of valueOf() method to get a wrapper object from a primitive number −

Example.groovy

class Example {
   static void main(String[] args) {
      int x = 5;
      Double z = 15.56;
		
      Integer xNew = Integer.valueOf(x);
      println(xNew);
		
      Double zNew = Double.valueOf(z);
      println(zNew);
   } 
} 

Output

When we run the above program, we will get the following result −

5 
15.56 

Example - Get Wrapper from a string

Following is an example of the usage of valueOf() method to get a wrapper object from a number formatted as string −

Example.groovy

class Example {
   static void main(String[] args) {
      String x = "5";
      String z = "15.56";
		
      Integer xNew = Integer.valueOf(x);
      println(xNew);
		
      Double zNew = Double.valueOf(z);
      println(zNew);
   } 
} 

Output

When we run the above program, we will get the following result −

5 
15.56 

Example - Get Wrapper from a string with radix

Following is an example of the usage of valueOf() method to get a wrapper object from a number formatted as string in required radix −

Example.groovy

class Example {
   static void main(String[] args) {
      String x = "5";
      String z = "444";
		
      Integer xNew = Integer.valueOf(x, 16);
      println(xNew);
		
      Integer zNew = Integer.valueOf(z, 16);
      println(zNew);
   } 
} 

Output

When we run the above program, we will get the following result −

5 
1092
groovy_numbers.htm
Advertisements