Sie sind auf Seite 1von 108

JAVA

By

Rohan
Patel
X science

Preface
This project consist of information on java and its basics
features, types of java programming, java virtual
machine, BlueJ and the program of virtual calculator.
This project has helped me to enhance my computer
knowledge and information on java and also how to
write programs. The project basically consists of java
and its features, jvm and BlueJ.
Acknowledgement
I wish toexpress my gratitude to Vinita mam of Anand
Nikatan for providing me an opportunity to demy project
.This project bears on imprint of many people. I sincerely
thanks to teacher, parents and my friends for guidance
and encouragement in carrying out this project work.
Last but not least I wish to avail myself of this
opportunity, express a sense of gratitude and love to
everyone who helped me for their mutual support,
strength and help and for everything.
Rohan Patel
Content
Java
Comparison of java and c++
Data type
Type members
Statements and expression
Methods
Runtime environment
Java virtual machine
Type of java programs
Bluej
Objet
Class
Program (virtual calculator)
Program (ATM)

Java
Content
Introduction
History of java
Principles of java
Practices
Performance
Automatic memory management
Syntax
Expressiveness
Benchmarks
Time line of specific language comparisons
Introduction
Java

Object-oriented, structured,
Paradigm
imperative
Appeared in 1995
Sun Microsystems (Now owned
Designed by
by Oracle Corporation)
James Gosling & Sun
Developer
Microsystems
Java Standard Edition 6
Stable release (1.6.0_21) (July 7, 2010; 2
months ago)
Static, strong, safe, nominative,
Typing discipline
manifest
Major
OpenJDK, HotSpot, many others
implementations
Dialects Generic Java, Pizza
Ada 83, C++, C#, Delphi Object
Pascal, Eiffel, Generic Java,
Influenced by
Mesa, Modula-3, Objective-C,
UCSD Pascal, Smalltalk
Ada 2005, BeanShell, C#,
Clojure, D, ECMAScript,
Influenced
Groovy, J#, JavaScript, PHP,
Python, Scala
OS Cross-platform (multi-platform)
GNU General Public License /
License
Java Community Process
Usual file
.java, .class, .jar
extensions
Website For Java Developers

Java is a programming language originally developed by James Gosling at Sun


Microsystems (which is now a subsidiary of 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 has a simpler object model and fewer low-level
facilities. Java applications are typically compiled to byte code (class file) that can run
on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a
general-purpose, concurrent, class-based, object-oriented language that is specifically
designed to have as few implementation dependencies as possible. It is intended to let
application developers "write once, run anywhere". Java is currently one of the most
popular programming languages in use, and is widely used from application software
to web applications.

History of java
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. Java was originally designed for interactive television, but it was
too advanced. The language was initially called Oak after an oak tree that stood
outside Gosling's office; it went by the name Green later, and was later renamed Java,
from a list of random words. Gosling aimed to implement a virtual machine and a
language that had a familiar C/C++ style of notation.

Sun Microsystems released the first public implementation as Java 1.0 in 1995. It
promised "Write Once, Run anywhere" (WORA), providing no-cost run-times on
popular platforms. Fairly secure and featuring configurable security, it allowed
network- and file-access restrictions. Major web browsers soon incorporated the
ability to run Java applets within web pages, and Java quickly became popular. With
the advent of Java 2 (released initially as J2SE 1.2 in December 1998–1999), new
versions had multiple configurations built for different types of platforms. For
example, J2EE targeted enterprise applications and the greatly stripped-down version
J2ME for mobile applications (Mobile Java). J2SE designated the Standard Edition.
In 2006, for marketing purposes, Sun renamed new J2 versions as Java EE, Java ME,
and Java SE, respectively.

In 1997, Sun Microsystems approached the ISO/IEC JTC1 standards body and later
the Ecma International to formalize Java, but it soon withdrew from the process. Java
remains a de facto standard, controlled through the Java Community Process. At one
time, Sun made most of its Java implementations available without charge, despite
their proprietary software status. Sun generated revenue from Java through the selling
of licenses for specialized products such as the Java Enterprise System. Sun
distinguishes between its Software Development Kit (SDK) and Runtime
Environment (JRE) (a subset of the SDK); the primary distinction involves the JRE's
lack of the compiler, utility programs, and header files.

On November 13, 2006, Sun released much of Java as open source software under the
terms of the GNU General Public License (GPL). On May 8, 2007, Sun finished the
process, making all of Java's core code available under free software/open-source
distribution terms, aside from a small portion of code to which Sun did not hold the
copyright.

Sun's vice-president Rich Green has said that Sun's ideal role with regards to Java is
as an "evangelist."

Following Oracle Corporation's acquisition of Sun Microsystems in 2009–2010,


Oracle has described itself as the "steward of Java technology with a relentless
commitment to fostering a community of participation and transparency".

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

1. It should be "simple, object oriented, and familiar".


2. It should be "robust and secure".
3. It should be "architecture neutral and portable".
4. It should execute with "high performance".
5. It should be "interpreted, threaded, and dynamic".

Practices
Java Platform
One characteristic of Java is portability, which means that computer programs written
in the Java language must run similarly on any supported hardware/operating-system
platform. This is achieved by compiling the Java language code to an intermediate
representation called Java bytecode, instead of directly to platform-specific machine
code. Java bytecode instructions are analogous to machine code, but are intended to
be interpreted by a virtual machine (VM) written specifically for the host hardware.
End-users commonly use a Java Runtime Environment (JRE) installed on their own
machine for standalone Java applications, or in a Web browser for Java applets.

Standardized libraries provide a generic way to access host-specific features such as


graphics, threading and networking.
A major benefit of using bytecode is porting. However, the overhead of interpretation
means that interpreted programs almost always run more slowly than programs
compiled to native executables would. Just-in-Time compilers were introduced from
an early stage that compile bytecodes to machine code during runtime. Over the years,
this JVM built-in feature has been optimized to a point where the JVM's performance
competes with natively compiled C code.

Implementations
Sun Microsystems officially licenses the Java Standard Edition platform for Linux,
Mac OS X, and Solaris. Although in the past Sun has licensed Java to Microsoft, the
license has expired and has not been renewed. Through a network of third-party
vendors and licensees, alternative Java environments are available for these and other
platforms.

Sun's trademark license for usage of the Java brand insists that all implementations be
"compatible". This resulted in a legal dispute with Microsoft after Sun claimed that
the Microsoft implementation did not support RMI or JNI and had added platform-
specific features of their own. Sun sued in 1997, and in 2001 won a settlement of
US$20 million as well as a court order enforcing the terms of the license from Sun.
As a result, Microsoft no longer ships Java with Windows, and in recent versions of
Windows, Internet Explorer cannot support Java applets without a third-party plugin.
Sun, and others, have made available free Java run-time systems for those and other
versions of Windows.

Platform-independent Java is essential to the Java EE strategy, and an even more


rigorous validation is required to certify an implementation. This environment enables
portable server-side applications, such as Web services, Java Servlets, and Enterprise
JavaBeans, as well as with embedded systems based on OSGi, using Embedded Java
environments. Through the new GlassFish project, Sun is working to create a fully
functional, unified open source implementation of the Java EE technologies.

Sun also distributes a superset of the JRE called the Java Development Kit
(commonly known as the JDK), which includes development tools such as the Java
compiler, Javadoc, Jar and debugger.

Performance
Programs written in Java have a reputation for being slower and requiring more
memory than those written in C. However, Java programs' execution speed improved
significantly with the introduction of Just-in-time compilation in 1997/1998 for Java
1.1, the addition of language features supporting better code analysis (such as inner
classes, StringBuffer class, optional assertions, etc.), and optimizations in the Java
Virtual Machine itself, such as HotSpot becoming the default for Sun's JVM in 2000.

To boost even further the speed performances that can be achieved using the Java
language Systronix made JStik, a microcontroller based on the aJile Systems line of
embedded Java processors. In addition, the widely used ARM family of CPUs has
hardware support for executing Java bytecode through its Jazelle option.
Automatic memory management
Java uses an automatic garbage collector to manage memory in the object lifecycle.
The programmer determines when objects are created, and the Java runtime is
responsible for recovering the memory once objects are no longer in use. Once no
references to an object remain, the unreachable memory becomes eligible to be freed
automatically by the garbage collector. Something similar to a memory leak may still
occur if a programmer's code holds a reference to an object that is no longer needed,
typically when objects that are no longer needed are stored in containers that are still
in use. If methods for a nonexistent object are called, a "null pointer exception" is
thrown.

One of the ideas behind Java's automatic memory management model is that
programmers can be spared the burden of having to perform manual memory
management. In some languages memory for the creation of objects is implicitly
allocated on the stack, or explicitly allocated and deallocated from the heap. Either
way, the responsibility of managing memory resides with the programmer. If the
program does not deallocate an object, a memory leak occurs. If the program attempts
to access or deallocate memory that has already been deallocated, the result is
undefined and difficult to predict, and the program is likely to become unstable and/or
crash. This can be partially remedied by the use of smart pointers, but these add
overhead and complexity. Note that garbage collection does not prevent 'logical'
memory leaks, i.e. those where the memory is still referenced but never used.

Garbage collection may happen at any time. Ideally, it will occur when a program is
idle. It is guaranteed to be triggered if there is insufficient free memory on the heap to
allocate a new object; this can cause a program to stall momentarily. Explicit memory
management is not possible in Java.

Java does not support C/C++ style pointer arithmetic, where object addresses and
unsigned integers (usually long integers) can be used interchangeably. This allows the
garbage collector to relocate referenced objects, and ensures type safety and security.

As in C++ and some other object-oriented languages, variables of Java's primitive


data types are not objects. Values of primitive types are either stored directly in fields
(for objects) or on the stack (for methods) rather than on the heap, as commonly true
for objects (but see Escape analysis). This was a conscious decision by Java's
designers for performance reasons. Because of this, Java was not considered to be a
pure object-oriented programming language. However, as of Java 5.0, autoboxing
enables programmers to proceed as if primitive types were instances of their wrapper
class.

Syntax
The syntax of Java is largely derived from C++. Unlike C++, which combines the
syntax for structured, generic, and object-oriented programming, Java was built
almost exclusively as an object oriented language. All code is written inside a class
and everything is an object, with the exception of the intrinsic data types (ordinal and
real numbers, boolean values, and characters), which are not classes for performance
reasons.

Java suppresses several features (such as operator overloading and multiple


inheritance) for classes in order to simplify the language and to prevent possible
errors and anti-pattern design.

Java uses similar commenting methods to C++. There are three different styles of
comment: a single line style marked with two slashes (//), a multiple line style opened
with a slash asterisk (/*) and closed with an asterisk slash (*/) and the Javadoc
commenting style opened with a slash and two asterisks (/**) and closed with an
asterisk slash (*/). The Javadoc style of commenting allows the user to run the
Javadoc executable to compile documentation for the program.

Example:

// This is an example of a single line comment using two slashes

/* This is an example of a multiple line comment using the slash and asterisk.

This type of comment can be used to hold a lot of information or deactivate

code but it is very important to remember to close the comment. */

/**

* This is an example of a Javadoc comment; Javadoc can compile documentation

* from this text.

*/

Examples

Hello world

The traditional Hello world program can be written in Java as:

// Outputs "Hello, world!" and then exits

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello world!");
}

Source files must be named after the public class they contain, appending the suffix
.java, for example, HelloWorld.java. It must first be compiled into bytecode, using a
Java compiler, producing a file named HelloWorld.class. Only then can it be
executed, or 'launched'. The java source file may only contain one public class but can
contain multiple classes with less than public access and any number of public inner
classes.

A class that is not declared public may be stored in any .java file. 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 were the concatenation of the name of their
enclosing class, a $, and an integer.

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. The class hierarchy
is related to the name of the directory in which the .java file is.

The keyword static in front of a method indicates a static method, which is associated
only with the class and not with any specific instance of that class. Only static
methods can be invoked without a reference to an object. Static methods cannot
access any method variables that are not static.

The keyword void indicates that the main method does not return any value to the
caller. If a Java program is to exit with an error code, it must call System.exit()
explicitly.

The method name "main" is not a keyword in the Java language. It is simply the name
of the method the Java launcher calls to pass control to the program. Java classes that
run in managed environments such as applets and Enterprise JavaBean do not use or
need a main() method. A java program may contain multiple classes that have main
methods, which means that the VM needs to be explicitly told which class to launch
from.

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. Since Java 5,
the main method can also use variable arguments, in the form of public static void
main(String... args), allowing the main method to be invoked with an arbitrary
number of String arguments. The effect of this alternate declaration is semantically
identical (the args parameter is still an array of String objects), but allows an
alternative syntax for creating and passing the array.

The Java launcher launches Java by loading a given class (specified on the command
line or as an attribute in a JAR) and starting its public static void main(String[])
method. Stand-alone programs must declare this method explicitly. The String[] args
parameter is an array of String objects containing any arguments passed to the class.
The parameters to main are often passed by means of a command line.
Printing is part of a 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
many methods for printing data to standard out, including println(String) which also
appends a new line to the passed string.

The string "Hello, world!" is automatically converted to a String object by the


compiler.

A more comprehensive example

// OddEven.java

import javax.swing.JOptionPane;

public class OddEven {

// "input" is the number that the user gives to the computer

private int input; // a whole number("int" means integer)

/*

* This is the constructor method. It gets called when an object of the OddEven
type

* is being created.

*/

public OddEven() {

/*

* Code not shown for simplicity. In most Java programs constructors can initialize
objects

* with default values, or create other objects that this object might use to perform
its

* functions. In some Java programs, the constructor may simply be an empty


function if nothing

* needs to be initialized prior to the functioning of the object. In this program's


case, an
* empty constructor would suffice, even if it is empty. A constructor must exist,
however if the

* user doesn't put one in then the compiler will create an empty one.

*/

// This is the main method. It gets called when this class is run through a Java
interpreter.

public static void main(String[] args) {

/*

* This line of code creates a new instance of this class called "number" (also
known as an

* Object) and initializes it by calling the constructor. The next line of code calls

* the "showDialog()" method, which brings up a prompt to ask you for a number

*/

OddEven number = new OddEven();

number.showDialog();

public void showDialog() {

/*

* "try" makes sure nothing goes wrong. If something does,

* the interpreter skips to "catch" to see what it should do.

*/

try {

/*

* The code below brings up a JOptionPane, which is a dialog box


* The String returned by the "showInputDialog()" method is converted into

* an integer, making the program treat it as a number instead of a word.

* After that, this method calls a second method, calculate() that will

* display either "Even" or "Odd."

*/

input = Integer.parseInt(JOptionPane.showInputDialog("Please Enter A


Number"));

calculate();

} catch (NumberFormatException e) {

/*

* Getting in the catch block means that there was a problem with the format
of

* the number. Probably some letters were typed in instead of a number.

*/

System.err.println("ERROR: Invalid input. Please type in a numerical


value.");

/*

* When this gets called, it sends a message to the interpreter.

* The interpreter usually shows it on the command prompt (For Windows users)

* or the terminal (For Linux users).(Assuming it's open)

*/

private void calculate() {

if (input % 2 == 0) {

System.out.println("Even");
} else {

System.out.println("Odd");

• The import statement imports the JOptionPane class from the javax.swing
package.
• The OddEven class declares a single private field of type int named input.
Every instance of the OddEven class has its own copy of the input field. The
private declaration means that no other class can access (read or write) the
input field.
• OddEven() is a public constructor. Constructors have the same name as the
enclosing class they are declared in, and unlike a method, have no return type.
A constructor is used to initialize an object that is a newly created instance of
the class.
• The calculate() method is declared without the static keyword. This means
that the method is invoked using a specific instance of the OddEven class.
(The reference used to invoke the method is passed as an undeclared
parameter of type OddEven named this.) The method tests the expression
input % 2 == 0 using the if keyword to see if the remainder of dividing the
input field belonging to the instance of the class by two is zero. If this
expression is true, then it prints Even; if this expression is false it prints Odd.
(The input field can be equivalently accessed as this.input, which explicitly
uses the undeclared this parameter.)
• OddEven number = new OddEven(); declares a local object reference
variable in the main method named number. This variable can hold a reference
to an object of type OddEven. The declaration initializes number by first
creating an instance of the OddEven class, using the new keyword and the
OddEven() constructor, and then assigning this instance to the variable.
• The statement number.showDialog(); calls the calculate method. The
instance of OddEven object referenced by the number local variable is used to
invoke the method and passed as the undeclared this parameter to the calculate
method.
• input = Integer.parseInt(JOptionPane.showInputDialog("Please Enter A
Number")); is a statement that converts the type of String to the primitive
data type int by using a utility function in the primitive wrapper class Integer.

Expressiveness
Language Statements ratio Lines ratio The literature on programming languages
C 1 1 contains an abundance of informal claims
C++ 2.5 1 about their relative expressive power, but
Fortran 2.5 0.8 there is no framework for formalizing such
statements nor for deriving interesting
Java 2.5 1.5
Perl 6 6
Smalltalk 6 6.25
Python 6 6.5
consequences. This chart provides two measures of expressiveness from two different
sources. An additional measure of expressiveness, in GZip bytes, can be found on the
Computer Language Benchmarks Game.

Benchmarks
Benchmarks are designed to mimic a particular type of workload on a component or
system. The computer programs used for compiling some of the benchmark data in
this section may not have been fully optimized, and the relevance of the data is
disputed. The most accurate benchmarks are those that are customized to your
particular situation. Other people's benchmark data may have some value to others,
but proper interpretation brings many challenges. See this page about flawed
benchmarks and comparisons. The Computer Language Benchmarks Game site
contains a large number of micro-benchmarks of reader-contributed code snippets,
with an interface that generates various charts and tables comparing specific
programming languages and types of tests.

Time line of specific language comparisons


• 1973 - Comparative Notes on Algol 68 and PL/I - S. H. Valentine - February
1973
• 1976 - Evaluation of ALGOL 68, Jovial J3B, Pascal, SIMULA 67, and
TACPOL Versus TINMAN - Requirements for a Common High Order
Programming Language.
• 1977 - A comparison of PASCAL and ALGOL 68[1] - Andrew S. Tanenbaum
- June 1977.
• 1993 - Five Little Languages and How They Grew - BLISS, Pascal, Algol 68,
BCPL & C - Dennis M. Ritchie - April 1993.
• 2009 - On Go - oh, go on - How well will Google's Go stand up against Brand
X programming language? - David Given - November 2009
Comparison of java and c++
Content
General
Language features
Resource management
Libraries
Runtime
Templates vs. Generics
Miscellaneous
Performance
Proprietary control
Language and features

General
C++ Java
No backward compatibility with any
Compatible with C source code, except for
previous language. The syntax is however
a few corner cases.
strongly influenced by C/C++.
Write once run anywhere / everywhere
Write once compile anywhere (WOCA)
(WORA / WORE)
Allows both procedural programming and Encourages an object oriented
object-oriented programming. programming paradigm.
Allows direct calls to native system Call through the Java Native Interface and
libraries. recently Java Native Access
Exposes low-level system facilities. Runs in a protected virtual machine.
Only provides object types and type Is reflective, allowing metaprogramming
names. and dynamic code generation at runtime.
Has multiple binary compatibility Has a binary compatibility standard,
standards (commonly Microsoft and allowing runtime check of correctness of
Itanium/GNU) libraries.
Optional automated bounds checking. (e.g.
Normally performs bounds checking.
the at() method in vector and string
HotSpot can remove bounds checking.
containers)
Supports native unsigned arithmetic. No native support for unsigned arithmetic.
Standardized minimum limits for all
numerical types, but the actual sizes are
Standardized limits and sizes of all
implementation-defined. Standardized
primitive types on all platforms.
types are available as typedefs (uint8_t, ...,
uintptr_t).
Primitive data types always passed by
Pointers, References, and pass by value are value. Objects are passed by nullable
supported reference (comparable to using pointers for
all class or struct parameters in C++).
Explicit memory management, though Automatic garbage collection (can be
triggered manually). Doesn't have the
third party frameworks exist to provide
concept of Destructor and usage of
garbage collection. Supports destructors.
finalize() is not recommended.
Supports only class and allocates them on
Supports class, struct, and union and can the heap. Java SE 6 optimizes with escape
allocate them on heap or stack analysis to allocate some objects on the
stack.
Rigid type safety except for widening
Allows explicitly overriding types. conversions. Autoboxing/Unboxing added
in Java 1.5.
The standard library has grown with each
The C++ Standard Library has a much release. By version 1.6 the library included
more limited scope and functionality than support for locales, logging, containers and
the Java standard library but includes: iterators, algorithms, GUI programming
Language support, Diagnostics, General (but not using the system GUI), graphics,
Utilities, Strings, Locales, Containers, multi-threading, networking, platform
Algorithms, Iterators, Numerics, security, introspection, dynamic class
Input/Output and Standard C Library. The loading, blocking and non-blocking I/O,
Boost library offers much more and provided interfaces or support classes
functionality including threads and for XML, XSLT, MIDI, database
network I/O. Users must choose from a connectivity, naming services (e.g. LDAP),
plethora of (mostly mutually incompatible) cryptography, security services (e.g.
third-party libraries for GUI and other Kerberos), print services, and web services.
functionality. SWT offers an abstraction for platform
specific GUIs.
The meaning of operators is generally
Operator overloading for most operators immutable, however the + and +=
operators have been overloaded for Strings.
Full multiple inheritance, including virtual Single inheritance only from classes,
inheritance. multiple from interfaces.
Generics are used to achieve an analogous
effect to C++ templates, however they do
Compile time Templates not translate from source code to byte code
due to the use of Type Erasure by the
compiler.
No function pointer mechanism. Instead
Function pointers, function objects,
idioms such as Interfaces, Adapters and
lambdas (in C++0x) and interfaces
Listeners are extensively used.
No standard inline documentation
mechanism. 3rd party software (e.g. Javadoc standard documentation
Doxygen) exists.
final provides a limited version of const,
const keyword for defining immutable equivalent to type* const pointers for
variables and member functions that do not objects and plain const of primitive types
change the object. only. No const member functions, nor any
equivalent to const type* pointers.
Supports labels with loops and statement
Supports the goto statement.
blocks.
Source code can be written to be platform Is compiled into byte code for the JVM. Is
independent (can be compiled for
Windows, BSD, Linux, Mac OS X, Solaris dependent on the Java platform but the
etc. without needing modification) and source code is typically written not to be
written to take advantage of platform dependent on operating system specific
specific features. Is typically compiled into features.
native machine code.

C++ is a powerful language designed for system programming. The Java language
was designed to be simple and easy to learn with a powerful cross-platform library.
The Java standard library is considerably large for a standard library. However, Java
does not always provide full access to the features and performance of the platform
that the software runs on. The C++ standard libraries are simple and robust providing
containers and associative arrays.

Language features
Syntax
• Java syntax has a context-free grammar which can be parsed by a simple
LALR parser. Parsing C++ is somewhat more complicated; for example,
Foo<1>(3); is a sequence of comparisons if Foo is a variable, but it creates an
object if Foo is the name of a class template.
• C++ allows namespace level constants, variables, and functions. All such Java
declarations must be inside a class or interface.
• In C++ declarations, a class name declares an object of that class as a value
(a.k.a. value semantics). There is no way to do this in Java. Objects are not
values in Java. In Java declarations, a class name declares a reference to an
object of that class (a.k.a. reference semantics). The equivalent way to do this
in C++ is to use "*" to declare a pointer.
• In C++, the operator "." takes an object as the left operand and accesses a
member of the object. Since objects cannot be values in Java, and all objects
are accessed through references, this cannot be done in Java. In Java, the "."
operator takes a reference to an object as the left operand and access a member
of that object. The equivalent operator in C++ is "->".

C++ Java
class Foo { // Declares class Foo class Foo { // Defines class Foo

public: public int x = 0; // Member variable,

int x; // Member variable // with initializer

public Foo() { // Constructor for


Foo
Foo(): x(0) { // Constructor for Foo,
}
} // initializes x
public int bar(int i) {// Member method
int bar(int i) { // Member function bar()
bar()
return 3*i + x;
return 3*i + x;
}
}
};
}
Foo a;

Foo a; // declares a to be a reference to a Foo


object
// declares a to be a Foo object value,
a = new Foo();
// initialized using the default constructor
// initializes using the default constructor
// If you wanted to use another constructor,
// If you wanted to use another constructor,
// you would declare it as "Foo a(args);"
// you would declare it as "Foo a = new
Foo(args);"
Foo b = a.clone();

Foo b = a; // copies the values of all members

// copies the contents of a to a new Foo // of this instance if, and only if,
object b;
// Foo implements a public method called
// alternative syntax is "Foo b(a)"
// clone() which returns a new copy of the
object
a.x = 5; // modifies the object a a.x = 5; // modifies the object a
cout << b.x << endl; System.out.println(b.x);

// outputs 0, because b is a // outputs 0, because b points to a

// different object than a // different object than a


Foo c;
Foo *c;
// declares c to be a reference to a Foo
// declares c to be a pointer to a
// object (initially null if c is a class
member;
// Foo object (initially
// you are required to initialize c before use
// undefined; could point anywhere)
// if it is a local variable)
c = new Foo(); c = new Foo();
// binds c to reference a new Foo object // binds c to reference a new Foo object
Foo *d = c; Foo d = c;

// binds d to reference the same object as c // binds d to reference the same object as c
c->x = 5; c.x = 5;

// modifies the object referenced by c // modifies the object referenced by c


a.bar(5); // invokes Foo::bar() for a a.bar(5); // invokes Foo.bar() for a

c->bar(5); // invokes Foo::bar() for *c c.bar(5); // invokes Foo.bar() for c


System.out.println(d.x);
cout << d->x << endl;
// outputs 5, because
// outputs 5, because d references the
// d references
// same object as c
// the same object as c

• In C++, it is possible to declare a pointer to a const type, that is, you cannot
modify the object pointed to by the pointer using that pointer. Functions and
methods can also guarantee that they will not modify the object pointed to by a
pointer by using the "const" keyword. This enforces const-correctness. This is
not possible in Java. You can declare a reference "final" in Java (like declaring
a pointer "const" in C++), but this just prevents you from re-binding that
reference; you can still modify the object referenced by the reference.

C++ Java
private final Foo a;//Use getA() instead of
a
const Foo *a; // you cannot modify the
object public Foo getA(){

//pointed to by a through a return a.clone()

}
a = new Foo(); a=new Foo();//Only in constructor
a->x = 5; getA().x=5;

// ILLEGAL //Only modifies a clone of a's x, not a.x


Foo *const b = new Foo(); final Foo b = new Foo();

// you can declare a "const" pointer // you can declare a "final" reference
b = new Foo(); b = new Foo();

//ILLEGAL, you can't re-bind it // ILLEGAL, you can't re-bind it


b->x = 5; b.x = 5;

// LEGAL, you can still modify the object // LEGAL, you can still modify the object
• C++ supports goto statements; Java enforces structured control flow, and
relies on labelled break and labelled continue statements to provide some
goto-like functionality. Some commenters point out that these labelled flow
control statements break the single point-of-exit property of structured
programming.
• C++ provides low-level features which Java lacks. In C++, pointers can be
used to manipulate specific memory locations, a task necessary for writing
low-level operating system components. Similarly, many C++ compilers
support inline assembler. In Java, such code has to reside in external libraries,
and can only be accessed through the Java Native Interface with a significant
overhead for each call.

Semantics
• C++ allows default values for arguments of a function/method, Java does not.
However, method overloading can be used to obtain similar results in Java.
• The minimal compilation unit in C++ is a function; the compilation unit in
Java is a class. In C++, functions can be compiled separately. In Java, to
compile and maintain methods separately requires moving them into super and
extended classes or using some other code refactoring technique.
• C++ allows a range of implicit conversions between native types, and also
allows the programmer to define implicit conversions involving user-defined
types. In Java, only widening conversions between native types are implicit;
other conversions require explicit cast syntax.
o A consequence of this is that although loop conditions (if, while and
the exit condition in for) in Java and C++ both expect a boolean
expression, code such as if(a = 5) will cause a compile error in Java
because there is no implicit narrowing conversion from int to boolean.
This is handy if the code was a typo for if(a == 5). Yet current C++
compilers usually generate a warning when such an assignment is
performed within a conditional expression.
• For passing parameters to functions, C++ supports both pass-by-reference and
pass-by-value. In Java, parameters are always passed by value. However, in
Java all non-primitive values are references to objects (in C++ terms, they are
(smart)-pointers). Objects are not values in Java and only their references can
be manipulated; C++ developers who are used to having objects as values may
confuse this with pass-by-reference.
• Java built-in types are of a specified size and range defined by the virtual
machine; In C++, a minimal range of values is defined for built-in types, but
the exact representation (number of bits) can be mapped to whatever native
types are supported on a given platform.
o For instance, Java characters are 16-bit Unicode characters, and strings
are composed of a sequence of such characters. C++ offers both
narrow and wide characters, but the actual size of each is platform
dependent, as is the character set used. Strings can be formed from
either type.
• The rounding and precision of floating point values and operations in C++ is
platform dependent. Java provides an optional strict floating-point model that
guarantees consistent results across platforms, though possibly at the cost of
slower run-time performance.
• In C++, pointers can be manipulated directly as memory address values. Java
does not have pointers — it only has object references and array references,
neither of which allow direct access to memory addresses. In C++ one can
construct pointers to pointers, while Java references only access objects.
• In C++, pointers can point to functions or methods (function pointers or
functors). The equivalent mechanism in Java uses object or interface
references.
• Through the use of stack-allocated objects, C++ supports scoped resource
management, a technique used to automatically manage memory and other
system resources that supports deterministic object destruction. Yet, scoped
resource management in C++ cannot be guaranteed; it is only a design pattern,
and hence relies on programmers' adherence. Java supports automatic memory
management using garbage collection, but other system resources (windows,
communication ports, threads) often have to be explicitly released if the
garbage collector can not determine they are no longer used.
• C++ features programmer-defined operator overloading which is not
supported in Java. The only overloaded operators in Java are the "+" and "+="
operators, which concatenate strings as well as performing addition.
• Java features standard API support for reflection and dynamic loading of
arbitrary new code.
• C++ supports static and dynamic linking of binary to manage the space
required for binary and performance.
• Java has generics, whose main purpose is to provide type-safe containers. C++
has templates, which provide more extensive support for generic
programming.
• Both Java and C++ distinguish between native types (these are also known as
"fundamental" or "built-in" types) and user-defined types (these are also
known as "compound" types). In Java, native types have value semantics only,
and compound types have reference semantics only. In C++ all types have
value semantics, but a reference can be created to any type, which will allow
the object to be manipulated via reference semantics.
• C++ supports multiple inheritance of arbitrary classes. In Java a class can
derive from only one class, but a class can implement multiple interfaces (in
other words, it supports multiple inheritance of types, but only single
inheritance of implementation).
• Java explicitly distinguishes between interfaces and classes. In C++ multiple
inheritance and pure virtual functions make it possible to define classes that
function almost like Java interfaces do, with a few small differences.
• Java has both language and standard library support for multi-threading. The
synchronized keyword in Java provides simple and secure mutex locks to
support multi-threaded applications, though synchronized sections have to be
left in LIFO order. Java also provides robust and complex libraries for more
advanced multi-threading synchronization. In C++ there is currently no
defined memory model for multi-threading; however, third party libraries
provide support roughly equivalent to that of Java; obvious difference being
the non-uniformity of these C++ libraries.
• C++ methods can be declared as virtual functions, which means the method to
be called is determined by the run-time type of the object. By default, methods
in C++ are not virtual. In Java, methods are virtual by default, but can be made
non-virtual by using the final keyword.
• C++ enumerations are primitive types and support conversion to and
comparison with other integer types. Java enumerations are actually instances
of a class (they extend java.lang.Enum<E>) and may therefore define
constructors, fields, and methods as any other class.

Resource management
• Java offers automatic garbage collection. Memory management in C++ is
usually done through constructors, destructors, and smart pointers. The C++
standard permits garbage collection, but does not require it; garbage collection
is rarely used in practice. The enforced use of automatic garbage collection
means that writing real-time software can be difficult in Java.
• C++ can allocate arbitrary blocks of memory. Java only allocates memory
through object instantiation. (Note that in Java, the programmer can simulate
allocation of arbitrary memory blocks by creating an array of bytes. Still, Java
arrays are objects.)
• Java and C++ use different idioms for resource management. Java relies
mainly on garbage collection, which can only reclaim memory and may be a
last shot at other resources, while C++ relies mainly on the RAII (Resource
Acquisition Is Initialization) idiom. This is reflected in several differences
between the two languages:
o In C++ it is common to allocate objects of compound types as local
stack-bound variables which are destroyed when they go out of scope.
In Java compound types are always allocated on the heap and collected
by the garbage collector (except in virtual machines that use escape
analysis to convert heap allocations to stack allocations).
o C++ has destructors, while Java has finalizers. Both are invoked prior
to an object's deallocation, but they differ significantly. A C++ object's
destructor must be implicitly (in the case of stack-bound variables) or
explicitly invoked to deallocate the object. The destructor executes
synchronously just prior to the point in the program at which the object
is deallocated. Synchronous, coordinated uninitialization and
deallocation in C++ thus satisfy the RAII idiom. In Java, object
deallocation is implicitly handled by the garbage collector. A Java
object's finalizer is invoked asynchronously some time after it has been
accessed for the last time and before it is actually deallocated, which
may never happen. Very few objects require finalizers; a finalizer is
only required by objects that must guarantee some clean up of the
object state prior to deallocation — typically releasing resources
external to the JVM. In Java safe synchronous deallocation of
resources has to be performed explicitly using the try/finally construct.
o In C++ it is possible to have a dangling pointer – a stale reference to an
object that has already been deallocated; attempting to use a dangling
pointer typically results in program failure. In Java, the garbage
collector won't destroy a referenced object.
o In C++ it is possible to have uninitialized primitive objects, Java
enforces default initialization.
o In C++ it is possible to have an object that is allocated, but has no
reachable reference to it. Such an unreachable object cannot be
destroyed (deallocated), and results in a memory leak. In contrast, in
Java an object will not be deallocated by the garbage collector until it
becomes unreachable (by the user program). (Note: weak references
are supported, which work with the Java garbage collector to allow for
different strengths of reachability.) Garbage collection in Java prevents
many memory leaks, but leaks are still possible under some
circumstances.
o Java is more prone to leaking non-memory resources, while idiomatic
C++ makes that much harder.

Libraries
• C++ provides cross-platform access to many features typically available in
platform-specific libraries. Direct access from Java to native operating system
and hardware functions requires the use of the Java Native Interface.

Runtime
• C++ is normally compiled directly to machine code which is then executed
directly by the operating system. Java is normally compiled to byte-code
which the Java virtual machine (JVM) then either interprets or JIT compiles to
machine code and then executes.
• Due to its unconstrained expressiveness, low level C++ language features (e.g.
unchecked array access, raw pointers, type punning) cannot be reliably
checked at compile-time or without overhead at run-time. Related
programming errors can lead to low-level buffer overflows and segmentation
faults. The Standard Template Library provides higher-level abstractions (like
vector, list and map) to help avoid such errors. In Java, low level errors either
cannot occur or are detected by the JVM and reported to the application in the
form of an exception.
• The Java language requires specific behavior in the case of an out-of-bounds
array access, which generally requires bounds checking of array accesses. This
eliminates a possible source of instability but usually at the cost of slowing
down execution. In some cases, compiler analysis can prove a bounds check
unnecessary and eliminate it. C++ has no required behavior for out-of-bounds
access of native arrays, thus requiring no bounds checking for native arrays.
C++ standard library collections like std::vector, however, offer optional
bounds checking. In summary, Java arrays are "always safe; severely
constrained; always have overhead" while C++ native arrays "have optional
overhead; are completely unconstrained; are potentially unsafe."

Templates vs. Generics


Both C++ and Java provide facilities for generic programming, templates and
generics, respectively. Although they were created to solve similar kinds of problems,
and have similar syntax, they are actually quite different.
C++ Templates Java Generics
Classes and methods can be
Classes and functions can be templated.
genericized.
Parameters can be any type or integral Parameters can only be reference
value. types (not primitive types).
Separate copies of the class or function are One version of the class or function
likely to be generated for each type is compiled, works for all type
parameter when compiled. parameters.
Type parameters are erased when
Objects of a class with different type compiled; objects of a class with
parameters are different types at run time. different type parameters are the
same type at run time.
Implementation source code of the
Signature of the class or function
templated class or function must be
from a compiled class file is
included in order to use it (declaration
sufficient to use it.
insufficient).
Templates can be specialized -- a separate
implementation could be provided for a Generics cannot be specialized.
particular template parameter.
Template parameters can have default
Generic type parameters cannot
arguments (only for template classes, not
have default arguments.
functions).
Does not support wildcards. Instead,
Supports wildcard as type parameter
return types are often available as nested
if it is only used once.
typedefs.
Supports bounding of type
parameters with "extends" and
Does not directly support bounding of
"super" for upper and lower bounds,
type parameters, but metaprogramming
respectively; allows enforcement of
provides this
relationships between type
parameters.
Does not allow instantiation of class
Allows instantiation of class of type
of type parameter type (except
parameter type.
through reflection).
Type parameter of templated class
Type parameter of templated class can be
cannot be used for static methods
used for static methods and variables.
and variables.
Static variables are shared between
Static variables are not shared between
instances of a classes of different
classes of different type parameters.
type parameters.
Templated classes and functions do not Generic classes and functions can
enforce type relations for type parameters enforce type relationships for type
in their declaration. Use of a wrong type parameters in their declaration. Use
parameter results in the template code "not of a wrong type parameter results in
working", usually generating an error a type error at the code that uses it.
message at a place in the template code Operations on parametrized types in
where an operation is not allowed for that generic code are only allowed in
type and not in the user's code. Proper use ways that can be guaranteed to be
of templated classes and functions is safe by the declaration. This results
dependent on proper documentation.
in greater type safety at the cost of
Metaprogramming provides these features
flexibility.
at the cost of additional effort.
Templates are Turing-complete (see
Generics are not Turing-complete.
template metaprogramming).

Miscellaneous
• Java and C++ use different techniques for splitting up code in multiple source
files. Java uses a package system that dictates the file name and path for all
program definitions. In Java, the compiler imports the executable class files.
C++ uses a header file source code inclusion system for sharing declarations
between source files. (See Comparison of imports and includes.)
• Compiled Java code files are generally smaller than code files in C++ as Java
bytecode is usually more compact than native machine code and Java
programs are never statically linked.
• C++ compilation features an additional textual preprocessing phase, while
Java does not. Thus some users add a preprocessing phase to their build
process for better support of conditional compilation.
• In both languages, arrays have a fixed size. In Java, arrays are first-class
objects, while in C++ they are merely a continuous run of their base objects,
often referred to using a pointer to their first element and an optional length. In
Java, arrays are bounds-checked and know their length, while in C++ you can
treat any subsequence as an array in its own right. Both C++ and Java provide
container classes (std::vector and java.util.ArrayList respectively) which are
resizable and store their size.
• Java's division and modulus operators are well defined to truncate to zero. C+
+ does not specify whether or not these operators truncate to zero or "truncate
to -infinity". -3/2 will always be -1 in Java, but a C++ compiler may return
either -1 or -2, depending on the platform. C99 defines division in the same
fashion as Java. Both languages guarantee (where a and b are integer types)
that (a/b)*b + (a%b) == a for all a and b (b != 0). The C++ version will
sometimes be faster, as it is allowed to pick whichever truncation mode is
native to the processor.
• The sizes of integer types is defined in Java (int is 32-bit, long is 64-bit), while
in C++ the size of integers and pointers is compiler and ABI dependent within
given constraints. Thus, carefully-written C++ code can take advantage of the
64-bit processor's capabilities while still functioning properly on 32-bit
processors. However, care must be taken to write the C++ program in a
portable manner. In contrast, Java's fixed integer sizes mean that programmer
error in this regar regard shouldn't be possible. This may incur a performance
penalty since Java code cannot run using an arbitrary processor's word size.

Performance
In addition to running a compiled Java program, computers running Java applications
must also run the Java Virtual Machine JVM, while compiled C++ programs can be
run without external applications. Early versions of Java were significantly
outperformed by statically compiled languages such as C++. This is because the
program statements of these two closely related languages may compile to a few
machine instructions with C++, while compiling into several byte codes involving
several machine instructions each when interpreted by a JVM. For example:

Java/C++ statement C++ generated code (x86) Java generated byte code
aload_1

mov edx,[ebp+4h] iload_2


dup2
vector[i]++;
mov eax,[ebp+1Ch] iaload
inc dword ptr [edx+eax*4] iconst_1
iadd
iastore

While C++ is faster than Java in most cases, there are several studies of mostly
numerical benchmarks, which argue that Java could potentially outperform C++ in
some circumstances,. However, it was shown that numerical (micro-)benchmarks are
not appropriate for evaluation of languages as compiler is able to optimize both cases
equally, or eliminate benchmarked code entirely. If referring to a real world program,
Java would suffer because of number of reasons:

• All objects are allocated on the heap. For functions using small objects this
can result in huge performance degradation as stack allocation costs
essentially zero.
• Methods are by-default virtual. This increases memory usage as much as
several times for small objects because of virtual function tables. Also, it
induces performance penalty, because JIT compiler has to do additional
optimization passes even for de-virtualization of small functions.
• A lot of casting required even using standard containers induces performance
penalty as it is needed to walk through entire inheritance hierarchy.
• Virtual Java Machine Increases memory usage even further, thus reducing
memory locality and increasing chances of cache misses and therefore
slowdown of the program.
• Lack of access to low level details does not allow developer to better optimize
the program where the compiler is unable to do so.

It is argued, however, that compared to Java, C++ also has a number of downsides:

• Pointers make optimization difficult since they may point to arbitrary data.
However this is obsoleted as new compilers introduced strict-aliasing rule and
because of support of the C99 keyword restrict.
• Java garbage collection may have better cache coherence than usual usage of
malloc/new for memory allocation as its allocations are generally made
sequentially. Nevertheless, arguments exist that both allocators equally
fragment the heap and no one exhibits better cache locality.
• Run-time compilation can potentially use additional information available at
run-time to optimise code more effectively, such as knowing what processor
the code will be executed on. However this claim is effectively made obsolete
as most state-of-the-art C++ compilers generate multiple code paths to employ
full computational abilities of the given system

Furthermore, it is arguable that time spent debugging more complex C++ code could
just as easily be spent optimising existing Java code. Of course this is subject to other
concerns such as how far it is possible to optimise bottleneck code in a given
program. Ultimately, for processor-hungry cases such as video rendering, C++ has the
direct access to hardware (being OS-native) and as such, will always be able to
outperform Java given a particular hardware spec.

Proprietary control
C++ is not a trademark of any company or organization and is not owned by any
individual. Java is a trademark of Sun Microsystems, which is now owned by Oracle.

The C++ language is defined by ISO/IEC 14882, an ISO standard, which is published
by the ISO/IEC JTC1/SC22/WG21 committee. The Java language is defined by the
Java Language Specification, a book which is published by Sun (now Oracle).

Language and features


Feature comparison

Data types Java C#


Single-root (unified) type
No Yes
system
Yes; 8, 16, 32, 64
Signed integers Yes; 8, 16, 32, 64 bits
bits
Unsigned integers No Yes; 8, 16, 32, 64 bits
Character Yes Yes
Date/time Yes; reference type Yes; value type
IEEE 754 binary32
Yes Yes
floating point number
IEEE 754 binary64
Yes Yes
floating point number
No; but see
High precision floating 128-bit (28 digits)
Arbitrary size
point number Decimal type
decimals
Boolean type Yes Yes
Immutable
Immutable reference
Strings reference type,
type, Unicode
Unicode
Reference type; no
Arbitrary size integers Yes
operators
Reference type; no
Arbitrary size decimals No
operators
Complex numbers No Yes
Reference types Yes Yes
Arrays Yes Yes
No; only primitive
Value types Yes
types
Enumerated types Yes; reference type Yes; scalar
No; but wrapper
Lifted (nullable) types Yes
types
Tuples No Yes
Pointers No Yes
Reference types Java C#
Garbage collection Yes Yes
Weak references Yes Yes
Soft references Yes No
Yes; proxy
Proxy support Yes; object contexts
generation
Object orientation Java C#
Classes Yes Yes
Interfaces Yes Yes
Abstract classes Yes Yes
Public, protected,
Member accessibility Public, package,
internal, protected
levels private, protected
internal, private
Class level inner classes Yes Yes
Instance level inner
Yes No
classes
Partial classes No Yes
Statement level
Yes No
anonymous classes
Implicit (inferred)
No Yes
anonymous classes
Deprecation/obsolescence Yes Yes
Overload versioning Some Yes
Properties No Yes
Events No Yes
Operators (operator
No Yes
overloading)
Indexers No Yes
Implicit conversions No Yes
Explicit conversions No Yes
Fields and initialization Java C#
Fields Yes Yes
Constants Yes Yes
Static (class) constructors Yes Yes
Instance constructors Yes Yes
Finalizers/destructors Yes Yes
Instance initializers Yes No
Top-down (fields);
Bottom-up (fields
Object initialization bottom-up
and constructors)
(constructors)
Object initializers No Yes
No; can be
Collection initializers Yes
modelled
Array initializers Yes Yes
Methods and properties Java C#
Static imports Yes No
Virtual Virtual by default Non-virtual by default
Abstract Yes Yes
Sealing Yes Yes
Explicit interface
No Yes
implementation
Value (input) parameters Yes Yes
Reference (input/output)
No Yes
parameters
Output (output)
No Yes
parameters
Variadic methods Yes Yes
Optional arguments No Yes
Named arguments No Yes
Generator methods No Yes
Extension methods No Yes
Conditional methods No Yes
Partial methods No Yes
Generics Java C#
Reified generics No Yes
Co-variance Yes Yes
Contra-variance Yes Yes
Reference type constraint Yes; implicit Yes
Value/primitive type
No Yes
constraint
Constructor constraint No Yes
Relation constraint Yes Yes
Primitive/value type
No Yes
support
Migration compatibility Yes No
Functional
Java C#
programming
Method references No; some use cases Yes
covered by
anonymous inner
classes
No; some use cases
covered by
Closures/lambdas Yes
anonymous inner
classes
Expression trees No Yes
Generic query language No Yes
Runtime (dynamic)
Java C#
binding
Late-bound (dynamic)
No Yes
type
Runtime type
information and Java C#
manipulation
Yes; but with type
Runtime type information Yes
erasure
Runtime generics
No Yes
realization
No; third party
Runtime type construction Yes
tools exist
Statements Java C#
Loops Yes Yes
Conditionals Yes Yes
Flow control Yes Yes
Assignment Yes Yes
Exception control Yes Yes
Variable declaration Yes Yes
Variable type inference No Yes
Deterministic disposal
No Yes
(ARM-blocks)
Expressions and
Java C#
operators
Arithmetic operators Yes Yes
Logical operators Yes Yes
Bitwise logic operators Yes Yes
Conditional Yes Yes
String concatenation Yes Yes
Casts Yes Yes
Boxing Yes; implicit Yes; implicit
Unboxing Yes; implicit Yes; explicit
Lifted operators No Yes
Overflow control No Yes
Strict floating point
Yes; opt-in/out No
evaluation
Verbatim (here-)strings No Yes
Exceptions Java C#
Checked exceptions Yes No
Try-catch-finally Yes Yes
Arrays and collections Java C#
Abstract data types Yes Partial
One-dimensional, zero-
Yes Yes
based index arrays
Rectangular
No Yes
(multidimensional) arrays
Jagged (arrays of arrays)
Yes Yes
arrays
Non-zero based arrays No Some
Unified arrays and
No Yes
collections
Maps/dictionaries Yes Yes
Sorted dictionaries Yes Yes
Sets Yes Yes
Sorted sets Yes Yes
Lists/vectors Yes Yes
Queues/stacks Yes Yes
Priority queue Yes No
Bags/multisets Yes Yes
Metadata Java C#
Metadata
Interface based Class based
annotations/attributes
No; unless a single
Positional arguments Yes
argument
Named arguments Yes Yes
Default values At definition Through initialization
Nested types Yes Yes
Specialization No Yes
Conditional metadata No Yes
Preprocessing,
compilation and Java C#
packaging
Namespaces Packages Namespaces
Packaging Package Assembly
Classes/assembly search
Yes; ClassPath No; /lib
path
File contents Restricted Free
Conditional compilation No Yes
Custom errors/warnings No Yes
Explicit regions No Yes
Threading and
Java C#
synchronization
Threads Yes Yes
Thread pool Yes Yes
Task based parallelism No Yes
Semaphores Yes Yes
Monitors Yes Yes
Yes;
Thread local variables Yes
ThreadStaticAttribute
Native interoperability Java C#
External/native methods Yes Yes
External glue code Yes; metadata
Marshalling
required controlled
Pointers and arithmetics No Yes
Native types No Yes
Fixed size buffers No Yes
Explicit stack allocation No Yes
Address-of No Yes
Object pinning (fix
No Yes
variable to address)
Platform support Java C#
Linux Yes Yes
Mac OS X Yes Yes
Solaris Yes Yes
FreeBSD Yes Yes
AIX Yes Yes
iOS No Yes
Windows Yes Yes
Open source &
Java C#
standards
Standardised by national
No Yes
standards body
Open source compiler and
core libraries Yes Yes
implementation available
Vendor patent grant Partial Yes; full
Data types
Content
Unified type system
Simple/primitive types
Advanced numeric types
Built-in compound data types
Reference types
Value types
Lifted (nullable) types
Enumerations
Delegates / method references
Late-bound (dynamic) type
Pointer
Object handling
Reference

Unified type system


In Java the primitive types are special in that they are not object-oriented and they
could not have been defined using the language itself. The Java reference types all
derive from a common root type, however. C# has a unified type system in which all
types ultimately derive from a common root type. Consequently, all types implement
the methods of this root type, and extension methods defined for the object type apply
to all types, even primitive int literals and delegates. Note, that unlike Java, C# this
way supports objects with encapsulation which are not reference types.

In Java compound types are synonymous with reference types; you can not define
methods for a type unless it is also a class reference type. In C# the concepts of
encapsulation and methods have been decoupled from the reference requirement so
that a type can support methods and encapsulation without being a reference type.
Only reference types support virtual methods and specialization, however.

The primitive types of Java are special and could not have been defined using the
language itself. They also do not share a common ancestor with reference types.

Simple/primitive types
Both languages support a number built-in types which are copied and passed by value
rather than by reference. Java calls these types primitive types, while they are called
simple types in C#. The simple/primitive types typically have native support from the
underlying processor architecture.

C# has a few more primitive types than Java, because it supports unsigned as well as
signed integer types, and a decimal type for decimal floating-point calculations.

Java lacks the unsigned types. In particular, Java lacks a primitive type for an
unsigned byte. The Java byte type is signed, while the C# byte is unsigned and sbyte is
signed.

Both languages feature a native char (character) datatype as a simple type. Although
the Java char type can used with bitwise operators, this is actually accomplished by
promoting the char to an integer before the operation.

C# has a type for high-precision (28 decimal digits) decimal arithmetic (based on the
IEEE 754 Decimal128 format[citation needed]) for e.g. financial and monetary application.
While Java lacks such a built-in type, the Java library does feature an arbitrary
precision decimal type. This is not considered a language type and it does not support
the usual arithmetic operators; rather it is a reference type which must be manipulated
using the type methods. See more on arbitrary size/precision numbers below.

The C# primitive/simple types implement a number of interfaces and consequently


offer a number of methods directly on instances of the types - even on the literals. The
C# type names are also merely aliases for Common Language Runtime types. The C#
Long type is exactly the same type as the long type; the only difference is that the
former is the canonical .NET name while the latter is in C# alias for it.

Java does not offer methods directly on the primitive types. Instead methods which
operate on the primitive values are offered through companion wrapper classes. A
fixed set of such wrapper classes exist each of which wraps on of the fixed set of
primitive types. As an example, the Java Long type is a reference type which wraps
the primitive long type. They are not the same type, however.

The following table summarizes the corresponding simple/primitive types of the


languages:

.NET
Width Java Java
C# alias CLR Range (apx.)
(bits) type wrapper
type
Sbyte SByte 8 -128 to 127 byte Byte
Not Not
Byte Byte 8 0 to 255
available available
Short Int16 16 -32768 to 32767 short Short
Not Not
Ushort UInt16 16 0 to 65535
available available
-2,147,483,648 to
Int Int32 32 int Integer
2,147,483,647
Not Not
Uint UInt32 32 0 to 4,294,967,295
available available
-9,223,372,036,854,775,808
Long Int64 64 to long Long
9,223,372,036,854,775,807
0 to Not Not
Ulong UInt64 64
18,446,744,073,709,551,615 available available
-3.402823e38 to
Float Single 32 float Float
3.402823e38
-1.79769313486232e308 to
Double Double 64 double Double
1.79769313486232e308
±1.0 × 10e−28 to ±7.9 × Not Not
Decimal Decimal 128
10e28 available available
char Char 16 \u0000 to \uFFFF char Character
bool Boolean 8 true, false boolean Boolean

Advanced numeric types


Both languages offer library-defined arbitrary size integer types.
Only Java offers a data type for arbitrary precision decimal point calculations and
only C# offers a type for working with complex numbers.

In both languages the number of operations which can be performed are limited
compared to the built-in IEEE 754 floating point types. For instance, none of the
types support square root or logarithms.

By leveraging the C# support for type integration through custom operator


overloading and custom (implicit and explicit) type conversions, C# achieves better
parity with the built-in types.

Java C#
BigInteger bigNumber =
BigInteger bigNumber =
new
BigInteger("123456789012345678901234567890");
BigInteger.Parse("12345678901234567890123456

BigInteger answer = bigNumber.multiply(new


var answer = bigNumber * 42;
BigInteger("42"));
var square = bigNumber * bigNumber;
BigInteger square =
bigNumber.multiply(bigNumber);
var sum = bigNumber + bigNumber;
BigInteger sum = bigNumber.add(bigNumber);

Built-in compound data types


Both languages treat strings as (immutable) objects of reference type. In both
languages the type contains a number of methods to manipulate strings, parse, format
etc. In both languages regular expressions are considered an external feature and is
implemented in separate classes.

Both languages' libraries define classes for working with dates and calendars in
different cultures. The Java java.util.Date is a mutable reference type where the C#
System.DateTime is a struct value type. C# additionally define a TimeSpan type for
working with time periods. Both languages support date/time arithmetic according to
different cultures.

Reference types
Both languages use classes and interfaces as the primary means for defining new,
object-oriented types. See below for further details.

Value types
C# allows the programmer to create user-defined value types, using the struct
keyword. Unlike classes, and like the standard primitives, such value types are passed
and assigned by value rather than by reference. They can also be part of an object
(either as a field or boxed), or stored in an array, without the memory indirection that
normally exists for class types.

Because value types have no notion of a null value and can be used in arrays without
initialization, they always come with an implicit default constructor that essentially
fills the struct memory space with zeroes. The programmer can only define additional
constructors with one or more arguments. Value types do not have virtual method
tables, and because of that (and the fixed memory footprint), they are implicitly
sealed. However, value types can (and frequently do) implement interfaces. For
example, the built-in integer types implement a number of interfaces.

Apart from the built-in primitive types, Java does not include the concept of value
types.

Enumerations
Enumerations in C# are derived from a primitive integer type (8, 16, 32, or 64 bit).
Any value of the underlying primitive type is a valid value of the enumeration type,
though an explicit cast may be needed to assign it. C# also supports bit-mapped
enumerations where an actual value may be a combination of enumerated values
bitwise or'ed together.

Enumerations in Java, are full objects. The only valid values are the ones listed in the
enumeration. Also, as objects, each enumeration can contain its own methods and
fields, like a dedicated toString() method, for instance, or comparators. They can be
considerered classes with a predefined amount of instances, which are the enum
constants. Special enumeration set and map collections provide fully type-safe
functionality with minimal overhead.

In both C# and Java programmers can use them in a switch statement without
conversion to a string or primitive integer type.

Delegates / method references


C# implements object oriented method pointers in the form of delegates. A delegate is
a special type which can capture a type-safe reference to a method. This reference can
then be stored in a delegate-type variable or passed to a method through a delegate
parameter for later invocation. C# delegates support covariance and contravariance,
and can hold a reference to any signature-compatible static method, instance method
or anonymous method or lambda expression.

Delegates should not be confused with closures and inline functions. The concepts are
related because a reference to a closure/inline function must be captured in a delegate
reference to be useful at all. But a delegate does not always reference an inline
function, it can also reference existing static or instance methods. Delegates form the
basis of C# events but should not be confused with those either.
Java does not have a language-level construct like the C# delegate. To mimic the
functionality the developer will have to create an ad-hoc implementation of a class
(typically an anonymous inner class) where one method performs the desired
invocation. The following code snippets show how to mimic most of the delegate
functionality in Java.

Java C#
// define a delegate // define a delegate

interface SomeDelegate { private delegate bool


SomeDelegate(string resource);
boolean Invoke(String arg);

}
// a target class

class Target {
// a target class
public bool
class Target { TargetMethod(string arg) {

public boolean // do something


TargetMethod(String arg) {
return true;
// do something
}
return true;
}
}

}
// usage

void DoSomething() {
// usage

void DoSomething() {
// construct a target with the
target method

// construct a target with the var target = new Target();


target method

final Target target = new


Target(); // capture the delegate for
later invocation

SomeDelegate dlg =
// capture the delegate for target.TargetMethod;
later invocation
SomeDelegate dlg = new
SomeDelegate() {
// invoke the delegate
public boolean
Invoke(String arg) { bool result =
dlg("argumentstring");
return
target.TargetMethod(arg); }

};

// invoke the delegate

boolean result =
dlg.Invoke("argumentstring");

Lifted (nullable) types


C# allows value/primitive/simple types to be "lifted" to allow the special null value in
addition to the type's native values. A type is lifted by adding a ? suffix to the type
name. Conversions are implicitly defined to convert between values of the base and
the lifted type. The lifted type can be compared against null or it can be tested for
HasValue. Also, lifted operators are implicitly and automatically defined based on
their non-lifted base, where - with the exception of some boolean operators - a null
argument will propagate to the result.

Java does not support type lifting as a concept, but the fixed set of built-in primitive
types all have corresponding (boxed) wrapper types which do support the null value
by virtue of being reference types. However, Java operators such as + are not defined
for these companion wrapper types. Instead Java will fall back to the primitive
operator and will attempt to unbox the operands before invocation. If one or both of
the operands are null, this unboxing will cause a NullPointerException to be thrown.

The following example illustrates how the lifted C# operator propagates the null value
of the operand where the corresponding code in Java will throw an exception.

Java C#
Integer a = 42; int? a = 42;

Integer b = null; int? b = null;


// this will generate a runtime
// c will receive the null value
NullPointerException
// because * is lifted and one of the
// because the * operator will
operands are null
attempt to unbox the null value
int? c = a * b;
Integer c = a * b;

Not all C# lifted operators have been defined to propagate null unconditionally if one
of the operands is null. Specifically, the boolean operators have been lifted to support
ternary logic thus keeping impedance with SQL.

Late-bound (dynamic) type


C# features a late bound dynamic type which supports no-reflection dynamic
invocation, interoperability with dynamic languages as well as ad-hoc binding to (for
example) document object models. The dynamic type resolves member access
dynamically at runtime as opposed to statically/virtual a compile time. The member
lookup mechanism is extensible with traditional reflection as a fall-back mechanism.

There are several use cases for the dynamic type in C#:

• Less verbose use of reflection: By casting an instance to the dynamic type,


members such as properties, methods, events etc. can be directly invoked on
the instance without using the reflection API directly.
• Interoperability with dynamic languages: The dynamic type comes with a hub-
and-spoke support for implementing dynamically typed objects and common
runtime infrastructure for efficient member lookup.
• Creating dynamic abstractions on the fly: For instance, a dynamic object could
provide simpler access to document object models such as XML- or XHTML
documents.

Java does not support a late-bound type. The use cases for C# dynamic type have
different corresponding constructs in Java:

• For dynamic late-bound by-name invocation of preexisting types, reflection


should be used.
• For interoperability with dynamic languages, some form of interoperability
API specific to that language will have to be used. The Java Virtual Machine
platform does have multiple dynamic languages implemented on top if it, but
there is no common standard for how to pass objects between languages.
Usually this will involve some form of reflection or reflection-like API. As an
example of how to use JavaFX objects from Java, see How to Use JavaFX in
Your Swing Application.
• For creating and interacting with objects entirely at runtime, e.g. interaction
with a document object model abstraction, a specific abstraction API will have
to be used.
Pointers
C# allows use of pointers and corresponding pointer arithmetic. Pointers and pointer-
arithmetic are potentially unsafe in a managed environment as they can be used to
bypass the strict rules for object access. C# addresses that concern by requiring that
code blocks or methods that use the feature be marked with the unsafe keyword, so
that all clients of such code can be aware that the code may be less secure than
otherwise. The compiler requires the /unsafe switch to allow compilation of a
program that uses such code, and assemblies containing unsafe code may only
execute if explicitly granted security permissions. Generally, unsafe code is either
used to allow better interoperability with unmanaged APIs or system calls (which are
inherently "unsafe"), or for performance reasons. Java does not permit pointers or
pointer-arithmetic within the Java runtime environment and native interop is handled
externally through JNI or other mechanisms.

Object handling
Both C# and Java are designed from the ground up as object oriented languages using
dynamic dispatch, with syntax similar to C++ (C++ in turn derives from C). Neither
language is a superset of C or C++, however. Both mainly use garbage collection as a
means of reclaiming memory resources, rather than explicit deallocation of memory
(though C# requires explicit deallocation for graphical, GDI+ objects, in which case it
uses the IDisposable interface). Both include thread synchronization mechanisms as
part of their language syntax.

In both languages objects are created with a new.

References
In both languages references are a central concept. All instances of classes are by
reference.

While not directly evident in the language syntax per se, both languages support the
concept of weak references. An instance which is only referenced by weak references
is eligible for garbage collection just as if there were no references at all. In both
languages this feature is exposed through the associated libraries, even though it is
really a core runtime feature.

In addition to weak references, Java has soft references. Soft references are much
like weak references, but the JVM will not deallocate softly-referenced objects until
the memory is actually needed.
Type members
Content
Operator overloading and implicit and explicit
conversions
Indexers
Partial classes
Inner- and local classes
Explicit member implementation
Events
Operator overloading and implicit and explicit
conversions
Operator overloading and user-defined casts are separate features which both aim to
allow new types to become first-class citizens in the type system. By leveraging these
features, types such as Complex and decimal has been integrated so that the usual
operators like addition, multiplication work with the new types.

Java does not include operator overloading nor custom conversions in order to prevent
abuse of the feature, and to keep the language simple.

Indexers
C# also includes indexers which can be considered a special case of operator
overloading (like C++ operator[]), or parametrized get/set properties. An indexer is a
property named this[] which uses one or more parameters (indexes); the indices can
be objects of any type:

myList[4] = 5;

string name = xmlNode.Attributes["name"];

orders = customerMap[theCustomer];

Java does not include indexers. The common Java pattern involves writing explicit
get_ and set_ methods where a C# programmer would use an indexer.

Partial classes
C# allows a class definition to be split across several source files using a feature
called partial classes. Each part must be marked with the keyword partial. All the
parts must be presented to the compiler as part of a single compilation. Parts can
reference members from other parts. Parts can implement interfaces and one part can
define a base class. The feature is useful in code generation scenarios (such as UI
design) where a code generator can supply one part and the developer another part to
be compiled together. The developer can thus edit their part without the risk of a code
generator overwriting that code at some later time. Unlike the class extension
mechanism a partial class allows "circular" dependencies amongst its parts as they are
guaranteed to be resolved at compile time. Java has no corresponding concept.

Inner- and local classes


Both languages allow inner classes, where a class is defined lexically inside another
class. However, in each language these inner classes have rather different semantics.

In Java, unless the inner class is declared static, a reference to an instance of an inner
class carries a reference to the outer class with it. As a result, code in the inner class
has access to both the static and non-static members of the outer class. To create an
instance of a non-static inner class, one has to name the instance of the embracing
outer class. This is done via a new new-operator introduced in JDK 1.3:
outerClassInstance.new Outer.InnerClass(). This can be done in any class that has a
reference to an instance of the outer class.

In C#, an inner class is conceptually the same as a normal class. In a sense, the outer
class only acts as a namespace. Thus, code in the inner class cannot access non-static
members of the outer class unless it does so through an explicit reference to an
instance of the outer class. Programmers can declare the inner class private to allow
only the outer class to have any access to it.

Java provides another feature called local classes or anonymous classes, which can be
defined within a method body. These are generally used to implement an interface
with only one or two methods, which are typically event handlers. They can also be
used to override virtual methods of a super-class however. The methods in those local
classes have access to the outer method's local variables declared final. C# satisfies
the use-cases for these by providing anonymous delegates; see event handling for
more about this.

C# also provides a feature called anonymous classes, but it is rather different from
Java's concept with the same name. It allows the programmer to instantiate a class by
providing only a set of names for the properties the class should have, and an
expression to initialize each. The types of the properties are inferred from the types of
those expressions. These implicitly-declared classes are derived directly from object.

Explicit member implementation


C# also has "Explicit Member Implementation" which allows a class to specifically
implement methods of an interface, separate to its own class methods, or to provide
different implementations for two methods with the same name and signature
inherited from two base interfaces.

Events
C# multicast-delegates are called events. Events provide support for event-driven
programming and is an implementation of the observer pattern. To support this there
is a special syntax to define events in classes, and operators to register, unregister or
combine event handlers.

Java does not offer events as a language construct. Java developers instead manually
implement the observer. Anonymous inner classes are commonly used to implement
the listener, allowing you to define the body of the class and create an instance of it in
a single point in the code.

Statements and expressions


Content
Boxing and Unboxing
Generics
Type erasure versus reified generics
Migration compatibility
Covariance and contravariance
Notation and special features
Numeric applications

Boxing and Unboxing


Both languages allow automatic boxing and unboxing to translate primitive data to
and from their object form. Effectively, this makes the primitive types a subtype of
the Object type. In C# this also means that primitive types can define methods, such
as an override of Object's ToString() method. In Java, separate primitive wrapper
classes provide such functionality. Java does not implicitly box primitive values when
dereferenced and an explicit cast is required for an instance call on a primitive value
— ((Integer)42).toString() instead of a C# instance call 42.ToString(). Another
difference is that Java makes heavy use of boxed types in generics (see below), and as
such allows an implicit unboxing conversion (in C# this requires a cast). As these
implicit unboxing conversions can potentially throw null pointer exceptions, modern
integrated development environments and compilers can be configured to highlight
them.

Generics
In the field of generics the two languages show a superficial syntactical similarity, but
they have deep underlying differences.

Type erasure versus reified generics


Generics in Java are a language-only construction; they are implemented only in the
compiler. The generated classfiles include generic signatures only in the form of
metadata (allowing the compiler to compile new classes against them). The runtime
has no knowledge of the generic type system; generics are not part of the JVM.
Instead, generics classes and methods are transformed during compilation through a
process known as type erasure. During this process the compiler replaces all generic
types with their raw version and inserts casts/checks appropriately in client code
where the type and its methods are used. The resulting byte code will contain no
references to any generic types or parameters (See also Generics in Java).

C# builds on support for generics from the virtual execution system itself, i.e. it is not
just a language feature. The language is merely a front-end for cross-language
generics support in the CLR. During compilation generics are verified for correctness,
but code generation for actually implementing the generics are deferred to class-load
time. Client code (code invoking generic methods/properties) are fully compiled and
can safely assume generics to be type-safe. This is called reification. Unlike with the
Java generics, there is no need to inject down-casts or type-checks in clients code. At
runtime, when a unique set of type parameters for a generic class/method/delegate is
encountered for the first time, the class loader/verifier will synthesize a concrete class
descriptor and generate method implementations. During the generation of method
implementations all reference types will be considered a single type, as reference
types can safely share the same implementations. Note, this is merely for the purpose
of the implementing code. Different sets of reference types will still have unique type
descriptors; their method tables will merely point to the same code.

The Java design imposes restrictions on the developer compared to the C# design. The
following list is not exhaustive (see also Java Generics FAQs - Frequently Asked
Questions by Angelika Langer):

Java C#
Type checks and downcasts are injected
C#/.NET generics guarantees type-safety
into client code (the code referencing the
and is verified at compile time and no extra
generics). Compared to non-generic code
checks/casts are necessary at runtime.
with manual casts, these casts will be the
Hence, generic code will run faster than
same. But compared to compile-time
non-generic code (and type-erased code)
verified code which would not need
which require casts when handling non-
runtime casts and checks, these operations
generic or type-erased objects.
represent a performance overhead.
Cannot use primitive types as type Primitive and value types are allowed as
parameters; instead the developer must use type parameters in generic realizations. At
the wrapper type corresponding to the runtime code will be synthesized and
primitive type. This incurs extra compiled for each unique combination of
performance overhead by requiring boxing type parameters upon first use. Generics
and unboxing conversions as well a which are realized with primitive/value
memory and garbage collection pressure
type do not require boxing/unboxing
because the wrappers will be heap
conversions.
allocated as opposed to stack allocated.
Generic exceptions are not allowed and the
Can both define generic exceptions and use
can not use a type parameter in a catch
those in catch clauses
clause.
Static members are shared across all Static members are separate for each
generic realizations (during type erasure all generic realization. A generic realization is
realizations are folded into a single class) a unique class.
Type parameters cannot be used in
declarations of static fields/methods or in No restrictions on use of type parameters
definitions of static inner classes
Can "import" (using directive) a specific
Cannot "import" a particular realization of
realization with an alias
a generic class
using StringList =
import java.util.List<String> // illegal
System.Collections.Generic.List<string>;
Cannot create an array where the A generic realization is a 1st class citizen
component type is a generic realization and can be used as any other class; also an
(concrete parameterized type) array component

object tenPairs = object tenPairs =

new Pair<Integer, String>[10]; // error new Pair<int, string>[10]; // ok


Type parameters represent actual, discrete
Cannot create an array where the
classes and can be used like any other type
component type is a type parameter
within the generic definition.
public class Lookup<TKey,TValue> {
public class Lookup<TKey, TValue> {
public TValue[] GetEmptyValues(TKey
public TValue[] GetEmptyValues(TKey
key) {
key) {
return new TValue[0]; // error
return new TValue[0]; // ok
}
}
}
}
There is no class literal for a concrete
A generic realization is an actual class.
realization of a generic type
instanceof is not allowed with type The is and as operators work the same for
parameters or concrete generic realizations type parameters as for any other type.
With a constructor constraint, generic
Cannot create new instances using a type methods or methods of generic classes can
parameter as the type create instances of classes which have
default constructors.
Type information is erased during Type information about C# generic types is
compilation. Special extensions to fully preserved at runtime, and allows
reflection must be used to discover the complete reflection support as well as
original type. instantiation of generic types.
Reflection cannot be used to construct new
generic realizations. During compilation Reflection can be used to create new
extra code (typecasts) are injected into the realizations for new combinations of type
client code of generics. This precludes parameters.
creating new realizations later.

C# allows generics directly for primitive types. Java, instead, allows the use of boxed
types as type parameters (e.g., List<Integer> instead of List<int>), but this comes at a
small cost since all such values need to be heap-allocated (however, a generic type
can be specialized with an array type of a primitive type in Java, for example
List<int[]> is allowed).

Migration compatibility
Java's type erasure design was motivated by a design requirement to achieve
migration compatibility - not to be confused with backward compatibility. In
particular the original requirements was "... there should be a clean, demonstrable
migration path for the Collections APIs that were introduced in the Java 2 platform".
This was interpreted by the designers as meaning that any new generic collections
should be passable to methods which expected one of the preexisting collection
classes.

Migration compatibility solves a hypothetical, temporal situation where you have two
software products (A,B) used by you to build software product C. Both A and B are
beyond your control, e.g. supplied by external vendors. Product B builds upon
product A - i.e. they have a direct relationship which you are unable to intercept
through configuration or otherwise. Vendor-A moves product A to take advantage of
generics and stops supporting the non-generic version of A. The vendor of B does not
move his product to take advantage of generics coordinated with A, creating a
situation where the non-generic code of B must be able to call/use generic code of A.
Migration compatibility allows the non-generic code of B to call and even manipulate
objects originating in A.

C# generics were introduced into the language while preserving full backwards
compatibility: Old code (pre C# 2.0) runs unchanged on the new generics-aware
runtime without recompilation. As for migration compatibility, new generic collection
classes and interfaces were developed which supplemented the non-generic .NET 1.x
collections rather than replacing them. In addition to generic collection interfaces, the
new generic collection classes implement the non-generic collection interfaces where
possible. This allows new generic collections to be passed to preexisting (non-generic
aware) methods, as long as those methods are coded to use the collection interfaces
and not the specific classes. This is not full migration compatibility, however.

Covariance and contravariance


Covariance and contravariance is supported by both languages. Java has use-site
variance which allows a single generic class to declare members using both co- and
contravariance. C# has define-site variance for generic interfaces and delegates.
Variance is not supported directly on classes but is supported through their
implementation of variant interfaces. C# also has use-site covariance support for
methods and delegates.

Notation and special features


Special feature keywords
keyword feature, example usage
checked, In C#, checked statement blocks or expressions can enable run-time
unchecked checking for arithmetic overflow.
C# implements properties as part of the language syntax with their
optional corresponding get and set accessors, as an alternative for the
get, set
accessor methods used in Java, which is not a language feature but a
coding-pattern based on method name conventions.
C# supports the goto keyword. This can occasionally be useful, for
example for implementing finite state machines or for generated code, but
the use of a more structured method of control flow is usually
recommended (see criticism of the goto statement). Java allows labeled
breaks and continues, which make up for many of the uses of goto.

switch(color)

case Color.Blue:
goto
Console.WriteLine("Color is blue"); break;

case Color.DarkBlue:

Console.WriteLine("Color is dark");

goto case Color.Blue;

// ...

}
C# has support for output and reference parameters. These allow returning
out, ref
multiple output values from a method, or passing values by reference.
Java uses strictfp to guarantee the results of floating point operations
strictfp
remain the same across platforms.
In C#, the switch statement also operates on strings and longs but only
allows fallthrough for empty statements. Java's switch statement does not
switch
operate on strings nor long primitive type but falls through for all
statements (excluding those with 'break').
throws Java requires every method to declare the checked exceptions or
superclasses of the checked exceptions that it can throw. Any method can
also optionally declare the unchecked exception that it throws. C# has no
such syntax.

public int readItem() throws java.io.IOException

// ...

}
C#'s using causes the Dispose method (implemented via the IDisposable
interface) of the object declared to be executed after the code block has
run or when an exception is thrown within the code block.

// Create a small file "test.txt", write a string,

// ... and close it (even if an exception occurs)


using
using (StreamWriter file = new StreamWriter("test.txt"))

file.Write("test");

Numeric applications
To adequately support applications in the field of mathematic and financial
computation, several language features exist. In this category, Java provides the
strictfp keyword, which enables strict floating-point calculations for a region of code.
This will ensure that calculations return the exact same result on all platforms. C#
provides no equivalent, but does provide the built-in decimal type, for accurate
decimal floating-point calculations. This forgoes the problems that exist with binary
floating-point representations (float, double). Such binary representations are not
suited to accurately represent decimal numbers and hence introduce rounding errors.
For financial applications, an accurate decimal type is essential.

The BigDecimal class also provides such characteristics for Java. BigDecimal and
BigInteger are types provided with Java that allow arbitrary-precision representation
of numbers. As of 2010 the current stable release of the .NET framework (4.0)
includes classes for manipulating arbitrary-precision integers and complex numbers
(with operators overloaded for easy use so that BigInteger objects can be used just
like any other primitive data type) but still .NET Framework lacks classes to deal with
arbitrary-precision floating point numbers (see Arbitrary-precision arithmetic).
In Java there is no way to provide the same level of integration for library-defined
types such as BigDecimal or complex numbers as there is for the primitive types. For
this purpose, C# provides the following:

• Operator overloading and indexers providing convenient syntax (see below).


• Implicit and explicit conversions; allow conversions such as exist for the built-
in int type that can implicitly convert to long.
• Valuetypes and generics based on valuetypes; in Java every custom type must
be allocated on the heap, which is detrimental for performance of both custom
types and collections.

In addition to this, C# can help mathematic applications with the checked and
unchecked operators that allow to enable or disable run-time checking for arithmetic
overflow for a region of code. It also offers rectangular arrays, that have advantages
over regular nested arrays for certain applications.

Methods
Content
Introduction
Generator methods
Explicit interface implementation
Closures
Language integrated query
Lambdas and expression trees
Partial methods
Extension methods
Conditional compilation
Namespaces and source files
Exception handing
Final block
Lower level code

Introduction
Methods in C# are non-virtual by default, and have to be declared virtual explicitly if
desired. In Java, all non-static non-private methods are virtual. Virtuality guarantees
that the most recent override for the method will always be called, but incurs a certain
runtime cost on invocation as these invocations cannot be normally inlined, and
require an indirect call via the virtual method table. However, some JVM
implementations, including the Sun reference implementation, implement inlining of
the most commonly called virtual methods.

Java methods are virtual by default (although they can be "sealed" by using the final
modifier to disallow overriding). There is no way to let derived classes define a new,
unrelated method with the same name.

This means that by default in C#, and only when explicitly asked in Java, you can
define new methods in a derived class with the same name and signature than the one
in its base class. Which implies that when you call that method on such an object,
depending on the current knowledge of the caller (if it knows its exact subclass or
not), the result will be different.
In Java (by default), the subclass's method will be called, but you will be able to call
the base class' own method if needed. In C# (by default), the base class' method will
be called, and you won't be able to intercept the call.

In very specific cases, when a base class is designed by a different person, and a new
version introduces a method with the same name and signature as some method
already present in the derived class, problems can happen.

In Java, this will mean that the method in the derived class will implicitly override the
method in the base class, even though that may not be the intent of the designers of
either class.

To prevent this versioning problem, C# requires that if a method should be


overridden, the override keyword must be specified. Otherwise, the method will
"hide" the inherited method. A compiler warning to this effect is issued, which can be
silenced by specifying the new keyword. This avoids the problem which can arise
from a base class being extended with a protected/public method whose signature is
already in use by a derived class.

Generator methods
Any C# method declared as returning IEnumerable, IEnumerator and/or the generic
versions of these interfaces can be implemented using yield syntax. This is a form of
limited, compiler-generated continuations and can drastically reduce the code required
to traverse or generate sequences, although that code is just generated by the compiler
instead. The feature can also be used to implement infinite sequences, e.g. the
sequence of Fibonacci numbers.

Below is an example of a C# generator method that takes an enumerable input


(possibly an array of ints) and yields the even numbers. The method will not iterate
through all items on the invocation; rather it will return an iterator which will pull
items from numbers only on demand.

public static IEnumerable<int> GetEven(IEnumerable<int> numbers) {

foreach(int i in numbers) if (i % 2 == 0) yield return i;

In Java, generators can be defined only using (possibly anonymous) classes, requiring
more boilerplate code.

Explicit interface implementation


In either language if a method (or property in C#) is specified with the same name and
signature in multiple interfaces, the members will clash when a class is designed
which implements those interfaces. An implementation will by default implement a
common method for all of the interfaces. If separate implementations are required
(because the methods really do serve separate purposes, or because return values
differ between the interfaces) C#'s explicit interface implementation will solve the
problem, though allowing different results for the same method, depending on the
current cast of the object. In Java there is no way to solve this problem other than
cleaning the code and refactoring one or more of the interfaces to avoid name clashes.

Closures
A closure is an inline function which captures variables from its lexical scope.

C# supports closures as anonymous methods or lambda expressions with full-featured


closure semantics.

In Java, anonymous inner classes remains the preferred way to emulate closures.
Aside from being a more verbose construction, this approach also has some
drawbacks compared to real closures, such as limited access to variables from the
enclosing scopes (only final members can be referenced).

When a reference to a method can be passed around for later execution, a problem
arises about what to do when the method has references to variables/parameters in its
lexical scope. C# closures can fully capture any variable/parameter from its lexical
scope. In Java's anonymous inner classes only references to final members of the
lexical scope are allowed, thus requiring the developer to artificially introduce extra
levels of indirections and boxing primitive types if he wants to reference and update
those from the inner class.

While Java does not currently feature closures, it has been announced that some form
of closures will be included in JDK 7.

Language integrated query


C#s Language INtegrated Query (LINQ) is not really a single feature; rather it is a
number of features designed to work together to allow for in-language querying
capabilities. LINQ has emerged as one of the most distinguishing features between
Java and C#.

LINQ consists of the following features:

• Extension methods allow existing interfaces/classes to be extended with new


methods. Implementations can be shared or an interface can have a dedicated
implementation.
• Lambdas allow for expression of criteria in a functional fashion.
• Expression trees allow a specific implementation to capture a lambda as a
concrete syntax tree rather than an executable block. This can be leveraged by
implementations to represent criteria in a different language, e.g. in the form
of a SQL where clause as is the case with e.g. Linq#LINQ_to_SQL
• Anonymous types and type inference supports capturing and working with the
result type of a query. A query may both join and project over query sources
which may lead to a result type which cannot be named.
• Query expressions to support a syntax familiar to SQL.
• Nullable (lifted) types to allow for better match with query providers which
support nullable types, like e.g. SQL.

Lambdas and expression trees


C# features a special type of in-line closures called lambdas. These are anonymous
methods: they have a signature and a body, but no name. They are not methods in that
they cannot form part of a class interface. They are mainly used to specify local
function-valued arguments in calls to other methods, a technique mainly associated
with functional programming. On top of that, lambda functions can double as a way
to define special data structures called expression trees. Whether they are seen as an
executable function or a data structure depends on compiler type inference and what
type of variable or parameter they are assigned/cast to. Lambdas and expression trees
play key roles in LINQ. Java does not feature lambdas or expression trees; its primary
mechanism for inline scope capture and method definition is the anonymous inner
class syntax.

Partial methods
Related to partial classes C# allows partial methods to be specified within partial
classes. A partial method is an intentional declaration of a method with a number of
restrictions on the signature. These restrictions ensure that if a definition is not
actually provided by any class part, then the method and every call to it can be safely
erased. This feature allows code to provide a large number of interception points (like
the template method GoF design pattern) without paying any runtime overhead if
these extension points are not being used by another class part at compile time. Java
has no corresponding concept.

Extension methods
Using a special this designator on the first parameter of a method, C# allows the
method to act as if it were a member method of the type of the first parameter. This
extension of the foreign class is purely syntactical. The extension method needs to be
static and defined within a purely static class. It must obey any restriction on such
external static methods and thus cannot break object encapsulation. The "extension" is
only active within scopes where the namespace of the static host class has been
imported. Java has no corresponding concept.

Conditional compilation
Unlike Java, C# implements conditional compilation using preprocessor directives. It
also provides a Conditional attribute to define methods that are only called when a
given compilation constant is defined. This way, assertions can be provided as a
framework feature with the method Debug.Assert(), which is only evaluated when the
DEBUG constant is defined. Since version 1.4, Java provides a language feature for
assertions, which are turned off at runtime by default but can be enabled using the "-
enableassertions" or "-ea" switch when invoking the JVM.

Namespaces and source files


C#'s namespaces are similar to those in C++. Unlike package names in Java, a
namespace is not in any way tied to location of the source file. While it's not strictly
necessary for a Java source file location to mirror its package directory structure, it is
the conventional organization.

Both languages allow importing of classes (e.g., import java.util.* in Java), allowing
a class to be referenced using only its name. Sometimes classes with the same name
exist in multiple namespaces or packages. Such classes can be referenced by using
fully qualified names, or by importing only selected classes with different names. To
do this, Java allows importing a single class (e.g., import java.util.List). C# allows
importing classes under a new local name using the following syntax: using Console
= System.Console. It also allows importing specializations of classes in the form of
using IntList = System.Collections.Generic.List<int>.

Java has a static import syntax that allows using the short name of some or all of the
static methods/fields in a class (e.g., allowing foo(bar) where foo() can be statically
imported from another class). C# has a static class syntax (not to be confused with
static inner classes in Java), which restricts a class to only contain static methods. C#
3.0 introduces extension methods to allow users to statically add a method to a type
(e.g., allowing foo.bar() where bar() can be an imported extension method working on
the type of foo).

The Sun Microsystems Java compiler requires that a source file name must match the
only public class inside it, while C# allows multiple public classes in the same file,
and puts no restrictions on the file name. C# 2.0 and later allows splitting a class
definition into several files by using the partial keyword in the source code. In Java, a
public class will always be in its own source file. In C#, source code files and logical
units separation are not tightly related.

Exception handling
Java supports checked exceptions (in addition to unchecked exceptions). C# only
supports unchecked exceptions. Checked exceptions force the programmer to either
declare the exception thrown in a method, or to catch the thrown exception using a
try-catch clause.
Checked exceptions can encourage good programming practice, ensuring that all
errors are dealt with. However Anders Hejlsberg, chief C# language architect,
argues that they were to some extent an experiment in Java and that they haven't been
shown to be worthwhile except in small example programs.

One criticism is that checked exceptions encourage programmers to use an empty


catch block (catch (Exception e) {}), which silently eats exceptions, rather than letting
the exceptions propagate to a higher-level exception-handling routine. Another
criticism of checked exceptions is that a new implementation of a method may cause
unanticipated checked exceptions to be thrown, which is a contract-breaking change.
This can happen in methods implementing an interface that only declares limited
exceptions, or when the underlying implementation of a method changes. To allow for
such unanticipated exceptions to be thrown, some programmers simply declare the
method can throw any type of exception ("throws Exception"), which defeats the
purpose of checked exceptions. In some cases however, exception chaining can be
applied instead; re-throwing the exception in a wrapper exception. For example, if an
object is changed to access a database instead of a file, an SQLException could be
caught and re-thrown as an IOException, since the caller may not need to know the
inner workings of the object.

There are also differences between the two languages in treating the try-finally
statement. The finally is always executed, even if the try block contains control-
passing statements like throw or return. In Java, this may result in unexpected
behavior if the try block is left by a return statement with some value, and then the
finally block that is executed afterwards is also left by a return statement with a
different value. C# resolves this problem by prohibiting any control-passing
statements like return or break in the finally block.

A common reason for using try-finally blocks is to guard resource managing code,
thus guaranteeing the release of precious resources in the finally block. C# features
the using statement as a syntactic shorthand for this common scenario, in which the
Dispose() method of the object of the using is always called.

Finally blocks
Java allows flow of control to leave the finally block of a try statement, regardless of
the way it was entered. This can cause another control flow statement (such as return)
to be terminated mid-execution. For example:

int foo() {

try {

return 0;

} finally {

return 1;
}

In the above code, the return statement within try block causes control to leave it, and
therefore finally block is executed before the actual return happens. However, finally
block itself performs a return as well; thus, the original return that caused it to be
entered is not actually executed, and the above method returns 1 rather than 0.

C# does not allow any statements which allow control flow to leave the finally block
prematurely, except for throw. In particular, return is not allowed at all, goto is not
allowed if the target label is outside the finally block, and continue and break are not
allowed if the nearest enclosing loop is outside the finally block.

Lower level code


The Java Native Interface (JNI) feature allows Java programs to call non-Java code.
However, JNI does require the code being called to follow several conventions and
impose restrictions on types and names used. This means that an extra adaption layer
between legacy code and Java is often needed. This adaption code must be coded in a
non-Java language, often C or C++. Java Native Access (JNA) allows easier calling of
native code that only requires writing Java code, but comes at a performance cost.

In addition, third party libraries provide for Java-COM bridging, e.g. JACOB (free),
and J-Integra for COM (proprietary).

.NET Platform Invoke (P/Invoke) offers the same capability by allowing calls from
C# to what Microsoft refers to as unmanaged code. Through metadata attributes the
programmer can control exactly how the parameters and results are marshalled, thus
avoiding the need for extra adaption code. P/Invoke allows almost complete access to
procedural APIs (such as Win32 or POSIX), but limited access to C++ class libraries.

In addition, .NET Framework also provides a .NET-COM bridge, allowing access to


COM components as if they were native .NET objects.

C# also allows the programmer to disable the normal type-checking and other safety
features of the CLR, which then enables the use of pointer variables. When using this
feature, the programmer must mark the code using the unsafe keyword. JNI, P/Invoke,
and "unsafe" code are equally risky features, exposing possible security holes and
application instability. An advantage of unsafe, managed code over P/Invoke or JNI is
that it allows the programmer to continue to work in the familiar C# environment to
accomplish some tasks that otherwise would require calling out to unmanaged code.
An assembly (program or library) using unsafe code must be compiled with a special
switch and will be marked as such. This enables runtime environments to take special
precautions before executing potentially harmful code.
Runtime environments
Content
Introduction
Language history and evolution
Introduction
Java (the programming language) is designed to execute on the Java platform via the
Java Runtime Environment (JRE). The Java platform includes the Java Virtual
Machine (JVM) as well as a common set of libraries. The JRE was originally
designed to support interpreted execution with final compilation as an option. Most
JRE environments execute fully or at least partially compiled, possibly with adaptive
optimization. The Java compiler produces Java bytecode. Upon execution the
bytecode is loaded by the Java runtime and either interpreted directly or compiled to
machine instructions and then executed.

Further information: Java Runtime Environment

C# is designed to execute on the Common Language Runtime (CLR). The CLR is


designed to execute fully compiled code. The C# compiler produces Common
Intermediate Language instructions. Upon execution the runtime loads this code and
compiles to machine instructions on the target architecture.

Language history and evolution


Java
Java is older than C# and has built up a large and highly active user base, becoming
the lingua franca in many modern branches of computer science, particularly areas
which involve networking Java dominates programming courses at high school and
college level in the United States, and there are currently more Java than C# books.
Java's maturity and popularity have ensured more third party Java API and libraries
(many of them open source) than C#.

An occasionally voiced criticism of the Java language is that it evolves slowly,


lacking some features which make fashionable programming patterns and
methodologies easier. Some critics suggest that the designers of C# may pander too
quickly to current trends in programming, thus lacking focus and simplicity Java's
designers seem to have taken a more conservative stand on adding major new features
to their language syntax than other current languages, perhapsnot wanting to tie the
language too tightly with trends which may prove to be dead ends.

These trends have been broken with the Java 5.0 release, which introduced several
new major language features: a foreach construct, autoboxing, methods with variable
number of parameters (varargs), enumerated types, generic types, and annotations.
With the exception of Generics, C# included all these features from its beginning,
some under different names. Proposals and specifications for the new features had
been worked on in the Java community for considerable time before they were
introduced. Indeed, some had been in gestation since before C#'s initial release (e.g.,
work on Generics formally began in May 1999) such was the Java community's
conservatism at that time.

Problem-specific language additions to Java have been considered and, for now at
least, rejected. This approach, along with a number of other new languages and
technologies that address themselves specifically towards current programming
trends, has sparked a renewed debate within the Java camp about the future direction
of the Java language and whether its 'conservative evolution' is right.

As of 2008 debate continued over the inclusion of closures and properties into the
language syntax for Java 7.

C#

By contrast, C# is a relatively new language. Microsoft has studied existing languages


such as Java and Object Pascal, and has changed some aspects of the language and
runtime environment in response to perceived failures and difficulties with its
predecessors. C# accommodates constructs more commonly found in languages such
as C++, Delphi (the design of which was Anders Hejlsberg's principal job when he
was at Borland), and, in recent C# versions, borrows from dynamic scripting
languages such as Ruby and Python.

C# 3.0 adds SQL-like language integrated queries suited for querying data from
collections, databases or XML documents, building upon general-purpose language
features, including lambda expressions and extension methods, to allow queries to be
expressed and optimized for user types.

Before creating C#, Microsoft implemented a modified Java environment, called J++,
adding new features in a manner which was in direct contravention to the standards
and conventions ensuring the platform neutrality which lies at the heart of Java. This
violated the license agreement Microsoft had signed, requiring that standards and
specifications be strictly adhered to in return for using the Java name and brand logos.
Sun Microsystems sued, and in settling the suit, Microsoft agreed to discontinue J++.
(The settlement allowed other existing Java-using Microsoft products to continue such
use for seven years.) With the release of the .NET framework (and C#), the project
was revived in the form of J#.

Java virtual machine


Content
Introduction
List of Java virtual machines
List of Java APIs
List of JVM languages
Java version history

Introduction
A JVM can also implement programming languages other than Java. For example,
Ada source code can be compiled to Java byte code, which may then be executed by a
JVM. JVMs can also be released by other companies besides Sun (the developer of
Java) — JVMs using the "Java" trademark may be developed by other companies as
long as they adhere to the JVM specification published by Sun (and related
contractual obligations).

Java was conceived keeping in mind the concept of WORA: "write once and run
anywhere". This is possible using the Java Virtual Machine. The JVM is the
environment in which java programs execute. It is software that is implemented on
top of real hardware and of standard operating-systems.
JVM is a crucial component of the Java Platform, and because JVMs are available for
many hardware and software platforms, Java can be both middleware and a platform
in its own right[clarification needed] — hence the trademark write once, run
anywhere. The use of the same byte code for all platforms allows Java to be described
as "compile once, run anywhere", as opposed to "write once, compile anywhere",
which describes cross-platform compiled languages. A JVM also enables such
features as automated exception handling, which provides "root-cause" debugging
information for every software error (exception), independent of the source code.

A JVM is distributed along with a set of standard class libraries that implement the
Java API (Application Programming Interface). Appropriate APIs bundled together
form the Java Runtime Environment (JRE).

List of Java virtual machines


This article provides non-exhaustive lists of Java SE Java virtual machines (JVMs).
It does not include a large number of Java ME vendors. Note that Java EE runs on the
standard Java SE JVM but that some vendors specialize in providing a modified JVM
optimized for Java EE applications. A large amount of Java development work takes
place on Windows, Solaris and Linux, primarily with the Sun JVMs. Note the further
complication of different 32-bit/64-bit varieties.

Proprietary implementations
• Azul VM a segmented Java Virtual Machine based on a proprietary chip
architecture optimized to run pure Java. The HW backend allows for 54 cores
and Terabytes of memory, with no garbage collection costs.
• CEE-J is a clean room implementation of Sun's Java technology, Skelmir is
not a licensee of Sun.
• Excelsior JET (with AOT compiler)
• Hewlett-Packard, Java for HP-UX, OpenVMS, Tru64 and Reliant (Tandem)
UNIX platforms
• J9 (IBM), for AIX, Linux, MVS, OS/400, Pocket PC, z/OS
• Apogee provides embedded Java using IBM J9 and Apache Harmony Class
Library for X86, ARM, MIPS, PowerPC running on Linux, LynxOS, WinCE.
• JBed, (Esmertec) is an embedded Java with multimedia capabilities
• JamaicaVM, (aicas) is a hard real-time Java VM for embedded systems
• JBlend, (Aplix) is a Java ME implementation
• JRockit (originally from Appeal Virtual Machines) acquired by Oracle for
Linux, Windows and Solaris
• Mac OS Runtime for Java (MRJ)
• MicroJvm (IS2T - Industrial Smart Software Technology) Wide range of
virtual machines dedicated to embedded systems (including hard real-time
constrained systems), ARM7, ARM9, AVR, AVR32, PPC, MIPS, ...
• Microsoft Java Virtual Machine (discontinued in 2001)
• OJVM (also known as "JServer") from Oracle Corporation
• PERC (Aonix/Atego) is a real time Java for embedded
• SAPJVM (SAP) is a licensed and modified SUN JVM ported to all supported
platforms of SAP NetWeaver, started as Java 5, in the meantime Java 6
compatible (Windows i386, x64, IA-64; Linux x86, IA-64, PowerPC; AIX
PowerPC; HP-UX SPARC IA-64; Solaris SPARC x86-64; i5/OS PpwerPC)

Lesser-known proprietary Java virtual machines


• Blackdown Java was a licensed port to Linux of the reference SunSoft
implementation. It was discontinued in 2007, after OpenJDK became
available.
• C virtual machine (CVM, from Sun), supports C
• Gemstone - modified for Java EE features (application DBMS)
• Golden Code Development (EComStation and OS/2 port of Java RTE and
SDK for Java SE v1.4.1_07)
• Intent (Tao Group)
• Novell, India.
• NSIcom CrE-ME
• HP ChaiVM and MicrochaiVM

Free and open source implementations


• AegisVM
• Apache Harmony
• CACAO
• HotSpot
• IcedTea
• IKVM.NET
• Jamiga
• JamVM
• Jaos
• Jato VM
• JC
• Jelatine JVM
• JESSICA (Java-Enabled Single-System-Image Computing Architecture)
• Jikes RVM
• JNode (operating system)
• JOP (Hardware implementation of the JVM)
• Juice
• Jupiter
• JX (operating system)
• Kaffe
• leJOS
• Maxine (meta-circular JVM being developed by SUN)
• Mika VM
• Mysaifu (Windows CE / Windows Mobile)
• NanoVM
• SableVM
• Squawk virtual machine (for embedded system and small devices)
• SuperWaba
• TakaTuka (for wireless sensor network devices)
• TinyVM
• VMkit of Low Level Virtual Machine
• VM02 a Java-compatible environment for the Apple II series of computers.
• Wonka VM
• Xam
• miniMV (from UABC-Tij for embedded systems and Wireles Sensor network
devices)

List of Java APIs

There are three types of Java Programming Language Application Programming


Interfaces (APIs) :

• the official core Java API, contained in the JDK or JRE, of one of the editions
of the Java Platform. The three editions of the Java Platform are Java ME
(Mobile edition), Java SE (Standard edition), and Java EE (Enterprise edition).
• optional official APIs that can be downloaded separately. The specification of
these APIs are defined according to a Java Specification Request (JSR), and
sometimes some of these APIs are later included in the core APIs of the
platform (the most notable example of this kind is Swing).
• unofficial APIs, developed by third parties, but not related to any JSRs.

Third-parties can freely implement any JSR specifications for an official API (even
for the core API of the language), providing that they conform to the Technology
Compatibility Kit (TCK) for this JSR (the TCK is a suite of tests that checks
conformance of implementations for a JSR). The result of this freedom is that many
official APIs have more implementations than the Sun's Reference implementation
(RI).

The following is a partial list of Application Programming Interfaces (APIs) for the
Java Programming Language.

Official APIs

Java Platform, Standard Edition (Java SE)

Bundled APIs (part of standard download)


Package(s) that contain the Description and Version
Name Acronym
API History
Abstract AWT java.awt First released with version
Window 1.0.
Toolkit
Collection of standard
data structures like Lists,
Java Collections
JCF java.util Maps, Queues, Stacks.
Framework
Included in J2SE 1.2 and
later.
Included in J2SE 1.2 and
Swing javax.swing
later.
Accessibility
java.awt.datatransfer
Drag n Drop
java.awt.dnd
javax.imageio
Image I/O
javax.imageio.*
javax.sound.midi
javax.sound.midi.spi
Sound
javax.sound.sampled
javax.sound.sampled.spi
java.rmi
API for defining RPC
java.rmi.dgc
Remote Method interfaces using Java
RMI java.rmi.registry
Invocation objects and object
java.rmi.server
methods.
java.rmi.activation
Java Database java.sql
JDBC
Connectivity javax.sql
Included as part of J2SE
Java javax.crypto
1.4 and later. Available as
Cryptography JCE javax.crypto.interfaces
an optional package to
Extension javax.crypto.spec
versions 1.2 and 1.3.
Java
Included in J2SE 1.4 and
Authentication
later, previously released
and JAAS javax.security.auth
as an optional package
Authorization
with version 1.3.
Service
A set of packages that
enable secure Internet
communications. Included
Java Secure javax.net
as part of J2SE 1.4 and
Socket JSSE javax.net.ssl
later, JSSE 1.0.3 is an
Extension java.security.cert
optional package to the
Java 2 SDK, versions 1.2
and 1.3.
Java Native JNI Allows Java code running
Interface in the Java virtual
machine (JVM) to call and
be called[1] by native
applications (programs
specific to a hardware and
operating system
platform) and libraries
written in other languages,
such as C, C++ and
assembly.
A technology that supplies
javax.management
tools for managing and
javax.management.loading
monitoring applications,
javax.management.modelmbean
system objects, devices
Java javax.management.monitor
(e.g. printers) and service
Management JMX javax.management.openmbean
oriented networks.
Extensions javax.management.relation
Included as part of J2SE
javax.management.remote
1.5 and later, was an
javax.management.remote.rmi
optional package prior to
javax.management.timer
this.

Optional APIs (downloaded separately)


An API which provides a set of
interfaces that support a high-
[[Acronym and
Name level programming model
initialism|Acrony
allowing to manipulate images
easily.
Java
Communications JCA
API
A specification of Java object
Java Data Objects JDO
persistence.
A full-featured, extensible help
system that enables you to
JavaHelp incorporate online help in applets,
components, applications,
operating systems, and devices.
An API that enables audio, video
Java Media and other time-based media to be
JMF
Framework added to Java applications and
applets.
Java Naming and
JNDI An API for directory services.
Directory Interface
This API allows for speech
Java Speech API JSAPI
synthesis
available
Java 3D J3D A scene graph-based 3D API.
here
available
Java OpenGL JOGL A wrapper library for OpenGL.
here
A framework to build mail and available
Java Mail (none)
messaging applications here
Java USB for A USB communication of Java available
(none)
Windows applications here
Java Platform, Enterprise Edition (Java EE)

Bundled APIs (part of standard download)


Name Acronym Java package(s) that contain the API
Java Message Service JMS
JavaServer Faces JSF javax.faces

Optional APIs (downloaded separately)


Name Acronym Available from
Java API for XML-Based RPC JAX-RPC available here

Java Platform, Micro Edition (Java ME)

Name Acronym Available from


Connected Limited Device Reference implementation is available
CLDC
Configuration here
Java Telephony API available here

Unofficial APIs (Released by third parties)


This list is very incomplete, as the number of APIs available for the Java platform is
overwhelming.

• Eclipse
• Netbeans

Compression

• LZMA SDK, the Java implementation of the SDK used by the popular 7-Zip
file archive software (available here)

Development assistance

• Lady4j. Programming assistant and application server issue solver. (available


here)
• Cobra HTML parser and renderer library.

Numerical analysis

• JScience

Real-time libraries

• Javolution

Rendering libraries
• Flying Saucer XML, XHTML, and CSS 2.1 rendering library.
• Cobra HTML parser and renderer library.

Windowing libraries

• Standard Widget Toolkit (SWT)

List of JVM languages


This list of JVM Languages comprises computer programming languages that are
used to produce software that runs on the Java Virtual Machine (JVM). Some of these
languages are interpreted by a Java program, and some are compiled to Java bytecode
and JITted during execution as regular Java programs to improve performance.

The JVM was initially designed to support only the Java programming language.
However, as time passed, more and more languages were designed to run on the Java
platform.

High-profile languages
Apart from the Java language itself, The most common or well-known JVM
languages are:

• AspectJ, an aspect-oriented extension of Java


• ColdFusion, a scripting language compiled to Java
• Clojure, a functional Lisp dialect
• Groovy, a scripting language
• JavaFX Script, a scripting language targeting the Rich Internet Application
domain
• JRuby, an implementation of Ruby
• Jython, an implementation of Python
• Rhino, an implementation of JavaScript
• Scala, an object-oriented and functional programming language[1]

JVM languages

JVM implementations of existing languages


Language Java implementations
Ada JGNAT
AWK Jawk
C C to Java Virtual Machine compilers
Cobol Veryant isCobol
ColdFusion Adobe ColdFusion
Railo
Open BlueDragon
Armed Bear Common Lisp
Common Lisp CLforJava
Jatha (Common LISP)
Component Pascal Gardens Point Component Pascal
Erlang
Forth myForth
JavaScript Rhino
jLogo
LOGO
XLogo
Kahlua
Lua
Jill
Oberon-2 Canterbury Oberon-2 for JVM
Objective Caml (OCaml) OCaml-Java
Pascal Canterbury Pascal for JVM
IBM WebSphere sMash PHP (P8)
PHP
Caucho Quercus
Python Jython
Rexx IBM NetRexx
Ruby JRuby
Bigloo
Kawa
Scheme
SISC
JScheme
Tcl Jacl

New JVM languages


• Alef++, a programming language inspired by Perl and Lisp.
• AspectJ, an aspect-oriented extension for the Java programming language.
• BeanShell, a scripting language whose syntax is close to Java.
• Mirah, a customizable programming language featuring type inference and a
heavily Ruby-inspired syntax.
• The E programming language has an implementation on the JVM.
• Fantom, a language built from the ground-up to be portable across the JVM
and the .NET CLR.
• Flow Java.
• Fortress, a language designed by Sun as a successor to Fortran, mainly for
writing parallel scientific computations
• Frink, a language that tracks units of measure through calculations.
• Hecl
• Ioke, a prototype-based language somewhat reminiscent of Io, with
similarities to Ruby, Lisp and Smalltalk.
• Jaskell, Haskell inspired scripting language
• Join Java, a extends Java with the Join Semantics of the Join Calculus.
• Jelly (Programming Language)
• Joy
• Judoscript.
• N.A.M.E. Basic.
• NetLogo, a multi-agent programming language.
• Nice.
• Noop, a language built with testability as a major focus.
• ObjectScript
• Pizza, a superset of Java with function pointers and algebraic data types.
• Pnuts.
• CAL, a Haskell-inspired functional programming language.
• Sleep, a procedural scripting language inspired by Perl and Objective-C.
• The V programming language has an implementation on the JVM.
• X10, a IBM language designed for high-performance heteregenous clusters
and parallel scientific computations. Syntax of X10 is highly based of Java,
and optimizing compiler targets JVM or C++.
• Yeti, a ML style functional programming language, that runs on the JVM

Java version history


Java Web Start, first introduced for J2SE 1.3, allows provision of applications over
the Web by clicking a desktop icon or a link on a website.

The Java language has undergone several changes since JDK 1.0 as well as numerous
additions of classes and packages to the standard library. 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.

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

Some programs allow conversion of Java programs from one version of the Java
Platform to an older one (for example Java 5.0 backported to 1.4) (see Java
backporting tools).

JDK 1.0 (January 23, 1996)

Codename Oak. Initial release

JDK 1.1 (February 19, 1997)

Major additions included:

• an extensive retooling of the AWT event model


• inner classes added to the language
• JavaBeans
• JDBC
• RMI
• reflection which supported Introspection only, no modification at runtime was
possible.

J2SE 1.2 (December 8, 1998)

Codename Playground. This and subsequent releases through J2SE 5.0 were
rebranded retrospectively 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:[3]

• strictfp keyword
• the Swing graphical API was integrated into the core classes
• Sun's JVM was equipped with a JIT compiler for the first time
• Java Plug-in
• Java IDL, an IDL implementation for CORBA interoperability
• Collections framework

J2SE 1.3 (May 8, 2000)

Codename Kestrel. The most notable changes were:

• HotSpot JVM included (the HotSpot JVM was first released in April, 1999 for
the J2SE 1.2 JVM)
• RMI was modified to support optional compatibility with CORBA
• JavaSound
• Java Naming and Directory Interface (JNDI) included in core libraries
(previously available as an extension)
• Java Platform Debugger Architecture (JPDA)
• Synthetic proxy classes

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:

• assert keyword (Specified in JSR 41.)


• regular expressions modeled after Perl regular expressions
• exception chaining allows an exception to encapsulate original lower-level
exception
• Internet Protocol version 6 (IPv6) support
• non-blocking NIO (New Input/Output) (Specified in JSR 51.)
• logging API (Specified in JSR 47.)
• image I/O API for reading and writing images in formats like JPEG and PNG
• integrated XML parser and XSLT processor (JAXP) (Specified in JSR 5 and
JSR 63.)
• integrated security and cryptography extensions (JCE, JSSE, JAAS)
• Java Web Start included (Java Web Start was first released in March, 2001 for
J2SE 1.3) (Specified in JSR 56.)

J2SE 5.0 (September 30, 2004)

Codename Tiger. Originally numbered 1.5, which is still used as the internal version
number. This version was developed under JSR 176.

J2SE 5.0 entered its end-of-life on April 8, 2008 and is no longer supported by Sun as
of November 3, 2009.

Tiger added a number of significant new language features:

• Generics: Provides compile-time (static) type safety for collections and


eliminates the need for most typecasts (type conversion). (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.)
• Swing: New skinnable look and feel, called synth.
• 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)). 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, or alternatively the calling code
can pass an array of that type.
• Enhanced for each 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<Widget> 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.)
• Fix the previously broken semantics of the Java Memory Model, which
defines how threads interact through memory.
• Automatic stub generation for RMI objects.
• static imports
• Java 5 is the last release of Java to officially support the Microsoft Windows
9x line (Windows 95, Windows 98, Windows ME). Unofficially, Java SE 6
Update 7 (1.6.0.7) is the last version of Java to be shown working on this
family of operating systems.
• The concurrency utilities in package java.util.concurrent.
• Scanner class for parsing data from various input streams and buffers.

Java SE 6 (December 11, 2006)

Codename Mustang. As of this version, Sun replaced the name "J2SE" with Java SE
and dropped the ".0" from the version number. Internal numbering for developers
remains 1.6.0. This version was developed under JSR 270.

During the development phase, new builds including enhancements and bug fixes
were released approximately weekly. Beta versions were released in February and
June 2006, leading up to a final release that occurred on December 11, 2006. The
current revision is Update 21 which was released in July 2010.

Major changes included in this version:

• Support for older Win9x versions dropped. Unofficially Java 6 Update 7 is the
last release of Java shown to work on these versions of Windows. This is
believed to be due to the major changes in Update 10.
• Scripting Language Support (JSR 223): Generic API for tight integration with
scripting languages, and built-in Mozilla JavaScript Rhino integration
• Dramatic performance improvements for the core platform, and Swing.
• Improved Web Service support through JAX-WS (JSR 224)
• JDBC 4.0 support (JSR 221).
• Java Compiler API (JSR 199): an API allowing a Java program to select and
invoke a Java Compiler programmatically.
• Upgrade of JAXB to version 2.0: Including integration of a StAX parser.
• Support for pluggable annotations (JSR 269)
• Many GUI improvements, such as integration of SwingWorker in the API,
table sorting and filtering, and true Swing double-buffering (eliminating the
gray-area effect).
• JVM improvements include: synchronization and compiler performance
optimizations, new algorithms and upgrades to existing garbage collection
algorithms, and application start-up performance.

Java SE 6 Update 10

Java SE 6 Update 10 (previously known as Java SE 6 Update N) was released


October 15, 2008 and while it does not change any public API, is meant as a major
enhancement in terms of end-user usability. The release version is currently available
for download.
Major changes for this update include:

• Java Deployment Toolkit, a set of JavaScript functions to ease the deployment


of applets and Java Web Start applications.
• Java Kernel, a small installer including only the most commonly used JRE
classes. Other packages are downloaded when needed.
• Enhanced updater.
• Enhanced versioning and pack200 support: server-side support is no longer
required.
• Java Quick Starter, to improve cold start-up time.
• Improved performance of Java2D graphics primitives on Windows, using
Direct3D and hardware acceleration.
• A new Swing look and feel called Nimbus and based on synth.
• Next-Generation Java Plug-In: applets now run in a separate process and
support many features of Web Start applications.

Java SE 6 Update 11

Released December 3, 2008

Java SE 6 Update 12

This release includes the 64-bit Java Plug-In (for 64-bit browsers only), Windows
Server 2008 support, and performance improvements of Java and JavaFX
applications.

Java SE 6 Update 14

Java SE 6 Update 14 (6u14) was released as of May 28, 2009.

This release includes extensive performance updates to the HotSpot JIT compiler,
compressed pointers for 64-bit machines, as well as support for the G1 (Garbage
First) low pause garbage collector.

The -XX:+DoEscapeAnalysis option directs the HotSpot JIT compiler to use escape
analysis to determine if local objects can be allocated on the stack instead of the heap.

Some developers have noticed an issue introduced in this release which causes
debuggers to miss breakpoints seemingly randomly. Sun has a corresponding bug,
which is tracking the issue. The workaround applies to the Client and Server VMs.
Using the -XX:+UseParallelGC option will prevent the failure. Another workaround
is to roll back to update 13, or to upgrade to update 16.

Java SE 6 Update 16

Released August 11, 2009. Fixes the issue introduced in update 14 which caused
debuggers to miss breakpoints.

Java SE 6 Update 17
Released November 4, 2009.

Java SE 6 Update 18

Released January 13, 2010.

Java SE 6 Update 19

Released March 30, 2010.

Java SE 6 Update 20

Released April 15, 2010.

Java SE 6 Update 21

Released July 7, 2010.

Java SE 7.0

Java 7 (codename Dolphin) is an upcoming major update to Java. The Dolphin


Project began in August 2006 and is tentatively scheduled for release in late 2010.
The development period is organized into ten milestones; as of August 2010,
milestone 10 is in progress. Multiple builds, which generally include enhancements
and bug fixes, are released per milestone. The Feature list at the Open JDK 7 project
lists many of the expected feature changes.

The expected feature additions for Java 7 are:

• Replacement of the existing concurrent low-pause garbage collector (also


called CMS or Concurrent Mark-Sweep collector) with the G1 garbage
collector, which should enhance performance
• JVM support for dynamic languages, following the prototyping work currently
done on the Multi Language Virtual Machine
• A new library for parallel computing on multi-core processors
• Modularization of the JDK under Project Jigsaw
• Compressed 64-bit pointers
• Extended support for Java Annotations under JSR 308
• Language-level support for lambda expressions (officially, lambda
expressions; unofficially, closures) under Project Lambda. There was an
ongoing debate in the Java community on whether to add support for lambda
expressions. Sun later declared that lambda expressions would be included in
Java 7 and asked for community input to refine the feature.

• Language changes under Project Coin. The features accepted for inclusion in
Project Coin are:

• Strings in switch

• Automatic resource management


• Improved Type Inference for Generic Instance Creation

• Simplified Varargs Method Invocation

• Better integral literals allowing for underscores as digit


separators

• Language-level support for Collections

• Concurrency utilities under JSR 166


• New file I/O library to enhance platform independence and add support for
metadata and symbolic links. The new packages are java.nio.file and
java.nio.file.attribute
• Library-level support for Elliptic curve cryptography algorithms
• An XRender pipeline for Java 2D, which improves handling of features
specific to modern GPUs
• New platform APIs for the graphics features originally planned for release in
Java version 6u10
• Enhanced library-level support for new network protocols, including SCTP
and Sockets Direct Protocol
• Upstream updates to XML and Unicode

Type of java programs


Applet
Servlet
Packages
JavaServer Pages
Swing application
Generics
Class library

Applet
Java applets are programs that are embedded in other applications, typically in a Web
page displayed in a Web browser.

// Hello.java

import javax.swing.JApplet;

import java.awt.Graphics;

public class Hello extends JApplet {


public void paintComponent(Graphics g) {

g.drawString("Hello, world!", 65, 95);

The import statements direct the Java compiler to include the javax.swing.JApplet
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. JApplet)
instead of the fully qualified class name (i.e. javax.swing.JApplet).

The Hello class extends (subclasses) the JApplet (Java Applet) class; the JApplet
class provides the framework for the host application to display and control the
lifecycle of the applet. The JApplet class is a JComponent (Java Graphical
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 paintComponent(Graphics) method inherited from the
Container superclass to provide the code to display the applet. The paintComponent()
method is passed a Graphics object that contains the graphic context used to display
the applet. The paintComponent() method calls the graphic context
drawString(String, int, int) method to display the "Hello, world!" string at a pixel
offset of (65, 95) from the upper-left corner in the applet's display.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd">

<!-- Hello.html -->

<html>

<head>

<title>Hello World Applet</title>

</head>

<body>

<applet code="Hello" width="200" height="200">

</applet>

</body>

</html>
An applet is placed in an HTML document using the <applet> HTML element. The
applet tag has three attributes set: code="Hello" specifies the name of the JApplet
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. However, the
applet tag is deprecated, so the object tag is preferred where supported.

The host application, typically a Web browser, instantiates the Hello applet and
creates an AppletContext for the applet. Once the applet has initialized itself, it is
added to the AWT display hierarchy. The paintComponent() method is called by the
AWT event dispatching thread whenever the display needs the applet to draw itself.

Servelt
Java Servlet technology provides Web developers with a simple, consistent
mechanism for extending the functionality of a Web server and for accessing existing
business systems. Servlets are server-side Java EE components that generate
responses (typically HTML pages) to requests (typically HTTP requests) from clients.
A servlet can almost be thought of as an applet that runs on the server side—without a
face.

// Hello.java

import java.io.*;

import javax.servlet.*;

public class Hello extends GenericServlet {

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

final PrintWriter pw = response.getWriter();

pw.println("Hello, world!");

pw.close();

The import statements direct the Java compiler to include all of the public classes and
interfaces from the java.io 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.

Packages
A Java package is a mechanism for organizing Java classes into namespaces similar to
the modules of Modula. Java packages can be stored in compressed files called JAR
files, allowing classes to download faster as a group rather than one at a time.
Programmers also typically use packages to organize classes belonging to the same
category or providing similar functionality.

• A package provides a unique namespace for the types it contains.


• Classes in the same package can access each other's package-access members.

JavaServer Pages
JavaServer Pages (JSP) are server-side Java EE components that generate responses,
typically HTML pages, to HTTP requests from clients. JSPs embed Java code in an
HTML page by using the special delimiters <% and %>. A JSP is compiled to a Java
servlet, a Java application in its own right, the first time it is accessed. After that, the
generated servlet creates the response.

Swing application
Swing is a graphical user interface library for the Java SE platform. It is possible to
specify a different look and feel through the pluggable look and feel system of Swing.
Clones of Windows, GTK+ and Motif are supplied by Sun. Apple also provides an
Aqua look and feel for Mac OS X. Where prior implementations of these looks and
feels may have been considered lacking, Swing in Java SE 6 addresses this problem
by using more native GUI widget drawing routines of the underlying platforms.
This example Swing application creates a single window with "Hello, world!" inside:

// Hello.java (Java SE 5)

import javax.swing.*;

public class Hello extends JFrame {

public Hello() {

super("hello");

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

add(new JLabel("Hello, world!"));

pack();

public static void main(String[] args) {

new Hello().setVisible(true);

The first import includes all of the public classes and interfaces from the javax.swing
package.

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

The Hello() constructor initializes the frame by first calling the superclass constructor,
passing the parameter "hello", which is used as the window's title. It then calls the
setDefaultCloseOperation(int) method inherited from JFrame to set the default
operation when the close control on the title bar is selected to
WindowConstants.EXIT_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 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 lay out 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.
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.

Generics
In 2004 generics were added to the Java language, as part of J2SE 5.0. Prior to the
introduction of generics, each variable declaration had to be of a specific type. For
container classes, for example, this is a problem because there is no easy way to
create a container that accepts only specific types of objects. Either the container
operates on all subtypes of a class or interface, usually Object, or a different container
class has to be created for each contained class. Generics allow compile-time type
checking without having to create a large number of container classes, each
containing almost identical code.

Class library
Java Platform and Class libraries diagram

• Java libraries are the compiled bytecodes of source code developed by the JRE
implementor to support application development in Java. Examples of these
libraries are:
o The core libraries, which include:
 Collection libraries that implement data structures such as lists,
dictionaries, trees and sets
 XML Processing (Parsing, Transforming, Validating) libraries
 Security
 Internationalization and localization libraries
o The integration libraries, which allow the application writer to
communicate with external systems. These libraries include:
 The Java Database Connectivity (JDBC) API for database
access
 Java Naming and Directory Interface (JNDI) for lookup and
discovery
 RMI and CORBA for distributed application development
 JMX for managing and monitoring applications
o User interface libraries, which include:
 The (heavyweight, or native) Abstract Window Toolkit (AWT),
which provides GUI components, the means for laying out
those components and the means for handling events from
those components
 The (lightweight) Swing libraries, which are built on AWT but
provide (non-native) implementations of the AWT widgetry
 APIs for audio capture, processing, and playback
• A platform dependent implementation of Java Virtual Machine (JVM) that is
the means by which the byte codes of the Java libraries and third party
applications are executed
• Plugins, which enable applets to be run in Web browsers
• Java Web Start, which allows Java applications to be efficiently distributed to
end-users across the Internet
• Licensing and documentation.

BlueJ
Content
Introduction
History
Features
Pedagogy
Limitations
Current Release

Introduction
BlueJ

Screenshot of BlueJ
Original author(s) Michael Kölling
Developer(s) BlueJ Team
3.0.2 / August 25, 2010; 19 days
Stable release
ago
Development status Active
Written in Java
Operating system Cross-platform
Platform Java
Available in Multilingual
Integrated development
Type
environment
License GNU General Public License
Website http://bluej.org/

BlueJ is an Integrated Development Environment for the Java programming


language, developed mainly for educational purposes, but also suitable for small-scale
software development.

BlueJ was developed to support the learning and teaching of object-oriented


programming, and its design differs from other development environments as a result.
The main screen graphically shows the class structure of an application under
development (in a UML-like diagram), and objects can be interactively created and
tested. This interaction facility, combined with a clean, simple user interface, allows
easy experimentation with objects under development. Object-oriented concepts
(classes, objects, communication through method calls) are represented visually and
in its interaction design in the interface.

History
The development of BlueJ was started in 1999 by Michael Kölling and John
Rosenberg at Monash University, as a successor to the Blue system. Blue was an
integrated system with its own programming language and environment. BlueJ
implements the Blue environment design for the Java Programming Language.

BlueJ is currently being maintained by a joint team at the University of Kent,


Canterbury, England - where Kölling now lectures, and La Trobe University in
Melbourne, Australia.

In March 2009, the BlueJ project became Free and Open Source Software , and
licensed under GNU GPL with Classpath exception .

Features
The features of BlueJ are designed as an aid to learning object-oriented programming
concepts, as well as an aid to program development itself. As a result, some
commonly available tools differ from other environments, some tools are absent, and
other tools are provided not commonly found in development environments. The
features include:

• Representation of Object orientation - the concepts of classes and objects are


presented in a visual manner. Both have distinct visual representations, and it
is easy to demonstrate that code is associated directly with a class, that an
object has a class type, and that the class type of an object directly determines
its available methods and fields as well as its behavior.

• Simplicity of the interface - The user interface is simpler than in full-scale


professional environments, and thus easier to learn. The goal is for the
development environment to "disappear". Students should be able to
concentrate on the programming task without the need to struggle with the
environment.

• Object interaction - Programmers are able to experiment with objects by


creating objects on the "Object Bench" and calling individual methods
interactively (including passing of parameters and inspection of results). This
is intended to encourage early and frequent testing, and experimentation to
help understand the programming model.

• The "Code Pad" - The code pad is a tool that instantly evaluates arbitrary Java
expressions and statements.

• Regression testing - BlueJ supports regression testing via an integration of


JUnit. In addition to manual writing of JUnit classes, interactive tests can be
recorded and JUnit test cases can be automatically created from these
recordings.

• Group work support - BlueJ provides simple support for group work via a
subset of CVS and Subversion functionality.

• Java ME support - Java ME (Micro Edition) projects can be developed and


deployed from BlueJ.

• Flexible extension system - Extensions (a.k.a. Plug-Ins) can be developed


using a public extensions API to extend the functionality of the core
environment.

• Jar files and applets - Creation of executable jar files and applets is built into
the system.

• Translations - The BlueJ system interface has been translated into at least 14
different natural languages.

The visual interaction features of BlueJ were designed to allow one to delay the
introduction of certain programming concepts considered difficult or problematic by
educators. These include:

• Syntax such as public static void main(String[] args) - which requires


unnecessarily introducing the keywords public and static, as well as method
arguments and arrays. BlueJ allows arbitrary classes to be instantiated and
arbitrary methods to be invoked interactively.

• Program input/output. In BlueJ both the parameter values for and the return
values from method calls can be entered/inspected directly, so there is no need
for students to deal with terminal I/O or write graphical user interfaces when
they are still struggling with the basic concepts of programming.

The program is a fully functional development tool, commonly used by schools,


colleges, and universities.
Some of the features BlueJ pioneered in modern development environments, such as
interactive instantiation, direct object interaction, unit test recording, the editor
"navigation view", and scope highlighting, are generally useful for software
development, however, are not usually found in other development environments.
Some attempts were made to replicate some of these features: For example,
Microsoft's Visual Studio replicated BlueJ's object bench feature, however, it
remained somewhat obscure because it is not included in all versions of that
environment.

Pedagogy
The pedagogical approach represented in BlueJ is based on constructivism and
visualisation. Working with the BlueJ environment provides concrete experiences for
abstract concepts, such as the class/object relationship, object instantiation, method
calling, and parameter passing. These abstract concepts are traditionally hard to
understand for novices, and providing concrete representations of them is intended to
help the learning process. Visualisations of the processes and structures (such as
objects on the object bench, and object inspectors) support this process.

The goal of this approach is for beginners to more easily develop a consistent mental
model of object-oriented systems, their properties, and their execution.

Limitations
Although BlueJ is a useful tool for learning the basic concepts of Object-oriented
programming, its features are too limited to be used as a mature development tool for
a trained programmer. It misses some of the highly appreciated features of popular
IDEs (e.g. Eclipse and Netbeans) such as live code checking and error detection (by
means of continuous compilation), suggested corrections for warnings/errors, and
code folding.

Current Release
As of 13 September 2010, the latest stable release is BlueJ version 3.0.2. This version
provides vastly improved editor features such as code completion and scope
highlighting.

A book, Objects First with Java - a Practical Introduction Using BlueJ written by
David J. Barnes and Michael Kölling, is also available.

Object
Objects are key to understanding object-oriented technology. Look around right now
and you'll find many examples of real-world objects: your dog, your desk, your
television set, your bicycle.

Real-world objects share two characteristics: They all have state and behavior. Dogs
have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).
Bicycles also have state (current gear, current pedal cadence, current speed) and
behavior (changing gear, changing pedal cadence, applying brakes). Identifying the
state and behavior for real-world objects is a great way to begin thinking in terms of
object-oriented programming.

Take a minute right now to observe the real-world objects that are in your immediate
area. For each object that you see, ask yourself two questions: "What possible states
can this object be in?" and "What possible behavior can this object perform?". Make
sure to write down your observations. As you do, you'll notice that real-world objects
vary in complexity; your desktop lamp may have only two possible states (on and off)
and two possible behaviors (turn on, turn off), but your desktop radio might have
additional states (on, off, current volume, current station) and behavior (turn on, turn
off, increase volume, decrease volume, seek, scan, and tune). You may also notice
that some objects, in turn, will also contain other objects. These real-world
observations all translate into the world of object-oriented programming.

Software objects are conceptually similar to real-world objects: they too consist of
state and related behavior. An object stores its state in fields (variables in some
programming languages) and exposes its behavior through methods (functions in
some programming languages). Methods operate on an object's internal state and
serve as the primary mechanism for object-to-object communication. Hiding internal
state and requiring all interaction to be performed through an object's methods is
known as data encapsulation — a fundamental principle of object-oriented
programming.

Object initialization
In both C# and Java, an object's fields can be initialized either by variable initializers
(expressions that can be assigned to variables where they are defined) or by
constructors (special subroutines that are executed when an object is being created).
In addition, Java contains instance initializers, which are anonymous blocks of code
with no arguments that are run before the constructor is executed.

C# initializes object fields in the following order when creating an object:

1. Derived static fields


2. Derived static constructor
3. Derived instance fields
4. Base static fields
5. Base static constructor
6. Base instance fields
7. Base instance constructor
8. Derived instance constructor
Some of the above fields may not be applicable (e.g. if an object does not have static
fields). Derived fields are those that are defined in the object's direct class while base
fields is a term for the fields that are defined in one of the object's superclasses. Note
that an object representation in memory contains all fields defined in its class or any
of its superclasses, even if some fields in superclasses are defined as private.

It is guaranteed that any field initializers take effect before any constructors are called,
since both instance constructor of the object's class and its super classes are called
after field initializers are called. There is, however, a potential trap in object
initialization when a virtual method is called from a base constructor. The overridden
method in a subclass may reference a field that is defined in the subclass, but this field
may not been initialized because the cubclass' constructor that contains field
initialization is called after the constructor of its base class.

In Java, the order of initialization is as follows:

1. Invocation of another constructor (either of the object's class or of object's


superclass)
2. Instance variable initializers and instance initializers (in the order they appear
listed in source code)
3. The constructor body

Like in C#, a new object is created by calling a specific constructor. Within a


constructor, the first statement may be invocation of another constructor. If this is
omitted, the call to the super class' argument-less constructor is added implicitly by
the compiler. Otherwise, either another overloaded constructor of the object's class
can be called explicitly, or a superclass' constructor can be called. In the former case,
the called constructor will again call another constructor (either of the object's class or
its cubclass) and the chain sooner or later ends up at the call to one of the superclass'
constructor.

After another constructor is called (which causes direct invocation superclass'


constructor, and so forth, down to the Object class), instance variables defined in the
object's class are initialized. Even if there are no variable initializers explicitly defined
for some variables, these variables are initialized to default values. Note that instance
variables defined in superclasses are already initialized by this point, because they
were initialized by superclass' constructor when it was called (either by constructor's
code or by variables' initializers performed before constructor's code or implicitly to
default values). In Java, variable initializers are executed according to their textual
order in the source file.

Finally, the constructor body is executed. This ensures proper order of initialization,
i.e. the fields of a base class finish initialization before initialization of the fields of an
object class begins.

There are two main potential traps in Java's object initialization. First, variable
initializers are expressions that can contain method calls. Since methods can reference
any variable defined in the class, the method called in variable's initializer can
reference a variable that is defined below the variable being initialized. Since
initialization order corresponds to textual order of variable definitions, such a variable
would not be initialized to the value prescribed by its initializer and would contain the
default value. Another potential trap is when a method that is overridden in the
derived class is called in the base class' constructor, which can lead to behavior the
programmer would not expect when object of the derived class is created. According
to initialization order, the body of the base class' constructor is executed before
variable initializers are evaluated and before the body of the derived class' constructor
is executed. The overridden method called form the base class' constructor can
however reference variables defined in the derived class, but these are not yet
initialized to the values specified by their initializers or set in derived class'
constructor.

Class
In the real world, you'll often find many individual objects all of the same kind. There
may be thousands of other bicycles in existence, all of the same make and model.
Each bicycle was built from the same set of blueprints and therefore contains the same
components. In object-oriented terms, we say that your bicycle is an instance of the
class of objects known as bicycles. A class is the blueprint from which individual
objects are created. The syntax of the Java programming language will look new to
you, but the design of this class is based on the previous discussion of bicycle objects.
The fields cadence, speed, and gear represent the object's state, and the methods
(changeCadence, changeGear, speedUp etc.) define its interaction with the outside
world.

You may have noticed that the Bicycle class does not contain a main method. That's
because it's not a complete application; it's just the blueprint for bicycles that might be
used in an application. The responsibility of creating and using new Bicycle objects
belongs to some other class in your application.
Program (virtual calculator)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class SwingCalculator {
public static void main(String[] args) {
JFrame frame = new Calculator();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class Calculator extends JFrame {
private final Font BIGGER_FONT = new Font("monspaced",
Font.PLAIN, 20);
private JTextField textfield;
private boolean number = true;
private String equalOp = "=";
private CalculatorOp op = new CalculatorOp();

public Calculator() {
textfield = new JTextField("0", 12);
textfield.setHorizontalAlignment(JTextField.RIGHT);
textfield.setFont(BIGGER_FONT);

ActionListener numberListener = new NumberListener();


String buttonOrder = "1234567890 ";
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < buttonOrder.length(); i++) {
String key = buttonOrder.substring(i, i+1);
if (key.equals(" ")) {
buttonPanel.add(new JLabel(""));
} else {
JButton button = new JButton(key);
button.addActionListener(numberListener);
button.setFont(BIGGER_FONT);
buttonPanel.add(button);
}
}
ActionListener operatorListener = new OperatorListener();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 4, 4));
String[] opOrder = {"+", "-", "*", "/","=","C"};
for (int i = 0; i < opOrder.length; i++) {
JButton button = new JButton(opOrder[i]);
button.addActionListener(operatorListener);
button.setFont(BIGGER_FONT);
panel.add(button);
}
JPanel pan = new JPanel();
pan.setLayout(new BorderLayout(4, 4));
pan.add(textfield, BorderLayout.NORTH );
pan.add(buttonPanel , BorderLayout.CENTER);
pan.add(panel , BorderLayout.EAST );
this.setContentPane(pan);
this.pack();
this.setTitle("Calculator");
this.setResizable(false);
}
private void action() {
number = true;
textfield.setText("0");
equalOp = "=";
op.setTotal("0");
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (number) {
action();
textfield.setText("0");
} else {
number = true;
String displayText = textfield.getText();
if (equalOp.equals("=")) {
op.setTotal(displayText);
} else if (equalOp.equals("+")) {
op.add(displayText);
} else if (equalOp.equals("-")) {
op.subtract(displayText);
} else if (equalOp.equals("*")) {
op.multiply(displayText);
} else if (equalOp.equals("/")) {
op.divide(displayText);
}
textfield.setText("" + op.getTotalString());
equalOp = e.getActionCommand();
}
}
}
class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String digit = event.getActionCommand();
if (number) {
textfield.setText(digit);
number = false;
} else {
textfield.setText(textfield.getText() + digit);
}
}
}
public class CalculatorOp {

private int total;


public CalculatorOp() {
total = 0;
}
public String getTotalString() {
return ""+total;
}
public void setTotal(String n) {
total = convertToNumber(n);
}
public void add(String n) {
total += convertToNumber(n);
}
public void subtract(String n) {
total -= convertToNumber(n);
}
public void multiply(String n) {
total *= convertToNumber(n);
}
public void divide(String n) {
total /= convertToNumber(n);
}
private int convertToNumber(String n) {
return Integer.parseInt(n);
}
}
}
Program (ATM)

public class ATM{//name of the program

public static Scanner kbd;//Scanner kbd function

public static void main(String[] args) {// the main program with the word
void doesn't let anything out

String userAnswer = null;//declaring the string

Scanner kbd = new Scanner(System.in); // declaring the function

double accountbalance = 0, depositamount = 0, withdrawalbalance=


0;//declaring the variables, accountbalance, depositamount, withdrawalbalance,
as double

String acctNum,pwd;//declaring acctNum, pwd as string

String acctres;//declaring acctres as string

int counter=0;//declaring counter as int

int Choice;//declaring Choice as int

do//gives the do-while loop the condition to repeat the statement

{
System.out.println("Please enter your account number: ");//gives
the system command to print

acctNum = kbd.nextLine();//getting the inputs and allocating

System.out.println("Please enter your account password: ");//gives


the system command to print

pwd = kbd.nextLine();//getting the inputs and allocating

acctres=checkID(acctNum,pwd);//Initializing acctres

if(!acctres.equals("error"))// checking for the situation of the acctres


variable for error

accountbalance = Double.parseDouble(acctres);//Initializing
accountbalance

do//gives the do-while loop the condition to repeat the statement

Choice = Menu();//Initializing Menu()

System.out.println(Choice);//gives the system command to


print

if (Choice == 1)//checking for input 1

System.out.println("Your Balance is: " +


accountbalance + "$");//gives the system command to print

else if (Choice == 2)//checking for input 2

{
System.out.println("How much would you like to deposit
to your account? ");//gives the system command to print

depositamount=kbd.nextDouble();//getting the inputs


and allocating

double calculatebalance = Deposit(accountbalance,


depositamount);//Initializing calculatebalance

System.out.println("Your Balance with your Deposit


now is: " + calculatebalance + "$");//gives the system command to print

else if (Choice == 3)//checking for input 3

System.out.println("How much would you like to


withdrawal from your account? ");//gives the system command to print

withdrawalbalance=kbd.nextDouble();//getting the
inputs and allocating

double calculatebalance1 = Withdraw(accountbalance,


withdrawalbalance);//Initializing calculatebalance1

System.out.println("You Balance now is: " +


calculatebalance1 + "$");//gives the system command to print

else// checking for the other inputs except the ones which
were mentioned

System.out.println("Do you want to Log Out? (Y or N)


");//gives the system command to print

userAnswer=kbd.next();//getting the inputs and


allocating

userAnswer=userAnswer.toUpperCase();//to ignore the


upper case or lower case input and count them as the same

if (userAnswer.equals("Y"))//checking for the situation


of userAnswer for being equal Y which means yes

{
System.out.println("You are now logged
out!");//gives the system command to print

System.exit(0);// gives command for the if statement

}while ((Choice <=4)|| (userAnswer.equals("N")));//Checking


input N

else// checking for other input except the ones that already were
mentioned

System.out.println("Error");//gives the system command to


print

counter++;//Increasing the counter by 1

System.out.println(counter);//gives the system command to print

}while(counter<3);//checking for the counter to be less than 3 or not

System.out.println("You have exceeded the required amount of


times.");//gives the system command to print

public static String checkID(String acctNum, String pwd)//separating the


part from the main program as a new function in the main function

{
String result = "error";//declaring the result as string

// Strings a, b, and c contain the valid account numbers and passwords.

// For each string, the account number is listed first, followed by

// a space, followed by the password for the account, followed by a space,

// followed by the current balance.

String a = "44567-5 mypassword 520.36";//declaring string a which id


equal 44567-5 mypassword 520.36 in this function

String b = "12345-6 anotherpassword 48.20";//declaring string b which


id equal 12345-6 anotherpassword 48.20 in this function

String c = "54321-0 betterpassword 96.74";//declaring string c which id


equal 54321-0 betterpassword 96.74 in this function

String d=a.substring(0,7);//declaring string d in this function

String e=a.substring(8,18);//declaring string e in this function

String eres=a.substring(19);//declaring string eres in this function

String f=b.substring(0,7);//declaring string f in this function

String g=b.substring(8,23);//declaring string g in this function

String gres=b.substring(24);//declaring string gres in this function

String h=c.substring(0,7);//declaring string h in this function

String i=c.substring(8,22);//declaring string i in this function

String ires=c.substring(23);//declaring string ires in this function

if(acctNum.equals(d) && pwd.equals(e))//checking for account number


and password

result=eres;//gives commands for the if statement

else if(acctNum.equals(f) && pwd.equals(g))//checking for account


number and password

{
result=gres;//gives commands for the if statement

else if(acctNum.equals(h) && pwd.equals(i))//checking for account


number and password

result=ires;//gives commands for the if statement

return result;//to get data out of the function and takes the value with it
only once

public static double Displaybalance1(double accountbalance)//separating the


part from the main program as a new function in the main function

return accountbalance;//to get data out of the function and takes the
value with it only once

public static double Deposit(double accountbalance, double


depositamount)//separating the part from the main program as a new function in
the main function

return accountbalance+ depositamount;//to get data out of the function


and takes the value with it only once

public static double Withdraw(double accountbalance, double


withdrawalbalance)//separating the part from the main program as a new
function in the main function
{

double newbalance1 = 0;//declaring the variables, newbalance1, as


double

if (withdrawalbalance<=accountbalance)//checking the condition in the


parentheses(if withdrawalamount is less than or equal the accontbalance or not)

newbalance1 = accountbalance - withdrawalbalance;//gives the


system command to print the calculated amount

else if (withdrawalbalance>accountbalance)//checking the condition in


the parentheses(if withdrawalamount is more than the accontbalance or not)

newbalance1 = accountbalance;//declaring the newbalance1 as


previous accountbalance without change

System.out.println("error, that is impossible! your account balance


still is: " + newbalance1);//gives the system command to print the
accountbalance without changing it

return newbalance1;//to get data out of the function and takes the value
with it only once

public static int Menu()//separating the part from the main program as a
new function in the main function

int Option ;//declaring the variables, Size, as int

do//gives the do-while loop the condition to repeat the statement

Scanner kbd1 = new Scanner(System.in);// declaring the function


System.out.println("1. Display Balance ");//gives the system
command to print

System.out.println("2. Deposit ");//gives the system command to


print

System.out.println("3. Withdraw ");//gives the system command to


print

System.out.println("4. Log Out ");//gives the system command to


print

System.out.println("Enter your option");//gives the system


command to print

Option = kbd1.nextInt();//getting the inputs and allocating

if ((Option<=0)&&(Option > 4))//checking for the statement in


parentheses(Smaller or equal 0 or bigger than 4 inputs)

System.out.println("Error! Choose again: ");//gives the system


command to print

}while ((Option<=0)&&(Option > 4));//gives the while loop the condition


to stop the repeating statement

return Option;//to get data out of the function and takes the value with it
only once

Das könnte Ihnen auch gefallen