53
Introduction to Introduction to Java Programming Java Programming - internals - internals

Java platform

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: Java platform

Introduction to Java Introduction to Java Programming - Programming -

internalsinternals

Page 2: Java platform

ContentsContents

• Computer Programming OverviewComputer Programming Overview

• Your First Java ProgramYour First Java Program

• Java Technology OverviewJava Technology Overview

• Eclipse IDEEclipse IDE

Page 3: Java platform

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

Page 4: Java platform

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

Page 5: Java platform

What is Computer What is Computer Programming?Programming?

Page 6: Java platform

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

Page 7: Java platform

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

Page 8: Java platform

Your First Java ProgramYour First Java Program

Page 9: Java platform

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");

}}

}}

Page 10: Java platform

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 a class called Define a class called ""HelloJavaHelloJava""

Define the Define the main()main() method – the program method – the program

entry pointentry point

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

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

Page 11: Java platform

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 lowercaseThe keyword The keyword classclass should be lowercaseshould be lowercase

The class The class SystemSystem should be in should be in

""Pascal CasePascal Case""

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 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()

The correct method The correct method name is name is main()main()

Page 12: Java platform

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 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

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

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 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 {{

The The }} symbol should be symbol should be under the beginning of the under the beginning of the line with corresponding line with corresponding {{

Page 13: Java platform

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

Such formatting Such formatting makes the code makes the code

unreadableunreadable

Page 14: Java platform

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

Page 15: Java platform

Your First Java ProgramYour First Java ProgramLive DemoLive Demo

Page 16: Java platform

Welcome to Java TechnologyWelcome to Java Technology

Page 17: Java platform

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)

Page 18: Java platform

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

Page 19: Java platform

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

Page 20: Java platform

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, ...)

Page 21: Java platform

Java Platform ArchitectureJava Platform Architecture

Page 22: Java platform

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

Page 23: Java platform

Java, JVM and OSJava, JVM and OS

Hardware(CPU, motherboard, network adapters, video, etc.)

Operating system

Java Virtual MachineOther native

programs.dll / .so / ...

Java program(bytecode, *.class files)

javacSource files

(plain text, *.java files)

JNI

Native methods

Page 24: Java platform

Java 5 ArchitectureJava 5 Architecture

Page 25: Java platform

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"); }}

}}

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

CompilationCompilation00100111010111011101000100111010111011101011101010111011101011011101010111011101011011011011101010110101011011011101010110101010101010101010101011010101010101010101011011101000110100000010111101000110100000010110101111011011101010010101111011011101010011101001101010101011011101001101010101011010111111010101110101010111111010101110101001010111010101001010001010111010101001010011111011010101011101011111011010101011101010100010101010010110010100010101010010110001010100111010101001101010100111010101001101011101101111101010101110110111110101

00100111010111011101000100111010111011101011101010111011101011011101010111011101011011011011101010110101011011011101010110101010101010101010101011010101010101010101011011101000110100000010111101000110100000010110101111011011101010010101111011011101010011101001101010101011011101001101010101011010111111010101110101010111111010101110101001010111010101001010001010111010101001010011111011010101011101011111011010101011101010100010101010010110010100010101010010110001010100111010101001101010100111010101001101011101101111101010101110110111110101

HelloJava.classHelloJava.class

ExecutionExecution

Page 26: Java platform

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

Page 27: Java platform

Architectural TradeoffsArchitectural Tradeoffs

• NotNot “the right tool for any job” “the right tool for any job”

Platform independenceProductivity

Execution speedLowest common subset of features

Garbage collection Lack of control of memory management and thread scheduling

Dynamic linking Symbolic referencesSecurity

Page 28: Java platform

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

Page 29: Java platform

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

Page 30: Java platform

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

Page 31: Java platform

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

Page 32: Java platform

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

Page 33: Java platform

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

Page 34: Java platform

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

Page 35: Java platform

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)

Page 36: Java platform

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

Page 37: Java platform

Classes and Class LoadersClasses and Class Loaders

Page 38: Java platform

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

Page 39: Java platform

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

Page 40: Java platform

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

Page 41: Java platform

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

Page 42: Java platform

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

Page 43: Java platform

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

Page 44: Java platform

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

Page 45: Java platform

EclipseEclipseCompiling, Compiling, RRunning and unning and DDebugging ebugging

Java PJava Programs rograms

Page 46: Java platform

Creating New Java Creating New Java ApplicationApplication

1.1. Window Window Open Open Perspective Perspective Java Java

2.2. File File New New Project Project

3.3. Choose Java ProjectChoose Java Project

4.4. Choose project nameChoose project name

5.5. Click FinishClick Finish

Page 47: Java platform

Creating New Java Creating New Java Application (2)Application (2)

1.1. File File New New Class Class

2.2. Choose the project Choose the project you just madeyou just made

3.3. Choose class nameChoose class name

4.4. Enable “public static Enable “public static void main (String void main (String args[])” check boxargs[])” check box

5.5. Click FinishClick Finish

Page 48: Java platform

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)

Page 49: Java platform

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

Page 50: Java platform

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!

Page 51: Java platform

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

Page 52: Java platform

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

Page 53: Java platform

EclipseEclipseCompiling, Compiling, RRunning and unning and DDebugging ebugging

Java PJava Programs rograms

Live DemoLive Demo