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. 

on Leave a Comment

Java if else Statement

In a java program, there may be a scenario when we have to execute a section of code, if a particular condition is satisfied. This can be done by if statement. Java has various types of if statements,

1. If statement
2. If-else statement
3. If-else-if ladder
4. Nested if statement

Java if Statement

Syntax of if statement in java:

if(condition)
{
  //statements
}

If the condition is true, if statements will execute. And if the condition is false, if statements will skip from the execution. 

Example of java if statement:

class JavaIfStatement
{
    public static void main(String [] args)
    {
        int x = 2; 
        if(x%2==0)
        {
            System.out.println(x+" is even number");
        }
    }
}

Output:

2 is even number

In this program, x is equal to 2 and we checks whether it is completely divisible by 2 or not through if statement. If x is completely divisible by 2, if block will execute and prints that x is even number.

Java if-else Statement

Syntax of if-else statement in java:

if(condition)
{
  //statements
}
else
{
  //statements
}

Example of java if-else statement:

class JavaIfElseStatement
{
    public static void main(String [] args)
    {
        int x = 13; 
        if(x%2==0)
        {
            System.out.println(x+" is even number");
        }
        else
        {
            System.out.println(x+" is odd number");
        }
    }
}

Output:

13 is odd number

Here x is equal to 13, if else statement checks whether it is completely divisible by 2 or not. If it is completely divisible by 2, if block executes and prints that x is even number, if x is not completely divisible by 2, else block executes and print that x is odd number.  

Java if-else-if ladder Statement

Syntax of if-else-if ladder statement in java:

if(condition1)
{  
  //statements
}
else if(condition2)
{  
  //statements
}  
...  
else
{  
  //statements
}

Example of java if-else-if ladder statement:

class JavaIfElseIfStatement
{
    public static void main(String [] args)
    {
        int x = 0; 
        if(x<0)
        {
            System.out.println(x+" is negative number");
        }
        else if(x>0)
        {
            System.out.println(x+" is positive number");
        }
        else
        {
            System.out.println(x+" is equal to zero");
        }
    }
}

Output:

0 is equal to zero

This program checks whether x is positive number, negative number or equal to zero through if-else-if ladder. 

Java nested if ladder Statement

Example of Java nested if ladder Statement

class JavaNestedIfStatement
{
    public static void main(String [] args)
    {
        int a = 5, b = 6, c = 7, d = 8; 
        if(a>b || a>c || a>d)
        {
            System.out.println(a+" is greatest number");
        }
        else
        {
            if(b>c)
            {
               if(b>d)
               {
                  System.out.println(b+" is greatest number");
               }
            }
            else if(c>d)
            {
                System.out.println(c+" is greatest number");
            }
            else
            {
                System.out.println(d+" is greatest number");
            }
        }
    }
}

Output:

8 is greatest number

This program checks greatest of 4 numbers using nested if ladder.
on Leave a Comment

Java Program for Bubble Sort

This java program sorts an array using bubble sort technique. In bubble sort technique, adjacent elements of array are compared. If the current element is greater than next element, then both elements perform swapping.

Java Program for Bubble Sort

import java.util.Scanner;

class BubbleSort
{
    public static void main(String [] args)
    {
        int n, i, j, swap;
        Scanner index = new Scanner(System.in);
        System.out.print("Enter length of integer array : ");
        n = index.nextInt();
        int array[] = new int[n];
        System.out.print("Enter elements of array : ");
        for (i = 0; i < n; i++) 
           array[i] = index.nextInt();
         for(i=0; i < n; i++){  
            for(j=1; j < (n-i); j++){  
              if(array[j-1] > array[j]){  
                swap = array[j-1];  
                array[j-1] = array[j];  
                array[j] = swap;  
               }        
            }  
         }  
        System.out.println("Sorted list of numbers");
        for (i = 0; i < n; i++) 
           System.out.print(array[i]+"  ");
    }
}

Output:

Enter length of integer array : 5
Enter elements of array : 4 9 6 3 1
Sorted list of numbers
1  3  4  6  9
on Leave a Comment

Java Program to Check Armstrong Number

This java program checks whether a number is Armstrong number or not. A number is Armstrong number, if the sum of cube of its digits is equal to that number. Example of Armstrong numbers, 407, 153, 371 etc.

For example, 407 is Armstrong number because
(4*4*4) = 64
(0*0*0) = 0
(7*7*7) = 343

Now, (64+0+343) = 407 

Java Program to Check Armstrong Number

import java.util.Scanner;
class ArmstrongNumber
{  
  public static void main(String [] args)  {  
    int a, temp, cube=0;  
    System.out.print("Enter a number : ");
    Scanner s = new Scanner(System.in);
    int num = s.nextInt(); 
    temp=num;  
    while(num>0)  
    {  
    a=num%10;  
    num=num/10;  
    cube=cube+(a*a*a);  
    }  
    if(temp==cube)  
    System.out.println(temp+" is a Armstrong number");   
    else  
        System.out.println(temp+"is not a Armstrong number");   
   }  
}  

Output:

Enter a number : 407
407 is a Armstrong number
on Leave a Comment

Java Access Modifiers

We can set the accessibility of any method or data members using access modifiers.

Java has four access modifiers

- Default
- Private
- Protected
- Public

Default

If you do not specify any other access modifier, then it is default access modifier by default.

If data or method members of a class declared as default access modifier, they are accessible only from the class of same package. 

Example:

package p1;
class A
{
 void display()
 {
  System.out.println("Iam in class A");
 }
}

package p2;
import p1.*;

class B
{
 public static void main(String[] args) {
  A obj1 = new A();
  obj1.display();
 }
}

Output:

Compile time error

This show compile time error because default members cannot be accessed from outside the package.

Private

private is a keyword in java programming language

The data or method members declared as private can be only accessible in the class in which they are declared.

Class and interface cannot be private but class inside a class can be private.

Private members cannot be accessible by the other classes of the same package.   

Other class can indirectly access private variables through public methods. 

If we make private constructor of a class, then we can not make object of that class from outside the class 

Example:

class A
{
 private int age;
 public void setage(int x)
 {
  age = x;
 }
}
class PrivateMembers
{
 public static void main(String [] args)
 {
  A obj = new A();
  obj.age = 18;    // Compile time error
  obj.setage(18);  // This will work 
 }
}

Protected

protected is a keyword in java programming language.

The data or method members declared as protected can be accessible within same package or outside the package through inheritance.

Class and interface cannot be protected, but class inside a class can be protected.

Example:

package p1;

public class A
{
 protected void display()
 {
  System.out.println("Iam in class A");
 }
}

package p2;
import p1.*;

class B extends A
{
 public static void main(String[] args) {
  A obj1 = new A();
  obj1.display();
 }
}

Output:


Iam in class A


Public 

public is keyword in java programming language.

The data or method members declared as public can be accessible anywhere in a program.

Public access modifier has the widest scope among all other modifiers.

Example:

package p1;

public class A
{
 public void display()
 {
  System.out.println("Iam in class A");
 }
}

package p2;
import p1.*;

class B 
{
 public static void main(String[] args) {
  A obj1 = new A();
  obj1.display();
 }
}

Output:


Iam in class A



on Leave a Comment

Java Program to Print Multiplication Table of a Number

This java program generates multiplication table of a given number. First you have to enter a number and then multiply that number from 1 to 10 using for loop and then print multiplication table of that number. 

Java Program to Generate Multiplication Table

import java.util.Scanner;
class MultiplicationTable
{
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter a Number : ");
  int n = sc.nextInt();
  System.out.println("Multiplication Table of "+n+" :");
  for(int i = 1; i<=10; i++)
   System.out.println(n+" * "+i+" = "+n*i);
 }
}

Output:


Enter a Number : 10
Multiplication Table of 10 :
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100

on Leave a Comment

Java Increment and Decrement Operators

In this article, we will learn about java increment and decrement operators with programming examples. 

Java Increment Operator

Java increment operator is one of the arithmetic operators. Increment operator increments the value inside a variable. Increment operator is a unary operator, it operates on one operand. It is represented by ++ symbol.

It has two types:

Pre Increment Operator

In this, ++ operator is written before the variable name.

For example,

int a = 1;
++a;

Now value of a become 2.

Programming Example of Pre Increment Operator


class PreIncrement
{
    public static void main(String[] args)
    {
        int a = 1;
        int b = ++a;
        System.out.println("a = "+a);
        System.out.println("b = "+b);
    }
}

Output:


a = 2
b = 2


Post Increment Operator

In this, ++ operator is written after the variable name.

For example,

int a = 1;
a++;

Now value of a become 2.

Programming Example of Post Increment Operator


class PostIncrement
{
    public static void main(String[] args)
    {
       int a = 1;
       int b = a++;
       System.out.println("a = "+a);
       System.out.println("b = "+b);
    }
}

Output:


a = 2
b = 1


Value of b is 1, because value of a is assigned to b and after assigning, variable a increments.

Java Decrement Operator

Java Decrement operator is one of the arithmetic operator. Decrement operator Decrements the value inside a variable. Decrement operator is a unary operator, it operates on one operand. It is represented by -- symbol.

It has two types:

Pre Decrement Operator

In this, -- operator is written before the variable name.

For example,

int a = 2;
--a;

Now value of a become 1.

Programming Example of Pre Decrement Operator


class PreDecrement
{
    public static void main(String[] args)
    {
 int a = 2;
 int b = --a;
 System.out.println("a = "+a);
 System.out.println("b = "+b);
    }
}

Output:


a = 1
b = 1


Post Decrement Operator

In this, -- operator is written after the variable name.

For example,

int a = 2;
a--;

Now value of a become 1.

Programming Example of Post Decrement Operator


class PostDecrement
{
    public static void main(String[] args)
    {
 int a = 2;
 int b = a--;
 System.out.println("a = "+a);
 System.out.println("b = "+b);
    }
}

Output:


a = 1
b = 2


Value of b is 2, because value of a is assigned to b and after assigning, variable a decrements.

on Leave a Comment

What is Mesh Topology?

In mesh topologyevery device is interconnected to other device through a dedicated point to point link. Mesh network can be LAN, WLAN or VLAN. This topology is mainly used in wireless network. In true mesh topology, every device is connected to other device through a dedicated link.
Mesh Topology
Mesh Topology
Mesh topology can be of two types:

(1) Full Mesh Topology: In full mesh topology, every device has a connection to another device. The total number of physical link in full mesh topology can be calculated as n(n-1)/2, where n is number of nodes. This formula is because if node 1 is connected to n-1 nodes, node 2 is connected to n-1 nodes and finally node n is connected to n-1 nodes. So we need n(n-1) links and each link allow communication in duplex mode, so we divide the total number of links by 2. 

(2) Partial Mesh Topology: In partial mesh topology, each device is not connected to every other device. But each device is only connected to one or two devices. So, it is less costly. It is a smart way to implement mesh topology.

Advantages of Mesh Topology

- It uses dedicated links, so each link carries only its data load, so it solves the traffic problem.

- Mesh topology is robust. If one links fails, then it doesn't affect the entire system.

- It provides security and privacy because message is transferred through a dedicated link.

- Fault identification and isolation is easy.

- Modification in network doesn't affect the other nodes.

Disadvantages of Mesh Topology

- Installation and reconnection is difficult.

- It requires more physical space to implement, because it requires more cabling.

- Hardware require to connect each link is expensive.

- Maintenance of mesh topology is also difficult.


on Leave a Comment

What is Star Topology?

In star topology, workstations are not directly linked to each other but they are connected to central component, usually called a hub. All devices have a dedicated point to point dedicated link to the central controller. If a device want to send data to other device, then it sends to the controller, the controller again send it to intended device. If the signal becomes weak before reaching to its intended node, then hub boost up the message and sends it to intended node.

Star Topology
Star Topology

Advantages of Star Topology

- Star topology is less expensive than mesh topology.

- Star topology is easy to install and reconfigure.

- It is robust because if one link fails, then only that link doesn't works, all other links remain active.

- New devices can be add and delete easily.

- It provides centralization. 

Disadvantages of Star Topology

- Dependency to central controller, usually a hub. If the hub goes down, while system will shut down.

-  It is costly because hub, switch increases overall cost.

- There is a limit how much devices can be added, which depends on central controller (hub or switch).

on Leave a Comment

What is Ring Topology?

In ring topology, all workstations are placed on a circle of cable called ring without any termination edge. Each device has a dedicated point to point connection. Every device has exactly two nodes for communication, all messages travel through a line in same direction either clockwise or anticlockwise until the message reaches its destination. In ring topology, each device incorporates a repeater. The repeater re transmits the message to another device until it reaches its destination.

Ring Topology
Ring Topology


Advantages of Ring Topology

- A ring is easy to install and reconfigure. 

- Addition or deletion of any device requires changing only two connections

- In ring topology, data travels in a particular direction, so it reduces data collision.

- In ring topology, data can be transfer at high speed.

Disadvantages of Ring Topology

- Failure of any cable or workstation break the loop and entire network will shut down.

- In ring topology, the maximum ring length and numbers of nodes are limited.

- Establishment of ring topology is more expensive as compared to hubs and Ethernet cards.

- It is slower than star topology because packets has to travel through all computers until it reaches its destination.

on Leave a Comment

What is Bus Topology?

Bus topology uses a common bus or backbone cable to connect all the devices with the terminators at each ends. The backbone cable acts as a shared communication media and each node (workstations, file servers, peripherals) is attached to the bus with an interface connector. When a computer send message, it is passed back and forth along the bus. In bus topology, terminators are required at both ends of the common bus. Terminator absorbs the signals when it reaches to terminator (end of common bus). Terminators are necessary because for preventing signal bounce. As a signal travels through a common bus, it produces heat. For this reason, there is a limit of number of nodes and common bus length. Bus topology was the one of the first topologies used in early LAN networks.


Bus Topology
Bus Topology

Advantages of bus topology

- It is less expensive because it does not requires any network devices like hubs and routers. 

- It is easy to expand a bus network.

- Connecting a computer or peripheral to a linear bus is easy. 

- Bus topology uses less cabling than other network topology like mesh or star. 

- Ease of installation.

Disadvantages of bus topology

- Bus topology does not provide centralization.

- In bus topology, only one user can transfer message at one time, otherwise both messages may collide.

- If the common bus or backbone cable fails, the entire network will be shut down. 

- Adding a new device may require modification or replacement of backbone cable or common bus.  

- Terminators are required at both ends of the common bus.