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

PDF
Cheat sheet python3
PPTX
Enter The Matrix
PDF
6. Generics. Collections. Streams
PDF
JAVA 8 : Migration et enjeux stratégiques en entreprise
PDF
Python 2.5 reference card (2009)
PDF
Python3 cheatsheet
PDF
Clojure: The Art of Abstraction
PPTX
Procedural Content Generation with Clojure
Cheat sheet python3
Enter The Matrix
6. Generics. Collections. Streams
JAVA 8 : Migration et enjeux stratégiques en entreprise
Python 2.5 reference card (2009)
Python3 cheatsheet
Clojure: The Art of Abstraction
Procedural Content Generation with Clojure

What's hot (20)

PDF
Java_practical_handbook
PPTX
Clojure for Data Science
DOCX
Java practical
PDF
Sam wd programs
PDF
The Ring programming language version 1.3 book - Part 83 of 88
PDF
Clojure for Data Science
PDF
Clojure class
PDF
Numpy tutorial(final) 20160303
PPT
JDBC Core Concept
PDF
A tour of Python
PDF
Machine Learning Live
PPTX
Introduction to Monads in Scala (1)
PDF
Python_ 3 CheatSheet
PPTX
Poor Man's Functional Programming
PDF
Javascript
PPTX
Scala - where objects and functions meet
PDF
Futures e abstração - QCon São Paulo 2015
PDF
Python For Data Science Cheat Sheet
PPTX
COSCUP: Introduction to Julia
PDF
Pune Clojure Course Outline
Java_practical_handbook
Clojure for Data Science
Java practical
Sam wd programs
The Ring programming language version 1.3 book - Part 83 of 88
Clojure for Data Science
Clojure class
Numpy tutorial(final) 20160303
JDBC Core Concept
A tour of Python
Machine Learning Live
Introduction to Monads in Scala (1)
Python_ 3 CheatSheet
Poor Man's Functional Programming
Javascript
Scala - where objects and functions meet
Futures e abstração - QCon São Paulo 2015
Python For Data Science Cheat Sheet
COSCUP: Introduction to Julia
Pune Clojure Course Outline
Ad

Viewers also liked (9)

DOCX
Calendario portada
PPT
Oop lecture6
PPT
Oop lecture1
PPTX
Cwgd
PPT
Oop lecture2
PPT
Oop lecture8
PPT
Oop lecture9 12
PDF
Presentacion viernes 20 [compatibility mode]
PPT
Oop lecture9 11
Calendario portada
Oop lecture6
Oop lecture1
Cwgd
Oop lecture2
Oop lecture8
Oop lecture9 12
Presentacion viernes 20 [compatibility mode]
Oop lecture9 11
Ad

Similar to Oop lecture9 13 (20)

PDF
Java 8 lambda expressions
PDF
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
PDF
Java Class Design
PPT
Utility.ppt
DOCX
Java file
DOCX
Java file
PDF
The Future of JVM Languages
PDF
Core java pract_sem iii
PDF
OOP_Activity 1_ An Activty about code.pdf
PPTX
Groovy puzzlers по русски с Joker 2014
PDF
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
PDF
Java programs
PPTX
Basic java, java collection Framework and Date Time API
DOCX
DOCX
Write a program that reads a graph from a file and determines whether.docx
PDF
Simple 27 Java Program on basic java syntax
DOCX
Java programs
PDF
Java VS Python
PPTX
CodeCamp Iasi 10 march 2012 - Practical Groovy
PDF
Lezione03
Java 8 lambda expressions
LECTURE 2 MORE TYPES, METHODS, CONDITIONALS.pdf
Java Class Design
Utility.ppt
Java file
Java file
The Future of JVM Languages
Core java pract_sem iii
OOP_Activity 1_ An Activty about code.pdf
Groovy puzzlers по русски с Joker 2014
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Java programs
Basic java, java collection Framework and Date Time API
Write a program that reads a graph from a file and determines whether.docx
Simple 27 Java Program on basic java syntax
Java programs
Java VS Python
CodeCamp Iasi 10 march 2012 - Practical Groovy
Lezione03

More from Shahriar Robbani (8)

PPTX
PPT
Oop lecture9 10
PPT
Oop lecture4
PPT
Oop lecture9
PPT
Oop lecture7
PPT
Oop lecture5
PPT
Oop lecture3
Oop lecture9 10
Oop lecture4
Oop lecture9
Oop lecture7
Oop lecture5
Oop lecture3

Recently uploaded (20)

PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Business Ethics Teaching Materials for college
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Insiders guide to clinical Medicine.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
Pharma ospi slides which help in ospi learning
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
RMMM.pdf make it easy to upload and study
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Institutional Correction lecture only . . .
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Business Ethics Teaching Materials for college
PPH.pptx obstetrics and gynecology in nursing
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Insiders guide to clinical Medicine.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Cell Structure & Organelles in detailed.
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Pharma ospi slides which help in ospi learning
O5-L3 Freight Transport Ops (International) V1.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
VCE English Exam - Section C Student Revision Booklet
Pharmacology of Heart Failure /Pharmacotherapy of CHF
RMMM.pdf make it easy to upload and study
Renaissance Architecture: A Journey from Faith to Humanism
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Institutional Correction lecture only . . .

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