[java] string to integer??!?!?!??!?

Started by
5 comments, last by HearYouMe 22 years, 10 months ago
I have something like this.. String a = "1"; int b = "0"; how can i get the value of b to equal a''s value? Is there like a string to integer value command or something.. i dunno. im new to java but i really need to do this. im making a tic-tac-toe game where the user enters a row and col and then i go like board[col][row]="X"; but it wont allow that cause col and row are strings
Advertisement
string to integer

int a = Integer.parseInt("1");


integer to string

String a = new String("" + 1);



{ Stating the obvious never helped any situation !! }
no need to call the constructor, just do ""+1. It is probably faster and it''s also a little easier to read
Why not just read in the values as integers?

--OctDev
The Tyr project is here.
its the same , since String class is immutable.

String a = new String("a");

and

String a = "a";

both are the same because string class will copy itself to create a new copy. immutable.

{ Stating the obvious never helped any situation !! }
Actually,

String a = new String("a");

and

String a = "a";

are not the same in java, if you look at the language specification. Constants in the source code are compiled into the constant table in the class file. With String objects, this means they will be part of the JVM''s intern pool for strings, meaning that ("a" == "a") will always evaluate to true. However, putting new in the source code guarantees that a new object will be allocated, meaning that ("a" == new String("a")) will be false.

And by the way, the best way to convert an integer to a string is

int i = 1468;
String s = Integer.toString(i);

The s = "" + i approach is compiled as

s = new StringBuffer("").append(i).toString();

which is less than fast, as in addition to creating the new Stringbuffer and calling toString() on it when it''s done, StringBuffer''s append(int) method calls String.valueOf(int), which calls Integer.toString(int, 10), which calls Integer.toString(int).

Digging through the source code distributed with the jdk can be fun. =)
issit ?? . i didnt realise ..
i knew that literal''s were compiled into the class, but i though immutable objects always duplicated themselves ..

anyway, sorry for the mixup .



{ Stating the obvious never helped any situation !! }

This topic is closed to new replies.

Advertisement