SlideShare ist ein Scribd-Unternehmen logo
1 von 1
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Andere mochten auch (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
 

Ähnlich wie Traps and Pitfalls: Understanding Byte Codes for Variable Swapping - Part IV

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 JVMKoichi Sakata
 
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 Sudokubnmoran
 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia岳華 杜
 
Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Coen De Roover
 
Clojureによるバイトコードプログラミング
ClojureによるバイトコードプログラミングClojureによるバイトコードプログラミング
Clojureによるバイトコードプログラミングsohta
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developersbrweber2
 
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-PastePVS-Studio
 
Clojure made really really simple
Clojure made really really simpleClojure made really really simple
Clojure made really really simpleJohn Stevenson
 
computer notes - Evaluating postfix expressions
computer notes - Evaluating postfix expressionscomputer notes - Evaluating postfix expressions
computer notes - Evaluating postfix expressionsecomputernotes
 
Sdtl manual
Sdtl manualSdtl manual
Sdtl manualqaz8989
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanWei-Yuan Chang
 
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 conditionsAlexander Decker
 
Clojure made simple - Lightning talk
Clojure made simple - Lightning talkClojure made simple - Lightning talk
Clojure made simple - Lightning talkJohn Stevenson
 

Ähnlich wie Traps and Pitfalls: Understanding Byte Codes for Variable Swapping - Part IV (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
 

Mehr von Ganesh Samarthyam

Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeGanesh Samarthyam
 
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”Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGanesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeGanesh Samarthyam
 
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 ExamplesGanesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationGanesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterGanesh Samarthyam
 
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)Ganesh Samarthyam
 
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++ Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckGanesh Samarthyam
 
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 LanguageGanesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz QuestionsGanesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz QuestionsGanesh Samarthyam
 
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 quizGanesh Samarthyam
 

Mehr von 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
 

Kürzlich hochgeladen

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 

Kürzlich hochgeladen (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 

Traps and Pitfalls: Understanding Byte Codes for Variable Swapping - Part IV

  • 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