SlideShare a Scribd company logo
1 of 52
JAVA OVERVIEW
LESSON 2
What you we learn
Should learn the basics of the Java language
All Java language needed for Android development
Object-oriented software basics
What is Java?
Java is a language and a platform originated by
Sun Microsystems.
Java’s syntax is partly patterned after the C and
C++ languages
Help shorten the learning curve.
Classes
Object-oriented applications represent entities as
objects.
Each object encapsulates an entity’s attributes and
behaviors.
Objects do not pop out of thin air; they must be
instantiated (created) from something.
Languages such as C++ and Java refer to this
“something” as a class.
Declaring a Class
Declares a class
named
CheckingAccount.
By convention, a
class’s name begins
with an uppercase
letter.
class CheckingAccount
{
// fields
// methods
// other declarations
}
Fields
After declaring a class, you can declare variables
in the class’s body.
Entity attributes
Class attributes
Declaring Fields
Declares two fields
name owner and
balance.
By convention, a field’s
name begins with a
lowercase letter
class CheckingAccount
{
String owner;
int balance;
int theCounter;
}
TYPE NAME
Java Primitive Types
Primitive Type Reserved Size Min Max
Boolean boolean -- -- --
Character char 16 bit
Byte Integer byte 8-bit -128 127
Short Integer short 16-bit -2^15 2^15 -1
Integer int 32-bit -2^31 2^31 -1
Long Integer long 64-bit -2^63 2^63 - 1
Floating-point float 32-bit IEEE 754 IEEE 754
Double Precision floating-point double 64-bit IEEE 754 IEEE 754
Arrays
a multi-value variable
each element holds
one value.
ex. of array based field
class WeatherData
{
String country;
String[ ] cities;
double[ ] [ ] temp;
}
ARRAY TYPE
Static Fields
counter is a class field.
a field associates with
a class instead of the
class’s object.
one object associate
with all created class of
the same type
class CheckingAccount
{
String owner;
int balance;
static int counter;
}
KEYWORD
Initializing Fields
Is it common to initialize an instance field to a
value.
fields are initialized to default values when the
object is created.
String = “”;
int = 0;
objects = null;
Example
class WeatherData
{
String country = “United States”;
String[ ] cities = {“Chicago”, “New York”};
double[ ] [ ] temperatures = {{0.0, 0.0}, {0.0, 0.0}};
}
Expressions &
Operators
Operator Symbol
Addition +
Array Index [ ]
Assignment =
Bitwise &
Bitwise complement ~
Bitwise exclusive OR ^
Bitwise inclusive OR |
Cast ( type )
Compound assignment
+=, -=, *=, /=, %=, &=, |=, ^=,
<<=, >>=, >>>=
Expressions &
Operators Continued...
Operator Symbol
Conditional ?:
Conditional AND &&
Conditional OR ||
Division /
Equality “==”
Inequality !=
Left shift <<
Logical AND &
Logical complement !
Logical exclusive OR ^
Expressions &
Operators Continued...
Operator Symbol
Logical inclusive OR |
Member access .
Method call ( )
Multiplication *
Object creation new
Decrement --
Increment ++
Relational greater than >
Relational greater than equal
to
>=
Expressions &
Operators Continued...
Operator Symbol
Relational less than <
Relational less than equal to <=
Relational type checking instanceof
Remainder %
Signed right shift >>
String concatenation +
Subtraction -
Unary minus -
Unary plus +
Unsigned right shift >>>
Casting
Casting is used to
convert one type to
another.
Only certain types can
be casted to another
type.
char c = ‘A’;
// incorrect way
byte b = c;
// correct way
byte b = (byte) c;
CAST
Read-only Fields
final keyword
final used for fields that
are read-only.
this field must be
initialized in the
constructor or field’s
declaration.
constant can be
accomplished by using
static with final.
class Employee
{
final int AGE = 26;
// constant ex.
final static int RETIRE_AGE = 65;
}
Declaring Methods
Declare methods within a
class’s body.
Should return a type.
followed by an identifier
that names the method.
followed by a parameter
list.
followed by a body.
class CheckingAccount
{
String owner;
int balance;
static int counter;
void printBalance()
{
// function
}
}
Implementing Methods
void printBalance()
{
int magnitude = (balance < 0) ? -balance : balance;
String balanceRep = (balance < 0) ? “(“ : “”;
balanceRep += magnitude;
balanceRep += (balance < 0) ? “)” : “”;
System.out.println(balanceRep);
}
Decisions & Loops
if statement
switch statement
for loops
while loops
do while loops
break and continue
If statements
void printBalance()
{
if (balance < 0)
System.out.println(balance);
else if (balance == 0)
System.out.println(“zero balance”);
else
System.out.println(balance * balance);
}
Switch Statement
switch (selector expression)
{
case value1: statement1 [break;]
case value2: statement2 [break;]
case valueN: statementN [break;]
[default: statement]
}
int balance = 5;
switch(balance)
{
case 1: balance = 42; break;
case 2: balance = 43; break;
default: balance = 99;
}
For Loops
for ([ initialize ]; [ test ]; [ update ])
statement;
public static void doSomething(int size)
{
for (int i = 0; i < size; i++)
{
// inside the for loop
}
}
While Loops
while (Boolean expression)
statement
int ch = 0;
while (ch != ‘C’ && ch != ‘c’)
{
System.out.println(“Press C or c to continue”);
ch = System.in.read();
}
Do While Loops
do
statement
while(Boolean expression);
int ch;
do
{
System.out.println(“Press C or c to continue”);
}
while (ch != ‘C’ && ch != ‘c’);
Break and Continue
break
continue
break outer
continue outer
Constructors
Constructors are named blocks of code, declared in
class bodies for constructing objects by initializing
their instance fields and other developer needs.
class CheckingAccount
{
String owner;
int balance;
// Constructor start
CheckingAccount(String acctOwner, int acctBalance)
{
owner = acctOwner;
balance = acctBalance;
}
}
Access Control
Public
A field, method, or constructor that is accessible from anywhere.
A source file can only contain one public class per source file.
Protected
A field, method, or constructor that is accessible from all classes in of subclasses.
Private
A field, method, or constructor that is can not be accessed beyond the class in which it is
declared.
Package-private ?
Example of Access
public class Employee
{
private String name;
public Employee(String name)
{
setName(name);
}
public void setName(string empName)
{
name = empName;
}
}
Creating Objects and
Arrays
Employee emp = new Employee(“John”, “Doe”);
OBJECT TYPE CREATE MEMORY SPACE AND
RETURN OBJECT’S REFERENCE
CONSTRUCTOR
Accessing Fields
// Create object
Account account = new Account(23423);
// Call the field
int id = account.customerId;
// id contains the number 23423
PUBLIC FIELD
Calling Methods
// Create object
Account account = new Account(23423);
// Call the method
int id = account.getCustomerId(); // id = 23423
// set the id to 87873
account.setCustomerId(87873);
id = account.getCustomerId(); // id = 87873
PUBLIC METHOD
PUBLIC METHOD
Chained Instance
Method Calls
Account myAccount = new Account(9723);
// multiple method calls
myAccount.deposit(1000).printBalance();
PUBLIC METHOD #1PUBLIC METHOD #2
Garbage Collections
Objects are created via reserved word new
how are they destroyed?
Garbage collector is code that runs in the
background and checks for unreferenced objects.
When it discovers an unreferenced object, the
garbage collector removes it from the heap
(memory)
Garbage Collector++
// referenced object
Account myAcc = new Account(9734);
// unreferenced object
myAcc = null;
Inheritance or
Extending
public abstract class Animal
{
public abstract void eat();
}
public class Bird extends Animal
{
@Override
public final void eat()
{
}
}
Inheritance Method
Override
public abstract class Animal
{
public abstract void eat();
}
public class Bird extends Animal
{
@Override
public final void eat()
{
}
}
Runtime Type
Identification
public class A
{
// stuff
}
void main( )
{
int h = 0;
A obj = new A( );
if ( ( h instanceof A) || ( obj instanceof A ) )
{
// Do something
}
}
Interfaces
Interfaces are like contracts
An agreement between two class or parties that
says these methods and properties are to be in
both classes and will not change.
Good for two classes that have nothing in common
to have common methods and properties.
Implementing
Interfaces
public interface ICountable
{
int getCount();
}
public abstract class Animal implements ICountable
{
@Override
public final int getCount()
{
return 1;
}
}
Extending Interfaces
interface IDrawable
{
void draw(int color);
}
interface Fillable extends IDrawable
{
void fill(int color);
}
Anonymous Classes
abstract class Speaker
{
abstract void speak();
}
public class ACDemo
{
public ACDemo()
{
new Speaker()
{
void speak()
{
System.out.println(“Hello”);
}
}
.speak();
}
}
Local Classes
public class EnclosingClass
{
public void m (final int x)
{
final int y = x*2;
class LocalClass
{
int a = x;
int b = y;
}
}
}
Packages
Packages are the same as namespaces in C++
A package is a unique namespace that can contain
a combination of top-level class, types, and sub-
packages.
Package name must be unique
Importing
import is the same as #include in C++
Includes a package to use with the current file.
Uses the import keyword
Exceptions
try
{
// try some code here.
}
catch ( SomeException ex )
{
}
Collections
ArrayList
LinkedList
TreeSet
HashSet
LinkedHashSet
EnumSet
PriorityQueue
Etc....
ArrayList
// Create new ArrayList
ArrayList<String> listOfStuff = new ArrayList<String>();
// Add items to list
listOfStuff.add(“NewString”);
// Get item
String s = list.get(0);
Enumerations
public class Weekday
{
public final static int SUNDAY = 0;
public final static int MONDAY = 1;
....
}
public enum Coin
{
PENNY,
NICKEL,
DIME,
QUARTER
}
Canvas Quiz
new Java.class.finalize(
);

More Related Content

What's hot

Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continuedRatnaJava
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IEduardo Bergavera
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming conceptsGanesh Karthik
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++Mohamad Al_hsan
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrongJulien Wetterwald
 
Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindiappsdevelopment
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objectsRai University
 

What's hot (20)

Write First C++ class
Write First C++ classWrite First C++ class
Write First C++ class
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
class c++
class c++class c++
class c++
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
Class
ClassClass
Class
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
1204csharp
1204csharp1204csharp
1204csharp
 
New lambdas
New lambdasNew lambdas
New lambdas
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
 
Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2Synapseindia strcture of dotnet development part 2
Synapseindia strcture of dotnet development part 2
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 

Viewers also liked

Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)Michael Shrove
 
Ch14-Software Engineering 9
Ch14-Software Engineering 9Ch14-Software Engineering 9
Ch14-Software Engineering 9Ian Sommerville
 
Building Digital Success: I need a BA
Building Digital Success: I need a BABuilding Digital Success: I need a BA
Building Digital Success: I need a BAIIBA UK Chapter
 
Taking Swift for a spin
Taking Swift for a spinTaking Swift for a spin
Taking Swift for a spinThoughtworks
 
Swift Office Hours - Launch Event
Swift Office Hours - Launch EventSwift Office Hours - Launch Event
Swift Office Hours - Launch EventNareg Khoshafian
 
Accelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business AnalysisAccelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business AnalysisIIBA UK Chapter
 
Starlight taylor swift for women 2014 عطر ستريت تيلور سويفت نسائي
Starlight taylor swift for women  2014  عطر  ستريت  تيلور سويفت نسائيStarlight taylor swift for women  2014  عطر  ستريت  تيلور سويفت نسائي
Starlight taylor swift for women 2014 عطر ستريت تيلور سويفت نسائيAZ Panor
 
Background Audio Playback
Background Audio PlaybackBackground Audio Playback
Background Audio PlaybackKorhan Bircan
 
ios_summit_2016_korhan
ios_summit_2016_korhanios_summit_2016_korhan
ios_summit_2016_korhanKorhan Bircan
 
Swift Buildpack for Cloud Foundry
Swift Buildpack for Cloud FoundrySwift Buildpack for Cloud Foundry
Swift Buildpack for Cloud FoundryRobert Gogolok
 
The Power of an Agile BA
The Power of an Agile BAThe Power of an Agile BA
The Power of an Agile BAIIBA UK Chapter
 
Agile Product Development: Scaled Delivery
Agile Product Development: Scaled DeliveryAgile Product Development: Scaled Delivery
Agile Product Development: Scaled DeliveryIIBA UK Chapter
 
Between Business Demands and Thriving Technology: The 'Modern Day BA'
Between Business Demands and Thriving Technology: The 'Modern Day BA'Between Business Demands and Thriving Technology: The 'Modern Day BA'
Between Business Demands and Thriving Technology: The 'Modern Day BA'IIBA UK Chapter
 

Viewers also liked (20)

Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)Android and IOS UI Development (Android 5.0 and iOS 9.0)
Android and IOS UI Development (Android 5.0 and iOS 9.0)
 
Ch14-Software Engineering 9
Ch14-Software Engineering 9Ch14-Software Engineering 9
Ch14-Software Engineering 9
 
Sensors 9
Sensors   9Sensors   9
Sensors 9
 
Building Digital Success: I need a BA
Building Digital Success: I need a BABuilding Digital Success: I need a BA
Building Digital Success: I need a BA
 
Taking Swift for a spin
Taking Swift for a spinTaking Swift for a spin
Taking Swift for a spin
 
3 swift 컬렉션
3 swift 컬렉션3 swift 컬렉션
3 swift 컬렉션
 
Swift Office Hours - Launch Event
Swift Office Hours - Launch EventSwift Office Hours - Launch Event
Swift Office Hours - Launch Event
 
Storage 8
Storage   8Storage   8
Storage 8
 
Accelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business AnalysisAccelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business Analysis
 
Basics 4
Basics   4Basics   4
Basics 4
 
Starlight taylor swift for women 2014 عطر ستريت تيلور سويفت نسائي
Starlight taylor swift for women  2014  عطر  ستريت  تيلور سويفت نسائيStarlight taylor swift for women  2014  عطر  ستريت  تيلور سويفت نسائي
Starlight taylor swift for women 2014 عطر ستريت تيلور سويفت نسائي
 
Korhan bircan
Korhan bircanKorhan bircan
Korhan bircan
 
Background Audio Playback
Background Audio PlaybackBackground Audio Playback
Background Audio Playback
 
ios_summit_2016_korhan
ios_summit_2016_korhanios_summit_2016_korhan
ios_summit_2016_korhan
 
Just get out of the way
Just get out of the wayJust get out of the way
Just get out of the way
 
Swift Buildpack for Cloud Foundry
Swift Buildpack for Cloud FoundrySwift Buildpack for Cloud Foundry
Swift Buildpack for Cloud Foundry
 
Going Swiftly Functional
Going Swiftly FunctionalGoing Swiftly Functional
Going Swiftly Functional
 
The Power of an Agile BA
The Power of an Agile BAThe Power of an Agile BA
The Power of an Agile BA
 
Agile Product Development: Scaled Delivery
Agile Product Development: Scaled DeliveryAgile Product Development: Scaled Delivery
Agile Product Development: Scaled Delivery
 
Between Business Demands and Thriving Technology: The 'Modern Day BA'
Between Business Demands and Thriving Technology: The 'Modern Day BA'Between Business Demands and Thriving Technology: The 'Modern Day BA'
Between Business Demands and Thriving Technology: The 'Modern Day BA'
 

Similar to Java 2

Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Ali Raza Zaidi
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfARORACOCKERY2111
 
3 functions and class
3   functions and class3   functions and class
3 functions and classtrixiacruz
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptxEpsiba1
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developementfrwebhelp
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.pptMikeAdva
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingHock Leng PUAH
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console ProgramHock Leng PUAH
 

Similar to Java 2 (20)

java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Clean Code
Clean CodeClean Code
Clean Code
 
Java session4
Java session4Java session4
Java session4
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Classes
ClassesClasses
Classes
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.ppt
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 

Java 2

  • 2. What you we learn Should learn the basics of the Java language All Java language needed for Android development Object-oriented software basics
  • 3. What is Java? Java is a language and a platform originated by Sun Microsystems. Java’s syntax is partly patterned after the C and C++ languages Help shorten the learning curve.
  • 4. Classes Object-oriented applications represent entities as objects. Each object encapsulates an entity’s attributes and behaviors. Objects do not pop out of thin air; they must be instantiated (created) from something. Languages such as C++ and Java refer to this “something” as a class.
  • 5. Declaring a Class Declares a class named CheckingAccount. By convention, a class’s name begins with an uppercase letter. class CheckingAccount { // fields // methods // other declarations }
  • 6. Fields After declaring a class, you can declare variables in the class’s body. Entity attributes Class attributes
  • 7. Declaring Fields Declares two fields name owner and balance. By convention, a field’s name begins with a lowercase letter class CheckingAccount { String owner; int balance; int theCounter; } TYPE NAME
  • 8. Java Primitive Types Primitive Type Reserved Size Min Max Boolean boolean -- -- -- Character char 16 bit Byte Integer byte 8-bit -128 127 Short Integer short 16-bit -2^15 2^15 -1 Integer int 32-bit -2^31 2^31 -1 Long Integer long 64-bit -2^63 2^63 - 1 Floating-point float 32-bit IEEE 754 IEEE 754 Double Precision floating-point double 64-bit IEEE 754 IEEE 754
  • 9. Arrays a multi-value variable each element holds one value. ex. of array based field class WeatherData { String country; String[ ] cities; double[ ] [ ] temp; } ARRAY TYPE
  • 10. Static Fields counter is a class field. a field associates with a class instead of the class’s object. one object associate with all created class of the same type class CheckingAccount { String owner; int balance; static int counter; } KEYWORD
  • 11. Initializing Fields Is it common to initialize an instance field to a value. fields are initialized to default values when the object is created. String = “”; int = 0; objects = null;
  • 12. Example class WeatherData { String country = “United States”; String[ ] cities = {“Chicago”, “New York”}; double[ ] [ ] temperatures = {{0.0, 0.0}, {0.0, 0.0}}; }
  • 13. Expressions & Operators Operator Symbol Addition + Array Index [ ] Assignment = Bitwise & Bitwise complement ~ Bitwise exclusive OR ^ Bitwise inclusive OR | Cast ( type ) Compound assignment +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=
  • 14. Expressions & Operators Continued... Operator Symbol Conditional ?: Conditional AND && Conditional OR || Division / Equality “==” Inequality != Left shift << Logical AND & Logical complement ! Logical exclusive OR ^
  • 15. Expressions & Operators Continued... Operator Symbol Logical inclusive OR | Member access . Method call ( ) Multiplication * Object creation new Decrement -- Increment ++ Relational greater than > Relational greater than equal to >=
  • 16. Expressions & Operators Continued... Operator Symbol Relational less than < Relational less than equal to <= Relational type checking instanceof Remainder % Signed right shift >> String concatenation + Subtraction - Unary minus - Unary plus + Unsigned right shift >>>
  • 17. Casting Casting is used to convert one type to another. Only certain types can be casted to another type. char c = ‘A’; // incorrect way byte b = c; // correct way byte b = (byte) c; CAST
  • 18. Read-only Fields final keyword final used for fields that are read-only. this field must be initialized in the constructor or field’s declaration. constant can be accomplished by using static with final. class Employee { final int AGE = 26; // constant ex. final static int RETIRE_AGE = 65; }
  • 19. Declaring Methods Declare methods within a class’s body. Should return a type. followed by an identifier that names the method. followed by a parameter list. followed by a body. class CheckingAccount { String owner; int balance; static int counter; void printBalance() { // function } }
  • 20. Implementing Methods void printBalance() { int magnitude = (balance < 0) ? -balance : balance; String balanceRep = (balance < 0) ? “(“ : “”; balanceRep += magnitude; balanceRep += (balance < 0) ? “)” : “”; System.out.println(balanceRep); }
  • 21. Decisions & Loops if statement switch statement for loops while loops do while loops break and continue
  • 22. If statements void printBalance() { if (balance < 0) System.out.println(balance); else if (balance == 0) System.out.println(“zero balance”); else System.out.println(balance * balance); }
  • 23. Switch Statement switch (selector expression) { case value1: statement1 [break;] case value2: statement2 [break;] case valueN: statementN [break;] [default: statement] } int balance = 5; switch(balance) { case 1: balance = 42; break; case 2: balance = 43; break; default: balance = 99; }
  • 24. For Loops for ([ initialize ]; [ test ]; [ update ]) statement; public static void doSomething(int size) { for (int i = 0; i < size; i++) { // inside the for loop } }
  • 25. While Loops while (Boolean expression) statement int ch = 0; while (ch != ‘C’ && ch != ‘c’) { System.out.println(“Press C or c to continue”); ch = System.in.read(); }
  • 26. Do While Loops do statement while(Boolean expression); int ch; do { System.out.println(“Press C or c to continue”); } while (ch != ‘C’ && ch != ‘c’);
  • 28. Constructors Constructors are named blocks of code, declared in class bodies for constructing objects by initializing their instance fields and other developer needs. class CheckingAccount { String owner; int balance; // Constructor start CheckingAccount(String acctOwner, int acctBalance) { owner = acctOwner; balance = acctBalance; } }
  • 29. Access Control Public A field, method, or constructor that is accessible from anywhere. A source file can only contain one public class per source file. Protected A field, method, or constructor that is accessible from all classes in of subclasses. Private A field, method, or constructor that is can not be accessed beyond the class in which it is declared. Package-private ?
  • 30. Example of Access public class Employee { private String name; public Employee(String name) { setName(name); } public void setName(string empName) { name = empName; } }
  • 31. Creating Objects and Arrays Employee emp = new Employee(“John”, “Doe”); OBJECT TYPE CREATE MEMORY SPACE AND RETURN OBJECT’S REFERENCE CONSTRUCTOR
  • 32. Accessing Fields // Create object Account account = new Account(23423); // Call the field int id = account.customerId; // id contains the number 23423 PUBLIC FIELD
  • 33. Calling Methods // Create object Account account = new Account(23423); // Call the method int id = account.getCustomerId(); // id = 23423 // set the id to 87873 account.setCustomerId(87873); id = account.getCustomerId(); // id = 87873 PUBLIC METHOD PUBLIC METHOD
  • 34. Chained Instance Method Calls Account myAccount = new Account(9723); // multiple method calls myAccount.deposit(1000).printBalance(); PUBLIC METHOD #1PUBLIC METHOD #2
  • 35. Garbage Collections Objects are created via reserved word new how are they destroyed? Garbage collector is code that runs in the background and checks for unreferenced objects. When it discovers an unreferenced object, the garbage collector removes it from the heap (memory)
  • 36. Garbage Collector++ // referenced object Account myAcc = new Account(9734); // unreferenced object myAcc = null;
  • 37. Inheritance or Extending public abstract class Animal { public abstract void eat(); } public class Bird extends Animal { @Override public final void eat() { } }
  • 38. Inheritance Method Override public abstract class Animal { public abstract void eat(); } public class Bird extends Animal { @Override public final void eat() { } }
  • 39. Runtime Type Identification public class A { // stuff } void main( ) { int h = 0; A obj = new A( ); if ( ( h instanceof A) || ( obj instanceof A ) ) { // Do something } }
  • 40. Interfaces Interfaces are like contracts An agreement between two class or parties that says these methods and properties are to be in both classes and will not change. Good for two classes that have nothing in common to have common methods and properties.
  • 41. Implementing Interfaces public interface ICountable { int getCount(); } public abstract class Animal implements ICountable { @Override public final int getCount() { return 1; } }
  • 42. Extending Interfaces interface IDrawable { void draw(int color); } interface Fillable extends IDrawable { void fill(int color); }
  • 43. Anonymous Classes abstract class Speaker { abstract void speak(); } public class ACDemo { public ACDemo() { new Speaker() { void speak() { System.out.println(“Hello”); } } .speak(); } }
  • 44. Local Classes public class EnclosingClass { public void m (final int x) { final int y = x*2; class LocalClass { int a = x; int b = y; } } }
  • 45. Packages Packages are the same as namespaces in C++ A package is a unique namespace that can contain a combination of top-level class, types, and sub- packages. Package name must be unique
  • 46. Importing import is the same as #include in C++ Includes a package to use with the current file. Uses the import keyword
  • 47. Exceptions try { // try some code here. } catch ( SomeException ex ) { }
  • 49. ArrayList // Create new ArrayList ArrayList<String> listOfStuff = new ArrayList<String>(); // Add items to list listOfStuff.add(“NewString”); // Get item String s = list.get(0);
  • 50. Enumerations public class Weekday { public final static int SUNDAY = 0; public final static int MONDAY = 1; .... } public enum Coin { PENNY, NICKEL, DIME, QUARTER }