Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to subtract two strings

 
preethi Ayyappan
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am having a string variable,say
String a="30"
and another string variable
String b="1"
.

Now i need to subtract 1 from 30.How do i subtract these two things.
please assist me to do this.

Thanks
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Convert String to int [premitive]
 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can use


to parse the value..
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Harshit Rastogi wrote:you can use


to parse the value..


return type of the valueOf is wrapper(Integer) . this wont be much flexible in terms of mathematical operations .

if i were in your place, i would go for

 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
return type of the valueOf is wrapper(Integer) .


if jdk1.5 is used it doesnt matter because of autoboxing
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Harshit Rastogi wrote:if jdk1.5 is used it doesnt matter because of autoboxing


yes. true...
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Still, Integer.parseInt is more efficient because it doesn't create a new Integer object, which Integer.valueOf will do.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15437
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote:Still, Integer.parseInt is more efficient because it doesn't create a new Integer object, which Integer.valueOf will do.

The method Integer.valueOf(int i) uses a cache if i is between -128 and 127, so it doesn't create a new object if the value is between those boundaries. So I thought you were incorrect when you said that Integer.valueOf(String s) always creates a new object. I checked out the source code of class Integer (available in src.zip in the JDK directory), and to my surprise saw this:

So indeed, the method that takes a String always creates a new Integer object - you were right.

I wonder why this is - why did the people who programmed the JDK not write it like this?

Strange! But you know, the standard Java library isn't perfect...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic