Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to use Arithmetic Operators in Java ?.

Introduction:- 

Hello friends, In order to learn Java programming you must be very clear in Java fundamentals. You must have clear idea say how to use different kinds of operators in Java source code. Today in order to make you familiar with Operators used in Java, I will be providing you tutorial on Arithmetic Operator. Read more If you want some depth understanding on what are Arithmetic operator in Java ?. Here in this hub I will be telling you basic use of Arithmetic operator. I will be presenting before you the source code and than try to explain you code step-by-step. Our program code in this hub will require Java's basic knowledge such as : How to write your first Java program ?. and how to create, compile and run a java program ?.

Arithmetic Operator Explanation :-

The Java programming language uses arithmetic operators very extensively. Arithmetic operators are used where we have to perform basic mathematical computations. The mathematical computations such as addition, subtraction, division, multiplication etc . The operators used are: + for addition, - for subtraction, * for multiplication, / for division and % for modulus operator.

Program to demonstrate working of Arithmetic Operators :-


public class Arithmetic { 

  public static void main(String[ ] args) {
    int a = Integer.parseInt(args[0]);
    int b = Integer.parseInt(args[1]);
    int sum  = a + b;
    int prod = a * b;
    int quot = a / b;
    int rem  = a % b;
    int sub  = a - b;

    System.out.println(a + " + " + b + " = " + sum);
    System.out.println(a + " * " + b + " = " + prod);
    System.out.println(a + " / " + b + " = " + quot);
    System.out.println(a + " - " + b + " = " + sub);
    System.out.println(a + " % " + b + " = " + rem);
    System.out.println(a+ " = " +quot+ " * " +b+ " + " +rem);
  }
}


Output and Explanation of working of above sample code :-
When we run above program by command say : java Arithmetic 10 6 We get the following output on the console window:
10 + 6 = 16
10 * 6 = 60
10 / 6 = 1
10 - 6 = 4
10 % 6 = 4
10 = 1 * 6 + 4
Here we pass two command-line arguments "10" and "6". These two strings are passed as an argument to main method and gets stored in the form of an array. Where args[0] is assigned "10" value and args[1] is assigned "6" value. In order to use numeric value in program we need to parse string tointeger value. To do parsing we use Integer class which has method called as parseInt. This is static method and has argument which is a String. This method takes the String value and parses to numeric type. This values are assigned to int variables a and b.

Line 6 to 10:- All the lines from 6 to 10 do the Arithmetic Operations. Line 6 performs the addition of a and b by the use of + operator.Line 7 performs the multiplication of a and b by the use of * operator. Line 8 performs the division of a by b by the use of / operator. Line 9 performs the mod of a by b by the use of % operator. Line 10 performs the subtraction of b from a by the use of - operator.

Line 12 to 17:- Lines from 12 to 17 just prints the values calculated by applying above Arithmetic Operators. It uses System.out.println() method to perform all printing of values to console window.


Write a program to find factorial of a number in Java with and without recursion ?

Introduction :-

Hello friends, Today let us begin with a new Java program. Many of serious programmers who are just beginning to code in Java, come across a problem that is, how to write a program that calculate factorial of a number with and without recursion. Learning Java by an example is the most effective technique to inculcate this versatile language. Generally, whatever you know about language its additional when you have power to code small snippets. Learning by coding will not only give you command over the language but also develop the skills in you to code successfully. Java has a good implementation of using the recursion. I will be going to demonstrate the program with and without using concepts of recursion.


Factorial of a number formula :- In general logic to find a factorial of a number is simple and easy. The formula for finding the factorial of a number is : Factorial of a (n) number = n.(n-1).(n-2).(n-3). ...... .32.1 , If suppose we need to find factorial of number 5, it will be 5.4.3.2.1 = 120. In this hub I will be explaining you the code step by step that how a factorial of a number is calculated and printed on the console. The last section would be the code which will demonstrate the working of factorial number calculations. Factorial of a number without recursion :-  On example 1, I will be teaching you how to find factorial of a number without using idea of recursion. I will explain the code few lines first , followed by code and then rest of the explanation. The code will give you insight to some basic coding principles used in Java. Let us go for explanation for the code below : A closer look at the program stated below :- Line 1- Java has the ability to reuse the code. There are many predefined classes in Java which we will be using in our factorial calculation program. On line-1 we are importing Scanner class which is been kept in java.util package. Generally to help compiler in locating the class used in the program we use it regularly. Line 3 to 5 - Our Java program begins with a declaration of class named Factorial this class is declared as public so that it can be accessible to all Java class. Class Factorial contains a main method which is the entry point for every Java program. It is a static method so it is called by the JVM without any objects creation on heap. On next line there is a Java statement which just prints the String written in "". The println method just prints whatever is given to it in double quotes. Here in below example it first ask user , "Enter the number of for factorial calculations:". It asks user to enter a number for which he wants to calculate the factorial.
Click here to download complete source code 
import java.util.Scanner;

public class Factorial {
    public static void main (String[ ] args) {
      System.out.println("Enter the number for 
      factorial calculations : "); 

      Scanner scanner = new Scanner(System.in);
      
      int a = scanner.nextInt();
      double fact= 1;

      System.out.println("Factorial of " +a+ ":");
      for (int i= 1; i<=a; i++){
        fact=fact*i;
      }
      System.out.println(fact);
   }
} 
Line 7 to 11 :- On line 7, a new Scanner object is created on heap. The Scanner Class is used to read data from a keyboard or disk. Here variable name is scanner and type is Scanner. Here new operator is used to create a physical Scanner object on the heap. This Scanner object is used to read data from the keyboard. System.in passed into constructor of Scanner object generally reads data from the keyboard in bytes. It is the Scanner object which will convert bytes into types such as ints. Line 10 code uses Scanner method nextInt() to obtain user input as Integer, which he types on the keyboard. Generally upon execution of line, the program waits for user to type an int value from keyboard and press enter. Upon pressing enter value types by user gets assigned to int variable called as a. Factorial of a number with recursion :- On example 2, I will be teaching you how to find factorial of a number using idea of recursion. I will explain the code few lines first , followed by code and then rest of the explanation. The code will give you insight to some basic coding principles used in Java. Let us go for explanation for the code below : A closer look at the program stated below :- Whole code works same as above example. Only difference in the code is one is without recursion and other is with recursion. Line 11 calls static method fact by passing an integer to it. When returning from fact method it calls again fact method with integer value one less than previous integer value. The call sits on the stack till all the methods gets executed when value return from fact is 1. Now fact methods waiting on call gets executed sequentially, till last fact method gets executed and returns the calculated factorial value. Click here to download complete source code 
import java.util.Scanner;

public class Factorial {
  public static void main (String[ ] args) {
    System.out.println("Enter the number for "
         + "factorial calculations : "); 

    Scanner scanner = new Scanner(System.in);
      
    int a = scanner.nextInt();
    int result = fact(a);
    System.out.println("Factorial of " +a+ " is :"+result);
      
  }
  static int fact(int b){
   if(b <= 1)
     return 1;
   else
     return b * fact(b-1);
  }
}

Method Overloading in Java

Introduction

In Java, when we come across a question that what do you mean by method in Java ?. We can simply state its definition saying method is the small block of code that usually performs some specific tasks and help dividing program into specific modules. Generally we need methods because we want to use the concept of code reusability , that means suppose we have written few lines of code which are frequently been used in program. So each time if we want to execute the same code say with different values we wont type again and again. We simply create a method which will have that generic code which can be used by say different arguments passed through it. Thus, it will not impact performance.



What do you mean by Method Overloading in Java ?. 

By Method Overloading, we mean that we can declare methods of same name in a class as long as they have different signatures. By different signatures we mean method can be of same name but with different set of parameters. This difference in parameters can be determined by number , their types and order of their types. Generally, these methods almost perform same actions but they do it with different parameters and their types. Compiler calls an overloaded method based on the number of parameters passed to it, based on different data types used in that and based on order of parameters used.

Example using Method Overloading :- 

Below is the code that demonstrate the concept of method overloading. Here if we look closely to the example we have overloaded method by the name max(). This method is overloaded in the below sample code. If we closely look at the difference of max method declaration. We can see it has been defined by three different ways, lets look into that more closely :-
  • int max(intnum1, intnum2)
  • double max(doublenum1, doublenum2)
  • double max(doublenum1, doublenum2, doublenum3)
In first case, we have max method with two integer parameters. In second case, we have max method with two double parameters. in third case, we have max method with three double parameters. Thus difference in number, data types of parameters and order creates a method which can be overloaded. One note: method overloading has nothing to do with the return types. Generally, return types may or may not be same when we want a method to be overload.

A program to show concept of Method Overloading :


public class MethodOverloading {
  public static void main(String[ ] args) {
    System.out.println("The maximum between 4 and 6 is "
      + max(4, 6));
     
    System.out.println("The maximum between 4.2 and 6.4 is "
      + max(4.2, 6.4));
     
    System.out.println("The maximum between 4.2, 6.4 and 8.6 is "
      + max(4.2, 6.4 , 8.6));
  }
   
  public static int max(int num1, int num2){
    if (num1 > num2)
       return num1;
    else
       return num2;
  }
   
  public static double max(double num1, double num2){
    if (num1 > num2)
       return num1;
    else
       return num2;
  }
   
  public static double max(double num1, double num2, double num3){
    return max( max( num1,num2 ), num3 );
  }

}


Output and explanation of above code:-

Generally, above code is Java code, which performs operation to find the greatest number between the two / three variable. Let us look at the output printed on the console.
The maximum between 4 and 6 is 6
The maximum between 4.2 and 6.4 is 6.4
The maximum between 4.2, 6.4 and 8.6 is 8.6
Generally, in above line of code we have to understand how method max works. In the first case, we have defined two integer argument for max method.It takes two arguments and finds greatest number between the two through if-else construct. In the second case, we have defined two double argument for max method.It takes two arguments and finds greatest number between the two through if-else construct. In the third case, we have defined three double argument for max method.It takes three arguments and finds greatest number between the three through if-else construct and recursion.
 
© 2021 Learn Java by Examples Template by Hubberspot