Java Programming Language

Java Programming Language

Length: 8956 words (25.6 double-spaced pages)

Rating: Excellent

Open Document

Essay Preview

More ↓
Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1990s. Unlike conventional languages which are generally designed to be compiled to native code, Java is compiled to a bytecode which is then run (generally using JIT compilation) by a Java virtual machine.

The language itself borrows much syntax from C and C++ but has a much simpler object model and does away with low level tools like programmer-manipulable pointers.

Java is only distantly related to JavaScript, though they have similar names and share a C-like syntax.

As with other parts of the Java platform, the Java language has evolved over the years while largely maintaining backwards compatibility.

JDK 1.0 (January 23, 1996) ¡ª Initial release. [press release]
JDK 1.1 (February 19, 1997) [press release]
inner classes added to the language
J2SE 1.2 (December 8, 1998) ¡ª Codename Playground. This and subsequent releases through J2SE 5.0 were rebranded Java 2 and the version name "J2SE" (Java 2 Platform, Standard Edition) replaced JDK to distinguish the base platform from J2EE (Java 2 Platform, Enterprise Edition) and J2ME (Java 2 Platform, Micro Edition). Major additions included: [press release]
strictfp keyword
J2SE 1.3 (May 8, 2000) ¡ª Codename Kestrel. [press release]
J2SE 1.4 (February 6, 2002) ¡ª Codename Merlin. This was the first release of the Java platform developed under the Java Community Process as JSR 59. Major changes included: [press release]
J2SE 5.0 (September 30, 2004) ¡ª Codename Tiger. (Originally numbered 1.5, which is still used as the internal version number.[1]) Developed under JSR 176, Tiger added a number of significant new language features: [press release]
Generics ¡ª provides compile-time (static) type safety for collections and eliminates the need for most typecasts. (Specified by JSR 14.)
Metadata ¡ª also called annotations, allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. (Specified by JSR 175.)
Autoboxing/unboxing ¡ª automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer). (Specified by JSR 201.)
Enumerations ¡ª the enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). (Specified by JSR 201.)
Varargs ¡ª the last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String... lines)).

How to Cite this Page

MLA Citation:
"Java Programming Language." 25 Feb 2020

Need Writing Help?

Get feedback on grammar, clarity, concision and logic instantly.

Check your paper »

Java Programming Language Essay

- Java: It's not just for breakfast anymore. The World-Wide Web as it is today reminds me of a bad date I had once; boring, flat, and unexciting. It does absolutely nothing for me. The pages are limited by the specifications of HTML which calls for a two-dimensional layout and a static page. I for one am looking for some new element. A new angle if you will. Something to jolt some life into The Web. Sun Microsystem's Java will bring a new interactive element to the Web. It is designed to enhance the browsing experience and take us into the next generation of The Web....   [tags: Computers Technology Programming Languages]

Research Papers
1765 words (5 pages)

Java And The Principles Of Object Oriented Programming Essay

- 7. Conclusion 7.1 Appraisal: Java and the principles of object oriented programming language were taught through multiple modules, such as AC22004, Object Oriented Analysis and Design and AC11001, Introduction To Software Development. Although they went hand in hand, the former module focused on the different stages in the design process when programming in an object oriented language as well as the main principles of these languages. The latter was focused on Java, both theory and in practice (and thus also included the main principles of object oriented languages)....   [tags: Object-oriented programming, Programming language]

Research Papers
950 words (2.7 pages)

Programming Language And Procedural Programming Essay

- One of the major paradigms in programming language is Object Oriented programming. In modern software engineering object oriented programming is considered as the major concept, as it allows the programmer to facilitate clean and efficient code. Apart from this, the design patterns of object oriented programming suits well with most of the computing issues. Object oriented programming produces well organized code and also focuses on determinant of productivity. In this report we will discuss and compare objected oriented programming language and procedural programming language along with the genesis of OOP....   [tags: Object-oriented programming, Programming language]

Research Papers
798 words (2.3 pages)

Essay about Programming Language Model Of Programming

- Programming has been regarded as a logical procedure that “takes input data, processes it, and produces output data.” (Rouse, 2008, para 1) Three common examples of programming are object-oriented programming (OOP), event-driven programming (EDP), and procedural programming (PP). (Rouse, 2008) OOP is a programming language model defined by “objects” as opposed to "actions" and “data rather than logic.” (Rouse, 2008, para 1) EDP is a programming language model defined by reacting to user or processor actions such as keyboard strokes and mouse clicking to execute a command....   [tags: Programming language, Object-oriented programming]

Research Papers
876 words (2.5 pages)

Essay on Programming Languages : Programming Language

- Programming Languages Programming language is a form of language that is designed to communicate instructions to a computer; the language can be used to control the behavior of the computer or calculate math equations. There are five generations of programming languages that have been developed from the 1930’s to present day. These programs make it capable for computers to perform a number of applications from computing algorithms to directing the behavior of the computer. Once the first computers were created programming languages took longer to develop....   [tags: Computer, Programming language, Computer program]

Research Papers
1174 words (3.4 pages)

Essay about Java

- Java is one of many high-level programming languages that use abstraction (reducing and factoring details) to create software for computers and many other electronic devices. Compared to low-level programming languages, high-level programming languages use a mixture of natural language (any language used by humans) and typical computer terms to create an easier to understand and simpler form of programming. Figures 1 and 2 show the difference in writing a simple program called “Hello World” in Assembly (a low-level programming language) and in Java....   [tags: Computer Programming]

Research Papers
1092 words (3.1 pages)

Essay about Paradigm Shift Within Programming Languages

- Paradigm Shift in Programming Languages till date -by Rachit Shah (14BCE110) Programming Languages have existed for over a century. Over the years there has been major change in its syntax and its way of operation to suit our needs. Programming languages enable users to write programs for specific computation or algorithms. In the 1940s the first programming languages were assembly languages. But since it was too laborious ( having to learn all memory locations ) and too error-prone, it needed to evolve into something more human-language like....   [tags: Programming language, Object-oriented programming]

Research Papers
1021 words (2.9 pages)

What Are Programming Languages? Essay

- In the 20th century, meaningful education was all about learning ABCs and 123s whereas now it is all about learning programming languages. We are surrounded by the things that are programmed to make our work easier. Without programming, the mobiles that we use would have been reduced to small bricks. Like our heart keeps us alive, in the same way, programming brings all the hardware to life. What are programming languages. A programming language is a formally constructed language designed to communicate instructions to a machine, particularly a computer....   [tags: Programming language, Compiler, Computer program]

Research Papers
1416 words (4 pages)

Popularity of Java Essay

- Popularity of Java Java is a programming language designed to run dynamic, interactive and secure applications on computer systems. Java has several features which make it extremely popular. Even though Java has obtained remarkable popularity through it’s use on the internet, Java has also been adapted to the operating systems of several electronic devices which are commonly used. How Java is used in the industry Since Java’s inception in 1995, it began to spread throughout the programming world like a virus, gaining popularity everywhere it is used....   [tags: Information Technology ]

Research Papers
1151 words (3.3 pages)

Essay on Comparison Of Java, Javascript, Java Applets And Java Beans

- Comparison of Java, JavaScript, Java Applets and Java Beans Introduction Starting back in the early 1990's with the introduction of Java to the computer scene there has been many updates and advances in how languages interact with web based programs. In this paper we are going to highlight several areas of several different Java flavors. The flavors we are addressing are Java, JavaScript, Java Applets and JavaBeans. We will discuss their history, features, usage and syntax and finally follow up with a chart providing a comparison of the different Java architectures. History Java, a language based on C++, was developed by James Gosling and colleagues at Sun Microsystems in the early 1990's...   [tags: Compare Contrast Papers]

Research Papers
1827 words (5.2 pages)

In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method.
Enhanced for loop ¡ª the for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable, such as the standard Collection classes, using a construct of the form:
void displayWidgets (Iterable widgets) { |
for (Widget w : widgets) { |
w.display(); |
} |
} |
This example iterates over the Iterable object widgets, assigning each of its items in turn to the variable w, and then calling the Widget method display() for each item. (Specified by JSR 201.)

Java SE 6 ¡ª Codename Mustang. As of 2006 this is currently in development under JSR 270. A beta version was released on February 15, 2006[press release] and is available at . Another beta is expected summer 2006 with the final release in autumn 2006. New builds including enhancements and bug fixes are released approximately weekly. As of this version, Sun replaced the name "J2SE" with Java SE and dropped the ".0" from the version number.[2]
Java SE 7 ¡ª Codename Dolphin. As of 2006, this is in the early planning stages. Development is expected to begin in spring 2006, with release estimated in 2008.[3]
In addition to the language changes, much more dramatic changes have been made to the Java class library over the years, which has grown from a few hundred classes in JDK 1.0 to over three thousand in J2SE 5.0. Entire new APIs, such as Swing and Java2D, have been introduced, and many of the original JDK 1.0 classes and methods have been deprecated.

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

1. It should use the object-oriented programming methodology.
2. It should allow the same program to be executed on multiple operating systems.
3. It should contain built-in support for using computer networks.
4. It should be designed to execute code from remote sources securely.
5. It should be easy to use and borrow the good parts of older object-oriented languages like C++.

To achieve the goals of networking support and remote code execution, Java programmers sometimes find it necessary to use extensions such as CORBA, Internet Communications Engine, or OSGi.

Object orientation
The first characteristic, object orientation ("OO"), refers to a method of programming and language design. Although there are many interpretations of OO, one primary distinguishing idea is to design software so that the various types of data it manipulates are combined together with their relevant operations. Thus, data and code are combined into entities called objects. An object can be thought of as a self-contained bundle of behavior (code) and state (data). The principle is to separate the things that change from the things that stay the same; often, a change to some data structure requires a corresponding change to the code that operates on that data, or vice versa. This separation into coherent objects provides a more stable foundation for a software system's design. The intent is to make large software projects easier to manage, thus improving quality and reducing the number of failed projects.

Another primary goal of OO programming is to develop more generic objects so that software can become more reusable between projects. A generic "customer" object, for example, should in theory have roughly the same basic set of behaviors between different software projects, especially when these projects overlap on some fundamental level as they often do in large organizations. In this sense, software objects can hopefully be seen more as pluggable components, helping the software industry build projects largely from existing and well tested pieces, thus leading to a massive reduction in development times. Software reusability has met with mixed practical results, with two main difficulties: the design of truly generic objects is poorly-understood, and a methodology for broad communication of reuse opportunities is lacking. Some open source communities want to help ease the reuse problem, by providing authors with ways to disseminate information about generally reusable objects and object libraries.

Platform Independence
The second characteristic, platform independence, means that programs written in the Java language must run similarly on diverse hardware. One should be able to write a program once and run it anywhere.

This is achieved by most Java compilers by compiling the Java language code "halfway" to bytecode (specifically Java bytecode)¡ªsimplified machine instructions specific to the Java platform. The code is then run on a virtual machine (VM), a program written in native code on the host hardware that interprets and executes generic Java bytecode. Further, standardized libraries are provided to allow access to features of the host machines (such as graphics, threading and networking) in unified ways. Note that, although there's an explicit compiling stage, at some point, the Java bytecode is interpreted or converted to native machine instructions by the JIT compiler.

There are also implementations of Java compilers that compile to native object code, such as GCJ, removing the intermediate bytecode stage, but the output of these compilers can only be run on a single architecture.

Sun's license for Java insists that all implementations be "compatible". This resulted in a legal dispute with Microsoft after Sun claimed that the Microsoft implementation did not support the RMI and JNI interfaces and had added platform-specific features of their own. Sun sued and won both damages (some $20 million) and a court order enforcing the terms of the license from Sun. In response, Microsoft no longer ships Java with Windows, and in recent versions of Windows, Internet Explorer cannot support Java applets without a third-party plugin. However, Sun and others have made available Java run-time systems at no cost for those and other versions of Windows.

The first implementations of the language used an interpreted virtual machine to achieve portability. These implementations produced programs that ran more slowly than programs written in C or C++, so the language suffered a reputation for poor performance. More recent JVM implementations produce programs that run significantly faster than before, using multiple techniques.

The first technique is to simply compile directly into native code like a more traditional compiler, skipping bytecodes entirely. This achieves good performance, but at the expense of portability. Another technique, known as just-in-time compilation (JIT), translates the Java bytecodes into native code at the time that the program is run. More sophisticated VMs use dynamic recompilation, in which the VM can analyze the behavior of the running program and selectively recompile and optimise critical parts of the program. Dynamic recompilation can achieve optimizations superior to static compilation because the dynamic compiler can base optimizations on knowledge about the runtime environment and the set of loaded classes. JIT compilation and dynamic recompilation allow Java programs to take advantage of the speed of native code without losing portability.

Portability is a technically difficult goal to achieve, and Java's success at that goal has been mixed. Although it is indeed possible to write programs for the Java platform that behave consistently across many host platforms, the large number of available platforms with small errors or inconsistencies led some to parody Sun's "Write once, run anywhere" slogan as "Write once, debug everywhere".

Platform-independent Java is however very successful with server-side applications, such as web services, servlets, and Enterprise Java Beans, as well as with Embedded systems based on OSGi, using Embedded Java environments.

Automatic garbage collection
One possible argument against languages such as C++ is that programmers should be spared the burden of having to perform manual memory management. In C++, the programmer must allocate memory to create any object stored on the heap, and deallocate memory to delete any such objects. If a programmer forgets to deallocate memory or writes code that fails to do so in a timely fashion, a memory leak can occur: the program will consume a potentially arbitrarily large amount of memory. In addition, if a region of memory is deallocated twice, the program can become unstable and may crash.

In Java, this potential problem is avoided by automatic garbage collection. The programmer determines when objects are created and the Java runtime is responsible for managing the objects' lifecycle. The program or other objects can reference an object by holding a reference to it (which, from a low-level point of view, is its address on the heap). When no references to an object remain, the Java garbage collector automatically deletes the unreachable object, freeing memory and preventing a memory leak. Memory leaks may still occur if a programmer's code holds a reference to an object that is no longer needed¡ªin other words, they can still occur but at higher conceptual levels. On the whole, Java's automatic garbage collection makes creation and deletion of objects in Java simpler, potentially safer, and often faster than in C++.

Garbage collection in Java is virtually invisible to the developer. That is, developers may have no notion of when garbage collection will take place as it may not necessarily correlate with any actions being explicitly performed by the code they write.

Note that memory is only one of many resources which must be managed.

The syntax of the Java programming language is a set of rules that defines how a Java program is written and interpreted.

Data structures
Although the language has special syntax for them, arrays and strings are not primitive types: they are reference types that can be assigned to java.lang.Object.

Simple data types
Integer types
byte 8-bit signed
short 16-bit signed
int 32-bit signed
long 64-bit signed
Floating-point types
float 32-bit signed
double 64-bit signed

Floating-point math never throws an exception
Dividing by 0 equals Inf (Infinity)
Dividing by Inf equals 0
char 16-bit Unicode
boolean true or false

Can't represent false as 0 or null
Can't represent true as non-zero
Can't cast from boolean to non-boolean, or vice versa
Primitive wrapper classes

Can be used to convert values from one type to another
Can be used to pass simple data types by reference
Passed by value to methods.
Initialized by default to 0, null, or false.

octal 0365, 0[0..7]*
hexadecimal 0xF5, 0x[0..9, A..F, a..f]*
decimal 245, [1..9][0..9]*
Floating-point values
float 23.5F, 23.5f; 1.72E3F, 1.72E3f, 1.72e3F, 1.72e3f
double 23.5, 23.5D, 23.5d; 1.72E3, 1.72E3D, ...
Character literals
char 'a', 'Z'
String literals
String "Hello, world"
Characters escapes in strings
Unicode character u followed by the hexadecimal unicode code point
Tab t
Backspace b
Carriage return r
Form feed f
Backslash \
Single quote '
Double quote "
Line feed n


String objects are immutable
String objects must be initialized when created
When the compiler encounters a string literal (a series of characters enclosed in double quotes), it creates a String object
The "+" and "+=" operators are overloaded for use in string concatenation
String str1 = "alpha";
String str2 = new String("alpha");
StringBuffer and StringBuilder

StringBuffer and StringBuilder objects are mutable
Neither String nor StringBuffer are a descendant of one another
StringBuffer str1 = new StringBuffer("beta");
StringBuffer str2 = new StringBuffer(50);

Java has array types for each type, including arrays of primitive types, class and interface types, as well as higher-dimensional arrays of array types.
All elements of an array must descend from the same type.
All array classes descend from the class java.lang.Object, and mirror the hierarchy of the types they contain.
Array objects have a read-only length attribute that contains the number of elements in the array.
Arrays are allocated at runtime, so the specified size in an array creation expression may be a variable (rather than a constant expression as in C).
Java arrays have a single dimension. Multi-dimensional arrays are supported by the language, but are treated as arrays of arrays.
// Declare the array - name is "myArray", element type is references to "SomeClass"
SomeClass[] myArray;

// Allocate the array
myArray = new SomeClass[10];

// Or Combine the declaration and array creation
SomeClass[] myArray = new SomeClass[10];

// Allocate the elements of the array (not needed for simple data types)
for (int i = 0; i < myArray.length; i++)
myArray[i] = new SomeClass();

International language support
The language distinguishes between bytes and characters. Characters are stored internally using UCS-2, although as of J2SE 5.0, the language also supports using UTF-16 and its surrogates. Java program source may therefore contain any Unicode character.

The following is thus perfectly valid Java code; it contains Chinese characters in the class and variable names as well as in a string literal:

public class ¹þ‡DÊÀ½ç {
private String Îı¾ = "¹þ‡DÊÀ½ç";


Binary operators
Syntax Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (returns the integer remainder)
Unary operators
Syntax Meaning
- Unary negation (reverses the sign)
++ Increment (can be prefix or postfix)
-- Decrement (can be prefix or postfix)
Syntax Meaning
= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign
&= Bitwise AND and assign
|= Bitwise OR and assign
^= Bitwise XOR and assign
= Right shift (sign-propogating and assign)
>>>= Right shift (zero fill) and assign
Syntax Meaning
== Equals
!= Not equal
> Greater than
>= Greater than or equal to
< Less than
Right shift (sign-propagating)
>>> Right shift (zero fill)
Unary operators
~ NOT (inverts the bits)
String operators
Syntax Meaning
+ Concatenation
+= Concatenation and assignment

Control structures

If ... else
if (expr) {
else if (expr) {
else {
Switch statement
switch (expr) {
case VALUE:
case VALUE:
The expr value must be a byte, short, int, or char.
Each case value must be a unique literal value; variables cannot be used.

For loop
for (initial-expr; cond-expr; incr-expr) {
New for loop for Iterable elements, added in J2SE 5.0. This iterates through Iterable Iterable_name, values are stored in variable variable_name.

for (element_type variable_name: Iterable_name) {

While loop
while (expr) {

Do ... while
do {
} while (expr);

Jump statements
Syntax Meaning
break; Break from the innermost enclosing loop immediately.
continue Continue on to the next iteration of the loop.
break LABEL Jump to the statement immediately after the labeled statement (terminate the labeled statement).
continue LABEL Jump to the labeled statement (restart a labeled statement or continue execution of a labeled loop)

int sum = 0;
int i = 1;
while (i < 10) {
if (i == 3) {
continue; // Skip the rest of this loop iteration.
sum += i;

if (sum > 15) {
break; // Exit the loop.

Consists of an identifier followed by a colon
Used to identify the statement or block of code that the jump statements refer to
If the label is omitted, the jump statements refer to the innermost enclosing loop

LABEL1: statement;
LABEL2: { statements; }


Java has nested classes that are declared within the body of another class or interface. A class that is not a nested class is called a top level class. An inner class is a non-static nested class.

Classes can be declared with the following modifiers:

abstract ¨C cannot be instantiated. Only interfaces and abstract classes may contain abstract methods. A concrete (non-abstract) subclass that extends an abstract class must override any inherited abstract methods with non-abstract methods. Cannot be final.
final ¨C cannot be subclassed. All methods in a final class are implicity final. Cannot be abstract.
strictfp ¨C all floating-point operations within the class and any enclosed nested classes use strict floating-point semantics. Strict floating-point semantics guarantee that floating-point operations produce the same results on all platforms.

class ChildClass extends ParentClass { ... } // ChildClass inherits from ParentClass
The default parent of a class is the Object class.
A class can only extend a single parent class (no multiple inheritance of implementation).

this ¨C Reference to the current subclass (assumed by default) (i.e. this.someMethod()).
super ¨C Reference to the parent class (i.e. super.someMethod()). Can be used in a subclass to access inherited methods that the subclass has overridden or inherited fields that the subclass has hidden.

An interface is an abstract class with no implementation details. Its purpose is to define how a set of classes will be used. Classes that implement a common interface can be used interchangeably within the context of the interface type. Interfaces also help to enforce the concept of abstraction¡ªhiding the details of how a class is implemented.

An interface can only contain abstract methods and static final fields. Interface methods are public and abstract by default (unimplemented), and interface fields are public, static and final by default.

Java does not support full orthogonal multiple inheritance. Multiple inheritance in C++ has complicated rules to disambiguate fields and methods inherited from multiple superclasses and types inherited multiple times. By separating interface from implementation, interfaces offer much of the benefit of multiple inheritance with less complexity and ambiguity. The price of no multiple inheritance is some code redundancy; since interfaces only define the signature of a class but cannot contain any implementation, every class inheriting an interface must provide the implementation of the defined methods, unlike in pure multiple inheritance, where the implementation is also inherited.

Java interfaces behave much like the concept of the Objective-C protocol.

Implementing interfaces
A class can implement one or more interfaces using the implements keyword, in addition to extending another class.

interface MyInterface {
void foo();

interface Interface2 {
void bar();

class MyClass implements MyInterface {
void foo() {...}

class ChildClass extends ParentClass implements MyInterface, Interface2 {
void foo() {...}
void bar();
In the following example,

public interface Deleteable {
void delete();
any non-abstract class that implements the Deleteable interface must define a non-abstract method named delete that has no parameters and a void return type. The implementation and function of the method are determined by each class. There are many uses for this concept, for example:

public class Fred implements Deleteable {
// This method satisfies the Deleteable interface
public void delete() {
// Code implementation goes here
public void someOtherMethod() {

public void deleteAll(Deleteable[] list) {
for (int i = 0; i < list.length; i++) {
Because any objects in the above array are guaranteed to have the delete() method, the deleteAll() method needn't differentiate between the Fred objects or any other Deleteable objects.

Extending interfaces
An interface can extend one or more interfaces using the extends keyword.

interface ChildInterface extends ParentInterface, AnotherInterface {
A class that implements the resulting interface must define the combined set of methods.

public interface MyInterface {

public interface Interface2 extends MyInterface {

public class MyClass implements MyInterface {
void foo() {...}
void bar() {...}

Access modifiers
Access modifiers determine which code may access classes and class members.

Top level class access
public ¨C accessible outside the package in which it's defined.
default ¨C accessible only within the package in which it's defined.

Class member access
Class members are fields, methods, constructors and nested classes declared within the body of a class. In order of increasing restrictions on access, the access modifiers for class members are:

public ¨C accessible by any class.
protected ¨C accessible within the class; by any derived class; and by other classes within the package.
default ¨C accessible by any class within the package.
private ¨C accessible only within the class (includes access from within enclosed inner classes). Members that are declared private are not inherited by subclasses.
When overriding a method, the method access modifier can't be made more restrictive¡ªto do so would break the interface contract of the parent class. Thus when overridden, a public method must be declared public and a protected method cannot be given default access. However, it is permissible to override a method to make it more accessible. Thus when overriding, a default (package) access method can be declared as protected or public and a protected method can be declared as public.

In addition to the access modifiers, data fields may be declared with the following modifiers:

final ¨C the value cannot be changed. Must be initialized exactly once. A final field declared without an initializer is a blank final field¡ªa static blank final field must be definitively initialized by a static initializer; a non-static blank final field must be initialized during the execution of each and every constructor. Cannot be volatile.
static ¨C belongs to the class, rather than to an instance of the class.
transient ¨C not a part of the persistent state of an object. The value should not be saved and later restored.
volatile ¨C informs the compiler that it may be accessed by separate threads asynchronously. Cannot be final.

Fields that are declared as both static and final are effectively constants; static means there is one occurrence of the field associated with the class, and final means that the field is assigned a value exactly once.

Initializers are blocks of code that are executed at the same time as initializers for fields.

Static initializers
Static initializers are blocks of code that are executed at the same time as initializers for static fields. Static field initializers and static initializers are executed in the order declared. The static initialization is executed after the class is loaded.

static int count = 20;
static int[] squares;
static { // a static initializer
squares = new int[count];
for (int i = 0; i < count; i++)
squares[i] = i * i;
static int x = squares[5]; // x is assigned the value 25

Instance initializers
Instance initializers are blocks of code that are executed at the same time as initializers for instance (non-static) fields. Instance field initializers and instance initializers are executed in the order declared.

Both instance initializers and instance field initializers are executed during the invocation of a constructor. The initializers are executed immediately after the superclass constructor and before the body of the constructor.

In addition to the access modifiers, methods may be declared with the following modifiers:

abstract ¨C the method is undefined in the class, and must be defined by any concrete (non-abstract) subclass. Cannot be static, final or native.
final ¨C the method cannot be redefined in a subclass. For instance (non-static) methods, this allows the compiler to expand the method (similar to an inline function) if the method is small enough. Cannot be abstract.
native ¨C the method links to native machine-dependent code. Declared without a body. Cannot be abstract.
static ¨C belongs to the class, rather than to an instance of the class. Cannot be abstract.
strictfp ¨C all floating-point operations in the method and enclosed inner classes use strict floating-point semantics. Strict floating-point semantics guarantee that floating-point operations produce the same results on all platforms.
synchronized ¨C causes the current thread to acquire the lock for the associated object before executing the body of the method. If the lock is currently held by another thread, the current thread will block until the lock is released and the thread is able to obtain the lock. The associtated object is the Class object for static methods and the object instance for non-static methods. While it is allowed to declare an abstract method as synchronized, it is meaningless to do so since synchronization is an aspect of the implementation, not the declaration, and abstract methods do not have an implementation.
Note that a private method can't be abstract and is implicitly final.

A constructor is called to initialize an object immediately after the object has be allocated. Typically, a construct is invoked using the new keyword, although constructors can also be invoked using reflection provided by the java.reflect package.

The access modifiers are the only modifiers that may be used for declaring constructors.

When possible, the object should be a valid, meaningful object once it is constructed, as opposed to relying on a separate initialization method.
By convention, a copy constructor is a constructor that accepts an object of its own type as a parameter and copies the data members.
If no explicit constructor is defined, then the compiler provides an implicit empty default constructor that takes no parameters.
Constructors can be overloaded.
The first statement in a constructor may invoke a superclass constructor: super(...); or another constructor in the same class: this(...);
If there is no explicit call to super(...) or this(...), then the default superclass constructor super(); is called before the body of the constructor is executed.

Methods in the Object class
Methods in the Object class are inherited, and thus shared in common, by all classes.

The clone method
Main article: Clone (function)
The Object.clone() method returns a new object that is a copy of the current object. Classes must implement the marker interface Cloneable to indicate that they can be cloned.

The equals method
The Object) Object.equals(Object) method compares the object to another object and returns a boolean result indicating if the two objects are equal. Semantically, this method compares the contents of the objects whereas the equality comparison operator "==" compares the object references. The equals method is used by many of the data structure classes in the java.util package. Some of these data structure classes also rely on the Object.hashCode method¡ªsee the hashCode method for details on the contract between equals and hashCode.

The finalize method
Main article: Finalizer
The Object.finalize() method is called exactly once before the garbage collector frees the memory for object. A class overrides finalize to perform any clean up that must be performed before an object is reclaimed. Most objects do not need to override finalize.

There is no guarantee when the finalize method will be called, or the order in which the finalize method will be called for multiple objects. If the JVM exits without performing garbage collection, the OS may free the objects, in which case the finalize method doesn't get called.

The finalize method should always be declared protected to prevent other classes from calling the finalize method.

protected void finalize() throws Throwable { ... }

The getClass method
The Object.getClass() method returns the Class object for the class that was used to instantiate the object. The class object is the base class of reflection in Java. Additional reflection is provided in the java.lang.reflect package.

The hashCode method
The Object.hashCode() method returns an integer (int) that is used as a hash code for storing the object in an associative array. Classes that implement the java.util.Map interface provide associative arrays and rely on the hashCode method. A good hashCode implementation will return a hash code that is stable (does not change) and evenly distributed (the hash codes of unequal objects tend to be unequal and the hash codes are evenly distributed across integer values).

Because associative arrays depend on both the equals and hashCode methods, there is an important contract between these two methods that must be maintained if the objects are to be inserted into a Map:

For two objects a and b
a.equals(b) == b.equals(a)
if a.equals(b) then a.hashCode() == b.hashCode()
In order to maintain this contract, a class that overrides the equals method must also override the hashCode method, and vice versa, so that hashCode is based on the same properties (or a subset of the properties) as equals.

A further contract that the map has with the object is that the results of the hashCode and equals methods will not change once the object has been inserted into the map. For this reason, it is generally a good practice to base the hash function on immutable properties of the object.

The toString method
The Object.toString() method returns a String that contains a text representation of the object. The toString method is implicitly called by the compiler when an object operand is used with the string concatenation operators (+ and +=).

The wait and notify thread signaling methods
Every object has two wait lists for threads associated with it. One wait list is used by the synchronized keyword to acquire the mutex lock associated with the object. If the mutex lock is currently held by another thread, the current thread is added to the list of blocked threads waiting on the mutex lock. The other wait list is used for signaling between threads accomplished through the wait and notify and notifyAll methods.

Use of wait/notify allows efficient coordination of tasks between
threads. When one thread needs to wait for another thread to complete an operation, or needs to wait until an event occurs, the thread can suspend its execution and wait to be notified when the event occurs. This is in contrast to polling, where the thread repeatedly sleeps for a short period of time and then checks a flag or other condition indicator. Polling is both more computationally expensive, as the thread has to continue checking, and less responsive since the thread won't notice the condition has changed until the next time to check.

The wait methods
There are three overloaded versions of the wait method to support different ways to specify the timeout value: wait(), wait (long timeout) and int) wait (long timeout, int nanos). The first method uses a timeout value of zero (0), which means that the wait does not timeout; the second method takes the number of milliseconds as a timeout; the third method takes the number of nanoseconds as a timeout, calculated as 1000000 * timeout + nanos.

The thread calling wait is blocked (removed from the set of executable threads) and added to the object's wait list. The thread remains in the object's wait list until one of three events occurs:

another thread calls the object's notify or notifyAll method (see the notify methods below for details);
another thread calls the thread's interrupt() method; or
a non-zero timeout that was specified in the call to wait expires.
The wait method must be called inside of a block or method synchronized on the object. This insures that there are no race conditions between wait and notify. When the thread is placed in the wait list, the thread releases the object's mutex lock. After the thread is removed from the wait list and added to the set of executable thread, it must acquire the object's mutex lock before continuing execution.

The notify and notifyAll methods
The Object.notify() and Object.notifyAll() methods remove one or more threads from an object's wait list and add them to the set of executable threads. notify removes a single thread from the wait list, while notifyAll removes all threads from the wait list. Which thread is removed by notify is unspecified and dependent on the JVM implementation.

The notify methods must be called inside of a block or method synchronized on the object. This insures that there are no race conditions between wait and notify.

Versions of Java prior to J2SE 1.4 only supported stream-based blocking I/O. This required a thread per stream being handled, as no other processing could take place while the active thread blocked waiting for input or output. This was a major scalability and performance issue for anyone needing to implement any Java network service. Since the introduction of NIO (New I/O) in J2SE 1.4, this scalability problem has been rectified by the introduction of a non-blocking I/O framework (though there are a number of open issues in the NIO API as implemented by Sun).

The non-blocking IO framework, though considerably more complex than the original blocking IO framework, allows any number of "channels" to be handled by a single thread. The framework is based on the Reactor Pattern.

Running code

Java code that runs in a stand-alone virtual machine (not in a Web browser)
A main method must be defined as follows:
public class MyClass {
public static void main (String[] args) {...}

Main article: Java applet
Java code that runs in a web browser, in a designated display area
init and destroy are only called once, but start and stop are called as many times as the user visits the web page.

import java.applet.*;

public class MyApplet extends Applet {
init() {...} // Called when the browser first loads the applet.
destroy() {...} // Called when the user quits the browser.
start(){...} // Called when the applet starts running.
stop() {...} // Called when the user leaves the web page,
// reloads it, or quits the browser.

Embedding the applet tag
The HTML applet tag can be embedded in the applet source code.
Inclusion of the applet tag allows the applet to be run directly by a simple applet viewer, without the need for an .html file.
Typically, the applet tag immediately follows the import statements.
It must be enclosed by /* */ comments.


Main article: Java servlet
Java code that runs on a Web server, with the output (generally HTML or XML) typically sent to a Web browser.
Servlets are the Java equivalent to CGI programming.

JSP (JavaServer Pages)
Main article: JavaServer Pages
Java code that's embedded in a Web page
JSP tags are processed on a Web server; the resulting output (generally HTML or XML) is sent to the client.
JSP code is compiled into a Java Servlet before it's run.
JSP is an extension of Java Servlets.
The usage of JSP tags is comparable to the usage of PHP or ASP tags.

JSP tags
Syntax Meaning


Case sensitivity
Java is case sensitive.

// Single-line comment
/* Multiple-line
comment */
* These lines are used before the declaration of a class, method,
* or data member. This type of comment can be extracted by a utility
* to automatically create the documentation for a class.

Stand-alone application
// Hello World Example

public class HelloWorldExample {

private static final String g_HELLO = "Hello";
private static final String g_SPACE = " ";
private static final String g_WORLD = "World";
private static final String g_PERIOD = ".";
public static void printHelloWorldExample() {
System.out.println(g_HELLO + g_SPACE + g_WORLD + g_PERIOD);
public static void main(String[] args) {
The above example merits a bit of explanation.

Everything in Java is written inside a class, including stand-alone programs.
Source files are by convention named the same as the class they contain, appending the mandatory suffix .java. A class which is declared public is required to follow this convention. (In this case, the class is Hello, therefore the source must be stored in a file called
The compiler will generate a class file for each class defined in the source file. The name of the class file is the name of the class, with .class appended. For class file generation, anonymous classes are treated as if their name was the concatenation of the name of their enclosing class, a $, and an integer.
Programs to be executed as stand-alone must have a main() method.
The keyword void indicates that the main method does not return anything.
The main method must accept an array of String objects. By convention, it is referenced as args although any other legal identifier name can be used.
The keyword static indicates that the method is a class method, associated with the class rather than object instances. Main methods must be static.
The keyword public denotes that a method can be called from code in other classes, or that a class may be used by classes outside the class hierarchy. Main methods must also be public.
The printing facility is part of the Java standard library: The System class defines a public static field called out. The out object is an instance of the PrintStream class and provides the method println(String) for displaying data to the screen (standard out).
Standalone programs are run by giving the Java runtime the name of the class whose main method is to be invoked. For example, at a Unix command line java -cp . Hello will start the above program (compiled into Hello.class) from the current directory. The name of the class whose main method is to be invoked can also be specified in the MANIFEST of a Java archive (Jar) file.

Java applets are programs that are embedded in other applications, typically in a Web page displayed in a Web browser.
import java.applet.Applet;
import java.awt.Graphics;

public class Hello extends Applet {
public void paint(Graphics gc) {
gc.drawString("Hello, world!", 65, 95);

Hello World Applet

The import statements direct the Java compiler to include the java.applet.Applet and java.awt.Graphics classes in the compilation. The import statement allows these classes to be referenced in the source code using the simple class name (i.e. Applet) instead of the fully-qualified class name (i.e. java.applet.Applet).

The Hello class extends (subclasses) the Applet class; the Applet class provides the framework for the host application to display and control the lifecycle of the applet. The Applet class is an Abstract Windowing Toolkit (AWT) Component, which provides the applet with the capability to display a graphical user interface (GUI) and respond to user events.

The Hello class overrides the paint(Graphics) method inherited from the Container superclass to provide the code to display the applet. The paint() method is passed a Graphics object that contains the graphic context used to display the applet. The paint() method calls the graphic context drawString(String, int, int) method to display the "Hello, world!" string at a pixel offset of (65, 95) in the applet's display.

An applet is placed in an HTML document using the HTML element. The applet tag has three attributes set: code="Hello" specifies the name of the Applet class and width="200" height="200" sets the pixel width and height of the applet. (Applets may also be embedded in HTML using either the object or embed element, although support for these elements by Web browsers is inconsistent.[4][5])

Java servlets are server-side Java EE components that generate responses to requests from clients.
import javax.servlet.*;

public class Hello extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
PrintWriter pw = response.getWriter();
pw.println("Hello, world!");
The import statements direct the Java compiler to include all of the public classes and interfaces from the and javax.servlet packages in the compilation.

The Hello class extends the GenericServlet class; the GenericServlet class provides the interface for the server to forward requests to the servlet and control the servlet's lifecycle.

The Hello class overrides the service(ServletRequest, ServletResponse) method defined by the Servlet interface to provide the code for the service request handler. The service() method is passed a ServletRequest object that contains the request from the client and a ServletResponse object used to create the response returned to the client. The service() method declares that it throws the exceptions ServletException and IOException if a problem prevents it from responding to the request.

The setContentType(String) method in the response object is called to set the MIME content type of the returned data to "text/html". The getWriter() method in the response returns a PrintWriter object that is used to write the data that is sent to the client. The println(String) method is called to write the "Hello, world!" string to the response and then the close() method is called to close the print writer, which causes the data that has been written to the stream to be returned to the client.

Swing application
Swing is the advanced graphical user interface library for the Java SE platform.
// Hello.jav
import javax.swing.*;

public class Hello extends JFrame {
Hello() {
add(new JLabel("Hello, world!"));

public static void main(String[] args) {
new Hello().setVisible(true);
The import statement directs the Java compiler to include all of the public classes and interfaces from the javax.swing package in the compilation.

The Hello class extends the JFrame class; the JFrame class implements a window with a title bar with a close control.

The Hello() constructor initializes the frame by first calling the setDefaultCloseOperation(int) method inherited from JFrame to set the default operation when the close control on the title bar is selected to WindowConstants.DISPOSE_ON_CLOSE¡ªthis causes the JFrame to be disposed of when the frame is closed (as opposed to merely hidden), which allows the JVM to exit and the program to terminate. Next a new JLabel is created for the string "Hello, world!" and the add(Component) method inherited from the Container superclass is called to add the label to the frame. The pack() method inherited from the Window superclass is called to size the window and layout its contents.

The main() method is called by the JVM when the program starts. It instantiates a new Hello frame and causes it to be displayed by calling the setVisible(boolean) method inherited from the Component superclass with the boolean parameter true. Note that once the frame is displayed, exiting the main method does not cause the program to terminate because the AWT event dispatching thread remains active until all of the Swing top-level windows have been disposed.

Java was intended to serve as a novel way to manage software complexity. Most consider Java technology to deliver reasonably well on this promise. However, Java is not without flaws, and it does not universally accommodate all programming styles, environments, or requirements.

Java failed to deliver industry standard arithmetic capabilities. The IEEE 754 Standard for Binary Floating-Point Arithmetic had appeared in 1985 and has remained an industry standard since then. While Java's floating point arithmetic is largely based on the standard, certain features are not supported. Details about this kind of criticism can be found below in the external links section.
Java's semi-proprietary nature, supposed inflexibility to change, and growing entrenchment in the corporate sector, have caused some to refer to Java as "the new COBOL". Many consider this to be a somewhat hyperbolic assertion, although it does allude to some legitimate concerns with Java's prospects for the future.
Java's garbage collection manages only memory resources, and the time at which finalizers are called cannot be controlled by the programmer. Therefore objects that reserve external resources must still be disposed of manually (sometimes using the "finally" mechanism), or kept until the program terminates.

Java can be considered a less pure object-oriented programming language than for instance Ruby or Smalltalk because it makes certain compromises (such as the fact that not all values are objects) for performance reasons. The distinction between reference types and primitive types may be viewed as artificial.
Conversely, C++ programmers can become confused with Java because in Java primitives are always automatic variables and objects always reside on the heap, whereas C++ programmers are explicitly given the choice in both cases by means of operator new.
Java code is often more verbose than code written in other languages. This is due in part to its frequent type declarations and manual casts. It is also due to the lack of operator overloading (see below) and the relatively simple syntax. However, J2SE 5.0 introduced Generics which addresses the issue of manual casts, as well as new syntax for foreach-loops which also reduces verbosity.
Unlike C++, Java does not support user-definable operator overloading; however, this is a deliberate design decision, seen by many as a plus because of the well-known readability and maintenance problems experienced with operator overloading.
Java is predominantly a single-paradigm language. Historically, it has not been very accommodating of paradigms other than object-oriented programming. As of J2SE 5.0, the procedural paradigm is somewhat better supported in Java with the addition of the ability to import static methods and fields so that they can be referenced without prepending the class name.
Java only supports single inheritance of implementation unlike the orthogonal multiple inheritance that is available in many other languages. However, Java employs interfaces, which allow multiple inheritance of type and abstract methods.
Java's support of text matching and manipulation is not as strong as languages such as Perl, Ruby, or PHP, although regular expressions were introduced in J2SE 1.4.

Look and feel
The look and feel of GUI applications written in Java using the Swing platform is often different from native applications. While programmers can choose to use the AWT toolkit that displays native widgets (and thus look like the operating platform), the AWT toolkit is unable to meet advanced GUI programming needs by wrapping around advanced widgets and not sacrificing portability across the various supported platforms, each of which have vastly different APIs especially for higher-level widgets. The Swing toolkit, written completely in Java, avoids this problem by reimplementing widgets using only the most basic drawing mechanisms that are guaranteed available on all platforms. The drawback is that extra effort is required to resemble the operating platform. While this is possible (using the GTK+ and Windows Look-and-Feel), most users do not know how to change the default Metal Look-And-Feel to one that resembles their native platform, and as a result they are stuck with Java applications that look and feel different from their native applications. Of note however, Apple Computer's own optimized version of the Java Runtime, which is included within the Mac OS X distribution, by default implements its "Aqua" look-and-feel, giving Swing applications on the Macintosh a similar appearance to native software.

It is misleading to make any generalization about the performance of Java programs, because runtime performance is affected much more by the quality of the compiler or JVM than by any intrinsic properties of the language itself. Java bytecode can either be interpreted at run time by a virtual machine, or can be compiled at load time or runtime into machine code which runs directly on the computer's hardware. Interpretation is slower than native execution, and compilation at load time or runtime has an initial performance penalty for the compilation.

There are a few language requirements which incur an unavoidable time penalty, although these features are not unique to Java. Among these are array bounds checking, run-time type checking, and virtual function indirection.

The use of a garbage collector to automatically delete objects adds overhead compared to manual deallocation can have a positive or negative impact, or no discernable impact at all, on performance depending upon the garbage collector implementation and the characteristics of the application's use of objects. With the modern generational garbage collectors used in many JVMs, many applications actually experience greater performance because of faster allocation and deallocation algorithms.

Relative performance of JIT compilers as compared to native compilers can be quite close, and is often a subject of debate. The JIT compilation stage may be time consuming, which is inconvenient for applications that are short-lived and/or contain large amounts of code. Once compiled to native code, however, the performance of the program can be comparable to that achieved by a native compiler, even on numerical tasks. Although Java does not support manual inlining of method calls, many JIT compilers perform this optimization at load time and can exploit information from the runtime environment to guide more effective transformations, such as profile-directed inlining. Dynamic recompilation, as provided by Sun's HotSpot JVM, can exceed the performance of the static compilation available in most other languages by exploiting information that is only available at runtime.

Java was designed with an emphasis on security and portability, and does not support direct access to the machine architecture and address space. Java does not support inline assembly language, however, applications can drop down to native code to access these features using Java Native Interface (JNI) libraries.
Return to