int, float, long, char, double etc. are primitive data types. Primitive data types may be converted into object types, by using the wrapper classes contained in the java.lang package. Given below is a table, which shows the simple data types and their corresponding wrapper class types:
Given below is a table, which shows how Constructor methods are used for converting primitive numbers to object numbers:
NOTE: i, f, d and l are primitive data values denoting int, float, double and long data types. They may be constants or variables. Given below is a table, which lists the methods used for converting Object numbers to Primitive numbers using typeValue() method:
Given below is a table, which shows how numbers are converted to Strings using toString() method:
Given below is a table, which shows how string objects can be converted to numeric objects using the static method valueOf():
Given below is a table, which is used for converting numeric strings to primitive numbers using Parsing methods:
NOTE: parseType( ) methods throw a NumberFormatException if the value of the str does not represent the respective primitive type. Given below is an example, which uses some of most commonly used wrapper class methods, import java.io.*; class Invest { public static void main(String args[]) { Float principalAmount = new Float(0); Float interestRate = new Float(0); int numYears=0; try { DataInputStream in = new DataInputStream(System.in); System.out.println("Enter principal amount : "); System.out.flush(); String principalString = in.readLine(); principalAmount = Float.valueOf(principalString); System.out.println("Enter interest rate : "); System.out.flush(); String interestString = in.readLine(); interestRate = Float.valueOf(interestString); System.out.println("Enter Number of years : "); System.out.flush(); String yearsString = in.readLine(); numYears = Integer.parseInt(yearsString); } catch(IOException e) { System.out.println("I/O Exception "); System.exit(1); } float value = loan(principalAmount, floatValue(), interestRate, floatValue(), numYears); printline(); System.out.println("Final value = "+value); printline(); } static float loan(float p,float r, int n) { int year=1; float sum = p; while(year <= n) { sum = sum * (1 + r); year = year + 1; } return sum; } static void printline() { for(int i = 1; i <= 30; i++) { System.out.print("="); } System.out.println(" "); } } Output: Enter principal amount: 20000 Enter interest rate: .12 Enter number of years: 2 ============================== Final Value = 25088.0 ============================== |
Course Content > Session 5 >