Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.format equivalent in Java 1.4

Currently i have a method calling String.format() in Java 5 and it's working perfectly

String.format("%02x", octet) //octet is a int type

However due to some issue we need to deploy this code in a JDK 1.4 environment, and String.format doesn't exists in 1.4.

Anyone knows any alternative way to perform this function?

like image 924
ipohfly Avatar asked Nov 02 '12 11:11

ipohfly


People also ask

What is string format in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Syntax: There is two types of string format() method.

What is %- 5d in Java?

"%5d" Format a string with the required number of integers and also pad with spaces to the left side if integers are not adequate. "%05d" Format a string with the required number of integers and also pad with zeroes to the left if integers are not adequate.

What is %d and %s in Java?

%s refers to a string data type, %f refers to a float data type, and %d refers to a double data type.

What is %s in Java?

In your example, it is a placeholder character. It means when % is encountered, the next character determines how to interpret the argument and insert it into the printed result. %s means interpret as string, %d is for digit, %x is digit in hexadecimal, %f is for float, etc....


2 Answers

You could use something like this snippet:

String hexString = Integer.toHexString(octet);
if (hexString.length() < 2) {
    hexString = "0" + hexString;
}
like image 59
Keppil Avatar answered Oct 04 '22 04:10

Keppil


You need to use Integer.toHexString(int) and pad the text yourself.

like image 21
Peter Lawrey Avatar answered Oct 04 '22 03:10

Peter Lawrey