Strategy Design pattern in java

              A design pattern that selects the algorithm’s behavior dynamically. Basically,this is a behavioral design pattern. It follows the runtime instruction to choose the algorithm. So it is more flexible.

How to implement the strategy design pattern?

It includes the three major components.

Strategy Interface: It is the basic for all implementation.

Concrete Strategies: It implements the interface with specific functionality.

Context class: this is thee one which allows the strategy to choose at runtime.

A shopping Application is developed here.

Strategy interface: PayBillStrategy

CreditCardPay ,PayPalPay : concrete strategy

Billpay() is used to pay the bill. It is overridden for two strategy.

Context class: Shopping Cart

setPayBillStrategy() : Select the strategy at runtime.

Checkout() : used to send cart to bill payment.

Shop App : It is the class with main function. It creates the objects and call the context class member functions.

#Java Program to implement the strategy design pattern

interface PayBillStrategy {

    void billpay(int amount);

}

class CreditCardPay implements PayBillStrategy {

    private String cardNo;

    public CreditCardPay(String cardNo) {

        this.cardNo = cardNo;

    }

     @Override

    public void billpay(int amt) {

        System.out.println("Paid " + amt + " using Credit Card Payment: " + cardNo);

    }

}

 class PayPalPay implements PayBillStrategy {

    private String emailid;

    public PayPalPay(String emailid) {

        this.emailid = emailid;

    }

    @Override

    public void billpay(int amt) {

        System.out.println("Paid " + amt + " using PayPal payment: " + emailid);

    }

}

class ShoppingCart {

    private PayBillStrategy paybillStrategy;

    // Setting the strategy at runtime

    public void setPayBillStrategy(PayBillStrategy paybillStrategy) {

        this.paybillStrategy = paybillStrategy;

    }

    public void checkout(int amt) {

        paybillStrategy.billpay(amt);

    }

}

public class ShopApp {

    public static void main(String[] args) {

        ShoppingCart cart1 = new ShoppingCart();

        System.out.println("Shopping Application");

        System.out.println("Your Billing deatails:");

        // Using Credit Card Pay bill strategy

        cart1.setPayBillStrategy(new CreditCardPay("9876-5432-0129-8765"));

        cart1.checkout(230);

         // Using PayPal Pay bill strategy

        cart1.setPayBillStrategy(new PayPalPay("customer@rajeevas.com"));

        cart1.checkout(180);

    }

}

While executing this program, you get the below output.

C:\raji\blog>javac ShopApp.java

C:\raji\blog>java ShopApp

Shopping Application

Your Billing deatails:

Paid 230 using Credit Card: 9876-5432-0129-8765

Paid 180 using PayPal: customer@rajeevas.com

This strategy is flexible and maintainable. Thus the way of strategy design pattern in java was implemented using a shopping application.

Decorator Design Pattern in java

     It is a design pattern allows the user to add a function at run time. But it doesn’t change the behavior of other objects in the same class. Basically, it is a structured design pattern.

Features:

  • ·       Reusable
  • ·       Flexible
  • ·       Extensible

 Components of decorator pattern:

  • ·       Component interface
  • ·       Concrete component
  • ·       Decorator
  • ·       Concrete decorator

 Component interface:

              A foundation code which has an abstract method. This is the basic for decorator and concrete components.

Concrete component:

              This is the class which develops the basic behaviour of the component interface.

Decorator component:

              It is an abstract class which refers the component object. It creates the decorator interface and component instance references.

Concrete decorator:

              It adds the functionality to decorator class.

Java Program to implement Decorator design pattern for Juice Shop:

Steps to create the code:

  • ·       First, create a component interface “Juice”.
  • ·       Create a  concrete component “Basic Juice” with two function implementation “getInfo()” and “getPrice()”.
  • ·       “JuiceDecorator” – it is an abstract decorator component.
  • ·       Last implementation is concrete decorator which is “IceDecorator” and “HoneyDecorator” with dynamic functional code addition.
  • ·       Finally, write the main function.It creates the objects for all classes and call the functions.

#Java Program to implement Decorator design pattern for Juice Shop

interface Juice {

    String getInfo();

    double getPrice();

}

class BasicJuice implements Juice {

    public String getInfo() {

        return "Basic Juice";

    }

    public double getPrice() {

        return 5.0;

    }

}

abstract class JuiceDecorator implements Juice {

    protected Juice decoratedJuice;

    public JuiceDecorator(Juice juice) {

        this.decoratedJuice = juice;

    }

    public String getInfo() {

        return decoratedJuice.getInfo();

    }

    public double getPrice() {

        return decoratedJuice.getPrice();

    }

}

class IceDecorator extends JuiceDecorator {

    public IceDecorator(Juice juice) {

        super(juice);

    }

    public String getInfo() {

        return super.getInfo() + ", with ICE";

    }

    public double getPrice() {

        return super.getPrice() + 1.5;

    }

}

 

class HoneyDecorator extends JuiceDecorator {

    public HoneyDecorator(Juice juice) {

        super(juice);

    }

    public String getInfo() {

        return super.getInfo() + ", with Honey";

    }

    public double getPrice() {

        return super.getPrice() + 0.5;

    }

}

public class JuiceApp {

    public static void main(String[] args) {

        Juice juice = new BasicJuice();

        System.out.println(juice.getInfo() + " $" + juice.getPrice());

        juice = new IceDecorator(juice);

        System.out.println(juice.getInfo() + " $" + juice.getPrice());

        juice = new HoneyDecorator(juice);

        System.out.println(juice.getInfo() + " $" + juice.getPrice());

    }

}

Output:

C:\raji\blog>javac JuiceApp.java

C:\raji\blog>java JuiceApp

Basic Juice $5.0

Basic Juice, with ICE $6.5

Basic Juice, with ICE, with Honey $7.0

This program creates a basic juice application with price displaying based on decorator design pattern.

Observer Design Pattern in java:

               This is the third design pattern which deals with behavioral design.It has a subject and observers. Subject is the object and observers are the dependents. When a change occurs it reflects the observers.

Let us write a java program to implement this design pattern.

Steps:

  • ·       Create an interface observer with a method updateIt with a string msg.
  • ·       Write a code for subject class with observer array and four member functions. One for insertObserver, removing observer,notify the observer and display the state information.
  • ·       Implement a concreteObserver to implement observer.
  • ·       Override the updateIt() function.
  • ·       Finally, create the main() function for creating objects and function calling.

#Java Program to implement Observer Design Pattern

import java.util.ArrayList;

import java.util.List;

interface Observer {

    void updateIt(String msg);

}

 class Subject {

    private List<Observer> obs = new ArrayList<>();

    private String stateInfo;

     public void InsertObserver(Observer observer) {

        obs.add(observer);

    }

     public void Observer(Observer observer) {

        obs.remove(observer);

    }

     public void setState(String stateInfo) {

        this.stateInfo = stateInfo;

        notifyObservers();

    }

     public void notifyObservers() {

        for (Observer observer : obs) {

            observer.updateIt(stateInfo);

        }

    }

}

 class ConcreteObserver implements Observer {

    private String name;

     ConcreteObserver(String name) {

        this.name = name;

    }

     @Override

    public void updateIt(String stateInfo) {

        System.out.println(name + " received state change: " + stateInfo);

    }

}

 public class Main19 {

    public static void main(String[] args) {

        Subject subject = new Subject();

        Observer observer1 = new ConcreteObserver("Observer 1");

        Observer observer2 = new ConcreteObserver("Observer 2");

        subject.InsertObserver(observer1);

        subject.InsertObserver(observer2);

        subject.setState("State 1");

        subject.setState("State 2");

    }

}

While executing this program, you will get the below output.

C:\raji\blog>javac Main19.java

C:\raji\blog>java Main19

Observer 1 received state change: State 1

Observer 2 received state change: State 1

Observer 1 received state change: State 2

Observer 2 received state change: State 2

Thus the program to implement the observer design pattern is executed. Happy Coding!!!!

Design patterns in java (Part1)

      Java offers solutions for software design. These design patterns provides great solutions in efficient manner. These are easy to maintain. Java’s design patterns are listed below.

  • 1.       Singleton pattern
  • 2.       Factory pattern
  • 3.       Observer pattern
  • 4.       Decorator pattern
  • 5.       Strategy pattern

Each and every pattern is detailed explained as follows.

1.Singleton pattern:

              Single instance is created with the global scope. The instance can be visible for entire project.

Steps:

  • ·       First,create a singleton class. Develop a singleton instance code as private,static and final type.
  • ·       Just return the instance from a public member function getInsta().
  • ·       Secondly, a public class SingletonEg is written with main function.
  • ·       s1,s2 are the two instances developed from Singleton class.
  • ·       Check whether both are true.
  • ·       Yes, both are equal because these two are same singleton objects.

class Singleton { 

    private static final Singleton insta = new Singleton(); 

    private Singleton() {} 

    public static Singleton getInsta() { 

        return insta; 

    } 

} 

public class SingletonEg { 

    public static void main(String[] args) { 

        Singleton s1 = Singleton.getInsta(); 

        Singleton s2 = Singleton.getInsta(); 

        if (s1 == s2) { 

            System.out.println("Both singleton instances are same"); 

        } 

    } 

} 

The output is….

C:\raji\blog>javac SingletonEg.java

C:\raji\blog>java SingletonEg.java

Both singleton instances are same

Next is factory pattern.

2.Factory pattern:

              Creating an interface with objects and function. Let it can be overridden by sub class.

Steps:

  • ·       Write an interface with void function.
  • ·       Add two concrete classes implementing the same interface.
  • ·       Develop a Factory to generate object of concrete class based on given information
  • ·       Let the fruit class object uses the fruitfactory function.
  • ·       Interface: fruit
  • ·       Concrete classes: Apple and Orange.
  • ·       Factory class: fruitFactory
  • ·       Main class :FactoryPatternEg

Program:

interface fruit {

    void color();

}

class Apple implements fruit {

    @Override

    public void color() {

        System.out.println("Apple is red colour.");

    }

}

class Orange implements fruit {

    @Override

    public void color() {

        System.out.println("Orange is orange colour.");

    }

}

 class fruitFactory {

    public fruit getFruit(String fruitType) {

        if (fruitType == null) {

            return null;

        }

        if (fruitType.equalsIgnoreCase("APPLE")) {

            return new Apple();

        } else if (fruitType.equalsIgnoreCase("ORANGE")) {

            return new Orange();

        }

        return null;

    }

}

 public class FactoryPatternEg {

    public static void main(String[] args) {

        fruitFactory ff1 = new fruitFactory();

        // Get an object of apple and call its color method

        fruit f1 = ff1.getFruit("APPLE");

        f1.color();

        // Get an object of Orange and call its color method

        fruit f2 = ff1.getFruit("ORANGE");

        f2.color();

    }

}

Compile and run the program in command prompt. you will get the output.

C:\raji\blog>javac FactoryPatternEg.java

 C:\raji\blog>java FactoryPatternEg

Apple is red colour.

Orange is orange colour.

These are the first two design patterns in java. Next blog post shows you the remaining Design patterns.

JMM(Java Memory Model)

              Java is an object-oriented programming language. Any java program is compiled and executed to get the desired output. It follows an architecture called JVM(Java virtual Machine).

Java code is compiled by java compiler(javac). Compiled code is executed, and it gives the byte code. During this process JMM takes the control over to the memory. It involves the threads.

Thread is a lightweight process. Multithreading deals with multiple threads running at same time.

Why JMM?

              JMM deals with interactions between threads and memory. The memory can be classified into two types.

·       Main memory – It’s the place where execution takes place.

·       Working memory- It stores the details of variables of the thread.

Features of JMM:

Volatile variables:

  • Read and write operations on thread is visible for threads when it is declared as volatile.

Eg: private volatile boolean a = false;

Atomic functions:

  • Volatile read and write operations are synchronized in atomic manner.
  • Built in java package: “java.util.concurrent.atomic”

Synchronization:

              When multiple threads executed and a specific thread want to run in the execution block,it needs to be synchronized.

Locks and monitor:

    When threads are running, one should use critical region. Another one should be wait for critical region. This can be done by Locks and monitor.

Built in java package for implementing this concept: java.util.concurrent.locks

Ordering:

              This can be done by two categories.

Happens-Before Relationship: It deals with visibility of operations on memory.

Sequential consistency: The operations(read and write) is consistent.

Let us create a simple thread sample in java.

  • A class is created using Thread.
  • Run() is a method in thread to execute the process.
  • An object is created for the class.
  • The thread is started by start() function.

Program:

import java.io.*;

import java.util.*;

 public class sampleTh extends Thread {

    // code for run method

    public void run()

    {

        System.out.println("It's the time to start the thread...");

    }

    public static void main(String[] args)

    {

        sampleTh s1 = new sampleTh();

        // let us start the thread

        s1.start();

    }

}

Here is the output.

C:\raji\blog>javac sampleTh.java

C:\raji\blog>java sampleTh

It's the time to start the thread...

This is a simple thread operation in java uses JMM.

How to implement Generic function in restricted mode?

             As the earlier post implements the generic function in java. This program restricts the data type as numbers. This uses <T extends Number> for restriction.

Steps:

  • ·       Include the built in package “java.util.Scanner”.
  • ·       Create a class with main function. A generic function printIT() with number restriction is created.
  • ·       The input is given by the user. The first number is integer and the second number is float.
  • ·       If it mismatches, it throws the exception. Otherwise,it prints the number.

#Program

import java.util.Scanner;

public class sampleGr {

    public static <T extends Number> void printIt(T value) {

        System.out.println("The value is: " + value);

    }

    public static void main(String[] args) {

              Scanner scanner = new Scanner(System.in);

        System.out.print("enter the first value as integer and next value as float");

        int no = scanner.nextInt();

        float a = scanner.nextFloat();

        printIt(no);

        printIt(a);

    }

}

Output is given below.

C:\raji\blog>javac sampleGr.java

C:\raji\blog>java sampleGr

enter the first value as integer and next value as float

23

5.6

The value is: 23

The value is: 5.6

Exceptions are given as follows….

C:\raji\blog>java sampleGr

enter the first value as integer and next value as float

3.4

Exception in thread "main" java.util.InputMismatchException

        at java.base/java.util.Scanner.throwFor(Scanner.java:964)

        at java.base/java.util.Scanner.next(Scanner.java:1619)

        at java.base/java.util.Scanner.nextInt(Scanner.java:2284)

        at java.base/java.util.Scanner.nextInt(Scanner.java:2238)

        at sampleGr.main(sampleGr.java:10)

 

C:\raji\blog>java sampleGr

enter the first value as integer and next value as float

23

rt

Exception in thread "main" java.util.InputMismatchException

        at java.base/java.util.Scanner.throwFor(Scanner.java:964)

        at java.base/java.util.Scanner.next(Scanner.java:1619)

        at java.base/java.util.Scanner.nextFloat(Scanner.java:2522)

        at sampleGr.main(sampleGr.java:11)

 

C:\raji\blog>java sampleGr

enter the first value as integer and next value as float

rr

Exception in thread "main" java.util.InputMismatchException

        at java.base/java.util.Scanner.throwFor(Scanner.java:964)

        at java.base/java.util.Scanner.next(Scanner.java:1619)

        at java.base/java.util.Scanner.nextInt(Scanner.java:2284)

        at java.base/java.util.Scanner.nextInt(Scanner.java:2238)

        at sampleGr.main(sampleGr.java:10)

Note :” <T extends String>”. If you are using this keyword, this will hold only String values instead of all data types.

Thus the way of implementing Generic function in restricted mode in java in efficient way. You can use these type of restrictions based on the requirements. Keep Coding!!! 

How to implement Generics in java?

              “Generics” is a special feature in java. It creates a generalized data member, classes and members. This can be used for any datatypes. So, it gives you the compile time type safety.

Eg:

class gene <G> {

G info;

public G getInfo(){

return info;

}

}

Where,

G is a parameter. The user replaces this with any datatypes (Primitive datatypes like int,String or user defined datatype).

Note: Different datatypes can be used without rewriting the class.

Java program to implement generic class:

Generic class: sampleGene

Generic data member : T

Input method: input()

Output method: display()

Generic Objects : intsampleGene , strsampleGene

//Java Program

public class sampleGene<T> {

    private T t;

    public void display(T t) {

        this.t = t;

    }

    public T input() {

        return t;

    }

    public static void main(String[] args) {

        sampleGene<Integer> intsampleGene = new sampleGene<>();

        intsampleGene.display(456);

        System.out.println("Integer Value: " + intsampleGene.input());

       sampleGene<String> strsampleGene = new sampleGene<>();

        strsampleGene.display("Have a nice day");

        System.out.println("String Value: " + strsampleGene.input());

    }

}

Output:

C:\raji\blog>javac sampleGene.java

C:\raji\blog>java sampleGene

Integer Value: 456

String Value: Have a nice day

Next Program implement the generic function.

Java Program to implement generic function:

              This program creates a generic function to process string and int array elements.

Generic function: display()- It gets the data as array elements and prints it.

The array elements can be a int array or String.

//Program

public class genMethod{

    public static <T> void display(T[] inputA) {

        for (T element : inputA) {

            System.out.print(element + " ");

        }

        System.out.println();

    }    public static void main(String[] args) {

        Integer[] intArray = {34, 42, 63, 74, 85};

        String[] strArray = {"Java","Generic","Programming"};

        display(intArray);

        display(strArray);

    }

}

When you execute this program, you will get the below output.

C:\raji\blog>javac genMethod.java

C:\raji\blog>java genMethod

34 42 63 74 85

Java Generic Programming
Note: you can try any type of array elements using this program.

Binary searching of array elements in java using functions:

               Binary searching is efficient one among the searching method. It finds the mid item. Using the mid item, divide the array elements into two halves. Checks each half and repeat the process for all the elements.

Java program to illustrate binary searching using functions:

              This program gives you way to implement binary search in java. Here are the steps.

·       Include the built in files

  • ·       Create a public class with main function.
  • ·       Inputs: number of elements in the array, array elements, the data is searched.

·       Logic:

  • ·       Two variable h(high),l(low) where l=0, h =length of the array -1.
  • ·       Check whether l is less than h ,continue the loop.
  • ·       Find the mid value by adding l,h value and divide by 2.
  • ·       If any array element is matched with the data to be searched, return the mid value.
  • ·       Else, the array element is less than data assign l as mid+1.
  • ·       Else, assign the h value as mid -1.

Program:

import java.util.Arrays;

import java.util.Scanner;

public class bSearch {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of elements");

        int no = scanner.nextInt(); // Read the number of elements

        int[] a = new int[no]; // Array declaration

        int j=0,key=0;

        System.out.println("Enter " + no + " elements: ");

        for (j = 0; j< no; j++) {

            a[j] = scanner.nextInt(); // get the array elements

        }

        System.out.println("Enter the data to be searched");

        int data = scanner.nextInt();

        int in = binaryS(a,data);

        if (in != -1) {

            System.out.println("Element found at index: " + in);

        } else {

            System.out.println("Element not found");

        }

    }

    public static int binaryS(int[] a, int data) {

        int l = 0;

        int h = a.length - 1;

        while (l <= h) {

            int mid = (l + h) / 2;

            if (a[mid] == data) {

                return mid;

            } else if (a[mid] < data) {

                l = mid + 1;

            } else {

                h = mid - 1;

            }

        }

        return -1;

    }

}

Output:

C:\raji\blog>javac bSearch.java

C:\raji\blog>java bSearch

Enter the number of elements4

Enter 4 elements:

98

56

23

45

Enter the data to be searched

56

Element found at index: 1

 This is the way of implementing binary search program in java using functions.

Linear search in java

    Searching is a way of finding an element in an array. This can be done by many ways. Basically, two methods are used.

  • ·       Linear search
  • ·       Binary search

Linear search in java:

              It is a sequential search which finds a data by looking the elements one by one until the data is found.

Steps to follow to write the java program:

  • ·       Import a built in package java.util.Scanner.
  • ·       Create a class with main function.
  • ·       Add the input statements to get the input.
  • ·       First, read the number of elements  for array. Next, get the array elements.
  • ·       Finally, get the data to be searched in the array.
  • ·       Set two variables j and key as 0.
  • ·       Using a loop, repeat the process for all elements in the array.
  • ·       Check the key value with data in the array.
  • ·       If the data is found, print the position and data. Set the key as 1.
  • ·       Finally, check the key value, if it is 0,print the data is not found message.

Program:

import java.util.Scanner;

public class LinearPgm {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of elements");

        int no = scanner.nextInt(); // Read the number of elements

        int[] a = new int[no]; // Array declaration

        int j=0,key=0;

        System.out.println("Enter " + no + " elements: ");

        for (j = 0; j< no; j++) {

            a[j] = scanner.nextInt(); // get the array elements

        }

        System.out.println("Enter the data to be searched");

        int data = scanner.nextInt();

         for (j = 0; j < a.length; j++) {

            if (a[j] == data) {

              System.out.print("The data is found at"+ (j+1) +"Position");

              key =1;

            }

          }

         if(key==0)

          System.out.println("The data is not found");

  }

 }           

Output:

C:\blog>javac LinearPgm.java

C:\blog>java LinearPgm

Enter the number of elements5

Enter 5 elements:

12

24

35

46

57

Enter the data to be searched

35

The data is found at3Position

Note: Linear search is not efficient for large data.

This is the way of creating linear search program in java.

Java Programs to illustrate Array Operations

             Array is a collection of similar data items. Genarally,operations on array includes finding a maximum number in array, reversing the array elements, sorting and searching.

This blog includes two java programs to illustrate array operations.

1.Java Program to find biggest number in the array:

              This program includes the below steps.

  • ·       Include the built in package java.util.Scanner.
  • ·       A public class MaxElement is created with main() function.
  • ·       Read the number of elements in an array as input.
  • ·       Using a loop(for loop), get all the elements to array.
  • ·       Set a variable max to first element of array.
  • ·       Check each element with max value to find the biggest value.
  • ·       If the array element is greater than max, set the max as array element.
  • ·       otherwise, repeat the process.
  • ·       Finally, print the maximum value of the array.

#Java program to find the biggest array element.

import java.util.Scanner;

public class MaxElement {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of elements");

        int no = scanner.nextInt(); // Read the number of elements

        int[] a = new int[no]; // Array declaration

        int j=0;

        System.out.println("Enter " + no + " elements: ");

        for (j = 0; j< no; j++) {

            a[j] = scanner.nextInt(); // get the array elements

        }

         int max = a[0];

        for (int num : a) {

            if (num > max) {

                max = num;

            }

        }

        System.out.println("The Biggest array element is:"+max);

     }

}

The output is as follows….

C:\raji\blog>javac MaxElement.java

C:\raji\blog>java MaxElement

Enter the number of elements 5

Enter 5 elements:

11

23

76

45

18

The Biggest array element is:76

Next program is to reverse the elements in array.

2.Java Program to reverse the elements in the array:

              This program is to reverse the elements from the beginning to last.

Steps:👇

  • As a beginning, import the built in package java.util.scanner.
  • A class is created with main() function.
  • First,get the number of elements of the array.
  • Read the array elements.
  • Declare the two variables as Sta and end. Using this variables, repeat the process from starting element to last element to reverse the array.
  • Finally,print the array reversed.

#Java Program to reverse the elements in the array:

import java.util.Scanner;

public class ReverseElement {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of elements");

        int no = scanner.nextInt(); // Read the number of elements

        int[] a = new int[no]; // Array declaration

        int j=0;

        System.out.println("Enter " + no + " elements: ");

        for (j = 0; j< no; j++) {

            a[j] = scanner.nextInt(); // get the array elements

        }

       int sta = 0;

        int end = a.length - 1;

        while (sta < end) {

            int temp = a[sta];

            a[sta] = a[end];

            a[end] = temp;

            sta++;

            end--;

        }

      System.out.print("The Reversed array is:");

      System.out.println("");

      for(j=0;j<no;j++)

      {

       System.out.println(a[j]);

     }

 }

}

Output:

C:\raji\blog>javac ReverseElement.java

C:\raji\blog>java ReverseElement

Enter the number of elements5

Enter 5 elements:

54

34

23

67

87

The Reversed array is:

87

67

23

34

54

These are the java programs to perform array operations. Keep coding!!!!

Arrays in java

“A collection of similar data items that can be stored in continuous memory” – An array.

It has the index starts from 0 to n.

Syntax:

Datatype Array_variable[ index_value];

Eg:

int a[10];

Sample Java program to create and display the array elements:

·       Create a class “arrayEg” and write the main() function inside it.

·       Declare the variable a[] as integer and assign some values.

·       Using a for loop, print the value.

class arrayEg

{

 public static void main(String args[])

 {

  int a[]={11,12,13,14,15,16,17,18,19,20};

  System.out.println("The array elements are:");

  for(int i=0;i<10;i++)

  {

   System.out.println(a[i]);

  }

 }

}

Compile and run the program.

C:\raji\blog>javac arrayEg.java

C:\raji\blog>java arrayEg

The array elements are:

11

12

13

14

15

16

17

18

19

20

It is the easy way to use array elements. Next program is to find sum of elements of an array.

#Java program to find Sum of elements program of an array:

·       A special package “java.util.Scanner” is imported in this program.

·       A public class “ArrayEg1” with main() function is written here.

·       Create an object for Scanner class.

·       Read the input from runtime as number of elements.

·       Read the array elements using a for loop.

·       Again, using a for loop, add the array elements to sum variable.

·       Print the sum of elements.

·       Close the scanner.

Program:

import java.util.Scanner;

public class ArrayEg1 {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of elements");

        int no = scanner.nextInt(); // Read the number of elements

        int[] a = new int[no]; // Array declaration

        int j=0, sum=0;

        System.out.println("Enter " + no + " elements: ");

        for (j = 0; j< no; j++) {

            a[j] = scanner.nextInt(); // get the array elements

        }

        for (j = 0; j < no; j++) {

            sum=sum+a[j];

            }

         System.out.println("The sum of elements in the array: "+sum);

        scanner.close(); // Close the scanner

    }

}

The output is shown below.

C:\raji\blog>javac ArrayEg1.java

C:\raji\blog>java ArrayEg1

Enter the number of elements5

Enter 5 elements:

11

22

33

44

55

The sum of elements in the array: 165

This is the way of using Arrays in java.