Thursday, April 26, 2012

Puzzles


Dear readers, While going through different sites, came to see an interesting site on puzzles. It is really interesting, please have a look here: http://worksheets.theteacherscorner.net/make-your-own/brain-teasers/

Monday, April 23, 2012

Dealing with ISOMsg and JPOS in Java

Dear reader,
This article is solely for my reference. If it is not useful too, please don't comment.

//Complete method for Credit using JPos connector
public TransactionResult credit() {
    TransactionResult tr = null;
    QMUX qmx = null;
    ISOMsg reqMsg = null;
    reqMsg = createCreditMsg(SystemInfo, PaymentRequest, "NPCI");
    String muxName = "mux.npci-mux";
    if (muxName == null)
        throw new ProcessingException("Unable to obtain QMUX name");
    qmx = (QMUX) NameRegistrar.get(muxName);
    int timeOut = 30000;
    
    respMsg = (OboISOMsg) qmx.request(reqMsg, timeOut);  //OboISOMsg extends IsoMsg, see below

    //Checking for Timeout
    if (respMsg == null || "91".equalsIgnoreCase(respMsg.getString(39))) {   //"00" means successful response
        System.out.println("Request Timed Out! Sending the verification message");
        ISOMsg verfMsg = (ISOMsg) reqMsg.clone();
        NPCIUserData srcUserData = (NPCIUserData) paymReq.getTransUnit().getUserData();
        NPCIUserData tgtUserData = (NPCIUserData) paymReq.getTransUnit().getMemberData();
        try {
            verfMsg.set(120,"Deepak8801001"); //name+nbin+mas; Take data from srcUserData and tgtUserData
            int retryCount = count++;
            for (int i = 0; i < 3; i++) {  //3 times re-sending.
                verfMsg.set(11, "111222");  //STAN: 6 digits
                int verifyReqTimeOut = 2000;
                respMsg = (OboISOMsg) qmx.request(verfMsg, verifyReqTimeOut);
                if (respMsg != null    && !"91".equalsIgnoreCase(respMsg.getString(39)))
                    break;
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    
    //Checking for proper response
    if(respMsg != null && respMsg.msgProcessingOK) {  //Means response is proper
        tr = processCreditResponse(respMsg, paymReq.getTransUnit().getUserData().getDeviceNumber(), reqMsg); 
    }
    //Means a failed response
    else {
        tr = new TransactionResult();
        tr.setStatus("FAILED");
        ProcessorResult pResult = new ProcessorResult();
        if (reqMsg != null) {
            pResult.set("DE11", reqMsg.getString(11));
            pResult.set("DE37", reqMsg.getString(37));
        }
        tr.setProcessorrResult(pResult);
    }
 return tr;
}

public TransactionResult processCreditResponse(ISOMsg respMsg,
            String devNbr, ISOMsg reqMsg) throws InvalidParameterException,
            MethodNotSupportedException, ProcessingException {
        TransactionResult tr = (TransactionResult) processDefaultResponse(
                new TransactionResult(), respMsg, devNbr, reqMsg);
        return tr;
}

protected ProcessorResponse processDefaultResponse(
            ProcessorResponse pr, ISOMsg respMsg, String dn, ISOMsg reqMsg) {
        pr.setDeviceNumber(dn);
        pr.setMappedAccountNumber(respMsg.getString(2));
        pr.setReturnCode(respMsg.getString(39));
        pr.setStatus(("00".equals(respMsg.getString(39)) ? "SUCCESS": "FAILED"));
        if (respMsg.hasField(38))
            pr.setExternalTransactionRef(respMsg.getString(38));

        ProcessorResult procRes = new ProcessorResult();
        procRes.set("DE3", respMsg.getString(3)); // processing cd
        procRes.set("DE7", respMsg.getString(7)); // transm dt
        procRes.set("DE11", respMsg.getString(11)); // trc nbr
        procRes.set("DE12", respMsg.getString(12)); // tx time
        procRes.set("DE13", respMsg.getString(13)); // tx date
        procRes.set("DE37", respMsg.getString(37)); // retrvl ref nbr
        procRes.set("DE39", respMsg.getString(39)); // response cd
        if (respMsg.hasField(120)) {
            String beneName = getBeneficiaryName(respMsg);
            if (beneName != null)
                procRes.set("BENEFICIARY", beneName); // beneficiary Name
        }
        pr.setProcessorrResult(procRes);
        return pr;
}


public class OboISOMsg extends ISOMsg {
    private byte[] rawMsg = null;
    public boolean msgProcessingOK = true;
    private Exception processingErr = null;
    private Long dbID = null;
    public boolean msgIsUnhandled = false;
    private long processingTime = 0L;
}

public class ProcessorPaymentRequest extends ProcessorRequest {    
    private Amount amount;
    private String memoText;
    private String transactionType;
    private String firstName    =    null;
    private String lastName        =    null;
    private String middleName    =    null;
    private String cardType        =    null;
    //setter and getter
}

public class PaymentRequest  extends ProcessorPaymentRequest {    
    private TransactionUnit transUnit;
    private String memo;
    //setter and getter
}
public class TransactionUnit extends EWPBusinessObject{
    public static final String kNullStr    =    "{NULL}";
    private UserData userData;
    private UserData memberData;
    private String status;
    private Amount fee;
    private String externalRefId;    
    private String processrCode;
    //setter and getter
}    

public class SystemInfo implements Serializable{
    private static final String kUnknown    =    "unknown";    
    private String systemCode    = kUnknown;
    private String serverIP        = kUnknown;    
    private String callerIP        = kUnknown;
    //setter and getter
}    
    
<void method="put"> 
     <string>jPOS_MUX_NAME</string> 
     <string>mux.npci-mux</string> 
</void> 


public ISOMsg createCreditMsg(SystemInfo sysInf, PaymentRequest paymReq, String fi) throws Exception {
        ISOMsg msg = new ISOMsg("0200");
        NPCIUserData srcUserData = (NPCIUserData) paymReq.getTransUnit().getUserData();
        NPCIUserData tgtUserData = (NPCIUserData) paymReq.getTransUnit().getMemberData();
        try {
            msg.set(2, tgtUserData.getNBin() + "00" + "1" + "00"+ tgtUserData.getDeviceNumber());
            msg.set(3, NPCIConstants.DE3_PROCESSING_CODE);  //900000
            msg.set(4, ISOUtil.padleft(amount, 12, '0'));   //amount can be replaced by 
                                                            //ISOCurrency.convertToIsoMsg("12500")
            msg.set(7, ISODate.getDateTime(new Date()));
            msg.set(11, "111222");  //STAN: 6 digits
            msg.set(12, ISODate.getTime(new Date()));
            msg.set(13, ISODate.getDate(new Date()));
            msg.set(18, NPCIConstants.DE18_MCC); //4814
            msg.set(22, NPCIConstants.DE22_POS_ENTRY_MODE); //019
            msg.set(25, NPCIConstants.DE25_POS_CONDITION_CODE); //05
            msg.set(32, NPCIConstants.DE32_AcquirerId); //100035
            msg.set(37, getISO8583P037RtrRefNbr(msg));  //Reference number, check method 
                                                        //getISO8583P037RtrRefNbr() given below.            
            msg.set(41, NPCIConstants.DE41_Tid    + srcUserData.getDeviceNumber().substring(5, 10););    
            
            msg.set(42, ISOUtil.strpad(NPCIConstants.DE42_Mid) + srcUserData.getDeviceNumber(), 15);
            msg.set(49, NPCIConstants.DE49_CurrencyCode); //356: for Indian rupees
            msg.set(120, "Deepak8801001"); //name+nbin+mas
        } catch (ISOException e) {
            e.printStackTrace();
        }
        return msg;
}

protected String getISO8583P037RtrRefNbr(ISOMsg req) {
        String rrn = null;
        Date d = new Date();
        String jd = ISODate.getJulianDate(d); // YDDD
        SimpleDateFormat sd = new SimpleDateFormat("HH");
        String hh = sd.format(d); // HH
        rrn = jd + hh + req.getString(11);
        return rrn;
}
    
public class UserData {        
    private String deviceNumber;
    private String accountNumber;
    private Long accountId;
    private String mappedAccountNumber;
    private String mappedRoutingNumber;
    private String validationPIN;
    private String mappedAccountExpiry;
    private String firstName;
    private String lastName;
    private String middleName;
    private String prepaidCardStatus;
    private AddressTO userAddress;
    private String bank_ICA; ///For Master Card Money Send
    private String cardType;
    private String mappedACType;
    private UserLocale userLocale;
    //setter and getter
}    
public class NPCIUserData extends UserData {    
    private String mas;
    private String NBin;
    //setter and getter
}
----------------------------------END---------------------------------------

Thursday, April 12, 2012

Design own ArrayList and Iterator in Java

Dear reader,

Today I am writing answers for few common interview questions: 
1. Difference between ArrayList and LinkedList and where to use what.
2. A basic program on ArrayList and Iterator.
3. Design your own ArrayList.
4. How Iterator works and design your own Iterator.

Answer Descriptions:

Difference between ArrayList and LinkedList in Java:
    ArrayList extends AbstractList and LinkedList extends AbstractSequentialList however both implement 
    List Interface but they work internally different. Based on their super-class you can easily figure out that 
    LinkedList is a sequential List but ArrayList is not. Main difference between ArrayList and LinkedList 
    is that ArrayList is implemented using re-sizable array while LinkedList is implemented using Doubly 
    LinkedList. In this article we will see differences between LinkedList and ArrayList and try to find 
    out when and where to use one over other.

The data-structure in the root of these two APIs are LinkedList==>Doubly Linked List and ArrayList==>Array.

1) Since Array is an index based data-structure, searching or getting elements from Array with index is 
   pretty fast. Array provides O(1) performance for get(index) method. However removal is costly in Array (so ArrayList)
   as you need to re-arrange all the elements for maintaining index values. On the Other hand LinkedList doesn't provide 
   Random or Index based access and you need to iterate over LinkedList to retrieve any element which will be of order O(n).

2) Insertions are easy and fast in LinkedList as compared to ArrayList because there is no risk of re-sizing 
   array (also copying content to new array if array gets full) which makes adding into ArrayList of O(n) in 
   worst case, while adding speed is O(1) in LinkedList. ArrayList also needs to update its index if you 
   insert something to it (except if you add value at the end of array).

3) Again Removal is costly in ArrayList as you have to re-arrange all elements for updated index.

4) LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object(data) 
   but in case of LinkedList each node holds both data and address of next and previous node.
   
5) You can customize an ArrayList size while constructing an ArrayList by passing a parameter.
   I mean when we write: "new ArrayList()", an array of size 10 elements is created. So specify "new ArrayList(100)";
   I mean based on your requirement.

When to use LinkedList and ArrayList in Java:
    As I said LinkedList is not as popular as ArrayList but still there are situation where a LinkedList is better 
    choice than ArrayList in Java. Use LinkedList in Java if:

    1) Your application can live without Random access. Because if you need nth element in LinkedList you need to 
        first traverse up to nth element O(n) and than you get data from that node.
    2) Your application is more insertion and deletion driven and you insert or remove more than retrieval. Since 
        insertion or removal doesn't involve re-sizing, LinkedList is much faster than ArrayList.
    3) ArrayList is fast and easy to use, just try to minimize array re-sizing by constructing ArrayList with proper 
        initial size.


Basic Program on ArrayList and Iterator: 
//MyIteratorExample.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MyIteratorExample {
    public static void main(String[] args) {
        List<String> list=new ArrayList<String>();
        list.add("Mango");
        list.add("Strawaberry");
        list.add("Papaya");
        list.add("Watermalon");

        Iterator<String> it=list.iterator();        
        while(it.hasNext()){
            String s=it.next();
            System.out.println("Value: "+s);
        }
        System.out.println("----Another way to iterate through List is below----");
        for(String s:list) {  
            System.out.println("Value: "+s);
        }
    }
}
//Output:
Value: Mango
Value: Strawaberry
Value: Papaya
Value: Watermalon

----Another way to iterate through List is below (using for-each loop)----

NOTE: for-each loop is applicable to only those collection APIs which implements Iterable interface. The 
      signature is like below:
        
        //Collection (interface) extends Iterable  
        //List (interface) extends Iterable

        public Iterator iterator() {
            System.out.println("My overridded iterator method called in Fruit class");
            return new FruitIterator(this);  //FruitIterator implements java.util.Iterator interface
        }

Design your own ArrayList and Iterator:
    Writing two basics first:
    a. ArrayList: ArrayList is a collection which implements various interfaces and extends AbstractList class.
    b. Iterator: Only those classes can be iterated who implement "java.lang.Iterable" interface.   

I have written 3 files for ArrayList and Iterator design and execution. One is having main method which can be 
executed to see the output. Main program has main method and it uses mine designed ArrayList and Iterator. Se below 
are the 3 files:

FruitIterator.java   //Iterator designed by me.
MyOwnArrayList.java  //ArrayList designed by me.
MyFruitIteratorExample.java  //Having main method which executes my ArrayList and my Iterator.

************Mine designed ArrayList***********
import java.util.RandomAccess;

public class MyOwnArrayList implements RandomAccess, Cloneable, java.io.Serializable {

    private transient Object[] elementData;  //Making one array to hold data
    private int size;
    protected transient int modCount = 0;  //Counter to find how many times Array is re-sized.
    private static final long serialVersionUID = 1234L;

    public MyOwnArrayList() {  //Making an initial Array of size 10.
        this(10);
    }
    public MyOwnArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
        this.elementData = (Object[])new Object[initialCapacity];
    }

    public boolean add(Object obj) {
        validateCapacity(size + 1);  
        elementData[size++] = obj;
        return true;
    }

    public Object get(int index) {
        Object obj=elementData[index];
        return obj;
    }

    public int size() {
        return size;
    }
    public void validateCapacity(int minCapacity) {
        modCount++;
        int oldCapacity = elementData.length;
        if (minCapacity > oldCapacity) {
            Object oldData[] = elementData;
            int newCapacity = (oldCapacity * 3)/2 + 1; //Size increases by 1.5 times+1.

            if (newCapacity < minCapacity)
                newCapacity = minCapacity;
            elementData = (Object[])new Object[newCapacity];            
            System.arraycopy(oldData, 0, elementData, 0, size); //src, srcPos, dest, destPos, length
            //System.arraycopy(src, srcPos, dest, destPos, length);
        }
    }

    public Object remove(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);

        modCount++;
        Object oldValue = elementData[index];

        int numMoved = size - index - 1;
        if (numMoved > 0) {
            //System.arraycopy(src, srcPos, dest, destPos, length);
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        }
        elementData[--size] = null; // Let gc do its work
        return oldValue;
    }
    
    //Defining iterator method
    public FruitIterator iterator() {
        System.out.println("My overridded iterator method called in Fruit class");
        return new FruitIterator(this);
    }
}

************Mine designed Iterator***********
public class FruitIterator {
    private MyOwnArrayList fruitList;
    private int position;

    public FruitIterator(MyOwnArrayList fruitList) {
        this.fruitList = fruitList;
    }

    public boolean hasNext() {
        if (position < fruitList.size())
            return true;
        else
            return false;
    }

    public Object next() {
        Object aniObj = fruitList.get(position);
        position++;
        return aniObj;
    }
    public void remove() {
        fruitList.remove(position);
    }
}


//Program: MyFruitIteratorExample.java, Execute the below program.
public class MyFruitIteratorExample {
    public static void main(String[] args) {
        
        MyOwnArrayList fruitList = new MyOwnArrayList();
        fruitList.add("Mango");
        fruitList.add("Strawaberry");
        fruitList.add("Papaya");
        fruitList.add("Watermalon");
        
        System.out.println("-----Calling my iterator on my ArrayList-----");
        FruitIterator it=fruitList.iterator();        
        while(it.hasNext()){
            String s=(String)it.next();
            System.out.println("Value: "+s);
        }
        System.out.println("--Fruit List size: "+fruitList.size());
        fruitList.remove(1);
        System.out.println("--After removal, Fruit List size: "+fruitList.size());
    }
}

//Output:
-----Calling my iterator on my ArrayList-----
My overridded iterator method called in Fruit class
Value: Mango
Value: Strawaberry
Value: Papaya
Value: Watermalon
--Fruit List size: 4
--After removal, Fruit List size: 3

NOTE: That's it. It is done. Now the same program won't compile if you use for-Each loop in main
      program to iterate my ArrayList. The reason is for-Each loop is designed to have an Iterator 
      return type from iterator() method which is defined in my ArrayList. So your Custom Iterator
      must implements Iterator interface then. This is also design of Iterator but it is a kind of
      extension. See below code will not compile.
      
      MyOwnArrayList fruitList = new MyOwnArrayList();
      fruitList.add("Mango");
      fruitList.add("Strawaberry");
      fruitList.add("Papaya");
      fruitList.add("Watermalon");
      for(Object obj:fruitList){     //Can only iterate over an array or an instance of java.lang.Iterable
            System.out.println("Value: "+obj);
      }
      
      Now keep the above code as it is and make the below changes:
      //Add Iterable interface in my ArrayList
       public class MyOwnArrayList implements RandomAccess, Cloneable, java.io.Serializable, Iterable {..}
      
      //Make FruitIterator and implementation of Iterator
      public class FruitIterator implements java.util.Iterator {..}
      
      Then the above for-Each loop will compile and run well.
============================END===============================      

Tuesday, April 10, 2012

ISO-8583 Standard in Java for Financial Transactions

Dear Reader,

I am writing about "ISO-8583 Standard" which is used in financial transactions that I learnt
while writing code and monitoring these banking/financial transactions.

A Financial transaction is a communication between 2 Systems through socket connection. Of course
this connection is maintained by network team. Once connection is established, each system (Sender and Recipient)
can send messages in ISO-8583 format which is common for request and response. However there are attributes which
differentiates a message into Request and Response.

From our experience the communication starts with Sign-on and then Echo messages and then financial transaction 
starts. Also periodically an echo message is sent to make sure the other system is still alive.

So following steps are involved in Transaction Flow:
    1. System A open connection to System B (through specific IP and Port).
    2. Connection established.
    3. System A send Sign-On request message.
    4. System B send Sign-on response message.
    5. System A will start sending Echo request message periodically (e.g. every 2 minute).
    6. System B will send Echo response message whenever receive Echo request message.
    7. When financial transaction happen, System A will send Transaction request message.
    8. Then System B will send Transaction response message.
    9. If something wrong happens (usually Timeout, so System A didn’t get the response), System A 
       will send Reversal request message to cancel the previous transaction.
    10. System B will send Reversal response message based on previous transaction.

I hope the flow is clear now. Next the question is how is this ISO-8583 message looks like.
An ISO-8583 message is made of the following parts:
   a. Message Type Indicator (MTI).
   b. One or more bitmaps, indicating which data elements are present.
   c. Data Elements, the fields of the message.

   
Message Type Indicator or MTI is 4 digits numeric that describe the message type. Commonly used are:
    - 02xx : Financial Message (e.g 0200 for request, 0210 for response)
    - 04xx : Reversal Message (e.g 0400 for request, 0410 for response)
    - 08xx : Network Management Message (e.g 0800 for request, 0810 for response)
    
    

    This 4 digit numeric field classifies the high level function of the message. A message type indicator 
    includes the ISO 8583 version, the Message Class, the Message Function and the Message Origin. 
    The following example (MTI 0110) lists what each digit indicates:    
        0xxx -> version of ISO 8583 (1987 version: 0-1987, 1-1993, 2-2003, 9-Private Usage).
        x1xx -> class of the Message (Authorization Message: 1-Authorization Message, 2-Financial Message, 
                4-Reversal Message)
                
        xx1x -> function of the Message (Request Response: 0-Request, 1-Request Response, 2-Advice, 
                4-Notification, 8-Response Acknowledgement).
        xxx0 -> who began the communication (Acquirer: 0-Acquirer, 1-Acquirer Repeat, 2-Issuer, 3-Issuer Repeat).

Complete example is below on the above pattern:
0200-     (Meaning: Acquirer Financial Request), Value: Request for funds, typically from an ATM or NPCI.
0210-     (Meaning: Issuer Response to Financial Request), Value:    Issuer response to request for funds.
More details can be checked at Wikipedia: http://en.wikipedia.org/wiki/ISO_8583

Bitmaps: 
Within ISO-8583, a bitmap is a field or subfield within a message which indicates which other data elements 
or data element subfields are present in a message. A message will contain at least one bitmap, 
called the Primary Bitmap which indicates which of Data Elements 1 to 64 are present. A secondary bitmap may 
also be present, generally as data element one and indicates which of data elements 65 to 128 are present. 
Similarly, a tertiary, but these are rarely used. In most of the messages Primary bitmap is enough.

The bitmap may be transmitted as 8 bytes of binary data, or as 16 hexadecimal characters 0-9, A-F. A field is 
present only when the specific bit in the bitmap is true. For example, 
byte '82x is binary '1000 0010' which means fields 1 and 7 are present in the message and fields 2, 3, 4, 5, 6, 
and 8 are not present. More details can be checked at Wikipedia: http://en.wikipedia.org/wiki/ISO_8583

Data Elements:
 Data Elements are the essence of the whole ISO message, which contains information about the transaction 
 (transaction type, amount, customer id, etc). 
 Data elements are the individual fields carrying the transaction information. There are up to 128 data 
 elements specified in the original ISO 8583:1987 standard, and up to 192 data elements in later releases.
 The 1993 revision added new definitions, deleted some, while leaving the message format itself unchanged. 
 Each data element have their own format, attribute and length. Each data element number also have standard 
 purpose, for example DE #4 is transaction amount.
 
 I am explaining below based on the example above. Check Wikipedia link given above again for full list.
 Each data element is designed to have a fixed set of either numeric, alpha numeric or variable character
 sets. These are called data type for each data element. Below are few abbreviations and meanings:

 a         Alpha, including blanks
 n         Numeric values only
 s         Special characters only
 an     Alphanumeric
 as     Alpha & special characters only
 ns     Numeric and special characters only
 ans     Alphabetic, numeric and special characters.
 b         Binary data
 z         Tracks 2 and 3 code set as defined in ISO/IEC 7813 and ISO/IEC 4909 respectively
 . or .. or ...     variable field length indicator, each . indicating a digit.
 x or xx or xxx     fixed length of field or maximum length in the case of variable length fields.

So, 
 DE6     n 12     Amount, cardholder billing with fixed 12 digits.
 DE7     n 10     Transmission date & time with fixed 10 digits.
 DE32     n ..11     Acquiring institution identification code with variable length. In our system: 100035.
 DE39     an 2     Response code, In our system: 00-Success, any other-Failure.
 
Now Few Data Elements name and details are given below: 
 DE32 = AcquirerId;
 DE41 = TID;
 DE42 = MID;
 DE49 = 356;
 DE3 = Processing code;
 DE4 = Transaction amount;
 DE7 – Transmission date & time (10 digits);
 DE11 – Systems trace audit number (STAN- 6 digits);
 DE44 – Additional response data;
 DE105 – Reserved for ISO use;

To make it practical let’s use an example. We want to send:
    DE3 : 201234
    DE4 : 10000
    DE7 : 1107221830
    DE11 : 123456
    DE44 : A5DFGR
    DE32 : 100035
    DE105 : ABCDEFGHIJ 1234567890

So now you will have a large bit pattern holding these values, that I don't want to display this.
By the way there is an open source Tool/Jar called JPOS Library which does this conversion. So we 
just use that Jar and set these attributes based on Data elements position in Code. 

Next I will write article about implementing ISO-8583 using JPOS library.

-----------------------------END-----------------------------

Monday, April 9, 2012

Auto-Wiring in Spring

Dear Reader,

We are going to discuss "Auto-Wiring in Spring framework". You might be knowing or might be expert on this,
either way you can comment if something more need to be added.

Topics discussed:
 1) A simple and complete program on Spring framework to start with.
 2) Types of Auto-Wiring and details of each Auto Wire mode.

Auto-Wiring is a term we use in Spring framework. It is a kind of injection of objects.
Let me write a basic Spring program and then I will discuss further:

======================================
//Customer class 
package com.deepak;
public class Customer {
    private Person person;
    public Customer(){
        System.out.println("Default Customer constructor");
    }  
    //person is set here through Constructor and setter method, see below:
    public Customer(Person person) {
        System.out.println("Parameterized Customer constructor");
        this.person = person;
    }
    public void setPerson(Person person) {
        System.out.println("Customer setter method");
        this.person = person;
    }
    public Person getPerson() {
        System.out.println("Customer getter method");
        return person;
    }
}

//Person class
package com.deepak;
public class Person {
    String skill="Default Skill is Java and Spring";
    public Person(){
        System.out.println("Default Person constructor");
    }

    public String getSkill() {
        System.out.println("Person getter method");
        return skill;
    }
    public void setSkill(String skill) {
        System.out.println("Person setter method");
        this.skill = skill;
    }
}

//autowire.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="customer" class="com.deepak.Customer">
        <property name="person" ref="person" />
    </bean>

    <bean id="person" class="com.deepak.Person">
        <property name="skill" value="Skill set changed to J2EE and Spring" />
    </bean>
</beans>


//Main Program to run
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.deepak.Customer;
import com.deepak.Person;

public class AutoWireMainProgram {
    public static void main(String[] args) {
        BeanFactory beanfactory = new ClassPathXmlApplicationContext("./autowire.xml");
        
        Customer customerBean=(Customer)beanfactory.getBean("customer");
        Person personBean=(Person)beanfactory.getBean("person");
        System.out.println("PersonBean: "+personBean+", Skill: "+personBean.getSkill());
        System.out.println("Bean Factory contains Bean(\"person\"): "+beanfactory.containsBean("person"));
    }
}


//Output:
    log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
    log4j:WARN Please initialize the log4j system properly.
    Default Customer constructor
    Default Person constructor
    Person setter method
    Customer setter method
    Person getter method
    PersonBean: com.deepak.Person@285b5c, Skill: Skill set changed to J2EE and Spring
    Bean Factory contains Bean("person"): true
======================================


The programs are quite basic and do not need any explanation.
That's it. Now we will see how Auto-Wiring works. In Spring we can wire beans with auto-wiring feature, this need to be 
configured in XML config file. To enable it, just define the "autowire" attribute in <bean> tag. 

So total 5 Auto-wiring modes are supported:
   1. no – It means No auto wiring. Better set it manually via "ref" attribute.
   2. byName – Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire it.
   3. byType – Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean 
      property, auto wire it.
   4. constructor – byType mode in constructor argument.
   5. default – This is same as "no" auto-wire in terms of functions.

Generally "byName", "byType", "constructor" are in use for Auto-wiring. You can see one more type "autodetect" mode but
I don't see this in Spring2.5 where I have tested the application.  

Details of all wiring modes:

Auto-Wiring with "no" mode: The above example uses "ref" attribute to refer a bean. This is "no" auto-wire. By the way
   same can be specified, so "no" wire mode is like below:
   
    //autowire.xml
    <bean id="customer" class="com.deepak.Customer" autowire="no">
        <!-- <property name="person" ref="person" /> -->
    </bean>

    <bean id="person" class="com.deepak.Person">
        <property name="skill" value="Skill set changed to J2EE and Spring" />
    </bean>

//No change in main program code base, below is the output:
    log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
    log4j:WARN Please initialize the log4j system properly.
    Default Customer constructor
    Default Person constructor
    Person setter method
    Person getter method
    PersonBean: com.deepak.Person@284370, Skill: Skill set changed to J2EE and Spring
    Bean Factory contains Bean("person"): true

NOTE: "Customer setter method" line is missing, not invoked. The same output comes when you set autowire="default".
      That shows by default it is "no" wire mode. Also note line "property name=person ref=person" is commented in bean tag.    
    

Auto-Wiring with "byName" mode: 
  Auto wire with "byName" mode means wiring by property name. Customer class has property name "person". 
  So Spring will auto wire it via setter method – "setPerson(Person person)".  
    
    //autowire.xml
    <bean id="customer" class="com.deepak.Customer" autowire="byName">    
    </bean>

    <bean id="person" class="com.deepak.Person">
        <property name="skill" value="Skill set changed to J2EE and Spring" />
    </bean>

//No change in main program code base, below is the output:
    log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
    log4j:WARN Please initialize the log4j system properly.
    Default Customer constructor
    Default Person constructor
    Person setter method
    Customer setter method
    Person getter method
    PersonBean: com.deepak.Person@284f12, Skill: Skill set changed to J2EE and Spring
    Bean Factory contains Bean("person"): true

NOTE: "Customer setter method" line is displayed, means invoked. The output is same as first one when we have not used wiring.    

Auto-Wiring with "byType" mode: 
    Auto wire with "byType" mode means wiring by property data type. Customer class has property "person" whose data
    type is "Person" and the same in config file too. So Spring will auto wire it via setter method – "setPerson(Person person)".   
    
    //autowire.xml
    <bean id="customer" class="com.deepak.Customer" autowire="byType">    
    </bean>

    <bean id="person" class="com.deepak.Person">
        <property name="skill" value="Skill set changed to J2EE and Spring" />
    </bean>
    
//No change in main program code base, below is the output:
    log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
    log4j:WARN Please initialize the log4j system properly.
    Default Customer constructor
    Default Person constructor
    Person setter method
    Customer setter method
    Person getter method
    PersonBean: com.deepak.Person@28862d, Skill: Skill set changed to J2EE and Spring
    Bean Factory contains Bean("person"): true

NOTE: "Customer setter method" line is displayed here too. The output is same as first one when we have not used wiring.    

Auto-Wiring with "constructor" mode: 
    Auto wire with "constructor" mode sets a bean by property data type in constructor argument. In this case, 
    since the data type of "person" bean is same as the constructor argument in Customer class. So Spring auto wired it 
    via constructor method – "public Customer(Person person)". Read the NOTE below carefully.
    
    //autowire.xml
    <bean id="customer" class="com.deepak.Customer" autowire="constructor">
    </bean>

    <bean id="person" class="com.deepak.Person">
        <property name="skill" value="Skill set changed to J2EE and Spring" />
    </bean>
    
//No change in main program code base, below is the output:
    log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
    log4j:WARN Please initialize the log4j system properly.
    Default Person constructor
    Person setter method
    Parameterized Customer constructor
    Person getter method
    PersonBean: com.deepak.Person@286fff, Skill: Skill set changed to J2EE and Spring
    Bean Factory contains Bean("person"): true

NOTE: "Customer setter method" line is not displayed here. But did you note: "Parameterized Customer constructor"
      is displayed which is a result of constructor auto wire. See the Constructor of Customer class again:
     
       public Customer(Person person) {
        System.out.println("Parameterized Customer constructor");
        this.person = person;
      }

Auto-Wiring with "default" mode: 
    This is same as "no" mode, which is discussed above.

Conclusion:  Spring "auto-wiring" makes development faster but it adds costs. The bean configuration file becomes
            quite complex because of this and some time you don’t even know which bean will auto wired in which bean.
===========================END==========================

Saturday, April 7, 2012

Generics in Java

Dear reader,

After a long duration I got time to discuss Generics and WildCard characters in Java. 
Generics are quite common now a days and is used heavily in applications. But generally we use 
Typed collections like List<String>, we say as List of String types. However here we will explore some 
more things.

Generics are basically for type-checking/type-safety, which is ERASED once compilation is done. I mean at 
run-time there is no generic concepts in JVM. So if you don't put your objects (type of objects) properly in 
collection or array, you may end up with ClassCastException or ArrayStoreException at run-time while fetching 
objects. 

This article covers:
 1) Normal program on Generics and how to use that. Comments are provided in program itself.
 2) Output of all those programs at the end of each program.
 3) "? extends T" type Generics.
 4) "? super T" type Generics.
 5) Implementation of "? extends" and "? super" in methods.
 6) Implementation of "T" in interfaces.

NOTE: Generics are not co-variant (please read further for co-variant) but Arrays are. 
      While you might find it helpful to think of collections as being an abstraction of arrays, they have some 
      special properties that collections do not. Arrays in the Java language are covariant -- which means that if 
      Integer extends Number (which it does), then not only is an Integer also a Number, but an Integer[] is also a 
      Number[], and you are free to pass or assign an Integer[] where a Number[] is called for. (More formally, 
      if Number is a supertype of Integer, then Number[] is a supertype of Integer[].) You might think the same is 
      true of generic types as well -- that List<Number> is a supertype of List<Integer>, and that you can pass a 
      List<Integer> where a List<Number> is expected. Unfortunately, it doesn't work that way. See below ex:
     
    Number[] n=new Number[3];
    Integer[] m=new Integer[3];
    n=m;  //Allowed
    m=n;  //Wrong. Reference of Super class to sub-class not allowed. Won't compile.
        
    List<Integer> li = new ArrayList<Integer>();
    List<Number> ln = new ArrayList<Number>();
    List<Number> ln2 = li;  //Illegal, Won't compile.
    ln.add(new Float(3.1415)); //Adding number is Ok, as Float is a Number sub type.
     
Now lets discuss Generics in detail. I am giving proper names for classes for representing super and 
sub-classes like:
1. Fruit super class
2. --Mango extends Fruit
3. --Papaya extends Fruit
4. --Apple extends Fruit
   ----WashingtonApple extends Apple

Coding:
-----------Fruit.java----------
public class Fruit{
}

-----------Mango.java----------
public class Mango extends Fruit {
}

-----------Papaya.java----------
public class Papaya extends Fruit {
}

-----------Apple.java----------
public class Apple extends Fruit {
}

-----------WashingtonApple.java----------
public class WashingtonApple extends Apple {
}

---------------------------------
//Main basic program to run: FruitMain.java

import java.util.ArrayList;
import java.util.List;

public class FruitMain {
    public static void main(String[] args) {
        Mango m=new Mango();
        Papaya p=new Papaya();
        Fruit f=new Fruit();
        //m=f; //Not allowed
        f=m; //Allowed
        f=p; //Allowed
        
        List <Fruit> fruitList=new ArrayList<Fruit>();
        fruitList.add(new Mango());
        fruitList.add(new Papaya());
        System.out.println("List contains: "+fruitList);

        List <Mango> mangoList=new ArrayList<Mango>();
        List <Papaya> papayaList=new ArrayList<Papaya>();
        //mangoList=fruitList;  //Not allowed, you know it is normal.
        
        //fruitList=mangoList;  //Here sub types are not allowed. Generics are not Co-variant.
                                   //But why? If a mango is a fruit, a box of mangoes (a list) is also a 
                                //box of fruits. Because you may later add: fruitList.add(new Papaya());

        //fruitList=papayaList; //Same as above, sub-types are not allowed.
        
        Mango[] mangoArray = new Mango[1];
        Fruit[] fruitArray = mangoArray;  //Arrays are Co-variant.
        fruitArray[0] = new Papaya();  //Compiles but at runtime throws java.lang.ArrayStoreException
        System.out.println("Fruit Array contains: "+fruitArray);
        
        //Because of this behavior of arrays, during a store operation, the Java runtime needs to check 
        //that the types are compatible. The check, obviously, also adds a performance penalty that you 
        //should be aware of. Why above was not allowed because how do you call: sort(fruitArray);
        //Sort will work only when array has same type of values.
    }
}

//Output:
List contains: [Mango@130c19b, Papaya@1f6a7b9]
Exception in thread "main" java.lang.ArrayStoreException: Papaya
    at FruitMain.main(FruitMain.java:30)

Highlights: Sub-Class objects can be assigned to Super classes but same is not true in Generics.    
    f=m; //Allowed
    fruitList=mangoList;  //Here sub types are not allowed. Check comment in program.
    fruitArray[0] = new Papaya();  //Compiles but at runtime throws java.lang.ArrayStoreException
-----------

"? extends T" type Generics:
What "?" stands for? It stands for Unknown type. As in begining I told, Generics are for type-Safety
compilations, we use this to avoid getting ClassCast kind of problems at run time, so loop holes be filtered 
at compilation time only by providing strict type safety. A simple example:

Suppose you want to make a copy of a parameter whose type is Set<?>. You've also been told it's better to use 
Set<?> instead of the raw type "Set" if you don't know the type of the set's contents. So you try this:

    class Foo {
        public void doSomething(Set<?> set) {
            Set<?> copy = new HashSet<?>(set);  //Illegal
        }
    }

Unfortunately, you can't invoke a generic constructor with a wildcard type argument. You should do this:
    class Foo {
        public void doSomething(Set<?> set) {
            Set<?> copy = new HashSet<Object>(set);  //Legal
        }
    }
This is type-safe and will do what you think new HashSet<?>(set) would do. 

Now let's discuss "? extends". Please see the program below, it will be quite clear:

//WildcardMain.java
import java.util.ArrayList;
import java.util.List;

public class WildcardMain {
    public static void main(String[] args) {
        
        //Repeating the array again
        Apple[] appleArray = new Apple[2];
        Fruit[] fruitArray = appleArray;
        fruitArray[0] = new Apple(); 
        //fruitArray[1] = new Papaya();  //Compiles but at runtime throws java.lang.ArrayStoreException
        System.out.println("Fruit Array contains: "+fruitArray);
        
        
        //Now we will use WildCard character: "? extends Fruit" : means List has a sub-type 
        //of Fruit but we don't know what is exact sub-type, so no addition is allowed apart from null.
        
        List<Apple> apples = new ArrayList<Apple>();
        apples.add(new Apple());
        apples.add(new Apple());
        List<? extends Fruit> fruits = apples;
        
        fruits.add(null);
        //fruits.add(new Apple());  //Not allowed, no Compilation.
        //fruits.add(new Fruit());  //This too not allowed, no Compilation.
        //fruits.add(new Mango());  //Not allowed, no Compilation.
        //fruits.add(new WashingtonApple()); //Not allowed, no Compilation.
        System.out.println("Fruit WildCard Array contains: "+fruits);
        
        Fruit f=fruits.get(0);  //This is ok, as for whatever sub-type case, returned object will be Fruit.
        System.out.println("Returned Fruit: "+f);
    }
}
//Output:
Fruit Array contains: [LApple;@923e30
Fruit WildCard Array contains: [Apple@130c19b, Apple@1f6a7b9, null]
Returned Fruit: Apple@130c19b

-----------
"? super T" type Generics:
See the program below, it will be quite clear:

//WildcardSuper.java
import java.util.ArrayList;
import java.util.List;
public class WildcardSuper {
    public static void main(String[] args) {
        List<Fruit> fruits = new ArrayList<Fruit>();
        fruits.add(new Fruit());
        fruits.add(new Fruit());
        System.out.println("Fruit List contains: "+fruits);

        //Making super class of Apple but not sure what super type, So Apple, WashingtonApple is 
        //allowed but not Object which is also super class of Apple.
        List<? super Apple> apples = fruits; 
        System.out.println("Apple Super Wildcard contains: "+apples);
        
        apples.add(new Apple());    //Only Apple or sub-classes of Apple is allowed.
        //apples.add(new Mango());  //Not allowed.
        //apples.add(new Object()); //Only Apple or sub-classes of Apple is allowed.
        //apples.add(new Fruit());  //This is also not allowed. Since we can not know which super type 
                                    //it is, we aren't allowed to add instances of any.

        apples.add(new WashingtonApple());
        System.out.println("Now Apple Super Wildcard contains: "+apples);
        
        Object o=apples.get(0); //Only object will be returned as we don't what super type it is.
        System.out.println("Returned object: "+o);
    }
}
//Output:
Fruit List contains: [Fruit@82ba41, Fruit@923e30]
Apple Super Wildcard contains: [Fruit@82ba41, Fruit@923e30]
Now Apple Super Wildcard contains: [Fruit@82ba41, Fruit@923e30, Apple@7d772e, WashingtonApple@11b86e7]
Returned object: Fruit@82ba41

-----------
Implementation of "? extends" and "? super" in methods:

    static void makeEmpty(List<? extends Fruit> fruits){ 
        System.out.println("Container contents: "+fruits);
    }
        
    Since a List of whichever subtype of the class Fruit is a subtype of List<? extends Fruit>, 
    the previous method will accept any such list as a parameter. Ex:
        
        List<Apple> apples = new ArrayList<Apple>();        
        List<? extends Fruit> fruits = apples;  //Check more detail in above program: WildcardMain.java
        makeEmpty(fruits);         //Allowed as it is same as Fruit class.
        makeEmpty(apples);         //This is already allowed as it extends Fruit.
---------

    static void store(List<? super Fruit> container){ 
        System.out.println("Container contents: "+container);
    }
    
    This way, a List of whichever supertype of Fruit could be passed in to the store function and you could 
    safely put whichever Fruit subtype into it.

    List<Fruit> fruits = new ArrayList<Fruit>();    
    List<? super Apple> apples = fruits;     //Check more detail in above program: WildcardSuper.java    
    apples.add(new Apple());   //Only Apple or sub-classes of Apple is allowed. 
    //apples.add(new Mango());  //Not allowed.
    store(fruits);   //Only Fruit and super type of Fruits are allowed.
    //store(apples); //Not allowed

----------
Implementation of "T" in interfaces:
I don't want to discuss this topic in detail but just giving a sample program and help:
See the List interface in java.util package, below is the declaration:
public interface List<E> extends Collection<E> {}

//My definitions:
public interface JuicyInterface<T> {
    Juice<T> squeeze();
}
-------
public class Juice<T> {
}
-------
public class Orange extends Fruit implements JuicyInterface<Orange> {
    static Juice<Orange> orangeJuice=null;
    
    public Juice<Orange> squeeze() {
        return null;
    }
    public static void main(String[] args) {
        Orange orange=new Orange();
        orangeJuice=orange.squeeze();
        System.out.println(orangeJuice);
    }
}

Summarizing the behavior of the "? extends" and the "? super" wildcards, we draw the following conclusion:
  1. Use the "? extends" wildcard if you need to retrieve object from a data structure.
  2. Use the "? super" wildcard if you need to put objects in a data structure.
  3. If you need to do both things, don't use any wildcard.
--------------------------------END----------------------------------

Friday, April 6, 2012

Big-Endian and Little-Endian

Dear reader,

I am writing here about Endian-ness, which is a bit-storing pattern to hold data.
The more details are given below.

Java is Big-Endian which is a network order. That's why Java is portable.
The term Endian or Endian-ness refers to the ordering of bits for a representation of a larger data item as 
stored in external memory (or, sometimes, as sent on a serial network connection).

Big-Endian: 01234.. (Left to Right bit ordering).
|------------>>>>>

Little-Endian: ..43210 (Right to Left bit ordering).
<<<<<------------|

Endian | First byte(lowest address) | Middle bytes  |    Last byte(highest address) | Example    
Big    | Most_Significant             |    ...         |    Least_Significant          | Number written on paper in Roman.
Little | Least_Significant             |    ...         |    Most_Significant         | Arithmetic calculation order (carry propagation).

The simple forms are:
    increasing numeric significance with increasing memory addresses (or increasing time), known as little-endian, and
    decreasing numeric significance with increasing memory addresses (or increasing time), known as big-endian.


Giving below examples on Endianness and operating systems on these architectures:

Little-endian (operating systems with architectures on Little Endian):    
    FreeBSD on x86, x86-64, and Itanium.
    Linux on x86, x86-64, Alpha, Itanium, ARM and UniCore32.
    Mac OS X on x86, x86-64.
    NetBSD on x86, x86-64, Itanium, etc.
    OpenBSD on x86, x86-64, Itanium, etc.    
    Solaris on x86, x86-64, PowerPC.    
    Windows on x86, x86-64, Alpha, PowerPC, MIPS and Itanium.

Big-endian (operating systems with architectures on Big Endian):
    AIX on POWER.
    FreeBSD on PowerPC and SPARC.
    HP-UX on Itanium and PA-RISC.
    Linux on SPARC, POWER, PowerPC, ARMEB and Xtensa.
    Mac OS on PowerPC and 680x0.    
    NetBSD on PowerPC, SPARC, etc.
    OpenBSD on PowerPC, SPARC, etc.
    MVS and DOS/VSE on ESA/390, and z/VSE and z/OS on z/Architecture.
    Solaris on SPARC.
------------------------------END---------------------------

Basics of Java

Dear Reader,
I have written few programs on basics, it may help you to explore new things. By the way it is just
for my reference. Topics: 
 1. Infinite Loop
 2. Mixed basics (Including signed unsigned bit operations)
 3. Logical Operators
 4. finally
 5. String concatenation
 6. Count of iterations
 7. Inheritance
 8. Modulus

Infinite Loop:
------
public class InfiniteLoop {
    public static void main(String[] args) {
        System.out.println("The below line of code is an infinite loop:");
        for (int i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i+=1)
            System.out.println(i+", ");
    }
}
/*
It's an infinite loop, because every int value is less than or equal to Integer.MAX_VALUE. 
Once the loop gets to Integer.MAX_VALUE, it wraps to next value which is negative and starts over again.
*/
---------------


Mixed basics:
------
public class JoyOfHex {
    public static void main(String[] args) {        
        System.out.println(Long.toHexString(0x100000000L + 0xcafebabe)); 
        
        double x = 2.0;
        double y = 1.1;
        System.out.println( x - y );   //Why not 0.9
        
        int x1 = 10 + 010;
        System.out.println(x1);        //Why not 20 or if binary then 12 (10+2).
        
        double x2 = 1.0 / 2L;
        System.out.println(x2);        //You have to tell.
        
        int x3 = 11 % 2*5;
        System.out.println(x3);        //You have to tell.
        
        System.out.println(  ((int)(char)(byte) -1) );  //You have to tell.
    }
}
//Output:
cafebabe   //Why not 0x1cafebabe
0.8999999999999999  //1.1 gets represented as the nearest double then we subtract. The answer is rounded 
                    //to the nearest double, which happens to be the ugly thing you’ve just seen.
18  //If you put 0 before a number, JVM assumes that number as Octal.
0.5 //No magic here.
5
65535  //00000000000000001111111111111111

NOTE:  Signed (-1) 11111111111111111111111111111111
      (byte)Signed (-1): 11111111
      (char)Unsigned (65535) 1111111111111111
      (int)Signed (65535) 00000000000000001111111111111111
Rule: Sign extension is performed if the original value is signed. Otherwise zero extension.
    Java doesn't provide unsigned types. Java is Big-Endian which is network order.
    The term Endian or Endianness refers to the ordering of bits for a representation of a larger data item as 
    stored in external memory (or, sometimes, as sent on a serial network connection).

    Big-Endian: 01234.. (Left to Right bit ordering).
    |------------>>>>>

    Little-Endian: ..43210 (Right to Left bit ordering).
    <<<<<------------|

=================


Logical Operators:
------
public class LogicalOperator {
    public static void main(String[] args) {
        int j=0;
        int i = (j++) + (j++);
        System.out.println(i+" "+j);
        
        //What will be value of k in below program
        int k=0;
        for (int m=0; m<100; m++){
            k=k++;
        }
        System.out.println(k);  //You have to tell.
    }
}
//Output:
1 2
0
---------------


finally:
------
public class TryHarder {
    public static void main(String[] args) {
        TryHarder t=new TryHarder();
        System.out.println(t.returnInt());
        t.noReturn();
    }
    public int returnInt(){
        try{
            return 5;
        }
        catch(Exception e){
            return 15;
        }
        finally {
            return 10;
        }
        //return 20;  //Unreachable code
    }
    public void noReturn(){
        try{
            System.out.println("Inside try");
            return;
        }
        catch(Exception e){
            System.out.println("Inside catch");
            return;
        }
        finally {
            System.out.println("Inside finally");
        }
    }
}
//Output:
10
Inside try
Inside finally
NOTE: finally may not execute only when System.exit() call is made. Or a Thread is interrupted or
      a dead lock has come in multithreaded env.
---------------


String Concatenation:
------
public class StringOut {
    public static void main(String[] args) {
        System.out.println("R"+"2");
        System.out.println('D'+'2');  
    }
}
//Output:
R2
118
//Ascii: 68 + 50, Ascii table link: http://www.asciitable.com/
---------------


Count of Iterations:
------
//How may iterations you think the following loop does
public class LoopHole {
    public static void main(String[] args) {
        double d = 0.0;
        long count=0L;
        while ( d != 1.0 ) {
            d += 1.0 / 13;        //1.0 / 13 = 0.07692307692307693
            count++;
            System.out.println(d);
        }
        System.out.println("Count is: "+count); //Code is keep on counting, an infinite loop.
    }
}
//Output:
Infinite loop. Always handle addition properly.

See below code: 
long y = 1000000*5000;  //Overflows as right side calculation is on Integers. Specify "L" for long.
long y = 1000000L*5000; //Correct, made one as Long.
---------------

Inheritance:
------
class PolyPain {
    public String name = "Parent";
    public void Print() { 
        System.out.println("Parent");
    }
    public static void Print2() { 
        System.out.println("Parent"); 
    }
}

public class PolyPainChild extends PolyPain {
    public String name = "Child";
    public void Print() { 
        System.out.println("Child"); 
    }
    public static void Print2() { 
        System.out.println("Child"); 
    }
    public static void main(String[] args) {
        PolyPainChild c = new PolyPainChild();
        PolyPain p = (PolyPain)c;
        p.Print();  //Child
        p.Print2(); //Parent
        System.out.println(p.name); //Parent
    }
}
//Output:
Child
Parent
Parent

NOTE: Overridden methods exhibit dynamic polymorphism. Overridden static methods do not.
Overridden (“shadowed”) fields also do not exhibit dynamic polymorphism. 
---------------

Modulus:
------
public static boolean isOdd (int x) {
return (x % 2 == 1);
}
NOTE: Works for positive x only.

Java defines % as: (a / b) * b + (a % b) = a
So if a<0, b>0 then (a % b) < 0.
i.e. (-7 % 2) = -1 and not 1.

Fixes:
    public static boolean isOdd (int x) {
        return (x % 2 != 0);
    }
    public static boolean isOdd (int x) {
        return (x & 1 != 0); //bit wise operator.
    }
------------------------------END------------------------------

Thursday, April 5, 2012

Equals and HashCode in Java

Dear reader,
I have already written equals() and hashCode() as a part of "How HashMap works in Java", however writing
it again by making very simple example. HashMap related stuff can be seen in the below link:
http://deepakmodi2006.blogspot.in/2012/03/hashmap-in-java.html

Below are the points to remember:
    1) These two methods are defined in java.lang.Object class.
    2) If two objects are equal using equals() method (not ==) then their hashCode must be same.
    3) If hashCode are same for two or more than two objects, they may not be equal using equals() method.
    4) Overridding both methods in your API is not mandatory, you can override any one method.
    
    5) At last written the Contract based on what both method works as specified in Java Doc.
    6) Also make sure don't use random number generator in hashCode method, as it generates unexpected number, 
       every time you run the code and you will not be able to generate same hashCode for the same object passed.
       I mean suppose we generate hashCode() using a class Person's object based on this:
   
       public int hashCode(){
         return (int)Math.random()+firstName.hashCode()+lastName.hashCode();
       }
   
       Now for name "Deepak Modi" and "Deepak Kumar", hashCode should be different. Of course it is different here 
       in first run of the program. But when you run the program again without making any changes, you will get again 
       different hashCode what you generated for "Deepak Modi" and "Deepak Kumar" earlier. Java Spec don't say this. 
   

Please see below example:
===================================================
import java.util.HashMap;
import java.util.Map;

public class EqualsClass {
    String name;
    int id;
    public EqualsClass(){}
    public EqualsClass(String name, int id){
        this.id=id;
        this.name=name;
    }    
    @Override
    public int hashCode(){
        return 34;
    }
    public static void main(String[] args) {
        Map m=new HashMap();
        m.put("A", "65");
        m.put("B", "66");
        m.put("C", "67");
        System.out.println("Initially Map contains: "+m);

        EqualsClass p1=new EqualsClass("Deepak1",1);
        EqualsClass p2=new EqualsClass("Deepak2",2);
        m.put(p1,"Deepak1");
        m.put(p2,"Deepak2");

        System.out.println("After adding our Objects, Map contains: "+m);
        System.out.println("First object hashCode: "+p1.hashCode());
        System.out.println("Second object hashCode: "+p2.hashCode());
        System.out.println("p1.equals(p2): "+p1.equals(p2));
        System.out.println("p1==p2: "+(p1==p2));
    }
}
//Output:
Initially Map contains: {A=65, C=67, B=66}
After adding our Objects, Map contains: {EqualsClass@22=Deepak2, EqualsClass@22=Deepak1, A=65, C=67, B=66}
First object hashCode: 34
Second object hashCode: 34
p1.equals(p2): false
p1==p2: false

NOTE: Analyze the above output. HashCode of both objects are same even then they are not equal.
      I have written only hashCode() method and not equals(), it runs fine. Overridding both are not mandatory.
      Now I will add equals() method and then see:

=============
import java.util.HashMap;
import java.util.Map;

public class EqualsClass {
    String name;
    int id;
    public EqualsClass(){}
    public EqualsClass(String name, int id){
        this.id=id;
        this.name=name;
    }
    @Override
    public boolean equals(Object obj){
        return true;
    }
    @Override
    public int hashCode(){
        return 34;
    }
    public static void main(String[] args) {
        Map m=new HashMap();
        m.put("A", "65");
        m.put("B", "66");
        m.put("C", "67");
        System.out.println("Initially Map contains: "+m);

        EqualsClass p1=new EqualsClass("Deepak1",1);
        EqualsClass p2=new EqualsClass("Deepak2",2);
        m.put(p1,"Deepak1");
        m.put(p2,"Deepak2");

        System.out.println("After adding our Objects, Map contains: "+m);
        System.out.println("First object hashCode: "+p1.hashCode());
        System.out.println("Second object hashCode: "+p2.hashCode());
        System.out.println("p1.equals(p2): "+p1.equals(p2));
        System.out.println("p1==p2: "+(p1==p2));
    }
}
//Output:
Initially Map contains: {A=65, C=67, B=66}
After adding our Objects, Map contains: {EqualsClass@22=Deepak2, A=65, C=67, B=66}
First object hashCode: 34
Second object hashCode: 34
p1.equals(p2): true
p1==p2: false
---------------      
NOTE: Analyze the above output. I have made HashCode of all objects same and equals() method is returning true in 
      all the cases. Result: All objects are treated as equal. Also the last object in Map overrides the previous 
      Key in Map.

equals() Method contract: The equals method implements an equivalence relation:
 1. It is reflexive: for any reference value x, x.equals(x) should return true.
 2. It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) 
    returns true.
 3. It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, 
    then x.equals(z) should return true.
 4. It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or 
    consistently return false, provided no information used in equals comparisons on the object is modified.
 5. For any non-null reference value x, x.equals(null) should return false.      
 6. It is necessary to override the hashCode method whenever this equals method is overridden, so as to maintain the 
    general contract for the hashCode method, which states that equal objects must have equal hash codes.       
 7. If two references are pointing to same object, I mean if x==y, then they x.equals(y) will result true.    
      

hashCode() Method contract: Returns a hash code value for the object. This method is supported for the benefit of 
    HashTables/HashMaps. The general contract of hashCode is:
 1. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method 
    must consistently return the same integer, provided no information used in equals comparisons on the object is modified. 
    This integer need not remain consistent from one execution of an application to another execution of the same application.
    Hence we should avoid using Math.random() or Random Class API for generating hashCode() as random will generate random
    values for the same object everytime we run to fetch hashCode().
    
 2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two 
    objects must produce the same integer result. If two objects are un-equal according to the equals(java.lang.Object) 
    method, then calling the hashCode method on each of the two objects may produce same integer results. However, the 
    programmer should be aware that producing distinct integer results for un-equal objects will improve the performance of 
    HashTables/HashMaps.
    
 3. As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for 
    distinct objects. This is typically implemented by converting the internal address of the object into an integer.     

--------------
So finally an example of correct implementation:
-----------------------
public class Test {
    private int num;
    private String data;

    public boolean equals(Object obj) {
        if(this == obj)
            return true;
        if((obj == null) || (obj.getClass() != this.getClass()))
            return false;

        //Now Object must be Test at this point as rest all are filtered above
        Test test = (Test)obj;
        return num == test.num &&
               (data == test.data ||
                (data!=null && data.equals(test.data)) 
               );
    }
    public int hashCode() {
        int hash = 7;
        hash = 31 * hash + num;
        hash = 31 * hash + (null == data ? 0 : data.hashCode());
        return hash;
    }
    //Other methods
}

NOTE: A common loop hole people use in equals() method like "instanceof" operator as below:
      Always use this: 
            (obj.getClass() != this.getClass())) return false;  //Use this
      
      As compare to: 
            if(!(obj instanceof Test)) return false;  //Never use this

      This is because, the first condition ensures that it will return false if the argument is a subclass of the class 
      Test. However, in case of the second condition (instanceof) it returns true. The instanceof operator condition fails 
      to return false if the argument is a subclass of the class Test. Thus, it might violate the symmetry requirement of 
      the contract. The instanceof check is correct only if the class is final, so that no subclass would exist. 
      
-------------------------END----------------------------    

Reflection in Java

Dear reader,
  I am discussing here "Java's Reflection API". Points discussed are below:
        a. Introduction and Use of Java's Reflection API.
        b. Getting the complete details of a Class using Reflection API and Complete program to use that 
           and so output.
        c. Call the Method using reflection and setting the values (it is there in program itself).
        d. How to find Getter/Setter method using Java Reflection API.
        e. How to call a Private method of a class using Reflection API. Again complete program is given.
        f. How to create Arrays using Reflection and how to find an Object if it is an Array. Also how to
           convert an Array into java.lang.Class.

Introduction:
It helps us to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the 
classes, methods etc at compile time. It is also used to instantiate new objects, invoke methods and get/set 
field values. 

Using Java Reflection you can inspect Java classes at runtime. Inspecting classes is often the first thing 
you do when using Reflection. From the classes you can obtain information about:
    Class Name
    Class Modifies (public, private, synchronized etc.)
    Package Info
    Super class
    Implemented Interfaces
    Constructors
    Methods
    Fields
    Annotations
At the same time you can invoke constructors, methods using reflection. I have written a very good program on
this which covers one by one all most all topics. Please go through carefully.

Complete Program:
==========PersonClass.java=============
//This class is having all the field, method declarations. It is inside a package "com.modi.deepak".

package com.modi.deepak;
public class ParentClass {
    static int no_numerics=10;
    public int no_states=28;
    private static int no_chars=26;
    public int arr[]={0,1,2,3,4};
    
    /*private ParentClass(){
        System.out.println("ParentClass's default constructor");
    }*/
    public ParentClass(){
        System.out.println("ParentClass's default constructor");
    }
    private ParentClass(int no_numerics){
        System.out.println("ParentClass's integer parameterized constructor");
    }
    public ParentClass(String no_numerics){
        System.out.println("ParentClass's String parameterized constructor");
    }
    public void myMethod(){
        System.out.println("PersonClass myMethod with no parameter");
    }
    public static String myMethod(String name){
        System.out.println("PersonClass myMethod with String parameter");
        return "Hello:" +name;
    }
}

==========MainClass.java=============
//This is the main program which I need to run to see the output, no package, in default folder.

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.modi.deepak.ParentClass;  //importing ParentClass

public class MainClass {
    public static void main(String[] args) {
        System.out.println("Inside main class, main method...");

        Class classObject=ParentClass.class;
        System.out.println("Class's Full Name: "+classObject.getName());
        System.out.println("Class's Simple Name: "+classObject.getSimpleName());
        System.out.println("Count of modifiers: "+classObject.getModifiers());

        Package packageObject = classObject.getPackage(); //Gives you package name.
        System.out.println("Class's Package Name: "+classObject.getPackage());

        Class superclass = classObject.getSuperclass();  //Gives you super class name
        System.out.println("Class's Super class Name: "+superclass);

        Class[] interfaces = classObject.getInterfaces(); //Gives all interfaces class implements.
        Constructor[] constructors = classObject.getConstructors(); //Gives all public Constructors class has.

        Method[] methodObject= classObject.getMethods(); //Gives all methods class has.
        System.out.println("\nMethods of this class:");
        for(Method m:methodObject)
            System.out.print(m.getName()+", ");

        System.out.println("\n"); //For new line
        Field[] fieldObject = classObject.getFields();  //Getting all field objects which are public.
        System.out.println("Public field length: "+fieldObject.length);  //Only 2
        for(Field m:fieldObject)
            System.out.print(m.getName()+", ");  //Only no_states, arr, as they are public

        Field[] allFieldObject = classObject.getDeclaredFields();  //Getting all fields including private.
        System.out.println("\nAll field length: "+allFieldObject.length);  //Total 4
        for(Field m:allFieldObject)
            System.out.print(m.getName()+", ");  //all fields including private

        //Fetching Annotations
        Annotation[] annotations = classObject.getAnnotations();


        //Selected methods
        try {
            Constructor constructor = classObject.getConstructor(new Class[]{String.class}); //Only public constructor
            System.out.println("\nSelected Constructor: "+constructor);
        }
        //If no constructor matches the given constructor arguments, in this case String.class, 
        //a NoSuchMethodException is thrown. 
        catch(NoSuchMethodException e){
            e.printStackTrace();
        }

        //Instantiating an Object using reflection (constructor) only private constructor
        try {
            Constructor constructor = ParentClass.class.getConstructor(String.class);
            System.out.println("\nCreating an object using Reflection, only public constructor be invoked:");
            //Below argument is optional but need to provide String as we want to invoke String
            //Parameterized constructor
            ParentClass myObject = (ParentClass)constructor.newInstance("This String is optional");
            System.out.println("See above line output, constructor invoked..");
        }
        catch(NoSuchMethodException e){
            e.printStackTrace();
        }
        catch(InstantiationException e){
            e.printStackTrace();
        }
        catch(IllegalAccessException e){
            e.printStackTrace();
        } 
        catch (IllegalArgumentException e) {
            e.printStackTrace();
        } 
        catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        //Setting field values
        try {
            Field field = classObject.getField("no_states");  
            ParentClass objectInstance = new ParentClass();  //Getting the value using normal new keyword.
            int value = (Integer)(field.get(objectInstance));  
            System.out.println("\nOld value from Class: "+value);
            value+=20;   //value can't be changed for final fields like no_states should not be final. 
            field.set(objectInstance, value);
            System.out.println("Modified value from Class: "+value);
        }
        catch(Exception e){
            e.printStackTrace();            
        }



        //Fetching and invoking methods dynamically
        try {
            Method method = ParentClass.class.getMethod("myMethod", String.class);
            //Method method123 = classObject.getMethod("myMethod", null);  //In case no parameter in method
            Object returnValue = method.invoke(null, "Deepak");
            
            ParentClass objectInstance = new ParentClass();  //Getting the value using normal new keyword.
            Object returnValue2 = method.invoke(objectInstance, "Deepak Modi");
            
            //The null parameter is the object you want to invoke the method on. If the method is 
            //static you supply null instead of an object instance. In this example, if 
            //myMethod(String.class) is not static, you need to supply a valid PersonClass instance. 
            System.out.println("\nReturned value after method call: "+returnValue);
            System.out.println("\nReturned value after method call: "+returnValue2);
        } 
        catch (SecurityException e) {
            e.printStackTrace();
        } 
        catch (NoSuchMethodException e) {
            e.printStackTrace();
        } 
        catch (IllegalArgumentException e) {
            e.printStackTrace();
        } 
        catch (IllegalAccessException e) {
            e.printStackTrace();
        } 
        catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
    
//Output:
Inside main class, main method...
Class's Full Name: com.modi.deepak.ParentClass
Class's Simple Name: ParentClass
Count of modifiers: 1
Class's Package Name: package com.modi.deepak
Class's Super class Name: class java.lang.Object

Methods of this class:
myMethod, myMethod, getClass, hashCode, equals, toString, notify, notifyAll, wait, wait, wait, 

Public field length: 2
no_states, arr, 
All field length: 4
no_numerics, no_states, no_chars, arr, 
Selected Constructor: public com.modi.deepak.ParentClass(java.lang.String)

Creating an object using Reflection, only public constructor be invoked:
ParentClass's String parameterized constructor
See above line output, constructor invoked..
ParentClass's default constructor

Old value from Class: 28
Modified value from Class: 48
PersonClass myMethod with String parameter
ParentClass's default constructor
PersonClass myMethod with String parameter

Returned value after method call: Hello:Deepak

Returned value after method call: Hello:Deepak Modi
----------------------------------------------------------

Finding Setter and Getter method:
Apart from these fetching strategy, you can find a Setter/Getter methods using Reflection too,
Below is the code for the same:

    public static void printGettersSetters(Class aClass){
        Method[] methods = aClass.getMethods();

        for(Method method : methods){
            if(isGetter(method)) System.out.println("getter: " + method);
            if(isSetter(method)) System.out.println("setter: " + method);
        }
    }

    public static boolean isGetter(Method method){
        if(!method.getName().startsWith("get"))      return false;
        if(method.getParameterTypes().length != 0)   return false;  
        if(void.class.equals(method.getReturnType()) return false;
        return true;
    }

    public static boolean isSetter(Method method){
        if(!method.getName().startsWith("set")) return false;
        if(method.getParameterTypes().length != 1) return false;
        return true;
    }
------------------------------

NOTE: Generally there are two kind of methods available in reflection like "aClass.getMethods()" and 
      "aClass.getDeclaredMethods()". "getDeclaredMethods()" will give all the methods description like private, 
      protected, public, default but "getMethods()" will give only public method descriptions.
      So all declared methods like "getDeclaredFields(), getDeclaredConstructors(), getDeclaredMethods()" etc are available.
------------------------------

Accessing Private Methods from a class using Reflection:
-----------
//This is the class whose private method I want to invoke
package com.modi.deepak;
public class PrivateClass {
    private String value="Temp Value";
    private PrivateClass(){
        System.out.println("PrivateClass's private constructor");
    }
    public PrivateClass(String param){
        System.out.println("PrivateClass's public String parameterized constructor");
        this.value=param;
    }
    private String myMethod(){
        System.out.println("\n******PrivateClass private myMethod with no parameter******\n");
        return "Hello: " +value;
    }
    public void myAnotherMethod(String name){
        System.out.println("PrivateClass public myAnotherMethod with String parameter:"+name);
    }
}
-----------
//Main program who will call the above class
import java.lang.reflect.Method;
import com.modi.deepak.PrivateClass;

public class MainPrivateClass {
    public static void main(String[] args) throws Exception { //Throwing all exceptions here
        PrivateClass normalObject = new PrivateClass("Deepak Modi is good technical developer");
        
        normalObject.myAnotherMethod("Java is Ocean");
        //normalObject.myMethod();  //This is private method, not visible outside, Compiler won't allow it.

        Class privateObject=PrivateClass.class;
        Method privateMethod = privateObject.getDeclaredMethod("myMethod", null);
        
        //Making private method accessibility true
        privateMethod.setAccessible(true);

        String returnValue = (String)privateMethod.invoke(normalObject, null);
        System.out.println("Private method invoked, see above line output: returnValue = " + returnValue);
    }
}
-----------
//Output:
PrivateClass's public String parameterized constructor
PrivateClass public myAnotherMethod with String parameter:Java is Ocean

******PrivateClass private myMethod with no parameter******

Private method invoked, see above line output: returnValue = Hello: Deepak Modi is good technical developer

=================================
Creation of Array using Reflection: We can create an Array using Reflection.
Please see the program below. The most challenging part is to convert an Array (integer or String or anything else)
into a "java.lang.Class" object via Reflection. See below:

    Class intArray = Class.forName("[I");

The JVM represents an int via the letter I. The [ on the left means it is the class of an int array. This works 
for all other primitives too. For objects you need to use a slightly different notation:
   
   Class strArrayClass = Class.forName("[Ljava.lang.String;");
Notice the [L to the left of the class name, and the ; to the right. This means an array of objects with the given type.
If you use the below line of code: 
   Class c1=Class.forName("java.lang.String"); //It will not be an Array.

Please go through the complete coding below:   

---------------
import java.lang.reflect.Array;
public class ArrayReflection {
    public static void main(String[] args) {

        int arr[]=(int[])Array.newInstance(int.class,5);
        System.out.println("Newly Created Array length: "+arr.length);
        arr[0]=0;
        arr[1]=1;
        arr[2]=2;
        arr[3]=3;
        arr[4]=4;
        System.out.println("Array elements are: ");
        for(int num:arr)
            System.out.print(num+", ");

        //Now If I have an array, need to find what kind of Array it is:
        String[] strArray = new String[4];
        Class strArrayClass = strArray.getClass();
        //Class strArrayClass = String[].class;   //This and above line, both are same

        Class strArrayComponentType = strArrayClass.getComponentType();
        System.out.println("\nType of Array: "+strArrayComponentType);

        try {
            Class c=Class.forName("java.lang.Integer");
            System.out.println("Class: "+c+", Type: "+c.getComponentType()+", isArray: "+c.isArray());

            Class c1=Class.forName("java.lang.String");
            System.out.println("Class: "+c1+", Type: "+c1.getComponentType()+", isArray: "+c1.isArray());

            Class c2=Class.forName("[I");  //For Integer Array
            System.out.println("Class: "+c2+", Type: "+c2.getComponentType()+", isArray: "+c2.isArray());
            
            Class c5=Class.forName("[Ijava.lang.Integer");  //For Integer Array, complete path here.
            System.out.println("Class: "+c5+", Type: "+c5.getComponentType()+", isArray: "+c5.isArray());

            Class c3=Class.forName("[Ljava.lang.String;"); //For String Array
            System.out.println("Class: "+c3+", Type: "+c3.getComponentType()+", isArray: "+c3.isArray());
            
            Class c4=Class.forName("[Ljava.lang.Long;"); //For Long Array
            System.out.println("Class: "+c4+", Type: "+c4.getComponentType()+", isArray: "+c4.isArray());
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
---------------
//Output:
Newly Created Array length: 5
Array elements are: 
0, 1, 2, 3, 4, 
Type of Array: class java.lang.String
Class: class java.lang.Integer, Type: null, isArray: false
Class: class java.lang.String, Type: null, isArray: false
Class: class [I, Type: int, isArray: true
Class: class [I, Type: int, isArray: true
Class: class [Ljava.lang.String;, Type: class java.lang.String, isArray: true
Class: class [Ljava.lang.Long;, Type: class java.lang.Long, isArray: true


That's it. In next article I will write about Reflection for Generics, Proxy Objects.
However I found a good URL to read for, you can go through it, in fact few Ideas I have taken from the same URL:
http://tutorials.jenkov.com/java-reflection/generics.html
http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html

Other useful links are below:
http://www.xyzws.com/javafaq/how-to-use-reflection-to-call-methods-in-java/153
http://onjava.com/pub/a/onjava/2007/03/15/reflections-on-java-reflection.html?page=1
http://www.wikijava.org/wiki/Class_and_static_Method_Reflection_example
---------------------------------END-----------------------------------      

Monday, April 2, 2012

Loop and Star Printing Programs

Dear reader,
I am writing this blog on a basic Loop and Star(*) printing in Java. Now these loop questions are asked only
at freshers level but recently one interviewer has asked me to do that. He has asked me 4 patterns to print
including Mirroring an Array Matrix. However I saved myself by replying 3 out of 4. Writing here the complete
program for me/your reference, hope it will help.

Programs written here, output is given too for help:
    1) Print a simple Pyramid, One sided and then Reverse one sided. This was not asked to me.
    2) Print a complete Pyramid which looks real, space between STARs. This was asked.
    3) Show a Mirror image of an Array. Row data should get reversed with their mirror images. This was asked.
    4) Printing a Numeric Pyramid using numbers. Again not asked.

==============Print a simple Pyramid, One sided and then Reverse one sided=================
//StarPrinting.java

public class StarPrinting {
    public static void main(String[] args) {
        int n=5;
        //One sided pyramid
        System.out.println("One sided pyramid:");
        for(int i=0;i<=n;i++) {
            for(int j=0;j<=i;j++){
                System.out.print("*");
            }
            System.out.println();
        }
        
        //Reverse Pyramid
        System.out.println("\nReverse pyramid:");
        for(int i=n;i>=0;i--) {
            for(int j=0;j<=i;j++){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
//Output:::::::::::::::
One sided pyramid:
*
**
***
****
*****
******

Reverse pyramid:
******
*****
****
***
**
*
==============Print a simple Pyramid, One sided and then Reverse one sided=================


==============Print a complete Pyramid which looks real, space between STARs===============
//OriginalPyramid.java

public class OriginalPyramid {
    public static void main(String[] args) {        
        int n=5; // Assign "n" any number
        
        //Both sided pyramid
        System.out.println("Both sided pyramid:");
        for(int i=0;i<=n;i++) {
            for(int j=i+n; j< (2*n); j++){
                System.out.print(" ");   //Print left side spaces
            }
            for(int k=0; k<i; k++){
                System.out.print("* ");  //Print Star and then followed by a space 
            }
            System.out.println();
        }
    }
}
//Output:::::::::::::::
Both sided pyramid:
     
    * 
   * * 
  * * * 
 * * * * 
* * * * * 
==============Print a complete Pyramid which looks real, space between STARs=================



==============Mirror image of an Array Matrix========================
/* Write a program to print Mirror image of below left side Array:
1 2 3  Mirror  3 2 1
4 5 6          6 5 4
7 8 9          9 8 7
10 11 12      12 11 10 
*/

//MirrorArray.java
public class MirrorArray {
      public static void main(String[] args) {
            int arr1[][]={ {1,2,3},{4,5,6},{7,8,9},{10,11,12}};
            int row=arr1.length;
            int col=arr1[0].length;
            int arr2[][]=new int[row][col];  //Here I will store mirror array elements.
            
            //Output array should have same no of rows and columns as master array. 
            System.out.println("Original Array elements:");
            for(int i=0;i<row;i++) {
                  for(int j=0;j<col;j++){
                        System.out.print(arr1[i][j]+" ");
                  }
                  System.out.println();
            }            
            System.out.println("Mirror Array elements:");
            for(int i=0;i<row;i++) {
                  for(int j=0;j<col;j++){
                        arr2[i][j]=arr1[i][col-(j+1)];
                        System.out.print(arr2[i][j]+" ");
                  }
                  System.out.println();
            }
      }
}
//Output::::::::::::
Original Array elements:
1 2 3 
4 5 6 
7 8 9 
10 11 12 
Mirror Array elements:
3 2 1 
6 5 4 
9 8 7 
12 11 10 
==============Mirror image of an Array Matrix========================


==============Numeric Pyramid========================
//PowerFactor.java
public class PowerFactor {
    public static void main(String[] args) {
        int n=4;
        int row;
        System.out.println("Numeric Pyramid:");
        for (row = 0; row <= n; row++){   //Prints each row 
            for (int spaces = n; spaces >= row; spaces --){ //Prints out double spaces to left
                System.out.print("  ");
            }

            int power1 = 0; //Power that 2 is being raised to
            for (int i=0; i<row; i++) { //Prints left side of the pyramid 
                System.out.print(" " + (int)Math.pow(2, power1));
                power1++;
            }

            int power2=row - 1;
            for (int i=1; i<row; i++) { //Prints right side of the pyramid 
                power2--;
                System.out.print(" "+(int)Math.pow(2, power2));       
            }
            System.out.println();
        }
    }
}

//Output:::::::::
Numeric Pyramid:
    
    1
  1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
==============Numeric Pyramid========================