on Leave a Comment

Java Program to Convert Binary to Decimal

This java program converts binary number into decimal number. First, you have to enter a binary number and then convert binary number to decimal number and finally print decimal equivalent of that binary number.

Java Program to Convert Binary Number to Decimal Number

import java.util.Scanner;

public class BinaryToDecimal
{
    public static void main(String args[])
    {
        int binary, decimal=0, i=1;
        Scanner read = new Scanner(System.in);
  
        System.out.print("Enter any Binary Number : ");
        binary = read.nextInt();
        
        int bin = binary;   
        int remainder = 1;

        while(binary > 0)
        {
            remainder = binary%10;
            decimal = decimal + remainder*i;
            i = i*2;
            binary = binary/10;
        }
  
        System.out.print("Decimal Equivalent of " +bin+ " is : "+decimal);
    }
}

Output:

Enter any Binary Number : 1111
Decimal Equivalent of 1111 is : 15

Java Program to Convert Binary to Decimal Using Integer.parseInt() Method

import java.util.Scanner;
class BinaryToDecimal {
    public static void main(String args[]){
       Scanner input = new Scanner( System.in );
       System.out.print("Enter any Binary Number: ");
       String binary =input.nextLine();

       System.out.println("Decimal Equivalent of " +binary+ " is : "+Integer.parseInt(binary,2));
    }
}

Output:

Enter any Binary Number: 1101
Decimal Equivalent of 1101 is : 13
on Leave a Comment

Java Program to Convert Decimal to Binary

This java program converts decimal number into binary number. First you have to enter a decimal number, then number will convert into its equivalent binary number and finally display on the screen.

Java program to convert decimal to binary

import java.util.Scanner;

public class DecimalToBinary
{
    public static void main(String args[])
    {
        int decimal;
        int binary[] = new int[100];
        Scanner scan = new Scanner(System.in);
  
        System.out.print("Enter a Decimal Number : ");
        decimal = scan.nextInt();

        int i = 1, num;
  
        num = decimal;
  
        while(num != 0)
        {
            binary[i++] = num%2;
            num = num/2;
        }
  
        System.out.print("Binary Equivalent of " + decimal + " is : ");
        for(int j=i-1; j>0; j--)
        {
            System.out.print(binary[j]);
        }
    }
}

Output:

Enter a Decimal Number : 25
Binary Equivalent of 25 is : 11001

Java Program to Convert Decimal to Binary Using toBinaryString() Method

import java.util.Scanner;

public class DecimalToBinary
{
    public static void main(String args[])
    {
        int decimal;
        Scanner scan = new Scanner(System.in);
        
        System.out.print("Enter a Decimal Number : ");
        decimal = scan.nextInt();
                
        System.out.print("Binary Equivalent of " + decimal + " is : "+Integer.toBinaryString(decimal));
    }
}

Output:

Enter a Decimal Number : 30
Binary Equivalent of 30 is : 11110

on Leave a Comment

FizzBuzz Program in Java

In this article, we will see FizzBuzz Program in Java. FizzBuzz is a most frequently asked question in interview. But, it is very simple.

In FizzBuzz program, we print a series of positive integers from 1 to n. If any number is completely divisible by 3 and 5, then print "FizzBuzz" and if any number is only completely divisible by 3, then print "Fizz" and if any number is only completely divisible by 5, then prints "Buzz", otherwise prints that positive integer. 

FizzBuzz Program in Java

import java.util.*;
class FizzBuzz
{
    public static void main(String[] args) {
        System.out.print("Enter the terms (in numbers):");

        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        for(int i=1;i<=n;i++)
        {
            if((i%3==0)&&(i%5==0))
              System.out.println("FizzBuzz");
            else if(i%3==0)
              System.out.println("Fizz");
            else if(i%5==0)
              System.out.println("Buzz");
            else 
              System.out.println(i);
        }
    }
}

Output:

Enter the terms (in numbers):20
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
on Leave a Comment

Java Method Overloading with Examples

In java, we can create different methods having same name but different parameters list and definition. This concept is called method overloading. Method overloading is useful when objects are required to perform similar task but having different parameters. For example, suppose you have to perform addition of numbers, then you write a method first(int a, int b) to add two number, then again you write a method second(int a, int b, int c) to add three numbers and so on. Now problem is, it is difficult to remember methods name for adding numbers. Method overloading allows similar methods having same name but having different number of parameters.

Ways to Overload Methods

- Having Different numbers of parameter.
- Parameters having different data type.
- Sequence of different data type parameters in parameter list.

Method overloading is way to achieve static polymorphism.

Examples of Methods Overloading

1. Having Different numbers of parameter.

class Example
{
 public int add(int a, int b)
 {
  return a+b;
 }
 public int add(int a, int b, int c)
 {
  return a+b+c;
 }
 public int add(int a, int b, int c, int d)
 {
  return a+b+c+d;
 }
}

class MethodOverloading
{
 public static void main(String[] args) {
  Example obj = new Example();

  System.out.println("Sum of 1 and 2 is "+obj.add(1, 2));
  System.out.println("Sum of 1, 2 and 3 is "+obj.add(1, 2, 3));
  System.out.println("Sum of 1, 2, 3 and 4 is "+obj.add(1, 2, 3, 4));
 }
}

Output:

Sum of 1 and 2 is 3
Sum of 1, 2 and 3 is 6
Sum of 1, 2, 3 and 4 is 10

2. Parameters having different data type.

class Example
{
 public int add(int a, int b)
 {
  return a+b;
 }
 public float add(float a, float b)
 {
  return a+b;
 }
}

class MethodOverloading
{
 public static void main(String[] args) {
  Example obj = new Example();

  System.out.println("Sum of 1 and 2 is "+obj.add(1, 2));
  System.out.println("Sum of 1.1 and 2.2 is "+obj.add(1.1f, 2.2f));
 }
}

Output:

Sum of 1 and 2 is 3
Sum of 1.1 and 2.2 is 3.3000002

3. Sequence of different data type parameters in parameter list.

class Example
{
 public float add(int a, float b)
 {
  return a+b;
 }
 public float add(float a, int b)
 {
  return a+b;
 }
}

class MethodOverloading
{
 public static void main(String[] args) {
  Example obj = new Example();

  System.out.println("Sum of 1 and 2.2 is "+obj.add(1, 2.2f));
  System.out.println("Sum of 1.1 and 2 is "+obj.add(1.1f, 2));
 }
}

Output:

Sum of 1 and 2.2 is 3.2
Sum of 1.1 and 2 is 3.1

Note: Return type doesn't matter in method overloading.

Can we overload java main() method?

Like other method, java main() method can also be overload.

But JVM always calls main methods having string array as parameter.

Example:

class MethodOverloading
{
 public static void main(String[] args) {
  System.out.println("Main method with String[] args");
 }
 public static void main(String args) {
  System.out.println("Main method with String args");
 }
 public static void main() {
  System.out.println("Main without parameter");
 }
}

Output:

Main method with String[] args


Method Overloading Valid/Invalid Cases

Invalid Cases

Case 1:

int add(int a, int b, int c)
int add(int x, int y, int z)

Invalid, because both method having same number of parameters with same data type and having same sequence.

Case 2:

int add(int a, int b, int c)
float add(int x, int y, int z)

Invalid, because both method having same number of parameters with same data type and having same sequence.

Valid Cases

Case 1:

int add(int a, int b)
int add(int a, int b, int c)

Valid, because both method have different number of parameters.

Case 2:

int add(int a, int b, int c)
float add(float a, float b)

Valid, because both method having different parameter type.

Case 3:

float add(int a, float b)
float add(float a, int b)

Valid, because both method having different sequence of parameters.

on Leave a Comment

Java Copy Constructor

copy constructor copies all the data members of an existing object to the new object of same class. In java, if we don't define any copy constructor, then compiler doesn't create default copy constructor. Copy constructor is similar to parameterized constructor except that we have to pass the reference of an object as the parameter. 

Example of Java Copy Constructor

class CopyConstructor
{
 int id;
 String name;
 CopyConstructor(int i, String n)
 {
  id = i;
  name = n;
 }
 void showData()
 {
  System.out.println("\nDetails:\nId : "+id+"\nName : "+name);
 }
 CopyConstructor(CopyConstructor c)
 {
  id = c.id;
  name = c.name;
 }
 public static void main(String[] args) {
  CopyConstructor c1 = new CopyConstructor(1, "Albert");
  c1.showData();
  CopyConstructor c2 = new CopyConstructor(c1);
  System.out.println("\nAfter Copy Constructor Execution, new object fields are:");
  c2.showData();
 }
}


Output:

Details:
Id : 1
Name : Albert

After Copy Constructor Execution, new object fields are:

Details:
Id : 1
Name : Albert
on Leave a Comment

Constructor in Java

Constructor is a special type of method that automatically calls when an object is created. Constructors are mainly used to initialize objects. We can also initialize an object with the help of methods, for example setData(). 

Rules for Creating Constructor

- Constructors have the same name as the class itself.

- Constructor has not any return type, even void.

- Constructors can have access modifier.

Types of Constructor in Java

There are two types of constructor in java.

Java No-Argument Constructor

A constructor that has no parameter is known as no-argument constructor. No-argument constructor is also known as default constructor. If we don't create any type constructor in a class, then compiler automatically creates default constructor. But if we define any type of constructor, then compiler does not create any constructor. Compiler created constructor initialize an object to the default value, depends on its data members. 

Example of Java No-Argument Constructor

class Testing 
{
 String name;
 int id;

 Testing()
 {
  System.out.println("A default constructor has no parameter");
 }
}
class DefConstructor
{
 public static void main(String[] args) {
  Testing t = new Testing();
 }
}

Output:

A default constructor has no parameter

Java Parameterized Constructor

A constructor that has parameters is known as parameterized constructor. A parameterized constructor can have one or more parameters. 

Example of Java Parameterized Constructor

class Testing 
{
 String name;
 int id;

 Testing(int x, String n)
 {
  id = x;
  name = n;
 }
 void showData()
 {
  System.out.println("Id : "+id+"\nName : "+name);
 }
}
class DefConstructor
{
 public static void main(String[] args) {
  Testing t = new Testing(1, "Bill");
  t.showData();
 }
}

Output:

Id : 1
Name : Bill

Constructor Overloading in Java

A class can have any number of constructors. Compiler differentiates constructors by number of parameters and type of parameters and order of constructors in which they are defined.

Example of Constructor Overloading in Java

class ConOverloading
{
 ConOverloading()
 {
  System.out.println("Default constructor is running");
 }
 ConOverloading(int x)
 {
  System.out.println("Parameterized constructor is running");
 }
 ConOverloading(ConOverloading c)
 {
  System.out.println("Copy constructor is running");
 }
 public static void main(String[] args) {
  ConOverloading c1 = new ConOverloading();
  ConOverloading c2 = new ConOverloading(10);
  ConOverloading c3 = new ConOverloading(c1);
 }
}

Output:

Default constructor is running
Parameterized constructor is running
Copy constructor is running





on Leave a Comment

Factorial Program in Java

This java program finds factorial of a number. Factorial of a number is the product of all positive descending integers.

For Example:

6! = 6*5*4*3*2*1 = 720

Java Program to Find Factorial of a Number

import java.util.Scanner;
class JavaFactorial
{
 public static void main(String[] args) { 
     Scanner sc = new Scanner(System.in);
     System.out.print("Enter a number to find factorial : "); 
     int num = sc.nextInt();
     long factorial = 1;
     for(int i = num; i > 0; --i)
     {
        factorial *= i;
     }
     System.out.print("Factorial of "+num+" is "+factorial);
 }
}

Output:

Enter a number to find factorial : 6
Factorial of 6 is 720

Java Program to Find Factorial of a Number Using Recursion

import java.util.Scanner;
class JavaFactorial
{
    static int factorial(int n){    
    if (n == 0)    
      return 1;    
    else    
      return(n * factorial(n-1));    
    }    
    public static void main(String[] args) { 
 Scanner sc = new Scanner(System.in);
 System.out.print("Enter a number to find factorial : "); 
 int num = sc.nextInt();
 long factorial = factorial(num);  
 System.out.print("Factorial of "+num+" is "+factorial);
    }
}

Output:

Enter a number to find factorial : 6
Factorial of 6 is 720

on Leave a Comment

Java Program to Calculate the Sum of Natural Numbers

This java program calculates the sum of natural numbers. First you have to ask "How many numbers do you want to enter?" and then read all numbers and store the sum of all number in a variable.

Java Program to Calculate the Sum of Natural Numbers

import java.util.Scanner;

class SumNum
{
 public static void main(String[] args) {
  System.out.print("How many numbers do you want to enter?   ");
  int n, sum = 0;
  Scanner sc = new Scanner(System.in);
  n = sc.nextInt();
  for(int i = 0; i<n; i++)
  {
   System.out.print("Enter "+(i+1)+" number : ");
   sum = sum + sc.nextInt();
  }
  System.out.println("Sum of all number is "+sum);

 }
}

Output:

How many numbers do you want to enter?   5
Enter 1 number : 1
Enter 2 number : 8
Enter 3 number : 7
Enter 4 number : 4
Enter 5 number : 5
Sum of all number is 25
on Leave a Comment

What is Protocol in Networking?

Protocol is a set of rules for efficient data communication over a network. In a network, communication occurred between different systems that are capable for sending or receiving data. But all systems are not able to send to receive data as we expect. For this, all system should be agree on a protocol. 

Protocols defines:

How to find destination IP addresses?

How to send data back and forth?

When to communicate and so on.

Protocols exist at various different level of journey of overall communication. In the OSI model and TCP/IP model, protocols presents in each layer for different functions. There should be the same protocol on both sender and receiver side.

A protocol has some key elements:

Syntax : The 'syntax' defines the structure and format of data. It defines how data is represented.

Semantics : It defines how data is interpreted what action to take based on interpretation. 

Timing : Timing defines how fast data would be sent and when to send data.

Some Protocols are:

FTP File Transfer Protocol

SMTP Simple Mail Transfer Protocol

TCP Transmission Control Protocol

Telnet Teletype Network

HTTP Hyper Text Transfer Protocol

HTTPs Secure Hyper Text Transfer Protocol

POP Post Office Protocol

HTCPCP Hyper Text Coffee Pot Control Protocol

MTP Media Transfer Protocol

SFTP Secure File Transfer Protocol

SSL Secure Socket Layer

TLS Transport Layer Security

E6 Ethernet globalization protocols

NTP Network time protocol

PPP Point to Point Protocol

NNTP Network News Transfer Protocol

QOTD Quote Of The Day

IMAP Internet Message Access Protocol

on Leave a Comment

Java Program to Convert Fahrenheit to Celsius

This java program converts Fahrenheit to Celsius. First, user enters the temperature in Fahrenheit and this temperature is converting into Celsius temperature using simple formula:

f = c * 9/5 + 32;

Here is source code that converts temperature in Fahrenheit to Celsius.

Java Program to Convert Fahrenheit to Celsius

import java.util.Scanner;

public class FahrenheitToCelsius
{
    public static void main(String args[])
    {
        double fah;
        double cel;
  
        System.out.print("Enter Temperature in Fahrenheit : ");

        Scanner read = new Scanner(System.in);
        fah = read.nextFloat();
  
        cel = (fah-32) / 1.8;
  
        System.out.print("Temperature in Celsius = " + cel);
    }
}

Output:

Enter Temperature in Fahrenheit : 67
Temperature in Celsius = 19.444444444444443
on Leave a Comment

Java Program to Print Floyd's Triangle

This java program prints Floyd's triangle. The Floyd's triangle is right-angled triangular array of natural numbers. Here, nested for loop is used to print Floyd's triangle. 

Example of Floyd's triangle:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Java Program to Print Floyd's Triangle

class FloydsTriangle
{
	public static void main(String[] args) {
            int i, j;
	    int a = 1;
	    for ( i= 1 ; i <= 10 ; i++ )
            {
               for ( j = 1 ; j <= i ; j++ )
               {
                   System.out.print(a+" ");
                   a++;
               }
 
               System.out.println();
            }
	}
}

Output:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
on Leave a Comment

Java Program to Reverse an Array

This java program reverse an array. First, you have to enter the size of array, then enter array elements using keyboard. Then sorts array using for loop. Finally, display reversed array. 

The for loop which is actually reversing array, using three variables ij and temp. Variable j is containing index of last element and i contains index of first element and swapping is performed between arr[i] and arr[j] using temp variable. After swapping, j decrements and i increments, and for loop again executes until condition (i<j) hold true.

Java Source Code to Reverse an Array

import java.util.Scanner;

public class ReverseArray
{
   public static void main(String args[])
   {
       int size;
       Scanner scan = new Scanner(System.in);
    
       System.out.print("Enter Size of Array  : ");
       size = scan.nextInt();

       int arr[] = new int[size];
       int i, j, temp;

       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = scan.nextInt();
       }
    
       //Reversing Array Using for Loop
       for(j = size-1, i = 0; i<j; j--, i++)
       {
           temp = arr[i];
           arr[i] = arr[j];
           arr[j] = temp;
       }
    
       System.out.print("Reversed Array is : ");
       for(i=0; i<size; i++)
       {
           System.out.print(arr[i]+ "  ");
       }       
   }
}

Output:

Enter Size of Array  : 5
Enter Array Elements : 1 2 3 4 5
Reversed Array is : 5  4  3  2  1
on Leave a Comment

Java for-each Loop | Enhanced for Loop

Java for-each loop is also known as enhanced for loop. This feature introduced with the J2SE 5.0 release. Java for-each loop is used to retrieve elements of array efficiently. This loop iterates through each element of array, so it is called for-each loop. Java for-each loop is also starts with for keyword.

Syntax of Java for each Loop

for(type identifier : array | collection)
{
  //Statements
}

Here, type represents data type, identifier represents the variable name and array represents the array name. There is not need to declare and initialize a loop counter variable in for-each loop. In for-each loop, we declare a variable that is same as base type variable.

Example of Java for Loop

class JavaForLoop
{
 public static void main(String[] args) {
  char[] ch = {'J', 'A', 'V', 'A'};
  for(int i = 0; i<ch.length; i++)
  {
   System.out.println(ch[i]);
  }
 }
}

Output:

J
A
V
A

Same Task Using Java for-each Loop

class JavaForLoop
{
 public static void main(String[] args) {
  char[] ch = {'J', 'A', 'V', 'A'};
  for(char c : ch)
  {
   System.out.println(c);
  }
 }
}

Output:

J
A
V
A

Limitations of Java for-each loop

For compatible use of for-each loop, you have at least Java 5.

We can't sort an array using for-each loop because it has only single element access.

For-each loop only iterates forward over the array in single steps.

It can't compare two arrays. 



on Leave a Comment

What is Tree Topology? Advantages and Disadvantages

A tree topology is a combination of both star topology and bus topology. We know that in star topology, multiple workstation connected to a central device usually a hub and bus topology uses a common bus or backbone cable to connect multiple devices. In tree topology, many star networks connected to a backbone cable. The central device which connects all the workstations in star network is connected to a backbone cable. Tree topology is very useful when we have to connect multiple networks, for example in a college, each building has own network and we have to connect all these networks.
Tree Topology
Tree Topology 

Here, every green sphere is a workstation and yellow sphere is a central device. These workstations are connected to central device through short black lines. And all central devices are connected to a backbone cable through long black lines.

Advantages of Tree Topology

Expansion of existing network is easy.

Other local star network does not breaks as backbone cable breakdown.

Detection and correction of faults is easy

Each device is connected to a central device through a dedicated link.

Disadvantages of Tree Topology

It requires more cabling.

If the common backbone cable breakdown, entire network will also breaks.

It is difficult to manage a tree topology, as the network increases difficulties also increases.




on Leave a Comment

Java do while Loop with Examples

In do while loop, at the first time body of loop is executed before the condition test is performed.

General Form of Java do while Loop

do{  
//Body of Loop
}while(condition); 

On reaching do statement, body of loop executes first and after executing body of loop, test condition will evaluate which appears at the end of do statement. Body of loop executed repeatedly until the test condition is true.

Test condition always appears at the bottom of loop, therefore body of loop always executes at least once.

Flow Diagram of Java do while Loop
Java do while Loop
Java do while Loop
Example of Java do while Loop

class JavaDoWhileLoop
{
 public static void main(String[] args) {
  char c = 'A';

                do
  {
   System.out.println(c);
   c++;
  }
  while(c<='E');
 }
}

Output:

A
B
C
D
E
on Leave a Comment

Java while Loop with Examples

Java while loop executes multiple statements repeatedly until certain conditions holds true.

General form of Java while loop:

initialization;
while(condition)
{
  //Body of loop
}

The condition is evaluated and if the condition is true, body of loop is executed. Control is transferred back to the loop condition after executing the body of loop and the condition is evaluated again and if the condition is true, body of loop is executed.

Body of loop may contain zero or more statements. If there is only statement, then it is not necessary to put braces.

Flow Diagram of Java while Loop
Java while loop
Java while loop
Example of Java while Loop

class JavaWhileLoop
{
 public static void main(String[] args) {
  char c = 'A';

  while(c<='E')
  {
   System.out.println(c);
   c++;
  }
 }
}

Output:

A
B
C
D
E
on Leave a Comment

Java for Loop With Examples

The java for loop is a entry controlled loop, that allows to execute specific block of code repeatedly until certain condition is false.

General Form of Java for Loop is:

for(initialization; condition; update)
{
  //Body of the loop
}

Execution of for loop statement is as follows:

(1) Initialization is done using assignment operator, for example i = 0. The variable which is initialized is called loop control variable. Initialization code executes once at the beginning of for loop statement. You can initialize zero or more than one variable in a single for loop statement.

Example:

class JavaForLoop
{
 public static void main(String[] args) {
  int i = 1;
  for( ; i<=5; i++)
  {
   System.out.println(i);
  }
 }
}

Output:

1
2
3
4
5

(2) The loop condition is a relational expression. This condition can be either true or false. If it is true, body of for loop executes and if the condition is false, body of for loop will skipped. This condition is checked every time after executing body of for loop

(3) After executing the last statement of for loop, control is transferred back to the for statement. Now the control variable will update (for example increment or decrement). New value of control variable is again tested will loop condition.

Flow Chart of Java for Loop
Java for Loop
Java for Loop
Example of Java for Loop

class JavaForLoop
{
 public static void main(String[] args) {
  int i = 2;
  for(int j = 1 ; j<=10; j++)
  {
   System.out.println(i+" * "+j+" = "+i*j);
  }
 }
}

Output:


2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

on Leave a Comment

Java Program to Find Largest Number in an Array

This java program finds the largest number in an array. First, enter the size of array, then enter the elements of array. Now, store the first array element into a variable, then compare this variable with each array element, if variable is smaller than any array elements, then store that array element into variable. 

Java Program to Find Largest Number in an Array

/* Java Program to Find Largest Element in Array */

import java.util.Scanner;

public class LargestNumber
{
   public static void main(String args[])
   {
       int size, largest, i;
       Scanner read = new Scanner(System.in);
     
       System.out.print("Enter the Size of Array : ");
       size = read.nextInt();
       int arr[] = new int[size];
          
       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = read.nextInt();
       }
    
       /* Searching for the Largest Number*/
    
       largest = arr[0];
    
       for(i=0; i<size; i++)
       {
           if(largest < arr[i])
           {
               largest = arr[i];
           }
           
       }
    
       System.out.print("Largest Element in Array is " +largest); 
   }
}

Output:

Enter the Size of Array : 5
Enter Array Elements : 89
56
87
65
90
Largest Element in Array is 90
on Leave a Comment

Java Program for Selection Sort

This java program sorts an array using selection sort technique. First enter the length of array using keyboard, after that enter the elements of array. Now, compare the elements of array and if first element is greater than second element, then perform swapping.

Selection Sort in Java

import java.util.Scanner;
class SelectionSort
{
    public static void main(String[] args) {
       int length, i, j, temp;
       System.out.print("Enter the Length of Array : ");
       Scanner sc = new Scanner(System.in);
       length = sc.nextInt();
       int arr[] = new int[length];
 
       System.out.print("Enter Array Elements : ");
       for(i=0; i<length; i++)
       {
           arr[i] = sc.nextInt();
       }
    
       for(i=0; i<length; i++)
       {
           for(j=i+1; j<length; j++)
           {
               if(arr[i] > arr[j])
               {
                   temp = arr[i];
                   arr[i] = arr[j];
                   arr[j] = temp;
               }
           }
       }
    
       System.out.print("Sorted Array : ");
       for(i=0; i<length; i++)
       {
           System.out.print(arr[i]+ "  ");
       }
   }
}

Output:

Enter the Length of Array : 5
Enter Array Elements : 8 6 7 1 2
Sorted Array : 1  2  6  7  8
on Leave a Comment

Java Switch Case Statement

The switch statement is java built-in multi-way decision statement. The switch statement test an expression with a list of case values and if the expression matches with case value, the block of statements followed by that case will execute.

Syntax:

switch(expression) 
{
   case value1:
      block1
      break; 
   
   case value2:
      block2
      break; 
   ......
   ......
   default : 
      // Statements
}

Rules for implementing switch statement:

The expression should be integer expression or character expression.

The value1, value2 are also integral constant.

All values should be unique in a switch statement.

We can use any number of case statements and each case statement is following by value and colon.

Each case block may contain zero or more statements.

It is not necessary to put braces around the blocks.

The default statement is optional and if you write default statement, it must appear after all the case statements.

Flow Chart
Java Switch Statement
Java Switch Statement

Example of Switch Statement

import java.util.Scanner;
class SwitchStatement
{
 public static void main(String[] args) {
  System.out.print("Enter a number between 1 to 7 : ");
  Scanner sc = new Scanner(System.in);
  int x = sc.nextInt();
  String day;
  switch(x)
  {
   case 1:  
         day = "Monday";
         System.out.println(day);
                              break;
                        case 2:  
                              day = "Tuesday";
                              System.out.println(day);
                              break;
                        case 3:  
                              day = "Wednesday";
                              System.out.println(day);
                              break;
                        case 4:
                               day = "Thursday";
                               System.out.println(day);
                               break;
                        case 5:
                               day = "Friday";
                               System.out.println(day);
                               break;
                        case 6:
                               day = "Saturday";
                               System.out.println(day);
                               break;
                        case 7:
                               day = "Sunday";
                               System.out.println(day);
                               break;
                       default:
                               day = "Invalid day";
                               System.out.println(day);
                               break;
  }
 }
}

Output:

Enter a number between 1 to 7 : 6
Saturday

In this program value of x will compared with case values, if any match is found, that case block will execute, otherwise default statements will execute.