Write a Java program to Demonstrate the Math.copySign() method


This Java program demonstrates the usage of the Math.copySign method to copy the sign of one double value to another double value. Here's a breakdown of the program:

  • The import java.util.*; statement imports the java.util package, which is not used in this program.
  • The public class CopySign_Method statement declares a public class called CopySign_Method, which is the name of the Java file that this program is saved in.
  • The public static void main(String[] args) method is the entry point for the program. It takes an array of strings as an argument, but in this program, that argument is not used.
  • Inside the main method, a double variable n is declared and initialized to 0.
  • The Math.copySign(-158.42, 52.167) method is used to copy the sign of the first argument -158.42 to the second argument 52.167. Since the first argument is negative, the result of this method call is negative.
  • The result is then assigned to the n variable.
  • The result is printed to the console using System.out.print.

Source Code

import java.util.*;
public class CopySign_Method
{
	public static void main(String[] args) 
	{
		double n = 0;
		n = Math.copySign(-158.42, 52.167);
		System.out.print("Result : " + n);
	}
}

Output

Result : 158.42

Example Programs