Назад Зміст Вперед

Лабораторна робота: «Взаємні перетворення Strings та Wrappers»

Example of wrapper class

class WraperDemo
{
public static void main(String[] args)
{
String  s[] = {"10", "20"};
System.out.println("Sum before:"+ s[0] + s[1]); // 1020
int x=Integer.parseInt(s[0]); // convert String to Integer
int y=Integer.parseInt(s[1]); // convert String to Integer
int z=x+y;
System.out.println("sum after: "+z); // 30
}
}

Output

Sum before: 1020
Sum after: 30

Convert Java String to Integer object Example

  1. /*
  2.   Convert String to Integer example
  3.   This example shows how we can convert String object to Integer object.
  4. */
  5. public class StringToIntegerExample {
  6.   public static void main(String[] args) {
  7.    
  8.     //We can convert String to Integer using following ways.
  9.     //1. Construct Integer using constructor.
  10.     Integer intObj1 = new Integer("100");
  11.     System.out.println(intObj1);
  12.    
  13.     //2. Use valueOf method of Integer class. This method is static.
  14.     String str = "100";
  15.     Integer intObj2 = Integer.valueOf(str);
  16.     System.out.println(intObj2);
  17.    
  18.     //Please note that both method can throw a NumberFormatException if
  19.     //string can not be parsed.
  20.    
  21.   }
  22. }
  23. /*
  24. Output of the program would be :
  25. 100
  26. 100
  27. */

>>Більше
.