Java platform

4,768 views 53 slides Oct 12, 2010
Slide 1
Slide 1 of 53
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53

About This Presentation

Introduction to the Java platform, Java virtual machine, loading classes, Java API


Slide Content

Introduction to Java Introduction to Java
Programming - Programming -
internalsinternals

ContentsContents
•Computer Programming OverviewComputer Programming Overview
•Your First Java ProgramYour First Java Program
•Java Technology OverviewJava Technology Overview
•Eclipse IDEEclipse IDE

ContentsContents
•The Structure of Java ProgramsThe Structure of Java Programs
•Keywords and IdentifiersKeywords and Identifiers
•Data TypesData Types
•Integral, Textual, Floating-PointIntegral, Textual, Floating-Point
•EnumerationsEnumerations
•Variables, Declarations, Assignments, Variables, Declarations, Assignments,
OperatorsOperators

ContentsContents
•Expressions and StatementsExpressions and Statements
•Logical StatementsLogical Statements
•Loop StatementsLoop Statements
•Console Input and OutputConsole Input and Output
•Arrays and Array ManipulationArrays and Array Manipulation
•Using the Java API DocumentationUsing the Java API Documentation

What is Computer What is Computer
Programming?Programming?

Define: Computer Define: Computer
ProgrammingProgramming
•Computer Programming: creating a Computer Programming: creating a
sequence of instructions to enable the sequence of instructions to enable the
computer to do somethingcomputer to do something
Definition by GoogleDefinition by Google

Programming PhasesProgramming Phases
•Define a task/problemDefine a task/problem
•Plan your solutionPlan your solution
•Find suitable algorithm to solve itFind suitable algorithm to solve it
•Find suitable data structures to useFind suitable data structures to use
•Write codeWrite code
•Fix program error (bugs)Fix program error (bugs)
•Make your customer happyMake your customer happy
= Specification= Specification
= Design= Design
= Implementation= Implementation
= Testing & = Testing &
DebuggingDebugging
= Deployment= Deployment

Your First Java ProgramYour First Java Program

First Look at Java CodeFirst Look at Java Code
Sample Java Source code:Sample Java Source code:
public class HelloJava {public class HelloJava {
public static void main(String args[]) {public static void main(String args[]) {
System.out.println("Hello, Java");System.out.println("Hello, Java");
}}
}}

Java Code – How It Works?Java Code – How It Works?
public class HelloJava {public class HelloJava {
public static void main(String args[]){public static void main(String args[]){
System.out.println("Hello, Java");System.out.println("Hello, Java");
}}
}}
Define a class called Define a class called
""HelloJavaHelloJava""
Define the Define the main()main()
method – the program method – the program
entry pointentry point
Print a text on the console Print a text on the console
calling the method "calling the method "println()println()" "
of the system's standard outputof the system's standard output

Java Is Case Sensitive!Java Is Case Sensitive!
public class HelloJava {public class HelloJava {
public static void Main(String args[]){public static void Main(String args[]){
system.out.PrintLn("Hello, Java");system.out.PrintLn("Hello, Java");
}}
}}
The keyword The keyword classclass
should be lowercaseshould be lowercase
The class The class SystemSystem
should be in should be in
""Pascal CasePascal Case""
The method The method
println()println() should should
be in be in ""camelcamel CaseCase""
The correct method The correct method
name is name is main()main()

Java Code Should Be Well Java Code Should Be Well
FormattedFormatted
public class HelloJava {public class HelloJava {
public static void main(String args[])public static void main(String args[]) {{
System.out.println("Hello, Java");System.out.println("Hello, Java");
}}
}}
The The {{ symbol should symbol should
be on the same line.be on the same line.
The block after the The block after the
{{ symbol should be symbol should be
indented by a TABindented by a TAB
Class names Class names
should start with should start with
a CAPITAL lettera CAPITAL letter
The The {{ symbol should symbol should
be on the same line.be on the same line.
The The }} symbol should be symbol should be
under the beginning of the under the beginning of the
line with corresponding line with corresponding {{

Example of Bad FormattingExample of Bad Formatting
public public
class HelloJava class HelloJava
{public static {public static
void void
main(String args[]){main(String args[]){
System.out.printlnSystem.out.println
("Hello, Java");("Hello, Java");
System.out.println("Hello, Java");} }System.out.println("Hello, Java");} }
Such formatting Such formatting
makes the code makes the code
unreadableunreadable

File Names Match Class File Names Match Class
Names!Names!
•In Java all public classes should be in a file In Java all public classes should be in a file
name matching their namename matching their name
•For example the class For example the class HelloJavaHelloJava should be should be
in the file in the file HelloJava.javaHelloJava.java
public class HelloJava {public class HelloJava {
public static void main(String args[]){public static void main(String args[]){
System.out.println("Hello, Java");System.out.println("Hello, Java");
}}
}}
HelloJava.javaHelloJava.java

Your First Java ProgramYour First Java Program
Live DemoLive Demo

Welcome to Java TechnologyWelcome to Java Technology

Why Java?Why Java?
•Meets the emerging software development Meets the emerging software development
challenges of its timechallenges of its time
•Platform independencePlatform independence
•Run on wide variety of hardwareRun on wide variety of hardware
•Desktop, server-side, embeddedDesktop, server-side, embedded
•Easier to develop, administer, maintainEasier to develop, administer, maintain
•Object-oriented approachObject-oriented approach
•Built-in securityBuilt-in security
•Network mobility (mobile code)Network mobility (mobile code)

History of JavaHistory of Java
•Project “Oak” began in mid 80’s at Sun Project “Oak” began in mid 80’s at Sun
Microsystems by James Gosling Microsystems by James Gosling
•Java 1.0 – released Jan 1996Java 1.0 – released Jan 1996
•Java 1.1 – released Feb 1997Java 1.1 – released Feb 1997
•Reflection, inner classesReflection, inner classes
•Serialization, AWT, JavaBeansSerialization, AWT, JavaBeans
•Java 1.2 – released Dec 1998Java 1.2 – released Dec 1998
•Also known as "Java 2 Platform"Also known as "Java 2 Platform"
•Significant improvementSignificant improvement
•Swing GUI, performance and security Swing GUI, performance and security
improvementsimprovements

History of JavaHistory of Java
•Java 2 splits -> J2SE, J2EE, J2ME – 1999Java 2 splits -> J2SE, J2EE, J2ME – 1999
•J2SE 1.3 – released May 2000J2SE 1.3 – released May 2000
•CORBA, RMI, Sound API, many enhancementsCORBA, RMI, Sound API, many enhancements
•J2SE 1.4 – released Feb 2002J2SE 1.4 – released Feb 2002
•Assertions, non-blocking I/O, XML parserAssertions, non-blocking I/O, XML parser
•J2SE 1.5 (5.0) – released Sep 2004J2SE 1.5 (5.0) – released Sep 2004
•Lots of new language featuresLots of new language features
•Generics, enhanced for loop, variable arguments Generics, enhanced for loop, variable arguments
list, auto boxing/unboxing, ...list, auto boxing/unboxing, ...
•Java SE 6.0 – December 2006Java SE 6.0 – December 2006
•Better performance, scripting support, new APIsBetter performance, scripting support, new APIs

What is the Java What is the Java
Technology?Technology?
•Java technology is:Java technology is:
•A programming languageA programming language
•A development environmentA development environment
•An application environmentAn application environment
•A deployment environmentA deployment environment
•It is similar in syntax to C++ and C#It is similar in syntax to C++ and C#
•Used for developing applets and Used for developing applets and
applications (standalone, server-side, Web applications (standalone, server-side, Web
services, mobile, embedded, ...)services, mobile, embedded, ...)

Java Platform ArchitectureJava Platform Architecture

The Java Platform The Java Platform
ArchitectureArchitecture
•Consists of four distinct, but interrelated Consists of four distinct, but interrelated
technologiestechnologies
•The Java virtual machine (JVM)The Java virtual machine (JVM)
•Class loaders and class filesClass loaders and class files
•The Java programming languageThe Java programming language
•The Java APIThe Java API
•Writing Java programs is related to all of Writing Java programs is related to all of
these technologiesthese technologies

Java, JVM and OSJava, JVM and OS
Hardware
(CPU, motherboard, network adapters, video, etc.)
Operating system
Java Virtual Machine
Other native
programs
.dll / .so / ...
Java program
(bytecode, *.class files)
javac
Source files
(plain text, *.java files)
JNI
Native methods

Java 5 ArchitectureJava 5 Architecture

Java Compilation and Java Compilation and
ExecutionExecution
public class HelloJava {public class HelloJava {
public static voidpublic static void
main(String args[])main(String args[]) {{
System.out.println(System.out.println(
"Hello, Java");"Hello, Java");
}}
}}
HelloJava.javaHelloJava.java
CompilationCompilation
001001110101110111010001001110101110111010
111010101110111010110111010101110111010110
110110111010101101010110110111010101101010
101010101010101010110101010101010101010110
111010001101000000101111010001101000000101
101011110110111010100101011110110111010100
111010011010101010110111010011010101010110
101111110101011101010101111110101011101010
010101110101010010100010101110101010010100
111110110101010111010111110110101010111010
101000101010100101100101000101010100101100
010101001110101010011010101001110101010011
01011101101111101010101110110111110101
HelloJava.classHelloJava.class
ExecutionExecution

The Java Programming The Java Programming
EnvironmentEnvironment
A.java
Your program’s source files
C.javaB.java
A.class C.classB.class
Your program’s class files
Java
Compiler
Object.class
Java API’s class files
Your program’s class files
Class
files
move
locally
or
through
a
network
A.class C.classB.class
String.class
...
Java Virtual
Machine

Architectural TradeoffsArchitectural Tradeoffs
•NotNot “the right tool for any job” “the right tool for any job”
Platform independence
Productivity
Execution speed
Lowest common subset of
features
Garbage collection Lack of control of memory
management and thread
scheduling
Dynamic linking Symbolic references
Security

Java Platform EditionsJava Platform Editions
Linux Box
Java Platform for
Linux
Your Java
Program
PC Running
WinNT
Java Platform for
Win32
Your Java
Program
Your Toaster
Java Platform for
Your Toaster
Your Java
Program

Java Platform EditionsJava Platform Editions
•The Java platform has several editions:The Java platform has several editions:
•J2SE (Java SE)J2SE (Java SE)
•J2EE (Java EE)J2EE (Java EE)
•J2MEJ2ME

J2SE, J2EE, J2MEJ2SE, J2EE, J2ME
•Java 2 Standard Edition (J2SE, Java SE)Java 2 Standard Edition (J2SE, Java SE)
•Used to write standalone Java Applications Used to write standalone Java Applications
and Appletsand Applets
•Java 2 Enterprise Edition (J2EE, Java EE)Java 2 Enterprise Edition (J2EE, Java EE)
•A set of API’s and server specifications built A set of API’s and server specifications built
on top of J2SEon top of J2SE
•Used for building Enterprise, Web applications Used for building Enterprise, Web applications
and Web servicesand Web services
•Java 2 Micro Edition (J2ME)Java 2 Micro Edition (J2ME)
•A pared down version of J2SE and API’s for A pared down version of J2SE and API’s for
wireless and embedded deviceswireless and embedded devices

Java Virtual Machine Java Virtual Machine
(JVM)(JVM)

The Java Virtual MachineThe Java Virtual Machine
•Main featuresMain features
•Load class filesLoad class files
•Execute bytecodes they containExecute bytecodes they contain
•Loose features specificationLoose features specification
•Use any technique to execute bytecodeUse any technique to execute bytecode
•Software/hardware implementationSoftware/hardware implementation
•Can be implemented on a wide variety of Can be implemented on a wide variety of
computers and devicescomputers and devices

The Java Virtual MachineThe Java Virtual Machine
•JVM provides definitions for the:JVM provides definitions for the:
•Instruction set (virtual CPU)Instruction set (virtual CPU)
•Register setRegister set
•Class file formatClass file format
•StackStack
•Garbage-collected heapGarbage-collected heap
•Memory areaMemory area

Garbage CollectionGarbage Collection
•Allocated memory that is no longer needed is Allocated memory that is no longer needed is
automatically deallocatedautomatically deallocated
•The Java programming language provides a The Java programming language provides a
system level thread to track memory allocationsystem level thread to track memory allocation
•Garbage collection:Garbage collection:
•Checks for and frees memory no longer neededChecks for and frees memory no longer needed
•Is done automaticallyIs done automatically
•Can vary dramatically across JVM Can vary dramatically across JVM
implementationsimplementations

The JVM and Host The JVM and Host
Operating SystemsOperating Systems
•Java methodsJava methods
•Written in Java, compiled to bytecodesWritten in Java, compiled to bytecodes
•Stored in class files (Stored in class files (.class.class))
•Native methodsNative methods
•Written in other languages (C, C++, …)Written in other languages (C, C++, …)
•Compiled to native machine codeCompiled to native machine code
•Dynamic librariesDynamic libraries
•Java Native Interface (JNI)Java Native Interface (JNI)

The JVM and Host The JVM and Host
Operating SystemsOperating Systems
Class
Loader
Execution
Engine
bytecodes
Your
program’s
class files
The Java
API’s
class files
Host Operating System
Native method invocations

Classes and Class LoadersClasses and Class Loaders

Classes and Class LoadersClasses and Class Loaders
•The “bootstrap” class loaderThe “bootstrap” class loader
•Only oneOnly one
•Part of the JVM implementationPart of the JVM implementation
•Loads classes in some default wayLoads classes in some default way
•User-defined class loadersUser-defined class loaders
•Written and compiled in JavaWritten and compiled in Java
•Installed at runtimeInstalled at runtime
•Load classes in custom waysLoad classes in custom ways
•NotNot part of the JVM implementation part of the JVM implementation

Class Loaders ArchitectureClass Loaders Architecture
Bootstrap class loader
User-defined
class loader
User-defined
class loader
User-defined
class loader
Objects on the heap
Part of the JVM implementation

Class LoadersClass Loaders
•Load classes over networks, from DB, …Load classes over networks, from DB, …
•Keep track of loaded classesKeep track of loaded classes
•Class namespacesClass namespaces
•Access between class namespacesAccess between class namespaces
•AdvantagesAdvantages
•SecuritySecurity
•MobilityMobility
•ExtensibilityExtensibility

Java Class FilesJava Class Files
•JavaJava classes, translated to “bytecodes”classes, translated to “bytecodes”
•Stored with Stored with .class.class file extension file extension
•Platform independent binary formatPlatform independent binary format
•Consistent byte order of integersConsistent byte order of integers
•Designed to be compactDesigned to be compact
•Network mobilityNetwork mobility
•Can be downloaded as neededCan be downloaded as needed
•Dynamic linkingDynamic linking

ClasspathClasspath
•The CLASSPATH environment variableThe CLASSPATH environment variable
•Third-party and user-defined classesThird-party and user-defined classes
•Can be overridden using the “-classpath” Can be overridden using the “-classpath”
Java command-line argumentJava command-line argument
•Classpath entries can beClasspath entries can be
•DirectoriesDirectories
•Archive files (.jar and .zip)Archive files (.jar and .zip)
•Classes are loaded in the order of Classes are loaded in the order of
appearanceappearance

JAR FilesJAR Files
•Java programs are compiled to Java programs are compiled to .class.class files files
(Java bytecode + class metadata)(Java bytecode + class metadata)
•Class files are packed in JAR archivesClass files are packed in JAR archives
•JAR files (short for JAR files (short for JJava ava ARARchive) arechive) are
•Standard ZIP filesStandard ZIP files
•Can use compression or notCan use compression or not
•Used to distribute a set of compiled Java Used to distribute a set of compiled Java
classes, associated metadata and resourcesclasses, associated metadata and resources

JAR FilesJAR Files
•Can be created and extracted with Can be created and extracted with jarjar
command line toolcommand line tool
•Creating Creating .jar.jar file: file:
•Extracting Extracting .jar.jar files files
•Can be created and extracted with Can be created and extracted with WinZipWinZip
or other ZIP manipulation toolor other ZIP manipulation tool
jar -cf MyJarArchive.jar *.classjar -cf MyJarArchive.jar *.class
jar -xf MyJarArchive.jar *.classjar -xf MyJarArchive.jar *.class

EclipseEclipse
Compiling, Compiling, RRunning and unning and DDebugging ebugging
Java PJava Programs rograms

Creating New Java Creating New Java
ApplicationApplication
•Window Window  Open Open
Perspective Perspective  Java Java
•File File  New New  Project Project
•Choose Java ProjectChoose Java Project
•Choose project nameChoose project name
•Click FinishClick Finish

Creating New Java Creating New Java
Application (2)Application (2)
•File File  New New  Class Class
•Choose the project Choose the project
you just madeyou just made
•Choose class nameChoose class name
•Enable “public static Enable “public static
void main (String void main (String
args[])” check boxargs[])” check box
•Click FinishClick Finish

1.1.Eclipse creates some source code for you.Eclipse creates some source code for you.
Creating New Java Creating New Java
Application (3)Application (3)

Compiling Source CodeCompiling Source Code
•Compilation process includes:Compilation process includes:
•Syntactic checksSyntactic checks
•Type safety checksType safety checks
•Translation of the source code to Java Translation of the source code to Java
bytecodebytecode
•In Eclipse compilation is made automaticallyIn Eclipse compilation is made automatically
•As you type, the program is checked for As you type, the program is checked for
errors and is compilederrors and is compiled
•Saving the file (Ctrl+S) forces compilationSaving the file (Ctrl+S) forces compilation

Running ProgramsRunning Programs
•Running process includes:Running process includes:
•Compiling (if project not compiled)Compiling (if project not compiled)
•Starting the applicationStarting the application
•You can run application by:You can run application by:
•Using Using Run As->Java ApplicationRun As->Java Application popup menu popup menu
* NOTE: Not all types of projects are able to be * NOTE: Not all types of projects are able to be
run!run!

Debugging The CodeDebugging The Code
•Debugging process includes:Debugging process includes:
•Spotting an errorSpotting an error
•Finding the code that causes the errorFinding the code that causes the error
•Fixing the codeFixing the code
•Testing to see if the error is gone and no Testing to see if the error is gone and no
errors are introducederrors are introduced
•This process is iterative and continuousThis process is iterative and continuous

Debugging in EclipseDebugging in Eclipse
•Eclipse has built-in debuggerEclipse has built-in debugger
•It provides:It provides:
•BreakpointsBreakpoints
•Ability to trace the code executionAbility to trace the code execution
•Ability to inspect variables at runtimeAbility to inspect variables at runtime

EclipseEclipse
Compiling, Compiling, RRunning and unning and DDebugging ebugging
Java PJava Programs rograms
Live DemoLive Demo