SlideShare a Scribd company logo
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(
);
Ad

More Related Content

What's hot (20)

Write First C++ class
Write First C++ classWrite First C++ class
Write First C++ class
Learn By Watch
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
RatnaJava
 
class c++
class c++class c++
class c++
vinay chauhan
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
talha ijaz
 
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
Eduardo Bergavera
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
Ganesh Karthik
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 
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
Eduardo 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
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
Mohamed Krar
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
UniSoftCorner Pvt Ltd India.
 
Class
ClassClass
Class
Swarup Kumar Boro
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
Terry Yoast
 
1204csharp
1204csharp1204csharp
1204csharp
g_hemanth17
 
New lambdas
New lambdasNew lambdas
New lambdas
Wiem Zine Elabidine
 
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
Julien 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 2
Synapseindiappsdevelopment
 
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
Rai University
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
RatnaJava
 
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
Eduardo Bergavera
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
Ganesh 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 II
Eduardo 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 wrong
Julien 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 2
Synapseindiappsdevelopment
 
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
Rai University
 

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)
Michael Shrove
 
Ch14-Software Engineering 9
Ch14-Software Engineering 9Ch14-Software Engineering 9
Ch14-Software Engineering 9
Ian Sommerville
 
Sensors 9
Sensors   9Sensors   9
Sensors 9
Michael Shrove
 
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
IIBA UK Chapter
 
Taking Swift for a spin
Taking Swift for a spinTaking Swift for a spin
Taking Swift for a spin
Thoughtworks
 
3 swift 컬렉션
3 swift 컬렉션3 swift 컬렉션
3 swift 컬렉션
Changwon National University
 
Swift Office Hours - Launch Event
Swift Office Hours - Launch EventSwift Office Hours - Launch Event
Swift Office Hours - Launch Event
Nareg Khoshafian
 
Storage 8
Storage   8Storage   8
Storage 8
Michael Shrove
 
Accelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business AnalysisAccelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business Analysis
IIBA UK Chapter
 
Basics 4
Basics   4Basics   4
Basics 4
Michael Shrove
 
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
 
Korhan bircan
Korhan bircanKorhan bircan
Korhan bircan
Korhan Bircan
 
Background Audio Playback
Background Audio PlaybackBackground Audio Playback
Background Audio Playback
Korhan Bircan
 
ios_summit_2016_korhan
ios_summit_2016_korhanios_summit_2016_korhan
ios_summit_2016_korhan
Korhan Bircan
 
Just get out of the way
Just get out of the wayJust get out of the way
Just get out of the way
IIBA UK Chapter
 
Swift Buildpack for Cloud Foundry
Swift Buildpack for Cloud FoundrySwift Buildpack for Cloud Foundry
Swift Buildpack for Cloud Foundry
Robert Gogolok
 
Going Swiftly Functional
Going Swiftly FunctionalGoing Swiftly Functional
Going Swiftly Functional
Pushkar Kulkarni
 
The Power of an Agile BA
The Power of an Agile BAThe Power of an Agile BA
The Power of an Agile BA
IIBA UK Chapter
 
Agile Product Development: Scaled Delivery
Agile Product Development: Scaled DeliveryAgile Product Development: Scaled Delivery
Agile Product Development: Scaled Delivery
IIBA 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
 
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 9
Ian 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 BA
IIBA UK Chapter
 
Taking Swift for a spin
Taking Swift for a spinTaking Swift for a spin
Taking Swift for a spin
Thoughtworks
 
Swift Office Hours - Launch Event
Swift Office Hours - Launch EventSwift Office Hours - Launch Event
Swift Office Hours - Launch Event
Nareg Khoshafian
 
Accelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business AnalysisAccelerating Agile by Adding Business Analysis
Accelerating Agile by Adding Business Analysis
IIBA 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 Playback
Korhan Bircan
 
ios_summit_2016_korhan
ios_summit_2016_korhanios_summit_2016_korhan
ios_summit_2016_korhan
Korhan Bircan
 
Swift Buildpack for Cloud Foundry
Swift Buildpack for Cloud FoundrySwift Buildpack for Cloud Foundry
Swift Buildpack for Cloud Foundry
Robert Gogolok
 
The Power of an Agile BA
The Power of an Agile BAThe Power of an Agile BA
The Power of an Agile BA
IIBA UK Chapter
 
Agile Product Development: Scaled Delivery
Agile Product Development: Scaled DeliveryAgile Product Development: Scaled Delivery
Agile Product Development: Scaled Delivery
IIBA 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
 
Ad

Similar to Java 2 (20)

java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
Tushar Desarda
 
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
Ali 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.pdf
ARORACOCKERY2111
 
classes and objects.pdfggggggggffffffffgggf
classes and objects.pdfggggggggffffffffgggfclasses and objects.pdfggggggggffffffffgggf
classes and objects.pdfggggggggffffffffgggf
gurpreetk8199
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
trixiacruz
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
InfinityWorld3
 
C Language fundamentals hhhhhhhhhhhh.ppt
C Language fundamentals hhhhhhhhhhhh.pptC Language fundamentals hhhhhhhhhhhh.ppt
C Language fundamentals hhhhhhhhhhhh.ppt
lalita57189
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
Intro C# Book
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
Clean Code
Clean CodeClean Code
Clean Code
Nascenia IT
 
C++ Presen. tation.pptx
C++ Presen.                   tation.pptxC++ Presen.                   tation.pptx
C++ Presen. tation.pptx
mohitsinha7739289047
 
Java session4
Java session4Java session4
Java session4
Jigarthacker
 
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
Ramrao Desai
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
frwebhelp
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie 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++ Exams
MuhammadTalha436
 
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyjChapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
Classes
ClassesClasses
Classes
Swarup Boro
 
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
Ali 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.pdf
ARORACOCKERY2111
 
classes and objects.pdfggggggggffffffffgggf
classes and objects.pdfggggggggffffffffgggfclasses and objects.pdfggggggggffffffffgggf
classes and objects.pdfggggggggffffffffgggf
gurpreetk8199
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
trixiacruz
 
C Language fundamentals hhhhhhhhhhhh.ppt
C Language fundamentals hhhhhhhhhhhh.pptC Language fundamentals hhhhhhhhhhhh.ppt
C Language fundamentals hhhhhhhhhhhh.ppt
lalita57189
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
Intro 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 Level
Ramrao Desai
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
frwebhelp
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie 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++ Exams
MuhammadTalha436
 
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyjChapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
Ad

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 }