ๅฐŠๆ•ฌ็š„ ๅพฎไฟกๆฑ‡็Ž‡๏ผš1ๅ†† โ‰ˆ 0.046166 ๅ…ƒ ๆ”ฏไป˜ๅฎๆฑ‡็Ž‡๏ผš1ๅ†† โ‰ˆ 0.046257ๅ…ƒ [้€€ๅ‡บ็™ปๅฝ•]
SlideShare a Scribd company logo
Lecture 13
Iteration in Java




           Object Oriented Programming
            Eastern University, Dhaka
                    Md. Raihan Kibria
Simple c-style iteration

public class IterationDemo {

    public static void main(String[] args) {
      List<String>lst = new ArrayList<String>();
      lst.add("One");
      lst.add("Two");
      lst.add("Three");

        for (int i=0; i<lst.size(); i++)
            System.out.println(lst.get(i));

    }
}




        Output:
        One
        Two
        Three
More iterators
 //more eye-friendly iteration
 for (String s : lst)
   System.out.println(s);


 Gives the same output


Most generic iterationโ€”using Iterator
 Iterator<String>it = lst.iterator();
 while (it.hasNext())
   System.out.println(it.next());

 Gives the same output
Iterating over a set
Set<String>s = new HashSet<String>();
s.add("One");
s.add("Two");
s.add("Three");

Iterator<String>it = lst.iterator();
while (it.hasNext())
  System.out.println(it.next());

Gives the same output:
One
Two
Three
Iterating over a map
Map<String, String>map = new HashMap<String, String>();
map.put("One", "111111");
map.put("Two", "222222");
map.put("Three", "333333");

Iterator<Map.Entry<String, String>>it = map.entrySet().iterator();
while (it.hasNext()){
  Map.Entry<String, String>entry = it.next();
  System.out.println(entry.getKey() + "--" + entry.getValue());
}




            Output:

            Three--333333
            One--111111
            Two--222222
Remember old style iteration still
       works for arrays
 String[] str = new String[]{"One", "Two", "Three"};
 for (int i=0; i<str.length; i++)
   System.out.println(str[i]);

     Output:
     One
     Two
     Three



String[] str = new String[]{"One", "Two", "Three"};

for (String s : str)
  System.out.println(s);
       Output:
       One
       Two
       Three
Some common methods present in
         all objects
toString()
equals()
hashCode()
finalize()
toString()
public class Student {
  int id;
  String name;

     public Student(int id, String name) {
       super();
       this.id = id;
       this.name = name;
     }

     public String toString(){
       return this.id + "--" + this.name;
 }
}


public static void main(String[] args){
    Student student = new Student(3, "Joe");
    System.out.println(student);
}

Output:
3--Joe
Another toString() demo
List<Student>stus = new ArrayList<Student>();
Student st = new Student(1, "John");
stus.add(st);
stus.add(st);
System.out.println("Printing list: ");
for (Student s: stus)
    System.out.println(s);


     Output:

     Printing list:
     1--John
     1--John
hashCode() demo with equals()
public class HashCodeDemo {

    public static class Student {
      int id;
      String name;

    public Student(int id, String name) {
      super();
      this.id = id;
      this.name = name;
    }

    public String toString() {
      return this.id + "--" + this.name;
    }

     /*      public boolean equals(Object obj) {
     Student arg = (Student) obj;
     return this.id == arg.id;
     }*/

    public int hashCode() {
      return this.id;
    }
}
public static void main(String[] args) {
      Map<Student, String> map = new HashMap<Student, String>();
      map.put(new Student(1, "John"), null);
      map.put(new Student(1, "John"), null);
      map.put(new Student(2, "John"), null);
      System.out.println(map.size());

      Iterator<Map.Entry<Student, String>> it1 = map.entrySet().iterator();
      System.out.println("Printing map: ");
      while (it1.hasNext())
        System.out.println(it1.next());
      }
}



    Output:                 Now we uncomment the equals() method in the
    3                       previous slide:
    Printing map:
    1--John=null            Output:
    1--John=null            2
    2--John=null            Printing map:
                            1--John=null
                            2--John=null

      Explanation: hashCode merely specifies a slot;
      equals() helps put the object in the slot
equals() method
๏ต Two objects are equal if their equals() method returns
  true. Demo:
public class Student {
    int id;
    String name;

    public Student(int id, String name) {
      super();
      this.id = id;
      this.name = name;
    }

    public String toString(){
      return this.id + "--" + this.name;
    }

    public int hashCode() {
      return this.id;
    }

    public boolean equals(Object obj) {
      Student s = (Student)obj;
      if (s.id == this.id)
          return true;
      return false;
    }
equals() continued
 System.out.println(st.equals(st2));
 System.out.println(st==st2);




Output:

true
false




In java โ€œ==โ€ operator is not same as โ€œequals()โ€
finalize()
๏ต   What is garbage collection?
๏ต   In C/C++ the programmer can get a chunk
    of program using malloc() and can dispose
    memory using memfree()
๏ต   Having programmer free will at memory
    management resulted in memory leaks in
    many C programs
๏ต   Java will not let programmer directly
    acquiring memory.
๏ต   Rather JVM manages memory
Finalize() (c..)
โ€ข
    When an object is de-referenced, the object
    is automatically removed from the memory
    by JVM.
โ€ข
    Whenever, an object is removed its finalize()
    method is called
โ€ข
    Garbage collection is automatically
    scheduled by the JVM
โ€ข
    However, a programmer can trigger a
    garbage collection by calling System.gc()
โ€ข
    Example in the next page:
Finalize() (c..)
public class AnObject {

    protected void finalize() throws Throwable {
      super.finalize();
      System.out.println("Finalize method is called");
    }

    public static void main(String[] args){
      new AnObject();
    }
}


    Output:
Finalize() (c..)
public class AnObject {

    protected void finalize() throws Throwable {
      super.finalize();
      System.out.println("Finalize method is called");
    }

    public static void main(String[] args){
      new AnObject();
      System.gc();
    }
}




Output:
Finalize method is called
Garbage collection formally
             defined
Garbage collection is a mechanism provided
 by Java Virtual Machine to reclaim heap
 space from objects which are eligible for
 Garbage collection

More Related Content

What's hot

Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
Manusha Dilan
ย 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
Mike Anderson
ย 
Java practical
Java practicalJava practical
Java practical
shweta-sharma99
ย 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
Soumya Behera
ย 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88
Mahmoud Samir Fayed
ย 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
henrygarner
ย 
Clojure class
Clojure classClojure class
Clojure class
Aysylu Greenberg
ย 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
Namgee Lee
ย 
JDBC Core Concept
JDBC Core ConceptJDBC Core Concept
JDBC Core Concept
Rays Technologies
ย 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
Aleksandar Veselinovic
ย 
Machine Learning Live
Machine Learning LiveMachine Learning Live
Machine Learning Live
Mike Anderson
ย 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
stasimus
ย 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
Dr. Volkan OBAN
ย 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
Dmitry Buzdin
ย 
Javascript
JavascriptJavascript
Javascript
Vlad Ifrim
ย 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
Mario Fusco
ย 
Futures e abstraรงรฃo - QCon Sรฃo Paulo 2015
Futures e abstraรงรฃo - QCon Sรฃo Paulo 2015Futures e abstraรงรฃo - QCon Sรฃo Paulo 2015
Futures e abstraรงรฃo - QCon Sรฃo Paulo 2015
Leonardo Borges
ย 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
Karlijn Willems
ย 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia
ๅฒณ่ฏ ๆœ
ย 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
Baishampayan Ghose
ย 

What's hot (20)

Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
ย 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
ย 
Java practical
Java practicalJava practical
Java practical
ย 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
ย 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88
ย 
Clojure for Data Science
Clojure for Data ScienceClojure for Data Science
Clojure for Data Science
ย 
Clojure class
Clojure classClojure class
Clojure class
ย 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
ย 
JDBC Core Concept
JDBC Core ConceptJDBC Core Concept
JDBC Core Concept
ย 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
ย 
Machine Learning Live
Machine Learning LiveMachine Learning Live
Machine Learning Live
ย 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
ย 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
ย 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
ย 
Javascript
JavascriptJavascript
Javascript
ย 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
ย 
Futures e abstraรงรฃo - QCon Sรฃo Paulo 2015
Futures e abstraรงรฃo - QCon Sรฃo Paulo 2015Futures e abstraรงรฃo - QCon Sรฃo Paulo 2015
Futures e abstraรงรฃo - QCon Sรฃo Paulo 2015
ย 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
ย 
COSCUP: Introduction to Julia
COSCUP: Introduction to JuliaCOSCUP: Introduction to Julia
COSCUP: Introduction to Julia
ย 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
ย 

Viewers also liked

Calendario portada
Calendario portadaCalendario portada
Calendario portada
Isabel Jb
ย 
Oop lecture6
Oop lecture6Oop lecture6
Oop lecture6
Shahriar Robbani
ย 
Oop lecture1
Oop lecture1Oop lecture1
Oop lecture1
Shahriar Robbani
ย 
Cwgd
CwgdCwgd
Cwgd
cwgday
ย 
Oop lecture2
Oop lecture2Oop lecture2
Oop lecture2
Shahriar Robbani
ย 
Oop lecture8
Oop lecture8Oop lecture8
Oop lecture8
Shahriar Robbani
ย 
Oop lecture9 12
Oop lecture9 12Oop lecture9 12
Oop lecture9 12
Shahriar Robbani
ย 
Presentacion viernes 20 [compatibility mode]
Presentacion viernes 20 [compatibility mode]Presentacion viernes 20 [compatibility mode]
Presentacion viernes 20 [compatibility mode]
edyarr
ย 
Oop lecture9 11
Oop lecture9 11Oop lecture9 11
Oop lecture9 11
Shahriar Robbani
ย 

Viewers also liked (9)

Calendario portada
Calendario portadaCalendario portada
Calendario portada
ย 
Oop lecture6
Oop lecture6Oop lecture6
Oop lecture6
ย 
Oop lecture1
Oop lecture1Oop lecture1
Oop lecture1
ย 
Cwgd
CwgdCwgd
Cwgd
ย 
Oop lecture2
Oop lecture2Oop lecture2
Oop lecture2
ย 
Oop lecture8
Oop lecture8Oop lecture8
Oop lecture8
ย 
Oop lecture9 12
Oop lecture9 12Oop lecture9 12
Oop lecture9 12
ย 
Presentacion viernes 20 [compatibility mode]
Presentacion viernes 20 [compatibility mode]Presentacion viernes 20 [compatibility mode]
Presentacion viernes 20 [compatibility mode]
ย 
Oop lecture9 11
Oop lecture9 11Oop lecture9 11
Oop lecture9 11
ย 

Similar to Oop lecture9 13

Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
Logan Chien
ย 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
ShashikantSathe3
ย 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
ย 
Utility.ppt
Utility.pptUtility.ppt
Utility.ppt
BruceLee275640
ย 
Java file
Java fileJava file
Java file
simarsimmygrewal
ย 
Java file
Java fileJava file
Java file
simarsimmygrewal
ย 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
VictorSzoltysek
ย 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
Niraj Bharambe
ย 
Groovy puzzlers ะฟะพ ั€ัƒััะบะธ ั Joker 2014
Groovy puzzlers ะฟะพ ั€ัƒััะบะธ ั Joker 2014Groovy puzzlers ะฟะพ ั€ัƒััะบะธ ั Joker 2014
Groovy puzzlers ะฟะพ ั€ัƒััะบะธ ั Joker 2014
Baruch Sadogursky
ย 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
ย 
Java programs
Java programsJava programs
Java programs
Mukund Gandrakota
ย 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
jagriti srivastava
ย 
Java programs
Java programsJava programs
Java programs
Dr.M.Karthika parthasarathy
ย 
Write a program that reads a graph from a file and determines whether.docx
 Write a program that reads a graph from a file and determines whether.docx Write a program that reads a graph from a file and determines whether.docx
Write a program that reads a graph from a file and determines whether.docx
ajoy21
ย 
Java programs
Java programsJava programs
Java programs
jojeph
ย 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
Simone Federici
ย 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
Codecamp Romania
ย 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
ย 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
ย 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
ย 

Similar to Oop lecture9 13 (20)

Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
ย 
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdfLECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
ย 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
ย 
Utility.ppt
Utility.pptUtility.ppt
Utility.ppt
ย 
Java file
Java fileJava file
Java file
ย 
Java file
Java fileJava file
Java file
ย 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
ย 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
ย 
Groovy puzzlers ะฟะพ ั€ัƒััะบะธ ั Joker 2014
Groovy puzzlers ะฟะพ ั€ัƒััะบะธ ั Joker 2014Groovy puzzlers ะฟะพ ั€ัƒััะบะธ ั Joker 2014
Groovy puzzlers ะฟะพ ั€ัƒััะบะธ ั Joker 2014
ย 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
ย 
Java programs
Java programsJava programs
Java programs
ย 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
ย 
Java programs
Java programsJava programs
Java programs
ย 
Write a program that reads a graph from a file and determines whether.docx
 Write a program that reads a graph from a file and determines whether.docx Write a program that reads a graph from a file and determines whether.docx
Write a program that reads a graph from a file and determines whether.docx
ย 
Java programs
Java programsJava programs
Java programs
ย 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
ย 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
ย 
Lezione03
Lezione03Lezione03
Lezione03
ย 
Lezione03
Lezione03Lezione03
Lezione03
ย 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
ย 

More from Shahriar Robbani

Group111
Group111Group111
Group111
Shahriar Robbani
ย 
SQL
SQLSQL
Oop lecture9 10
Oop lecture9 10Oop lecture9 10
Oop lecture9 10
Shahriar Robbani
ย 
Oop lecture4
Oop lecture4Oop lecture4
Oop lecture4
Shahriar Robbani
ย 
Oop lecture9
Oop lecture9Oop lecture9
Oop lecture9
Shahriar Robbani
ย 
Oop lecture7
Oop lecture7Oop lecture7
Oop lecture7
Shahriar Robbani
ย 
Oop lecture5
Oop lecture5Oop lecture5
Oop lecture5
Shahriar Robbani
ย 
Oop lecture3
Oop lecture3Oop lecture3
Oop lecture3
Shahriar Robbani
ย 

More from Shahriar Robbani (8)

Group111
Group111Group111
Group111
ย 
SQL
SQLSQL
SQL
ย 
Oop lecture9 10
Oop lecture9 10Oop lecture9 10
Oop lecture9 10
ย 
Oop lecture4
Oop lecture4Oop lecture4
Oop lecture4
ย 
Oop lecture9
Oop lecture9Oop lecture9
Oop lecture9
ย 
Oop lecture7
Oop lecture7Oop lecture7
Oop lecture7
ย 
Oop lecture5
Oop lecture5Oop lecture5
Oop lecture5
ย 
Oop lecture3
Oop lecture3Oop lecture3
Oop lecture3
ย 

Recently uploaded

A Quiz on Drug Abuse Awareness by Quizzito
A Quiz on Drug Abuse Awareness by QuizzitoA Quiz on Drug Abuse Awareness by Quizzito
A Quiz on Drug Abuse Awareness by Quizzito
Quizzito The Quiz Society of Gargi College
ย 
IoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdfIoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdf
roshanranjit222
ย 
Talking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual AidsTalking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual Aids
MattVassar1
ย 
Accounting for Restricted Grants When and How To Record Properly
Accounting for Restricted Grants  When and How To Record ProperlyAccounting for Restricted Grants  When and How To Record Properly
Accounting for Restricted Grants When and How To Record Properly
TechSoup
ย 
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT KanpurDiversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Quiz Club IIT Kanpur
ย 
The Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptxThe Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptx
PriyaKumari928991
ย 
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
ShwetaGawande8
ย 
Creating Images and Videos through AI.pptx
Creating Images and Videos through AI.pptxCreating Images and Videos through AI.pptx
Creating Images and Videos through AI.pptx
Forum of Blended Learning
ย 
Erasmus + DISSEMINATION ACTIVITIES Croatia
Erasmus + DISSEMINATION ACTIVITIES CroatiaErasmus + DISSEMINATION ACTIVITIES Croatia
Erasmus + DISSEMINATION ACTIVITIES Croatia
whatchangedhowreflec
ย 
Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024
khabri85
ย 
How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17
Celine George
ย 
How to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRMHow to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRM
Celine George
ย 
What are the new features in the Fleet Odoo 17
What are the new features in the Fleet Odoo 17What are the new features in the Fleet Odoo 17
What are the new features in the Fleet Odoo 17
Celine George
ย 
(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"
MJDuyan
ย 
Bแป˜ Bร€I TแบฌP TEST THEO UNIT - FORM 2025 - TIแบพNG ANH 12 GLOBAL SUCCESS - KรŒ 1 (B...
Bแป˜ Bร€I TแบฌP TEST THEO UNIT - FORM 2025 - TIแบพNG ANH 12 GLOBAL SUCCESS - KรŒ 1 (B...Bแป˜ Bร€I TแบฌP TEST THEO UNIT - FORM 2025 - TIแบพNG ANH 12 GLOBAL SUCCESS - KรŒ 1 (B...
Bแป˜ Bร€I TแบฌP TEST THEO UNIT - FORM 2025 - TIแบพNG ANH 12 GLOBAL SUCCESS - KรŒ 1 (B...
Nguyen Thanh Tu Collection
ย 
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptxScience-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Catherine Dela Cruz
ย 
Post init hook in the odoo 17 ERP Module
Post init hook in the  odoo 17 ERP ModulePost init hook in the  odoo 17 ERP Module
Post init hook in the odoo 17 ERP Module
Celine George
ย 
The Science of Learning: implications for modern teaching
The Science of Learning: implications for modern teachingThe Science of Learning: implications for modern teaching
The Science of Learning: implications for modern teaching
Derek Wenmoth
ย 
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
220711130100 udita Chakraborty  Aims and objectives of national policy on inf...220711130100 udita Chakraborty  Aims and objectives of national policy on inf...
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
Kalna College
ย 
Information and Communication Technology in Education
Information and Communication Technology in EducationInformation and Communication Technology in Education
Information and Communication Technology in Education
MJDuyan
ย 

Recently uploaded (20)

A Quiz on Drug Abuse Awareness by Quizzito
A Quiz on Drug Abuse Awareness by QuizzitoA Quiz on Drug Abuse Awareness by Quizzito
A Quiz on Drug Abuse Awareness by Quizzito
ย 
IoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdfIoT (Internet of Things) introduction Notes.pdf
IoT (Internet of Things) introduction Notes.pdf
ย 
Talking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual AidsTalking Tech through Compelling Visual Aids
Talking Tech through Compelling Visual Aids
ย 
Accounting for Restricted Grants When and How To Record Properly
Accounting for Restricted Grants  When and How To Record ProperlyAccounting for Restricted Grants  When and How To Record Properly
Accounting for Restricted Grants When and How To Record Properly
ย 
Diversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT KanpurDiversity Quiz Finals by Quiz Club, IIT Kanpur
Diversity Quiz Finals by Quiz Club, IIT Kanpur
ย 
The Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptxThe Rise of the Digital Telecommunication Marketplace.pptx
The Rise of the Digital Telecommunication Marketplace.pptx
ย 
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
INTRODUCTION TO HOSPITALS & AND ITS ORGANIZATION
ย 
Creating Images and Videos through AI.pptx
Creating Images and Videos through AI.pptxCreating Images and Videos through AI.pptx
Creating Images and Videos through AI.pptx
ย 
Erasmus + DISSEMINATION ACTIVITIES Croatia
Erasmus + DISSEMINATION ACTIVITIES CroatiaErasmus + DISSEMINATION ACTIVITIES Croatia
Erasmus + DISSEMINATION ACTIVITIES Croatia
ย 
Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024Brand Guideline of Bashundhara A4 Paper - 2024
Brand Guideline of Bashundhara A4 Paper - 2024
ย 
How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17How to Create User Notification in Odoo 17
How to Create User Notification in Odoo 17
ย 
How to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRMHow to Create a Stage or a Pipeline in Odoo 17 CRM
How to Create a Stage or a Pipeline in Odoo 17 CRM
ย 
What are the new features in the Fleet Odoo 17
What are the new features in the Fleet Odoo 17What are the new features in the Fleet Odoo 17
What are the new features in the Fleet Odoo 17
ย 
(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"(T.L.E.) Agriculture: "Ornamental Plants"
(T.L.E.) Agriculture: "Ornamental Plants"
ย 
Bแป˜ Bร€I TแบฌP TEST THEO UNIT - FORM 2025 - TIแบพNG ANH 12 GLOBAL SUCCESS - KรŒ 1 (B...
Bแป˜ Bร€I TแบฌP TEST THEO UNIT - FORM 2025 - TIแบพNG ANH 12 GLOBAL SUCCESS - KรŒ 1 (B...Bแป˜ Bร€I TแบฌP TEST THEO UNIT - FORM 2025 - TIแบพNG ANH 12 GLOBAL SUCCESS - KรŒ 1 (B...
Bแป˜ Bร€I TแบฌP TEST THEO UNIT - FORM 2025 - TIแบพNG ANH 12 GLOBAL SUCCESS - KรŒ 1 (B...
ย 
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptxScience-9-Lesson-1-The Bohr Model-NLC.pptx pptx
Science-9-Lesson-1-The Bohr Model-NLC.pptx pptx
ย 
Post init hook in the odoo 17 ERP Module
Post init hook in the  odoo 17 ERP ModulePost init hook in the  odoo 17 ERP Module
Post init hook in the odoo 17 ERP Module
ย 
The Science of Learning: implications for modern teaching
The Science of Learning: implications for modern teachingThe Science of Learning: implications for modern teaching
The Science of Learning: implications for modern teaching
ย 
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
220711130100 udita Chakraborty  Aims and objectives of national policy on inf...220711130100 udita Chakraborty  Aims and objectives of national policy on inf...
220711130100 udita Chakraborty Aims and objectives of national policy on inf...
ย 
Information and Communication Technology in Education
Information and Communication Technology in EducationInformation and Communication Technology in Education
Information and Communication Technology in Education
ย 

Oop lecture9 13

  • 1. Lecture 13 Iteration in Java Object Oriented Programming Eastern University, Dhaka Md. Raihan Kibria
  • 2. Simple c-style iteration public class IterationDemo { public static void main(String[] args) { List<String>lst = new ArrayList<String>(); lst.add("One"); lst.add("Two"); lst.add("Three"); for (int i=0; i<lst.size(); i++) System.out.println(lst.get(i)); } } Output: One Two Three
  • 3. More iterators //more eye-friendly iteration for (String s : lst) System.out.println(s); Gives the same output Most generic iterationโ€”using Iterator Iterator<String>it = lst.iterator(); while (it.hasNext()) System.out.println(it.next()); Gives the same output
  • 4. Iterating over a set Set<String>s = new HashSet<String>(); s.add("One"); s.add("Two"); s.add("Three"); Iterator<String>it = lst.iterator(); while (it.hasNext()) System.out.println(it.next()); Gives the same output: One Two Three
  • 5. Iterating over a map Map<String, String>map = new HashMap<String, String>(); map.put("One", "111111"); map.put("Two", "222222"); map.put("Three", "333333"); Iterator<Map.Entry<String, String>>it = map.entrySet().iterator(); while (it.hasNext()){ Map.Entry<String, String>entry = it.next(); System.out.println(entry.getKey() + "--" + entry.getValue()); } Output: Three--333333 One--111111 Two--222222
  • 6. Remember old style iteration still works for arrays String[] str = new String[]{"One", "Two", "Three"}; for (int i=0; i<str.length; i++) System.out.println(str[i]); Output: One Two Three String[] str = new String[]{"One", "Two", "Three"}; for (String s : str) System.out.println(s); Output: One Two Three
  • 7. Some common methods present in all objects toString() equals() hashCode() finalize()
  • 8. toString() public class Student { int id; String name; public Student(int id, String name) { super(); this.id = id; this.name = name; } public String toString(){ return this.id + "--" + this.name; } } public static void main(String[] args){ Student student = new Student(3, "Joe"); System.out.println(student); } Output: 3--Joe
  • 9. Another toString() demo List<Student>stus = new ArrayList<Student>(); Student st = new Student(1, "John"); stus.add(st); stus.add(st); System.out.println("Printing list: "); for (Student s: stus) System.out.println(s); Output: Printing list: 1--John 1--John
  • 10. hashCode() demo with equals() public class HashCodeDemo { public static class Student { int id; String name; public Student(int id, String name) { super(); this.id = id; this.name = name; } public String toString() { return this.id + "--" + this.name; } /* public boolean equals(Object obj) { Student arg = (Student) obj; return this.id == arg.id; }*/ public int hashCode() { return this.id; } }
  • 11. public static void main(String[] args) { Map<Student, String> map = new HashMap<Student, String>(); map.put(new Student(1, "John"), null); map.put(new Student(1, "John"), null); map.put(new Student(2, "John"), null); System.out.println(map.size()); Iterator<Map.Entry<Student, String>> it1 = map.entrySet().iterator(); System.out.println("Printing map: "); while (it1.hasNext()) System.out.println(it1.next()); } } Output: Now we uncomment the equals() method in the 3 previous slide: Printing map: 1--John=null Output: 1--John=null 2 2--John=null Printing map: 1--John=null 2--John=null Explanation: hashCode merely specifies a slot; equals() helps put the object in the slot
  • 12. equals() method ๏ต Two objects are equal if their equals() method returns true. Demo: public class Student { int id; String name; public Student(int id, String name) { super(); this.id = id; this.name = name; } public String toString(){ return this.id + "--" + this.name; } public int hashCode() { return this.id; } public boolean equals(Object obj) { Student s = (Student)obj; if (s.id == this.id) return true; return false; }
  • 13. equals() continued System.out.println(st.equals(st2)); System.out.println(st==st2); Output: true false In java โ€œ==โ€ operator is not same as โ€œequals()โ€
  • 14. finalize() ๏ต What is garbage collection? ๏ต In C/C++ the programmer can get a chunk of program using malloc() and can dispose memory using memfree() ๏ต Having programmer free will at memory management resulted in memory leaks in many C programs ๏ต Java will not let programmer directly acquiring memory. ๏ต Rather JVM manages memory
  • 15. Finalize() (c..) โ€ข When an object is de-referenced, the object is automatically removed from the memory by JVM. โ€ข Whenever, an object is removed its finalize() method is called โ€ข Garbage collection is automatically scheduled by the JVM โ€ข However, a programmer can trigger a garbage collection by calling System.gc() โ€ข Example in the next page:
  • 16. Finalize() (c..) public class AnObject { protected void finalize() throws Throwable { super.finalize(); System.out.println("Finalize method is called"); } public static void main(String[] args){ new AnObject(); } } Output:
  • 17. Finalize() (c..) public class AnObject { protected void finalize() throws Throwable { super.finalize(); System.out.println("Finalize method is called"); } public static void main(String[] args){ new AnObject(); System.gc(); } } Output: Finalize method is called
  • 18. Garbage collection formally defined Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection
  ็ฟป่ฏ‘๏ผš