Sunday, April 27, 2025

Java Tutorial - Simple Math Methods

This is a Java program that demonstrates the use of some of the math functions provided by the Math class:  

public class Main {

	public static void main(String[] args) {
		int x = 10;
		int y = 81;
		int z = -5;
		
		System.out.println("Max: " + (Math.max(x, y)));
		System.out.println("Min: " + (Math.min(x, y)));
		System.out.println("Sqrt: " + (Math.sqrt(y)));
		System.out.println("Abs: " + (Math.abs(z)));
		
		System.out.println("Some Random Num:" + (Math.random()));	 
		
	}	
}
Line by line:
        int x = 10;
        int y = 81;
        int z = -5;

These lines declare and initialize three integer variables: x, y, and z. 

        System.out.println("Max: " + (Math.max(x, y)));
        System.out.println("Min: " + (Math.min(x, y)));

These lines use the Math.max and Math.min methods to find the maximum and minimum of the values stored in x and y, and print them to the console. 

        System.out.println("Sqrt: " + (Math.sqrt(y)));

This line uses the Math.sqrt method to find the square root of y, and prints it to the console. 

        System.out.println("Abs: " + (Math.abs(z)));

This line uses the Math.abs method to find the absolute value of z, and prints it to the console. 

        System.out.println("Some Random Num:" + (Math.random()));	

This line uses the Math.random method to generate a random number between 0.0 and 1.0, and prints it to the console.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...