• Register
Welcome to Kodlogs Q&A, where you can ask programming questions and receive answers from other members of the community. For programmers, by programmers Kodlogs is an open community for anyone that does coding. We help you get answers to your toughest coding questions, share knowledge with your coworkers in private, and find your next IT dream job.

Most popular tags

java program php python javascript c# android r c spring-boot arrays html mysql entity-framework sql-server matlab redirect code program numpy spring asp loop net class quirks-mode internet-explorer-9 internet-explorer machine-learning winforms visual-studio-2010 webpack python-3 python-2 aspnet dataframe pandas jdbc ios eclipse sum loops css cmd tcp math security jquery sockets sql 7 number firebase-authentication aws-organizations amazon-web-services php-7 string-formatting cplusplus visual-studio-2015 net-core net-mvc msbuild extension-methods foreign-keys sql-server-2005 windows-services react-redux reactjs inputstream facebook-graph-api for-loop entity-framework-4 reportingservices-2005 reporting-services mips linear-regression scikit-learn anova deep-learning keras block-device melt reshape2 floating-point webpack-dev-server javascrip 0-lollipop android-5 statsmodels avx indentation-error eclipseide javafx-2 php-not-recognized laravel command-line unit-testing tinyurl atom-editor android-emulator android-studio android-sdk-tools ionic2 cordova jupyter-notebook foobar2k tcplistener net-2 net-4 ole-db-provider windows-10 vagrantfile ggplot2 glmnet jvm-arguments global-variables orm virtualenv atom xls oledb redux webclient prediction headless hyperlink outlook pipeline iis perfect-square objective-c carthage xcode8 compiler-errors numpy-ndarray standard-deviation xampp apple mdf destructor vagrant gettime gmail ioexception heuristics milliseconds reporting cpu npm modx-revolution goldsky modx prevnext javascript-dictionary stack-smashing device-monitor radio-button android-actionbaractivity android-activity android-fragments java-long unqualified-id ora-12154 javc c++ java nullpointerexception runtime-error drjava awt-eventqueue dsx math-pow ajquery nosuchelementexception appcompatactivity jtextfield jpanel inputmismatchexception deque jupyter javafx lvalue junit tensorflow ibm factorial servlet apache boot virtualbox indentation jvm margins 2147483647 xcode firebase plot deployment processor automation socketexception pointers concatenation oracle devices color recursion sequence search date caching expected response directory csv algorithms release collections facebook float figure url expression microsoft sorting sort datetime httpwebrequest cryptography json ajax exe dictionary required windows string variable size dll system exception files x int function random import code 2
0 votes
2 views
Casting in Java
by (320 points)  
reshown by

1 Answer

0 votes
When you perform arithmetic withvariables or constants of the same type,the result of the operation retains thesame type.  For example, when you take twoints and multiplying together, the resultwill be an int.  When you subtract twodoubles, the result will be a double.However you might need to performmathematical operations on unliketypes.  The process of converting one datatype to another is type conversion.  Javaperform some conversions automaticallyalso called implicit conversion but someconversions must be requested explicitlyby the programmer.  When you performarithmetic with unlike operands ortypes, Java chooses a unifying typefor the result. When two unlike types areused to know expression, the unifying type isone that is higher in precision.  In otherwords, the number that is the lower type,the int or the long, would be convertedto be a higher type - the float or thedouble. Java has no problem adding theprecision in but it does have issueswith taking the precision away and thatwould require the explicit typeconversion.  In the example of the inttimes the double the result of themultiplication is a double. Java willconvert the int to a higher ranking datatype and will use that in themultiplication.However if I try to change gross pay tobe an int,Java will give you a type mismatchsaying that it cannot convert fromdouble to int.  There are some cases wherewe know that we're going to lose theprecision and we're okay with that.In this example, myMoney contains moredetails than an int of myDollars.However we just want the dollar so wecan use an explicit conversion. myMoneyis converted to an int before it is storedinto the integer variable named mydollars.  When the double value isconverted to an int, the decimal placesare lost.However the cast operator does notpermanently alter any variable's datatype so myMoney still contains 134.89and only myDollars would contain the134 at this point.Type casting is forcing one data type tobe used as a value for another.  Toperform type cast, you use a cast operatorwhich is created by placingthe desired result type in parentheses.In this example we have two integersbeing divided and the result should betreated as a double.  If we system out theresult inside of sampleMoney,we'll see that the result is 67.  Howeverif we up the number of kids to three,we should end up with a decimal pointhere because dividing 134 by 3 wouldresult in 44.66666.  Therefore, we needeither myDollars or numberOfKids tobe treated as the double so that we canget the precision that we need.  The waythat we cast to a double is to put thekeyword double inside parentheses.  NowmyDollars we treated as a double and theresult will be as a double as well.  Thecast operator is followed by thevariable or the constant that needs tobe cast.  Always be sure to check yourresults to verify that you're gettingthe data type that you need for yourprogram.
by  
...