SlideShare una empresa de Scribd logo
1 de 1
Descargar para leer sin conexión
The Joy of
Programming                                                                                                           S.G. GaneSh


Traps and Pitfalls: Swapping Two Variables— Part IV
Last month, we covered an interesting issue in swapping variables without a temporary in a single
statement and saw that the trick does not work in Java. This month, we’ll look at what happens
behind the scenes in the JVM by analysing the byte codes generated for the statement.



L
        ast month, we introduced a problem in Java: given       instruction duplicates the value in the top of the stack.
        two integers i and j, the following statement does          Now, let us simulate the execution of instructions. On
        not swap the values of two variables correctly i ^=     top is the execution stack and its state; at the bottom is
(j ^= (i ^= j)).                                                the value for memory locations i and j, and is indicated by
    To understand what is happening, let us analyse the         ‘_1’ and ‘_2’.
byte code generated for this statement. How do we get               Assume that the initial values of i and j are 3 and 6
the byte codes? By using the javap tool on the generated        and hence _1 and _2 have the values 3 and 6, respectively,
class file, which will be available in the same directory as    stored in them.
javac (in the bin directory). javap is a Java dis-assembler
tool that reads the Java class files and dumps the info in        1) Init       2) after      3) after      4) ixor        5) dup
a human-readable form. First issue the command, javac              state       executing     executing
                                                                               iload_1 &     iload_1 &
Swap.java and then javap -c Swap; you’ll get the detailed                        iload_2       iload_2
output with byte codes.
    From this output, here is the sequence of byte codes                                         6                            5
generated for the statement i ^= (j ^= (i ^= j)):                                                3             5              5
                                                                                   6             6             6              6
    39:   iload_1                                                                  3             3             3              3
    40:   iload_2                                                 3     6       3     6       3     6       3     6        3     6
                                                                i(_1) j(_2)   i(_1) j(_2)   i(_1) j(_2)   i(_1) j(_2)    i(_1) j(_2)
    41:   iload_1
    42:   iload_2
    43:   ixor                                                  6) istore_1    7) after     8) istore_2     9) ixor     10) istore_1
                                                                              ixor & dup
    44:   dup
    45:   istore_1
    46:   ixor                                                       5             3
                                                                     6             3             3
    47:   dup                                                        3             3             3             0
    48:   istore_2                                                5     6       5     6       5     3       5     3        0     3
    49:   ixor                                                  i(_1) j(_2)   i(_1) j(_2)   i(_1) j(_2)   i(_1) j(_2)    i(_1) j(_2)
    50:   istore_1
    Here is a quick intro on byte codes. The intermediate           As you can see, for the initial values of 3 and 6 for i
language for Java is byte codes. These are assembly             and j, after execution of the instructions, the final values
language codes for an imaginary stack-based machine             are 0 and 3, respectively. I hope that it is now clear how
(that is the reason why the Java runtime is called a ‘virtual   the Java compiler translated the statement i ^= (j ^=
machine’). The size of an instruction is one byte, and hence    (i ^= j)); and why the values of i and j are not swapped
the name ‘byte code’.                                           correctly (which is according to the Java specifications).
    There are only a few instructions that we need to           Now, you can try the same process for the three
understand to interpret how this instruction sequence           consecutive statements i ^= j; j ^= i; and i ^= j. You’ll
works. The instruction prefixed with i—as in iload              realise that the compiler emits a different sequence
and istore—indicates that the instruction is meant              of byte codes. You can also verify that this instruction
for integers (remember that i and j are integers). The          sequence swaps the values of i and j correctly!
instructions iload and istore load and store an integer to
and from the ‘runtime execution stack’ and ‘local memory         S.G. Ganesh is a research engineer at Siemens (Corporate
area in the stack’. Here the suffix _1 and _2 indicates          Technology), Bangalore. His latest book is “60 Tips on
the first two local variables i and j. The instruction ixor      Object Oriented Programming” (ISBN 978-0-07-065670-3),
                                                                 published by Tata McGraw-Hill, New Delhi. You can reach
pops the values twice from the stack and X-ORs the
                                                                 him at sgganesh@gmail.com
result and pushes the result back into the stack. The dup


 12    juLY 2008     |   LINuX For You   |   www.openITis.com

Más contenido relacionado

Destacado

Saint patrick's day
Saint patrick's daySaint patrick's day
Saint patrick's day
Rafaarabit33
 
Beyoncé Knowles
Beyoncé  KnowlesBeyoncé  Knowles
Beyoncé Knowles
mariemal
 
42 Ang N3 Injuries
42 Ang N3 Injuries42 Ang N3 Injuries
42 Ang N3 Injuries
guestad292d
 

Destacado (6)

“World Youth Report 2003”: Chapter One: Youth and Education
“World Youth Report 2003”: Chapter One: Youth and Education“World Youth Report 2003”: Chapter One: Youth and Education
“World Youth Report 2003”: Chapter One: Youth and Education
 
Saint patrick's day
Saint patrick's daySaint patrick's day
Saint patrick's day
 
Beyoncé Knowles
Beyoncé  KnowlesBeyoncé  Knowles
Beyoncé Knowles
 
42 Ang N3 Injuries
42 Ang N3 Injuries42 Ang N3 Injuries
42 Ang N3 Injuries
 
Commission for Social Development, 45th Session Resolution on Youth 45/2 incl...
Commission for Social Development, 45th Session Resolution on Youth 45/2 incl...Commission for Social Development, 45th Session Resolution on Youth 45/2 incl...
Commission for Social Development, 45th Session Resolution on Youth 45/2 incl...
 
Basic orientation to Linux
Basic orientation to LinuxBasic orientation to Linux
Basic orientation to Linux
 

Similar a 19 Jo P July 08

Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012
Coen De Roover
 
Clojureによるバイトコードプログラミング
ClojureによるバイトコードプログラミングClojureによるバイトコードプログラミング
Clojureによるバイトコードプログラミング
sohta
 
computer notes - Evaluating postfix expressions
computer notes - Evaluating postfix expressionscomputer notes - Evaluating postfix expressions
computer notes - Evaluating postfix expressions
ecomputernotes
 
Markov model analyzing its behavior for uncertainty conditions
Markov model  analyzing its behavior for uncertainty conditionsMarkov model  analyzing its behavior for uncertainty conditions
Markov model analyzing its behavior for uncertainty conditions
Alexander Decker
 

Similar a 19 Jo P July 08 (20)

How Scala code is expressed in the JVM
How Scala code is expressed in the JVMHow Scala code is expressed in the JVM
How Scala code is expressed in the JVM
 
18 Jo P June 08
18 Jo P June 0818 Jo P June 08
18 Jo P June 08
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia
 
20171127 當julia遇上資料科學
20171127 當julia遇上資料科學20171127 當julia遇上資料科學
20171127 當julia遇上資料科學
 
L1 Sudoku
L1 SudokuL1 Sudoku
L1 Sudoku
 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia
 
Core java msc
Core java mscCore java msc
Core java msc
 
CAP615-Unit1.pptx
CAP615-Unit1.pptxCAP615-Unit1.pptx
CAP615-Unit1.pptx
 
Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012
 
Clojureによるバイトコードプログラミング
ClojureによるバイトコードプログラミングClojureによるバイトコードプログラミング
Clojureによるバイトコードプログラミング
 
Scilab vs matlab
Scilab vs matlabScilab vs matlab
Scilab vs matlab
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developers
 
Explanations to the article on Copy-Paste
Explanations to the article on Copy-PasteExplanations to the article on Copy-Paste
Explanations to the article on Copy-Paste
 
Clojure made really really simple
Clojure made really really simpleClojure made really really simple
Clojure made really really simple
 
computer notes - Evaluating postfix expressions
computer notes - Evaluating postfix expressionscomputer notes - Evaluating postfix expressions
computer notes - Evaluating postfix expressions
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Sdtl manual
Sdtl manualSdtl manual
Sdtl manual
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
Markov model analyzing its behavior for uncertainty conditions
Markov model  analyzing its behavior for uncertainty conditionsMarkov model  analyzing its behavior for uncertainty conditions
Markov model analyzing its behavior for uncertainty conditions
 
Clojure made simple - Lightning talk
Clojure made simple - Lightning talkClojure made simple - Lightning talk
Clojure made simple - Lightning talk
 

Más de Ganesh Samarthyam

Más de Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

19 Jo P July 08

  • 1. The Joy of Programming S.G. GaneSh Traps and Pitfalls: Swapping Two Variables— Part IV Last month, we covered an interesting issue in swapping variables without a temporary in a single statement and saw that the trick does not work in Java. This month, we’ll look at what happens behind the scenes in the JVM by analysing the byte codes generated for the statement. L ast month, we introduced a problem in Java: given instruction duplicates the value in the top of the stack. two integers i and j, the following statement does Now, let us simulate the execution of instructions. On not swap the values of two variables correctly i ^= top is the execution stack and its state; at the bottom is (j ^= (i ^= j)). the value for memory locations i and j, and is indicated by To understand what is happening, let us analyse the ‘_1’ and ‘_2’. byte code generated for this statement. How do we get Assume that the initial values of i and j are 3 and 6 the byte codes? By using the javap tool on the generated and hence _1 and _2 have the values 3 and 6, respectively, class file, which will be available in the same directory as stored in them. javac (in the bin directory). javap is a Java dis-assembler tool that reads the Java class files and dumps the info in 1) Init 2) after 3) after 4) ixor 5) dup a human-readable form. First issue the command, javac state executing executing iload_1 & iload_1 & Swap.java and then javap -c Swap; you’ll get the detailed iload_2 iload_2 output with byte codes. From this output, here is the sequence of byte codes 6 5 generated for the statement i ^= (j ^= (i ^= j)): 3 5 5 6 6 6 6 39: iload_1 3 3 3 3 40: iload_2 3 6 3 6 3 6 3 6 3 6 i(_1) j(_2) i(_1) j(_2) i(_1) j(_2) i(_1) j(_2) i(_1) j(_2) 41: iload_1 42: iload_2 43: ixor 6) istore_1 7) after 8) istore_2 9) ixor 10) istore_1 ixor & dup 44: dup 45: istore_1 46: ixor 5 3 6 3 3 47: dup 3 3 3 0 48: istore_2 5 6 5 6 5 3 5 3 0 3 49: ixor i(_1) j(_2) i(_1) j(_2) i(_1) j(_2) i(_1) j(_2) i(_1) j(_2) 50: istore_1 Here is a quick intro on byte codes. The intermediate As you can see, for the initial values of 3 and 6 for i language for Java is byte codes. These are assembly and j, after execution of the instructions, the final values language codes for an imaginary stack-based machine are 0 and 3, respectively. I hope that it is now clear how (that is the reason why the Java runtime is called a ‘virtual the Java compiler translated the statement i ^= (j ^= machine’). The size of an instruction is one byte, and hence (i ^= j)); and why the values of i and j are not swapped the name ‘byte code’. correctly (which is according to the Java specifications). There are only a few instructions that we need to Now, you can try the same process for the three understand to interpret how this instruction sequence consecutive statements i ^= j; j ^= i; and i ^= j. You’ll works. The instruction prefixed with i—as in iload realise that the compiler emits a different sequence and istore—indicates that the instruction is meant of byte codes. You can also verify that this instruction for integers (remember that i and j are integers). The sequence swaps the values of i and j correctly! instructions iload and istore load and store an integer to and from the ‘runtime execution stack’ and ‘local memory S.G. Ganesh is a research engineer at Siemens (Corporate area in the stack’. Here the suffix _1 and _2 indicates Technology), Bangalore. His latest book is “60 Tips on the first two local variables i and j. The instruction ixor Object Oriented Programming” (ISBN 978-0-07-065670-3), published by Tata McGraw-Hill, New Delhi. You can reach pops the values twice from the stack and X-ORs the him at sgganesh@gmail.com result and pushes the result back into the stack. The dup 12 juLY 2008 | LINuX For You | www.openITis.com