Tag Archives: Java

Introduction to Java

Java is a high level, modern programming language designed in the early 1990s by Sun Microsystems, and currently owned by Oracle.
Java is Platform Independent, which means that you only need to write the program once to be able to run it on a number of different platforms!
Java is simple,portable, robust, dynamic,and secure,with the ability to fit the needs of virtually any type of application.
Java guarantees that you’ll be able to Write Once, Run Anywhere.

               More than 3 billion devices run Java.

Java is used to develop apps for Google’s Android OS, various Desktop Applications, such as media players, antivirus programs, Web Applications, Enterprise Applications (i.e. banking), and many more!

             Your First Java Program

Let’s start by creating a simple program that prints “Hello World” to the screen.

public class HelloWorld {
 public static void main(String[ ] args) {
 System.out.println("Hello World");
 }
}

In Java, every line of code that can actually run needs to be inside a class.
In our example, we named the class HelloWorld.

In Java, each application has an entry point, or a starting point, which is a method called main. Along with main, the keywords public and static will also be explained below.
As a summary:
a) Every program in Java must have a class.
b) Every Java program starts from the main method.

The main Method

To run our program, the main method must be identical to this signature:

public static void main(String[ ] args)
1. public: anyone can access it.
2. static: method can be run without creating an instance of the class containing the main method.
3. void: method doesn’t return any value.
4. main: the name of the method

For example, the following code declares a method called foo, which does not return anything and has no parameters:

void foo()
The method‘s parameters are declared inside the parentheses that follow the name of the method. For main, it’s an array of strings called args.
Next is the body of the main method, enclosed in curly braces:
{
 System.out.println("Hello World!");
}
The println method prints a line of text to the screen.
The System class and its out stream are used to access the println method.
In classes, methods, and other flow-control structures code is always enclosed in curly braces { }.

              Semicolons in Java

You can pass a different text as the parameter to the println method to print it.

class DemoClass {
 public static void main(String[ ] args) {
 System.out.println("I am learning Java");
 }
}

In Java, each code statement must end with a semicolon.
Remember: do not use semicolons after method and class declarations that follow with the body defined using the curly braces.

Java program to find Sum of proper divisor of a number

Given a natural number n, calculate sum of all its proper divisors. A proper divisor of a natural number is the divisor that is strictly less than the number.

For example, number 10 has 3 proper divisors: 1, 2, 5 and the divisor summation is: 1 + 2 + 5 = 8.



import java.util.*;
import java.lang.*;
import java.io.*;

class SumOfDivisors {
    public static void main (String[] args) {
        Scanner sc=new Scanner(System.in);
            System.out.println("Enter a number:");
            int n=sc.nextInt();
            int result=1;
            for(int i=2;i<Math.sqrt(n);i++){
                if(n%i==0){
                    if(n/i==0){
                        result +=i;
                    }else{
                        result +=(i+n/i);
                    }
                }
            }
            System.out.println(result);
        
    }
}

All divisor of a natural number(three ways)

Given a number n, print all distinct divisors of it , including 1 and the number itself.

Example:

Input: n=20

output: 1 2 4 5 10 20
input n=125
output: 1 5 25 125
Method 1: A solution would be to iterate all the number from 1 to n, checking if that number divides n and print it.

Method 2: A solution would be to iterate all the number from 1 to square root of n, checking if that number divides n and print the number pair if number pair are equal then print only one. It print the divisors in small-big pair.

Method 3: A solution would be to iterate all the number from 1 to square root of n, checking if that number divides n and print the first number and store the second number in a list if number pair are equal then print only one and print the list in reverse order. It print the divisors in sorted order.

Below is a java program for the same.

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sani Kamal on 29-May-17.
 */
//Java program to find all divisors of a natural number including
// 1 and the number itself
public class PrintDivisors {
    //Method to print all divisors
    //Time complexity: O(n)
    //Auxiliary Space= O(1)
    //It prints divisors in sorted order
    private static void printDivisorAsc(int number) {
        for (int i = 1; i <= number; i++) {
            if (number % i == 0) {
                System.out.print(i + " ");
            }

        }
    }

    //Method to print all divisors
    //Time complexity: O(log(n))
    //Auxiliary Space= O(1)
    //it prints divisors in random order
    private static void printDivisorRand(int number) {
        //This loop run till square root
        for (int i = 1; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                //If divisors are equal, print only one
                if (number / i == i) {
                    System.out.print(i + " ");

                }
                //otherwise print both
                else {
                    System.out.print(i + " " + number / i + " ");
                }
            }

        }
    }
    //Method to print all divisors,it prints divisors in sorted order
    //Time complexity: O(log(n))
    //Auxiliary Space= O(1)
    private static void printDivisorSorted(int number) {
        List li=new ArrayList<Integer>();
        //This loop run till square root
        for (int i = 1; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                //If divisors are equal, print only one
                if (number / i == i) {
                    System.out.print(i + " ");

                }
                else {
                    System.out.print(i + " ");
                    // add the second divisor in list
                    li.add(number/i);
                }
            }

        }
        //The list will print reverse
        for (int i = li.size()-1; i >=0 ; i--) {
            System.out.print(li.get(i)+" ");

        }
    }
        //Driver program to test above method
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a number to find divisors:");
        try {
            int num = Integer.parseInt(br.readLine());
            printDivisorAsc(num);
            System.out.println();
            printDivisorRand(num);
            System.out.println();
            printDivisorSorted(num);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }
}




Output

"C:\Program Files\Java\jdk1.8.0_65\bin\java" 
Enter a number to find divisors:
124
1 2 4 31 62 124 
1 124 2 62 4 31 
1 2 4 31 62 124 
Process finished with exit code 0

java program that lists all the files in a given directory

java program that lists all the directory and files in a given directory

import java.io.File;

/**
 * java program that lists all the files in a given directory
 * Created by sani kamal on 07-May-17.
 */
public class FileListing {
    public static void main(String[] args) {
        String dirPath = "C:\\Program Files\\Java\\jdk1.8.0_65\\db";
        File basedir = new File(dirPath);
        if (basedir != null && basedir.exists()) {
            File[] files = basedir.listFiles();
            System.out.println("Files in the directory:" + basedir.getAbsolutePath());
            System.out.println("Is directory writable: " + basedir.canWrite());
            System.out.println("Is directory readable: " + basedir.canRead());
            System.out.println("Numbers of file or directory:" + files.length);
            File file;
            for (int i = 0; i < files.length; i++) {
                file = files[i];
                if (file.isDirectory()) {
                    System.out.println("Directory:" + file.getName());
                } else {
                    System.out.println("File:" + file.getName());
                }

            }
        } else {
            System.out.println("Please provide a valid directory path...");
        }
    }
}

Tower of Hanoi implementation in java

The Tower of Hanoi (also called the Tower of Brahma or Lucas’ Tower  and sometimes pluralized) is a mathematical game or puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a canonical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  1. Only one disk can be moved at a time.
  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  3. No disk may be placed on top of a smaller disk.

With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2n − 1, where n is the number of disks.

Recursive Algorithm

The recursive solution to move n discs from the start pole to the end pole using an auxiliary pole is given below.

Base Case – When n = 1
Move the disc from start pole to end pole
Recursive Case – When n > 1
Step 1: Move (n-1) discs from start pole to auxiliary pole.
Step 2: Move the last disc from start pole to end pole.
Step 3: Move the (n-1) discs from auxiliary pole to end pole.
Steps 1 and 3 are recursive invocations of the same procedure.
Java Program
The recursive program for the puzzle in Java is given below:
<pre>import java.util.Scanner;

/**
 * java program to implement tower of hanoi
 * Created by sani kamal on 07-May-17.
 */
public class TowerOfHanoi {
    //main function
    public static void main(String[] args) {
        System.out.println("Enter number of disc:");
        Scanner sc = new Scanner(System.in);
        int numberOfDiscs = sc.nextInt();
        moveDiscs(numberOfDiscs, "A", "B", "C");


    }

    public static void moveDiscs(int n, String start, String middle, String end) {
        //Moved n-th disc to the end pole
        if (n == 1) {
            System.out.println("Move " + n + " disc from " + start + " to " + end);
        } else {
            //Move n-1 discs from start pole to the midle
            moveDiscs(n - 1, start, end, middle);
            System.out.println("Move " + n + " disc from " + start + " to " + end);
            //Move n-1 discs from middle pole to the end
            moveDiscs(n - 1, middle, start, end);

        }

    }
}</pre>

Java Program to Implement Euclid GCD Algorithm using Recursion

The Euclidean algorithm calculates the greatest common divisor (GCD) of two number a and b. The greatest common divisor g is the largest natural number that divides both a and b without leaving a remainder. Synonyms for the GCD include the greatest common factor (GCF), the highest common factor (HCF), the highest common divisor (HCD), and the greatest common measure (GCM).

The Algorithm

The Euclidean Algorithm for finding GCD(A,B) is as follows:
  • If A = 0 then GCD(A,B)=B, since the GCD(0,B)=B, and we can stop.
  • If B = 0 then GCD(A,B)=A, since the GCD(A,0)=A, and we can stop.
  • Write A in quotient remainder form (A = B⋅Q + R)
  • Find GCD(B,R) using the Euclidean Algorithm since GCD(A,B) = GCD(B,R)
           // Function to return gcd of a and b
        int gcd(int a, int b)
          {
             if (a == 0)
                 return b;
             return gcd(b%a, a);
           }
This is a program to find GCD (Greatest Common Divisor) of two numbers using Euclid’s Algorithm.
<pre>import java.util.Scanner;

/**
 * Java Program to Implement Euclid GCD Algorithm using Recursion
 * Created by sani kamal on 07-May-17.
 */
public class GCDEuclid {
    //main function
    public static void main(String[] args) {
        GCDEuclid gcdeu = new GCDEuclid();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number1:");
        int num1 = sc.nextInt();
        System.out.println("Enter number2:");
        int num2 = sc.nextInt();
        System.out.println("GCD of " + num1 + " and " + num2 + " is:" + gcdeu.gcd(num1, num2));


    }

    // This function calculate GCD
    private int gcd(int a, int b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);

    }
}</pre>
The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
"C:\Program Files\Java\jdk1.8.0_65\bin\java" -Didea.launcher.port=7536 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_65\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_65\jre\lib\rt.jar;C:\Users\THINKSONU\IdeaProjects\JavaByExample\out\production\JavaByExample;C:\Users\THINKSONU\IdeaProjects\JavaByExample\lib\laf-plugin-7.2.1.jar;C:\Users\THINKSONU\IdeaProjects\JavaByExample\lib\laf-widget-6.3.jar;C:\Users\THINKSONU\IdeaProjects\JavaByExample\lib\substance-7.2.jar;C:\Users\THINKSONU\IdeaProjects\JavaByExample\lib\trident.jar.zip;C:\Users\THINKSONU\IdeaProjects\JavaByExample\lib\xmlbeans-2.6.0.jar;C:\Users\THINKSONU\IdeaProjects\JavaByExample\lib\poi-ooxml-schemas-3.14-20160307.jar;C:\Users\THINKSONU\IdeaProjects\JavaByExample\lib\poi-ooxml-3.14-20160307.jar;C:\Users\THINKSONU\IdeaProjects\JavaByExample\lib\poi-3.14-20160307.jar;C:\Users\THINKSONU\IdeaProjects\JavaByExample\lib\mail.jar;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.1.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.muktangon.net.recursion.GCDEuclid
Enter number1:
5
Enter number2:
25
GCD of 5 and 25 is:5

Process finished with exit code 0

java program to find n-th fibonacci number using recursion

The Fibonacci numbers are the numbers in the following integer sequence called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:

The fibonacci series is defined as follows:

0,1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , …

Recursive Algorithm for Fibonacci Numbers

Algorithm F(n)

if n ≤ 1 then return n

else return F(n-1) + F(n-2)

 

Full java program is given below:

<pre>import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * java program to find n-th fibonacci number using recursion
 * Created by sani kamal on 07-May-17.
 */
public class Fibonacci {
    public static void main(String[] args) {
        Fibonacci fib = new Fibonacci();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("Enter a number:");
            int num = Integer.parseInt(br.readLine());
            System.out.print(num+"th Fibonacci number is:" + fib.fibonacci(num));

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }

    private int fibonacci(int n) {
        if (n < 1)
            return 0;
        else if (n == 1)
            return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}</pre>

Java program to print Fibonacci sequence using array

This java program will print fibonacci sequence up to given number.

if input is 5 then the program print 0 1 1 2 3

<pre>import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * java program to print fibonacci sequence
 * Created by Sani Kamal on 05-May-17.
 */
public class FibonacciSequence {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("Enter the number of item to be printed: :");
            int num = Integer.parseInt(br.readLine());
            num = num > 2 ? num : 2;
            int[] fibArray = new int[num];
            fibArray[0] = 0;
            fibArray[1] = 1;
            for (int i = 2; i < num; i++) {
                fibArray[i] = fibArray[i - 1] + fibArray[i - 2];

            }
            System.out.println("Fibonacci Sequence..");
            for (int i = 0; i < num; i++) {
                System.out.print(fibArray[i]+" ");

            }


        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}</pre>

Java program to find 2nd largest and 2nd smallest number in a given array

<pre>import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * java program to find the largest,2nd largest,smallest and
 * 2nd smallest numbers in a given array
 * Created by Sani Kamal on 05-May-17.
 */
public class FindLargest {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.println("Enter size of array:");
            int num = Integer.parseInt(br.readLine());
            int[] numbers = new int[num];
            for (int i = 0; i < num; i++) {
                numbers[i] = (int) (Math.random() * 125);

            }
            //print all the numbers in  array
            System.out.println("Array Elements:");
            for (int i = 0; i < num; i++) {
                System.out.print(numbers[i] + " ");
            }
            System.out.println();
            //sort array
            Arrays.sort(numbers);
            System.out.println("Sorted array:");
            for (int number : numbers) {
                System.out.print(number + " ");
            }
            System.out.println();
            System.out.println("Largest element in array:" + numbers[num- 1]);
            System.out.println("2nd largest element in array:" + numbers[num - 2]);
            System.out.println("smallest element in array:" + numbers[0]);
            System.out.println("2nd smallest element in array:" + numbers[1]);

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}</pre>

Java program to find the smallest number of the three number

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class FindSmallest {
    public static void main(String[] args) {
        System.out.println("This program will find the smallest number of the three number");
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        try {
            System.out.println("Enter number1:");
            String input = br.readLine();
            int num1 = Integer.parseInt(input);
            System.out.println("Enter number2:");
            input = br.readLine();
            int num2 = Integer.parseInt(input);
            System.out.println("Enter number3:");
            input = br.readLine();
            int num3 = Integer.parseInt(input);
            int smallest = num1;
            if (num2 < smallest) {
                smallest = num2;
            }
            if (num3 < smallest) {
                smallest = num3;
            }
            System.out.println("Number Entered:" + num1 + " " + num2 + " " + num3);
            System.out.println("Smallest number:" + smallest);


        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }
}