SlideShare a Scribd company logo
Arrays
Objectives
 Declare and create arrays of primitive, class
or array types
 How to initialize the elements of an array
 No of elements in the array
 Create a multi-dimensional array
 Write code to copy array values from one
array type to another
Declaring Arrays
 Group data Objects of the same type
 Declare arrays of primitive or class types
char s[];
Point p[]; //Where point is a class
char[] s;
Point[] p;
 Create space for a reference
 An array is an object; it is created with new
Creating Arrays
 Use the new Keyword to create an array object
 Example
public char[] createArray(){
char[] a;
a = new char[26];
for(int i =0;i<26;i++){
a[i]=‘A’+i;
}
return a;
}
Execution Stack
Heap Memory
A
B
C
Z
char
main
this
a
createArray
Creating Arrays
 Object Array
public Point[] createArray(){
Point[] p;
p = new Point[10];
for(int i =0;i<26;i++){
p[i]=new Point(I,I+1);
}
return p;
}
Execution Stack
Point[]
main
this
p
Heap Memory
createArray
x
y
x
y
x
y
Point
Initialize Arrays
String names[];
names=new String[3];
names[0]=“George”;
names[1]=“Jen”;
names[2]=“Simon”;
MyDate date[];
dates=new MyDate[2];
dates[0]=new
MyDate(22,7,1976);
dates[1]=new
MyDate(22,12,1974);
String names[]={
“George”,”Jen”,”Simon”
};
MyDate dates[]={
new MyDate(22,7,1976),
new MyDate(22,12,1974)
};
Multi-Dimensional Arrays
 Arrays of arrays
int twoDim[][] = new int[4][];
twoDim[0]=new int[5];
twoDim[1]=new int[5];
int twoDim[][]=new int[][4]; //illegal
Multi-Dimensional Arrays
 Non-rectangular array of arrays
twoDim[0] =new int[2];
twoDim[1]=new int[4];
twoDim[2]=new int[6];
twoDim[3]=new int[8];
 Shorthand to create 2 Dimensional arrays
int twoDim[] = new int[4][5];
Array Bounds
 All array subscripts begin at 0
int list[]=new int[10];
for(int i = 0;i<list.length;i++){
System.out.println(list[i]);
}
Array Resizing
 Cannot Resize an Array
 Can use the same reference variable to refer
to an entirely new array
int elements[] = new int[6];
elements = new int[10];
 In this case, the first array is effectively lost unless
another reference to it is retained elsewhere.
Copying Arrays
 The System.arrayCopy() method
//original Copy
int elements[]={1,2,3,4,5,6};
//new larger array
int hold[]={10,9,8,7,6,5,4,3,2,1};
//Copy all of the elements array to the
//hold array starting at 0 th index
System.arrayCopy(elements,0,hold,0,elements.length);
Inheritance
The is a Relationship
 The Employee Class
+name: String=“”
+salary:double
+birthDate:Date
Employee
+getDetails():String
public class Employee{
public String name=“”;
public double salary;
public Date birthDate;
public String getDetails(){
----
}
}
The is a Relationship
 The Manager Class
+name: String=“”
+salary:double
+birthDate:Date
+department:String
Manager
+getDetails():String
public class Manager{
public String name=“”;
public double salary;
public Date birthDate;
public String department;
public String getDetails(){
----
}
}
The is a Relationship
+name: String=“”
+salary:double
+birthDate:Date
Employee
+getDetails():String
public class Employee{
public String name=“”;
public double salary;
public Date birthDate;
public String getDetails(){---}
}
public class Manager extends Employee{
public String department=“”;
}
+department:String=“”
Employee
Single Inheritance
 When a class inherits from only one class, it
is called single inheritance
 Single Inheritance makes code more reliable
 Interfaces provide the benefits of multiple
inheritance without drawbacks
Constructors are not inherited
 A subclass inherits all methods and variables
from the super class (parent class)
 A subclass does not inherit the constructor
from the super class
 Note-
 A Parent constructor is always called in addition
to a child Constructor
Polymorphism
 Polymorphism is the ability to have different forms.
 An object has only one form
 A reference variable can refer to objects of different
forms
Employee emp1=new Manager();
//Illegal attempt to assign Manager attribute
Emp1.department=“Sales”
Heterogeneous Collections
 Collection of objects of the same class type are called
homogeneous Collection
MyDate[] dates=new MyDate[2];
dates[0]=new MyDate(22,12,1976);
dates[1]=new MyDate(22,7,1974);
 Collection of objects with different class types are called
heterogeneous collections
Employee[] staff = new Employee[1024];
Staff[0]=new Manager();
Staff[1]=new Employee();
Staff[2]=new Engineer();
Polymorphic Arguments
 Because a manager is an Employee
//in the Employee class
public TaxRate findTaxRate(Employee e){
--
}
//elsewhere in the application class
Manager m = new Manager();
:
TaxRate t = findTaxRate(m);
The instanceof Operator
public class Employee extends Object
public class Manager extends Employee
public class Engineer extends Employee
---------------------------------------
public void doSomething(Employee e){
if(e instanceof Manager){
//Process a Manager
}
else if(e instanceof Engineer){
//Process an Engineer
}
else{
//Process other type of Employee
}
}
Casting Objects
 Use instanceof to test the type of an object
 Restore full functionality of an Object casting
 Check for proper casting using the following
guidelines
 Casts up hierarchy are done implicitly
 Downward casts must be to sub class and checked by the
compiler
 The object type is checked at runtime when runtime
errors can occur
The has a Relationship
public class Vehicle{
private Engine theEngine;
public Engine getEngine(){
return theEngine;
}
}
Truck Engine1
Access Control
 Variables and Methods can be at one of four access
levels; public, protected, default or private.
 Classes can be public or default
Modifier Same Class Same Pkg Subclass Universe
public Yes Yes Yes Yes
protected Yes Yes Yes
default Yes Yes
private Yes
Protected access is provided to subclasses in different Packages
Overloading Method Names
 Example
public void println(int i);
public void println(float f);
public void println(String s);
 Argument lists must differ
 Return types can be different
Overloading Constructors
 As with methods constructors can be
overloaded
 Example
public Employee(String name, double salary, Date dob)
public Employee(String name, double salary)
public Employee(String name, Date dob)
 Argument list must differ
 The this reference can be used at the first line of a constructor to call
another constructor
Overriding Methods
 A subclass can modify behavior inherited
from a parent class
 A subclass can create a method with different
functionality than the parent’s method with
the same
 Name
 Return Type
 Argument List
Overriding Methods
 Virtual method invocation
Employee e = new Manager();
e.getDetails();
 Compile-time type and runtime type
Rules about Overridden Methods
 Must have a return type that is identical to
the method it overrides
 Cannot be less accessible than the method it
overrides
The super Keyword
 super is used in a class to refer to its
superclass
 super is used to refer to the members of
superclass, both data attributes and methods
 Behavior invoked does not have to be in the
superclass, it can be further up in the
hierarchy
Invoking Parent Class Constructors
 To invoke a parent constructor you must place a
call to super in the first line of the Constructor
 You can call a specific parent constructor by the
arguments that you use in the call to super
 If no this or super call is used in a constructor, then
an implicit call to super() is added by the compiler
 If the parent class does not supply a non-private
“default” constructor, then a compiler warning will be
issued
Constructing and Initializing
Objects
 Memory is allocated and default initialization
occurs
 Instance variable initialization uses these steps
recursively
1. Bind Constructor parameters
2. If explicit this(), call recursively and skip to step 5
3. Call recursively the implicit or explicit super call,
except for Object
4. Execute explicit instance variable initializes
5. Execute the body of the current Constructor
The Object class
 The Object class is the root of all classes in
Java
 A class declaration with no extends clause,
implicitly uses “extends Object”
The == Operator Vs equals
Method
 The = = operator determines is two references are
identical to each other
 The equals method determines if objects are
equal.
 User classes can override the equals method to
implement a domain-specific test for equality
 Note: You should override the hashcode method, if
you override the equals method
toString Method
 Converts an Object to a String
 Used during string concatenation
 Override this method to provide information about
a user-defined object in readable format
 Primitive types are converted to a String using
the wrapper class’s toString static method
Wrapper Classes
Primitive Wrapper Class
boolean Boolean
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double

More Related Content

PPT
java tutorial 2
PPT
Basic c#
PPTX
class and objects
PPT
14. Defining Classes
PPTX
classes and objects in C++
PPTX
Learn Concept of Class and Object in C# Part 3
PPT
Visula C# Programming Lecture 6
PPTX
java tutorial 2
Basic c#
class and objects
14. Defining Classes
classes and objects in C++
Learn Concept of Class and Object in C# Part 3
Visula C# Programming Lecture 6

What's hot (19)

PDF
C# Summer course - Lecture 4
PDF
Object Oriented Programming using C++ Part III
PPT
Object-Oriented Programming Using C++
PDF
C# Summer course - Lecture 3
PPT
C++ oop
PPTX
Classes in c++ (OOP Presentation)
PDF
Object Oriented Programming using C++ Part I
PPTX
SPF Getting Started - Console Program
PDF
Object Oriented Programming With C++
PDF
Built in classes in java
PPT
C++ classes tutorials
PPTX
Object oriented programming in C++
PPT
C++ classes tutorials
PPT
C++ tutorials
PPTX
Oops presentation
PPTX
Presentation 4th
PDF
Introduction to C++
PPTX
11. Objects and Classes
PPTX
2CPP14 - Abstraction
C# Summer course - Lecture 4
Object Oriented Programming using C++ Part III
Object-Oriented Programming Using C++
C# Summer course - Lecture 3
C++ oop
Classes in c++ (OOP Presentation)
Object Oriented Programming using C++ Part I
SPF Getting Started - Console Program
Object Oriented Programming With C++
Built in classes in java
C++ classes tutorials
Object oriented programming in C++
C++ classes tutorials
C++ tutorials
Oops presentation
Presentation 4th
Introduction to C++
11. Objects and Classes
2CPP14 - Abstraction
Ad

Similar to java tutorial 3 (20)

PPTX
‫Chapter3 inheritance
PPTX
Inheritance
PPT
Java tutorial for Beginners and Entry Level
PPT
11slide.ppt
PPT
Object Oriented Programming Concept.Hello
PPT
11slide
PPT
Java Reflection
ODP
Ppt of c++ vs c#
PPT
Java oops PPT
PDF
OOPs Concepts - Android Programming
PDF
OOPs & Inheritance Notes
PPT
Inheritance
PPT
025466482929 -OOP with Java Development Kit.ppt
PPT
02-OOP with Java.ppt
PPTX
PPTX
Object oriented concepts
PDF
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
PPSX
Oop features java presentationshow
PPTX
Lecture 4_Java Method-constructor_imp_keywords
‫Chapter3 inheritance
Inheritance
Java tutorial for Beginners and Entry Level
11slide.ppt
Object Oriented Programming Concept.Hello
11slide
Java Reflection
Ppt of c++ vs c#
Java oops PPT
OOPs Concepts - Android Programming
OOPs & Inheritance Notes
Inheritance
025466482929 -OOP with Java Development Kit.ppt
02-OOP with Java.ppt
Object oriented concepts
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
Oop features java presentationshow
Lecture 4_Java Method-constructor_imp_keywords
Ad

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Business Ethics Teaching Materials for college
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Institutional Correction lecture only . . .
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Classroom Observation Tools for Teachers
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Complications of Minimal Access Surgery at WLH
Final Presentation General Medicine 03-08-2024.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Business Ethics Teaching Materials for college
Microbial diseases, their pathogenesis and prophylaxis
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Institutional Correction lecture only . . .
Microbial disease of the cardiovascular and lymphatic systems
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Basic Mud Logging Guide for educational purpose
PPH.pptx obstetrics and gynecology in nursing
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Types and Its function , kingdom of life
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Classroom Observation Tools for Teachers
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Complications of Minimal Access Surgery at WLH

java tutorial 3

  • 2. Objectives  Declare and create arrays of primitive, class or array types  How to initialize the elements of an array  No of elements in the array  Create a multi-dimensional array  Write code to copy array values from one array type to another
  • 3. Declaring Arrays  Group data Objects of the same type  Declare arrays of primitive or class types char s[]; Point p[]; //Where point is a class char[] s; Point[] p;  Create space for a reference  An array is an object; it is created with new
  • 4. Creating Arrays  Use the new Keyword to create an array object  Example public char[] createArray(){ char[] a; a = new char[26]; for(int i =0;i<26;i++){ a[i]=‘A’+i; } return a; } Execution Stack Heap Memory A B C Z char main this a createArray
  • 5. Creating Arrays  Object Array public Point[] createArray(){ Point[] p; p = new Point[10]; for(int i =0;i<26;i++){ p[i]=new Point(I,I+1); } return p; } Execution Stack Point[] main this p Heap Memory createArray x y x y x y Point
  • 6. Initialize Arrays String names[]; names=new String[3]; names[0]=“George”; names[1]=“Jen”; names[2]=“Simon”; MyDate date[]; dates=new MyDate[2]; dates[0]=new MyDate(22,7,1976); dates[1]=new MyDate(22,12,1974); String names[]={ “George”,”Jen”,”Simon” }; MyDate dates[]={ new MyDate(22,7,1976), new MyDate(22,12,1974) };
  • 7. Multi-Dimensional Arrays  Arrays of arrays int twoDim[][] = new int[4][]; twoDim[0]=new int[5]; twoDim[1]=new int[5]; int twoDim[][]=new int[][4]; //illegal
  • 8. Multi-Dimensional Arrays  Non-rectangular array of arrays twoDim[0] =new int[2]; twoDim[1]=new int[4]; twoDim[2]=new int[6]; twoDim[3]=new int[8];  Shorthand to create 2 Dimensional arrays int twoDim[] = new int[4][5];
  • 9. Array Bounds  All array subscripts begin at 0 int list[]=new int[10]; for(int i = 0;i<list.length;i++){ System.out.println(list[i]); }
  • 10. Array Resizing  Cannot Resize an Array  Can use the same reference variable to refer to an entirely new array int elements[] = new int[6]; elements = new int[10];  In this case, the first array is effectively lost unless another reference to it is retained elsewhere.
  • 11. Copying Arrays  The System.arrayCopy() method //original Copy int elements[]={1,2,3,4,5,6}; //new larger array int hold[]={10,9,8,7,6,5,4,3,2,1}; //Copy all of the elements array to the //hold array starting at 0 th index System.arrayCopy(elements,0,hold,0,elements.length);
  • 13. The is a Relationship  The Employee Class +name: String=“” +salary:double +birthDate:Date Employee +getDetails():String public class Employee{ public String name=“”; public double salary; public Date birthDate; public String getDetails(){ ---- } }
  • 14. The is a Relationship  The Manager Class +name: String=“” +salary:double +birthDate:Date +department:String Manager +getDetails():String public class Manager{ public String name=“”; public double salary; public Date birthDate; public String department; public String getDetails(){ ---- } }
  • 15. The is a Relationship +name: String=“” +salary:double +birthDate:Date Employee +getDetails():String public class Employee{ public String name=“”; public double salary; public Date birthDate; public String getDetails(){---} } public class Manager extends Employee{ public String department=“”; } +department:String=“” Employee
  • 16. Single Inheritance  When a class inherits from only one class, it is called single inheritance  Single Inheritance makes code more reliable  Interfaces provide the benefits of multiple inheritance without drawbacks
  • 17. Constructors are not inherited  A subclass inherits all methods and variables from the super class (parent class)  A subclass does not inherit the constructor from the super class  Note-  A Parent constructor is always called in addition to a child Constructor
  • 18. Polymorphism  Polymorphism is the ability to have different forms.  An object has only one form  A reference variable can refer to objects of different forms Employee emp1=new Manager(); //Illegal attempt to assign Manager attribute Emp1.department=“Sales”
  • 19. Heterogeneous Collections  Collection of objects of the same class type are called homogeneous Collection MyDate[] dates=new MyDate[2]; dates[0]=new MyDate(22,12,1976); dates[1]=new MyDate(22,7,1974);  Collection of objects with different class types are called heterogeneous collections Employee[] staff = new Employee[1024]; Staff[0]=new Manager(); Staff[1]=new Employee(); Staff[2]=new Engineer();
  • 20. Polymorphic Arguments  Because a manager is an Employee //in the Employee class public TaxRate findTaxRate(Employee e){ -- } //elsewhere in the application class Manager m = new Manager(); : TaxRate t = findTaxRate(m);
  • 21. The instanceof Operator public class Employee extends Object public class Manager extends Employee public class Engineer extends Employee --------------------------------------- public void doSomething(Employee e){ if(e instanceof Manager){ //Process a Manager } else if(e instanceof Engineer){ //Process an Engineer } else{ //Process other type of Employee } }
  • 22. Casting Objects  Use instanceof to test the type of an object  Restore full functionality of an Object casting  Check for proper casting using the following guidelines  Casts up hierarchy are done implicitly  Downward casts must be to sub class and checked by the compiler  The object type is checked at runtime when runtime errors can occur
  • 23. The has a Relationship public class Vehicle{ private Engine theEngine; public Engine getEngine(){ return theEngine; } } Truck Engine1
  • 24. Access Control  Variables and Methods can be at one of four access levels; public, protected, default or private.  Classes can be public or default Modifier Same Class Same Pkg Subclass Universe public Yes Yes Yes Yes protected Yes Yes Yes default Yes Yes private Yes Protected access is provided to subclasses in different Packages
  • 25. Overloading Method Names  Example public void println(int i); public void println(float f); public void println(String s);  Argument lists must differ  Return types can be different
  • 26. Overloading Constructors  As with methods constructors can be overloaded  Example public Employee(String name, double salary, Date dob) public Employee(String name, double salary) public Employee(String name, Date dob)  Argument list must differ  The this reference can be used at the first line of a constructor to call another constructor
  • 27. Overriding Methods  A subclass can modify behavior inherited from a parent class  A subclass can create a method with different functionality than the parent’s method with the same  Name  Return Type  Argument List
  • 28. Overriding Methods  Virtual method invocation Employee e = new Manager(); e.getDetails();  Compile-time type and runtime type
  • 29. Rules about Overridden Methods  Must have a return type that is identical to the method it overrides  Cannot be less accessible than the method it overrides
  • 30. The super Keyword  super is used in a class to refer to its superclass  super is used to refer to the members of superclass, both data attributes and methods  Behavior invoked does not have to be in the superclass, it can be further up in the hierarchy
  • 31. Invoking Parent Class Constructors  To invoke a parent constructor you must place a call to super in the first line of the Constructor  You can call a specific parent constructor by the arguments that you use in the call to super  If no this or super call is used in a constructor, then an implicit call to super() is added by the compiler  If the parent class does not supply a non-private “default” constructor, then a compiler warning will be issued
  • 32. Constructing and Initializing Objects  Memory is allocated and default initialization occurs  Instance variable initialization uses these steps recursively 1. Bind Constructor parameters 2. If explicit this(), call recursively and skip to step 5 3. Call recursively the implicit or explicit super call, except for Object 4. Execute explicit instance variable initializes 5. Execute the body of the current Constructor
  • 33. The Object class  The Object class is the root of all classes in Java  A class declaration with no extends clause, implicitly uses “extends Object”
  • 34. The == Operator Vs equals Method  The = = operator determines is two references are identical to each other  The equals method determines if objects are equal.  User classes can override the equals method to implement a domain-specific test for equality  Note: You should override the hashcode method, if you override the equals method
  • 35. toString Method  Converts an Object to a String  Used during string concatenation  Override this method to provide information about a user-defined object in readable format  Primitive types are converted to a String using the wrapper class’s toString static method
  • 36. Wrapper Classes Primitive Wrapper Class boolean Boolean byte Byte char Character short Short int Integer long Long float Float double Double