Entradas


In Java, there are two types of function parameters: The Coetáneo parameter and the Formal parameter. Coetáneo parameters are passed during the function call in another function, whereas formal parameters are the parameters added at the function definition.

In functions, there are two ways to pass an argument or parameters: Call by value and Call by reference. The purpose of this article is to focus on how to call by reference in Java.

How to Call by Reference in Java?

When a function or a method is called in Java, call by reference is the term that refers to a parameter. This method’s core feature is that we use it to refer to the address of a variable. As a result, any change in the variable’s address will be reflected whenever the function that uses it is called or invoked.

Let’s try some examples with the help of the specified method.

Example 1

In this example, first, we will create a method named “add()” by passing two integer type parameters, “x” and “y”. This method will output the sum of the given numbers. Also, the parameters of this method are called the formal parameters:

static int add(int x,int y)
  {
   return x+y;
  }

 
In the main() method, we call the add() method by passing the parameters that refer to the address of the formal parameters. Here, “a” and “b” are the reference parameters for variables “x” and “y”:

public static void main(String[] args) {
    int a=15;
       int b=83;
    System.out.println(«The sum of numbers a and b: « + add(a,b));
}

 

The given output indicates that the added parameters are successfully accessed and utilized:

Example 2

In this example, we have two methods: “ref()” and “main()”. The ref() method will add the value of the specified parameters and then multiply it by “3”:


In the main() method, the third line calls the ref() method by passing arguments “a” and “b” that refers to the address of the formal parameters “x” and “y”:

public static void main(String[] args) {
         int a=15;
         int b=83;
         ref(a,b);  
}

 

Output


We compiled all the instructions related to calling by reference in Java.

Conclusion

In Java, you can call the method by passing an argument as a reference in contemporáneo parameters. Invoking a method by using call by reference means the argument refers to the variable’s address. Whenever a function is called, the added changes will also reflect the variable. In this article, we have discussed the method for calling by reference in Java.



Source link


Java is a collection of packages, classes, and objects. One of the Java classes is a wrapper called Character, which belongs to the Java.lang package. The object of the Character class holds/wraps a particular value, “char”. In Java, characters or chars are often compared to check their differences or similarities.

This tutorial will guide you on how to compare chars in Java.

How to Compare chars in Java?

To compare chars in Java, you can use:

    • compare() method
    • equals() method
    • Relational operators

Let’s check out each of them one by one.

How to Compare chars by Using compare() Method?

The “compare()” method of the Java “Character” class numerically compares two characters. This method is used to compare the primitive chars and the Character objects. It takes two characters as parameters to compare and returns a numeric value.

Syntax

The syntax of compare() method is given as:

 
If both chars “x” and “y” are the same, the compare() method will return “0”. If the first char is less than the second char, it will return a negative value. Similarly, the specified method will return a positive value when the first char is greater than the second char.

Example 1: Compare Primitive chars by Using compare() Method

Let’s compare two primitive characters, “f” and “b”, by using the compare() method. These two characters are stored in “ch1” and “ch2”:

char ch1 = ‘f’;
char ch2 = ‘b’;

 
Now, we will use the “compare()” method to compare these two characters with conditional statements:

if(Character.compare(ch1, ch2) > 0) {
    System.out.println(«character 1 ‘f’ is greater than character 2 ‘b'»);}
 else if(Character.compare(ch1, ch2) < 0) {
    System.out.println(«character 1 ‘f’ is less than character 2 ‘b'»);}
 else
    System.out.println(«Both characters are equal»);

 

The output shows that the “ch1” is numerically greater than “ch2”:

Example 2: Compare Character Objects by Using compare() Method

In a Java program, Character objects can also be compared by using the “compare()” method. First, we will create two Character objects “chr1” and “chr2” with “c” and “v” values respectively:

Character chr1 = ‘c’;
Character chr2 = ‘v’;

 
Now, we call the “compare()” method of the Character class to compare these two character objects using the given conditions:

if(Character.compare(chr1, chr2) > 0) {
    System.out.println(«c is greater than v»);}
else if(Character.compare(chr1, chr2) < 0) {
    System.out.println(«c is less than v»);}
else
    System.out.println(«Both characters are equal»);

 

Output


Let’s head towards the second method!

How to Compare chars by Using equals() Method?

The “equals()” method also belongs to the “Character” class that can be used to compare the Character objects. It simply compares the values and checks whether these characters are equal or not based on their case.

Syntax

The syntax of the equals() method is as follows:

 
The “equals()” method takes a character object as a parameter. If the values of the “obj1” and “obj2” are equal, the equals() method returns true; otherwise, it returns false.

Example

In this example, we will compare two Character objects, “k” and “K”, by creating two objects, “ch1” and “ch2” of Character class:

Character ch1 = ‘k’;
Character ch2 = ‘K’;

 
If the value of ch1 is equal to ch2, the equals() method will return true; otherwise it will return false.:

if(ch1.equals(ch2))
    System.out.println(«Both characters are equal»);
else
    System.out.println(«Both characters are not equal»);

 

As we know, Java is a case-sensitive language, so the equals() method will return false because “k” and “K” are not equal:

How to Compare chars by Using Relational Operators?

There is one more approach for comparing both primitive characters and Character objects, which is using relational operators such as “==”, “<”, and “>”. These operators can be added in the condition based on the requirements.

The following example will compare two Character objects, “ch1” and “ch2,” using the greater than “>” and less than “<” relational operators.

Example

First, we will create two Character objects, “ch1” and “ch2,” with the following values:

Character ch1 = ‘n’;
Character ch2 = ‘m’;

 
Now, we will use relational operators to compare and check if the ch1 object is greater than or less than the other object:

 if(ch1<ch2) {
      System.out.println(«ch1 ‘n’ is less than ch2 ‘m’ «);
 }else if (ch1>ch2) {
      System.out.println(«ch1 is ‘n’ greater than ch2 ‘m’ «);
 }else
   System.out.println(«Both characters are equal»);

 

Output


We have provided all the necessary instructions to compare chars in Java.

Conclusion

To compare Character objects in Java, you can use compare() method, and to compare both primitive chars and Character objects, utilize the equals() method and relational operators. Java compares primitive values numerically, whereas the Character objects are compared based on their case or values, depending upon the method you utilize. In this tutorial, we thoroughly discussed methods to compare chars in Java.



Source link


In Java, “double” and “int” are the most popular primitive data types, where double is a 64-bit floating-point number and integer, also known as “int”, is a 32-bit integer representing signed two’s complement. While programming in Java, you may need to convert double to int where the input given by the user is in floating points, and an integer value is required for further processing.

This post will teach the procedure of converting double to int in Java.

How to Convert double to int in Java?

Converting a number from double to int is considered a common conversion task in programming. As mentioned earlier, the double data type has a parte value. When these numbers are converted to integers, the parte digits are rounded to the closest number.

In Java, you can convert data type double to int:

    • Using “TypeCasting
    • Using “Double.intValue()” method
    • Using “Math.round()” method

Let’s discuss each of them one by one!

Method 1: Convert double to int in Java by Using TypeCasting

Typecasting is a process of converting one data type to another. It is primarily utilized by Java developers to test the data variable. You can also use it for converting double data type variables to int.

Syntax

The syntax for converting double to int in Java using TypeCasting method is given as:

 
d” is the variable that stores a value of data type “double”. The keyword “int” with the parenthesis like “(int)” indicates that the mentioned double type “d” variable is typecasted into an integer, and the resultant value will be stored in “i”.

Example

First, we will create a double type variable “d” and assign it the following value:

 
Next, we will convert “d” into an int by using typecasting:

 
After performing the specified operation, we will print the converted value:

System.out.println(«The value in data type Double « + d + » is converted in Integer « + i);

 

The output shows the integer value “856” after truncating the parte points:

Method 2: Convert double to int in Java by Using Double.intValue() Method

Double.intValue() is another method used to convert the number from double data type to int. The “intValue()” is the method of the Java “Double” Wrapper class. This method converts the double value into the nearest integer value and returns an integer. It works similar to typecasting.

Syntax

The syntax for converting a number in data type double to int by using “Double.intValue()” method is as follows:

int i = new Double(d).intValue();

 
Have a look at the following example to know more about the given method.

Example

We will convert the value of the already created “d” variable using the “Double.intValue()” method:

int i = new Double(d).intValue();

 
The above-given code will create an object of the “Double” Wrapper class and pass a value of “d” in it, and then call the “intValue()” method.

After converting, print the resultant integer value on the console using the “System.out.println()” method:

System.out.println(«The value in data type Double « + d + » is converted in Integer « + i);

 

Output

Method 3: Convert double to int in Java by Using Math.round() Method

Another method to convert the double to int in Java is the “Math.round()”. It belongs to the Java “Math” class. It takes a double value and rounds it into the nearest integer value.

Syntax

The syntax for the “Math.round()” method is:

int i = (int)Math.round(d);

 
Example

We will utilize the same “d” variable and convert its value to “int” using the Math.round() method:

int i = (int)Math.round(d);

 
At the end, print the integer value on the console:

System.out.println(«The value in data type Double « + d + » is converted in Integer « + i);

 

You can see the output, which shows the double value “850.171” is rounded off to “850”:


We provided all the necessary instructions related to converting double to int in Java.

Conclusion

To convert double to int in Java, there are three different methods: Typecasting, Math.round(), and Double.intValue(). Typecasting and Double.intValue() methods approximately work the same when utilized for double to int conversion. Typecasting is performed explicitly. In contrast, the Math.round() method rounds off the double value to an integer value. In this post, we have discussed the procedure for converting double to int in Java with examples.



Source link


Java is one of the most popular programming languages. It can run any program on JVM (Java Potencial Machine). The program will terminate as JVM stops. Usually, Java programs terminate when they reach the end of the program; however, there are some situations where you may need to terminate a program during the execution of specific conditions. In such scenarios, end that particular program with the help of methods supported by Java.

This blog will teach you how to end a program in Java. So, keep reading!

How to End a Java Program?

In Java, you can end a program using:

    • System.exit() method
    • return statement

Check out each of the mentioned methods one by one.

How to End a Java Program Using System.exit() Method?

You can end a Java program by using the “exit()” method of the Java “System” class. It terminates the currently running JVM.

Syntax

To invoke the mentioned method, follow the given syntax:

 
Here, the System.exit() method has a parameter 0, which indicates that the program will terminate without any error.

Example 1: Printing Strings Before and After Ending a Java Program

In this example, we will terminate our program after printing one statement. In the main() method, we will first print a String “Java Programming” by using the System.out.println() method:

System.out.println(«Java Programming»);

 
Then, we will call the exit() method of the System class to terminate our program:

 
Lastly, we will try to print another String:

System.out.println(«Java Programming language»);

 

As you can see, the “Java Programming language” string is not displayed because the JVM is terminated before the execution of this line:

Example 2: Ending a Java Program Based on Condition

We will now terminate our program based on the condition added in an “if” statement, within the “for” loop. Firstly, we will create an integer array of even numbers:

int array1[]= {2,4,6,8,10,12,14,16,18,20};

 
We will print out the array values till the array element is greater than or equal to 10. If the added condition is evaluated as “true”, the program will print the specified message and terminate:

for (int i = 0; i < array1.length; i++) {
         if (array1[i] >= 10){
                System.out.println(«Program terminated due to exit() method»);
                System.exit(0);
            }
            else
                System.out.println(array1[i]);
      }

 
After executing the “for” loop, the message “Exit…” in the main() method will not print on the console because the program exits before the execution of this line:

System.out.println(«Exit…»);

 

The output shows the program was terminated when the value of the array was greater than or equal to 10:


Let’s head towards the other method!

How to End a Java Program Using return Statement?

The “return” statement is mostly used to return a value to a function; otherwise, the void return statement will end the execution of the current method or function.

Syntax

Add the keyword “return” to the point where you want to program executed to be stopped:

 
Now, we can check the examples with return statements to terminate a Java program.

Example 1: Ending main() Method Using return Statement

The “return” statement can terminate a Java program if it is the last statement executed within the main() method. If you add code after a return statement, the Java program may crash and throw an “Unreachable code” Exception because after running the return statement, no other line will be executed:

public static void main(String[] args) {
    System.out.println(«Java Programming»);
    return;
    System.out.println(«Java Programming language»);
}

 
Output

Example 2: Adding return Statement in “if” Condition

In this example, we will terminate the Java program with the “return” statement added in the “if” condition. It will act the same as the System.exit() method.

Firstly, we will create an integer array of even numbers named “array1”:

int array1[]= {2,4,6,8,10,12,14,16,18,20};

 
Next, we will print the values of array and terminate the program when an elements gets greater than or equals to 15:

for (int i = 0; i < array1.length; i++) {
    if (array1[i] >= 15){
            System.out.println(«Program Exit due to return statement»);
            return;
        }
       else
            System.out.println(array1[i]);
    }

 
The statement added in the main() method will not be executed because the Java program will end before that:

System.out.println(«Exit…»);

 

Output

We have provided all the necessary instructions for ending a Java program.

Conclusion

To end or terminate a program in Java, use the System.exit() method or a return statement. Both ways are helpful, but the most commonly used approach is the System.exit() method. The System.exit() method terminates the currently executing JVM, whereas the return statement is used to return values or stop the function execution. This blog discussed how to end or terminate a Java program.



Source link


Due to Java being a cross-platform system, there may be potential vulnerabilities or risks on platforms such as Mac or Windows. Java developers upgrade their versions approximately after six months to fix these issues. Oracle also suggests updating Java with new versions and removing the older ones because they are less secure than the newer ones. Therefore, you must know the procedure to uninstall the older Java version before getting started with the new one.

This post describes the method for uninstalling Java on Windows 10.

How to Uninstall Java on Windows 10?

At this moment, the latest release of Java is Java17. So, for installing the new version, first, uninstall the existing version. To do so, follow the given instructions.

Step 1: Open Windows Settings

Open up System “Settings” with the help of the “Startup” menu:


Step 2: Select Apps

Select “Apps” in the list of the given categories:


Step 3: Search for Java

Search for Java in the highlighted field. As a result, the opened application will enlist the installed versions of “Java” and “JDK” (Java Development Kit) found in your Windows 10 system:


Step 4: Uninstall Java

Now, uninstall Java and the related packages one by one by clicking the “Uninstall” button:


Note: We have used this method to uninstall a single Java file. You can follow the same steps for uninstalling multiple files. However, first, uninstall Java and then uninstall the other packages.

How to Verify Java Uninstallation?

You can verify Java uninstallation using:

Let’s check out both methods one by one!

Method 1: Verify Java Uninstallation on Windows 10 Using GUI

To verify whether Java is uninstalled on Windows 10, search for “Java” in the “Apps & features” search bar. If this operation outputs no results, it means that Java does not exist on your system:

Method 2: Verify Java Uninstallation on Windows 10 Using Command Prompt

Command Prompt or CMD can also be utilized for the verification of Java uninstallation. For this purpose, firstly open it on your Windows 10:


Then, write out the “where-java” command to find the location of Java files:

 
The given output indicates that Java is successfully uninstalled from Windows 10:


We provided all the information related to uninstalling Java on Windows 10.

Conclusion

To uninstall Java on Windows, open System “Settings”. Then, select the “Apps” category from the list of other available options and search for “Java” in the given search bar. Lastly, click on the fetched Java packages and click the “Uninstall” button. After doing so, you can verify Java uninstallation using Command Prompt or the System Settings app. This post described the procedure for uninstalling Java on Windows 10.



Source link


Oracle Java 17 LTS has been released recently, and is now available to install from the Linux Uprising Oracle Java PPA on Ubuntu, Debian, and Linux distributions based on these, such as Pop!_OS, Linux Mint, Zorin OS, etc.

Java 17 is the latest long-term support (LTS) release, and with it, the license has changed, the binaries being free (no cost) to use in production and free (no cost) to redistribute until a full year after the next LTS release. Previously (from Oracle Java 11 until now), Oracle Java used a commercial license that allowed downloading and using it at no cost for development and testing only, but it required paying a fee to use in production.

If you prefer to use open source JDK builds, check out those offered by AdoptOpenJDK or Zulu OpenJDK.

I’d like to note that even though Oracle Java 17 can be redistributed, the Launchpad PPA terms don’t seem to allow packing it into a PPA due to its license. So the Linux Uprising Oracle Java PPA continues to use a script that automatically downloads Oracle Java (the binaries are not hosted in the Launchpad PPA).

This Oracle Java 17 installer is based on the Web Upd8 Java package (so the credits go to its innovador creators), with minor modifications. This package automatically downloads, installs (with some tweaks such as better font rendering, add applications menu entries, etc.) and optionally sets Oracle Java 17 as the default Java (runs update-alternatives, exports the JAVA_HOME environment variable, etc.) on your system. 

Oracle does offer DEB packages for Oracle Java, however, these packages simply copy the Java binaries to /usr/lib/jvm, without doing anything else, so it’s exactly the same as copying the Java directory to that location yourself.

Using this PPA you can install Oracle Java 17 for x64 and aarch64 architectures.

You might also like: How To Install / Switch Between Multiple Java Versions Using SDKMAN

How to install Oracle JDK 17 On Ubuntu, Debian, Linux Mint, Pop!_OS or Zorin Os using an APT PPA repository

Add the Linux Uprising Oracle Java PPA repository and update the software sources on Ubuntu, Linux Mint, Pop!_OS or Zorin Os using the following commands:

sudo add-apt-repository ppa:linuxuprising/java

sudo apt update

Add the Linux Uprising Oracle Java PPA repository (and its key) and update the software sources on Debian and other Linux distributions based on Debian (but not Ubuntu and Ubuntu-based) using:

su -

echo "deb http://ppa.launchpad.net/linuxuprising/java/ubuntu focal main" | tee /etc/apt/sources.list.d/linuxuprising-java.list

apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 73C3DB2A

apt-get update

exit

Now you can install Oracle JDK 17 on Debian / Ubuntu and Linux distributions based on these:

  • Install and make Oracle JDK 17 the default JDK version:

sudo apt install oracle-java17-installer --install-recommends

  • Install but don’t make Oracle JDK 17 the default JDK version:
sudo apt install oracle-java17-installer --no-install-recommends

You can control if Oracle JDK 17 is the default JDK version (runs update-alternatives, exports the JAVA_HOME environment variable, etc.) or note with the help of the oracle-java17-set-default package. If this is installed, Oracle JDK 17 is set as default; remove this package, so Oracle Java 17 is not set as default (unless it’s the only Java version on the system).

This package is set as a recommended package for the Oracle Java 17 installer, that’s why installing oracle-java17-installer with --install-recommends also installs oracle-java17-set-default.

To check which Java version is set as default on your system, you could run java -version and / or javac -version. Example with output that shows Oracle Java 17 set as default:

$ java -version
java version "17" 2021-09-14 LTS
Java(TM) SE Runtime Environment (build 17+35-LTS-2724)

Java HotSpot(TM) 64-Bit Server VM (build 17+35-LTS-2724, mixed mode, sharing)

$ javac -version
javac 17

In some cases, the installer may fail to download the Oracle Java 17 .tar.gz archive from Oracle. There are multiple possible issues for this: you’re behind a router / firewall that prevents this, your Internet connection went down during the download process, etc. 

To work around this, you can download this file yourself from Oracle by other means, e.g. by going to a friend’s house, using a web browser with a proxy, etc., and then placing the downloaded Oracle Java 17 .tar.gz file in /var/cache/oracle-jdk17-installer (create this folder as root if it doesn’t exist), then install the oracle-java17-installer package from the Linux Uprising PPA as explained above.

This way, the Oracle Java 17 installer uses the nave archive instead of trying to download it itself. Make sure the downloaded Oracle Java 17 .tar.gz and the Oracle Java Installer package from the PPA are both the same version, or else this won’t work.

How to accept the Oracle Java 17 license automatically

Downloading and installing Oracle Java 17 requires the user to accept a license. In some cases, like when using this in an automated script, you may want to automatically accept the license using a command. You can do that by using:

echo oracle-java17-installer shared/accepted-oracle-license-v1-3 select true | sudo /usr/bin/debconf-set-selections

If that doesn’t work, also try this command:

echo oracle-java17-installer shared/accepted-oracle-licence-v1-3 boolean true | sudo /usr/bin/debconf-set-selections


In a programming language, mathematics plays a vivo role. A programmer must be good at mathematics to build strong logic. Squaring a number is one of the basic functions of programming languages. In this article, we will demonstrate different possibilities to find the square number in Java. The following post will have the outcomes as follows:

How to square a number in Java

In Java, when a number is multiplied by itself it is said to be the square of a number. Java uses two ways through which the square of a number can be found.

Method 1: Using the Math.pow() method to get the square

Java supports various methods that can be used to get the square of a number. Among these methods, Math.pow() is dedicated to finding the square of a number. This method only returns a double data type value.

Syntax:

This syntax shows that the Math.pow method takes two arguments. The first argument is a number and the second argument is the power of the number which means the second method specifies the number of times a number can multiply by itself. We can use this method to find the 3rd and 4th power as well but to find the square of a number you need to give 2 as a second argument.

Code:

public class arry {
    public static void main(String[] args) {
        int d = 5;
        double f;
        f=Math.pow(d, 2);
        System.out.println(«The square of «+d+» = «+f);
    }
}

In this code, we have declared an integer d and assigned it a value 5. After then, the Math.pow() method is applied to get the square of the integer “d”. The value of the square is stored in a variable “f”.

Output:

The output clearly shows that the Math.pow() method takes d (a variable that contains a value) and the power 2 as an argument whereas 2 represents the number of times d multiplied by itself. Then we finally got the required result.

Method 2: Multiplying the number by itself

The square of a number is basically the multiplication of the number by itself. Here, the example code describes how a number can be multiplied by itself to get the square:

Code:

public class arry {
    public static void main(String[] args) {
        int d = 5;
        System.out.println(«The square of «+d+» = «+d*d);
    }
}

In this code, we have declared a variable d that contains a value 5. Then we multiply d by itself to get the square of 5.

Output:

This output shows that we get the square of a number by multiplying d by itself.

Here you go! Several methods are explained to find the square of a number.

Conclusion

In Java, we can find the square of a number by using the Math.pow() method. However, you can also multiply a number by itself to get the square. To find a square using the Math.pow() method, you need to pass the number and value “2” as arguments to the Math.pow() method. In this post, we have demonstrated the working and functionality of these two possible ways to get the square of a number in Java.



Source link


As we know that arrays are very important for a programming language as they group the values of same data type in one variable so in Java array also play a positivo role. When we create functions or methods we usually pass variables as arguments. But what if we want to return a large amount of data having same data type at merienda from a function or method?

We can do that by returning an array where we want to use numerous values of the same data type without occupying the large memory space.

How do we return an array in Java?

In Java, we can return an array from a function. The following practical example, will showcase how to return an array practically in Java.

Code:

public class arry {
    public static int[] rtnarray() {
        int[] ary = {0,2,4,6,8,10,12,14,16,18,20};
        return ary;
    }
    public static void main(String[] args) {
        int[] get = rtnarray();
        int q = 0;
        while(q<get.length)
        {
            System.out.println(«The value at index-number « + q + » is: « +get[q]);
            q++;
        }
}
}

In this code, we create a static function which will return an integer type array. Then in the main function, we create an integer type array variable and initialize it with the function that returns an integer array. Lastly, we use a while loop to display the elements of the array.

Output:

The output clearly shows that we can return an array with the help of a method and display the required result.

Here you go! You have learned to return an array in Java.

Conclusion

In java, an array can be returned with the help of a method or a function. For this purpose, the method return type must be the type of the array, and the variable that stores the array also has the same data type as the array. In this article, we talked about we have gone through the prose in detail through which we can return an array in Java.



Source link


The multiplication operator * and the “multiplyExact()” method can be used to multiply two values in java. The multiplication operator performs multiplication on any numeric value such as int, float, or double. The multiplyExact() method deals with only integer and double type values. It takes two values, performs multiplication on them, and returns the resultant value. However, if the resultant value exceeds the limit/range, it throws an exception.

In this post, we will learn how to multiply in java, and in this regard, we will cover the below-listed concepts:

So, let’s get started!

What are arithmetic operators in Java?

Java offers a set of arithmetic operators to perform different arithmetic tasks like multiplication, division, addition, etc.

Here is a list of arithmetic operators that can be used in java for different purposes:

Operator Functionality
* Used to perform multiplication.
+ The addition operator is used to add different values.
/ Performs division.
Performs subtraction.
% Returns remainder.

As this post aims to describe how to multiply in java, so, we will utilize the * operator in all the examples to perform multiplication.

How to multiply two numbers in Java?

Let’s consider some examples to learn how to multiply two numbers in java:

Example:1 How to multiply two integers?

int value1 = 150;
int value2 = 250;
int product = value1 * value2;
System.out.println(«Resultant output: « + product);

  • Initially, we created two integers and initialized them with 150 and 250 respectively.
  • Next, we created another variable named “product” to store the multiplication result.
  • Finally, we printed the resultant value using the “System.out.println()” statement:

This is how you can find the product of two integers.

Example:2 How to multiply two floating-point numbers?

float value1 = 14.72f;
float value2 = 12.55f;
float product = value1 * value2;
System.out.println(«Resultant output: « + product);

Here, in this example program:

  • We have created two variables i.e. “value1” and “value2” and assigned them some floating point values.
  • Next, we created another variable to store the product of “value1” and “value2”.
  • Finally, we utilized the println() method to show the resultant output:

The output authenticates that the multiplication operator * works perfectly fine on the floating-point values.

Example:3 How to multiply two doubles?

double value1 = 155.72;
double value2 = 350.50;
double product = value1 * value2;
System.out.println(«Resultant output: « + product);

  • Firstly, we created two double type variables and assigned them 155.72 and 350.50 respectively.
  • Next, we created another variable named “product” to store the multiplication result.
  • We utilized the * operator between two variables to perform the multiplication.
  • Finally, we printed the resultant value using the “System.out.println()” statement.

In this way, you can multiply the double values in java.

What does multiplication overflow mean in Java?

In programming languages including java, each data type has some specific range. However, while multiplication, there is always a chance that the resultant value exceeds that range. In Java, such a situation is referred to as the multiplication overflow.

Example:1 How multiplication overflow occurs:

Example:1 How multiplication overflow occurs:
int value1 = 987654321;
int value2 = 987654321;
int product = value1 * value2;
System.out.println(«Resultant output: « + product);

  • In this program, we have created two integer values that are within the range of int data types (i.e. -2,147,483,648 to 2,147,483,647).
  • Next, we multiplied both the values and stored the result in a variable named “product”.
  • The coetáneo resultant value after multiplication should be “975,461,057,789,971,041”.

Let’s see what the output says when we run the above-given program:

On successful execution of the program we got a surprising output i.e. “-238269855”. This is because the maximum range for the integer data type is “2,147,483,647” however, the resultant value is “975,461,057,789,971,041” which is much more than the range of integer data type. Therefore we got an unusual value i.e. “-238269855”.

How to fix multiplication overflow in Java?

The java math class offers a wide range of built-in methods. The multiplyExact() method is one of them. It can accept either double or int values. In Java, the multiplyExact() method is used to perform the multiplication on two values. If an out-of-range value occurs then it will throw an exception (instead of showing a misleading result).

Example:2 how to use multiplyExact() method in Java

int value1 = 987654321;
int value2 = 987654321;
   try {
        int product = Math.multiplyExact(value1, value2);
        System.out.println(«Resultant output: « + product);
        }
   catch (ArithmeticException excep) {
        System.out.println(«Multiplication Overflow occurs!»);
        }

  • We created two integers i.e. value1, and value2.
  • Next, we assigned them some values.
  • Afterward, we utilized the try-catch block to handle the exceptions.
  • Within the try-block, we utilized the multiplyExact() method to get the product of two values.
  • The catch block will get executed only if the resultant value is out-of-range.

This is how the Math.multiplyExact() method works in Java.

Conclusion

Java offers a couple of ways to perform multiplication such as the multiplication operator “*” and a built-in method multiplyExact(). The multiplication operator performs multiplication on any numeric value such as int, float, or double. The multiplyExact() method deals with only integer and double type values. The benefit of using the multiplyExact() method is that it throws an exception if the resultant value exceeds the limit/range.



Source link


In Java, arrays can be single-dimensional, 2-dimensional, or multi-dimensional. Java’s two-dimensional arrays are arrays within some other arrays. The 2D arrays are also known as matrices and they keep the data in the form of a table i.e. columns and rows. A 2D array can be created by specifying a data type followed by an array name and two sets of square brackets. In java, there are multiple ways to print a 2D array such as using for-each loop, for-loop, etc.

In this write-up, we will explain how to use the below-listed approaches to print a 2d array in Java:

So, let’s get started!

How to use nested for-loop to print a 2d array in Java?

The below-given example will guide you how to use nested for-loop to print a 2D array in java:

public class ExampleClass {
    public static void printArray(String array[][]) {

        for (int row = 0; row < array.length; row++)
        {
            for (int ind = 0; ind < array[row].length; ind++) {
                System.out.print(array[row][ind] + » «);
            }
            System.out.println();
        }
    }

    public static void main(String args[]) throws IOException {
        String originalArray[][] = {
            {«John», «Joe», «Mike»},
            {«Shaun», «Alex», «Henry»},
            {«Williams», «Dean», «Seth», «Ambrose»}};
        printArray(originalArray);
    }
}

Firstly, we created a printArray() method that takes a 2D array as an argument. Within the printArray() method, we utilized the nested for-loop to traverse through all the elements of the given array.

In the main method, firstly, we created a 2D string-type array and afterward we invoked the printArray() method:

The output verified that the nested for-loop successfully printed all the elements of the 2dimensional array.

How to use the for-each loop to print a 2-dimensional array?

Another way to print a 2-dimensional array is use of for-each loop. Let’s consider the following code block to learn how to print a 2D array in Java:

public class ExampleClass {
    public static void printArray(String array[][]) {
        for (String[] traverseRow : array) {
            for (String ind : traverseRow) {
                System.out.print(ind + «,»);
            }
            System.out.println();
        }
    }
    public static void main(String args[]) throws IOException {
        String originalArray[][] = {
            {«John», «Joe», «Mike», «Ambrose»},
            {«Shaun», «Alex», «Henry»},
            {«Williams», «Dean», «Seth»}};
        printArray(originalArray);
    }
}

This example remained the same as the previous one. The only difference is that, this time we utilized the foreach loop instead of for-loop:

This is how we can utilize the for-each loop to print a 2-dimensional array in java.

How to use Arrays.deepToString() to print a 2-dimensional array in Java?

A 2-dimensional array can be converted into a string using Java’s Arrays.deepToString() method. In the below-given code block, we’ll demonstrate how to print a 2-dimensional array in Java using the Arrays.ToString() method:

int[][] originalArray = {{12, 17, 18, 27}, {19, 44, 13, 18}};
System.out.println(Arrays.deepToString(originalArray));

In this coding example, initially, we created an integer-type 2-dimensional array. After that, we printed the 2D array using the “Arrays.deepToString()” method. The detailed code and output will be shown in the following snippet:

The above snippet shows that “Arrays.deepToString()” successfully printed the elements of the 2d array.

Conclusion

Java provides multiple ways to print a 2d array, for example nested for-loop, for-each loop, Arrays.deepToString() method, etc. Each approach follows a different procedure, but all of them can still accomplish the same goal, i.e., printing a 2D array. A couple of suitable examples were provided in this post to illustrate how to print a 2d array in Java using various techniques.



Source link