Tuesday, December 4, 2012

Regular Expression Basic Syntax Reference


Regular Expression Basic Syntax Reference

Characters
CharacterDescriptionExample
Any character except [\^$.|?*+()All characters except the listed special characters match a single instance of themselves. { and } are literal characters, unless they're part of a valid regular expression token (e.g. the {n} quantifier).a matches a
\ (backslash) followed by any of [\^$.|?*+(){}A backslash escapes special characters to suppress their special meaning.\+ matches +
\Q...\EMatches the characters between \Q and \E literally, suppressing the meaning of special characters.\Q+-*/\E matches+-*/
\xFF where FF are 2 hexadecimal digitsMatches the character with the specified ASCII/ANSI value, which depends on the code page used. Can be used in character classes.\xA9 matches © when using the Latin-1 code page.
\n, \r and \tMatch an LF character, CR character and a tab character respectively. Can be used in character classes.\r\n matches a DOS/Windows CRLF line break.
\a, \e, \f and\vMatch a bell character (\x07), escape character (\x1B), form feed (\x0C) and vertical tab (\x0B) respectively. Can be used in character classes.
\cA through \cZMatch an ASCII character Control+A through Control+Z, equivalent to\x01 through \x1A. Can be used in character classes.\cM\cJ matches a DOS/Windows CRLF line break.
Character Classes or Character Sets [abc]
CharacterDescriptionExample
[ (opening square bracket)Starts a character class. A character class matches a single character out of all the possibilities offered by the character class. Inside a character class, different rules apply. The rules in this section are only valid inside character classes. The rules outside this section are not valid in character classes, except for a few character escapes that are indicated with "can be used inside character classes".
Any character except ^-]\ add that character to the possible matches for the character class.All characters except the listed special characters.[abc] matches a, b orc
\ (backslash) followed by any of ^-]\A backslash escapes special characters to suppress their special meaning.[\^\]] matches ^ or ]
- (hyphen) except immediately after the opening [Specifies a range of characters. (Specifies a hyphen if placed immediately after the opening [)[a-zA-Z0-9] matches any letter or digit
^ (caret) immediately after the opening [Negates the character class, causing it to match a single characternot listed in the character class. (Specifies a caret if placed anywhere except after the opening [)[^a-d] matches x (any character except a, b, c or d)
\d, \w and \sShorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.[\d\s] matches a character that is a digit or whitespace
\D, \W and \SNegated versions of the above. Should be used only outside character classes. (Can be used inside, but that is confusing.)\D matches a character that is not a digit
[\b]Inside a character class, \b is a backspace character.[\b\t] matches a backspace or tab character
Dot
CharacterDescriptionExample
. (dot)Matches any single character except line break characters \r and \n. Most regex flavors have an option to make the dot match line break characters too.. matches x or (almost) any other character
Anchors
CharacterDescriptionExample
^ (caret)Matches at the start of the string the regex pattern is applied to. Matches a position rather than a character. Most regex flavors have an option to make the caret match after line breaks (i.e. at the start of a line in a file) as well.^. matches a inabc\ndef. Also matches d in "multi-line" mode.
$ (dollar)Matches at the end of the string the regex pattern is applied to. Matches a position rather than a character. Most regex flavors have an option to make the dollar match before line breaks (i.e. at the end of a line in a file) as well. Also matches before the very last line break if the string ends with a line break..$ matches f inabc\ndef. Also matches c in "multi-line" mode.
\AMatches at the start of the string the regex pattern is applied to. Matches a position rather than a character. Never matches after line breaks.\A. matches a in abc
\ZMatches at the end of the string the regex pattern is applied to. Matches a position rather than a character. Never matches before line breaks, except for the very last line break if the string ends with a line break..\Z matches f inabc\ndef
\zMatches at the end of the string the regex pattern is applied to. Matches a position rather than a character. Never matches before line breaks..\z matches f inabc\ndef
Word Boundaries
CharacterDescriptionExample
\bMatches at the position between a word character (anything matched by \w) and a non-word character (anything matched by [^\w] or \W) as well as at the start and/or end of the string if the first and/or last characters in the string are word characters..\b matches c in abc
\BMatches at the position between two word characters (i.e the position between \w\w) as well as at the position between two non-word characters (i.e. \W\W).\B.\B matches b in abc
Alternation
CharacterDescriptionExample
| (pipe)Causes the regex engine to match either the part on the left side, or the part on the right side. Can be strung together into a series of options.abc|def|xyz matchesabc, def or xyz
| (pipe)The pipe has the lowest precedence of all operators. Use grouping to alternate only part of the regular expression.abc(def|xyz)matches abcdef orabcxyz
Quantifiers
CharacterDescriptionExample
? (question mark)Makes the preceding item optional. Greedy, so the optional item is included in the match if possible.abc? matches ab orabc
??Makes the preceding item optional. Lazy, so the optional item is excluded in the match if possible. This construct is often excluded from documentation because of its limited use.abc?? matches ab orabc
* (star)Repeats the previous item zero or more times. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is not matched at all.".*" matches"def" "ghi" inabc "def" "ghi" jkl
*? (lazy star)Repeats the previous item zero or more times. Lazy, so the engine first attempts to skip the previous item, before trying permutations with ever increasing matches of the preceding item.".*?" matches "def"inabc "def" "ghi" jkl
+ (plus)Repeats the previous item once or more. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is matched only once.".+" matches"def" "ghi" inabc "def" "ghi" jkl
+? (lazy plus)Repeats the previous item once or more. Lazy, so the engine first matches the previous item only once, before trying permutations with ever increasing matches of the preceding item.".+?" matches "def"inabc "def" "ghi" jkl
{n} where n is an integer >= 1Repeats the previous item exactly n times.a{3} matches aaa
{n,m} where n >= 0 and m >= nRepeats the previous item between n and m times. Greedy, so repeating m times is tried before reducing the repetition to n times.a{2,4} matches aaaa,aaa or aa
{n,m}? where n >= 0 and m >= nRepeats the previous item between n and m times. Lazy, so repeating n times is tried before increasing the repetition to m times.a{2,4}? matches aa,aaa or aaaa
{n,} where n >= 0Repeats the previous item at least n times. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is matched only n times.a{2,} matches aaaaain aaaaa
{n,}? where n >= 0Repeats the previous item n or more times. Lazy, so the engine first matches the previous item n times, before trying permutations with ever increasing matches of the preceding item.a{2,}? matches aa inaaaaa

Java Serialization

本文讲解了Java序列化的机制和原理。从文中你可以了解如何序列化一个对象,什么时候需要序列化以及Java序列化的算法。有关Java对象的序列化和反序列化也算是Java基础的一部分,下面对Java序列化的机制和原理进行一些介绍。
Java序列化算法透析
  Serialization(序列化)是一种将对象以一连串的字节描述的过程;反序列化deserialization是一种将这些字节重建成一个对象的过程。Java序列化API提供一种处理对象序列化的标准机制。在这里你能学到如何序列化一个对象,什么时候需要序列化以及Java序列化的算法,我们用一个实例来示范序列化以后的字节是如何描述一个对象的信息的。
  序列化的必要性
    Java中,一切都是对象,在分布式环境中经常需要将Object从这一端网络或设备传递到另一端。
    这就需要有一种可以在两端传输数据的协议。Java序列化机制就是为了解决这个问题而产生。
    如何序列化一个对象
    一个对象能够序列化的前提是实现Serializable接口,Serializable接口没有方法,更像是个标记。
    有了这个标记的Class就能被序列化机制处理。
    1. import java.io.Serializable;  
    2.  
    3. class TestSerial implements Serializable {  
    4.  
    5.        public byte version = 100;  
    6.  
    7.        public byte count = 0;  
    8.  
    9. } 
    然后我们写个程序将对象序列化并输出。ObjectOutputStream能把Object输出成Byte流。
    我们将Byte流暂时存储到temp.out文件里。
    1. public static void main(String args[]) throws IOException {  
    2.  
    3.        FileOutputStream fos = new FileOutputStream("temp.out");  
    4.  
    5.        ObjectOutputStream oos = new ObjectOutputStream(fos);  
    6.  
    7.        TestSerial ts = new TestSerial();  
    8.  
    9.        oos.writeObject(ts);  
    10.  
    11.        oos.flush();  
    12.  
    13.        oos.close();  
    14.  
    如果要从持久的文件中读取Bytes重建对象,我们可以使用ObjectInputStream。  
    public static void main(String args[]) throws IOException {  
       FileInputStream fis = new FileInputStream("temp.out");  
    
                               ObjectInputStream oin = new ObjectInputStream(fis);    
    
                              TestSerial ts = (TestSerial) oin.readObject();   
    
                               System.out.println("version="+ts.version);  
    
                           } 
                        
    
                        执行结果为
                        100.
                        对象的序列化格式
    
    
                        将一个对象序列化后是什么样子呢?打开刚才我们将对象序列化输出的temp.out文件,
    
                        以16进制方式显示。内容应该如下:
    
    
                        
    AC ED 00 05 73 72 00 0A 53 65 72 69 61 6C 54 65
    73 74 A0 0C 34 00 FE B1 DD F9 02 00 02 42 00 05
    63 6F 75 6E 74 42 00 07 76 65 72 73 69 6F 6E 78
    70 00 64
    
    这一坨字节就是用来描述序列化以后的TestSerial对象的,我们注意到TestSerial类中只有两个域: public byte version = 100; public byte count = 0; 且都是byte型,理论上存储这两个域只需要2个byte,但是实际上temp.out占据空间为51bytes, 也就是说除了数据以外,还包括了对序列化对象的其他描述。 Java的序列化算法 序列化算法一般会按步骤做如下事情: ◆将对象实例相关的类元数据输出。 ◆递归地输出类的超类描述直到不再有超类。 ◆类元数据完了以后,开始从最顶层的超类开始输出对象实例的实际数据值。 ◆从上至下递归输出实例的数据 我们用另一个更完整覆盖所有可能出现的情况的例子来说明:
    1. class parent implements Serializable {  
    2.  
    3.        int parentVersion = 10;  
    4.  
    5. }  
    6.  
    7.    
    8.  
    9. class contain implements Serializable{  
    10.  
    11.        int containVersion = 11;  
    12.  
    13. }  
    14.  
    15. public class SerialTest extends parent implements Serializable {  
    16.  
    17.        int version = 66;  
    18.  
    19.        contain con = new contain();  
    20.  
    21.    
    22.  
    23.        public int getVersion() {  
    24.  
    25.               return version;  
    26.  
    27.        }  
    28.  
    29.        public static void main(String args[]) throws IOException {  
    30.  
    31.               FileOutputStream fos = new FileOutputStream("temp.out");  
    32.  
    33.               ObjectOutputStream oos = new ObjectOutputStream(fos);  
    34.  
    35.               SerialTest st = new SerialTest();  
    36.  
    37.               oos.writeObject(st);  
    38.  
    39.               oos.flush();  
    40.  
    41.               oos.close();  
    42.  
    43.        }  
    44.  
    45. } 
    这个例子是相当的直白啦。SerialTest类实现了Parent超类,内部还持有一个Container对象。
    序列化后的格式如下:
    AC ED 00 05 73 72 00 0A 53 65 72 69 61 6C 54 65
    73 74 05 52 81 5A AC 66 02 F6 02 00 02 49 00 07
    76 65 72 73 69 6F 6E 4C 00 03 63 6F 6E 74 00 09
    4C 63 6F 6E 74 61 69 6E 3B 78 72 00 06 70 61 72
    65 6E 74 0E DB D2 BD 85 EE 63 7A 02 00 01 49 00
    0D 70 61 72 65 6E 74 56 65 72 73 69 6F 6E 78 70
    00 00 00 0A 00 00 00 42 73 72 00 07 63 6F 6E 74
    61 69 6E FC BB E6 0E FB CB 60 C7 02 00 01 49 00
    0E 63 6F 6E 74 61 69 6E 56 65 72 73 69 6F 6E 78
    70 00 00 00 0B
    我们来仔细看看这些字节都代表了啥。开头部分,见颜色:
    1. AC ED: STREAM_MAGIC. 声明使用了序列化协议.
    2. 00 05: STREAM_VERSION. 序列化协议版本.
    3. 0x73: TC_OBJECT. 声明这是一个新的对象.  
    序列化算法的第一步就是输出对象相关类的描述。例子所示对象为SerialTest类实例,
    因此接下来输出SerialTest类的描述。见颜色:
    1. 0x72: TC_CLASSDESC. 声明这里开始一个新Class。
    2. 00 0A: Class名字的长度.
    3. 53 65 72 69 61 6c 54 65 73 74: SerialTest,Class类名.
    4. 05 52 81 5A AC 66 02 F6: SerialVersionUID, 序列化ID,如果没有指定,
      则会由算法随机生成一个8byte的ID.
    5. 0x02: 标记号. 该值声明该对象支持序列化。
    6. 00 02: 该类所包含的域个数。
    接下来,算法输出其中的一个域,int version=66;见颜色:
    1. 0x49: 域类型. 49 代表"I", 也就是Int.
    2. 00 07: 域名字的长度.
    3. 76 65 72 73 69 6F 6E: version,域名字描述.
    然后,算法输出下一个域,contain con = new contain();这个有点特殊,是个对象。
    描述对象类型引用时需要使用JVM的标准对象签名表示法,见颜色:
    1. 0x4C: 域的类型.
    2. 00 03: 域名字长度.
    3. 63 6F 6E: 域名字描述,con
    4. 0x74: TC_STRING. 代表一个new String.用String来引用对象。
    5. 00 09: 该String长度.
    6. 4C 63 6F 6E 74 61 69 6E 3B: Lcontain;, JVM的标准对象签名表示法.
    7. 0x78: TC_ENDBLOCKDATA,对象数据块结束的标志
    .接下来算法就会输出超类也就是Parent类描述了,见颜色:
    1. 0x72: TC_CLASSDESC. 声明这个是个新类.
    2. 00 06: 类名长度.
    3. 70 61 72 65 6E 74: parent,类名描述。
    4. 0E DB D2 BD 85 EE 63 7A: SerialVersionUID, 序列化ID.
    5. 0x02: 标记号. 该值声明该对象支持序列化.
    6. 00 01: 类中域的个数.
    下一步,输出parent类的域描述,int parentVersion=100;同见颜色:
    1. 0x49: 域类型. 49 代表"I", 也就是Int.
    2. 00 0D: 域名字长度.
    3. 70 61 72 65 6E 74 56 65 72 73 69 6F 6E: parentVersion,域名字描述。
    4. 0x78: TC_ENDBLOCKDATA,对象块结束的标志。
    5. 0x70: TC_NULL, 说明没有其他超类的标志。.
    到此为止,算法已经对所有的类的描述都做了输出。下一步就是把实例对象的实际值输出了。这时候是从parent Class的域开始的,见颜色:
    1. 00 00 00 0A: 10, parentVersion域的值.
    还有SerialTest类的域:
    1. 00 00 00 42: 66, version域的值.
    再往后的bytes比较有意思,算法需要描述contain类的信息,要记住,
    现在还没有对contain类进行过描述,见颜色:
    1. 0x73: TC_OBJECT, 声明这是一个新的对象.
    2. 0x72: TC_CLASSDESC声明这里开始一个新Class.
    3. 00 07: 类名的长度.
    4. 63 6F 6E 74 61 69 6E: contain,类名描述.
    5. FC BB E6 0E FB CB 60 C7: SerialVersionUID, 序列化ID.
    6. 0x02: Various flags. 标记号. 该值声明该对象支持序列化
    7. 00 01: 类内的域个数。
    .输出contain的唯一的域描述,int containVersion=11;
    1. 0x49: 域类型. 49 代表"I", 也就是Int..
    2. 00 0E: 域名字长度.
    3. 63 6F 6E 74 61 69 6E 56 65 72 73 69 6F 6E: containVersion, 域名字描述.
    4. 0x78: TC_ENDBLOCKDATA对象块结束的标志.
    这时,序列化算法会检查contain是否有超类,如果有的话会接着输出。
    1. 0x70:TC_NULL,没有超类了。
    最后,将contain类实际域值输出。
    1. 00 00 00 0B: 11, containVersion的值.
    OK,我们讨论了java序列化的机制和原理,希望能对同学们有所帮助。
 1、序列化是干什么的?
  简单说就是为了保存在内存中的各种对象的状态(也就是实例变量,不是方法),并且可以把保存的对象状态再读出来。虽然你可以用你自己的各种各样的方法来保 存object states,但是Java给你提供一种应该比你自己好的保存对象状态的机制,那就是序列化。
  2、什么情况下需要序列化
  a)当你想把的内存中的对象状态保存到一个文件中或者数据库中时候;
  b)当你想用套接字在网络上传送对象的时候;
  c)当你想通过RMI传输对象的时候;
  6、相关注意事项
  a)序列化时,只对对象的状态进行保存,而不管对象的方法;
  b)当一个父类实现序列化,子类自动实现序列化,不需要显式实现Serializable接口;
  c)当一个对象的实例变量引用其他对象,序列化该对象时也把引用对象进行序列化;
  d)并非所有的对象都可以序列化,,至于为什么不可以,有很多原因了,比如:
  1.安全方面的原因,比如一个对象拥有private,public等field,对于一个要传输的对象,比如写到文件,或者进行rmi传输 等等,在序列化进行传输的过程中,这个对象的private等域是不受保护的。
  2. 资源分配方面的原因,比如socket,thread类,如果可以序列化,进行传输或者保存,也无法对他们进行重新的资源分 配,而且,也是没有必要这样实现。
  详细描述:

Monday, December 3, 2012

The Greek Letter - Front Office Risk Management


Greeks


Dimensions of risk involved in taking a position in an option (or other derivative). Each risk variable is a result of an imperfect assumption or relationship of the option with another underlying variable. Various sophisticated hedging strategies are used to neutralize or decrease the effects of each variable of risk.


Neutralizing the effect of each variable requires substantial buying and selling and, as a result of such high transactions costs, many traders only make periodic attempts to rebalance their options portfolios.

With the exception of vega (which is not a Greek letter), each measure of risk is represented by a different letter of the Greek alphabet:

Δ(Delta) represents the rate of change between the option's price and the underlying asset's price - in other words, price sensitivity.

Θ(Theta) represents the rate of change between an option portfolio and time, or time sensitivity.

Γ(Gamma) represents the rate of change between an option portfolio's delta and the underlying asset's price - in other words, second-order time price sensitivity.
 
ϒ(Vega) represents the rate of change between an option portfolio's value and the underlying asset's volatility - in other words, sensitivity to volatility.

ρ (Rho) represents the rate of change between an option portfolio's value and the interest rate, or sensitivity to the interest rate.

Read more: http://www.investopedia.com/terms/g/greeks.asp#ixzz2E1nWPEok

the Market and Products


· the Market
Exchange-traded Market
 - trade standardized contracts
Over the counter Market
 - trade customized contracts: market participants are free to negotiate any mutual attractive trade.

· the Products
Forward contracts 
- agreement to sell and buy an asset at a certain future time for a certain price 
- contrast to a spot contract - agreement to sell and buy today.

Future contracts

- agreement to sell and buy an asset at a certain future time for a certain price 


What is the difference between forward and futures contracts?


Differences Conclusion:

forward: OTC, settlement happens at the end of the contract, used by hedgers mostly -  delivery of the asset or cash settlement will usually take place.
future:  exchanged-traded, marked-to-market daily, used by speculators mostly- they are usually closed out prior to maturity and delivery usually never happens.


Fundamentally, forward and futures contracts have the same function: both types of contracts allow people to buy or sell a specific type of asset at a specific time at a given price.

However, it is in the specific details that these contracts differ. First of all, futures contracts are exchange-traded and, therefore, are standardized contracts. Forward contracts, on the other hand, are private agreements between two parties and are not as rigid in their stated terms and conditions. Because forward contracts are private agreements, there is always a chance that a party may default on its side of the agreement. Futures contracts have clearing houses that guarantee the transactions, which drastically lowers the probability of default to almost never.

Secondly, the specific details concerning settlement and delivery are quite distinct. For forward contracts, settlement of the contract occurs at the end of the contract. Futures contracts are marked-to-market daily, which means that daily changes are settled day by day until the end of the contract. Furthermore, settlement for futures contracts can occur over a range of dates. Forward contracts, on the other hand, only possess one settlement date.

Lastly, because futures contracts are quite frequently employed by speculators, who bet on the direction in which an asset's price will move, they are usually closed out prior to maturity and delivery usually never happens. On the other hand, forward contracts are mostly used by hedgers that want to eliminate the volatility of an asset's price, and delivery of the asset or cash settlement will usually take place.

Options
both on OTC and Exchange: but most of the options are traded in exchange in America.
America Option can be exercised at anytime up to the expiration date.
- Chicago Board Options Exchange

-call option: buy
- put option: sell


SWAP
-The most common type of swap is 'plain vanilla' interest rate swap.


Chapter 8 Option Market - mainly about stock options
Terminologies:
- call option, the right to buy - hoping the stock price is increase (stock price>strike price)
- put option, the right to sell - hoping the stock price is decrease  (stock price<strike price).
EX: Europe Option, on the maturity date, the current price of APPLE is $500, the strike price of Option is $550, then you can first buy the pertinent amount of stocks from market in $500/share and then exercise the Option by selling those stocks to the market maker in $550, earn $50/share. You can do early exercise in American Option Market.
- expiration date or maturity
- exercise price or strike price
- Four types of Positions
Customer bought options from Institutions
1. Long Position in a Call Option
2. Long Position in a Put Option
Institution sold options to Customers
3. Short Position in a Call Option
4. Short Position in a Put Option

Underling Assets of Option:
1. Stock Option 2. Foreign Currency Option 3.Index Option 4. Future Option

Offsetting Order 平仓
Commission 佣金


Definition of 'Naked Option'

A trading position where the seller of an option contract does not own any, or enough, of the underlying security to act as protection against adverse price movements. If the price of the underlying security moves against the trader, who does not already own the underlying security, he or she would be required to purchase the shares regardless of how high the price is. The potential for losses, then, can be unlimited, and as a result, brokers typically have specific rules regarding naked trading. Inexperienced traders, for example, would not be allowed to place this type of order.

LIBOR curve
The LIBOR curve and the Treasury yield curve are the most widely-used proxies for the risk-free interest rates. Although not theoretically risk-free, LIBOR is considered a good proxy against which to measure the risk/return tradeoff for other short-term floating rate instruments
.







Sunday, December 2, 2012

Learn Spring


Before starting spring I'd suggest you first go read about IoC and Dependency Injection. After that the best place to start is their reference manual here and spring by example website.
Martin Fowler's DI article is another good read.

Exception Handling

1. Exception thrown by a catch cannot be caught by the following catch blocks at the same level.
//catch{} can only catch those exceptions throw from try{}
public class TestClass{
   public static void main(String args[]){
      try{
         m1();
      }catch(IndexOutOfBoundsException e){
         System.out.println("1");
         throw new NullPointerException();
      }catch(NullPointerException e){
         System.out.println("2");
         return;
      }catch (Exception e) {
         System.out.println("3");
      }finally{
         System.out.println("4");
      }
      System.out.println("END");//catch block throw NullPointerException.

   }
   // IndexOutOfBoundsException is a subclass of RuntimeException.
   static void m1(){
      System.out.println("m1 Starts");
      throw new IndexOutOfBoundsException( "Big Bang " );
   }
}

2. You can apply a label to any code block or a block level statement (such as a for statement) but not to individual statement such as loop X : int i = 10;

      loop :         // 1
      {
         System.out.println("Loop Lable line");
               break loop;       // 2
      }

3. Either throws or catch{} is required if there was exception
class TestClass{
 public static void main(String args[]) throws Exception{
  try{
   m1();
   System.out.println("A");
  } //这里没有catch block 但是method throws Exception,所以没有compile error
  finally{
   System.out.println("B");
  }
  System.out.println("C");
 }
 public static void m1() throws Exception { throw new Exception(); }
}


Saturday, December 1, 2012

What is variable hiding and shadowing?


What is variable hiding and shadowing?

In Java, there are three kinds of variables: 
1. local variables, -- in methods
2. instance variables, -- not-static fields
3. class variables. -- static 

Variables have their scopes. Different kinds of variables have different scopes. A variable is shadowed if there is another variable with the same name that is closer in scope. In other words, referring to the variable by name will use the one closest in scope , the one in the outer scope is shadowed.

A Local Variable Shadows An Instance Variable

Inside a class method, when a local variable have the same name as one of the instance variable, the local variable shadows the instance variable inside the method block.
In the following example, there is a instance variable named "a", and inside the method setA() there is a local variable "a":
class Program {
  int  a;
  int  b;

  void setA(int a) {
    a = a; //here, the local variable has closer scope than the instance 
          // variable, so the expression set parameter equal to itself
    this.a = a; // this is the correct way to set the parameter to the 
           //instance variable.
  }

  void setB(int b) {
    this.b = b;
  }
}
Let's look at another example,
class Program {
   String name = "Instance Var."; 
   void someMethod() { 
     String name ="Local Var."; 
     System.out.println(name);   //Local Var.
     System.out.println(this.name); //Instance Var. 
   } 
}
Note: Instance variables are not overridden, they are hidden.

A Class Variable Shadows the Inherited Variable from Its Parent Classes 

When an instance variable in a subclass has the same name as an instance variable in a super class, then the instance variable is chosen in the class that is the reference type.
A class can declare a variable with the same name as an inherited variable from its parent class, thus "hiding" or shadowing the inherited version. (This is like overriding, but for variables.) For example,
public class Base {
    public  String name = "Base";
    public  String getName() { return name; }
}


public class Sub extends Base {
    public String name = "Sub";
    public String getName() { return name; }
}
The above shows two classes and Sub class is a subclass of Base class. Both of classes has a String type variable named name.
  • Use Case I
    class Program {
      public static void main(String[] args) {
        Sub s = new Sub();
        System.out.println(s.name); //Output "Sub"
      }
    }
    The above code directly accesses the name variable in the instance of Sub named s. This access, as one would expect, yields a value of "Sub".
  • Use Case II
    class Program {
      public static void main(String[] args) {
        Sub s  = new Sub();
        Base b = s;
        System.out.println(s.name); //Output "Sub"
        System.out.println(b.name); //Output "Base"
      }
    }
    In use case II, even though the variable b refers an instance of class Sub, the b.name still evaluates to "Base". Because variables names in Java are resolved by the reference type, not the object they are referencing.
    In this example, even though both b and s are referencing the object of type Sub, s is declared as type Sub, b is declared as type Base, Java runtime gets the s.name from the class of Sub, and b.name from the class of Base.

Access Supper Class Variables


When shadowing does happen, you can access the super class name by either the syntax super.name or by casting the object to its super class, with the syntax((Superclass)object).name.
Variables shadowed by Interface hierarchies are referenced the same way they are for class hierarchies. The following example shows the shadowing from interface hierarchies:
interface IBase {
  String name = "base";
}

interface ISub extends IBase {
  String name = "sub";
}

public class Shadow implements ISub {
  String name = "shadow";

  void print(Strig name)
  {
    System.out.println("method name = " + name);
    System.out.println("class name = " + this.name);
    System.out.println("IBase name = " + 
          ((IBase) this).name);
    System.out.println("ISub name = " + 
          ((ISub) this).name);
  }

  public static void main(String[] args) {
    (new Shadow()).print("parameter");
  }
}

The output of this program is: 

method name = parameter
name = shadow
IBase name = base
ISub name = sub
As you can see, it can be confusing when variable shadowing occurs. It's a good practice not to use the same variable names in the class or interface hierarchies.
There are exceptions. When the variable in the supper class has private access or is in another package and has default access, there is no room for confusion. The sub class cannot access such variables in its supper class.