Page 246 - Computer science 868 Class 12
P. 246

2. parseInt() and ValueOf(): These methods are used to convert String to primitive data type.
                 The different methods are stated below.
                •  String to int: In this, a number in String format is converted to Integer format.
                      String s = "25";
                      int n;
                     n=Integer.parseInt(s);           OR   n=Integer.valueOf(s);
                      System.out.println("Result :" + n);
                 Output: Result : 25
                •  String to long: In this, the String value is converted to long data type.
                      String s= "25";
                      long n;
                      n=Long.parseLong(s);  OR   n=Long.valueOf(s);
                      System.out.println("Result :" + n);
                 Output: Result: 25
                •  String to float: In this, the String value is converted to a float variable.
                      String s= "1343";
                      float n;
                     n=Float.parseFloat(s);           OR   n=Float.valueOf(s);
                      System.out.println("Result :" + n);
                 Output: Result: 1343;
                •  String to Double: In this, the String value is converted to double value.
                      String s= "3278";
                      double n;
                      double n=Double.parseDouble(s);    OR   n=Double.valueOf(s);
                      System.out.println("Result :" + n);
                 Output: Result: 1343;


                Program 3     Write a program to convert primitive data type to object and vice-versa.


                1       class convert

                2       {
                3           public static void main()

                4           {
                5               // creates objects of wrapper class
                6               Integer intvar = Integer.valueOf(768);

                7               Double douvar = Double.valueOf(23.45);

                8               // converts into primitive types
                9               int in = intvar.intValue();
                10              double do1 = douvar.doubleValue();

                11              //Printing
                12              System.out.println("The value of in : " + in);

                13              System.out.println("The value of do: " + do1);
                14              //Converts to wrapper object

                15              intvar = in;


                244244  Touchpad Computer Science-XII
   241   242   243   244   245   246   247   248   249   250   251