Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for JAVA Basics #9 - Casting
Chathumi Kumarapeli
Chathumi Kumarapeli

Posted on • Edited on

     

JAVA Basics #9 - Casting

In this article we are going to focus on casting and type conversions and also on 'Math' class.

Casting

Implicit Casting

Examine the following code.

shorty=1;intz=y+2;System.out.println(z);
Enter fullscreen modeExit fullscreen mode

Notice that the data types of 'x' and 'y' are different in the above code. Can you guess the output? Will this execute and give the accurate answer, or will this give an error?
Well you will notice that this gives the accurate answer. That is because 'x' is of type 'short' which is of size 1 byte. And 'y' is an integer which is of size 4 bytes. Therefore, any variable that can be stored in a 1 byte can easily be store in 4 bytes. Because of that, this code runs just fine. This is calledIMPLICIT CASTING. Java does this casting automatically.

byte -> short -> int -> long -> float -> double

Task

Try the below code and examine the output.

packagecom.company;publicclassMain{publicstaticvoidmain(String[]args){inty=1;shortz=y+2;System.out.println(z);}}
Enter fullscreen modeExit fullscreen mode

Explicit Casting

In most of the frameworks which are used to built user interfaces, user inputs are taken as strings. In such a case assume that user inputs a number and you want to add 100 into it. However, the number user inputted is a string. So how can you add 100? This is where you want to use 'explicit casting'. Arithmetic operations are only performed in between compatible types. Therefore, first you need to 'explicitly' convert the user input into an integer and then proceed. Look at the code given below.

StringuserInput="167";intintInput=Integer.parseInt(userInput)+100;System.out.println(intInput);
Enter fullscreen modeExit fullscreen mode

The above code will first convert stringuserInput into an integer, and then will add another 100 into it.

Math Class

'Math' is another predefined class in java. Let's see what methods we do have in that class.

You can easily round off numbers by usinground method as shown below;

intx=Math.round(20.4F);System.out.println(x);
Enter fullscreen modeExit fullscreen mode

This will give output as 20.

You can also compare numbers and get maximum and minimum out of them.

intmaxNum=Math.max(10,20);intminNum=Math.max(10,20);System.out.println(maxNum);System.out.println(minNum);
Enter fullscreen modeExit fullscreen mode

You also can generate a random number with the help of 'Math' class. Check this code;

doublerandNum=Math.round(Math.random());System.out.println(randNum);
Enter fullscreen modeExit fullscreen mode

The above code will generate a floating point number between 0 and 1. But you can change that range as you wish. For example you can get a number between 0 and 100 by using the following line;

intrandNum2=(int)Math.round(Math.random()*100);System.out.println(randNum2);
Enter fullscreen modeExit fullscreen mode

In here since I have used(int) the floating point number is converted as an integer. Which means, you will get an integer in the range [0, 100].

There are many more predefined methods in 'Math' class. Explore and practice those as well :)

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
terabytetiger profile image
Tyler V. (he/him)
He/Him. A developer that loves to teach others and spread my passion for Mathematics, Coding, and Pet Photography!In love with Vue.js 💚
  • Location
    United States
  • Education
    BS in Mathematics & Comp Sci
  • Work
    Frontend Developer
  • Joined

Hi!

In this code block:

intmaxNum=Math.max(10,20);intminNum=Math.max(10,20);System.out.println(maxNum);System.out.println(minNum);
Enter fullscreen modeExit fullscreen mode

I think you mean to haveMath.min(10,20) on the second line :)

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer
  • Location
    Sri Lanka
  • Joined

More fromChathumi Kumarapeli

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp