SlideShare une entreprise Scribd logo
1  sur  19
Télécharger pour lire hors ligne
Java course - IAG0040




             More Java Basics
                and OOP


Anton Keks                            2011
Construction
 ●
     All objects are constructed using the new keyword
     –   MyClass fooBar = new MyClass();
 ●
     Object creation always executes a constructor
     –   Constructors may take parameters as any other
         methods
 ●   Default constructor (without parameters) exists if
     there are no other constructors defined
 ●   Constructor is a method without a return type (it
     returns the object's instance), the name of a
     constructor is the same as of the class.
Java course – IAG0040                                    Lecture 3
Anton Keks                                                 Slide 2
Destruction
 ●
     No need to destroy objects manually
 ●
     Garbage Collector (GC) does the job of destruction
     –   Executed in background when memory gets low
     –   Can actually be faster than explicit deallocation
     –   Can be invoked manually with System.gc();
 ●   An object is destroyed if there are no references left to
     it in the program, this almost eliminates memory leaks
 ●   Out of scope local variables are also candidates
 ●   finalize() method may be used instead of a destructor,
     however, its execution is not guaranteed
Java course – IAG0040                                    Lecture 3
Anton Keks                                                 Slide 3
Conditions
 ●
         if-else
     –   if (boolean-expression)   a boolean-expression
                                   should return a boolean
            statement              or Boolean value
         else
            statement
 ●
         switch
                                   an expression can return an
     –   switch (expression) {     int, short, char, byte, their
            case X:                respective wrapper classes
               statement           (which are unboxed) or an
               break;              enum type
            default:
               statement           a statement is a single Java
               break;              statement or multiple
         }                         statements in curly braces { }

Java course – IAG0040                                      Lecture 3
Anton Keks                                                   Slide 4
While loops
 ●
         while
     –   while (boolean-expression)
           statement
     –   Executes the statement while boolean-expression evaluates to true
 ●       do-while
     –   do
           statement
         while (boolean-expression);
     –   Same, but boolean-expression is evaluated after each iteration, not
         before



Java course – IAG0040                                                 Lecture 3
Anton Keks                                                              Slide 5
For loops
 ●
         for loop
     –   for(initialization; boolean-expression; step)
            statement
     –   Example: for(int i=0, j=1; i < 5; i++, j*=2) {}
 ●
         for each loop (arrays and Iterables)
     –   for(variable : iterable)
           statement
     –   for (int a : new int[] {1,2,3}) {}
     –   iterates over all elements of an iterable, executing the
         statement for each of its elements, assigning the element itself
         to the variable
Java course – IAG0040                                             Lecture 3
Anton Keks                                                          Slide 6
break and continue
 ●
         break and continue keywords can be used in any loop
     –   break interrupts the innermost loop
     –   continue skips to the next iteration of the innermost loop
 ●
         goto keyword is forbidden in Java, but break and
         continue can be used with labels
     –   outer: while(true) {
            inner: while(true) {
               break outer;
            }
         }
     –   Labels can be specified only right before a loop. Usage of break or
         continue with a label affects the labeled loop, not the innermost
         one.
Java course – IAG0040                                                 Lecture 3
Anton Keks                                                              Slide 7
Arrays
 ●
         Array is a special type of Object
     –   Arrays are actually arrays of references
     –   Elements are automatically initialized with zeros or nulls
     –   Automatic range checking is performed, always zero based
     ●   ArrayIndexOutOfBoundsException is thrown otherwise
     –   Special property is accessible: length
 ●       Definition: type followed by [ ]: byte[] a; String s[];
 ●       Creation using the new keyword: byte[]             a = new byte[12];
 ●       Access: byte b = a[0]; byte b2 = a[a.length – 1];
 ●       Static initialization: byte[] a = new byte[] {1,2,3};
 ●       Multidimensional: int[][] matrix = new int[3][3];
Java course – IAG0040                                                  Lecture 3
Anton Keks                                                               Slide 8
Strings
 ●       An immutable char array with additional features
 ●       Literals: “!” same as new String(new char[] {'!'})
 ●       Any object can be converted toString()
 ●       All primitive wrappers understand Strings: new Integer(“3”)
 ●       Equality is checked with equals() method
 ●       String pooling
     –    “ab” != new String(“ab”)
     –    “a1” == “a” + 1
 ●       StringBuilder is used behind the scenes for concatenation

Java course – IAG0040                                            Lecture 3
Anton Keks                                                         Slide 9
Classpath
 ●
     Classpath tells the JVM where to look for
     packages and classes
        –   java -cp or java -classpath
        –   $CLASSPATH environment variable
 ●   Works like $PATH environment variable
 ●   Every used class must be present on classpath
     during both compilation and runtime



Java course – IAG0040                            Lecture 3
Anton Keks                                        Slide 10
Classpath example
 ●
     Your class net.azib.Hello
 ●   Uses org.log4j.Logger and com.sun.World
 ●   In filesystem:
        –   ~/myclasses/net/azib/Hello.class
        –   ~/log4j/org/log4j/Logger.class
        –   ~/lib/sun.jar, which contains com/sun/World.class
 ●
     Should be run as following:            (separated with “;” on Windows)

        –   java -cp myclasses:log4j:lib/sun.jar net.azib.Hello
                             --- classpath ---

Java course – IAG0040                                            Lecture 3
Anton Keks                                                        Slide 11
Java API documentation



      Let's examine the API documentation a bit:
       http://java.sun.com/javase/6/docs/api/
  (http://java.azib.net -> Lirerature & Links -> API documentation)




Java course – IAG0040                                         Lecture 3
Anton Keks                                                     Slide 12
Javadoc comments
 ●
         Javadoc allows to document the code in place
     –   Helps with synchronization of code and documentation
 ●       Syntax: /** a javadoc comment */
     –   Documents the following source code element
     –   Tags: start with '@', have special meaning
     ●   Examples: @author, @version, @param
     ●   @deprecated – processed by the compiler to issue warnings
     –   Links: {@link java.lang.Object}, use '#' for fields or methods
     ●   {@link Object#equals(Object)}
 ●       javadoc program generates HTML documentation

Java course – IAG0040                                                Lecture 3
Anton Keks                                                            Slide 13
Varargs
●
        A way to pass unbounded number of parameters to methods
●
        Is merely a convenient syntax for passing arrays
●       void process(String ... a)
    –   In the method body, a can be used as an array of Strings
    –   There can be only one varargs-type parameter, and it should
        always be the last one
●       Caller can use two variants:
    –   process(new String[] {“a”, “b”}) - the old way
    –   process(“a”, “b”) - the varargs (new) way
●       System.out.printf() uses varargs
Java course – IAG0040                                              Lecture 3
Anton Keks                                                          Slide 14
Autoboxing
 ●
     Automatically wraps/unwraps primitive types into
     corresponding wrapper classes
 ●
     Boxing conversion, e.g. boolean -> Boolean, int ->
     Integer
 ●
     Unboxing conversion, e.g. Character -> char, etc
 ●   These values are cached: true, false, all bytes, chars
     from u0000 to u007F, ints and shorts from -128 to
     127
 ●   Examples:
     Integer n = 5;               // boxing
     char c = new Character('z'); // unboxing
Java course – IAG0040                                Lecture 3
Anton Keks                                            Slide 15
Extending classes
 ●
     Root class: java.lang.Object (used implicitly)
 ●   Unlike C++, only single inheritance is supported
 ●   class A {}        // extends Object
     class B extends A {}
     –   new B() instanceof A == true
     –   new B() instanceof Object == true
 ●   Access current class/instance with this keyword
 ●   Access base class with super keyword

Java course – IAG0040                           Lecture 3
Anton Keks                                       Slide 16
Extending classes
 ●       All methods are polymorphic (aka virtual in C++)
     –   final methods cannot be overridden
     –   super.method() calls the super implementation (optional)
 ●       Constructors always call super constructors
     –   if no constructors are defined, default one is assumed
     ●   class A { }                 // implies public A() {}
     –   default constructor is called implicitly if possible
     ●   class B extends A {
            public B(int i) { }           // super() is called
            public B(byte b) { super(); } // same here
         }

Java course – IAG0040                                             Lecture 3
Anton Keks                                                         Slide 17
Abstract classes
 ●   Defined with the abstract keyword
 ●   Not a concrete class, cannot be instantiated
 ●
     Can contain abstract methods without implementation
 ●   abstract class Animal {     // new Animal() is not allowed
        private String name;
        String getName() { return name; }
        abstract void makeSound();
     }
 ●   class Dog extends Animal {
        void makeSound() {
           System.out.println(“Woof!”);
        }
     }

Java course – IAG0040                                   Lecture 3
Anton Keks                                               Slide 18
Interfaces
 ●
     Substitute for Java's lack of multiple inheritance
        –   a class can implement many interfaces
 ●
     Interface are extreme abstract classes without
     implementation at all
        –   all methods are public and abstract by default
        –   can contain static final constants
        –   marker interfaces don't define any methods at all, eg Cloneable
 ●   public interface Eatable {
        Taste getTaste();
        void eat();
     }
 ●   public class Apple implements Eatable, Comparable
     { /* implementation */ }

Java course – IAG0040                                             Lecture 3
Anton Keks                                                         Slide 19

Contenu connexe

Tendances

Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
Akshay Nagpurkar
 

Tendances (20)

Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Core java
Core javaCore java
Core java
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Core java
Core java Core java
Core java
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java Certification
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java features
Java featuresJava features
Java features
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 

En vedette

En vedette (20)

Java Basics
Java BasicsJava Basics
Java Basics
 
PALASH SL GUPTA
PALASH SL GUPTAPALASH SL GUPTA
PALASH SL GUPTA
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
Introduction to basics of java
Introduction to basics of javaIntroduction to basics of java
Introduction to basics of java
 
Java basics
Java basicsJava basics
Java basics
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
Java basics
Java basicsJava basics
Java basics
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
 
Java Basics
Java BasicsJava Basics
Java Basics
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
Java basics part 1
Java basics part 1Java basics part 1
Java basics part 1
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Ppt on java basics
Ppt on java basicsPpt on java basics
Ppt on java basics
 
Basics of java programming language
Basics of java programming languageBasics of java programming language
Basics of java programming language
 
02 java basics
02 java basics02 java basics
02 java basics
 

Similaire à Java Course 3: OOP

First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introduction
Oregon FIRST Robotics
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
Muhammad Abdullah
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
Chikugehlot
 

Similaire à Java Course 3: OOP (20)

Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introduction
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!
 
Jvm internals
Jvm internalsJvm internals
Jvm internals
 
core java
core javacore java
core java
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
 

Plus de Anton Keks

Plus de Anton Keks (8)

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Dernier (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Java Course 3: OOP

  • 1. Java course - IAG0040 More Java Basics and OOP Anton Keks 2011
  • 2. Construction ● All objects are constructed using the new keyword – MyClass fooBar = new MyClass(); ● Object creation always executes a constructor – Constructors may take parameters as any other methods ● Default constructor (without parameters) exists if there are no other constructors defined ● Constructor is a method without a return type (it returns the object's instance), the name of a constructor is the same as of the class. Java course – IAG0040 Lecture 3 Anton Keks Slide 2
  • 3. Destruction ● No need to destroy objects manually ● Garbage Collector (GC) does the job of destruction – Executed in background when memory gets low – Can actually be faster than explicit deallocation – Can be invoked manually with System.gc(); ● An object is destroyed if there are no references left to it in the program, this almost eliminates memory leaks ● Out of scope local variables are also candidates ● finalize() method may be used instead of a destructor, however, its execution is not guaranteed Java course – IAG0040 Lecture 3 Anton Keks Slide 3
  • 4. Conditions ● if-else – if (boolean-expression) a boolean-expression should return a boolean statement or Boolean value else statement ● switch an expression can return an – switch (expression) { int, short, char, byte, their case X: respective wrapper classes statement (which are unboxed) or an break; enum type default: statement a statement is a single Java break; statement or multiple } statements in curly braces { } Java course – IAG0040 Lecture 3 Anton Keks Slide 4
  • 5. While loops ● while – while (boolean-expression) statement – Executes the statement while boolean-expression evaluates to true ● do-while – do statement while (boolean-expression); – Same, but boolean-expression is evaluated after each iteration, not before Java course – IAG0040 Lecture 3 Anton Keks Slide 5
  • 6. For loops ● for loop – for(initialization; boolean-expression; step) statement – Example: for(int i=0, j=1; i < 5; i++, j*=2) {} ● for each loop (arrays and Iterables) – for(variable : iterable) statement – for (int a : new int[] {1,2,3}) {} – iterates over all elements of an iterable, executing the statement for each of its elements, assigning the element itself to the variable Java course – IAG0040 Lecture 3 Anton Keks Slide 6
  • 7. break and continue ● break and continue keywords can be used in any loop – break interrupts the innermost loop – continue skips to the next iteration of the innermost loop ● goto keyword is forbidden in Java, but break and continue can be used with labels – outer: while(true) { inner: while(true) { break outer; } } – Labels can be specified only right before a loop. Usage of break or continue with a label affects the labeled loop, not the innermost one. Java course – IAG0040 Lecture 3 Anton Keks Slide 7
  • 8. Arrays ● Array is a special type of Object – Arrays are actually arrays of references – Elements are automatically initialized with zeros or nulls – Automatic range checking is performed, always zero based ● ArrayIndexOutOfBoundsException is thrown otherwise – Special property is accessible: length ● Definition: type followed by [ ]: byte[] a; String s[]; ● Creation using the new keyword: byte[] a = new byte[12]; ● Access: byte b = a[0]; byte b2 = a[a.length – 1]; ● Static initialization: byte[] a = new byte[] {1,2,3}; ● Multidimensional: int[][] matrix = new int[3][3]; Java course – IAG0040 Lecture 3 Anton Keks Slide 8
  • 9. Strings ● An immutable char array with additional features ● Literals: “!” same as new String(new char[] {'!'}) ● Any object can be converted toString() ● All primitive wrappers understand Strings: new Integer(“3”) ● Equality is checked with equals() method ● String pooling – “ab” != new String(“ab”) – “a1” == “a” + 1 ● StringBuilder is used behind the scenes for concatenation Java course – IAG0040 Lecture 3 Anton Keks Slide 9
  • 10. Classpath ● Classpath tells the JVM where to look for packages and classes – java -cp or java -classpath – $CLASSPATH environment variable ● Works like $PATH environment variable ● Every used class must be present on classpath during both compilation and runtime Java course – IAG0040 Lecture 3 Anton Keks Slide 10
  • 11. Classpath example ● Your class net.azib.Hello ● Uses org.log4j.Logger and com.sun.World ● In filesystem: – ~/myclasses/net/azib/Hello.class – ~/log4j/org/log4j/Logger.class – ~/lib/sun.jar, which contains com/sun/World.class ● Should be run as following: (separated with “;” on Windows) – java -cp myclasses:log4j:lib/sun.jar net.azib.Hello --- classpath --- Java course – IAG0040 Lecture 3 Anton Keks Slide 11
  • 12. Java API documentation Let's examine the API documentation a bit: http://java.sun.com/javase/6/docs/api/ (http://java.azib.net -> Lirerature & Links -> API documentation) Java course – IAG0040 Lecture 3 Anton Keks Slide 12
  • 13. Javadoc comments ● Javadoc allows to document the code in place – Helps with synchronization of code and documentation ● Syntax: /** a javadoc comment */ – Documents the following source code element – Tags: start with '@', have special meaning ● Examples: @author, @version, @param ● @deprecated – processed by the compiler to issue warnings – Links: {@link java.lang.Object}, use '#' for fields or methods ● {@link Object#equals(Object)} ● javadoc program generates HTML documentation Java course – IAG0040 Lecture 3 Anton Keks Slide 13
  • 14. Varargs ● A way to pass unbounded number of parameters to methods ● Is merely a convenient syntax for passing arrays ● void process(String ... a) – In the method body, a can be used as an array of Strings – There can be only one varargs-type parameter, and it should always be the last one ● Caller can use two variants: – process(new String[] {“a”, “b”}) - the old way – process(“a”, “b”) - the varargs (new) way ● System.out.printf() uses varargs Java course – IAG0040 Lecture 3 Anton Keks Slide 14
  • 15. Autoboxing ● Automatically wraps/unwraps primitive types into corresponding wrapper classes ● Boxing conversion, e.g. boolean -> Boolean, int -> Integer ● Unboxing conversion, e.g. Character -> char, etc ● These values are cached: true, false, all bytes, chars from u0000 to u007F, ints and shorts from -128 to 127 ● Examples: Integer n = 5; // boxing char c = new Character('z'); // unboxing Java course – IAG0040 Lecture 3 Anton Keks Slide 15
  • 16. Extending classes ● Root class: java.lang.Object (used implicitly) ● Unlike C++, only single inheritance is supported ● class A {} // extends Object class B extends A {} – new B() instanceof A == true – new B() instanceof Object == true ● Access current class/instance with this keyword ● Access base class with super keyword Java course – IAG0040 Lecture 3 Anton Keks Slide 16
  • 17. Extending classes ● All methods are polymorphic (aka virtual in C++) – final methods cannot be overridden – super.method() calls the super implementation (optional) ● Constructors always call super constructors – if no constructors are defined, default one is assumed ● class A { } // implies public A() {} – default constructor is called implicitly if possible ● class B extends A { public B(int i) { } // super() is called public B(byte b) { super(); } // same here } Java course – IAG0040 Lecture 3 Anton Keks Slide 17
  • 18. Abstract classes ● Defined with the abstract keyword ● Not a concrete class, cannot be instantiated ● Can contain abstract methods without implementation ● abstract class Animal { // new Animal() is not allowed private String name; String getName() { return name; } abstract void makeSound(); } ● class Dog extends Animal { void makeSound() { System.out.println(“Woof!”); } } Java course – IAG0040 Lecture 3 Anton Keks Slide 18
  • 19. Interfaces ● Substitute for Java's lack of multiple inheritance – a class can implement many interfaces ● Interface are extreme abstract classes without implementation at all – all methods are public and abstract by default – can contain static final constants – marker interfaces don't define any methods at all, eg Cloneable ● public interface Eatable { Taste getTaste(); void eat(); } ● public class Apple implements Eatable, Comparable { /* implementation */ } Java course – IAG0040 Lecture 3 Anton Keks Slide 19