Preface: by Rohan Patel X Science
Preface: by Rohan Patel X Science
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
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."
Principles of java
There were five primary goals in the creation of the Java language:
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.
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.
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.
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 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 multiple line comment using the slash and asterisk.
/**
*/
Examples
Hello world
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 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.
// OddEven.java
import javax.swing.JOptionPane;
/*
* 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
* 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.
/*
* 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
*/
number.showDialog();
/*
*/
try {
/*
* After that, this method calls a second method, calculate() that will
*/
calculate();
} catch (NumberFormatException e) {
/*
* Getting in the catch block means that there was a problem with the format
of
*/
/*
* The interpreter usually shows it on the command prompt (For Windows users)
*/
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.
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
// 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);
// binds d to reference the same object as c // binds d to reference the same object as c
c->x = 5; c.x = 5;
• 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(){
}
a = new Foo(); a=new Foo();//Only in constructor
a->x = 5; getA().x=5;
// you can declare a "const" pointer // you can declare a "final" reference
b = new Foo(); b = new Foo();
// 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."
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
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).
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.
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.
.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
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.
Java C#
BigInteger bigNumber =
BigInteger bigNumber =
new
BigInteger("123456789012345678901234567890");
BigInteger.Parse("12345678901234567890123456
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 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
}
// a target class
class Target {
// a target class
public bool
class Target { TargetMethod(string arg) {
}
// usage
void DoSomething() {
// usage
void DoSomething() {
// construct a target with the
target method
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); }
};
boolean result =
dlg.Invoke("argumentstring");
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;
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.
There are several use cases for the dynamic type in C#:
Java does not support a late-bound type. The use cases for C# dynamic type have
different corresponding constructs in Java:
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.
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;
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.
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.
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.
Generics
In the field of generics the two languages show a superficial syntactical similarity, but
they have deep underlying differences.
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
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.
switch(color)
case Color.Blue:
goto
Console.WriteLine("Color is blue"); break;
case Color.DarkBlue:
Console.WriteLine("Color is dark");
// ...
}
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.
// ...
}
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.
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:
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.
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.
In Java, generators can be defined only using (possibly anonymous) classes, requiring
more boilerplate code.
Closures
A closure is an inline function which captures variables from its lexical scope.
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.
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.
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.
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.
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.
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.
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#
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#.
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).
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)
• 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
• Eclipse
• Netbeans
Compression
• LZMA SDK, the Java implementation of the SDK used by the popular 7-Zip
file archive software (available here)
Development assistance
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
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:
JVM languages
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).
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
• 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
Codename Merlin. This was the first release of the Java platform developed under the
Java Community Process as JSR 59. Major changes included:
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.
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.
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.
• 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 11
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
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
Java SE 6 Update 19
Java SE 6 Update 20
Java SE 6 Update 21
Java SE 7.0
• Language changes under Project Coin. The features accepted for inclusion in
Project Coin are:
• Strings in switch
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;
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.
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>
</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.*;
response.setContentType("text/html");
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 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.
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 Hello() {
super("hello");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
pack();
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/
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.
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:
• The "Code Pad" - The code pad is a tool that instantly evaluates arbitrary Java
expressions and statements.
• Group work support - BlueJ provides simple support for group work via a
subset of CVS and Subversion functionality.
• 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:
• 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.
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.
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.
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);
public static void main(String[] args) {// the main program with the word
void doesn't let anything out
{
System.out.println("Please enter your account number: ");//gives
the system command to print
acctres=checkID(acctNum,pwd);//Initializing acctres
accountbalance = Double.parseDouble(acctres);//Initializing
accountbalance
{
System.out.println("How much would you like to deposit
to your account? ");//gives the system command to print
withdrawalbalance=kbd.nextDouble();//getting the
inputs and allocating
else// checking for the other inputs except the ones which
were mentioned
{
System.out.println("You are now logged
out!");//gives the system command to print
else// checking for other input except the ones that already were
mentioned
{
String result = "error";//declaring the result as string
{
result=gres;//gives commands for the if statement
return result;//to get data out of the function and takes the value with it
only once
return accountbalance;//to get data out of the function and takes the
value with it only once
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
return Option;//to get data out of the function and takes the value with it
only once