• Advertisement

Archived

This topic is now archived and is closed to further replies.

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

This topic is 6084 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
string to integer

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


integer to string

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



{ Stating the obvious never helped any situation !! }

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
no need to call the constructor, just do ""+1. It is probably faster and it''s also a little easier to read

Share this post


Link to post
Share on other sites
Why not just read in the values as integers?

--OctDev

Share this post


Link to post
Share on other sites
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 !! }

Share this post


Link to post
Share on other sites
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. =)

Share this post


Link to post
Share on other sites
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 !! }

Share this post


Link to post
Share on other sites

  • Advertisement