search
HomeJavajavaTutorialHow to convert between Java basic data types

1. Automatic type conversion

1.Definition

When a Java program performs assignment or operation, it automatically converts small precision into large precision.

2. Data types are sorted by precision size

char —> int —> long —> float —> double

byte —> short —> int —> long —> float —> double

3. Usage details

  • When there are multiple data mixed operations, the system will first automatically convert all data into the data type with the largest capacity, and then perform calculations.

  • When assigning a data type with a high precision to a data type with a small precision, an error will be reported. Note that when assigning a numerical value, first determine whether it is within the range of the small-precision data type. If so, it is OK. If it is a variable assignment, it is not OK.

  • Byte, short and char cannot be automatically converted to each other.

  • byte, short and char can be calculated and converted into int type during calculation.

  • Boolean type does not participate in conversion.

  • Auto-promotion principle: The type of the expression result is automatically converted to the largest type among the operands.

2. Forced type conversion

1. Definition

The reverse process of automatic type conversion, converting data types with large capacity into data types with small capacity data type. A coercion character must be added when using it, but this may cause precision reduction or overflow.

2. Usage details

Forced type conversion is only effective for the most recent operand, and parentheses are often used to increase the priority.

The char type can save the constant value of int, but it cannot save the variable value of int and needs to be forced.

public class ForceTest{
    public static void main(String []args){
      int x = (int)(10*3.5+6*1.5);//正确
      int y = (int)10*3.5+6*1.5;//报错
    }
}

3. Conversion between basic data type and String type

1. Convert basic data type to String type

Just "" the value of this type.

int n1 = 100; String str1 = n1 + "";

2. Convert String type to basic data type

Just call the parseXX function through the wrapper class of the basic data type, but make sure that the String type can be converted into valid data, for example, you can convert " 123" conversion, but "hello" cannot be converted into an integer. If the format is incorrect, an exception will be thrown and the program will be terminated.

String Str1 = "345";
Integer.parseInt("123");
Double.parseDouble("123.5");
Float.parseFloat("123.3");
Short.parseShort("123");
Boolean.parseBoolean("true");
Long.parseLong("123456");
Byte.parseByte("12");
//将字符串转换成字符型需要调用charAt(int a)函数
Str1.charAt(a);
//表示字符串中第a+1个字符 Str1.charAt(0)='3';

The above is the detailed content of How to convert between Java basic data types. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment