32
Programming with JAVA Programming with JAVA Introduction of java Introduction of java Java Virtual Machine Java Virtual Machine Java system overview /Java compile-time /Java compile-time Environment Environment Java Buzzwords Java Buzzwords Different between C++ and JAVA Different between C++ and JAVA

Programming With JAVA

Embed Size (px)

Citation preview

Page 1: Programming With JAVA

Programming with JAVAProgramming with JAVA Introduction of java Introduction of java Java Virtual MachineJava Virtual Machine Java system overview /Java compile-time Environment /Java compile-time Environment Java BuzzwordsJava Buzzwords Different between C++ and JAVADifferent between C++ and JAVA

Page 2: Programming With JAVA

Introduction of javaIntroduction of java Java was developed by Jems Goslin at Java was developed by Jems Goslin at

Sun Microsystems in the early 1990’s.Sun Microsystems in the early 1990’s. The world wide web appeared in 1993, the The world wide web appeared in 1993, the

language has been enhanced to facilitate language has been enhanced to facilitate programming on web.programming on web.

Since then it become one of the most Since then it become one of the most popular language for web.popular language for web.

This language was initially called “Oak” but This language was initially called “Oak” but renamed as java in 1995.renamed as java in 1995.

Page 3: Programming With JAVA

Introduction of javaIntroduction of java The primary motivation was the need of The primary motivation was the need of

platform-independent language that could be platform-independent language that could be used to create software to be embedded in used to create software to be embedded in various customer electronic devices, such as various customer electronic devices, such as microwave ovens and remote controls.microwave ovens and remote controls.

Java never provides any tool to handle Java never provides any tool to handle operations related to memory.operations related to memory.

The memory addressing is implemented and The memory addressing is implemented and controlled by java virtual machine (JVM).controlled by java virtual machine (JVM).

Memory addressing mean where the variables Memory addressing mean where the variables are created, objects are stored, and methods are created, objects are stored, and methods are stored in memory.are stored in memory.

Page 4: Programming With JAVA

Introduction of javaIntroduction of java Java is derived from c++, because most of the Java is derived from c++, because most of the

features are taken from c++.features are taken from c++. Sun released the first JDK 1.0 in 1995.Sun released the first JDK 1.0 in 1995. It promised a platform independent language to It promised a platform independent language to

the programmer.the programmer. it was ‘write Once Run anywhere’.it was ‘write Once Run anywhere’. Sun launched different versions for different Sun launched different versions for different

purposes, e.g. J2EE is enterprise edition, use for purposes, e.g. J2EE is enterprise edition, use for server side programming, J2ME is micro edition server side programming, J2ME is micro edition used for mobile applications, and J2SE is for used for mobile applications, and J2SE is for standard edition.standard edition.

Page 5: Programming With JAVA

Introduction of wrapper class makes java a Introduction of wrapper class makes java a complete OOP language.complete OOP language.

When a java source file is compiled, a class file When a java source file is compiled, a class file is generated, which is a collection of Byte codes. is generated, which is a collection of Byte codes. Byte codes are portable. These are later Byte codes are portable. These are later changed to native code by JVM.changed to native code by JVM.

Bytes code are least affected by virus as Bytes code are least affected by virus as compared by executable files. If the Byte code is compared by executable files. If the Byte code is affected, these are recognized by the JVM and affected, these are recognized by the JVM and not allowed to be executed.not allowed to be executed.

Java has built-in support for exception handling.Java has built-in support for exception handling. It has built-in support for multithreading It has built-in support for multithreading

application development.application development. There is a built-in support for networking.There is a built-in support for networking.

Page 6: Programming With JAVA

Java Virtual MachineJava Virtual Machine JVM system is an interpreter. JVM system is an interpreter. Java virtual machine is a software system that translates Java virtual machine is a software system that translates

and execute java byte code.and execute java byte code. An instruction set and the meaning of those instructions – the An instruction set and the meaning of those instructions – the

byte codesbyte codes A binary format – the A binary format – the class fileclass file format format An algorithm to An algorithm to verifyverify the class file the class file

Page 7: Programming With JAVA

Method Area

Heap Java Stacks

PC Registers

Native method Stacks

Execution Engine

Class loader subsystem

Native method interfaceNative method libraries

Class files

Runtime data areas

JVM Architecture

Page 8: Programming With JAVA

1. 1. Class loader Sub-SystemClass loader Sub-System performs its task in a sequential performs its task in a sequential way:way:

It loads a class file .It loads a class file . It checks the correctness of the class file. If any one has It checks the correctness of the class file. If any one has

manipulated the class file, then the class file can not be manipulated the class file, then the class file can not be executed.executed.

It allocate memory for static variables.It allocate memory for static variables. It sets the default value of all static variable.It sets the default value of all static variable. It transforms symbolic reference into direct reference.It transforms symbolic reference into direct reference.2. 2. Method Area Method Area It is a logical memory component of JVM.It is a logical memory component of JVM.This logical section of memory holds the information about This logical section of memory holds the information about

classes and interfaces.classes and interfaces.Static variables are treated as class variables, because they take Static variables are treated as class variables, because they take

memory from method area.memory from method area.

Page 9: Programming With JAVA

3. 3. Heap Heap When object or array is created, memory is allocated to When object or array is created, memory is allocated to

them from heap.them from heap. JVM through the use of new operator allocates memory JVM through the use of new operator allocates memory

from the heap for an object.from the heap for an object. The JVM has a daemon thread known as Garbage The JVM has a daemon thread known as Garbage

Collector whose task is to free those objects from heap Collector whose task is to free those objects from heap whose reference is not alive in stack.whose reference is not alive in stack.

4. 4. JAVA Stack JAVA Stack Method codes are stored inside method area.Method codes are stored inside method area. For execution, a method needs memory because of local For execution, a method needs memory because of local

variables and the arguments it has taken.variables and the arguments it has taken. This purpose is fulfilled by java stack.This purpose is fulfilled by java stack.

Page 10: Programming With JAVA

5.5. Program counter registerProgram counter register It keeps track of the sequence of the program.It keeps track of the sequence of the program. Pc register holds the address of the instructions to be Pc register holds the address of the instructions to be

executed next.executed next.6.6. Native method stackNative method stack When a java application invokes a native method, that When a java application invokes a native method, that

application does not only use java stack but also use the application does not only use java stack but also use the native method stack for the execution of native methods.native method stack for the execution of native methods.

The libraries required for the execution of native methods The libraries required for the execution of native methods are available to the JVM through Java Native Interface.are available to the JVM through Java Native Interface.

7.7. Execution EngineExecution Engine Generate and executes the java byte code.Generate and executes the java byte code. It contains an interpreter and Just In Time compiler.It contains an interpreter and Just In Time compiler.

Page 11: Programming With JAVA

8.8. Java Native interfaceJava Native interface

JNI is used when the programmer has already JNI is used when the programmer has already developed the code in c/ c++ and wishes to make it developed the code in c/ c++ and wishes to make it accessible to java code.accessible to java code.

JNI never imposes any restriction on JVM.JNI never imposes any restriction on JVM. JVM can add support to JNI without affecting other JVM can add support to JNI without affecting other

parts of virtual machine.parts of virtual machine. Native methods accesses JVM features by calling JNI Native methods accesses JVM features by calling JNI

functions.functions.

Page 12: Programming With JAVA

Java system overview

Page 13: Programming With JAVA

Compile-time EnvironmentCompile-time Environment

JavaByte codes

move locallyor through

network

JavaSource(.java)

JavaCompiler

JavaBytecod

e(.class )

JavaInterpreter

Just in Time

Compiler

Runtime System

Class Loader

BytecodeVerifier

Java Class

Libraries

Operating System

Hardware

JavaVirtualmachine

Java compile-time Environment

Page 14: Programming With JAVA

Java compile-time EnvironmentJava compile-time Environment

Java is platform independent only for the reason:Java is platform independent only for the reason: Only depends on the Java Virtual Machine (JVM),Only depends on the Java Virtual Machine (JVM), code is compiled to code is compiled to byte codebyte code, which is , which is

interpreted by the resident JVM,interpreted by the resident JVM, JIT (just in time) compilers attempt to increase JIT (just in time) compilers attempt to increase

speed.speed.

Page 15: Programming With JAVA

Java Buzzwords or features of javaJava Buzzwords or features of java SimpleSimple

fixes some clumsy features of C++fixes some clumsy features of C++ no pointersno pointers automatic garbage collectionautomatic garbage collection rich pre-defined class libraryrich pre-defined class library

Object orientedObject oriented focus on the data (objects) and methods focus on the data (objects) and methods

manipulating the datamanipulating the data all functions are associated with objectsall functions are associated with objects almost all data types are objects (files, strings, etc.)almost all data types are objects (files, strings, etc.) potentially better code organization and reuse.potentially better code organization and reuse.

Page 16: Programming With JAVA

cont…...cont…...

InterpretedInterpreted java compiler generate byte-codes, not native java compiler generate byte-codes, not native

machine codemachine code The compiled byte-codes are platform-independentThe compiled byte-codes are platform-independent java byte codes are translated on the fly to machine java byte codes are translated on the fly to machine

readable instructions in runtime (Java Virtual readable instructions in runtime (Java Virtual Machine)Machine)

PortablePortable same application runs on all platformssame application runs on all platforms The sizes of the primitive data types are always the The sizes of the primitive data types are always the

same.same. The libraries define portable interfaces The libraries define portable interfaces

Page 17: Programming With JAVA

Cont….Cont…. ReliableReliable

Extensive compile-time and runtime error checking.Extensive compile-time and runtime error checking. No pointers but real arrays. Memory corruptions or unauthorized No pointers but real arrays. Memory corruptions or unauthorized

memory accesses are impossible.memory accesses are impossible. Automatic garbage collection tracks objects usage over time.Automatic garbage collection tracks objects usage over time.

SecureSecure The Java language is secure in that it is very difficult to write incorrect

code or viruses that can corrupt/steal your data, or harm hardware such as hard disks.

No pointer arithmetic• Garbage collection• Array bounds checking• No illegal data conversions• Browser level (applies to applets only):• No local file I/O

Page 18: Programming With JAVA

Java achieved protection by confining an applet to java execution Java achieved protection by confining an applet to java execution environment and not allowing it access to other parts of the computer.environment and not allowing it access to other parts of the computer.

MultithreadedMultithreaded

multiple concurrent threads of executions can run simultaneously.multiple concurrent threads of executions can run simultaneously. utilizes a sophisticated set of synchronization primitives (based on utilizes a sophisticated set of synchronization primitives (based on

monitors and condition variables paradigm) to achieve this. monitors and condition variables paradigm) to achieve this. DynamicDynamic

java is designed to adapt to evolving environmentjava is designed to adapt to evolving environment libraries can freely add new methods and instance variables without libraries can freely add new methods and instance variables without

any effect on their clientsany effect on their clients interfaces promote flexibility and reusability in code by specifying interfaces promote flexibility and reusability in code by specifying

a set of methods an object can perform, but leaves open how these a set of methods an object can perform, but leaves open how these methods should be implementedmethods should be implemented

can check the class type in runtimecan check the class type in runtime

Page 19: Programming With JAVA

DistributedDistributedIt handles TCP/IP protocols.It handles TCP/IP protocols.Java also support remote Method Invocation (RMI), this Java also support remote Method Invocation (RMI), this feature enables a program to invoke methods across a feature enables a program to invoke methods across a network.network.

Architecture- NeutralArchitecture- NeutralThe JVM make java ‘write once run any where, any time The JVM make java ‘write once run any where, any time forever.forever.

RobustnessThe Java language is robust. It has several features designed to avoid crashes during program execution, including:Array and string bounds checkingNo jumping to bad method addresses Interfaces and exceptions

Page 20: Programming With JAVA

First Java ProgramFirst Java ProgramClass ExampleClass Example{{// your program begins with a call to main// your program begins with a call to mainPublic static void main (string args[])Public static void main (string args[]){{System.out.println (“This is a simple Java program”);System.out.println (“This is a simple Java program”);}}}}Save this program Example.javaSave this program Example.javaCompile with javac Example.javaCompile with javac Example.javaExecute with java ExampleExecute with java ExampleHere class is to declare new class is being defined.Here class is to declare new class is being defined.Example is an identifier.Example is an identifier.Public static void main (string args[])Public static void main (string args[])

Public is access specifier then that member may be accessed by code out Public is access specifier then that member may be accessed by code out side the class in which it is declared.side the class in which it is declared.

Page 21: Programming With JAVA

Static allows main to be called without having to instantiate a Static allows main to be called without having to instantiate a particular instance of the class. This is necessary since main() is particular instance of the class. This is necessary since main() is called by JVM before any objects are made.called by JVM before any objects are made.

void simply tells the compiler that main() does not return void simply tells the compiler that main() does not return a value.a value.

main() is the method called when a java application begins.main() is the method called when a java application begins. String args [] declares a parameter named args, which is an String args [] declares a parameter named args, which is an

array of instances of the class string.array of instances of the class string. Objects of type string store character strings. In this case args Objects of type string store character strings. In this case args

receives any command-line arguments present when a program receives any command-line arguments present when a program is executed.is executed.

System.out.println (“This is a simple Java program”);System.out.println (“This is a simple Java program”);

println() is a built-in method for providing out puts, println() println() is a built-in method for providing out puts, println() is also used to display other type of information's.is also used to display other type of information's.

system is a predefined class that provides access to the system is a predefined class that provides access to the system, and out is the output stream that is connected to the system, and out is the output stream that is connected to the console.console.

Page 22: Programming With JAVA

Difference Between C++ and JAVADifference Between C++ and JAVA

Java is (an interpreted) write once, run anywhere Java is (an interpreted) write once, run anywhere language.language.

The biggest potential stumbling block is speed: The biggest potential stumbling block is speed: interpreted Java runs in the range of 20 times interpreted Java runs in the range of 20 times slower than C. But: nothing prevents the Java slower than C. But: nothing prevents the Java language from being compiled and there are just-in-language from being compiled and there are just-in-time (JIT) compilers that offer significant speed-ups.time (JIT) compilers that offer significant speed-ups.

Write once, run everywhere does (nearly) NEVER Write once, run everywhere does (nearly) NEVER work with C++, but does (nearly) ALWAYS work work with C++, but does (nearly) ALWAYS work with JAVA.with JAVA.

Page 23: Programming With JAVA

JAVA vs C++JAVA vs C++

You don't have separated HEADER-files defining class-You don't have separated HEADER-files defining class-propertiesproperties

You can define elements only within a class. You can define elements only within a class. All method definitions are also defined in the body of the class. All method definitions are also defined in the body of the class.

Thus, in C++ it would look like all the functions are inlined (but Thus, in C++ it would look like all the functions are inlined (but they’re not).they’re not).

File- and classname must be identical in JAVAFile- and classname must be identical in JAVA Instead of C++ “#include“ you use the “import keyword“.Instead of C++ “#include“ you use the “import keyword“.

• For example: import java.awt.*;. For example: import java.awt.*;.

• #include does not directly map to import, but it has a similar feel to it#include does not directly map to import, but it has a similar feel to it

Page 24: Programming With JAVA

JAVA vs C++JAVA vs C++

Instead of controlling blocks of declarations like Instead of controlling blocks of declarations like C++ does, the access specifiers (public, private, C++ does, the access specifiers (public, private, and protected) are placed on each definition for and protected) are placed on each definition for each member of a classeach member of a class

Without an explicit access specifier, an element defaults to Without an explicit access specifier, an element defaults to "friendly," which means that it is accessible to other elements in "friendly," which means that it is accessible to other elements in the same package (which is a collection of classes being the same package (which is a collection of classes being ‘friends‘)‘friends‘)

The class, and each method within the class, has an access The class, and each method within the class, has an access specifier to determine whether it’s visible outside the file.specifier to determine whether it’s visible outside the file.

Page 25: Programming With JAVA

JAVA vs C++JAVA vs C++ Everything must be in a class.Everything must be in a class.

There are no global functions or global data. If you want the There are no global functions or global data. If you want the equivalent of globals, make static methods and static data within equivalent of globals, make static methods and static data within a class. a class.

There are no structs or enumerations or unions, only classes.There are no structs or enumerations or unions, only classes. Class definitions are roughly the same form in Java as in C++, Class definitions are roughly the same form in Java as in C++,

but there’s no closing semicolon.but there’s no closing semicolon. Java has no preprocessor. Java has no preprocessor.

If you want to use classes in another library, you say import and If you want to use classes in another library, you say import and the name of the library. the name of the library.

There are no preprocessor-like macros.There are no preprocessor-like macros. There is no conditional compiling (#ifdef) There is no conditional compiling (#ifdef)

Page 26: Programming With JAVA

JAVA vs C++JAVA vs C++ All the primitive types in Java have specified sizes that All the primitive types in Java have specified sizes that

are machine independent for portability. are machine independent for portability. On some systems this leads to non-optimized performanceOn some systems this leads to non-optimized performance The char type uses the international 16-bit Unicode character The char type uses the international 16-bit Unicode character

set, so it can automatically represent most national characters.set, so it can automatically represent most national characters.

Type-checking and type requirements are much tighter Type-checking and type requirements are much tighter in Java. in Java.

For example:For example:• 1. Conditional expressions can be only boolean, not integral.1. Conditional expressions can be only boolean, not integral.

• 2. The result of an expression like X + Y must be used; you can’t 2. The result of an expression like X + Y must be used; you can’t just say "X + Y" for the side effect.just say "X + Y" for the side effect.

Page 27: Programming With JAVA

JAVA vs C++JAVA vs C++

There are Strings in JAVAThere are Strings in JAVA Strings are represented by the String-class, they Strings are represented by the String-class, they

aren‘t only some renamed pointersaren‘t only some renamed pointers Static quoted strings are automatically converted into Static quoted strings are automatically converted into

String objects. String objects. There is no independent static character array string There is no independent static character array string

like there is in C and C++.like there is in C and C++. There are no Java pointers in the sense of C There are no Java pointers in the sense of C

and C++and C++

There‘s nothing more to say, except that it is a bit There‘s nothing more to say, except that it is a bit confusing, that a pointerless language like JAVA has confusing, that a pointerless language like JAVA has a ‘null-pointer‘ error-message... a ‘null-pointer‘ error-message...

Page 28: Programming With JAVA

JAVA vs C++JAVA vs C++ Although they look similar, arrays have a very different structure and Although they look similar, arrays have a very different structure and

behavior in Java than they do in C++.behavior in Java than they do in C++.

There’s a read-only length member that tells you how big the array There’s a read-only length member that tells you how big the array is, and run-time checking throws an exception if you go out of is, and run-time checking throws an exception if you go out of bounds. bounds.

All arrays are created on the heap, and you can assign one array to All arrays are created on the heap, and you can assign one array to another (the array handle is simply copied). another (the array handle is simply copied).

There is a garbage collection in JAVAThere is a garbage collection in JAVA Garbage collection means memory leaks are much harder to cause Garbage collection means memory leaks are much harder to cause

in Java, but not impossible. (If you make native method calls that in Java, but not impossible. (If you make native method calls that allocate storage, these are typically not tracked by the garbage allocate storage, these are typically not tracked by the garbage collector.) collector.)

The garbage collector is a huge improvement over C++, and makes The garbage collector is a huge improvement over C++, and makes a lot of programming problems simply vanish. It might make Java a lot of programming problems simply vanish. It might make Java unsuitable for solving a small subset of problems that cannot unsuitable for solving a small subset of problems that cannot tolerate a garbage collector, but the advantage of a garbage tolerate a garbage collector, but the advantage of a garbage collector seems to greatly outweigh this potential drawback.collector seems to greatly outweigh this potential drawback.

Page 29: Programming With JAVA

JAVA vs C++JAVA vs C++ There are no destructors in Java. There are no destructors in Java.

There's no need because of garbage collection.There's no need because of garbage collection.

Java uses a singly-rooted hierarchy, so all objects are Java uses a singly-rooted hierarchy, so all objects are ultimately inherited from the root class Object.ultimately inherited from the root class Object.

The inheritance of properties of different classes is handled by The inheritance of properties of different classes is handled by interfaces.interfaces.

Java provides the interface keyword, which creates the Java provides the interface keyword, which creates the equivalent of an abstract base class filled with abstract methods equivalent of an abstract base class filled with abstract methods and with no data members. This makes a clear distinction and with no data members. This makes a clear distinction between something designed to be just an interface and an between something designed to be just an interface and an extension of existing functionality via the extends keyword. extension of existing functionality via the extends keyword.

It’s worth noting that the abstract keyword produces a similar It’s worth noting that the abstract keyword produces a similar effect in that you can’t create an object of that class. effect in that you can’t create an object of that class.

Page 30: Programming With JAVA

JAVA vs C++JAVA vs C++ Java has method overloading, but no operator Java has method overloading, but no operator

overloading.overloading. Java has both kinds of comments like C++ does.Java has both kinds of comments like C++ does. There’s no goto in Java. There’s no goto in Java.

The one unconditional jump mechanism is the break The one unconditional jump mechanism is the break label or continue label, which is used to jump out of label or continue label, which is used to jump out of the middle of multiply-nested loops.the middle of multiply-nested loops.

Java has built-in support for comment documentation Java has built-in support for comment documentation so the source code file can also contain its own so the source code file can also contain its own

documentation, which is stripped out and reformatted documentation, which is stripped out and reformatted into HTML via a separate program. This is a boon for into HTML via a separate program. This is a boon for documentation maintenance and use.documentation maintenance and use.

Page 31: Programming With JAVA

JAVA vs C++JAVA vs C++ Java contains standard libraries for GUIsJava contains standard libraries for GUIs

Simple, robust and effective way of creating user-interfacesSimple, robust and effective way of creating user-interfaces Graphical output as part of the languageGraphical output as part of the language

Java contains standard libraries for solving specific tasks. C++ Java contains standard libraries for solving specific tasks. C++ relies on non-standard third-party libraries. relies on non-standard third-party libraries.

These tasks include:These tasks include:• Networking, Database Connection (via JDBC) Networking, Database Connection (via JDBC) • Distributed Objects (via RMI and CORBA) Distributed Objects (via RMI and CORBA) • Compression, CommerceCompression, Commerce• Whatever you want: VoIP, Video-Telephony, MIDI, Games,...Whatever you want: VoIP, Video-Telephony, MIDI, Games,...• The availability and standard nature of these libraries allow for The availability and standard nature of these libraries allow for

more rapid application development.more rapid application development.

Page 32: Programming With JAVA

JAVA vs C++JAVA vs C++ Generally, Java is more robust, via:Generally, Java is more robust, via:

Object handles initialized to null (a keyword).Handles Object handles initialized to null (a keyword).Handles are always checked and exceptions are thrown for are always checked and exceptions are thrown for failures failures

All array accesses are checked for bounds violations All array accesses are checked for bounds violations Automatic garbage collection prevents memory leaks Automatic garbage collection prevents memory leaks Clean, relatively full-proof exception handling Clean, relatively full-proof exception handling Simple language support for multithreading Simple language support for multithreading Bytecode verification of network appletsBytecode verification of network applets Standard GUI Standard GUI