SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
Introduction to Java 2
      Programming
            Lecture 3
More Syntax; Working with Objects
Overview
• More new syntax
  – Arrays
  – String/StringBuffer objects
  – Parameter passing
• Working with objects
  – Constructors
  – Constants
Java Arrays – The Basics
• Declaring an array
int[] myArray;
int[] myArray = new int[5];
String[] stringArray = new String[10];
String[] strings = new String[] {“one”, “two”};

• Checking an arrays length
int arrayLength = myArray.length;

• Looping over an array
for(int i=0; i<myArray.length; i++)
{
   String s = myArray[i];
}
Java Arrays – Bounds Checking
• Bounds checking
  – Java does this automatically. Impossible to go
    beyond the end of an array (unlike C/C++)
  – Automatically generates an
    ArrayIndexOutOfBoundsException
Java Arrays – Copying
• Don’t copy arrays “by hand” (e.g. by looping over
  the array)
• The System class has an arrayCopy method to
  do this efficiently
int array1[] = new int[10];
int array2[] = new int[10];
//assume we add items to array1

//copy array1 into array2
System.arrayCopy(array1, 0, array2, 0, 10);
//copy last 5 elements in array1 into first 5 of array2
System.arrayCopy(array1, 5, array2, 0, 5);
Java Arrays – Sorting
• Again no need to do this “by hand”.
• The java.util.Arrays class has methods to sort
  different kinds of arrays

int myArray[] = new int[] {5, 4, 3, 2, 1};
java.util.Arrays.sort(myArray);
//myArray now holds 1, 2, 3, 4, 5


• Sorting arrays of objects is involves some extra
  work, as we’ll see in a later lesson
Strings
• Strings are objects
• The compiler automatically replaces any string
  literal with an equivalent String object
   – E.g. “my   String” becomes new String(“my string”);

• Strings are immutable
   – Can’t be changed once created…
   – ..but can be concatenated (using +) to create new
     strings
   String newString = “abc” + “def”;
Strings
• Strings have methods to manipulate their
  contents:
int length = someString.length();
String firstTwoLetters =
  someString.substring(0,2);
String upper = someString.toUpperCase();
boolean startsWithLetterA =
  someString.startsWith(“A”);
boolean containsOther =
  (someString.indexOf(otherString) != -1)
StringBuffer

• StringBuffer object allows a string value to be
  manipulated
   – I.e. they are not immutable
• StringBuffer has useful methods like:
   – Append, insert, delete, replace, etc
• Compiler automatically replaces String
  concatenation with a StringBuffer object
   – E.g. “my String” + “ other String” becomes…
   new StringBuffer(“my String”).append(“other
     String”).toString();
StringBuffer
• Take care with String concatenation
  – Explicitly using a StringBuffer is often
    more efficient
  – Can reuse buffer rather than discarding it
  StringBuffer.setLength(0)
Passing Parameters
• Java has two ways of passing parameters
  – Pass by Reference
  – Pass by Value
• Pass by Value applies to primitive types
  – int, float, etc
• Pass by Reference applies to reference types
  – objects and arrays
Passing Parameters
public class PassByValueTest
{
  public void increment(int x)
  {
     x = x + 1;
  }

    public void test()
    {
      int x = 0;
      increment(x);
      //whats the value of x here?
    }
}
Passing Parameters
public class PassByReferenceTest
{
  public void reverse(StringBuffer buffer)
  {
    buffer.reverse();
  }

    public void test()
    {
      StringBuffer buffer = new StringBuffer(“Hello”);
      reverse(buffer);
      //what does buffer contain now?
    }
}
Overview
• More new syntax
  –   Arrays
  –   Constants
  –   String/StringBuffer objects
  –   Parameter passing
• Working with objects
  – Constructors
  – Constants
• Exercises
Initialising Objects
• Variables of a reference type have a special value
  before they are initialised
   – A “nothing” value called null
• Attempting to manipulate an object before its
  initialised will cause an error
   – A NullPointerException
• To properly initialise a reference type, we need to
  assign it a value by creating an object
   – Objects are created with the new operator
   String someString = new String(“my String”);
Constructors
• new causes a constructor to be invoked
  – Constructor is a special method, used to
    initialise an object
  – Class often specifies several constructors (for
    flexibility)
  – new operator chooses right constructor based on
    parameters (overloading)
• Constructors can only be invoked by the
  new operator
Constructors – Example 1
public class MyClass
{
  private int x;
  public MyClass(int a)
  {
    x = a;
  }
}
We can then create an instance of MyClass as follows:

MyClass object = new MyClass(5);     //constructor is
  called
What are constructors for?
• Why do we use them?
   – Give us chance to ensure our objects are properly
     initialised
   – Can supply default values to member variables
   – Can accept parameters to allow an object to be
     customised
   – Can validate this data to ensure that the object is
     created correctly.
• A class always has at least one constructor
   – …even if you don’t define it, the compiler will
   – This is the default constructor
Constructors – Example 2
public class EmailAddress
{
  public EmailAddress(String address)
  {
    if (address.indexOf(“@”) == -1)
    {
      //not a valid address, signal an error?
    }
    //must be valid…
  }

    //methods
}
Destroying Objects
• No way to explicitly destroy an object
• Objects destroyed by the Garbage Collector
   – Once they go out of scope (I.e. no longer referenced by
     any variable)
• No way to reclaim memory, entirely under control
  of JVM
   – There is a finalize method, but its not guaranteed to be
     called (so pretty useless!)
   – Can request that the Garbage Collector can run, buts its
     free to ignore you
Modifiers
• Public/private are visibility modifiers
  – Used to indicate visibility of methods and
    attributes
• Java has a range of other modifiers
  – Control “ownership” of a method or attribute
  – Control when and how variable can be
    initialised
  – Control inheritance of methods (and whether
    they can be overridden by a sub-class)
Static
• static – indicates a class variable or
  class method. It’s not owned by an
  individual object
  – This means we don’t have to create an object to
    use it
  – Arrays.sort and System.arrayCopy
    are static methods
Static -- Example
public class MyClass
{
  public static void utilityMethod() { … }
  public void otherMethod() { … }
}

//using the above:
MyClass.utilityMethod();
MyClass objectOfMyClass = new MyClass();
objectOfMyClass.otherMethod();
objectOfMyClass.utilityMethod();

//this is illegal:
MyClass.otherMethod();
Final
• final – to make a variable that can have a
  single value
  – Can be assigned to once and once only
  – Useful to ensure a variable isn’t changed once
    its assigned.
final   int count;
count   = 10;
//the   following will cause an error
count   = 20;
Defining Constants
• Unlike other languages, Java has no const
  keyword
• Must use a combination of modifiers to make a
  constant
   – static – to indicate its owned by the class
   – final – to make sure it can’t be changed (and
     initialise it when its declared)
• Naming convention for constants is to use all
  capitals
• Example…
Constants – An Example
public class MyClass
{
  public static final int COUNT = 0;
  public static final boolean SWITCHED_ON =
  false;
}

//example usage:
if (MyClass.COUNT > 0) { … }

if (MyClass.SWITCHED_ON) {…}

Más contenido relacionado

La actualidad más candente

Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packagesSardar Alam
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Conceptsmdfkhan625
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in javaGaruda Trainings
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classesteach4uin
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Edureka!
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaRafael Magana
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxingGeetha Manohar
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objectsmaznabili
 

La actualidad más candente (20)

Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Java Strings
Java StringsJava Strings
Java Strings
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
 
Java Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O MechanismsJava Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O Mechanisms
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael Magana
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java String
Java StringJava String
Java String
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 

Destacado

Destacado (8)

Evaluationq1
Evaluationq1Evaluationq1
Evaluationq1
 
Question 6
Question 6Question 6
Question 6
 
El rock latino
El rock latinoEl rock latino
El rock latino
 
Evaluationq3
Evaluationq3Evaluationq3
Evaluationq3
 
Rock
RockRock
Rock
 
Lesson2
Lesson2Lesson2
Lesson2
 
4 t a boy scouts day 1
4 t a   boy scouts day 14 t a   boy scouts day 1
4 t a boy scouts day 1
 
B.A.P - Power Music Video Analysis
B.A.P - Power Music Video AnalysisB.A.P - Power Music Video Analysis
B.A.P - Power Music Video Analysis
 

Similar a Lesson3

class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.pptYonas D. Ebren
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsHelen SagayaRaj
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar Verma
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On WorkshopArpit Poladia
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryPray Desai
 
Java Script
Java ScriptJava Script
Java ScriptSarvan15
 
Java Script
Java ScriptJava Script
Java ScriptSarvan15
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP LanguageAhmed Ali
 

Similar a Lesson3 (20)

class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Java
JavaJava
Java
 
Java
Java Java
Java
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Java Script
Java ScriptJava Script
Java Script
 
Java Script
Java ScriptJava Script
Java Script
 
Swift as an OOP Language
Swift as an OOP LanguageSwift as an OOP Language
Swift as an OOP Language
 

Último

P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfYu Kanazawa / Osaka University
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.EnglishCEIPdeSigeiro
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxSaurabhParmar42
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxAditiChauhan701637
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxiammrhaywood
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphNetziValdelomar1
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfTechSoup
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17Celine George
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17Celine George
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...Nguyen Thanh Tu Collection
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapitolTechU
 
How to Solve Singleton Error in the Odoo 17
How to Solve Singleton Error in the  Odoo 17How to Solve Singleton Error in the  Odoo 17
How to Solve Singleton Error in the Odoo 17Celine George
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptxSandy Millin
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17Celine George
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesMohammad Hassany
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17Celine George
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxMYDA ANGELICA SUAN
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxEduSkills OECD
 
Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.raviapr7
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxKatherine Villaluna
 

Último (20)

P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdfP4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
P4C x ELT = P4ELT: Its Theoretical Background (Kanazawa, 2024 March).pdf
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptx
 
In - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptxIn - Vivo and In - Vitro Correlation.pptx
In - Vivo and In - Vitro Correlation.pptx
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a Paragraph
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
 
How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17How to Add Existing Field in One2Many Tree View in Odoo 17
How to Add Existing Field in One2Many Tree View in Odoo 17
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptx
 
How to Solve Singleton Error in the Odoo 17
How to Solve Singleton Error in the  Odoo 17How to Solve Singleton Error in the  Odoo 17
How to Solve Singleton Error in the Odoo 17
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming Classes
 
How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17How to Add a New Field in Existing Kanban View in Odoo 17
How to Add a New Field in Existing Kanban View in Odoo 17
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptx
 
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptxPISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
PISA-VET launch_El Iza Mohamedou_19 March 2024.pptx
 
Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.Drug Information Services- DIC and Sources.
Drug Information Services- DIC and Sources.
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
 

Lesson3

  • 1. Introduction to Java 2 Programming Lecture 3 More Syntax; Working with Objects
  • 2. Overview • More new syntax – Arrays – String/StringBuffer objects – Parameter passing • Working with objects – Constructors – Constants
  • 3. Java Arrays – The Basics • Declaring an array int[] myArray; int[] myArray = new int[5]; String[] stringArray = new String[10]; String[] strings = new String[] {“one”, “two”}; • Checking an arrays length int arrayLength = myArray.length; • Looping over an array for(int i=0; i<myArray.length; i++) { String s = myArray[i]; }
  • 4. Java Arrays – Bounds Checking • Bounds checking – Java does this automatically. Impossible to go beyond the end of an array (unlike C/C++) – Automatically generates an ArrayIndexOutOfBoundsException
  • 5. Java Arrays – Copying • Don’t copy arrays “by hand” (e.g. by looping over the array) • The System class has an arrayCopy method to do this efficiently int array1[] = new int[10]; int array2[] = new int[10]; //assume we add items to array1 //copy array1 into array2 System.arrayCopy(array1, 0, array2, 0, 10); //copy last 5 elements in array1 into first 5 of array2 System.arrayCopy(array1, 5, array2, 0, 5);
  • 6. Java Arrays – Sorting • Again no need to do this “by hand”. • The java.util.Arrays class has methods to sort different kinds of arrays int myArray[] = new int[] {5, 4, 3, 2, 1}; java.util.Arrays.sort(myArray); //myArray now holds 1, 2, 3, 4, 5 • Sorting arrays of objects is involves some extra work, as we’ll see in a later lesson
  • 7. Strings • Strings are objects • The compiler automatically replaces any string literal with an equivalent String object – E.g. “my String” becomes new String(“my string”); • Strings are immutable – Can’t be changed once created… – ..but can be concatenated (using +) to create new strings String newString = “abc” + “def”;
  • 8. Strings • Strings have methods to manipulate their contents: int length = someString.length(); String firstTwoLetters = someString.substring(0,2); String upper = someString.toUpperCase(); boolean startsWithLetterA = someString.startsWith(“A”); boolean containsOther = (someString.indexOf(otherString) != -1)
  • 9. StringBuffer • StringBuffer object allows a string value to be manipulated – I.e. they are not immutable • StringBuffer has useful methods like: – Append, insert, delete, replace, etc • Compiler automatically replaces String concatenation with a StringBuffer object – E.g. “my String” + “ other String” becomes… new StringBuffer(“my String”).append(“other String”).toString();
  • 10. StringBuffer • Take care with String concatenation – Explicitly using a StringBuffer is often more efficient – Can reuse buffer rather than discarding it StringBuffer.setLength(0)
  • 11. Passing Parameters • Java has two ways of passing parameters – Pass by Reference – Pass by Value • Pass by Value applies to primitive types – int, float, etc • Pass by Reference applies to reference types – objects and arrays
  • 12. Passing Parameters public class PassByValueTest { public void increment(int x) { x = x + 1; } public void test() { int x = 0; increment(x); //whats the value of x here? } }
  • 13. Passing Parameters public class PassByReferenceTest { public void reverse(StringBuffer buffer) { buffer.reverse(); } public void test() { StringBuffer buffer = new StringBuffer(“Hello”); reverse(buffer); //what does buffer contain now? } }
  • 14. Overview • More new syntax – Arrays – Constants – String/StringBuffer objects – Parameter passing • Working with objects – Constructors – Constants • Exercises
  • 15. Initialising Objects • Variables of a reference type have a special value before they are initialised – A “nothing” value called null • Attempting to manipulate an object before its initialised will cause an error – A NullPointerException • To properly initialise a reference type, we need to assign it a value by creating an object – Objects are created with the new operator String someString = new String(“my String”);
  • 16. Constructors • new causes a constructor to be invoked – Constructor is a special method, used to initialise an object – Class often specifies several constructors (for flexibility) – new operator chooses right constructor based on parameters (overloading) • Constructors can only be invoked by the new operator
  • 17. Constructors – Example 1 public class MyClass { private int x; public MyClass(int a) { x = a; } } We can then create an instance of MyClass as follows: MyClass object = new MyClass(5); //constructor is called
  • 18. What are constructors for? • Why do we use them? – Give us chance to ensure our objects are properly initialised – Can supply default values to member variables – Can accept parameters to allow an object to be customised – Can validate this data to ensure that the object is created correctly. • A class always has at least one constructor – …even if you don’t define it, the compiler will – This is the default constructor
  • 19. Constructors – Example 2 public class EmailAddress { public EmailAddress(String address) { if (address.indexOf(“@”) == -1) { //not a valid address, signal an error? } //must be valid… } //methods }
  • 20. Destroying Objects • No way to explicitly destroy an object • Objects destroyed by the Garbage Collector – Once they go out of scope (I.e. no longer referenced by any variable) • No way to reclaim memory, entirely under control of JVM – There is a finalize method, but its not guaranteed to be called (so pretty useless!) – Can request that the Garbage Collector can run, buts its free to ignore you
  • 21. Modifiers • Public/private are visibility modifiers – Used to indicate visibility of methods and attributes • Java has a range of other modifiers – Control “ownership” of a method or attribute – Control when and how variable can be initialised – Control inheritance of methods (and whether they can be overridden by a sub-class)
  • 22. Static • static – indicates a class variable or class method. It’s not owned by an individual object – This means we don’t have to create an object to use it – Arrays.sort and System.arrayCopy are static methods
  • 23. Static -- Example public class MyClass { public static void utilityMethod() { … } public void otherMethod() { … } } //using the above: MyClass.utilityMethod(); MyClass objectOfMyClass = new MyClass(); objectOfMyClass.otherMethod(); objectOfMyClass.utilityMethod(); //this is illegal: MyClass.otherMethod();
  • 24. Final • final – to make a variable that can have a single value – Can be assigned to once and once only – Useful to ensure a variable isn’t changed once its assigned. final int count; count = 10; //the following will cause an error count = 20;
  • 25. Defining Constants • Unlike other languages, Java has no const keyword • Must use a combination of modifiers to make a constant – static – to indicate its owned by the class – final – to make sure it can’t be changed (and initialise it when its declared) • Naming convention for constants is to use all capitals • Example…
  • 26. Constants – An Example public class MyClass { public static final int COUNT = 0; public static final boolean SWITCHED_ON = false; } //example usage: if (MyClass.COUNT > 0) { … } if (MyClass.SWITCHED_ON) {…}

Notas del editor

  1. Remember an array is a reference type, so its really an object. In Java an array has one public Property: its length. Its not possible to add new properties or methods to arrays. There are a separate Set of objects that model more complex data structures (Lists, Maps, Linked Lists, etc) Arrays are zero indexed. The length will return the total size of the array (so be careful with loops).
  2. We’ll look at exceptions in more detail in a later lesson, but basically the JVM will automatically generate an error if you go over the total size of an array. This avoids possible memory corruption.
  3. The System class is a utility class, available from any Java object that provides some basic utility methods that allow interaction with the JVM, the environment and the operating system. The System class is in the java.lang package, which is automatically imported by every class (you don’t need to import it specifically). The System class can more efficiently copy arrays because it can do it “behind the scenes” within the JVM by manipulating the memory directly. The array copy method takes two arrays, the start index of the first array (from where it’ll start copying), and the start index of the second array (where it’ll start copying too), and then how many items to copy.
  4. The java.util package contains more useful utility methods – including more complex data structures. The Arrays class has a number of methods for working with different types of arrays. Take time to review what it has available. Sorting arrays is very simple using this class. Sorting arrays of objects is slightly more complex. Strings work (but not entirely as expected). We’ll look at this in more detail in the future.
  5. Note that because strings are immutable, when we change case (for example) we create a new String, we can’t affect the old one. The last example shows use of brackets to group an expression. Check out the Javadoc for java.lang.String for a complete list of method.
  6. Pass by value passes the actual value. Pass by reference passes a reference to the object. This means that if you change an object in a method, you’re changing the original and not a copy.
  7. We’ll discuss overloading in more detail in a later lesson when we explore more of the fundamentals of OO programming.
  8. The Finalize method is similar to the C++ destructor, but isn’t guaranteed to be called.
  9. Like static, the final modifer can be applied to both methods and variables. We’ll just consider how it affects variables here, as it means something slightly different when applied to a method. Not often used by itself. Usually used in conjunction with static…