Converting primitives to strings - Java Language Basics

Java examples for Language Basics:Primitive Types

Introduction

Java automatically converts primitive values to string values whenever you use a primitive value in a concatenation.

Demo Code

public class Main {
  public static void main(String[] args) {
    String hello = "Hello";
    int world = 5;
    String greeting = hello + ", " + world;

    System.out.println(greeting);
  }//  w  w  w  . ja v  a  2  s  . c  o m

}

You can convert a primitive value to a string by using the toString method of the primitive type's wrapper class.

Demo Code

public class Main {
  public static void main(String[] args) {
    String hello = "Hello";
    int world = 5;
    String greeting = hello + " " + Integer.toString(world) ;

    System.out.println(greeting);
  }//from   w w  w .j a v  a2 s.c o  m

}

Related Tutorials