Java

This article introduces the Java programming language.

Overview

Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. As of 2016, Java is one of the most popular programming languages in use, particularly for client-server web applications, with a reported 9 million developers. Java was originally developed by James Gosling at Sun Microsystems (which has since been acquired by Oracle Corporation) and released in 1995 as a core component of Sun Microsystems’ Java platform. The language derives much of its syntax from C and C++, but it has fewer low-level facilities than either of them. Refer to Java Overview for more information.

Java History

Date Description
1995年5月23日 Java语言诞生
1996年1月 第一个JDK-JDK1.0诞生
1996年4月 10个最主要的操作系统供应商申明将在其产品中嵌入JAVA技术
1996年9月 约8.3万个网页应用了JAVA技术来制作
1997年2月18日 JDK1.1发布
1997年4月2日 JavaOne会议召开,参与者逾一万人,创当时全球同类会议规模之纪录
1997年9月 JavaDeveloperConnection社区成员超过十万
1998年2月 JDK1.1被下载超过2,000,000次
1998年12月8日 JAVA2企业平台J2EE发布
1999年6月 SUN公司发布Java的三个版本:标准版(J2SE)、企业版(J2EE)和微型版(J2ME)
2000年5月8日 JDK1.3发布
2000年5月29日 JDK1.4发布
2001年6月5日 NOKIA宣布,到2003年将出售1亿部支持Java的手机
2001年9月24日 J2EE1.3发布
2002年2月26日 J2SE1.4发布,自此Java的计算能力有了大幅提升
2004年9月30日 J2SE1.5发布,成为Java语言发展史上的又一里程碑。为了表示该版本的重要性,J2SE1.5更名为Java SE 5.0
2005年6月 JavaOne大会召开,SUN公司公开Java SE 6。此时,Java的各种版本已经更名,以取消其中的数字2:J2EE更名为Java EE,J2SE更名为Java SE,J2ME更名为Java ME
2006年12月 SUN公司发布JRE6.0
2009年12月 SUN公司发布Java EE 6
2010年11月 由于Oracle公司对于Java社区的不友善,因此Apache扬言将退出JCP
2011年7月28日 Oracle公司发布Java SE 7
2014年3月18日 Oracle公司发布Java SE 8
2017年8月21日 Oracle公司发布Java EE 8
2017年9月27日 Oracle公司发布Java SE 9

Java Principles

There were five primary goals in the creation of the Java language:

  • It must be simple, object-oriented, and familiar.
  • It must be robust and secure.
  • It must be architecture-neutral and portable.
  • It must execute with high performance.
  • It must be interpreted, threaded, and dynamic.

Java Versions

As of 2015, only Java 8 is officially supported. Here is major release versions of Java, along with their release dates. Refer to Java version history.

Java Version Internal Version Release_Date Codename Classes Packages
JDK 1.0 1.0.0 Jan 23, 1996   212 8
JDK 1.1 1.1.0 Feb 19, 1997   504 23
J2SE 1.2 1.2.0 Dec 08, 1998 Playground 1520 59
J2SE 1.3 1.3.0 May 08, 2000 Kestrel 1842 76
J2SE 1.4 1.4.0 Feb 06, 2002 Merlin 2991 135
J2SE 5.0 1.5.0 Sep 30, 2004 Tiger 3279 166
Java SE 6 1.6.0 Dec 11, 2006 Mustang 3793 203
Java SE 7 1.7.0 Jul 28, 2011 Dolphin 4024 209
Java SE 8 1.8.0 Mar 18, 2014 Spider 4240 217
Java SE 9 1.9.0 Sep 21, 2017      
Java SE 10 1.10.0 Mar 20, 2018      
Java SE 11 1.11.0 Sep 25, 2018      
Java SE 12 1.12.0 Mar 19, 2019      

Since J2SE 1.4, the evolution of the Java language has been governed by the Java Community Process (JCP), which uses Java Specification Requests (JSRs) to propose and specify additions and changes to the Java platform. The language is specified by the Java Language Specification (JLS); changes to the JLS are managed under JSR 901.

Java Community Process (JCP)

The Java Community Process (JCP), established in 1998, is a formalized mechanism that allows interested parties to develop standard technical specifications for Java technology. Anyone can become a JCP Member by filling a form available at the JCP website. JCP membership for organizations and commercial entities requires annual fees but is free for individuals.

The JCP involves the use of Java Specification Requests (JSRs) the formal documents that describe proposed specifications and technologies for adding to the Java platform. Formal public reviews of JSRs take place before a JSR becomes final and the JCP Executive Committee votes on it. A final JSR provides a reference implementation that is a free implementation of the technology in source code form and a Technology Compatibility Kit to verify the API specification.

A JSR describes the JCP itself. As of 2009, JSR 215 describes the current version (2.7) of the JCP.

List of JSRs:

Refer to Java Language and Virtual Machine Specifications:

Setup Java Development Environment

Java Development on Windows

1) Download JDK from the Oracle site and install it. Or you can download NetBeans with JDK 8 directly if you like NetBeans IDE more.

2) Setup environment variables: JAVA_HOME, CLASSPATH, PATH

After JDK installation finished, right click My Computer and select Properties, then click Advanced System Settings on the left-side tree, and System Properties window is opened, then click Environment Variables and add the following three new properties if it’s not existed yet; otherwise, edit them.

Name Value
JAVA_HOME C:\Program Files\Java\jdk1.8.0_121
CLASSPATH .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar;
PATH %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin;

After the above configuration, you can check the Java SDK installation with command:

C:\Users\ewaadex>java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b15)
Java HotSpot(TM) Client VM (build 25.45-b02, mixed mode)

3) Install IDE for Java: Eclipse IDE for Java Developers or NetBeans IDE.

Java Development on Linux

1) Download JDK from the Oracle site and install it. Or you can download NetBeans with JDK 8 directly if you like NetBeans IDE more.

2) Setup environment variables: JAVA_HOME, CLASSPATH, PATH

~ $ vim /etc/profile

export JAVA_HOME=/opt/software/java/jdk_1.7.0_60
export JRE_HOME=/opt/software/java/jdk_1.7.0_60/jre
export CLASSPATH=.:$CLASSPATH:$JAVA_HOME/lib:$JRE_HOME/lib
export PATH=$PATH:$JAVA_HOME/bin:$JRE_HOME/bin

~ $ source /etc/profile

After the above configuration, you can check the Java SDK installation with command:

esekilxv8640 [4:29] [/home/ewaadex] -> java -version
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03, mixed mode)

3) Install IDE for Java: Eclipse IDE for Java Developers or NetBeans IDE.

Java Platform SE

Java Platform SE Architecture

The following conceptual diagram illustrates the components of Oracle’s Java SE 8, refer to Java Platform Standard Edition 8 Documentation:

Java SE 8 Conceptual Diagram

Oracle has two software products that implement Java Platform Standard Edition (Java SE) 8:

  • Java SE Runtime Environment (JRE) 8

    The JRE provides the libraries, Java Virtual Machine (JVM), and other components necessary for you to run applets and applications written in the Java programming language. This runtime environment can be redistributed with applications to make them free-standing. Note that the JRE includes components not required by the Java SE specification, including both standard and non-standard Java components.

  • Java SE Development Kit (JDK) 8

    The JDK is a superset of JRE, and contains everything that is in JRE, plus command-line development tools such as compilers and debuggers that are necessary or useful for developing applets and applications.

Java Virtual Machine (JVM)

Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a Java program. There are three notions of the JVM: specification, implementation, and instance. The specification is a document that formally describes what is required of a JVM implementation. Having a single specification ensures all implementations are interoperable. A JVM implementation is a computer program that meets the requirements of the JVM specification. An instance of a JVM is an implementation running in a process that executes a computer program compiled into Java bytecode.

Java Runtime Environment (JRE) is a software package that contains what is required to run a Java program. It includes a Java Virtual Machine (JVM) implementation together with an implementation of the Java Class Library. The Oracle Corporation, which owns the Java trademark, distributes a Java Runtime Environment (JRE) with their Java Virtual Machine called HotSpot.

Java Development Kit (JDK) is a superset of a JRE and contains tools for Java programmers, e.g. a javac compiler. The Java Development Kit (JDK) is provided free of charge either by Oracle Corporation directly, or by the OpenJDK open source project, which is governed by Oracle.

Refer to Java Language and Virtual Machine Specifications:

Overview of Java virtual machine (JVM) architecture based on Java SE 7

The JDK provides one or more implementations of the Java virtual machine (VM), refer to Java Virtual Machine Technology:

  • On platforms typically used for client applications, the JDK comes with a VM implementation called the Java HotSpot Client VM (client VM). The client VM is tuned for reducing start-up time and memory footprint. It can be invoked by using the -client command-line option when launching an application.

  • On all platforms, the JDK comes with an implementation of the Java virtual machine called the Java HotSpot Server VM (server VM). The server VM is designed for maximum program execution speed. It can be invoked by using the -server command-line option when launching an application.

Java Platform SE Packages

The core classes of the Java platform are in packages whose names begin with java. Extensions to the Java platform that have been standardized by Sun Microsystems typically have package names that begin with javax. The Java platform also includes several endorsed standards, which have packages named after the standards body that created them, such as org.w3c and org.omg.

Refer to Java Versions for the numbers of classes and packages in each Java SE release.

Java Bootstrap Packages

Text Conventions:

Java Platform, Standard Edition 8 has the following packages, refer to:

Packages Description
java.applet Provides the classes necessary to create an applet and the classes an applet uses to communicate with its applet context.
java.awt Contains all of the classes for creating user interfaces and for painting graphics and images.
java.awt.color Provides classes for color spaces.
java.awt.datatransfer Provides interfaces and classes for transferring data between and within applications.
java.awt.dnd Drag and Drop is a direct manipulation gesture found in many Graphical User Interface systems that provides a mechanism to transfer information between two entities logically associated with presentation elements in the GUI.
java.awt.event Provides interfaces and classes for dealing with different types of events fired by AWT components.
java.awt.font Provides classes and interface relating to fonts.
java.awt.geom Provides the Java 2D classes for defining and performing operations on objects related to two-dimensional geometry.
java.awt.im Provides classes and interfaces for the input method framework.
java.awt.im.spi Provides interfaces that enable the development of input methods that can be used with any Java runtime environment.
java.awt.image Provides classes for creating and modifying images.
java.awt.image.renderable Provides classes and interfaces for producing rendering-independent images.
java.awt.print Provides classes and interfaces for a general printing API.
java.beans Contains classes related to developing beans – components based on the JavaBeans architecture.
java.beans.beancontext Provides classes and interfaces relating to bean context.
java.io Provides for system input and output through data streams, serialization and the file system. Refer to Fundamental Classes in Java
java.lang Provides classes that are fundamental to the design of the Java programming language. Refer to Fundamental Classes in Java
java.lang.annotation Provides library support for the Java programming language annotation facility.
java.lang.instrument Provides services that allow Java programming language agents to instrument programs running on the JVM.
java.lang.invoke Contains dynamic language support provided directly by the Java core class libraries and virtual machine.
java.lang.management Provides the management interfaces for monitoring and management of the Java virtual machine and other components in the Java runtime.
java.lang.ref Provides reference-object classes, which support a limited degree of interaction with the garbage collector.
java.lang.reflect Provides classes and interfaces for obtaining reflective information about classes and objects. Refer to Fundamental Classes in Java
java.math Provides classes for performing arbitrary-precision integer arithmetic (BigInteger) and arbitraryprecision decimal arithmetic (BigDecimal). Refer to Fundamental Classes in Java
java.net Provides the classes for implementing networking applications. Refer to Fundamental Classes in Java
java.nio Defines buffers, which are containers for data, and provides an overview of the other NIO packages.
java.nio.channels Defines channels, which represent connections to entities that are capable of performing I/O operations, such as files and sockets; defines selectors, for multiplexed, non-blocking I/O operations.
java.nio.channels.spi Service-provider classes for the java.nio.channels package.
java.nio.charset Defines charsets, decoders, and encoders, for translating between bytes and Unicode characters.
java.nio.charset.spi Service-provider classes for the java.nio.charset package.
java.nio.file Defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems.
java.nio.file.attribute Interfaces and classes providing access to file and file system attributes.
java.nio.file.spi Service-provider classes for the java.nio.file package.
java.rmi Provides the RMI package.
java.rmi.activation Provides support for RMI Object Activation.
java.rmi.dgc Provides classes and interface for RMI distributed garbage-collection (DGC).
java.rmi.registry Provides a class and two interfaces for the RMI registry.
java.rmi.server Provides classes and interfaces for supporting the server side of RMI.
java.security Provides the classes and interfaces for the security framework.
java.security.acl The classes and interfaces in this package have been superseded by classes in the java.security package.
java.security.cert Provides classes and interfaces for parsing and managing certificates, certificate revocation lists (CRLs), and certification paths.
java.security.interfaces Provides interfaces for generating RSA (Rivest, Shamir and Adleman AsymmetricCipher algorithm) keys as defined in the RSA Laboratory Technical Note PKCS#1, and DSA (Digital Signature Algorithm) keys as defined in NIST’s FIPS-186.
java.security.spec Provides classes and interfaces for key specifications and algorithm parameter specifications.
java.sql Provides the API for accessing and processing data stored in a data source (usually a relational database) using the Java programming language.
java.text Provides classes and interfaces for handling text, dates, numbers, and messages in a manner independent of natural languages. Refer to Fundamental Classes in Java
java.text.spi Service provider classes for the classes in the java.text package.
java.time The main API for dates, times, instants, and durations.
java.time.chrono Generic API for calendar systems other than the default ISO.
java.time.format Provides classes to print and parse dates and times.
java.time.temporal Access to date and time using fields and units, and date time adjusters.
java.time.zone Support for time-zones and their rules.
java.util Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array). Refer to Fundamental Classes in Java
java.util.concurrent Utility classes commonly useful in concurrent programming.
java.util.concurrent.atomic A small toolkit of classes that support lock-free thread-safe programming on single variables.
java.util.concurrent.locks Interfaces and classes providing a framework for locking and waiting for conditions that is distinct from built-in synchronization and monitors.
java.util.function Functional interfaces provide target types for lambda expressions and method references.
java.util.jar Provides classes for reading and writing the JAR (Java ARchive) file format, which is based on the standard ZIP file format with an optional manifest file.
java.util.logging Provides the classes and interfaces of the Java 2 platform’s core logging facilities.
java.util.prefs This package allows applications to store and retrieve user and system preference and configuration data.
java.util.regex Classes for matching character sequences against patterns specified by regular expressions.
java.util.spi Service provider classes for the classes in the java.util package.
java.util.stream Classes to support functional-style operations on streams of elements, such as map-reduce transformations on collections.
java.util.zip Provides classes for reading and writing the standard ZIP and GZIP file formats. Refer to Fundamental Classes in Java

Fundamental Classes in Java

java.io package

java.io package structure

exception classes in java.io package

java.lang package

java.lang package structure

exception classes in java.lang package

error classes in java.lang package

java.lang.reflect package

java.lang.reflect package structure

java.math package

java.math package structure

java.net package

java.net package structure

java.text package

java.text package structure

java.util package

java.util package structure

java.util.zip package

java.util.zip package structure

Java Extension Packages

A optional package is an implementation of an open, standard API (examples of optional packages from Sun Microsystems are JavaServlet, Java3D, JavaManagement). Most optional packages are rooted in the javax.* namespace, although there may be exceptions. Refer to The Java Extension Mechanism and Extension Mechanism Architecture.

Java SE 8 has the following extension packages, refer to Java Platform, Standard Edition 8 API Specification.

Packages Description
javax.accessibility Defines a contract between user-interface components and an assistive technology that provides access to those components.
javax.activation  
javax.activity Contains Activity service related exceptions thrown by the ORB machinery during unmarshalling.
javax.annotation  
javax.annotation.processing Facilities for declaring annotation processors and for allowing annotation processors to communicate with an annotation processing tool environment.
javax.crypto Provides the classes and interfaces for cryptographic operations.
javax.crypto.interfaces Provides interfaces for Diffie-Hellman keys as defined in RSA Laboratories’ PKCS #3.
javax.crypto.spec Provides classes and interfaces for key specifications and algorithm parameter specifications.
javax.imageio The main package of the Java Image I/O API.
javax.imageio.event A package of the Java Image I/O API dealing with synchronous notification of events during the reading and writing of images.
javax.imageio.metadata A package of the Java Image I/O API dealing with reading and writing metadata.
javax.imageio.plugins.bmp Package containing the public classes used by the built-in BMP plug-in.
javax.imageio.plugins.jpeg Classes supporting the built-in JPEG plug-in.
javax.imageio.spi A package of the Java Image I/O API containing the plug-in interfaces for readers, writers, transcoders, and streams, and a runtime registry.
javax.imageio.stream A package of the Java Image I/O API dealing with low-level I/O from files and streams.
javax.jws  
javax.jws.soap  
javax.lang.model Classes and hierarchies of packages used to model the Java programming language.
javax.lang.model.element Interfaces used to model elements of the Java programming language.
javax.lang.model.type Interfaces used to model Java programming language types.
javax.lang.model.util Utilities to assist in the processing of program elements and types.
javax.management Provides the core classes for the Java Management Extensions.
javax.management.loading Provides the classes which implement advanced dynamic loading.
javax.management.modelmbean Provides the definition of the ModelMBean classes.
javax.management.monitor Provides the definition of the monitor classes.
javax.management.openmbean Provides the open data types and Open MBean descriptor classes.
javax.management.relation Provides the definition of the Relation Service.
javax.management.remote Interfaces for remote access to JMX MBean servers.
javax.management.remote.rmi The RMI connector is a connector for the JMX Remote API that uses RMI to transmit client requests to a remote MBean server.
javax.management.timer Provides the definition of the Timer MBean.
javax.naming Provides the classes and interfaces for accessing naming services.
javax.naming.directory Extends the javax.naming package to provide functionality for accessing directory services.
javax.naming.event Provides support for event notification when accessing naming and directory services.
javax.naming.ldap Provides support for LDAPv3 extended operations and controls.
javax.naming.spi Provides the means for dynamically plugging in support for accessing naming and directory services through the javax.naming and related packages.
javax.net Provides classes for networking applications.
javax.net.ssl Provides classes for the secure socket package.
javax.print Provides the principal classes and interfaces for the JavaTM Print Service API.
javax.print.attribute Provides classes and interfaces that describe the types of JavaTM Print Service attributes and how they can be collected into attribute sets.
javax.print.attribute.standard Contains classes for specific printing attributes.
javax.print.event Contains event classes and listener interfaces.
javax.rmi Contains user APIs for RMI-IIOP.
javax.rmi.CORBA Contains portability APIs for RMI-IIOP.
javax.rmi.ssl Provides implementations of RMIClientSocketFactory and RMIServerSocketFactory over the Secure Sockets Layer (SSL) or Transport Layer Security (TLS) protocols.
javax.script The scripting API consists of interfaces and classes that define Java Scripting Engines and provides a framework for their use in Java applications.
javax.security.auth Provides a framework for authentication and authorization.
javax.security.auth.callback Provides the classes necessary for services to interact with applications in order to retrieve information (authentication data including usernames or passwords, for example) or to display information (error and warning messages, for example).
javax.security.auth.kerberos Contains utility classes related to the Kerberos network authentication protocol.
javax.security.auth.login Provides a pluggable authentication framework.
javax.security.auth.spi Provides the interface to be used for implementing pluggable authentication modules.
javax.security.auth.x500 Contains the classes that should be used to store X500 Principal and X500 Private Crendentials in a Subject.
javax.security.cert Provides classes for public key certificates.
javax.security.sasl Contains class and interfaces for supporting SASL.
javax.sound.midi Provides interfaces and classes for I/O, sequencing, and synthesis of MIDI (Musical Instrument Digital Interface) data.
javax.sound.midi.spi Supplies interfaces for service providers to implement when offering new MIDI devices, MIDI file readers and writers, or sound bank readers.
javax.sound.sampled Provides interfaces and classes for capture, processing, and playback of sampled audio data.
javax.sound.sampled.spi Supplies abstract classes for service providers to subclass when offering new audio devices, sound file readers and writers, or audio format converters.
javax.sql Provides the API for server side data source access and processing from the JavaTM programming language.
javax.sql.rowset Standard interfaces and base classes for JDBC RowSet implementations.
javax.sql.rowset.serial Provides utility classes to allow serializable mappings between SQL types and data types in the Java programming language.
javax.sql.rowset.spi The standard classes and interfaces that a third party vendor has to use in its implementation of a synchronization provider.
javax.swing Provides a set of “lightweight” (all-Java language) components that, to the maximum degree possible, work the same on all platforms.
javax.swing.border Provides classes and interface for drawing specialized borders around a Swing component.
javax.swing.colorchooser Contains classes and interfaces used by the JColorChooser component.
javax.swing.event Provides for events fired by Swing components.
javax.swing.filechooser Contains classes and interfaces used by the JFileChooser component.
javax.swing.plaf Provides one interface and many abstract classes that Swing uses to provide its pluggable look-andfeel capabilities.
javax.swing.plaf.basic Provides user interface objects built according to the Basic look and feel.
javax.swing.plaf.metal Provides user interface objects built according to the Java look and feel (once codenamed Metal), which is the default look and feel.
javax.swing.plaf.multi Provides user interface objects that combine two or more look and feels.
javax.swing.plaf.nimbus Provides user interface objects built according to the cross-platform Nimbus look and feel.
javax.swing.plaf.synth Synth is a skinnable look and feel in which all painting is delegated.
javax.swing.table Provides classes and interfaces for dealing with javax.swing.JTable.
javax.swing.text Provides classes and interfaces that deal with editable and noneditable text components.
javax.swing.text.html Provides the class HTMLEditorKit and supporting classes for creating HTML text editors.
javax.swing.text.html.parser Provides the default HTML parser, along with support classes.
javax.swing.text.rtf Provides a class (RTFEditorKit) for creating Rich-Text-Format text editors.
javax.swing.tree Provides classes and interfaces for dealing with javax.swing.JTree.
javax.swing.undo Allows developers to provide support for undo/redo in applications such as text editors.
javax.tools Provides interfaces for tools which can be invoked from a program, for example, compilers.
javax.transaction Contains three exceptions thrown by the ORB machinery during unmarshalling.
javax.transaction.xa Provides the API that defines the contract between the transaction manager and the resource manager, which allows the transaction manager to enlist and delist resource objects (supplied by the resource manager driver) in JTA transactions.
javax.xml  
javax.xml.bind Provides a runtime binding framework for client applications including unmarshalling, marshalling, and validation capabilities.
javax.xml.bind.annotation Defines annotations for customizing Java program elements to XML Schema mapping.
javax.xml.bind.annotation.adapters XmlAdapter and its spec-defined sub-classes to allow arbitrary Java classes to be used with JAXB.
javax.xml.bind.attachment This package is implemented by a MIME-based package processor that enables the interpretation and creation of optimized binary data within an MIME-based package format.
javax.xml.bind.helpers JAXB Provider Use Only: Provides partial default implementations for some of the javax.xml.bind interfaces.
javax.xml.bind.util Useful client utility classes.
javax.xml.crypto Common classes for XML cryptography.
javax.xml.crypto.dom DOM-specific classes for the javax.xml.crypto package.
javax.xml.crypto.dsig Classes for generating and validating XML digital signatures.
javax.xml.crypto.dsig.dom DOM-specific classes for the javax.xml.crypto.dsig package.
javax.xml.crypto.dsig.keyinfo Classes for parsing and processing KeyInfo elements and structures.
javax.xml.crypto.dsig.spec Parameter classes for XML digital signatures.
javax.xml.datatype XML/Java Type Mappings.
javax.xml.namespace XML Namespace processing.
javax.xml.parsers Provides classes allowing the processing of XML documents.
javax.xml.soap Provides the API for creating and building SOAP messages.
javax.xml.stream  
javax.xml.stream.events  
javax.xml.stream.util  
javax.xml.transform This package defines the generic APIs for processing transformation instructions, and performing a transformation from source to result.
javax.xml.transform.dom This package implements DOM-specific transformation APIs.
javax.xml.transform.sax This package implements SAX2-specific transformation APIs.
javax.xml.transform.stax Provides for StAX-specific transformation APIs.
javax.xml.transform.stream This package implements stream- and URIspecific transformation APIs.
javax.xml.validation Provides an API for validation of XML documents.
javax.xml.ws Contains the core JAX-WS APIs.
javax.xml.ws.handler Defines APIs for message handlers.
javax.xml.ws.handler.soap Defines APIs for SOAP message handlers.
javax.xml.ws.http Defines APIs specific to the HTTP binding.
javax.xml.ws.soap Defines APIs specific to the SOAP binding.
javax.xml.ws.spi Defines SPIs for JAX-WS.
javax.xml.ws.spi.http Provides HTTP SPI that is used for portable deployment of JAX-WS web services in containers
javax.xml.ws.wsaddressing Defines APIs related to WS-Addressing.
javax.xml.xpath Provides an object-model neutral API for the evaluation of XPath expressions and access to the evaluation environment.

Other Packages

Java SE 8 also includes the following packages, refer to Java Platform, Standard Edition 8 API Specification.

Packages Description
org.ietf.jgss This package presents a framework that allows application developers to make use of security services like authentication, data integrity and data confidentiality from a variety of underlying security mechanisms like Kerberos, using a unified API.
org.omg.CORBA Provides the mapping of the OMG CORBA APIs to the JavaTM programming language, including the class ORB, which is implemented so that a programmer can use it as a fully-functional Object Request Broker (ORB).
org.omg.CORBA_2_3 Defines additions to existing CORBA interfaces in the Java Standard Edition 6. These changes occurred in recent revisions to the CORBA API defined by the OMG. The new methods were added to interfaces derived from the corresponding interfaces in the CORBA package. This provides backward compatibility and avoids breaking the JCK tests.
org.omg.CORBA_2_3.portable Provides methods for the input and output of value types, and contains other updates to the org/omg/CORBA/portable package.
org.omg.CORBA.DynAnyPackage Provides the exceptions used with the DynAny interface (InvalidValue, Invalid, InvalidSeq, and TypeMismatch).
org.omg.CORBA.ORBPackage Provides the exception InvalidName, which is thrown by the method ORB.resolve_initial_references and the exception InconsistentTypeCode, which is thrown by the Dynamic Any creation methods in the ORB class.
org.omg.CORBA.portable Provides a portability layer, that is, a set of ORB APIs that makes it possible for code generated by one vendor to run on another vendor’s ORB.
org.omg.CORBA.TypeCodePackage Provides the user-defined exceptions BadKind and Bounds, which are thrown by methods in in the class TypeCode.
org.omg.CosNaming Provides a naming service for Java IDL.
org.omg.CosNaming.NamingContextExtPackage Contains the following classes, which are used in org.omg.CosNaming.NamingContextExt
org.omg.CosNaming.NamingContextPackage Contains Exception classes for the org.omg.CosNaming package.
org.omg.Dynamic Contains the Dynamic module specified in the OMG Portable Interceptor specification, section 21.9.
org.omg.DynamicAny Provides classes and interfaces that enable traversal of the data value associated with an any at runtime, and extraction of the primitive constituents of the data value.
org.omg.DynamicAny.DynAnyFactoryPackage Contains classes and exceptions from the DynAnyFactory interface of the DynamicAny module specified in the OMG The Common Object Request Broker: Architecture and Specification, section 9.2.2.
org.omg.DynamicAny.DynAnyPackage Contains classes and exceptions from the DynAny interface of the DynamicAny module specified in the OMG The Common Object Request Broker: Architecture and Specification, section 9.2.
org.omg.IOP Contains the IOP module specified in the OMG document The Common Object Request Broker: Architecture and Specification, section 13.6.
org.omg.IOP.CodecFactoryPackage Contains the exceptions specified in the IOP::CodeFactory interface (as part of the Portable Interceptors spec).
org.omg.IOP.CodecPackage This package is generated from the IOP::Codec IDL interface definition.
org.omg.Messaging Contains the Messaging module specified in the OMG CORBA Messaging specification.
org.omg.PortableInterceptor Provides a mechanism to register ORB hooks through which ORB services can intercept the normal flow of execution of the ORB.
org.omg.PortableInterceptor.ORBInitInfoPackage Contains the exceptions and typedefs from the ORBInitInfo local interface of the PortableInterceptor module specified in the OMG Portable Interceptor specification, section 21.7.2.
org.omg.PortableServer Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.CurrentPackage Provides method implementations with access to the identity of the object on which the method was invoked.
org.omg.PortableServer.POAManagerPackage Encapsulates the processing state of the POAs it is associated with.
org.omg.PortableServer.POAPackage Allows programmers to construct object implementations that are portable between different ORB products.
org.omg.PortableServer.portable Provides classes and interfaces for making the server side of your applications portable across multivendor ORBs.
org.omg.PortableServer.ServantLocatorPackage Provides classes and interfaces for locating the servant.
org.omg.SendingContext Provides support for the marshalling of value types.
org.omg.stub.java.rmi Contains RMI-IIOP Stubs for the Remote types that occur in the java.rmi package.
org.w3c.dom Provides the interfaces for the Document Object Model (DOM).
org.w3c.dom.bootstrap  
org.w3c.dom.events  
org.w3c.dom.ls  
org.w3c.dom.views  
org.xml.sax Provides the core SAX APIs.
org.xml.sax.ext Contains interfaces to SAX2 facilities that conformant SAX drivers won’t necessarily support.
org.xml.sax.helpers Contains helper classes, including support for bootstrapping SAX-based applications.

Java Permission Classes

Java has the following permission classes in Java Bootstrap Packages and Java Extension Packages:

Permission Classes Description  
java.security.AllPermission An instance of this special permission class implies all other permissions.  
javax.sound.sampled.AudioPermission Controls the ability to play and record sound.  
javax.security.auth.AuthPermission Controls access to authentication methods in javax.security.auth and its subpackages.  
java.awt.AWTPermission Controls access to sensitive methods in java.awt and its subpackages.  
java.io.FilePermission Governs access to the filesystem.  
java.util.logging.LoggingPermission Controls the ability of a program to modify the logging configuration.  
java.net.NetPermission Governs access to networking-related resources such as stream handlers and HTTP authentication. See also java.net.SocketPermission.  
java.util.PropertyPermission Governs access to system properties.  
java.lang.reflect.ReflectPermission Governs access through the java.lang.reflect package to classes and class members that would normally be inaccessible.  
java.lang.RuntimePermission Governs access to a number of methods and resources. Many of the controlled methods are defined by java.lang.System and java.lang.Runtime.  
java.security.SecurityPermission Governs access to various security-related methods.  
java.io.SerializablePermission Governs access to serialization-related methods.  
java.net.SocketPermission Governs access to the network.  
java.sql.SQLPermission Governs the ability to specify logging streams in the java.sql JDBC API .

JDK Tools and Utilities

Sun Microsystems’ implementation of Java includes a number of tools for Java developers, refer to JDK Tools and Utilities of Java Plantform SE 8:

Tools Description
apt Annotation Processing Tool.
extcheck JAR Version Conflict Utility. extcheck checks to see if the extension contained in the specified jarfile (or a newer version of that extension) has already been installed on the system.
jarsigner JAR Signing and Verification Tool. jarsigner adds a digital signature to the specified jarfile, or, if the -verify option is specified, it verifies the digital signature or signatures already attached to the JAR file. jarsigner and the related keytool program replace the javakey program of Java 1.1.
jar Java Archive Tool. jar is a tool that can create and manipulate Java Archive (JAR) files. A JAR file is a ZIP file that contains Java class files, auxiliary resource files required by those classes, and optional meta-information.
java The Java Interpreter. java is the Java byte-code interpreter; it runs Java programs. The program to be run is the class specified by classname. This must be a fully qualified name: it must include the package name of the class but not the .class file extension. The specified class must define a main() method with exactly the following signature: public static void main(String[] args). In Java 1.2 and later, a program can be packaged in an executable JAR file. To run a program packaged in this fashion, use the -jar option to specify the JAR file. The Java interpreter runs until the main() method exits, and any threads (except for threads marked as daemon threads) created by the program have also exited.
javac The Java Compiler. javac is the Java compiler; it compiles Java source code (in .java files) into Java byte codes (in .class files). The Java compiler is itself written in Java.
javadoc The Java Documentation Generator. javadoc generates API documentation for any number of packages and classes you specify. javadoc uses the javac compiler to process all the specified Java source files and all the Java source files in all the specified packages. It uses the information it gleans from this processing to generate detailed API documentation. javadoc creates HTML documentation by default, but you can customize its behavior by defining a doclet class that generates documentation in whatever format you desire.
javah Native Method C Stub Generator. javah generates C header and source files (.h and .c files) that are used when implementing Java native methods in C.
javap The Java Class Disassembler. javap reads the class files specified by the class names on the command line and prints a human-readable version of the API defined by those classes. javap can also disassemble the specified classes, displaying the Java VM byte codes for the methods they contain.
javaws Java Web Start launcher. javaws is the command-line interface to the Java Web Start network application launcher. When started without a url, javaws displays a graphical cache viewer which allows cached applications to be launched and Java Web Start to be configured.
jconsole Graphical Java Process Monitor. jconsole is a graphical interface to the memory, thread, class loading, and other monitoring tools provided by the java.lang.management package. It can monitor one or more local or remote Java processes.
jdb The Java Debugger. jdb is a debugger for Java classes. It is text-based, command-line-oriented, and has a command syntax like that of the Unix dbx or gdb debuggers used with C and C++ programs. jdb can also debug a program that is already running in another Java interpreter.
jinfo Display configuration of a Java process. jinfo prints the system properties and JVM command-line options for a running Java process or core file. In Java 5.0, jinfo is experimental, unsupported, and not available on all platforms.
jmap Display memory usage. jmap prints memory usage information for a local or remote Java process or a Java core file. Depending on the option it is invoked with, jmap displays one of four memory usage reports. In Java 5.0, jmap is experimental, unsupported, and not available on all platforms.
jps List Java processes. jps lists the Java processes running on the local host or on the specified remote host. If a remote host is specified, it must be running the jstatd daemon. For each Java process, it displays a process id and names the class or JAR file that the process is executing. Process ids are used by a number of other Java tools, such as jconsole, jstat, and jmap. For instance, jps -lmv
jsadebugd Daemon process for remote debugging. jsadebugd is a server process that allows remote invocations of jinfo, jmap, and jstack on a local Java process or core file. In Java 5.0, jsadebugd is experimental, unsupported, and not available on all platforms.
jstack Display stack traces for a Java process. jstack prints stack traces for each of the Java threads running in the specified Java process.
jstat Java VM statistics. jstat probes a running JVM once or repeatedly and displays statistics about its class loading, just-in-time compilation, memory, or garbage collection performance. jconsole can report many of the same statistics that jstat does but displays them in graphical rather than tabular form.
jstatd jstat daemon. jstatd is a server that provides information about local Java processes to the jps and jstat programs running on remote hosts.
keytool Key and Certificate Management Tool. keytool manages and manipulates a keystore, a repository for public and private keys and public key certificates. keytool defines various commands for generating keys, importing data into the keystore, and exporting and displaying keystore data. Keys and certificates are stored in a keystore using a case-insensitive name or alias. keytool uses this alias to refer to a key or certificate.
native2ascii Convert text to ASCII with Unicode escapes. native2ascii is a simple program that reads a text file (usually of Java source code) encoded using a local encoding and converts it to a Latin-1-plus-ASCII-encodedUnicode form allowed by the Java Language Specification. This is helpful when you must edit a file of Java code but do not have an editor that can handle the encoding of the file.
pack200 Compress a JAR file. pack200 tightly compresses a JAR file using the compression algorithm defined by JSR 200 and the standard gzip compression algorithm. Notice that the output file is specified on the command line before the input JAR file.
policytool Policy File Creation and Management Tool. policytool displays a Swing user interface that makes it easy to edit security policy configuration files.
serialver Class Version Number Generator. serialver displays the version number of a class or classes. This version number is used for the purposes of serialization: the version number must change each time the serialization format of the class changes.
unpack200 Unpack a JAR file. unpack200 unpacks a JAR file that has been compressed, or packed, by the pack200 tool, and optionally additionally compressed with gzip.

Java Platform SE’s Other Implementations

OpenJDK

OpenJDK is a free and open source implementation of the Java Platform, Standard Edition (Java SE).

Before OpenJDK, several free Java implementations were made by various companies and groups. One example is Apache Harmony. IBM also provides Java implementations, and RedHat provides it through the IcedTea project: a build and integration project for OpenJDK.

IBM SDK

IBM SDK, Java Technology Edition, Version 8 is a new release that is fully compatible with Oracle Java SE version 8 class libraries. The IBM implementation of Java contains IBM technology and extensions.

JRockit

JRockit, a proprietary Java virtual machine (JVM) originally developed by Appeal Virtual Machines and acquired by BEA Systems in 2002, became part of Oracle Fusion Middleware as part of acquisition of BEA Systems in 2008.

The JRockit code base and the HotSpot virtual machine from Sun Microsystems (now Oracle) are currently being integrated, with the target of releasing a JVM with a combined code base around the release date of Java Development kit (JDK) 8.

JRockit was made free and publicly available in May 2011.

Many JRE class files distributed with JRockit exactly replicate those distributed with HotSpot. JRockit overrides class files which relate closely to the JVM, therefore retaining API compatibility while enhancing the performance (processing speed) of the JVM.

JRockit History

Following the finalization of the acquisition of Sun Microsystems, Oracle announced in JavaOne 2010 that the best features of JRockit would be implemented in OpenJDK.

In May 2011, Oracle announced that JRockit has become free, confirming that they plan to port JRockit features on OpenJDK.

JRockit Performance

Oracle claims that using JRockit can give significant performance gains. Server benchmarks on earlier Java Virtual Machines tend to show that server performance of HotSpot was better, but that JRockit had a much better scalability.

Java Compiling and Execution

In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those 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 (JVM). The java launcher tool then runs your application with an instance of the Java Virtual Machine (JVM).

An overview of the software development process

Because the Java Virtual Machine (JVM) is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris Operating System, Linux, or Mac OS. Some virtual machines, such as the Java SE HotSpot at a Glance, perform additional steps at runtime to give your application a performance boost. This includes various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code. Refer to About the Java Technology.

Through the Java VM, the same application is capable of running on multiple platforms

Java Language

Keywords

Here is a list of keywords in the Java programming language. You cannot use any of the following as identifiers in your programs. The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.

abstract continue for new switch
assert [3] default goto [1] package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum [4] instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp [2] volatile
const [1] float native super while

  • [1] not used
  • [2] added in 1.2
  • [3] added in 1.4
  • [4] added in 5.0

Operators

As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left. Refer to Operators and Summary of Operators.

Operator Precedence

Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

The following table summarizes the operators available in Java. The P and A columns of the table specify the precedence and associativity of each group of related operators, respectively.

  • The default operator precedence in Java was chosen for compatibility with C; the designers of C chose this precedence so that most expressions can be written naturally without parentheses.

Java Operators

instanceof operator

  • The instanceof operator requires an object or array value as its left operand and the name of a reference type as its right operand. It evaluates to true if the object or array is an instance of the specified type; it returns false otherwise.
  • If the left operand is null, instanceof always evaluates to false.
  • If an instanceof expression evaluates to true, it means that you can safely cast and assign the left operand to a variable of the type of the right operand.
  • The instanceof operator can be used only with reference types and objects, not primitive types and values.

shift operators

  • The << operator shifts the bits of the left operand left by the number of places specified by the right operand. High-order bits of the left operand are lost, and zero bits are shifted in from the right.
  • The >> operator shifts the bits of the left operand to the right by the number of places specified by the right operand. The low-order bits of the left operand are shifted away and are lost. The high-order bits shifted in are the same as the original high-order bit of the left operand.
  • This >>> operator is like the >> operator, except that it always shifts zeros into the high-order bits of the result, regardless of the sign of the left-hand operand. This technique is called zero extension; it is appropriate when the left operand is being treated as an unsigned value (despite the fact that Java integer types are all signed).

Comments

Java supports three types of comments:

Single-line Comments

Single-line comment begins with the characters // and continues until the end of the current line.

// comments until the end of the line

Multiline Comments

Multiline comment begins with the characters /* and continues, over any number of lines, until the characters */. This type of comment cannot be nested (i.e., one /* */ comment cannot appear within another).

/*
 * multiline comment
 */

Doc Comments

doc comment is a special case of the multiline comment. doc comment begins with /** and end with */. This type of comment also cannot be nested. A program named javadoc extracts these comments and processes them to create online documentation for your class. A doc comment can contain HTML tags and can use additional syntax understood by javadoc. Refer to Javadoc tool documentation:

  • A doc comment appears immediately before a type or member definition and contains documentation for that type or member.
  • The descriptive material in a doc comment can contain simple HTML markup tags.
/**
* This immutable class represents <i>complex numbers</i>.
*
* @author David Flanagan
* @version 1.0
*/
public class Complex {
    /**
     * Holds the real part of this complex number.
     * @see #y
     */
    protected double x;
    /**
     * Holds the imaginary part of this complex number.
     * @see #x
     */
    protected double y;
    /**
     * Creates a new Complex object that represents the complex number x+yi.
     * @param x The real part of the complex number.
     * @param y The imaginary part of the complex number.
     */
    public Complex(double x, double y) {
        this.x = x;
        this.y = y;
    }
    /**
     * Adds two Complex objects and produces a third object that represents
     * their sum.
     * @param c1 A Complex object
     * @param c2 Another Complex object
     * @return A new Complex object that represents the sum of
     *         <code>c1</code> and <code>c2</code>.
     * @exception java.lang.NullPointerException
     *            If either argument is <code>null</code>.
     */
    public static Complex add(Complex c1, Complex c2) {
        return new Complex(c1.x + c2.x, c1.y + c2.y);
    }
}

Doc-Comment Tags

javadoc recognizes a number of special tags, each of which begins with an @ character.

The following doc comment tags are recognized by javadoc; a doc comment should typically use these tags in the order listed here:

  • @author name

    Adds an Author: entry that contains the specified name. This tag should be used for every class or interface definition but must not be used for individual methods and fields.

  • @version text

    Inserts a Version: entry that contains the specified text. This tag should be included in every class and interface doc comment but cannot be used for individual methods and fields.

  • @param parameter-name description

    Adds the specified parameter and its description to the Parameters: section of the current method. The doc comment for a method or constructor must contain one @param tag for each parameter the method expects. These tags should appear in the same order as the parameters specified by the method. The tag can be used only in doc comments for methods and constructors.

  • @return description

    Inserts a Returns: section that contains the specified description. This tag should appear in every doc comment for a method, unless the method returns void or is a constructor.

  • @exception full-classname description / @throws full-classname description

    Adds a Throws: entry that contains the specified exception name and description. A doc comment for a method or constructor should contain an @exception tag for every checked exception that appears in its throws clause.

    If a method can throw more than one exception, use multiple @exception tags on adjacent lines and list the exceptions in alphabetical order.

    This tag can be used only for method and constructor comments. The @throws tag is a synonym for @exception.

  • @see reference

    Adds a See Also: entry that contains the specified reference. This tag can appear in any kind of doc comment.

  • @deprecated explanation

    This tag specifies that the following type or member has been deprecated and that its use should be avoided. javadoc adds a prominent Deprecated entry to the documentation and includes the specified explanation text.

  • @since version

    Specifies when the type or member was added to the API. This tag should be followed by a version number or other version specification.

    Every doc comment for a type should include an @since tag, and any members added after the initial release of the type should have @since tags in their doc comments.

  • @serial description

    If you write a class that you expect to be serialized, you should document its serialization format using @serial and the related tags listed below. @serial should appear in the doc comment for any field that is part of the serialized state of a Serializable class.

  • @serialField name type description

    A Serializable class can define its serialized format by declaring an array of ObjectStreamField objects in a field named serialPersistentFields. For such a class, the doc comment for serialPersistentFields should include an @serialField tag for each element of the array.

  • @serialData description

    A Serializable class can define a writeObject() method to write data other than that written by the default serialization mechanism. An Externalizable class defines a writeExternal() method responsible for writing the complete state of an object to the serialization stream. The @serialData tag should be used in the doc comments for these writeObject() and writeExternal() methods, and the description should document the serialization format used by the method.

Inline Doc-Comment Tags

In addition to the preceding tags, javadoc also supports several inline tags that may appear anywhere that HTML text appears in a doc comment.

Inline doc-comment JDK Version
{@link reference} Java 1.2 and later
{@linkplain reference} Java 1.4 and later
{@inheritDoc}  
{@docRoot} Java 1.3 and later
{@literal text} Java 5.0 and later
{@code text} Java 5.0 and later
{@value} Java 1.4 and later
{@value reference} Java 5.0 and later

Doc-Comments for Packages

javadoc can also read and display summary documentation for packages. Since a package is defined in a directory, not in a single file of source code, javadoc looks for the package documentation in a file named package.html in the directory that contains the source code for the classes of the package.

The package.html file should contain simple HTML documentation for the package. It can also contain @see, @link, @deprecated, and @since tags. Since package.html is not a file of Java source code, the documentation it contains should be HTML and should not be a Java comment (i.e., it should not be enclosed within /** and */ characters). Finally, any @see and @link tags that appear in package.html must use fully qualified class names.

In addition to defining a package.html file for each package, you can also provide high-level documentation for a group of packages by defining an overview.html file in the source tree for those packages. When javadoc is run over that source tree, it uses overview.html as the highest level overview it displays.

Primitive Data Types

Java has the following primitive data types:

Type Size Minimum Maximum Default Wrapper Type
boolean - - - false Boolean
char 16 bits Unicode 0 Unicode \(2^{16}-1\) ‘\u0000’ (null) Character
byte 8 bits \(-2^{7}\) \(+2^{7}-1\) (byte)0 Byte
short 16 bits \(-2^{15}\) \(+2^{15}-1\) (short)0 Short
int 32 bits \(-2^{31}\) \(+2^{31}-1\) 0 Integer
long 64 bits \(-2^{63}\) \(+2^{63}-1\) 0L Long
float 32 bits IEEE 754 IEEE 754 0.0f Float
double 64 bits IEEE 754 IEEE 754 0.0d Double
void - - - - Void

  • All numeric types are signed, so don’t look for unsigned types.
  • The size of the boolean type is not explicitly specified; it is only defined to be able to take the literal values true or false.
  • Java includes two classes for performing high-precision arithmetic: BigInteger and BigDecimal. Although these approximately fit into the same category as the “wrapper” classes, neither one has a primitive analogue.

Declare a variable:

{public | private} [static] type identifier [= expression];

boolean

  • C and C++ programmers should note that Java is quite strict about its boolean type: boolean values can never be converted to or from other data types.
  • boolean is not an integral type, and integer values cannot be used in place of a boolean.

char

  • char values can be converted to and from the various integral types.
  • Unlike byte, short, int, and long, however, char is an unsigned type.
  • char acts like an integer type in most ways, so a char value can be used anywhere an int or long value is required.
  • Unicode standard is evolving, and each new version of Java adopts the latest version of Unicode. Java 1.4 used Unicode 3.0 and Java 5.0 adopts Unicode 4.0.

Integer types: byte, short, int, long

  • All integral types represent signed numbers; there is no unsigned keyword as there is in C and C++.
  • Integer literals can also be expressed in hexadecimal (0x123) or octal notation (0123). Java does not allow integer literals to be expressed in binary (base-2) notation.
  • Integer literals are 32-bit int values unless they end with the character L or l, in which case they are 64-bit long values.
  • Integer arithmetic in Java is modular, which means that it never produces an overflow or an underflow when you exceed the range of a given integer type.

Floating-Point types: float, double

  • Real numbers in Java are represented by the float and double data types.
  • Floating-point literals are double values by default. To include a float value literally in a program, follow the number with F or f.
  • Floating-point literals cannot be expressed in hexadecimal or octal notation.
  • In addition to representing ordinary numbers, the float and double types can also represent four special values: positive and negative infinity, zero, and NaN. The infinity values result when a floating-point computation produces a value that overflows the representable range of a float or double. When a floating-point computation underflows the representable range of a float or a double, a zero value results. NaN stands for not-a-number. The NaN value results when an illegal floating-point operation, such as 0.0/0.0, is performed.
  • Because the Java floating-point types can handle overflow to infinity and underflow to zero and have a special NaN value, floating-point arithmetic never throws exceptions, even when performing illegal operations, like dividing zero by zero or taking the square root of a negative number.
  • The float and double primitive types have corresponding classes, named Float and Double. Each of these classes defines the following useful constants: MIN_VALUE, MAX_VALUE, NEGATIVE_INFINITY, POSITIVE_INFINITY, and NaN.

Primitive Type Conversions

There are two basic types of conversions:

  • Widening conversion occurs when a value of one type is converted to a wider type — one that has a larger range of legal values. Java performs widening conversions automatically when, for example, you assign an int literal to a double variable or a char literal to an int variable.
  • Narrowing conversions are another matter, however. A narrowing conversion occurs when a value is converted to a type that is not wider than it is.

The following table shows which primitive types can be converted to which other types and how the conversion is performed.

Java Primitive Type Conversions

  • The letter N in the table means that the conversion cannot be performed.
  • The letter Y means that the conversion is a widening conversion and is therefore performed automatically and implicitly by Java.
  • The letter C means that the conversion is a narrowing conversion and requires an explicit cast.
  • The notation Y* means that the conversion is an automatic widening conversion, but that some of the least significant digits of the value may be lost in the conversion.

Primitive Data Type’s Wrappers

The java.lang package includes the corresponding Byte, Short, Integer, Long, Float, and Double classes, each of which is a subclass of Number.

Primitive Types Wrappers of Primitive Types
boolean java.lang.Boolean
char java.lang.Character
byte java.lang.Byte
short java.lang.Short
int java.lang.Integer
long java.lang.Long
float java.lang.Float
double java.lang.Double

  • Each integer type (byte, short, int and long) has a corresponding wrapper class: Byte, Short, Integer, and Long. Each of these classes defines MIN_VALUE and MAX_VALUE constants that describe the range of the type.

Statements

if..else statement

if (Boolean-expression)
    statement1;
[ else statement2; ]

while statement

[initialization]
while (termination-clause) {
    body;
    [iteration;]
}

do..while statement

do {
    body;
    [iteration;]
} while (termination-clause);

for statement

for (initialization; termination-clause; iteration)
{
    body;
}

for/in statement

for (declaration : expression)
{
	statement;
}
  • The for/in statement is also called enhanced for or foreach.
  • expression must be either an array or an object that implements the java.lang.Iterable interface.
  • The type of the array or Iterable elements must be assignment-compatible with the type of the variable declared in the declaration.

break statement

  • The break statement is most often written as simply the keyword break followed by a semicolon.
  • The break statement can also be followed by the name of a containing labeled statement.
break;
break out;

synchronized Statement

Sections of code that must not be executed simultaneously are known as critical sections. Java provides the synchronized statement to protect these critical sections. For instance:

synchronized ( expression ) {
    statements
}
  • expression is an expression that must evaluate to an object or an array.
  • statements constitute the code of the critical section and must be enclosed in curly braces.
  • Before executing the critical section, the Java interpreter first obtains an exclusive lock on the object or array specified by expression. It holds the lock until it is finished running the critical section, then releases it. While a thread holds the lock on an object, no other thread can obtain that lock. Therefore, no other thread can execute this or any other critical sections that require a lock on the same object. If a thread cannot immediately obtain the lock required to execute a critical section, it simply waits until the lock becomes available.

throw statement

  • The throw statement is used to throw an exception. The expression must evaluate to an exception object that describes the exception or error that has occurred.

  • An exception in Java is an object. The type of this object is java.lang.Throwable, or more commonly, some subclass of Throwable that more specifically describes the type of exception that occurred. Throwable has two standard subclasses: java.lang.Error and java.lang.Exception.

throw expression;

try/catch/finally statement

  • The try/catch/finally statement is Java’s exception-handling mechanism.
  • An exception in Java is an object. The type of this object is java.lang.Throwable, or more commonly, some subclass of Throwable that more specifically describes the type of exception that occurred.
  • The only way a try clause can exit without allowing the finally clause to be executed is by invoking the System.exit() method, which causes the Java interpreter to stop running.
try {
/*
 * Normally this code runs from the top of the block to the bottom
 * without problems. But it can sometimes throw an exception,
 * either directly with a throw statement or indirectly by calling
 * a method that throws an exception.
 */
}
catch (SomeException e1) {
/*
 * This block contains statements that handle an exception object
 * of type SomeException or a subclass of that type. Statements in
 * this block can refer to that exception object by the name e1.
 */
}
catch (AnotherException e2) {
/*
 * This block contains statements that handle an exception object
 * of type AnotherException or a subclass of that type. Statements
 * in this block can refer to that exception object by the name e2.
 */
}
finally {
/*
 * This block contains statements that are always executed after
 * we leave the try clause, regardless of whether we leave it:
 * 1) normally, after reaching the bottom of the block;
 * 2) because of a break, continue, or return statement;
 * 3) with an exception that is handled by a catch clause above; or
 * 4) with an uncaught exception that has not been handled.
 * If the try clause calls System.exit(), however, the interpreter
 * exits before the finally clause can be run.
 */
}

assert statement

  • An assert statement is used to document and verify design assumptions in Java code. This statement was added in Java 1.4.
  • An assertion consists of the assert keyword followed by a boolean expression that the programmer believes should always evaluate to true.
  • It is important to understand that the assert statement is not suitable for enforcing preconditions on public methods.

  • By default, assertions are disabled, and assert statements have no effect.
  • To enable assertions in all classes except for system classes, use the -ea argument.
  • To enable assertions in system classes, use -esa.
  • To enable assertions within a specific class, use -ea followed by a colon and the classname: java -ea:com.example.sorters.MergeSort com.example.sorters.Test.
  • To enable assertions for all classes in a package and in all of its subpackages, follow the -ea argument with a colon, the package name, and three dots: java -ea:com.example.sorters... com.example.sorters.Test.
  • You can disable assertions in the same way, using the -da argument.
assert assertion;
assert assertion : errorcode;

Methods

modifiers type methodName ( paramlist ) [ throws exceptions ]
  • modifiers is zero or more special modifier keywords, separated from each other by spaces. modifier keywords: abstract, final, native, public/protected/private, static, strictfp, synchronized.

  • type in a method signature specifies the return type of the method. If the method does not return a value, type must be void. If a method is declared with a non-void return type, it must include a return statement that returns a value of (or convertible to) the declared type.

  • Defining multiple methods with the same name is called method overloading.

  • The final part of a method signature is the throws clause, which is used to list the checked exceptions that a method can throw.
    • In addition to making a distinction between Error and Exception classes, the Java exception-handling scheme also distinguishes between checked and unchecked exceptions.
    • Any exception object that is an Error is unchecked.
    • Any exception object that is an Exception is checked, unless it is a subclass of java.lang.RuntimeException, in which case it is unchecked. (RuntimeException is a subclass of Exception)
  • If your method calls a method that can throw a checked exception, you must either include exception-handling code to handle that exception or use throws to declare that your method can also throw that exception.

  • A variable-length argument list is declared by following the type of the last argument to the method with an ellipsis ..., indicating that this last argument can be repeated zero or more times.
  • Remember that only one ellipsis ... can appear in a parameter list, and it may only appear on the last parameter in the list.
public static int max(int first, int... rest) {
    int max = first;
    for(int i: rest) {
        if (i > max)
            max = i;
    }
    return max;
}

Classes

Class Definition Syntax

Class definition syntax:

  • The members of a class may have access modifiers public, protected, or private, which specify their visibility and accessibility to clients and to subclasses.
  • The signature of a class may declare that the class extends another class. The extended class is known as the superclass and the extension is known as the subclass.
  • Every class you define has a superclass. If you do not specify the superclass with an extends clause, the superclass is the class java.lang.Object. Object is a special class for a couple of reasons:
    • It is the only class in Java that does not have a superclass.
    • All Java classes inherit the methods of Object.
  • The signature of a class may also declare that the class implements one or more interfaces.
{ public | final | abstract } class className extends SuperClass implements Interface1, Interface2 {

    /* Fields includes class fields and instance fields */
    field definition1
    ...
    field definitionN

    /* Methods includes class methods and instance methods */
    method definition1
    ...
    method definitionN

    /* Override methods defined in SuperClass */
    @Override
    method definitionX

    /* Implement methods declared in Interface1 and Interface2 */
    method definitionY

    /* A class may include main entry of Java program */
    public static void main (String args[]) {
        statements;
    }
}

Class declarations may include zero or more of the following modifiers:

  • public: A public class is visible to classes defined outside of its package.
  • abstract: An abstract class is one whose implementation is incomplete and cannot be instantiated. Any class with one or more abstract methods must be declared abstract.
  • final: The final modifier specifies that the class may not be extended. Declaring a class final may enable the Java VM to optimize its methods.
  • strictfp: If a class is declared strictfp, all its methods behave as if they were declared strictfp.

A class cannot be both abstract and final. By convention, if a class has more than one modifier, they appear in the order shown above.

Fields and Methods Declaration Syntax

Field modifiers are comprised of zero or more of the following keywords:

  • public, protected, private: These access modifiers specify whether and where a field can be used outside of the class that defines it.
  • static: If present, this modifier specifies that the field is associated with the defining class itself rather than with each instance of the class.
  • final: This modifier specifies that once the field has been initialized, its value may never be changed. Fields that are both static and final are compile-time constants that the compiler can inline. final fields can also be used to create classes whose instances are immutable.
  • transient: This modifier specifies that a field is not part of the persistent state of an object and that it need not be serialized along with the rest of the object.
  • volatile: Roughly speaking, a volatile field is like a synchronized method: safe for concurrent use by two or more threads. More accurately, volatile says that the value of a field must always be read from and flushed to main memory, and that it may not be cached by a thread (in a register or CPU cache).

Class Fields

  • The static modifier says that the field is a class field. Class fields are sometimes called static fields because of this static modifier.
  • Defining constants like this is a common use for class fields, meaning that the static and final modifiers are often used together.
public static final double PI = 3.14159;

Class Methods

  • As with class fields, class methods are declared with the static modifier.
  • Since a class method is not associated with an instance of its class, it cannot use any instance methods or fields.
public static double radiansToDegrees(double rads) { return rads * 180 / PI; }

Instance Fields

  • Any field declared without the static modifier is an instance field.
  • Instance fields are associated with instances of the class, rather than with the class itself.
  • Inside a class definition, instance fields are referred to by name alone. In code outside the class, the name of an instance method must be prefixed with a reference to the object that contains it.

Instance Methods

  • Any method not declared with the static keyword is an instance method.
  • To use an instance method from outside the class in which it is defined, we must prefix it with a reference to the instance that is to be operated on.
  • Instance methods can use any member of a class, whether it is declared static or not.
  • All instance methods are implemented with an implicit parameter not shown in the method signature: this, it holds a reference to the object through which the method is invoked. Note: when a method parameter or local variable in a method has the same name as one of the fields of the class, you must use this to refer to the field since the field name used alone refers to the method parameter or local variable.

Constructor

  • Every class in Java has at least one constructor, whose purpose is to perform any necessary initialization for a new object.
  • If no constructor is defined for a class, Java will define a default constructor that takes no arguments and performs no special initialization.

  • The constructor name is always the same as the class name.
  • Unlike all other methods, a constructor is declared without a return type, not even void.
  • It is perfectly legal to define multiple constructors for a class, as long as each constructor has a different parameter list.

  • Here’s how a constructor works. The new operator creates a new, but uninitialized, instance of the class. The constructor method is then called, with the new object passed implicitly (a this reference, as we saw earlier) as well as whatever arguments that are specified between parentheses passed explicitly. The constructor can use these arguments to do whatever initialization is necessary.

  • The this keyword can be used from a constructor to invoke one of the other constructors of the same class.
  • There is an important restriction on using this(): it can appear only as the first statement in a constructor.
// This is the basic constructor: initialize the radius
public Circle(double r) { this.r = r; }
// This constructor uses this() to invoke the constructor above
public Circle() { this(1.0); }
  • super() is used to invoke the constructor method of a superclass from within the constructor method of a subclass. Invoking a constructor using super() is subject to the same restrictions as is using this():
    • super() can be used in this way only within a constructor method.
    • The call to the superclass constructor must appear as the first statement within the constructor method, even before local variable declarations.

  • Java guarantees that the constructor method of a class is called whenever an instance of that class is created.
  • It also guarantees that the constructor is called whenever an instance of any subclass is created. In order to guarantee this second point, Java must ensure that every constructor method calls its superclass constructor method. Thus, if the first statement in a constructor does not explicitly invoke another constructor with this() or super(), Java implicitly inserts the call super(), that is, it calls the superclass constructor with no arguments. If the superclass does not have a constructor that takes no arguments, this implicit invocation causes a compilation error.
  • That means constructor calls are chained; any time an object is created, a sequence of constructor methods is invoked, from subclass to superclass on up to Object at the root of the class hierarchy.
  • There is an important implication here; when a constructor is invoked, it can count on the fields of its superclass to be initialized.
  • What if a class is declared without a constructor? In this case, Java implicitly adds a constructor to the class. This default constructor does nothing but invoke the superclass constructor.
  • In general, if a class does not define a no-argument constructor, all its subclasses must define constructors that explicitly invoke the superclass constructor with the necessary arguments.
  • Classes that should never be instantiated (such as java.lang.Math or java.lang.System) should define a private constructor. Such a constructor can never be invoked from outside of the class, but it prevents the automatic insertion of the default constructor.

Static Initializer

  • Java does allow us to write arbitrary code for the initialization of class fields, however, with a construct known as a static initializer.
  • A static initializer is simply the keyword static followed by a block of code in curly braces.
  • A static initializer can appear in a class definition anywhere a field or method definition can appear.
  • A class can have any number of static initializers. The body of each initializer block is incorporated into the class initialization method, along with any static field initialization expressions.
  • A static initializer is like a class method in that it cannot use the this keyword or any instance fields or instance methods of the class.
// We can draw the outline of a circle using trigonometric functions
// Trigonometry is slow, though, so we precompute a bunch of values
public class TrigCircle {
    // Here are our static lookup tables and their own simple initializers
    private static final int NUMPTS = 500;
    private static double sines[] = new double[NUMPTS];
    private static double cosines[] = new double[NUMPTS];

    // Here's a static initializer that fills in the arrays
    static {
        double x = 0.0;
        double delta_x = (Circle.PI/2)/(NUMPTS-1);
        for(int i = 0, x = 0.0; i < NUMPTS; i++, x += delta_x) {
            sines[i] = Math.sin(x);
            cosines[i] = Math.cos(x);
        }
    }
    // The rest of the class is omitted...
}

Instance Initializer

  • In Java 1.1 and later, classes are also allowed to have instance initializers. Instance initializers were introduced in Java 1.1 to support anonymous inner classes, which are not allowed to define constructors.
  • An instance initializer is like a static initializer, except that it initializes an object, not a class.
  • A class can have any number of instance initializers, and they can appear anywhere a field or method definition can appear. The body of each *instance initializer is inserted at the beginning of every constructor for the class, along with any field initialization expressions.
  • An instance initializer looks just like a static initializer, except that it doesn’t use the static keyword. In other words, an instance initializer is just a block of arbitrary Java code that appears within curly braces.
private static final int NUMPTS = 100;
private int[] data = new int[NUMPTS];
{
    for (int i = 0; i < NUMPTS; i++)
        data[i] = i;
}

Finalizer

  • A finalizer in Java is the opposite of a constructor. While a constructor method performs initialization for an object, a finalizer method can be used to perform cleanup or finalization for the object.
  • A finalizer is an instance method that takes no arguments and returns no value.
  • There can be only one finalizer per class, and it must be named finalize().
  • A finalizer can throw any kind of exception or error, but when a finalizer is automatically invoked by the garbage collector, any exception or error it throws is ignored and serves only to cause the finalizer method to return.
  • Finalizer methods are typically declared protected but can also be declared public.

  • If an object has a finalizer, the finalizer method is invoked sometime after the object becomes unused (or unreachable), but before the garbage collector reclaims the object.
  • Java makes no guarantees about when garbage collection will occur or in what order objects will be collected. Therefore, Java can make no guarantees about when (or even whether) a finalizer will be invoked, in what order finalizers will be invoked, or what thread will execute finalizers.
  • The Java interpreter can exit without garbage collecting all outstanding objects, so some finalizers may never be invoked.
  • After a finalizer is invoked, objects are not freed right away. This is because a finalizer method can resurrect an object by storing the this pointer somewhere so that the object once again has references. Thus, after finalize() is called, the garbage collector must once again determine that the object is unreferenced before it can garbage-collect it.
  • The finalize() method is an instance method, and finalizers act on instances. There is no equivalent mechanism for finalizing a class.
protected void finalize() throws Throwable {
	/*
	 * Invoke the finalizer of our superclass
	 */
	super.finalize();

	/*
	 * Delete a temporary file we were using.
	 * If the file doesn't exist or tempfile is null, this
	 * can throw an exception, but that exception is ignored.
	 */
	tempfile.delete();
}

Access Control

All the fields and methods of a class can always be used within the body of the class itself. Java defines access control rules that restrict members of a class from being used outside the class.

Access to packages

  • A package is always accessible to code defined within the package. Whether it is accessible to code from other packages depends on the way the package is deployed on the host system. Package access is not part of the Java language itself. Access control is usually done at the level of classes and members of classes instead.

Access to classes

  • By default, top-level classes are accessible within the package in which they are defined. However, if a top-level class is declared public, it is accessible everywhere (or everywhere that the package itself is accessible).

Access to members

  • The members of a class are always accessible within the body of the class.
  • By default, members are also accessible throughout the package in which the class is defined. This default level of access is often called package access.
  • If a member of a class is not declared with any of these modifiers (public, protected, and private), it has the default package access: it is accessible to code within all classes that are defined in the same package but inaccessible outside of the package

Access control and inheritance

  • The Java specification states that a subclass inherits all the instance fields and instance methods of its superclass accessible to it.
  • If the subclass is defined in the same package as the superclass, it inherits all non-private instance fields and methods.
  • If the subclass is defined in a different package, however, it inherits all protected and public instance fields and methods.
  • private fields and methods are never inherited; neither are class fields or class methods.
  • Constructors are not inherited.

Class-member-access-summary

Abstract Methods

Java lets us define a method without implementing it by declaring the method with the abstract modifier. An abstract method has no body; it simply has a signature definition followed by a semicolon.

Here are the rules about abstract methods and the abstract classes that contain them:

  • Any class with an abstract method is automatically abstract itself and must be declared as such.
  • An abstract class cannot be instantiated.
  • A subclass of an abstract class can be instantiated only if it overrides each of the abstract methods of its superclass and provides an implementation (i.e., a method body) for all of them.
  • If a subclass of an abstract class does not implement all the abstract methods it inherits, that subclass is itself abstract and must be declared as such.
  • static, private, and final methods cannot be abstract since these types of methods cannot be overridden by a subclass. Similarly, a final class cannot contain any abstract methods.
  • A class can be declared abstract even if it does not actually have any abstract methods. Declaring such a class abstract indicates that the implementation is somehow incomplete and is meant to serve as a superclass for one or more subclasses that complete the implementation. Such a class cannot be instantiated.

Interfaces

  • Like a class, an interface defines a new reference type. Unlike classes, however, interfaces provide no implementation for the types they define.
  • As its name implies, an interface specifies only an API: all of its methods are abstract and have no bodies.
  • It is not possible to directly instantiate an interface and create a member of the interface type. Instead, a class must implement the interface to provide the necessary method bodies. Any instances of that class are members of both the type defined by the class and the type defined by the interface.
  • Interfaces provide a limited but very powerful alternative to multiple inheritance. Classes in Java can inherit members from only a single superclass, but they can implement any number of interfaces.
public interface Centered {
    void setCenter(double x, double y);
    double getCenterX();
    double getCenterY();
}

A number of restrictions apply to the members of an interface:

  • An interface contains no implementation whatsoever. All methods of an interface are implicitly abstract and must have a semicolon in place of a method body. The abstract modifier is allowed but, by convention, is usually omitted. Since static methods may not be abstract, the methods of an interface may not be declared static.
  • An interface defines a public API. All members of an interface are implicitly public, and it is conventional to omit the unnecessary public modifier. It is an error to define a protected or private method in an interface.
  • An interface may not define any instance fields. Fields are an implementation detail, and an interface is a pure specification without any implementation. The only fields allowed in an interface definition are constants that are declared both static and final.
  • An interface cannot be instantiated, so it does not define a constructor.
  • Interfaces may contain nested types. Any such types are implicitly public and static.

Interfaces vs. Abstract Classes

  • An interface is useful because any class can implement it, even if that class extends some entirely unrelated superclass. But an interface is a pure API specification and contains no implementation. If an interface has numerous methods, it can become tedious to implement the methods over and over, especially when much of the implementation is duplicated by each implementing class.
  • An abstract class does not need to be entirely abstract; it can contain a partial implementation that subclasses can take advantage of. In some cases, numerous subclasses can rely on default method implementations provided by an abstract class. But a class that extends an abstract class cannot extend any other class, which can cause design difficulties in some situations.
  • Another important difference between interfaces and abstract classes has to do with compatibility. If you define an interface as part of a public API and then later add a new method to the interface, you break any classes that implemented the previous version of the interface. If you use an abstract class, however, you can safely add nonabstract methods to that class without requiring modifications to existing classes that extend the abstract class.
  • In some situations, it is clear that an interface or an abstract class is the right design choice. In other cases, a common design pattern is to use both. Define the type as a totally abstract interface, then create an abstract class that implements the interface and provides useful default implementations that subclasses can take advantage of.

Arrays

Declare an integer array and allocate 100 elements of memory:

int arrayName1[];
arrayName = new int[100];

char arrayName2[] = new char[100];

Declare and allocate an integer array in one statement:

int arrayName[] = new int[100];
int arrayName[] = { 1, 2, 3, 4 };
String[] greetings = { "Hello", "Hi", "Howdy" };

Multidimensional array:

int arrayName[] = new int[10][20];
  • Since arrays extend Object and implement the Cloneable and Serializable interfaces, any array type can be widened to any of these three types.
  • The array index expression must be of type int, or a type that can be widened to an int: byte, short, or even char.
  • It is obviously not legal to index an array with a boolean, float, or double value.
  • Remember that the length field of an array is an int and that arrays may not have more than Integer.MAX_VALUE elements.
  • Remember that the first element of an array a is a[0], the second element is a[1] and the last is a[a.length-1]. If an array index is too small or too large, Java throws an ArrayIndexOutOfBoundsException immediately.

Reference Types

Reference types are:

Reference vs. Primitive Types

Reference types and objects differ substantially from primitive types and their primitive values:

  • Eight primitive types are defined by the Java language. Reference types are user-defined, so there is an unlimited number of them.
  • Primitive types represent single values. Reference types are aggregate types that hold zero or more primitive values or objects.
  • Primitive types require between one and eight bytes of memory. When a primitive value is stored in a variable or passed to a method, the computer makes a copy of the bytes that hold the value. Objects, on the other hand, may require substantially more memory. Memory to store an object is dynamically allocated on the heap when the object is created and this memory is automatically garbage-collected when the object is no longer needed. When an object is assigned to a variable or passed to a method, the memory that represents the object is not copied. Instead, only a reference to that memory is stored in the variable or passed to the method.

The nature of references:

  • A reference is simply some kind of reference to an object.
  • If you are a C programmer, however, you can safely imagine a reference as a pointer or a memory address. Remember, though, that Java programs cannot manipulate references in any way. Unlike pointers in C and C++, references cannot be converted to or from integers, and they cannot be incremented or decremented.
  • C and C++ programmers should also note that Java does not support the & address-of operator or the * and -> dereference operators.
  • In Java, primitive types are always handled exclusively by value, and objects are always handled exclusively by reference.

  • Objects can be converted between different reference types. As with primitive types, reference type conversions can be widening conversions (allowed automatically by the compiler) or narrowing conversions that require a cast (and possibly a runtime check).

    • An object cannot be converted to an unrelated type.
    • An object can be converted to the type of its superclass or of any ancestor class. This is a widening conversion, so no cast is required.
    • An object can be converted to the type of a subclass, but this is a narrowing conversion and requires a cast. Only cast an object to the type of a subclass if you are sure, based on the logic of your program, that the object is actually an instance of the subclass. If it is not, the interpreter throws a ClassCastException.

Annotation

According to Java Annotation on Wikipedia:

In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Like Javadoc tags, Java annotations can be read from source files. Unlike Javadoc tags, Java annotations can also be embedded in and read from class files generated by the compiler. This allows annotations to be retained by JVM at run-time and read via reflection. It is possible to create meta-annotations out of the existing ones in Java.

The Java platform has various ad-hoc annotation mechanisms - for example, the transient modifier, or the @deprecated javadoc tag. JSR-175 introduced the general-purpose annotation (also known as metadata) facility to the Java Community Process (JCP) in 2002; it gained approval in September 2004. Annotations became available in the language itself beginning with version 1.5 of the JDK. The apt tool provided a provisional interface for compile-time annotation processing in JDK version 1.5; JSR-269 formalized this, and it became integrated into the javac compiler in JDK version 1.6.

Also refer to JSR-250: Common Annotations for the Java Platform (Online, Local PDF).

Built-in Annotations

Java defines a set of annotations that are built into the language. Of the seven standard annotations, three are part of java.lang, and the remaining four are imported from java.lang.annotation:

Annotations applied to Java code:

Annotations Description
@Override Checks that the method is an override. Causes a compile error if the method is not found in one of the parent classes or implemented interfaces. Refer to Annotation Type Override in Java SE 10.
@Deprecated Marks the method as obsolete. Causes a compile warning if the method is used. Refer to Annotation Type Deprecated in Java SE 10.
@SuppressWarnings Instructs the compiler to suppress the compile time warnings specified in the annotation parameters. Refer to Annotation Type SuppressWarnings in Java SE 10.

Annotations applied to other annotations (also known as “Meta Annotations”):

Annotations Description
@Retention Specifies how the marked annotation is stored - Whether in code only, compiled into the class, or available at runtime through reflection. Refer to Annotation Type Retention in Java SE 10.
@Documented Marks another annotation for inclusion in the documentation. Refer to Annotation Type Documented in Java SE 10.
@Target Marks another annotation to restrict what kind of Java elements the annotation may be applied to. Refer to Annotation Type Target in Java SE 10
@Inherited Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses). Refer to Annotation Type Inherited in Java SE 10.

Since Java 7, three additional annotations have been added to the language:

Annotations Description
@SafeVarargs Suppress warnings for all callers of a method or constructor with a generics varargs parameter, since Java 7. Refer to Annotation Type SafeVarargs in Java SE 10.
@FunctionalInterface Specifies that the type declaration is intended to be a functional interface, since Java 8. Refer to Annotation Type FunctionalInterface in Java SE 10.
@Repeatable Specifies that the annotation can be applied more than once to the same declaration, since Java 8. Refer to Annotation Type Repeatable in Java SE 10.

For instance:

public class Animal {
    public void speak() {
    }

    public String getType() {
        return "Generic animal";
    }
}

public class Cat extends Animal {
    @Override
    public void speak() {       // This is a good override.
        System.out.println("Meow.");
    }

    @Override
    public String gettype() {   // Compile-time error due to mistyped name.
        return "Cat";
    }
}

Custom Annotations

Annotation type declarations are similar to normal interface declarations. An at-sign @ precedes the interface keyword. Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. Methods can have default values.

// @Twizzle is an annotation to method toggle().
@Twizzle
public void toggle() {
}

// Declares the annotation Twizzle.
public @interface Twizzle {
}

Annotations may include an optional list of key-value pairs:

// Same as: @Edible(value = true)
@Edible(true)
Item item = new Carrot();

public @interface Edible {
    boolean value() default false;
}

@Author(first = "Oompah", last = "Loompah")
Book book = new Book();

public @interface Author {
  String first();
  String last();
}

Annotations themselves may be annotated to indicate where and when they can be used:

@Retention(RetentionPolicy.RUNTIME) // Make this annotation accessible at runtime via reflection.
@Target({ElementType.METHOD})       // This annotation can only be applied to class methods.
public @interface Tweezable {
}

The compiler reserves a set of special annotations (including @Deprecated, @Override and @SuppressWarnings) for syntactic purposes.

Annotations are often used by frameworks as a way of conveniently applying behaviours to user-defined classes and methods that must otherwise be declared in an external source (such as an XML configuration file) or programmatically (with API calls). The following, for example, is an annotated JPA data class:

@Entity                                             // Declares this an entity bean
@Table(name = "people")                             // Maps the bean to SQL table "people"
public class Person implements Serializable {
    @Id                                             // Map this to the primary key column.
    @GeneratedValue(strategy = GenerationType.AUTO) // Database will generate new primary keys, not us.
    private Integer id;

    @Column(length = 32)                            // Truncate column values to 32 characters.
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The annotations are not method calls and will not, by themselves, do anything. Rather, the class object is passed to the JPA implementation at run-time, which then extracts the annotations to generate an object-relational mapping.

A complete example is given below:

package com.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,
         ElementType.CONSTRUCTOR,ElementType.ANNOTATION_TYPE,
         ElementType.PACKAGE,ElementType.FIELD,ElementType.LOCAL_VARIABLE})
@Inherited

public @interface Unfinished {
    public enum Priority { LOW, MEDIUM, HIGH }
    String value();
    String[] changedBy() default "";
    String[] lastChangedBy() default "";
    Priority priority() default Priority.MEDIUM;
    String createdBy() default "James Gosling";
    String lastChanged() default "2011-07-08";
}
package com.annotation;

public @interface UnderConstruction {
    String owner() default "Patrick Naughton";
    String value() default "Object is Under Construction.";
    String createdBy() default "Mike Sheridan";
    String lastChanged() default "2011-07-08";
}
package com.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.annotation.UnderConstruction;
import com.annotation.Unfinished;
import com.annotation.Unfinished.Priority;
import com.util.Util;

@UnderConstruction(owner="Jon Doe")
public class DateValidator implements Validator {

    public void validate(FacesContext context, UIComponent component, Object value)
        throws ValidatorException
    {
        String date = (String) value;
        String errorLabel = "Please enter a valid date.";
        if (!component.getAttributes().isEmpty())
        {
            errorLabel = (String) component.getAttributes().get("errordisplayval");
        }

        if (!Util.validateAGivenDate(date))
        {
            @Unfinished(changedBy = "Steve",
                value = "whether to add message to context or not, confirm",
                priority = Priority.HIGH
            )
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setSummary(errorLabel);
            message.setDetail(errorLabel);
            throw new ValidatorException(message);
        }
    }
}

Annotation Processing

When Java source code is compiled, annotations can be processed by compiler plug-ins called annotation processors. Processors can produce informational messages or create additional Java source files or resources, which in turn may be compiled and processed, and also modify the annotated code itself. The Java compiler conditionally stores annotation metadata in the class files, if the annotation has a RetentionPolicy of CLASS or RUNTIME. Later, the Java Virtual Machine (JVM) or other programs can look for the metadata to determine how to interact with the program elements or change their behavior.

In addition to processing an annotation using an annotation processor, a Java programmer can write their own code that uses reflections to process the annotation. Java SE 5 supports a new interface that is defined in the java.lang.reflect package. This package contains the interface called AnnotatedElement that is implemented by the Java reflection classes including Class, Constructor, Field, Method, and Package. The implementations of this interface are used to represent an annotated element of the program currently running in the Java Virtual Machine (JVM). This interface allows annotations to be read reflectively.

The AnnotatedElement interface provides access to annotations having RUNTIME retention. This access is provided by the getAnnotation, getAnnotations, and isAnnotationPresent methods. Because annotation types are compiled and stored in byte code files just like classes, the annotations returned by these methods can be queried just like any regular Java object. A complete example of processing an annotation is provided below:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

// This is the annotation to be processed
// Default for Target is all Java Elements
// Change retention policy to RUNTIME (default is CLASS)
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeHeader {
    // Default value specified for developer attribute
    String developer() default "Unknown";
    String lastModified();
    String [] teamMembers();
    int meaningOfLife();
}
// This is the annotation being applied to a class
@TypeHeader(developer = "Bob Bee",
    lastModified = "2013-02-12",
    teamMembers = { "Ann", "Dan", "Fran" },
    meaningOfLife = 42)

public class SetCustomAnnotation {
    // Class contents go here
}
// This is the example code that processes the annotation
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;

public class UseCustomAnnotation {
    public static void main(String [] args) {
        Class<SetCustomAnnotation> classObject = SetCustomAnnotation.class;
        readAnnotation(classObject);
    }

    static void readAnnotation(AnnotatedElement element) {
        try {
            System.out.println("Annotation element values: \n");
            if (element.isAnnotationPresent(TypeHeader.class)) {
                // getAnnotation returns Annotation type
                Annotation singleAnnotation =
                        element.getAnnotation(TypeHeader.class);
                TypeHeader header = (TypeHeader) singleAnnotation;

                System.out.println("Developer: " + header.developer());
                System.out.println("Last Modified: " + header.lastModified());

                // teamMembers returned as String []
                System.out.print("Team members: ");
                for (String member : header.teamMembers())
                    System.out.print(member + ", ");
                System.out.print("\n");

                System.out.println("Meaning of Life: "+ header.meaningOfLife());
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

Packages and Java Namespace

package

A package is a named collection of classes, interfaces, and other reference types. Packages serve to group related classes and define a namespace for the classes they contain.

To specify the package a class is to be part of, you use a package declaration. The package keyword, if it appears, must be the first token of Java code (i.e., the first thing other than comments and space) in the Java file.

If no package directive appears in a Java file, all classes defined in that file are part of an unnamed default package. In this case, the qualified and unqualified names of a class are the same.

import

The types from java.lang and the current package are imported into the namespace so that they can be used without their package name.

import declarations must appear at the start of a Java file, immediately after the package declaration, if there is one, and before any type definitions.

In Java 5.0 and later, you can import the static members of types as well as types themselves using the keywords import static.

Another important use of import static declarations is to import the names of constants into your code. This works particularly well with enumerated types.

A static import declaration imports a name, not any one specific member with that name. Since Java allows method overloading and allows a type to have fields and methods with the same name, a single static member import declaration may actually import more than one member.

Java File Structure

Java file is the smallest unit of Java code that can be compiled by the Java compiler. A Java file consists of:

  • An optional package directive
  • Zero or more import or import static directives
  • One or more type definitions

All Java statements (except the package and import directives, which are not true statements) must appear within methods, and all methods must appear within a type definition.

Java files have a couple of other important restrictions:

  • First, each file can contain at most one class that is declared public.

    • A public class is one that is designed for use by other classes in other packages.
    • This restriction on public classes only applies to top-level classes; a class can contain any number of nested or inner classes that are declared public.
  • Second, if a Java file contains a public class, the name of the file must be the same as the name of the class, with the extension .java appended.

    • Regardless of whether your classes are public or not, it is good programming practice to define only one per file and to give the file the same name as the class.

When a Java file is compiled, each of the classes it defines is compiled into a separate class file that contains Java byte codes to be interpreted by the Java Virtual Machine. A class file has the same name as the class it defines, with the extension .class appended.

To create a program, you must define a class that has a special method with the following signature:

public static void main(String[] args)

Threads and Concurrency

Java makes it easy to define and work with multiple threads of execution within a program. java.lang.Thread is the fundamental thread class in the Java API. There are two ways to define a thread:

  • One is to subclass Thread, override the run() method and then instantiate your Thread subclass.
  • The other is to define a class that implements the Runnable method (i.e., define a run() method) and then pass an instance of this Runnable object to the Thread() constructor.

In either case, the result is a Thread object, where the run() method is the body of the thread. When you call the start() method of the Thread object, the interpreter creates a new thread to execute the run() method. This new thread continues to run until the run() method exits. Meanwhile, the original thread continues running itself, starting with the statement following the start() method.

A thread can be in one of six states. In Java 5.0, these states are represented by the Thread.State enumerated type, and the state of a thread can be queried with the getState() method. A listing of the Thread.State constants provides a good overview of the lifecycle of a thread:

States Description
NEW The Thread has been created but its start() method has not yet been called. All threads start in this state.
RUNNABLE The thread is running or is available to run when the operating system schedules it.
BLOCKED The thread is not running because it is waiting to acquire a lock so that it can enter a synchronized method or block.
WAITING The thread is not running because it has called Object.wait() or Thread.join().
TIMED_WAITING The thread is not running because it has called Thread.sleep() or has called Object.wait() or Thread.join() with a timeout value.
TERMINATED The thread has completed execution. Its run() method has exited normally or by throwing an exception.

Java Cheat Sheet

Comparison of Java and C/C++

Java and C/C++ differ in important ways, as summarized in the following list, refer to Comparison of Java and C++.

  • No preprocessor

    Java does not include a preprocessor and does not define any analogs of the #define, #include, and #ifdef directives. Constant definitions are replaced with static final fields in Java. Java does not require an #include directive because Java has no header files.

  • No global variables

    Java defines a very clean namespace. Packages contain classes, classes contain fields and methods, and methods contain local variables.

  • Well-defined primitive type sizes

    All the primitive types in Java have well-defined sizes. In C, the size of short, int, and long types is platform-dependent, which hampers portability.

  • No pointers

    Java classes and arrays are reference types, and references to objects and arrays are akin to pointers in C. Unlike C pointers, however, references in Java are entirely opaque. There is no way to convert a reference to a primitive type, and a reference cannot be incremented or decremented. There is no address-of operator like &, dereference operator like * or ->, or sizeof operator.

  • Garbage collection

    The Java Virtual Machine performs garbage collection so that Java programmers do not have to explicitly manage the memory used by all objects and arrays.

  • No goto statement

    Java doesn’t support a goto statement.

  • Variable declarations anywhere

    C requires local variable declarations to be made at the beginning of a method or block, while Java allows them anywhere in a method or block.

  • Forward references

    The Java compiler is smarter than the C compiler in that it allows methods to be invoked before they are defined.

  • Method overloading

    Java programs can define multiple methods with the same name, as long as the methods have different parameter lists.

  • No struct and union types

    Java doesn’t support C struct and union types. A Java class can be thought of as an enhanced struct, however.

  • No bitfields

    Java doesn’t support the (infrequently used) ability of C to specify the number of individual bits occupied by fields of a struct.

  • No typedef

    Java doesn’t support the typedef keyword used in C to define aliases for type names. Java’s lack of pointers makes its type-naming scheme simpler and more consistent than C’s, however, so many of the common uses of typedef are not really necessary in Java.

  • No method pointers

    C allows you to store the address of a function in a variable and pass this function pointer to other functions. You cannot do this with Java methods, but you can often achieve similar results by passing an object that implements a particular interface. Also, a Java method can be represented and invoked through a java.lang.reflect.Method object.

  • No multiple inheritance

    C++ supports multiple inheritance of method implementations from more than one superclass at a time. A class in Java can inherit method implementations only from a single superclass, but it can inherit method declarations from any number of interfaces.

  • Generics

    C++ supports templates. Java 5.0 introduces parameterized types or generics that provide similar functionality in a more robust fashion.

  • No operator overloading

    C++ allows you to define operators that perform arbitrary operations on instances of your classes. Java language designers decided to omit such operator overloading from the language. Note, though, that the use of the + operator for string concatenation in Java is at least reminiscent of operator overloading.

  • No conversion functions

    C++ allows you to define conversion functions for a class that automatically invokes an appropriate constructor method when a value is assigned to a variable of that class. This is simply a syntactic shortcut (similar to overriding the assignment operator) and is not included in Java.

  • Manipulate by reference

    In C++, objects are manipulated by value by default; you must use & to specify a variable or function argument automatically manipulated by reference. In Java, all objects are manipulated by reference, so there is no need for the & syntax.

Java Code Conventions

None of the conventions described here are mandatory. Following them, however, will make your code easier to read and maintain, portable, and self-documenting.

Packages

  • Ensure that your publicly visible package names are unique by prefixing them with the inverted name of your Internet domain (e.g., com.davidflanagan.utils).
  • All package names should be lowercase.

Reference types

  • A type name should begin with a capital letter and be written in mixed case (e.g., String).
  • If a class name consists of more than one word, each word should begin with a capital letter (e.g., StringBuffer).
  • If a type name, or one of the words of a type name, is an acronym, the acronym can be written in all capital letters (e.g., URL, HTMLParser).
  • Since classes and enumerated types are designed to represent objects, you should choose class names that are nouns.
  • When an interface is used to provide additional information about the classes that implement it, it is common to choose an interface name that is an adjective (e.g., Runnable, Cloneable, Serializable). When an interface works more like an abstract superclass, use a name that is a noun (e.g., Document, FileNameMap, Collection).

Methods

  • A method name always begins with a lowercase letter.
  • If the name contains more than one word, every word after the first begins with a capital letter (e.g., insert( ), insertObject(), insertObjectAt( )).
  • Method names are typically chosen so that the first word is a verb.

Fields and constants

  • Nonconstant field names follow the same capitalization conventions as method names.
  • If a field is a static final constant, it should be written in uppercase. If the name of a constant includes more than one word, the words should be separated with underscores (e.g., MAX_VALUE).
  • The constants defined by enum types are also typically written in all capital letters.

Parameters

  • Method parameters follow the same capitalization conventions as nonconstant fields.

Local variables

  • Variables are typically named following the same conventions as methods and fields.

Also refer to the following code conventions:

Java Projects

Spring

Spring helps development teams everywhere build simple, portable, fast and flexible JVM-based systems and applications. Refer to the following figure for Spring framework:

Spring Framework

Spring serials on IBM Developerworks:

WebWork

WebWork was a Java-based web application framework developed by OpenSymphony that merged into the current Struts2 framework. It was designed to improve developer productivity and simplify code. WebWork was built on top of XWork, which provided a generic command pattern framework as well as an Inversion of Control container. Refer to WebWork on Wikipedia.

Struts

Apache Struts is a free, open-source, MVC (Model View Controller) framework for creating elegant, modern Java web applications. It favors convention over configuration, is extensible using a plugin architecture, and ships with plugins to support REST, AJAX and JSON.

Hibernate

Hibernate ORM (Hibernate in short) is an object-relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct, persistent database accesses with high-level object handling functions.

Quartz

Quartz is a richly featured, open source job scheduling library that can be integrated within virtually any Java application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as support for JTA transactions and clustering.

Velocity

Velocity is a Java-based template engine. It permits anyone to use a simple yet powerful template language to reference objects defined in Java code.

When Velocity is used for web development, Web designers can work in parallel with Java programmers to develop web sites according to the Model-View-Controller (MVC) model, meaning that web page designers can focus solely on creating a site that looks good, and programmers can focus solely on writing top-notch code. Velocity separates Java code from the web pages, making the web site more maintainable over its lifespan and providing a viable alternative to Java Server Pages (JSPs) or PHP.

Velocity’s capabilities reach well beyond the realm of the web; for example, it can be used to generate SQL, PostScript and XML from templates. It can be used either as a standalone utility for generating source code and reports, or as an integrated component of other systems. For instance, Velocity provides template services for various web frameworks, enabling them with a view engine facilitating development of web applications according to a true MVC model.

iBatis/MyBatis

MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO (Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

Compiere ERP&CRM

Compiere is an open source ERP and CRM business solution for the Small and Medium-sized Enterprise (SME) in distribution, retail, service and manufacturing. Compiere is distributed by Consona Corporation and through a Partner Network, a collection of trained and authorized business partners.

Roller Weblogger

Apache Roller is a Java-based Open Source full-featured, Multi-blog, Multi-user, and group-blog server suitable for blog sites large and small. Roller was originally written by Dave Johnson in 2002 for a magazine article on open source development tools, but became popular at FreeRoller.net (now JRoller.com) and was later chosen to drive the employee blogs at Sun Microsystems, Inc. and IBM developerWorks blogs.

XPlanner

XPlanner is a web-based project planning and tracking tool for agile development teams (XP, Scrum, …). XPlanner is implemented using Java, JSP, and Struts, Hibernate and MySQL. More info at http://xplanner.org and http://xplanner.codehaus.org.

HSQLDB

HSQLDB (HyperSQL DataBase) is the leading SQL relational database software written in Java. It offers a small, fast multithreaded and transactional database engine with in-memory and disk-based tables and supports embedded and server modes. It includes a powerful command line SQL tool and simple GUI query tools.

HSQLDB supports the widest range of SQL Standard features seen in any open source database engine: SQL:2011 core language features and an extensive list of SQL:2011 optional features. It supports nearly full Advanced ANSI-92 SQL (BNF format). Many extensions to the Standard, including syntax compatibility modes and features of other popular database engines, are also supported.

Liferay

Liferay Portal is a free and open source enterprise portal software product. Distributed under the GNU Lesser General Public License and optional commercial license, Liferay has been declared “Best Open Source Portal” by InfoWorld in 2007. It is primarily used to power corporate intranets and extranets.

Written in Java, Liferay Portal is a web platform with features commonly required for the development of websites and portals. Liferay includes a built-in web content management system allowing users to build websites and portals as an assembly of themes, pages, portlets/gadgets and a common navigation. Liferay is sometimes described as a content management framework or a web application framework. Liferay’s support for plugins extends into multiple programming languages, including support for PHP and Ruby portlets.

Jetspeed

Jetspeed is an Open Portal Platform and Enterprise Information Portal, written entirely in open source under the Apache license in Java and XML and based on open standards. All access to the portal is managed through a robust portal security policy. Within a Jetspeed portal, individual portlets can be aggregated to create a page. Each portlet is an independent application with Jetspeed acting as the central hub making information from multiple sources available in an easy to use manner.

JOnAS

JOnAS is an open-source implementation of the Java EE application server specification, developed and hosted by the ObjectWeb consortium (ObjectWeb is a non-profit European consortium, founded by INRIA, Groupe Bull, and France Telecom). JOnAS is released under the LGPL open-source license.

JFox

JFox is an Open Source, standards-compliant, J2EE based application server implemented in 100% Pure Java, It comes from China Enterprise Open Source Community.

Online Java Compiler

Books

References