saadatislam saadatislam - 3 months ago 8
Java Question

Convert Char to String in Java

I want to convert character to string in a program .
is there any difference between ::::

String s = "" + 'x';
String s = 'x' + "";


output of followin g 2 programs are opposite.




code no : 1 >>>

import java.util.*;
public class Listing_5_11 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Enter Decimal value : ");
int decimal = input.nextInt();
String hex = "";

while (decimal!=0) {
int hexvalue = decimal%16;
//problem with this line;
hex = ((hexvalue>=0 && hexvalue<=9) ? (char)(hexvalue + '0') : (char)(hexvalue- 10 + 'A'))+hex;

decimal /= 16;

}
System.out.println("Decimal "+decimal+" = "+hex+" in hexadecimal . ");
input.close();
}

}


code no 2 :

import java.util.*;
public class Listing_5_11 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Enter Decimal value : ");
int decimal = input.nextInt();
String hex = "";

while (decimal!=0) {
int hexvalue = decimal%16;
hex = hex + ((hexvalue>=0 && hexvalue<=9) ? (char)(hexvalue + '0') : (char)(hexvalue- 10 + 'A'));

decimal /= 16;

}
System.out.println("Decimal "+decimal+" = "+hex+" in hexadecimal . ");
input.close();
}

}





what is difference of following ??:

**hex = hex + ((hexvalue>=0 && hexvalue<=9) ? (char)(hexvalue + '0') : (char)(hexvalue- 10 + 'A'));
**hex = ((hexvalue>=0 && hexvalue<=9) ? (char)(hexvalue + '0') : (char)(hexvalue- 10 + 'A'))+hex;


output is totaly opposite .

Answer
String s = "" + 'x'; 
String s = 'x' + "";

There is no difference between the top two lines because you are adding an empty string as "" If you do something like

String s = "Beginning of string" + 'x'; 
String s = 'x' + "Beginning of string";

The second line will produce wrong output or as you called it "opposite" to the first one

Comments