Java/Data Type/Convert to String

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Convert a byte array to a Hex string

 
public class Main {
  public static void main(String[] argv) {
    byte[] b = "ada".getBytes();
   
    for (int i = 0; i < b.length; i++) {
      System.out.println(Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1));
    }
    
  }
}
/*
61
64
61
*/





Convert an int value to String: concatenate string to an int value

 

public class Main {
  public static void main(String[] args) {
    int i = 50;
    String str = "" + i;
    System.out.println(str + " : " + ("" + i).getClass());
  }
}
// 50 : class java.lang.String





Convert an int value to String: Integer.toString(i)

 
public class Main {
  public static void main(String[] args) {
    int i = 50;
    String str = Integer.toString(i);
    System.out.println(str + " : " + Integer.toString(i).getClass());
  }
}
//50 : class java.lang.String





Convert an int value to String: new Integer(i).toString()

 
public class Main {
  public static void main(String[] args) {
    int i = 50;
    String str = new Integer(i).toString();
    System.out.println(str + " : " + new Integer(i).toString().getClass());
  }
}
//50 : class java.lang.String





Convert from integer to String

 
public class Main {
  public static void main(String[] args) throws Exception {
    int i = 2;
    String str = Integer.toString(i);
    System.out.println(str);
    // or
    str = "" + i;
    System.out.println(str);
  }
}





The Value of a String with String.valueOf method

  
        
class MainClass {
  public static void main(String[] args) {
    String s = String.valueOf(false);
    System.out.println(s);
    s = String.valueOf("A");
    System.out.println(s);
    char[] c = { "a", "b", "c" };
    s = String.valueOf(c);
    System.out.println(s);
    s = String.valueOf(c, 0, 2);
    System.out.println(s);
    s = String.valueOf(3.5d);
    System.out.println(s);
    s = String.valueOf(2.5f);
    System.out.println(s);
    s = String.valueOf(59);
    System.out.println(s);
    s = String.valueOf(8000l);
    System.out.println(s);
  }
}





To catch illegal number conversion, try using the try/catch mechanism.

 
public class Main {
  public static void main(String[] args) throws Exception {
    try {
      int i = Integer.parseInt("asdf");
    } catch (NumberFormatException e) {
      ;
    }
  }
}





Use toString method of Integer class to conver Integer into String.

 
public class Main {
  public static void main(String[] args) {
    Integer intObj = new Integer(10);
    
    String str = intObj.toString();
    System.out.println("Integer converted to String as " + str);
  }
}