SlideShare a Scribd company logo
1 of 55
Standard Edition 6
1
Agenda
• The Java Programming Language
• The Java Platform
• Language Basics
• Object-Oriented Programming Concepts
• Classes and Objects
• Collections Framework
• Exceptions
• Generics
• Reflection
• Concurrency
• JDBC Basics
2
The Java Programming Language
• The Java programming language is a high-level
language that can be characterized by all of the
following buzzwords:
Simple
Object oriented
Distributed
Multithreaded
Dynamic
Architecture neutral
Portable
High performance
Robust
Secure
3
The Java Programming Language
• All source code is first written in plain text files
ending with the .java extension.
• Source files are then compiled into .class files by
the javac compiler.
• A .class file does not contain code that is native to
your processor; it instead contains bytecodes — the
machine language of the Java Virtual
Machine (Java VM).
• The java launcher tool then runs your application
with an instance of the Java Virtual Machine.
4
The Java Programming Language
• All source code is first written in plain text files ending
with the .java extension.
• Source files are then compiled into .class files by the
javac compiler.
• A .class file does not contain code that is native to
your processor; it instead contains bytecodes — the
machine language of the Java Virtual Machine (Java
VM).
• The java launcher tool then runs your application with
an instance of the Java Virtual Machine
5
The Java Platform
• A platform is the hardware or software environment
in which a program runs. Some of the most popular
platforms are Microsoft Windows, Linux, Solaris OS,
and Mac OS. Most platforms can be described as a
combination of the operating system and underlying
hardware. The Java platform differs from most other
platforms in that it's a software-only platform that
runs on top of other hardware-based platforms.
• The Java platform has two components:
The Java Virtual Machine
The Java Application Programming Interface (API)
• As a platform-independent environment, the Java
platform can be a bit slower than native code.
However, advances in compiler and virtual machine
technologies are bringing performance close to that
of native code without threatening portability. 6
Language Basics - Variables
• The Java programming language defines the following kinds of variables:
• Instance Variables (Non-Static Fields) Technically speaking, objects store
their individual states in "non-static fields", that is, fields declared without the static
keyword. Non-static fields are also known as instance variables because their values
are unique to each instance of a class (to each object, in other words); the
currentSpeed of one bicycle is independent from the currentSpeed of another.
• Class Variables (Static Fields) A class variable is any field declared with
the static modifier; this tells the compiler that there is exactly one copy of this
variable in existence, regardless of how many times the class has been instantiated.
A field defining the number of gears for a particular kind of bicycle could be marked
as static since conceptually the same number of gears will apply to all instances.
The code static int numGears=6; would create such a static field. Additionally, the
keyword final could be added to indicate that the number of gears will never
change.
• Local Variables Similar to how an object stores its state in fields, a method will
often store its temporary state in local variables. The syntax for declaring a local
variable is similar to declaring a field (for example, int count = 0;). There is no
special keyword designating a variable as local; that determination comes entirely
from the location in which the variable is declared — which is between the opening
and closing braces of a method. As such, local variables are only visible to the
methods in which they are declared; they are not accessible from the rest of the
class.
• Parameters Recall that the signature for the main method is public static
void main(String[] args). Here, the args variable is the parameter to this
method. The important thing to remember is that parameters are always classified as
"variables" not "fields". This applies to other parameter-accepting constructs as well
(such as constructors and exception handlers) that you'll learn about later in the
7
Primitive Data Types
• The eight primitive data types supported by the Java programming language are:
• byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value
of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving
memory in large arrays, where the memory savings actually matters. They can also be used in
place of int where their limits help to clarify your code; the fact that a variable's range is limited
can serve as a form of documentation.
• short: The short data type is a 16-bit signed two's complement integer. It has a minimum value
of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply:
you can use a short to save memory in large arrays, in situations where the memory savings
actually matters.
• int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -
2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data
type is generally the default choice unless there is a reason (like the above) to choose
something else. This data type will most likely be large enough for the numbers your program
will use, but if you need a wider range of values, use long instead.
• long: The long data type is a 64-bit signed two's complement integer. It has a minimum value
of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
Use this data type when you need a range of values wider than those provided by int.
• float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values
is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language
Specification. As with the recommendations for byte and short, use a float (instead of double) if
you need to save memory in large arrays of floating point numbers. This data type should never
be used for precise values, such as currency. For that, you will need to use
the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful
classes provided by the Java platform.
• double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of
values is beyond the scope of this discussion, but is specified in section4.2.3 of the Java
Language Specification. For decimal values, this data type is generally the default choice. As
mentioned above, this data type should never be used for precise values, such as currency.
• boolean: The boolean data type has only two possible values: true and false. Use this data type
for simple flags that track true/false conditions. This data type represents one bit of information,
8
Operators
9
Operator Name
Assignment
Operator
=
Simple assignment operator
Arithmetic
Operators
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Equality and
Relational
Operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Conditional
Operators
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for if-then-else statement)
Bitwise and Bit Shift
Operators
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
Unary Operators
+
Unary plus operator; indicates positive value
(numbers are positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
- - Decrement operator; decrements a value by 1
!
Logical compliment operator; inverts the value
of a boolean
Type Comparison Operator
instanceof Compares an object to a specified type
public void doSomething(Number
param) {
if( param instanceof Double) {
System.out.println("param
is a Double");
}
}
Operator Precedence
10
Language Basics
• Expressions - An expression is a construct made up of variables, operators, and
method invocations, which are constructed according to the syntax of the language,
that evaluates to a single value. You've already seen examples of expressions,
illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
int result = 1 + 2; // result is now 3
if(value1 == value2)
System.out.println("value1 == value2");
• Statements - Statements are roughly equivalent to sentences in natural languages.
A statement forms a complete unit of execution.
• Blocks - A block is a group of zero or more statements between balanced braces
and can be used anywhere a single statement is allowed. The following
example, BlockDemo, illustrates the use of blocks:
class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}
11
Control Flow Statements - IF
• The statements inside your source files are generally executed from top to
bottom, in the order that they appear. Control flow statements, however,
break up the flow of execution by employing decision making, looping, and
branching, enabling your program to conditionally execute particular blocks
of code.
• The if-then Statement is the most basic of all the control flow statements.
It tells your program to execute a certain section of code only if a
particular test evaluates to true. For example, the Bicycle class could allow
the brakes to decrease the bicycle's speed only if the bicycle is already in
motion. One possible implementation of the apply Brakesmethod could be
as follows:
void applyBrakes(){
if (isMoving){
currentSpeed--;
}
}
• The if-then-else Statement provides a secondary path of execution
when an "if" clause evaluates to false.
void applyBrakes(){
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
} 12
Control Flow Statements - Switch
• The switch Statement - Unlike if-then and if-then-else, the switch statement
allows for any number of possible execution paths. A switch works with
the byte, short, char, and int primitive data types. It also works
with enumerated types (discussed in Classes and Inheritance) and a few
special classes that "wrap" certain primitive types: Character, Byte, Short,
and Integer (discussed in Simple Data Objects ).
13
class SwitchDemo {
public static void main(String[] args) {
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}
Another point of interest is the break statement
after each case. Each break statement
terminates the enclosing switch statement.
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}
Control Flow Statements - While
• The while statement continually executes a block of
statements while a particular condition is true. Its syntax
can be expressed as:
while (expression) {
statement(s)
}
• Using the while statement to print the values from 1
through 10 can be accomplished as in the following
WhileDemo program:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
14
Control Flow Statements – Do While
• The Java programming language also provides a do-
while statement, which can be expressed as follows:
do {
statement(s)
} while (expression);
• The difference between do-while and while is that do-while
evaluates its expression at the bottom of the loop instead of the
top. Therefore, the statements within the do block are always
executed at least once, as shown in the following DoWhileDemo
program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " +
count);
count++;
} while (count <= 11);
}
}
15
Control Flow Statements – For
• The for statement provides a compact way to iterate over a range of
values. Programmers often refer to it as the "for loop" because of the way
in which it repeatedly loops until a particular condition is satisfied. The
general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
• When using this version of the for statement, keep in mind that:
• The initialization expression initializes the loop; it's executed once, as the
loop begins.
• When the termination expression evaluates to false, the loop terminates.
• The increment expression is invoked after each iteration through the loop;
it is perfectly acceptable for this expression to increment or decrement a
value.
• The following program, ForDemo, uses the general form of the for
statement to print the numbers 1 through 10 to standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
} 16
Control Flow Statements – For
• The three expressions of the for loop are optional; an infinite loop can be
created as follows:
for ( ; ; ) { // infinite loop
// your code goes here
}
• The for statement also has another form designed for iteration through
Collections and arrays This form is sometimes referred to as the enhanced
for statement, and can be used to make your loops more compact and
easy to read. To demonstrate, consider the following array, which holds the
numbers 1 through 10:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
• The following program, EnhancedForDemo, uses the enhanced for to loop
through the array:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
17
Control Flow Statements – For-Break
• Branching Statements - Break
• The break statement has two forms: labeled and unlabeled.
• An unlabeled break statement terminates the
innermost switch, for, while, or do-while statement, but a
labeled break terminates an outer statement.
18
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
2000, 8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Found " + searchfor
+ " at index " + i);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } };
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
Object-Oriented Programming
Concepts
• Object - An object is a software bundle of related state and
behavior. Software objects are often used to model the real-world
objects that you find in everyday life.
• Software objects are conceptually similar to real-world objects: they
too consist of state and related behavior. An object stores its state
in fields (variables in some programming languages) and exposes
its behavior through methods (functions in some programming
languages). Methods operate on an object's internal state and serve
as the primary mechanism for object-to-object communication.
Hiding internal state and requiring all interaction to be performed
through an object's methods is known as data encapsulation — a
fundamental principle of object-oriented programming.
• Bundling code into individual software objects provides a number of
benefits, including:
 Modularity: The source code for an object can be written and maintained
independently of the source code for other objects. Once created, an object
can be easily passed around inside the system.
 Information-hiding: By interacting only with an object's methods, the details
of its internal implementation remain hidden from the outside world.
 Code re-use: If an object already exists (perhaps written by another
software developer), you can use that object in your program. This allows
specialists to implement/test/debug complex, task-specific objects, which you
can then trust to run in your own code.
 Pluggability and debugging ease: If a particular object turns out to be
problematic, you can simply remove it from your application and plug in a
19
Object-Oriented Programming
Concepts Class
• Class - is a blueprint or prototype from which
objects are created.
• In object-oriented terms, we say that your bicycle is
an instance of the class of objects known as
bicycles. A class is the blueprint from which
individual objects are created.
20
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue){
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:"+cadence+“
speed:"+speed+" gear:"+gear);
}
}
class BicycleDemo {
public static void main(String[] args) {
// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
Object-Oriented Programming
Concepts Inheritance
• Inheritance provides a powerful and natural mechanism
for organizing and structuring your software.
• Object-oriented programming allows classes
to inherit commonly used state and behavior from other
classes. In this example, Bicycle now becomes
the superclass of MountainBike, RoadBike,
and TandemBike. In the Java programming language,
each class is allowed to have one direct superclass,
and each superclass has the potential for an unlimited
number of subclasses:
• The syntax for creating a subclass is simple. At the
beginning of your class declaration, use
the extends keyword, followed by the name of the class
to inherit from:
class MountainBike extends Bicycle {
// new fields and methods defining a mountain bike would go here
}
21
This gives MountainBike all the same
fields and methods as Bicycle, yet allows
its code to focus exclusively on the
features that make it unique.
Interface
• An interface is a contract between a class and the outside world. When a
class implements an interface, it promises to provide the behavior
published by that interface.
• In its most common form, an interface is a group of related methods with
empty bodies. A bicycle's behavior, if specified as an interface, might
appear as follows:
interface Bicycle {
void changeCadence(int newValue); // wheel revolutions per
minute
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
• To implement this interface, the name of your class would change (to a
particular brand of bicycle, for example, such as ACMEBicycle), and you'd
use the implements keyword in the class declaration:
class ACMEBicycle implements Bicycle {
// remainder of this class implemented as before
}
• Implementing an interface allows a class to become more formal about the
behavior it promises to provide. Interfaces form a contract between the
class and the outside world, and this contract is enforced at build time by
the compiler. If your class claims to implement an interface, all methods
defined by that interface must appear in its source code before the class
will successfully compile.
22
Package
• A package is a namespace that organizes a set of related classes
and interfaces. Conceptually you can think of packages as being
similar to different folders on your computer. You might keep HTML
pages in one folder, images in another, and scripts or applications
in yet another. Because software written in the Java programming
language can be composed of hundreds or thousands of individual
classes, it makes sense to keep things organized by placing related
classes and interfaces into packages.
• The Java platform provides an enormous class library (a set of
packages) suitable for use in your own applications. This library is
known as the "Application Programming Interface", or "API" for
short. Its packages represent the tasks most commonly associated
with general-purpose programming. For example, a String object
contains state and behavior for character strings; a File object
allows a programmer to easily create, delete, inspect, compare, or
modify a file on the filesystem; a Socket object allows for the
creation and use of network sockets; various GUI objects control
buttons and checkboxes and anything else related to graphical user
interfaces. There are literally thousands of classes to choose from.
This allows you, the programmer, to focus on the design of your
particular application, rather than the infrastructure required to make
it work.
• The Java Platform API Specification contains the complete listing
for all packages, interfaces, classes, fields, and methods supplied
by the Java Platform 6, Standard Edition.
23
Classes
• The primary distinguishing feature of OOP languages is the class.
A class is a data structure that can associate the methods which
act on an object with the object itself. In pre-OOP languages
methods and data were separate. In OOP languages they are all
part of classes.
24
public class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int startSpeed, int startGear) {
gear = startGear;
speed = startSpeed;
}
// the Bicycle class has three methods
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
public class MountainBike extends Bicycle {
// the MountainBike subclass has one field
public int seatHeight;
// the MountainBike subclass has one
constructor
public MountainBike(int startHeight, int
startSpeed, int startGear) {
super(startSpeed, startGear);
seatHeight = startHeight;
}
// the MountainBike subclass has one method
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
Objects
• A typical Java program creates many objects, which as you know,
interact by invoking methods. Through these object interactions, a
program can carry out various tasks, such as implementing a GUI,
running an animation, or sending and receiving information over a
network. Here's a small program, called CreateObjectDemo, that
creates three objects: one Point object and two Rectangle objects.
25
public class CreateObjectDemo {
public static void main(String[] args) {
//Declare and create a point object
//and two rectangle objects.
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle();
Rectangle rectTwo = new Rectangle(originOne);
//display rectOne's width, height, and area
System.out.println("Width of rectOne: " + rectOne.width);
System.out.println("Height of rectOne: " + rectOne.height);
System.out.println("Area of rectOne: " + rectOne.getArea());
//set rectTwo's position
rectTwo.origin = originOne;
//display rectTwo's position
System.out.println("X Position of rectTwo: “ + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: “+ rectTwo.origin.y);
//move rectTwo and display its new position
rectTwo.move(40, 72);
System.out.println("X Position of rectTwo: “ + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: “ + rectTwo.origin.y);
}
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
public class Rectangle {
public int width = 0;
public int height = 0;
public Point origin;
// two constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
}
Creating and using objects
26
Returning a Value from a Method
• A method returns to the code that invoked it when it
completes all the statements in the method, reaches
a return statement, or throws an exception (covered later),
whichever occurs first.
• Any method declared void doesn't return a value. It does not
need to contain a return statement, but it may do so. In such
a case, a return statement can be used to branch out of a
control flow block and exit the method and is simply used
like this:
27
// a method for computing the area of the rectangle
public int getArea() {
return width * height;
}
public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike, Environment env)
{
Bicycle fastest;
// code to calculate which bike is faster, given
// each bike's gear and cadence and given
// the environment (terrain and wind)
return fastest;
}
Access Modifiers
• Access level modifiers determine whether other classes can
use a particular field or invoke a particular method. There are
two levels of access control: At the top level—public,
or package-private (no explicit modifier).
• At the member level—public, private, protected, or package-
private (no explicit modifier).
• A class may be declared with the modifier public, in which
case that class is visible to all classes everywhere. If a class
has no modifier (the default, also known as package-private),
it is visible only within its own package (packages are named
groups of related)
• The following table shows the access to members permitted
by each modifier.
28
Nested Classes
• The Java programming language allows you to
define a class within another class. Such a class is
called a nested class and is illustrated here:
• Nested classes are divided into two categories:
static and non-static. Nested classes that are
declared static are simply called static nested
classes. Non-static nested classes are called inner
classes.
29
class OuterClass {
...
class NestedClass
{
...
}
}
class OuterClass {
...
static class StaticNestedClass
{
...
}
class InnerClass {
...
}
}
A nested class is a member of its
enclosing class. Non-static nested classes
(inner classes) have access to other
members of the enclosing class, even if
they are declared private. Static nested
classes do not have access to other
members of the enclosing class. As a
member of the OuterClass, a nested class
can be declared private, public, protected,
Nested Classes
• Why Use Nested Classes?
 Logical grouping of classes—If a class is useful to only one other class,
then it is logical to embed it in that class and keep the two together.
Nesting such "helper classes" makes their package more streamlined.
 Increased encapsulation — Consider two top-level classes, A and B, where
B needs access to members of A that would otherwise be declaredprivate.
By hiding class B within class A, A's members can be declared private and
B can access them. In addition, B itself can be hidden from the outside
world.
 More readable, maintainable code — Nesting small classes within top-level
classes places the code closer to where it is used.
• Static Nested Classes
 As with class methods and variables, a static nested class is associated
with its outer class. And like static class methods, a static nested class
cannot refer directly to instance variables or methods defined in its
enclosing class — it can use them only through an object reference.
 For example, to create an object for the static nested class, use this
syntax:
 OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
• Inner Classes
 As with instance methods and variables, an inner class is associated with
an instance of its enclosing class and has direct access to that object's
methods and fields. Also, because an inner class is associated with an
instance, it cannot define any static members itself.
 To instantiate an inner class, you must first instantiate the outer class.
Then, create the inner object within the outer object with this syntax:
30
Nested Classes – Inner class example
31
public class DataStructure {
//create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
//fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
//print out values of even indices of the array
InnerEvenIterator iterator = this.new InnerEvenIterator();
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
//inner class implements the Iterator pattern
private class InnerEvenIterator {
//start stepping through the array from the beginning
private int next = 0;
public boolean hasNext() {
//check if a current element is the last in the array
return (next <= SIZE - 1);
}
public int getNext() {
//record a value of an even index of the array
int retValue = arrayOfInts[next];
//get the next even element
next += 2;
return retValue;
}
}
public static void main(String s[]) {
//fill the array with integer values and print out only values of even
indices
DataStructure ds = new DataStructure();
ds.printEven();
}
}
Collections Framework
• A collection - is simply an object that groups multiple elements into a
single unit. Collections are used to store, retrieve, manipulate, and
communicate aggregate data. Typically, they represent data items that form
a natural group, such as a poker hand (a collection of cards), a mail folder
(a collection of letters), or a telephone directory (a mapping of names to
phone numbers).
• Collections Framework - A collections framework is a unified architecture
for representing and manipulating collections. All collections frameworks
contain the following:
 Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated of the details of their representation. In object-
oriented languages, interfaces generally form a hierarchy.
 Implementations: These are the concrete implementations of the collection interfaces.
In essence, they are reusable data structures.
 Algorithms: These are the methods that perform useful computations, such as
searching and sorting, on objects that implement collection interfaces. The
algorithms are said to be polymorphic: that is, the same method can be used on
many different implementations of the appropriate collection interface. In essence,
algorithms are reusable functionality.
• Benefits of the Java Collections Framework
 Reduces programming effort
 Increases program speed and quality
 Allows interoperability among unrelated APIs
 Reduces effort to learn and to use new APIs
 Reduces effort to design new APIs
 Fosters software reuse 32
Collections Framework - Interface
• The core collection interfaces encapsulate different types of collections, which are shown
in the figure below.
• The following list describes the core collection interfaces:
• Collection — the root of the collection hierarchy. A collection represents a group of objects
known as its elements. The Collection interface is the least common denominator that all
collections implement and is used to pass collections around and to manipulate them
when maximum generality is desired. Some types of collections allow duplicate elements,
and others do not. Some are ordered and others are unordered. The Java platform
doesn't provide any direct implementations of this interface but provides implementations of
more specific sub-interfaces, such as Set and List.
• Set — a collection that cannot contain duplicate elements. This interface models the
mathematical set abstraction and is used to represent sets, such as the cards comprising
a poker hand, the courses making up a student's schedule, or the processes running on a
machine. See also The Set Interface section.
• List — an ordered collection (sometimes called a sequence). Lists can contain duplicate
elements. The user of a List generally has precise control over where in the list each
element is inserted and can access elements by their integer index (position). If you've
used Vector, you're familiar with the general flavor of List. Also see The List
Interface section.
• Queue — a collection used to hold multiple elements prior to processing. Besides
basic Collection operations, a Queue provides additional insertion, extraction, and
inspection operations.
• Map — an object that maps keys to values. A Map cannot contain duplicate keys; each
key can map to at most one value. If you've used Hashtable, you're already familiar with
the basics of Map. Also see The Map Interface section.
• SortedSet — a Set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering. Sorted sets are used for
33
Collections Framework
34
The Collection Interface
• The Collection Interface - A Collection represents a
group of objects known as its elements.
The Collection interface is used to pass around
collections of objects where maximum generality is
desired.
• Traversing Collections
• Bulk Operations
containsAll- returns true if the target Collection contains all of
the elements in the specified Collection.
addAll -adds all of the elements in the specified Collection to
the target Collection.
removeAll - removes from the target Collection all of its
elements that are also contained in the specified Collection.
retainAll - removes from the target Collection all its elements
that are not also contained in the specified Collection. That is, it
retains only those elements in the target Collection that are also
contained in the specified Collection.
35
for-each Construct
for (Object o : collection)
System.out.println(o);
Iterators
static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}
The Set Interface
• A Collection represents a group of objects known as its elements. The Collection interface
is used to pass around collections of objects where maximum generality is desired.
• The Java platform contains three general-purpose Set implementations: HashSet, TreeSet,
and LinkedHashSet. HashSet, which stores its elements in a hash table, is the best-
performing implementation; however it makes no guarantees concerning the order of
iteration. TreeSet, which stores its elements in a red-black tree, orders its elements based
on their values; it is substantially slower than HashSet. LinkedHashSet, which is
implemented as a hash table with a linked list running through it, orders its elements
based on the order in which they were inserted into the set (insertion-
order). LinkedHashSet spares its clients from the unspecified, generally chaotic ordering
provided by HashSet at a cost that is only slightly higher.
• Example
36
import java.util.*;
public class FindDups {
public static void main(String[] args) {
Set<String> s = new HashSet<String>();
for (String a : args)
if (!s.add(a))
System.out.println("Duplicate detected: " + a);
System.out.println(s.size() + " distinct words: " + s);
}
}
• Bulk Operations
 s1.containsAll(s2)- returns true if s2 is a subset of s1. (s2 is a subset of s1 if
set s1 contains all of the elements in s2.)
 s1.addAll(s2) - transforms s1 into the union of s1 and s2. (The union of two sets is the set
containing all of the elements contained in either set.)
 s1.retainAll(s2) - transforms s1 into the intersection of s1 and s2. (The intersection of two
sets is the set containing only the elements common to both sets.)
 s1.removeAll(s2) - transforms s1 into the (asymmetric) set difference of s1 and s2. (For
example, the set difference of s1 minus s2 is the set containing all of the elements found
The List Interface
• A List is an ordered Collection (sometimes called a sequence). Lists may
contain duplicate elements. In addition to the operations inherited
from Collection, the Listinterface includes operations for the following:
 Positional access — manipulates elements based on their numerical position in the list
 Search — searches for a specified object in the list and returns its numerical position
 Iteration — extends Iterator semantics to take advantage of the list's sequential nature
 Range-view — performs arbitrary range operations on the list.
• List Algorithms - Most polymorphic algorithms in the Collections class apply
specifically to List. Having all these algorithms at your disposal makes it
very easy to manipulate lists. Here's a summary of these algorithms
 sort — sorts a List using a merge sort algorithm, which provides a fast, stable sort.
(A stable sort is one that does not reorder equal elements.)
 Shuffle - randomly permutes the elements in a List.
 Reverse - reverses the order of the elements in a List.
 Rotate - rotates all the elements in a List by a specified distance.
 Swap - swaps the elements at specified positions in a List.
 replaceAll - replaces all occurrences of one specified value with another.
 Fill - overwrites every element in a List with the specified value.
 Copy - copies the source List into the destination List.
 binarySearch - searches for an element in an ordered List using the binary search
algorithm.
 indexOfSubList - returns the index of the first sublist of one List that is equal
to another.
 lastIndexOfSubList - returns the index of the last sublist of one List that is equal to
another. 37
The List Interface
38
import java.util.*;
public class Deal {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: Deal hands cards");
return;
}
int numHands = Integer.parseInt(args[0]);
int cardsPerHand = Integer.parseInt(args[1]);
// Make a normal 52-card deck.
String[] suit = new String[] { "spades", "hearts", "diamonds", "clubs" };
String[] rank = new String[] { "ace","2","3","4","5","6","7","8", "9","10","jack","queen","king" };
List<String> deck = new ArrayList<String>();
for (int i = 0; i < suit.length; i++)
for (int j = 0; j < rank.length; j++)
deck.add(rank[j] + " of " + suit[i]);
// Shuffle the deck.
Collections.shuffle(deck);
if (numHands * cardsPerHand > deck.size()) {
System.out.println("Not enough cards.");
return;
}
for (int i=0; i < numHands; i++)
System.out.println(dealHand(deck, cardsPerHand));
}
public static <E> List<E> dealHand(List<E> deck, int n) {
int deckSize = deck.size();
List<E> handView = deck.subList(deckSize - n, deckSize);
List<E> hand = new ArrayList<E>(handView);
handView.clear();
return hand;
}
}
The Queue Interface
• The Queue Interface - A Queue is a collection for holding
elements prior to processing. Besides basic Collection operations,
queues provide additional insertion, removal, and inspection
operations.
• Each Queue method exists in two forms: (1) one throws an
exception if the operation fails, and (2) the other returns a special
value if the operation fails (either null or false, depending on the
operation). The regular structure of the interface is illustrated in the
following table.
• In the following example program, a queue is used to implement a
countdown timer. The queue is preloaded with all the integer values
from a number specified on the command line to zero, in
descending order. Then, the values are removed from the queue
and printed at one-second intervals.
39
import java.util.*;
public class Countdown {
public static void main(String[] args)
throws InterruptedException {
int time = Integer.parseInt(args[0]);
Queue<Integer> queue = new LinkedList<Integer>();
for (int i = time; i >= 0; i--)
queue.add(i);
while (!queue.isEmpty()) {
System.out.println(queue.remove());
Thread.sleep(1000);
}
}
}
The Map Interface
• A Map is an object that maps keys to values. A map cannot
contain duplicate keys: Each key can map to at most one value. It
models the mathematicalfunction abstraction.
• The Java platform contains three general-purpose Map
implementations: HashMap, TreeMap, and LinkedHashMap. Their
behavior and performance are precisely analogous to HashSet,
TreeSet, and LinkedHashSet.
• The basic operations
of Map (put, get, containsKey, containsValue, size, and isEmpty)
behave exactly like their counterparts in Hashtable. The following
program generates a frequency table of the words found in its
argument list. The frequency table maps each word to the number
of times it occurs in the argument list.
40
import java.util.*;
public class Freq {
public static void main(String[] args) {
Map<String, Integer> m = new HashMap<String, Integer>();
// Initialize frequency table from command line
for (String a : args) {
Integer freq = m.get(a);
m.put(a, (freq == null) ? 1 : freq + 1);
}
System.out.println(m.size() + " distinct words:");
System.out.println(m);
}
}
Set Implementations
• There are three general-purpose Set implementations —
HashSet, TreeSet, and LinkedHashSet. Which of these
three to use is generally straightforward.
• HashSet is much faster than TreeSet (constant-time
versus log-time for most operations) but offers no
ordering guarantees. If you need to use the operations
in the SortedSet interface, or if value-ordered iteration is
required, use TreeSet; otherwise, use HashSet. It's a
fair bet that you'll end up using HashSet most of the
time.
• LinkedHashSet is in some sense intermediate
between HashSet and TreeSet. Implemented as a hash
table with a linked list running through it, it
provides insertion-ordered iteration (least recently
inserted to most recently) and runs nearly as fast
as HashSet. The LinkedHashSet implementation spares
its clients from the unspecified, generally chaotic
ordering provided by HashSet without incurring the
41
List Implementations
• There are two general-purpose List implementations —
ArrayList and LinkedList. Most of the time, you'll
probably use ArrayList, which offers constant-time
positional access and is just plain fast. It does not have
to allocate a node object for each element in the List,
and it can take advantage of System.arraycopy when it
has to move multiple elements at the same time. Think
of ArrayList as Vector without the synchronization
overhead.
• If you frequently add elements to the beginning of the
List or iterate over the List to delete elements from its
interior, you should consider using LinkedList. These
operations require constant-time in a LinkedList and
linear-time in an ArrayList. But you pay a big price in
performance. Positional access requires linear-time in a
LinkedList and constant-time in an ArrayList.
Furthermore, the constant factor for LinkedList is much
worse. If you think you want to use a LinkedList,
measure the performance of your application with both
LinkedList and ArrayList before making your choice;
42
Map Implementations
• The three general-purpose Map implementations are
HashMap, TreeMap and LinkedHashMap. If you need
SortedMap operations or key-ordered Collection-view
iteration, use TreeMap; if you want maximum speed and
don't care about iteration order, use HashMap; if you
want near-HashMap performance and insertion-order
iteration, use LinkedHashMap. In this respect, the
situation for Map is analogous to Set. Likewise,
everything else in the Set Implementations section also
applies to Map implementations.
• LinkedHashMap provides two capabilities that are not
available with LinkedHashSet. When you create a
LinkedHashMap, you can order it based on key access
rather than insertion. In other words, merely looking up
the value associated with a key brings that key to the
end of the map. Also, LinkedHashMap provides the
removeEldestEntry method, which may be overridden to
impose a policy for removing stale mappings
automatically when new mappings are added to the
map. This makes it very easy to implement a custom
43
Queue Implementations
• LinkedList implements the Queue interface,
providing first in, first out (FIFO) queue
operations for add, poll, and so on.
• The PriorityQueue class is a priority queue
based on the heap data structure. This queue
orders elements according to the order specified
at construction time, which can be the elements'
natural ordering or the ordering imposed by an
explicit Comparator.
44
Exceptions
• An exception is an event, which occurs during the execution of a program,
that disrupts the normal flow of the program's instructions.
• When an error occurs within a method, the method creates an object and
hands it off to the runtime system. The object, called an exception object,
contains information about the error, including its type and the state of the
program when the error occurred. Creating an exception object and
handing it to the runtime system is called throwing an exception.
• After a method throws an exception, the runtime system attempts to find
something to handle it. The set of possible "somethings" to handle the
exception is the ordered list of methods that had been called to get to the
method where the error occurred. The list of methods is known as the call
stack (see the next figure).
• The Call Stack
45
Exceptions
• Throwing Exceptions - If a method needs to be able to throw an exception, it has to
declare the exception(s) thrown in the method signature, and then include a throw-
statement in the method. Here is an example:
46
• Catching Exceptions - If a method calls another method that throws checked exceptions,
the calling method is forced to either pass the exception on, or catch it. Catching the
exception is done using a try-catch block. Here is an example:public void callDivide(){
try {
int result = divide(2,1);
System.out.println(result);
} catch (BadNumberException e) {
//do something clever with the exception
System.out.println(e.getMessage());
}
System.out.println("Division attempt done");
}
public void openFile(){
try {
// constructor may throw FileNotFoundException
FileReader reader = new FileReader("someFile");
int i=0;
while(i != -1){
//reader.read() may throw IOException
i = reader.read();
System.out.println((char) i );
}
reader.close();
System.out.println("--- File End ---");
} catch (FileNotFoundException e) {
//do something clever with the exception
} catch (IOException e) {
//do something clever with the exception
}
}
Propagating Exceptions
• You don't have to catch exceptions thrown from other
methods. If you cannot do anything about the exception
where the method throwing it is called, you can just let
the method propagate the exception up the call stack to
the method that called this method. If you do so the
method calling the method that throws the exception
must also declare to throw the exception. Here is how
the callDivide() method would look in that case.
47
public void callDivide() throws BadNumberException{
int result = divide(2,1);
System.out.println(result);
}
public void openFile() throws IOException {
FileReader reader = new FileReader("someFile");
int i=0;
while(i != -1){
i = reader.read();
System.out.println((char) i );
}
reader.close();
System.out.println("--- File End ---");
}
Exceptions - Finally
• You can attach a finally-clause to a try-catch block. The code inside the
finally clause will always be executed, even if an exception is thrown from
within the try or catch block. If your code has a return statement inside the
try or catch block, the code inside the finally-block will get executed before
returning from the method. Here is how a finally clause looks:
48
public void openFile(){
FileReader reader = null;
try {
reader = new FileReader("someFile");
int i=0;
while(i != -1){
i = reader.read();
System.out.println((char) i );
}
} catch (IOException e) {
//do something clever with the exception
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
//do something clever with the exception
}
}
System.out.println("--- File End ---");
}
}
Exception Hierarchies
• All Java exception classes inherit, either directly or indirectly, from class Exception, forming
an inheritance hierarchy. Programmers can extend this hierarchy to create their own
exception classes. Class Error and its subclasses (e.g., OutOfMemoryError) represent
abnormal situations that could happen in the JVM.
49
• Checked Exceptions - Java compiler enforces a catch-or-declare requirement for checked
exceptions. Checked exceptions in Java extend the java.lang.Exception class.
• Unchecked Exceptions - A feature built into the Java language is that Errors and
RuntimeExceptions (and their subclasses– marked in red in Figure 1) are what are called
unchecked exceptions:
 unchecked exceptions can be thrown "at any time";
 methods don't explicitly have to declare that they can throw an unchecked exception;
 callers don't have to handle them explicitly.
Fail Safe Exception Handling
• The last exception thrown in a try-catch-finally block is
the exception that will be propagated up the call stack.
All earlier exceptions will disappear.
50
InputStream input = null;
try{
input = new FileInputStream("myFile.txt");
//do something with the stream
} catch(IOException e){
throw new WrapperException(e);
} finally {
try{
input.close();
} catch(IOException e){
throw new WrapperException(e);
}
}
InputStream input = null;
try{
input = new FileInputStream("myFile.txt");
//do something with the stream
} catch(IOException e){ //first catch block
throw new WrapperException(e);
} finally {
try{
if(input != null) input.close();
} catch(IOException e){//second catch block
throw new WrapperException(e);
}
}
e.g. A non-fail-safe exception handling e.g. An improved version of the code
Generics
• Generics add stability to your code by making more of your bugs
detectable at compile time.
51
public class Box {
private Object object;
public void add(Object object) {
this.object = object;
}
public Object get() {
return object;
}
}
public class BoxDemo1 {
public static void main(String[] args) {
// ONLY place Integer objects into this box!
Box integerBox = new Box();
integerBox.add(new Integer(10));
Integer someInteger = (Integer)integerBox.get();
System.out.println(someInteger);
}
}
public class BoxDemo2 {
public static void main(String[] args) {
// ONLY place Integer objects into this box!
Box integerBox = new Box();
// Imagine this is one part of a large application
// modified by one programmer.
integerBox.add("10"); // note how the type is now String
// ... and this is another, perhaps written
// by a different programmer
Integer someInteger = (Integer)integerBox.get();
System.out.println(someInteger);
}
}
Exception in thread "main"
java.lang.ClassCastException:
java.lang.String cannot be cast to
java.lang.Integer at
BoxDemo2.main(BoxDemo2.java:6)
X
Generics Class
• Let's update our Box class to use generics. We'll first create
a generic type declaration by changing the code "public class Box"
to "public class Box<T>"; this introduces one type variable,
named T, that can be used anywhere inside the class. In this
context, we also say that T is a formal type parameter of
the Box class.
• To reference this generic class from within your own code, you
must perform a generic type invocation, which replaces T with
some concrete value, such as Integer:
52
//Generic version of the Box class.
public class Box<T> {
private T t; // T stands for "Type"
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
public class BoxDemo3 {
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
integerBox.add(new Integer(10));
Integer someInteger = integerBox.get(); // no cast!
System.out.println(someInteger);
}
}
Generics Type Parameter Naming
Conventions
• By convention, type parameter names are single,
uppercase letters. This stands in sharp contrast to the
variable naming conventions that you already know
about, and with good reason: Without this convention, it
would be difficult to tell the difference between a type
variable and an ordinary class or interface name. The
most commonly used type parameter names are:
E - Element (used extensively by the Java Collections
Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
• Generic Methods and Constructors
Type parameters can also be declared within method and
constructor signatures to create generic methods and generic
constructors. This is similar to declaring a generic type, but the
type parameter's scope is limited to the method or constructor
in which it's declared.
53
Generic Methods
• Type parameters can also be declared within
method and constructor signatures to
create generic methods and generic
constructors. This is similar to declaring a
generic type, but the type parameter's scope is
limited to the method or constructor in which it's
declared.
54
Reflection
• Reflection is a feature in the Java programming language. It allows an
executing Java program to examine or "introspect" upon itself, and
manipulate internal properties of the program. For example, it's possible for
a Java class to obtain the names of all its members and display them.
• The ability to examine and manipulate a Java class from within itself may
not sound like very much, but in other programming languages this feature
simply doesn't exist. For example, there is no way in a Pascal, C, or C++
program to obtain information about the functions defined within that
program.
55

More Related Content

What's hot

Chapter1pp
Chapter1ppChapter1pp
Chapter1pp
J. C.
 
Object Oriented Programming lecture 1
Object Oriented Programming lecture 1Object Oriented Programming lecture 1
Object Oriented Programming lecture 1
Anwar Ul Haq
 

What's hot (20)

Chapter1pp
Chapter1ppChapter1pp
Chapter1pp
 
C#
C#C#
C#
 
3 jf h-linearequations
3  jf h-linearequations3  jf h-linearequations
3 jf h-linearequations
 
Tcs NQTExam technical questions
Tcs NQTExam technical questionsTcs NQTExam technical questions
Tcs NQTExam technical questions
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 
java token
java tokenjava token
java token
 
Java stereams
Java stereamsJava stereams
Java stereams
 
Javaiostream
JavaiostreamJavaiostream
Javaiostream
 
Java tokens
Java tokensJava tokens
Java tokens
 
Basic
BasicBasic
Basic
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Lecture02 java
Lecture02 javaLecture02 java
Lecture02 java
 
Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2Week 2: Getting Your Hands Dirty – Part 2
Week 2: Getting Your Hands Dirty – Part 2
 
Basic IO
Basic IOBasic IO
Basic IO
 
Object Oriented Programming lecture 1
Object Oriented Programming lecture 1Object Oriented Programming lecture 1
Object Oriented Programming lecture 1
 
Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Class notes(week 5) on command line arguments
Class notes(week 5) on command line argumentsClass notes(week 5) on command line arguments
Class notes(week 5) on command line arguments
 
Chap1java5th
Chap1java5thChap1java5th
Chap1java5th
 
Javanotes
JavanotesJavanotes
Javanotes
 

Similar to Java platform

M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)
hossamghareb681
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
prat0ham
 

Similar to Java platform (20)

Learning core java
Learning core javaLearning core java
Learning core java
 
Java
JavaJava
Java
 
intro_java (1).pptx
intro_java (1).pptxintro_java (1).pptx
intro_java (1).pptx
 
Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
 
Java SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).pptJava SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).ppt
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
 
basics dart.pdf
basics dart.pdfbasics dart.pdf
basics dart.pdf
 
220 runtime environments
220 runtime environments220 runtime environments
220 runtime environments
 
M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
 
E learning excel vba programming lesson 3
E learning excel vba programming  lesson 3E learning excel vba programming  lesson 3
E learning excel vba programming lesson 3
 
Unit 1
Unit 1Unit 1
Unit 1
 
Aspdot
AspdotAspdot
Aspdot
 
8. data types
8. data types8. data types
8. data types
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed Overview
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
 
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptx
 

Recently uploaded

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
ashishpaul799
 

Recently uploaded (20)

Open Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPointOpen Educational Resources Primer PowerPoint
Open Educational Resources Primer PowerPoint
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).
 
“O BEIJO” EM ARTE .
“O BEIJO” EM ARTE                       .“O BEIJO” EM ARTE                       .
“O BEIJO” EM ARTE .
 
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdf
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdfPost Exam Fun(da) Intra UEM General Quiz - Finals.pdf
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdf
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 
Word Stress rules esl .pptx
Word Stress rules esl               .pptxWord Stress rules esl               .pptx
Word Stress rules esl .pptx
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 
Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17Features of Video Calls in the Discuss Module in Odoo 17
Features of Video Calls in the Discuss Module in Odoo 17
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
philosophy and it's principles based on the life
philosophy and it's principles based on the lifephilosophy and it's principles based on the life
philosophy and it's principles based on the life
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17How to Manage Notification Preferences in the Odoo 17
How to Manage Notification Preferences in the Odoo 17
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. Henry
 
....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf
 
Morse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptxMorse OER Some Benefits and Challenges.pptx
Morse OER Some Benefits and Challenges.pptx
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
 

Java platform

  • 2. Agenda • The Java Programming Language • The Java Platform • Language Basics • Object-Oriented Programming Concepts • Classes and Objects • Collections Framework • Exceptions • Generics • Reflection • Concurrency • JDBC Basics 2
  • 3. The Java Programming Language • The Java programming language is a high-level language that can be characterized by all of the following buzzwords: Simple Object oriented Distributed Multithreaded Dynamic Architecture neutral Portable High performance Robust Secure 3
  • 4. The Java Programming Language • All source code is first written in plain text files ending with the .java extension. • Source files are then compiled into .class files by the javac compiler. • A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine (Java VM). • The java launcher tool then runs your application with an instance of the Java Virtual Machine. 4
  • 5. The Java Programming Language • All source code is first written in plain text files ending with the .java extension. • Source files are then compiled into .class files by the javac compiler. • A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine (Java VM). • The java launcher tool then runs your application with an instance of the Java Virtual Machine 5
  • 6. The Java Platform • A platform is the hardware or software environment in which a program runs. Some of the most popular platforms are Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms. • The Java platform has two components: The Java Virtual Machine The Java Application Programming Interface (API) • As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability. 6
  • 7. Language Basics - Variables • The Java programming language defines the following kinds of variables: • Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another. • Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears=6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change. • Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. • Parameters Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you'll learn about later in the 7
  • 8. Primitive Data Types • The eight primitive data types supported by the Java programming language are: • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation. • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters. • int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of - 2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead. • long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int. • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform. • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency. • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, 8
  • 9. Operators 9 Operator Name Assignment Operator = Simple assignment operator Arithmetic Operators + Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator / Division operator % Remainder operator Equality and Relational Operators == Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to Conditional Operators && Conditional-AND || Conditional-OR ?: Ternary (shorthand for if-then-else statement) Bitwise and Bit Shift Operators ~ Unary bitwise complement << Signed left shift >> Signed right shift >>> Unsigned right shift & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR Unary Operators + Unary plus operator; indicates positive value (numbers are positive without this, however) - Unary minus operator; negates an expression ++ Increment operator; increments a value by 1 - - Decrement operator; decrements a value by 1 ! Logical compliment operator; inverts the value of a boolean Type Comparison Operator instanceof Compares an object to a specified type public void doSomething(Number param) { if( param instanceof Double) { System.out.println("param is a Double"); } }
  • 11. Language Basics • Expressions - An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You've already seen examples of expressions, illustrated in bold below: int cadence = 0; anArray[0] = 100; int result = 1 + 2; // result is now 3 if(value1 == value2) System.out.println("value1 == value2"); • Statements - Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. • Blocks - A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo, illustrates the use of blocks: class BlockDemo { public static void main(String[] args) { boolean condition = true; if (condition) { // begin block 1 System.out.println("Condition is true."); } // end block one else { // begin block 2 System.out.println("Condition is false."); } // end block 2 } } 11
  • 12. Control Flow Statements - IF • The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. • The if-then Statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the apply Brakesmethod could be as follows: void applyBrakes(){ if (isMoving){ currentSpeed--; } } • The if-then-else Statement provides a secondary path of execution when an "if" clause evaluates to false. void applyBrakes(){ if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has already stopped!"); } } 12
  • 13. Control Flow Statements - Switch • The switch Statement - Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects ). 13 class SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break; } } } Another point of interest is the break statement after each case. Each break statement terminates the enclosing switch statement. class SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if ( ((year % 4 == 0) && !(year % 100 == 0))|| (year % 400 == 0) ) numDays = 29; else numDays = 28; break; default: System.out.println("Invalid month."); break; } System.out.println("Number of Days = " + numDays); } }
  • 14. Control Flow Statements - While • The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as: while (expression) { statement(s) } • Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo program: class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } 14
  • 15. Control Flow Statements – Do While • The Java programming language also provides a do- while statement, which can be expressed as follows: do { statement(s) } while (expression); • The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo program: class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 11); } } 15
  • 16. Control Flow Statements – For • The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows: for (initialization; termination; increment) { statement(s) } • When using this version of the for statement, keep in mind that: • The initialization expression initializes the loop; it's executed once, as the loop begins. • When the termination expression evaluates to false, the loop terminates. • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value. • The following program, ForDemo, uses the general form of the for statement to print the numbers 1 through 10 to standard output: class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } 16
  • 17. Control Flow Statements – For • The three expressions of the for loop are optional; an infinite loop can be created as follows: for ( ; ; ) { // infinite loop // your code goes here } • The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10: int[] numbers = {1,2,3,4,5,6,7,8,9,10}; • The following program, EnhancedForDemo, uses the enhanced for to loop through the array: class EnhancedForDemo { public static void main(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println("Count is: " + item); } 17
  • 18. Control Flow Statements – For-Break • Branching Statements - Break • The break statement has two forms: labeled and unlabeled. • An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement. 18 class BreakDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; int searchfor = 12; int i; boolean foundIt = false; for (i = 0; i < arrayOfInts.length; i++) { if (arrayOfInts[i] == searchfor) { foundIt = true; break; } } if (foundIt) { System.out.println("Found " + searchfor + " at index " + i); } else { System.out.println(searchfor + " not in the array"); } } } class BreakWithLabelDemo { public static void main(String[] args) { int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i; int j = 0; boolean foundIt = false; search: for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } } if (foundIt) { System.out.println("Found " + searchfor + " at " + i + ", " + j); } else { System.out.println(searchfor + " not in the array"); } } }
  • 19. Object-Oriented Programming Concepts • Object - An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. • Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming. • Bundling code into individual software objects provides a number of benefits, including:  Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.  Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.  Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.  Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a 19
  • 20. Object-Oriented Programming Concepts Class • Class - is a blueprint or prototype from which objects are created. • In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created. 20 class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue){ cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println("cadence:"+cadence+“ speed:"+speed+" gear:"+gear); } } class BicycleDemo { public static void main(String[] args) { // Create two different Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // Invoke methods on those objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } }
  • 21. Object-Oriented Programming Concepts Inheritance • Inheritance provides a powerful and natural mechanism for organizing and structuring your software. • Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses: • The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here } 21 This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique.
  • 22. Interface • An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. • In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows: interface Bicycle { void changeCadence(int newValue); // wheel revolutions per minute void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } • To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before } • Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. 22
  • 23. Package • A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages. • The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work. • The Java Platform API Specification contains the complete listing for all packages, interfaces, classes, fields, and methods supplied by the Java Platform 6, Standard Edition. 23
  • 24. Classes • The primary distinguishing feature of OOP languages is the class. A class is a data structure that can associate the methods which act on an object with the object itself. In pre-OOP languages methods and data were separate. In OOP languages they are all part of classes. 24 public class Bicycle { // the Bicycle class has two fields public int gear; public int speed; // the Bicycle class has one constructor public Bicycle(int startSpeed, int startGear) { gear = startGear; speed = startSpeed; } // the Bicycle class has three methods public void setGear(int newValue) { gear = newValue; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } } public class MountainBike extends Bicycle { // the MountainBike subclass has one field public int seatHeight; // the MountainBike subclass has one constructor public MountainBike(int startHeight, int startSpeed, int startGear) { super(startSpeed, startGear); seatHeight = startHeight; } // the MountainBike subclass has one method public void setHeight(int newValue) { seatHeight = newValue; } }
  • 25. Objects • A typical Java program creates many objects, which as you know, interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Here's a small program, called CreateObjectDemo, that creates three objects: one Point object and two Rectangle objects. 25 public class CreateObjectDemo { public static void main(String[] args) { //Declare and create a point object //and two rectangle objects. Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(); Rectangle rectTwo = new Rectangle(originOne); //display rectOne's width, height, and area System.out.println("Width of rectOne: " + rectOne.width); System.out.println("Height of rectOne: " + rectOne.height); System.out.println("Area of rectOne: " + rectOne.getArea()); //set rectTwo's position rectTwo.origin = originOne; //display rectTwo's position System.out.println("X Position of rectTwo: “ + rectTwo.origin.x); System.out.println("Y Position of rectTwo: “+ rectTwo.origin.y); //move rectTwo and display its new position rectTwo.move(40, 72); System.out.println("X Position of rectTwo: “ + rectTwo.origin.x); System.out.println("Y Position of rectTwo: “ + rectTwo.origin.y); } public class Point { public int x = 0; public int y = 0; //constructor public Point(int a, int b) { x = a; y = b; } } public class Rectangle { public int width = 0; public int height = 0; public Point origin; // two constructors public Rectangle() { origin = new Point(0, 0); } public Rectangle(Point p) { origin = p; } }
  • 26. Creating and using objects 26
  • 27. Returning a Value from a Method • A method returns to the code that invoked it when it completes all the statements in the method, reaches a return statement, or throws an exception (covered later), whichever occurs first. • Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this: 27 // a method for computing the area of the rectangle public int getArea() { return width * height; } public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike, Environment env) { Bicycle fastest; // code to calculate which bike is faster, given // each bike's gear and cadence and given // the environment (terrain and wind) return fastest; }
  • 28. Access Modifiers • Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control: At the top level—public, or package-private (no explicit modifier). • At the member level—public, private, protected, or package- private (no explicit modifier). • A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related) • The following table shows the access to members permitted by each modifier. 28
  • 29. Nested Classes • The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here: • Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. 29 class OuterClass { ... class NestedClass { ... } } class OuterClass { ... static class StaticNestedClass { ... } class InnerClass { ... } } A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private, public, protected,
  • 30. Nested Classes • Why Use Nested Classes?  Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.  Increased encapsulation — Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declaredprivate. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.  More readable, maintainable code — Nesting small classes within top-level classes places the code closer to where it is used. • Static Nested Classes  As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.  For example, to create an object for the static nested class, use this syntax:  OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); • Inner Classes  As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.  To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: 30
  • 31. Nested Classes – Inner class example 31 public class DataStructure { //create an array private final static int SIZE = 15; private int[] arrayOfInts = new int[SIZE]; public DataStructure() { //fill the array with ascending integer values for (int i = 0; i < SIZE; i++) { arrayOfInts[i] = i; } } public void printEven() { //print out values of even indices of the array InnerEvenIterator iterator = this.new InnerEvenIterator(); while (iterator.hasNext()) { System.out.println(iterator.getNext() + " "); } } //inner class implements the Iterator pattern private class InnerEvenIterator { //start stepping through the array from the beginning private int next = 0; public boolean hasNext() { //check if a current element is the last in the array return (next <= SIZE - 1); } public int getNext() { //record a value of an even index of the array int retValue = arrayOfInts[next]; //get the next even element next += 2; return retValue; } } public static void main(String s[]) { //fill the array with integer values and print out only values of even indices DataStructure ds = new DataStructure(); ds.printEven(); } }
  • 32. Collections Framework • A collection - is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. Typically, they represent data items that form a natural group, such as a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a mapping of names to phone numbers). • Collections Framework - A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:  Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated of the details of their representation. In object- oriented languages, interfaces generally form a hierarchy.  Implementations: These are the concrete implementations of the collection interfaces. In essence, they are reusable data structures.  Algorithms: These are the methods that perform useful computations, such as searching and sorting, on objects that implement collection interfaces. The algorithms are said to be polymorphic: that is, the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality. • Benefits of the Java Collections Framework  Reduces programming effort  Increases program speed and quality  Allows interoperability among unrelated APIs  Reduces effort to learn and to use new APIs  Reduces effort to design new APIs  Fosters software reuse 32
  • 33. Collections Framework - Interface • The core collection interfaces encapsulate different types of collections, which are shown in the figure below. • The following list describes the core collection interfaces: • Collection — the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Collection interface is the least common denominator that all collections implement and is used to pass collections around and to manipulate them when maximum generality is desired. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform doesn't provide any direct implementations of this interface but provides implementations of more specific sub-interfaces, such as Set and List. • Set — a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine. See also The Set Interface section. • List — an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the list each element is inserted and can access elements by their integer index (position). If you've used Vector, you're familiar with the general flavor of List. Also see The List Interface section. • Queue — a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations. • Map — an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value. If you've used Hashtable, you're already familiar with the basics of Map. Also see The Map Interface section. • SortedSet — a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for 33
  • 35. The Collection Interface • The Collection Interface - A Collection represents a group of objects known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired. • Traversing Collections • Bulk Operations containsAll- returns true if the target Collection contains all of the elements in the specified Collection. addAll -adds all of the elements in the specified Collection to the target Collection. removeAll - removes from the target Collection all of its elements that are also contained in the specified Collection. retainAll - removes from the target Collection all its elements that are not also contained in the specified Collection. That is, it retains only those elements in the target Collection that are also contained in the specified Collection. 35 for-each Construct for (Object o : collection) System.out.println(o); Iterators static void filter(Collection<?> c) { for (Iterator<?> it = c.iterator(); it.hasNext(); ) if (!cond(it.next())) it.remove(); }
  • 36. The Set Interface • A Collection represents a group of objects known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired. • The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and LinkedHashSet. HashSet, which stores its elements in a hash table, is the best- performing implementation; however it makes no guarantees concerning the order of iteration. TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet. LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion- order). LinkedHashSet spares its clients from the unspecified, generally chaotic ordering provided by HashSet at a cost that is only slightly higher. • Example 36 import java.util.*; public class FindDups { public static void main(String[] args) { Set<String> s = new HashSet<String>(); for (String a : args) if (!s.add(a)) System.out.println("Duplicate detected: " + a); System.out.println(s.size() + " distinct words: " + s); } } • Bulk Operations  s1.containsAll(s2)- returns true if s2 is a subset of s1. (s2 is a subset of s1 if set s1 contains all of the elements in s2.)  s1.addAll(s2) - transforms s1 into the union of s1 and s2. (The union of two sets is the set containing all of the elements contained in either set.)  s1.retainAll(s2) - transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements common to both sets.)  s1.removeAll(s2) - transforms s1 into the (asymmetric) set difference of s1 and s2. (For example, the set difference of s1 minus s2 is the set containing all of the elements found
  • 37. The List Interface • A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the Listinterface includes operations for the following:  Positional access — manipulates elements based on their numerical position in the list  Search — searches for a specified object in the list and returns its numerical position  Iteration — extends Iterator semantics to take advantage of the list's sequential nature  Range-view — performs arbitrary range operations on the list. • List Algorithms - Most polymorphic algorithms in the Collections class apply specifically to List. Having all these algorithms at your disposal makes it very easy to manipulate lists. Here's a summary of these algorithms  sort — sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.)  Shuffle - randomly permutes the elements in a List.  Reverse - reverses the order of the elements in a List.  Rotate - rotates all the elements in a List by a specified distance.  Swap - swaps the elements at specified positions in a List.  replaceAll - replaces all occurrences of one specified value with another.  Fill - overwrites every element in a List with the specified value.  Copy - copies the source List into the destination List.  binarySearch - searches for an element in an ordered List using the binary search algorithm.  indexOfSubList - returns the index of the first sublist of one List that is equal to another.  lastIndexOfSubList - returns the index of the last sublist of one List that is equal to another. 37
  • 38. The List Interface 38 import java.util.*; public class Deal { public static void main(String[] args) { if (args.length < 2) { System.out.println("Usage: Deal hands cards"); return; } int numHands = Integer.parseInt(args[0]); int cardsPerHand = Integer.parseInt(args[1]); // Make a normal 52-card deck. String[] suit = new String[] { "spades", "hearts", "diamonds", "clubs" }; String[] rank = new String[] { "ace","2","3","4","5","6","7","8", "9","10","jack","queen","king" }; List<String> deck = new ArrayList<String>(); for (int i = 0; i < suit.length; i++) for (int j = 0; j < rank.length; j++) deck.add(rank[j] + " of " + suit[i]); // Shuffle the deck. Collections.shuffle(deck); if (numHands * cardsPerHand > deck.size()) { System.out.println("Not enough cards."); return; } for (int i=0; i < numHands; i++) System.out.println(dealHand(deck, cardsPerHand)); } public static <E> List<E> dealHand(List<E> deck, int n) { int deckSize = deck.size(); List<E> handView = deck.subList(deckSize - n, deckSize); List<E> hand = new ArrayList<E>(handView); handView.clear(); return hand; } }
  • 39. The Queue Interface • The Queue Interface - A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations. • Each Queue method exists in two forms: (1) one throws an exception if the operation fails, and (2) the other returns a special value if the operation fails (either null or false, depending on the operation). The regular structure of the interface is illustrated in the following table. • In the following example program, a queue is used to implement a countdown timer. The queue is preloaded with all the integer values from a number specified on the command line to zero, in descending order. Then, the values are removed from the queue and printed at one-second intervals. 39 import java.util.*; public class Countdown { public static void main(String[] args) throws InterruptedException { int time = Integer.parseInt(args[0]); Queue<Integer> queue = new LinkedList<Integer>(); for (int i = time; i >= 0; i--) queue.add(i); while (!queue.isEmpty()) { System.out.println(queue.remove()); Thread.sleep(1000); } } }
  • 40. The Map Interface • A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematicalfunction abstraction. • The Java platform contains three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap. Their behavior and performance are precisely analogous to HashSet, TreeSet, and LinkedHashSet. • The basic operations of Map (put, get, containsKey, containsValue, size, and isEmpty) behave exactly like their counterparts in Hashtable. The following program generates a frequency table of the words found in its argument list. The frequency table maps each word to the number of times it occurs in the argument list. 40 import java.util.*; public class Freq { public static void main(String[] args) { Map<String, Integer> m = new HashMap<String, Integer>(); // Initialize frequency table from command line for (String a : args) { Integer freq = m.get(a); m.put(a, (freq == null) ? 1 : freq + 1); } System.out.println(m.size() + " distinct words:"); System.out.println(m); } }
  • 41. Set Implementations • There are three general-purpose Set implementations — HashSet, TreeSet, and LinkedHashSet. Which of these three to use is generally straightforward. • HashSet is much faster than TreeSet (constant-time versus log-time for most operations) but offers no ordering guarantees. If you need to use the operations in the SortedSet interface, or if value-ordered iteration is required, use TreeSet; otherwise, use HashSet. It's a fair bet that you'll end up using HashSet most of the time. • LinkedHashSet is in some sense intermediate between HashSet and TreeSet. Implemented as a hash table with a linked list running through it, it provides insertion-ordered iteration (least recently inserted to most recently) and runs nearly as fast as HashSet. The LinkedHashSet implementation spares its clients from the unspecified, generally chaotic ordering provided by HashSet without incurring the 41
  • 42. List Implementations • There are two general-purpose List implementations — ArrayList and LinkedList. Most of the time, you'll probably use ArrayList, which offers constant-time positional access and is just plain fast. It does not have to allocate a node object for each element in the List, and it can take advantage of System.arraycopy when it has to move multiple elements at the same time. Think of ArrayList as Vector without the synchronization overhead. • If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time in an ArrayList. But you pay a big price in performance. Positional access requires linear-time in a LinkedList and constant-time in an ArrayList. Furthermore, the constant factor for LinkedList is much worse. If you think you want to use a LinkedList, measure the performance of your application with both LinkedList and ArrayList before making your choice; 42
  • 43. Map Implementations • The three general-purpose Map implementations are HashMap, TreeMap and LinkedHashMap. If you need SortedMap operations or key-ordered Collection-view iteration, use TreeMap; if you want maximum speed and don't care about iteration order, use HashMap; if you want near-HashMap performance and insertion-order iteration, use LinkedHashMap. In this respect, the situation for Map is analogous to Set. Likewise, everything else in the Set Implementations section also applies to Map implementations. • LinkedHashMap provides two capabilities that are not available with LinkedHashSet. When you create a LinkedHashMap, you can order it based on key access rather than insertion. In other words, merely looking up the value associated with a key brings that key to the end of the map. Also, LinkedHashMap provides the removeEldestEntry method, which may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map. This makes it very easy to implement a custom 43
  • 44. Queue Implementations • LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations for add, poll, and so on. • The PriorityQueue class is a priority queue based on the heap data structure. This queue orders elements according to the order specified at construction time, which can be the elements' natural ordering or the ordering imposed by an explicit Comparator. 44
  • 45. Exceptions • An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. • When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. • After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure). • The Call Stack 45
  • 46. Exceptions • Throwing Exceptions - If a method needs to be able to throw an exception, it has to declare the exception(s) thrown in the method signature, and then include a throw- statement in the method. Here is an example: 46 • Catching Exceptions - If a method calls another method that throws checked exceptions, the calling method is forced to either pass the exception on, or catch it. Catching the exception is done using a try-catch block. Here is an example:public void callDivide(){ try { int result = divide(2,1); System.out.println(result); } catch (BadNumberException e) { //do something clever with the exception System.out.println(e.getMessage()); } System.out.println("Division attempt done"); } public void openFile(){ try { // constructor may throw FileNotFoundException FileReader reader = new FileReader("someFile"); int i=0; while(i != -1){ //reader.read() may throw IOException i = reader.read(); System.out.println((char) i ); } reader.close(); System.out.println("--- File End ---"); } catch (FileNotFoundException e) { //do something clever with the exception } catch (IOException e) { //do something clever with the exception } }
  • 47. Propagating Exceptions • You don't have to catch exceptions thrown from other methods. If you cannot do anything about the exception where the method throwing it is called, you can just let the method propagate the exception up the call stack to the method that called this method. If you do so the method calling the method that throws the exception must also declare to throw the exception. Here is how the callDivide() method would look in that case. 47 public void callDivide() throws BadNumberException{ int result = divide(2,1); System.out.println(result); } public void openFile() throws IOException { FileReader reader = new FileReader("someFile"); int i=0; while(i != -1){ i = reader.read(); System.out.println((char) i ); } reader.close(); System.out.println("--- File End ---"); }
  • 48. Exceptions - Finally • You can attach a finally-clause to a try-catch block. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method. Here is how a finally clause looks: 48 public void openFile(){ FileReader reader = null; try { reader = new FileReader("someFile"); int i=0; while(i != -1){ i = reader.read(); System.out.println((char) i ); } } catch (IOException e) { //do something clever with the exception } finally { if(reader != null){ try { reader.close(); } catch (IOException e) { //do something clever with the exception } } System.out.println("--- File End ---"); } }
  • 49. Exception Hierarchies • All Java exception classes inherit, either directly or indirectly, from class Exception, forming an inheritance hierarchy. Programmers can extend this hierarchy to create their own exception classes. Class Error and its subclasses (e.g., OutOfMemoryError) represent abnormal situations that could happen in the JVM. 49 • Checked Exceptions - Java compiler enforces a catch-or-declare requirement for checked exceptions. Checked exceptions in Java extend the java.lang.Exception class. • Unchecked Exceptions - A feature built into the Java language is that Errors and RuntimeExceptions (and their subclasses– marked in red in Figure 1) are what are called unchecked exceptions:  unchecked exceptions can be thrown "at any time";  methods don't explicitly have to declare that they can throw an unchecked exception;  callers don't have to handle them explicitly.
  • 50. Fail Safe Exception Handling • The last exception thrown in a try-catch-finally block is the exception that will be propagated up the call stack. All earlier exceptions will disappear. 50 InputStream input = null; try{ input = new FileInputStream("myFile.txt"); //do something with the stream } catch(IOException e){ throw new WrapperException(e); } finally { try{ input.close(); } catch(IOException e){ throw new WrapperException(e); } } InputStream input = null; try{ input = new FileInputStream("myFile.txt"); //do something with the stream } catch(IOException e){ //first catch block throw new WrapperException(e); } finally { try{ if(input != null) input.close(); } catch(IOException e){//second catch block throw new WrapperException(e); } } e.g. A non-fail-safe exception handling e.g. An improved version of the code
  • 51. Generics • Generics add stability to your code by making more of your bugs detectable at compile time. 51 public class Box { private Object object; public void add(Object object) { this.object = object; } public Object get() { return object; } } public class BoxDemo1 { public static void main(String[] args) { // ONLY place Integer objects into this box! Box integerBox = new Box(); integerBox.add(new Integer(10)); Integer someInteger = (Integer)integerBox.get(); System.out.println(someInteger); } } public class BoxDemo2 { public static void main(String[] args) { // ONLY place Integer objects into this box! Box integerBox = new Box(); // Imagine this is one part of a large application // modified by one programmer. integerBox.add("10"); // note how the type is now String // ... and this is another, perhaps written // by a different programmer Integer someInteger = (Integer)integerBox.get(); System.out.println(someInteger); } } Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer at BoxDemo2.main(BoxDemo2.java:6) X
  • 52. Generics Class • Let's update our Box class to use generics. We'll first create a generic type declaration by changing the code "public class Box" to "public class Box<T>"; this introduces one type variable, named T, that can be used anywhere inside the class. In this context, we also say that T is a formal type parameter of the Box class. • To reference this generic class from within your own code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer: 52 //Generic version of the Box class. public class Box<T> { private T t; // T stands for "Type" public void add(T t) { this.t = t; } public T get() { return t; } } public class BoxDemo3 { public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); integerBox.add(new Integer(10)); Integer someInteger = integerBox.get(); // no cast! System.out.println(someInteger); } }
  • 53. Generics Type Parameter Naming Conventions • By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name. The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework) K - Key N - Number T - Type V - Value S,U,V etc. - 2nd, 3rd, 4th types • Generic Methods and Constructors Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors. This is similar to declaring a generic type, but the type parameter's scope is limited to the method or constructor in which it's declared. 53
  • 54. Generic Methods • Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors. This is similar to declaring a generic type, but the type parameter's scope is limited to the method or constructor in which it's declared. 54
  • 55. Reflection • Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them. • The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages this feature simply doesn't exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about the functions defined within that program. 55