Demonstrates the mathematical operators. : Primitive Data Type « Data Type « Java






Demonstrates the mathematical operators.

Demonstrates the mathematical operators.
     
//: c03:MathOps.java
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.

import java.util.*;

public class MathOps {

  // Shorthand to print a string and an int:

  static void printInt(String s, int i) {

    System.out.println(s + " = " + i);

  }

  // Shorthand to print a string and a float:

  static void printFloat(String s, float f) {

    System.out.println(s + " = " + f);

  }
  public static void main(String[] args) {
    // Create a random number generator,
    // seeds with current time by default:

    Random rand = new Random();

    int i, j, k;

    // Choose value from 1 to 100:

    j = rand.nextInt(100) + 1;

    k = rand.nextInt(100) + 1;

    printInt("j", j);  printInt("k", k);

    i = j + k; printInt("j + k", i);

    i = j - k; printInt("j - k", i);

    i = k / j; printInt("k / j", i);

    i = k * j; printInt("k * j", i);

    i = k % j; printInt("k % j", i);

    j %= k; printInt("j %= k", j);

    // Floating-point number tests:

    float u,v,w;  // applies to doubles, too

    v = rand.nextFloat();

    w = rand.nextFloat();

    printFloat("v", v); printFloat("w", w);

    u = v + w; printFloat("v + w", u);

    u = v - w; printFloat("v - w", u);

    u = v * w; printFloat("v * w", u);

    u = v / w; printFloat("v / w", u);

    // the following also works for

    // char, byte, short, int, long,

    // and double:

    u += v; printFloat("u += v", u);

    u -= v; printFloat("u -= v", u);

    u *= v; printFloat("u *= v", u);

    u /= v; printFloat("u /= v", u);

  }

} ///:~



           
         
    
    
    
    
  








Related examples in the same category

1.Use Integer constructor to convert int primitive type to Integer object.
2.Convert Java Integer object to Numeric primitive types
3.Convert Java String to Integer object
4.Create an Integer object
5.Arithmetic DemoArithmetic Demo
6.Max Variable Length DemoMax Variable Length Demo
7.Data Type Print TestData Type Print Test
8.Tests all the operators on all the primitive data types
9.Demonstrates the ++ and -- operatorsDemonstrates the ++ and -- operators
10.Literals
11.Java lets you overflowJava lets you overflow
12.Built in typesBuilt in types
13.Shows default initial valuesShows default initial values
14.Relational DemoRelational Demo
15.Parse Number
16.Java Type Helper
17.Convert the given array (which may be a primitive array) to an object array
18.Convert primitive back and forth
19.Returns a default value if the object passed is null
20.A mutable boolean wrapper.
21.A mutable byte wrapper.
22.A mutable double wrapper.
23.A mutable float wrapper.
24.A mutable int wrapper.
25.A mutable long wrapper.
26.A mutable short wrapper.
27.Primitive utilities