SlideShare une entreprise Scribd logo
1  sur  18
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

Contenu connexe

Tendances

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
 
Poor Man's Functional Programming
Poor Man's Functional ProgrammingPoor Man's Functional Programming
Poor Man's Functional Programming
Dmitry Buzdin
 
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
 

Tendances (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
 

En vedette (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
 

Similaire à Oop lecture9 13

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
 
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
jojeph
 
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
 

Similaire à 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
 

Plus de 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
 

Dernier

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Dernier (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 

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