Wrapper class and conversion between basic data type and string

Correspondence between basic data type and packing class:

Basic data type Packaging class
byte

Byte

short Short
int Integer
long Long

char

Character
float Float

double

Double
boolean Boolean

 

The conversion between basic data types and strings is as follows:

Convert basic data type to String object: through String.valueOf(primitive)

String object to basic data type: through WrapperClass.parseXxx(String)

 

Example code:

/**
 * Description: conversion between basic data type and string
 * Method 1: change the basic data type into a Sting object: convert through String.valueOf(primitive)
 * Method 2: the String object becomes the basic data type: through WrapperClass. parseXxx() transformation, Character wrapper class does not have this method
 * @author LiuYP_1024
 *
 */
public class PrimitiveAndString {
	public static void main(String[] args) {
		String num="123";
		String floatStr="4.56";
		
		//Convert string to byte
		byte byte1=Byte.parseByte(num);
		System.out.println(byte1);
		
		//Convert strings to short and long
		short short1=Short.parseShort(num);
		System.out.println(short1);
		long long1=Long.parseLong(num);
		
		//Convert string to int
		int int1=Integer.parseInt(num);
		int int2=new Integer(num);
		System.out.println(int1);
		System.out.println(int2);
		
		//Convert string to float
		float float1=Float.parseFloat(floatStr);
		float float2=new Float(floatStr);
		System.out.println(float1);
		System.out.println(float2);
		

		//Convert float and double to String
		String str1=String.valueOf(2.234f);
		String str2=String.valueOf(3.344);
		System.out.println(str1);
		System.out.println(str2);
		
		//Convert boolean to String
		String str3=String.valueOf(true);
		System.out.println(str3);
	}
}

In addition, there is another easier way to convert a basic data type to a string: connect the basic data type variable directly to "", as follows

String intStr=5+"";

Content collation from: Crazy Java handout

Keywords: Java

Added by mark123 on Fri, 01 Nov 2019 13:09:46 +0200