Archive for May, 2011


Hey Folks,

This is all about the post

What: Object Interaction

Language: Java

Example Illustrated: CheckingBankAccount

Functionalities : Create, Credit, Debit, Display Bank accounts

DataStructure used : Hashtable ( To store and lookup accounts)

Constraints :    Every debit made from an a/c with  less than $100 will be charged $10 fee

Every debit made from an a/c with less than $0 balance will be charged $30 overdraft fee

How many classes : 3 (CheckingAccount.java, AccountTable.java, Tester.java)

Points to note :

CheckingAccount.java and AccountTable.java are defined in a PACKAGE checkingaccount

Data members of  CheckingAccount.java don’t have any access-modifier (default modifier) . So it is visible for all classes in its own package . In other  words, AccountTable.java can access it directly without using any get methods.

But, main class (Tester.java) is the one the user directly interacts with. User shouldn’t have access to the datamembers of bank  account. In real world, a customer can credit or debit or view his own account details and not any body else. So giving access to  the hashtable of accounts (AccountTable.java) is a very poor design and SHOULD BE AVOIDED.

Its for this reason,  CheckingAccount and  the data structure to hold it (AccounTable ) are in one package and they can access directly the datamembers of each other whereas to keep the user away, Tester.java is out of the checkingaccount package.

This way a user can  interact with account classes only via accessors and mutators (get and set methods) and not directly with the data members of  those classes.  Now it makes sense why Tester was outside the package. If not, it can access the datamembers of other two classes directly.

As an example, thats why  to access  balance a datamember of CheckingAccount.java    Tester.java uses account.getBalance() [an accessor – as datamember ‘balance’ cant be accessed directly outside the package ] and  AccountTable.java uses account.balance as it is in the same package as CheckingAccount.java. The respective  lines is made bold  and Italicized in the code as well. Check it out below

Compilation :

1. Say you copy paste the Tester.java to a folder Bank

2. Create a folder checkingaccount inside Bank folder

3. Copy paste the remaining two java files to checkingaccount folder

Now, if u r under Linux OS, you may have something like

usr-name:~bank/ ls

Tester.java                     checkingaccount

usr-name:~bank/cd checkingaccount

usr-name:~bank/ checkingaccount/ ls

CheckingAccount.java              AccountTable.java

Now give                     javac *.java (This creates class files for the above two java files)

Now  cd .. and come to the parent directory (bank)

Now give                   javac   Tester.java to create Tester.class

Now to execute the program give                  java  Tester

So here is the code!

//Tester.java

/**
 *
 * @author poochedi
 */
import java.util.*;
import checkingaccount.*;

public class Tester {

      public static void main(String[] args) {

          System.out.println("Enter Your option (1-4) to continue and 5 to exit");
          System.out.println("1.CREATE ACCOUNT 2.CREDIT 3.DEBIT 4.DISPLAY 5.EXIT" );

          //create an object for hashtable
          AccountTable table = new AccountTable();

          Scanner scanObject = new Scanner(System.in);
          Scanner scanDetails;
          while( scanObject.hasNextLine() ) {

               int option = scanObject.nextInt();
               if(option > 5)
                System.out.println("Enter a number from 1-5");

               if(option == 1) {

                   //create an account
                   scanDetails = new Scanner(System.in);
                   System.out.println("Enter the following details");

                   System.out.println("Name");
                   String name = scanDetails.next();

                   System.out.println("A/c Number");
                   String acNumber = scanDetails.next();

                   CheckingAccount account = new CheckingAccount(name, acNumber);

                   //add the account to hash table
                   table.addAccount(account);
                   System.out.println("Account created successfully");
               }

               if(option == 2) {

                  //Credit to account
                  scanDetails = new Scanner(System.in);
                  System.out.println("Enter the name of the a/c holder");
                  String name = scanDetails.next();

                  CheckingAccount account = table.searchAccount(name);

                  if(account != null)
                  {
                    System.out.println("Enter the amount to be credited ");
                    double amount = Double.parseDouble(scanDetails.next());
                    account.credit(name, amount);
                    double newBalance = account.getBalance();
                    table.updateBalance(name,newBalance);
                  }
                  else
                    System.out.println("No such account found");
               }

               if(option == 3) {

                  //Debit from account
                  scanDetails = new Scanner(System.in);
                  System.out.println("Enter the name of the a/c holder");
                  String name = scanDetails.next();          

                  CheckingAccount account = table.searchAccount(name);
                  if(account != null) {

                    System.out.println("Enter the amount to be debited ");
                    double amount = Double.parseDouble(scanDetails.next());
                    account.debit(amount);
                    //put into table the updated details
                    double newBalance = account.getBalance();
                    table.updateBalance(name,newBalance);

                  }
                  else
                    System.out.println("No such account found");
               }

               if(option == 4) {

                 //display account details
                 scanDetails = new Scanner(System.in);
                 System.out.println("Enter the name of the a/c holder");
                 table.displayAccount();
               }

               if(option == 5) {

                  System.out.println("Thanks for using our service");
                  System.exit(0);
               }

               System.out.println("Enter Your option (1-4) to continue and 5 to exit");
               System.out.println("1.CREATE ACCOUNT 2.CREDIT 3.DEBIT 4.DISPLAY 5.EXIT");
               scanObject = new Scanner(System.in);
          }
    }

}
===================================================================================================================
//AccountTable.java
package checkingaccount;

/**
 *
 * @author poochedi
 */
import java.util.*;

public class AccountTable {

       //data member
      //DEFAULT access modifier
      //ACCESSIBLE ONLY WITHING THE PACKAGE
      Hashtable <String, CheckingAccount> table;

      //==========================================================================================================

      public AccountTable() {

          table = new Hashtable();
      }

      //==========================================================================================================

      public void addAccount(CheckingAccount account) {

          String key = account.accountHolder;
          table.put(key, account);
      }

//==========================================================================================================

      public CheckingAccount searchAccount(String name) {

              if(table.containsKey(name))
                    return table.get(name);
              return null;
      }

//==========================================================================================================

      public void displayAccount() {

              Enumeration enumObj = table.keys();
              while(enumObj.hasMoreElements()) {

                    String acNumber = (String) enumObj.nextElement();
                    CheckingAccount acc = table.get(acNumber);
                    System.out.print(acc.accountHolder + " ");
                    System.out.print(acc.accountNumber + " ");
                    System.out.print(acc.overDraftCount + " ");
                    System.out.println(acc.balance + " ");
              }
      }

//==========================================================================================================

      public void updateBalance(String name, double balance) {

            if(table.containsKey(name)) {

                  CheckingAccount acc = table.get(name);
                  acc.balance = balance;
                  table.put(name, acc);
            }
      }
}
===================================================================================================================
//CheckingAccount.java
package checkingaccount;

/**
 *
 * @author poochedi
 */

public class CheckingAccount {

        //data members -- DEFAULT access modifier
        //So ACCESSIBLE ONLY WITHIN THE PACKAGE
         String accountHolder;
         String accountNumber;
         double balance;
         int overDraftCount;

        //default constructor
        public CheckingAccount() {

            accountHolder = " ";
            accountNumber = "0000000-000";
            balance = 0.00;
            overDraftCount = 0;
        }

        //parameterized constructor
        public CheckingAccount(String acOwner, String acNumber) {

            accountHolder = acOwner;
            accountNumber = acNumber;
            balance = 0.00;
            overDraftCount = 0;

        }

//==========================================================================================================

        //mutators - set method - Process credit
        //add amount to balance
        public void credit(String name, double amountCredited) {

                //Search the account
                double totalOverDraftCharge = this.overDraftCount * 30;
                this.balance = this.balance + amountCredited - totalOverDraftCharge;
        }

//==========================================================================================================

        //mutators - set method - Process debit
        //deduct amount from balance
        public void debit(double amountToDeduct) {

                 double charge = 0.00;
              //if balance less than $100 deduct $10 for every check processed

                      if(this.balance < 100)
                          charge = 10.00;
                      this.balance = this.balance - amountToDeduct - charge;
                      if(this.balance < 0)
                          this.overDraftCount++;
        }

//==========================================================================================================

        //accessors - get methods - get the balance
        public double getBalance() {

                 //Search the account
                  return this.balance;
        }

}

I am yet another software engineer driven to America in search of better opportunities. Though onsite is one way to make it to USA, the land of opportunities, before you get one you are already tired of the routine mechanical work and are desperate to move to a better company. I din’t want to keep hopping from one company to another  in search of a better work environment, which is non-existent! Though, engineers back in India, talk about how working in India is patriotic, they conveniently forget the fact that they too work for foreign clients. So there is no point in blaming those Indians settled in abroad as unpatriotic, for all of us work for USA.

Now, this may rise a question why should we work for some other nation when we have the strongest educated human resource. Well,  we all study engineering because thats what fetches the highest salary now. From an IIT ian to a student from an average engineering college, every one dreams of a future in America. The impact of westernization is so high that gen-next kids listen only to Eminem and Justin Beiber and wonder at the awesomeness of English lyrics while we don’t consider lack of  mother tongue knowledge as a shame anymore. Thats how we are wired!  ok I am kind of drifting away from the intended topic.

Back to the question – What is happiness according to our generation, especially the IT sector? Even before I complete the question, anybody will answer MONEY! Kudos! U win the brownie points! This puts the next question  – are we really happy by earning the money we dream? Answer may not be instant. How much ever time you pause or even if you go without answering, our conscience knows its a big NO!

Do you think those people who come to study  Masters abroad are happy? Not atall! They slog to find part-time jobs.  They earn a little, dream to save a lot, spend a little and look into the bank balance every time before they leave for grocery shopping. Well thats the way of student life in any foreign country.

Ok, now what about IT people in India. They earn pretty well. They should live life king-size. If thats what you think, I am sorry you are too naive! Money is an addiction. Its a craving. You always want more. IT people in India earn and invest in land or car or any thing for the sake of status. There starts the problem. Its indeed a wise idea to invest money. But even for a land in B’lore you need to invest all your savings. In addition to it, you will need a bank loan which will last for minimum 5 years. Awing at the mammoth loan, one works tirelessly, loosing interest in sex life and a happy family. Many of the IT folks don’t even have time to talk to their spouse because by the time they return home, they grow largely tired and need a sleep badly. This approach to life makes their  spouse and kids desperate for warmth and care. This is the starting point for a cascade of problems in family life. People, especially women who realize this, want to leave their job and be at home attending their family. But any loan claimed, intimidates them and forces to understand, that only if both the adults go for job, the  loan can be repaid else there is no end for it.

So what about IT people settled in USA and other foreign countries? They have green card,  a regular working hours. They should be contented and happy. Unfortunately, answer is again a NO! Atleast, when you settle in India you have  relatives (dad n mom) to help in case of any emergencies. Also, if you loose a job in one IT company, any day you can shift to some others easily. But  in abroad, loosing your job is the last thing you want to think about!  Starting from Auto Insurance to credit card bills, everything queues up, time and again and life becomes a bitter struggle. Not to mention about health care bills. If you are admitted for a mild chest pain, seeing the bill, you will either get a fatal heart attack or commit suicide! No kidding, even a X-ray costs $400 in USA. If you are in emergency ward for a severe stomach pain, on seeing the bill you  are sure to develop chest pain, for, a half-an-hour time in emergency ward costs you $500. By the time you obtain green card, you could observe your hair line recedes, you put on weight out of stress and look 10+ of your actual age! Worst, is the dream to buy a home. Even if a husband and wife work, a mortgage per month costs 15 days salary of both. S0 what remains is, one month salary of one person, which tries to choke you before you could pay all other monthly bills.

Kaasu illadhavanuku oru prachana! irukuravanuku pala !!

Is it better to think that money is not happiness?? Folks, lets succumb to reality! We can’t do anything without money. Though not true, we are wired to think money is happiness.  Hope you find enough happiness. Bye!

Welcome all!

This blog is all about my perceptions, learnings and struggles. I am yet another person dreaming of and working steadily towards a “secure” future! We may differ only in what we think security is!