Posted in Java
public class StringToInteger { public static void main(String[] args) { System.out.println("Mengubah String ke Integer"); String str = "1234"; int a = 5; //mengubah variabel str menjadi int int num = Integer.parseInt(str); int b = num + a; System.out.println(b); } }Contoh lain menggunakan method
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package LatihanStringInt; /** * * @author Azhar */ public class StringToInteger { public static void main(String[] args) { System.out.println("Mengubah String ke Integer"); String str = "1234"; int a = 5; //mengubah variabel str menjadi int int num = getStrToInt(str); int b = num + a; System.out.println(b); } private static int getStrToInt(String n) { return Integer.parseInt(n); } }Sebaliknya, untuk mengubah Integer ke String menggunakan fungsi berikut:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package LatihanStringInt; /** * * @author Azhar */ public class IntegerToString { public static void main(String[] args) { int a = 1000; String b = String.valueOf(a); } }Selamat mencoba.