Skip to main content

How i+=j works in Java?It will surprise you?

According to the specification of Java for mathematical operations , 
If the left-hand operand expression is not an array access expression, then:

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.

I thought that for example: i += j;
Was just a shortcut for: i = i + j;
But if we try this:
int i = 15; long j = 28;
Then i = i + j; will not compile but i += j; will compile fine. So the question is here:
Does it mean that i += j; is a shortcut for something like this i = (type of i) (i + j)?
After digging out into the Java Language Specification I find out that,
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
After that I also tried some other examples :
A good example of this casting is using *= or /=
byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'

References:
https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2

Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. It has been simply incredibly generous with you to provide openly what exactly many individuals wouldíve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.
    Java Training | best java training institute in chennai | java j2ee training in chennai |
    java training chennai | java classes in chennai | java course in chennai | java training with placement in chennai| best java training center in chennai |
    java coaching classes in chennai

    ReplyDelete
  3. Casino Tycoon 3D | Mapyro
    Get directions, reviews and information for Casino Tycoon 3D in Greater Phoenix. 양산 출장마사지 Download the free 세종특별자치 출장마사지 app & get 전라남도 출장안마 directions directly to your location. 2nd 오산 출장샵 Floor. 창원 출장마사지 Casino Tycoon 3D

    ReplyDelete

Post a Comment

Top 5 Most Read Posts

Who is Peter Lynch and what is his philosophy in equity market investment? 25 Golden Rules of the most successful Fund Manager.

Peter Lynch (born January 19, 1944) is an American investor, mutual fund manager, and philanthropist. As the manager of the Magellan Fund at Fidelity Investments between 1977 and 1990, Lynch averaged a 29.2% annual return, consistently more than doubling the S&P 500 stock market index and making it the best-performing mutual fund in the world. During his 13 year tenure, assets under management increased from $18 million to $14 billion. He also co-authored a number of books and papers on investing and coined a number of well known mantras of modern individual investing strategies, such as Invest in what you know and ten bagger. Lynch is consistently described as a "legend" by the financial media for his performance record. Base on his career I have compiled his investing rules here. 25 GOLDEN RULES by @Peter Lynch 1: Nobody can predict interest rates, the future direction of the economy or the stock market. Dismiss all such forecasts & concentrate on what's actual

What is version checking in Hibernate ?

Version checking used in hibernate when more then one thread trying to access same data. For example : User A edit the row of the TABLE for update ( In the User Interface changing data This is user thinking time) and in the same time User B edit the same record for update and click the update. Then User A click the Update and update done. Change made by user B is gone. In hibernate you can prevent slate object updation using version checking. Check the version of the row when you are updating the row. Get the version of the row when you are fetching the row of the TABLE for update. On the time of updation just fetch the version number and match with your version number (on the time of fetching).

What is wrong with HDFC securities? Are they doing some fraudulent activities or just causing issues with their platform as usually it don't work during market hours?

I have opened a DEMAT account with HDFC Securities in 2019 as HDFC group is well known for the customer services and I also hold a salary account with HDFC Bank, DEMAT account with the following conditions/offers as expressed by the executive. Trading Account Opening Charges (One Time) :  ₹999 (At that time it offered on lower price, I forget the exact price) Trading Annual Maintenance Charges AMC (Yearly Fee) : ₹0 Demat Account Opening Charges (One Time) : ₹0 Demat Account Annual Maintenance Charges AMC (Yearly Fee) : ₹750, nil if portfolio value below ₹2 lacs. Equity Delivery : 0.50% Equity Intraday : 0.05% Equity Futures : 0.05% Equity Options : ₹100 per lot or 1% of the premium (whichever is higher) Currency Futures : ₹23 per contract Currency Options : ₹20 per contract Commodity Futures : 0.02% for Intraday / 0.025% for positional Commodity Options : 0.02% for Intraday / 0.025% for positional It was going good but after 2-3 months I got to know that there are som

Fundamental Analysis : Asian Paints Ltd.

Asian Paints group is the largest paint manufacturer in India also engaged in the business of manufacturing of varnishes, enamels or lacquers, surfacing preparation, organic composite solvents and thinners. It operates in 15 countries and has 26 paint manufacturing facilities in the world serving consumers in over 60 countries. Besides Asian Paints, the group operates around the world through its various brands viz. Asian Paints Berger, Apco Coatings, SCIB Paints, Taubmans, Causeway Paints and Kadisco Asian Paints. It also manufactures metal sanitary ware such as bath, sinks, washbasins and similar articles. Recently introduced Lightings, Furnishings and Furniture thus adding more products in the Home décor and Interior Design category. Market Cap ₹ 244,763 Cr. Current Price ₹ 2,552 High / Low ₹ 2,873 / 1,483 Stock P/E 89.0 Book Value ₹ 115 Dividend Yield 0.47 % ROCE 33.8 % ROE 27.5 % Face Value ₹ 1.00 Price to book value 22.2 EPS ₹ 28.7 High price all time ₹ 2,873 Low price all time ₹

What are JEE Containers? What are their different types?

Containers are the interface between a component and the low-level, platform-specific functionality that supports the component. Before it can be executed, a web, enterprise bean, or application client component must be assembled into a Java EE module and deployed into its container. The assembly process involves specifying container settings for each component in the Java EE application and for the Java EE application itself. Container settings customize the underlying support provided by the Java EE server, including such services as security, transaction management, Java Naming and Directory Interface (JNDI) API lookups, and remote connectivity. Here are some of the highlights. The Java EE security model lets you configure a web component or enterprise bean so that system resources are accessed only by authorized users. The Java EE transaction model lets you specify relationships among methods that make up a single transaction so that all methods in one transaction are treated as a