Sie sind auf Seite 1von 20

Java (programming language)

From Wikipedia, the free encyclopedia


"J ava language" redirects here. For the natural language from the Indonesian island of J ava, see
J avanese language.
Not to be confused with J avaScript
J ava
Paradigm(s)
multi-paradigm
structured, imperative
functional, generic
concurrent
Designed by
J ames Gosling
Sun Microsystems
Developer Oracle Corporation
Appeared in 1995
[1]
Stable release
J ava Standard Edition 8 Update
5 (1.8.0_5) / April
months ago
Typing discipline
Static, strong, safe
manifest
Major
implementations
OpenJ DK, many others
Dialects Generic J ava
Influenced by
Ada 83, C++
Generic J ava
3,
[5]
Oberon,
UCSD Pascal
Influenced
Ada 2005, BeanShell
Clojure, D, ECMAScript
Groovy, J #,
PHP, Python
Java (programming language)
From Wikipedia, the free encyclopedia
"J ava language" redirects here. For the natural language from the Indonesian island of J ava, see
J avaScript.
paradigm: object-oriented,
imperative,
generic, reflective,
J ames Goslingand
Sun Microsystems
Oracle Corporation
J ava Standard Edition 8 Update
5 (1.8.0_5) / April 15, 2014; 2
Static, strong, safe, nominative,
many others
Generic J ava, Pizza
C++, C#,
[2]
Eiffel,
[3]
Generic J ava, Mesa,
[4]
Modula-
,
[6]
Objective-C,
[7]
UCSD Pascal,
[8][9]
Smalltalk
BeanShell, C#,
ECMAScript,
, J avaScript, Kotlin,
Python, Scala, Seed7, Vala
"J ava language" redirects here. For the natural language from the Indonesian island of J ava, see
Implementation
language
C and C++
OS Cross-platform
License
GNU General Public License
J ava Community Process
Filename
extension(s)
.java , .class,
Website For J ava Developers
J ava Programming
Java is a computer programming language
specifically designed to have as few implementation depe
let application developers "write once, run anywhere
one platform does not need to be recompiled to run on another. J ava applications are typically
compiledto bytecode(class file) that can run on any
computer architecture. J ava is, as of 2014, one of the most popular programming languages in
use, particularly for client-server web applications, with a reported 9 m
J ava was originally developed by
into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems'
platform. The language derives much of its
facilities than either of them.
The original and reference implementation
were developed by Sun from 1991 and first released in 1995. As of May 2007, in compliance
with the specifications of the J ava Community Process
technologies under the GNU General Public License
implementations of these Sun technologies, such as the
compiler), GNU Classpath(standard libraries), and
Contents
1 History
o 1.1 Principles
o 1.2 Versions
2 Practices
o 2.1 J ava platform
2.1.1 Implementations
2.1.2 Performance
o 2.2 Automatic memory management
3 Syntax
4 Examples
o 4.1 Hello world
o 4.2 A more comprehensive example
platform(multi-platform)
GNU General Public License,
J ava Community Process
, .jar
For J ava Developers
J ava Programmingat Wikibooks
computer programming languagethat is concurrent, class-based, object
specifically designed to have as few implementation dependencies as possible. It is intended to
write once, run anywhere" (WORA), meaning that code that runs on
d to be recompiled to run on another. J ava applications are typically
) that can run on any J ava virtual machine(J VM) regardless of
. J ava is, as of 2014, one of the most popular programming languages in
server web applications, with a reported 9 million developers.
J ava was originally developed by J ames Goslingat Sun Microsystems(which has since
) and released in 1995 as a core component of Sun Microsystems'
e language derives much of its syntaxfrom C and C++, but it has fewer
reference implementationJ ava compilers, virtual machines, and
were developed by Sun from 1991 and first released in 1995. As of May 2007, in compliance
J ava Community Process, Sun relicensed most of its J ava
GNU General Public License. Others have also developed alternative
implementations of these Sun technologies, such as the GNU Compiler for J ava
(standard libraries), and IcedTea-Web (browser plugin for applets).
2.1.1 Implementations
2.1.2 Performance
2.2 Automatic memory management
4.2 A more comprehensive example
object-oriented, and
ndencies as possible. It is intended to
" (WORA), meaning that code that runs on
d to be recompiled to run on another. J ava applications are typically
(J VM) regardless of
. J ava is, as of 2014, one of the most popular programming languages in
illion developers.
[10][11]
(which has since merged
) and released in 1995 as a core component of Sun Microsystems' J ava
, but it has fewer low-level
l machines, and class libraries
were developed by Sun from 1991 and first released in 1995. As of May 2007, in compliance
, Sun relicensed most of its J ava
. Others have also developed alternative
(bytecode
Web (browser plugin for applets).
5 Special classes
o 5.1 Applet
o 5.2 Servlet
o 5.3 J avaServer Pages
o 5.4 Swing application
o 5.5 Generics
6 Criticism
7 Use on unofficial software platforms
o 7.1 Google
8 Class libraries
9 Documentation
10 Editions
11 See also
o 11.1 Comparison of J ava with other languages
12 Notes
13 References
14 External links
History
See also: J ava (software platform) History
Duke, the J ava mascot
J ames Gosling, Mike Sheridan, and
1991.
[12]
J ava was originally designed for interactive television, but it was too advanced for the
digital cable television industry at the time.
tree that stood outside Gosling's office; it went by the name
Java, from J ava coffee,
[14]
said to be consumed in large quantities by the language's
5.3 J avaServer Pages
5.4 Swing application
7 Use on unofficial software platforms
11.1 Comparison of J ava with other languages
J ava (software platform) History
, Mike Sheridan, and Patrick Naughtoninitiated the J ava language project in J une
J ava was originally designed for interactive television, but it was too advanced for the
digital cable television industry at the time.
[13]
The language was initially called
tree that stood outside Gosling's office; it went by the name Green later, and was later renamed
said to be consumed in large quantities by the language's
initiated the J ava language project in J une
J ava was originally designed for interactive television, but it was too advanced for the
The language was initially called Oak after an oak
later, and was later renamed
said to be consumed in large quantities by the language's
creators.
[citation needed]
Gosling aimed to implement a virtual machineand a language that had a
familiar C/C++style of notation.
[15]
Sun Microsystemsreleased the first public implementation as J ava 1.0 in 1995.
[1]
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
J ava quickly became popular. With the advent of Java 2 (released initially as J 2SE 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 J ava). 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 J TC1standards body and later the Ecma
International to formalize J ava, but it soon withdrew from the process.
[16]
J ava remains a de facto
standard, controlled through the J ava Community Process.
[17]
At one time, Sun made most of its
J ava implementations available without charge, despite their proprietary softwarestatus. Sun
generated revenue from J ava through the selling of licenses for specialized products such as the
J ava Enterprise System. Sun distinguishes between its Software Development Kit (SDK) and
Runtime Environment (J RE) (a subset of the SDK); the primary distinction involves the J RE's
lack of the compiler, utility programs, and header files.
On November 13, 2006, Sun released much of J ava as free and open source software, (FOSS),
under the terms of the GNU General Public License(GPL). On May 8, 2007, Sun finished the
process, making all of J ava'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.
[18]
Sun's vice-president Rich Green said that Sun's ideal role with regards to J ava was as an
"evangelist."
[19]
Following Oracle Corporation's acquisition of Sun Microsystems in 20092010,
Oracle has described itself as the "steward of J ava technology with a relentless commitment to
fostering a community of participation and transparency".
[20]
This did not hold Oracle, however,
from filing a lawsuit against Google shortly after that for using J ava inside the Android SDK (see
Google section below). J ava software runs on everything from laptopsto data centers, game
consolesto scientific supercomputers. There are 930 million J ava Runtime Environment
downloads each year and 3 billion mobile phonesrun J ava.
[21]
On April 2, 2010, J ames Gosling
resigned from Oracle.
[22]
Principles
J ames Gosling, the creator of J ava
There were five primary goals in the creation of the J ava language:
1. It should be "simple, object
2. It should be "robust and secure"
3. It should be "architecture
4. It should execute with "high performance"
5. It should be "interpreted, threaded, and dynamic"
Versions
Main article: J ava version history
Major release versions of J ava, along with their release dates:
J DK 1.0 (J anuary 21, 1996)
J DK 1.1 (February 19, 1997)
J 2SE 1.2 (December 8, 1998)
J 2SE 1.3 (May 8, 2000)
J 2SE 1.4 (February 6, 2002)
J 2SE 5.0 (September 30, 2004)
J ava SE 6 (December 11, 2006)
J ava SE 7 (J uly 28, 2011)
J ava SE 8 (March 18, 2014)
Practices
Java platform
Main articles: J ava (software platform)
, the creator of J ava
There were five primary goals in the creation of the J ava language:
[23]
It should be "simple, object-oriented and familiar"
It should be "robust and secure"
It should be "architecture-neutral and portable"
It should execute with "high performance"
It should be "interpreted, threaded, and dynamic"
J ava version history
Major release versions of J ava, along with their release dates:
J DK 1.0 (J anuary 21, 1996)
J DK 1.1 (February 19, 1997)
ber 8, 1998)
J 2SE 1.4 (February 6, 2002)
J 2SE 5.0 (September 30, 2004)
J ava SE 6 (December 11, 2006)
J ava SE 7 (J uly 28, 2011)
J ava SE 8 (March 18, 2014)
J ava (software platform) and J ava virtual machine
One characteristic of J ava is portability, which means that computer programs written in the J ava
language must run similarly on any hardware/operating-system platform. This is achieved by
compiling the J ava language code to an intermediate representation called J ava bytecode, instead
of directly to platform-specific machine code. J ava bytecode instructions are analogous to
machine code, but they are intended to be interpretedby a virtual machine(VM) written
specifically for the host hardware. End-userscommonly use a J ava Runtime Environment (J RE)
installed on their own machine for standalone J ava applications, or in a Web browser for J ava
applets.
Standardized libraries provide a generic way to access host-specific features such as graphics,
threading, and networking.
A major benefit of using bytecodeis porting. However, the overhead of interpretation means that
interpreted programs almost always run more slowly than programs compiled to native
executables would. J ust-in-Time (J IT) compilers were introduced from an early stage that
compile bytecodes to machine code during runtime.
Implementations
See also: Free J ava implementations
Oracle Corporationis the current owner of the official implementation of the J ava SE platform,
following their acquisition of Sun Microsystemson J anuary 27, 2010. This implementation is
based on the original implementation of J ava by Sun. The Oracle implementation is available for
Mac OS X, Windowsand Solaris. Because J ava lacks any formal standardization recognized by
Ecma International, ISO/IEC, ANSI, or other third-party standards organization, the Oracle
implementation is the de facto standard.
The Oracle implementation is packaged into two different distributions: The J ava Runtime
Environment (J RE) which contains the parts of the J ava SE platform required to run J ava
programs and is intended for end-users, and the J ava Development Kit (J DK), which is intended
for software developers and includes development tools such as the J ava compiler, J avadoc, J ar,
and a debugger.
OpenJ DK is another notable J ava SE implementation that is licensed under the GPL. The
implementation started when Sun began releasing the J ava source code under the GPL. As of
J ava SE 7, OpenJ DK is the official J ava reference implementation.
The goal of J ava is to make all implementations of J ava compatible. Historically, Sun's
trademark license for usage of the J ava 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 J NI 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.
[24]
As a result, Microsoft no longer ships Windows
with J ava.
Platform-independent J ava is essential to J ava EE, and an even more rigorous validation is
required to certify an implementation. This environment enables portable server-side
applications.
Performance
Main article: J ava performance
Programs written in J ava have a reputation for being slower and requiring more memory than
those written in C++.
[25][26]
However, J ava programs' execution speed improved significantly
with the introduction of J ust-in-time compilationin 1997/1998 for J ava 1.1,
[27]
the addition of
language features supporting better code analysis (such as inner classes, the StringBuilder class,
optional assertions, etc.), and optimizations in the J ava virtual machine itself, such as HotSpot
becoming the default for Sun's J VM in 2000.
Some platforms offer direct hardware support for J ava; there are microcontrollers that can run
J ava in hardware instead of a software J ava virtual machine, and ARM based processors can
have hardware support for executing J ava bytecode through their J azelleoption.
Automatic memory management
J ava uses an automatic garbage collector to manage memory in the object lifecycle. The
programmer determines when objects are created, and the J ava runtime is responsible for
recovering the memory once objects are no longer in use. Once no references to an object
remain, the unreachable memorybecomes eligible to be freed automatically by the garbage
collector. Something similar to a memory leakmay 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.
[28][29]
One of the ideas behind J ava'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. In the latter case the responsibility of managing memory resides with
the programmer. If the program does not deallocate an object, a memory leakoccurs. 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 J ava.
J ava does not support C/C++style pointer arithmetic, where object addresses and unsigned
integers (usually long integers) can be used interchangeably. This allows the garbage collector to
relocate referenced objects and ensures type safety and security.
As in C++and some other object-oriented languages, variables of J ava's primitive data typesare
not objects. Values of primitive types are either stored directly in fields (for objects) or on the
stack(for methods) rather than on the heap, as is commonly true for objects (but see escape
analysis). This was a conscious decision by J ava's designers for performance reasons. Because of
this, J ava was not considered to be a pure object-oriented programming language. However, as
of J ava 5.0, autoboxingenables programmers to proceed as if primitive types were instances of
their wrapper class.
J ava contains multiple types of garbage collectors. By default,
[citation needed]
HotSpot uses the
parallel scavenge garbage collector. However, there are also several other garbagecollectors that
can be used to manage the heap. For 90% of applications in J ava, the Concurrent Mark Sweep
garbage collector is sufficient.
[30]
Oracle aims to replace CMS with the Garbage-first collector
(G1).
Syntax
Main article: J ava syntax
The syntax of J ava is largely derived from C++. Unlike C++, which combines the syntax for
structured, generic, and object-oriented programming, J ava 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 primitive data types (i.e. integers, floating-point numbers, boolean values, and
characters), which are not classes for performance reasons.
Unlike C++, J ava does not support operator overloadingor multiple inheritancefor classes. This
simplifies the language and aids in preventing potential errors and anti-patterndesign.
J ava uses similar commenting methods to C++. There are three different styles of comments: a
single line style marked with two slashes (/ / ), a multiple line style opened with / * and closed
with */ , and the J avadoccommenting style opened with / ** and closed with */ . The J avadoc
style of commenting allows the user to run the J avadoc executable to compile documentation for
the program.
Example:
/ / Thi s i s an exampl e of a si ngl e l i ne comment usi ng t wo sl ashes
/ * Thi s i s an exampl e of a mul t i pl e l i ne comment usi ng t he sl ash and
ast er i sk.
Thi s t ype of comment can be used t o hol d a l ot of i nf or mat i on or deact i vat e
code, but i t i s ver y i mpor t ant t o r emember t o cl ose t he comment . */
package f i bsandl i es;
i mpor t j ava. ut i l . HashMap;
/ **
* Thi s i s an exampl e of a J avadoc comment ; J avadoc can compi l e document at i on
* f r omt hi s t ext . J avadoc comment s must i mmedi at el y p
document ed.
*/
publ i c cl ass Fi bCal cul at or ext ends Fi bonacci i mpl ement s Cal cul at or {
pr i vat e st at i c HashMap<I nt eger , I nt eger > memoi zed = new HashMap<I nt eger ,
I nt eger >( ) ;
st at i c {
memoi zed. put ( 1, 1) ;
memoi zed. put ( 2, 1) ;
}
/ ** An exampl e of a met hod wr i t t en i n J ava, wr apped i n a cl ass.
* Gi ven a non- negat i ve number FI BI NDEX, r et ur ns
* t he Nt h Fi bonacci number , wher e N equal s FI BI NDEX.
* @par amf i bI ndex The i ndex of t he Fi bonacci number
* @r et ur n The Fi bonacci number i t sel f
*/
publ i c st at i c i nt f i bonacci ( i nt f i bI ndex) {
i f ( memoi zed. cont ai nsKey( f i bI ndex) ) {
r et ur n memoi zed. get ( f i bI ndex) ;
} el se {
i nt answer = f i bonacci ( f i bI ndex
memoi zed. put ( f i bI ndex, answer ) ;
r et ur n answer ;
}
}
}
Examples
This article contains instructions, advice, or how
is to present facts, not to train. Please help
how-to content or by moving
Hello world
The traditional Hello world program
cl ass Hel l oWor l dApp {
publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
Syst em. out . pr i nt l n( " Hel l o Wor l d! " ) ; / / Di spl ay t he
}
}
To compare this to other programming languages see the list of
Source files must be named after the publ
example, Hel l oWor l dApp. j ava. It must first be compiled into bytecode, using a
* Thi s i s an exampl e of a J avadoc comment ; J avadoc can compi l e document at i on
* f r omt hi s t ext . J avadoc comment s must i mmedi at el y pr ecede t he t hi ng bei ng
publ i c cl ass Fi bCal cul at or ext ends Fi bonacci i mpl ement s Cal cul at or {
pr i vat e st at i c HashMap<I nt eger , I nt eger > memoi zed = new HashMap<I nt eger ,
memoi zed. put ( 1, 1) ;
ut ( 2, 1) ;
/ ** An exampl e of a met hod wr i t t en i n J ava, wr apped i n a cl ass.
negat i ve number FI BI NDEX, r et ur ns
* t he Nt h Fi bonacci number , wher e N equal s FI BI NDEX.
* @par amf i bI ndex The i ndex of t he Fi bonacci number
* @r et ur n The Fi bonacci number i t sel f
publ i c st at i c i nt f i bonacci ( i nt f i bI ndex) {
i f ( memoi zed. cont ai nsKey( f i bI ndex) ) {
r et ur n memoi zed. get ( f i bI ndex) ;
i nt answer = f i bonacci ( f i bI ndex - 1) + f i bonacci ( f i bI ndex
memoi zed. put ( f i bI ndex, answer ) ;
instructions, advice, or how-to content. The purpose of Wikipedia
is to present facts, not to train. Please help improve this articleeither by rewriting the
movingit to Wikiversity, Wikibooksor Wikivoyage
Hello world programcan be written in J ava as:
[31]
publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
Syst em. out . pr i nt l n( " Hel l o Wor l d! " ) ; / / Di spl ay t he st r i ng.
To compare this to other programming languages see the list of hello world program examples
Source files must be named after the public class they contain, appending the suffix
. It must first be compiled into bytecode, using a
* Thi s i s an exampl e of a J avadoc comment ; J avadoc can compi l e document at i on
r ecede t he t hi ng bei ng
publ i c cl ass Fi bCal cul at or ext ends Fi bonacci i mpl ement s Cal cul at or {
pr i vat e st at i c HashMap<I nt eger , I nt eger > memoi zed = new HashMap<I nt eger ,
/ ** An exampl e of a met hod wr i t t en i n J ava, wr apped i n a cl ass.
1) + f i bonacci ( f i bI ndex - 2) ;
. The purpose of Wikipedia
either by rewriting the
Wikivoyage(January 2012)
st r i ng.
hello world program examples.
ic class they contain, appending the suffix . j ava, for
. It must first be compiled into bytecode, using a J ava compiler,
producing a file named Hel l oWor l dApp. cl ass. Only then can it be executed, or 'launched'. The
J ava source file may only contain one public class, but it can contain multiple classes with other
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 classesare treated as if their
name were the concatenation of the name of their enclosing class, a $, and an integer.
The keywordpublic 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 hierarchyis related to the
name of the directory in which the .java file is located.
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 class members that
are not also static.
The keyword void indicates that the main method does not return any value to the caller. If a
J ava program is to exit with an error code, it must call System.exit() explicitly.
The method name "mai n" is not a keyword in the J ava language. It is simply the name of the
method the J ava launcher calls to pass control to the program. J ava classes that run in managed
environments such as applets and Enterprise J avaBeando not use or need a mai n( ) method. A
J ava program may contain multiple classes that have mai n methods, which means that the VM
needs to be explicitly told which class to launch from.
The main method must accept an arrayof String objects. By convention, it is referenced as
args although any other legal identifier name can be used. Since J ava 5, the main method can
also use variable arguments, in the form of publ i c st at i c voi d mai n( St r i ng. . . ar gs) ,
allowing the main method to be invoked with an arbitrary number of St r i ng arguments. The
effect of this alternate declaration is semantically identical (the ar gs parameter is still an array of
St r i ng objects), but it allows an alternative syntax for creating and passing the array.
The J ava launcher launches J ava by loading a given class (specified on the command line or as
an attribute in a J AR) and starting its publ i c st at i c voi d mai n( St r i ng[ ] ) method. Stand-
alone programs must declare this method explicitly. The St r i ng[ ] ar gs parameter is an array
of St r i ng objects containing any arguments passed to the class. The parameters to mai n are
often passed by means of a command line.
Printingis part of a J ava standard library: The System class defines a public static field called
out. The out object is an instance of the Pr i nt St r eamclass and provides many methods for
printing data to standard out, including println(String) which also appends a new line to the
passed string.
The string "Hello World!" is automatically converted to a String object by the compiler.
A more comprehensive example
This section does not cite
by adding citations to reliable sources
removed. (May 2013)
This article contains instructions, advice, or how
is to present facts, not to train. Please help
how-to content or by moving
/ / OddEven. j ava
i mpor t j avax. swi ng. J Opt i onPane;
publ i c cl ass OddEven {
pr i vat e i nt user I nput ; / / a whol e number ( " i nt " means i nt eger )
/ **
* Thi s i s t he const r uct or met hod. I t get s cal l ed when an obj ect of t he
OddEven t ype
* i s bei ng cr eat ed.
*/
publ i c OddEven( ) {
/ *
* I n most J ava pr ogr ams const r uct or s can i ni t i al i ze obj ect s wi t h
def aul t val ues, or cr eat e
* ot her obj ect s t hat t hi s obj ect mi ght use t o per f or mi t s f unct i ons.
I n some J ava pr ogr ams, t he
* const r uct or may si mpl y be an
i ni t i al i zed pr i or t o t he
* f unct i oni ng of t he obj ect . I n t hi s pr ogr am' s case, an empt y
const r uct or woul d suf f i ce.
* A const r uct or must exi st ; however , i f t he user doesn' t put one i n
t hen t he compi l er
* wi l l cr eat e an empt y one.
*/
}
/ **
* Thi s i s t he mai n met hod. I t get s cal l ed when t hi s cl ass i s r un t hr ough
a J ava i nt er pr et er .
* @par amar gs command l i ne ar gument s ( unused)
*/
publ i c st at i c voi d mai n( f i nal
/ *
* Thi s l i ne of code cr eat es a new i nst ance of t hi s cl ass cal l ed
" number " ( al so known as an
* Obj ect ) and i ni t i al i zes i t by cal l i ng t he const r uct or . The next
l i ne of code cal l s
* t he " showDi al og( ) " met hod,
a number .
*/
OddEven number = new OddEven( ) ;
number . showDi al og( ) ;
}
A more comprehensive example
cite any references or sources. Please help improve this section
adding citations to reliable sources. Unsourced material may be challenged and
instructions, advice, or how-to content. The purpose of Wikipedia
is to present facts, not to train. Please help improve this articleeither by rewriting the
movingit to Wikiversity, Wikibooksor Wikivoyage
i mpor t j avax. swi ng. J Opt i onPane;
pr i vat e i nt user I nput ; / / a whol e number ( " i nt " means i nt eger )
* Thi s i s t he const r uct or met hod. I t get s cal l ed when an obj ect of t he
* I n most J ava pr ogr ams const r uct or s can i ni t i al i ze obj ect s wi t h
* ot her obj ect s t hat t hi s obj ect mi ght use t o per f or mi t s f unct i ons.
* const r uct or may si mpl y be an empt y f unct i on i f not hi ng needs t o be
* f unct i oni ng of t he obj ect . I n t hi s pr ogr am' s case, an empt y
* A const r uct or must exi st ; however , i f t he user doesn' t put one i n
* wi l l cr eat e an empt y one.
* Thi s i s t he mai n met hod. I t get s cal l ed when t hi s cl ass i s r un t hr ough
* @par amar gs command l i ne ar gument s ( unused)
publ i c st at i c voi d mai n( f i nal St r i ng[ ] ar gs) {
* Thi s l i ne of code cr eat es a new i nst ance of t hi s cl ass cal l ed
* Obj ect ) and i ni t i al i zes i t by cal l i ng t he const r uct or . The next
* t he " showDi al og( ) " met hod, whi ch br i ngs up a pr ompt t o ask you f or
OddEven number = new OddEven( ) ;
number . showDi al og( ) ;
. Please help improve this section
. Unsourced material may be challenged and
. The purpose of Wikipedia
either by rewriting the
Wikivoyage(May 2013)
pr i vat e i nt user I nput ; / / a whol e number ( " i nt " means i nt eger )
* Thi s i s t he const r uct or met hod. I t get s cal l ed when an obj ect of t he
* I n most J ava pr ogr ams const r uct or s can i ni t i al i ze obj ect s wi t h
* ot her obj ect s t hat t hi s obj ect mi ght use t o per f or mi t s f unct i ons.
empt y f unct i on i f not hi ng needs t o be
* f unct i oni ng of t he obj ect . I n t hi s pr ogr am' s case, an empt y
* A const r uct or must exi st ; however , i f t he user doesn' t put one i n
* Thi s i s t he mai n met hod. I t get s cal l ed when t hi s cl ass i s r un t hr ough
* Thi s l i ne of code cr eat es a new i nst ance of t hi s cl ass cal l ed
* Obj ect ) and i ni t i al i zes i t by cal l i ng t he const r uct or . The next
whi ch br i ngs up a pr ompt t o ask you f or
publ i c voi d showDi al og( ) {
/ *
* " t r y" makes sur e not hi ng goes wr ong. I f somet hi ng does,
* t he i nt er pr et er ski ps t o " cat ch" t o see what i t shoul d do.
*/
t r y {
/ *
* The code bel ow br i ngs up a J Opt i onPane, whi ch i s a di al og box
* The St r i ng r et ur ned by t he " showI nput Di al og( ) " met hod i s
conver t ed i nt o
* an i nt eger , maki ng t he pr ogr amt r eat i t as a number i nst ead of
a wor d.
* Af t er t hat , t hi s met hod cal l s a second met hod, cal cul at e( )
t hat wi l l
* di spl ay ei t her " Even" or " Odd. "
*/
user I nput = I nt eger . par seI nt ( J Opt i onPane. showI nput Di al og( " Pl ease
ent er a number . " ) ) ;
cal cul at e( ) ;
} cat ch ( f i nal Number For mat Except i on e) {
/ *
* Get t i ng i n t he cat ch bl ock means t hat t her e was a pr obl emwi t h
t he f or mat of
* t he number . Pr obabl y some l et t er s wer e t yped i n i nst ead of a
number .
*/
Syst em. er r . pr i nt l n( " ERROR: I nval i d i nput . Pl ease t ype i n a
numer i cal val ue. " ) ;
}
}
/ **
* When t hi s get s cal l ed, i t sends a message t o t he i nt er pr et er .
* The i nt er pr et er usual l y shows i t on t he command pr ompt ( For Wi ndows
user s)
* or t he t er mi nal ( For *ni x user s) . ( Assumi ng i t ' s open)
*/
pr i vat e voi d cal cul at e( ) {
i f ( ( user I nput %2) == 0) {
J Opt i onPane. showMessageDi al og( nul l , " Even" ) ;
} el se {
J Opt i onPane. showMessageDi al og( nul l , " Odd" ) ;
}
}
}
The import statement imports the JOptionPane class from the javax.swing package.
The OddEven class declares a single private fieldof type int named userInput. Every
instance of the OddEven class has its own copy of the user I nput field. The private
declaration means that no other class can access (read or write) the user I nput 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
method is invoked using a specific instance of the
invoke the method is passed as an undeclared parameter of type
The method tests the expression
remainder of dividing the
zero. If this expression is true, then it prints
(The cal cul at e method can be equivalently accessed as
user I nput field can beequivalently accessed as
use the undeclared t hi s parameter.)
OddEven number = new OddEven();
mai n method named number
OddEven. The declaration initializes
class, using the new keyword and the
instance to the variable.
The statement number.showDialog();
OddEven object referenced by the
passed as the undeclared
userInput = Integer.parseInt(JOptionPane.showInputDialog("Please Enter
A Number")); is a statement that converts the type of
int by using a utility function in the
Special classes
This article contains instructions, advice, or how
is to present facts, not to train. Please help
how-to content or by moving
Applet
Main article: J ava applet
J ava applets are programs that are embedded in other applications, typically in a Web page
displayed in a Web browser.
/ / Hel l o. j ava
i mpor t j avax. swi ng. J Appl et ;
i mpor t j ava. awt . Gr aphi cs;
publ i c cl ass Hel l o ext ends J Appl et {
publ i c voi d pai nt Component ( f i nal Gr aphi cs g) {
g. dr awSt r i ng( " Hel l o, wor l d! " , 65, 95) ;
}
}
The import statements direct the
java.awt.Graphics classes in the compilation. The import statement allows these classes to be
method is declared without the st at i c keyword. This means that the
method is invoked using a specific instance of the OddEven class. (The reference
invoke the method is passed as an undeclared parameter of type OddEven
The method tests the expression user I nput %2 == 0 using the if keyword to see if the
remainder of dividing the user I nput 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
method can be equivalently accessed as t hi s. cal cul at e
equivalently accessed as t hi s. user I nput , which both explicitly
parameter.)
OddEven number = new OddEven(); declares a local object referencevariable in the
number . This variable can hold a reference to an object of type
. The declaration initializes number by first creating an instance of the
keyword and the OddEven( ) constructor, and then assigning this
number.showDialog(); calls the calculate method. The instance of
object referenced by the number local variableis used to invoke the method and
as the undeclared t hi s parameter to the cal cul at e method.
userInput = Integer.parseInt(JOptionPane.showInputDialog("Please Enter
is a statement that converts the type of String to the primitive data type
by using a utility function in the primitive wrapper classInteger.
instructions, advice, or how-to content. The purpose of Wikipedia
is to present facts, not to train. Please help improve this articleeither by rewriting the
movingit to Wikiversity, Wikibooksor Wikivoyage
J ava applets are programs that are embedded in other applications, typically in a Web page
i mpor t j avax. swi ng. J Appl et ;
publ i c cl ass Hel l o ext ends J Appl et {
publ i c voi d pai nt Component ( f i nal Gr aphi cs g) {
g. dr awSt r i ng( " Hel l o, wor l d! " , 65, 95) ;
statements direct the J ava compiler to include the javax.swing.JApplet
classes in the compilation. The import statement allows these classes to be
. This means that the
referenceused to
OddEven named this.)
keyword to see if the
field belonging to the instance of the class by two is
; if this expression is false it prints Odd.
t hi s. cal cul at e and the
, which both explicitly
variable in the
. This variable can hold a reference to an object of type
by first creating an instance of the OddEven
constructor, and then assigning this
calls the calculate method. The instance of
is used to invoke the method and
userInput = Integer.parseInt(JOptionPane.showInputDialog("Please Enter
primitive data type
. The purpose of Wikipedia
either by rewriting the
Wikivoyage(January 2012)
J ava applets are programs that are embedded in other applications, typically in a Web page
javax.swing.JApplet and
classes in the compilation. The import statement allows these classes to be
referenced in the source codeusing the simple class name (i.e. J Appl et ) instead of the fully
qualified class name (FQCN, i.e. j avax. swi ng. J Appl et ).
The Hel l o class extends (subclasses) the JApplet (J ava Applet) class; the J Appl et class
provides the framework for the host application to display and control the lifecycleof the applet.
The J Appl et class is a J Component (J ava Graphical Component) which provides the applet with
the capability to display a graphical user interface(GUI) and respond to user events.
The Hel l o class overridesthe paintComponent(Graphics) method (additionally indicated with
the annotation, supported as of J DK 1.5, Over r i de) inherited from the Cont ai ner superclassto
provide the code to display the applet. The pai nt Component ( ) method is passed a Graphics
object that contains the graphic context used to display the applet. The pai nt Component ( )
method calls the graphic context drawString(String, int, int) method to display the
"Hello, world!" string at a pixel offset of (65, 95) from the upper-left corner in the applet's
display.
<! DOCTYPE HTML PUBLI C " - / / W3C/ / DTD HTML 4. 01/ / EN"
" ht t p: / / www. w3. or g/ TR/ ht ml 4/ st r i ct . dt d" >
<! - - Hel l o. ht ml - - >
<ht ml >
<head>
<t i t l e>Hel l o Wor l d Appl et </ t i t l e>
</ head>
<body>
<appl et code=" Hel l o. cl ass" wi dt h=" 200" hei ght =" 200" >
</ appl et >
</ body>
</ ht ml >
An applet is placed in an HTML document using the <applet> HTML element. The appl et tag
has three attributes set: code="Hello" specifies the name of the J Appl et 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 obj ect or embed element,
[32]
although support for these
elements by Web browsers is inconsistent.
[33]
However, the appl et tag is deprecated, so the
obj ect tag is preferred where supported.
The host application, typically a Web browser, instantiates the Hello applet and creates an
Appl et Cont ext for the applet. Once the applet has initialized itself, it is added to the AWT
display hierarchy. The pai nt Component ( ) method is called by the AWT event dispatching
threadwhenever the display needs the applet to draw itself.
Servlet
Main article: J ava Servlet
J ava 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-sideJ ava 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 sidewithout a face.
/ / Hel l o. j ava
i mpor t j ava. i o. *;
i mpor t j avax. ser vl et . *;
publ i c cl ass Hel l o ext ends Gener i cSer vl et {
publ i c voi d ser vi ce( f i nal Ser vl et Request r equest , f i nal Ser vl et Response
r esponse)
t hr ows Ser vl et Except i on, I OExcept i on {
r esponse. set Cont ent Type( " t ext / ht ml " ) ;
f i nal Pr i nt Wr i t er pw = r esponse. get Wr i t er ( ) ;
t r y {
pw. pr i nt l n( " Hel l o, wor l d! " ) ;
} f i nal l y {
pw. cl ose( ) ;
}
}
}
The import statements direct the J ava compiler to include all of the public classes and interfaces
from the java.io and javax.servlet packages in the compilation. Packages make J ava well
suited for large scale applications.
The Hello class extends the GenericServlet class; the Gener i cSer vl et class provides the
interface for the server to forward requests to the servlet andcontrol the servlet's lifecycle.
The Hel l o class overrides the service(ServletRequest, ServletResponse) method defined
by the Ser vl et interfaceto provide the code for the service request handler. The ser vi ce( )
method is passed: a ServletRequest object that contains the request from the client and a
ServletResponse object used to create the response returned to the client. The ser vi ce( )
method declares that it throws the exceptionsSer vl et Except i on and I OExcept i on if a
problem prevents it from responding to the request.
The setContentType(String) method in the response object is called to set the MIME content
type of the returned data to "text/html". The getWriter() method in the response returns a
PrintWriter object that is used to write the data that is sent to the client. The println(String)
method is called to write the "Hello, world!" string to the response and then the close()
method is called to close the print writer, which causes the data that has been written to the
stream to be returned to the client.
JavaServer Pages
Main article: J avaServer Pages
J avaServer Pages (J SP) are server-sideJ ava EE components that generate responses, typically
HTML pages, to HTTP requests from clients. J SPs embed J ava code in an HTML pageby using
the special delimiters<%and %>. A J SP is compiled to a J ava servlet, a J ava application in its
own right, the first time it is accessed. After that, the generated servlet creates the response.
Swing application
Main article: Swing (J ava)
Swingis a graphical user interface libraryfor the J ava 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. Applealso provides an Aqualook and feel for
Mac OS X. Where prior implementations of these looks and feels may have been considered
lacking, Swing in J ava 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:
/ / Hel l o. j ava ( J ava SE 5)
i mpor t j avax. swi ng. *;
publ i c cl ass Hel l o ext ends J Fr ame {
publ i c Hel l o( ) {
super ( " hel l o" ) ;
super . set Def aul t Cl oseOper at i on( Wi ndowConst ant s. EXI T_ON_CLOSE) ;
super . add( new J Label ( " Hel l o, wor l d! " ) ) ;
super . pack( ) ;
super . set Vi si bl e( t r ue) ;
}
publ i c st at i c voi d mai n( f i nal St r i ng[ ] ar gs) {
new Hel l o( ) ;
}
}
The first import includes all of the public classes and interfaces from the javax.swing package.
The Hello class extends the JFrame class; the J Fr ame class implements a windowwith a title
bar and a close control.
The Hello() constructor initializes the frame by first calling the superclass constructor, passing
the parameter " hel l o" , which is used as the window's title. It then calls the
setDefaultCloseOperation(int) method inherited from J Fr ame to set the default operation
when the close control on the title bar is selected to WindowConstants.EXIT_ON_CLOSE this
causes the J Fr ame to be disposed of when the frame is closed (as opposed to merely hidden),
which allows the J ava virtual machine 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
Cont ai ner superclass is called to add the label to the frame. The pack() method inherited from
the Wi ndowsuperclass is called to size the window and lay out its contents.
The main() method is called by the J ava virtual machine 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 mai n method does not cause the program to terminate because the AWT
event dispatching threadremains active until all of the Swing top-level windows have been
disposed.
Generics
Main article: Generics in J ava
In 2004, genericswere added to the J ava language, as part of J 2SE 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 Obj ect , 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. In addition to enabling more efficient code, certain
runtime exceptions are converted to compile-time errors, a characteristic known as type safety.
Criticism
Main article: Criticism of J ava
Criticisms directed at J ava include the implementation of generics,
[34]
speed,
[35]
the handling of
unsigned numbers,
[36]
the implementation of floating-point arithmetic,
[37]
and a history of
security vulnerabilities in the primary J ava VM implementation HotSpot.
[38]
Use on unofficial software platforms
J ava, the programming language, requires the presence of a software platform in order for
compiled programs to be executed. One of the official software platforms is the J ava SE
platform. A very popular unofficial software platform is the Android software platform, which
uses a different bytecode language and virtual machine, and is designed for low-memory devices
such as smartphonesand tablets.
Androidmakes extensive use of J ava
Google
See also: Oracle v. Google
Googleand Android, Inc. have chosen to use J ava as a key pillar in the creation of the
operating system, an open-source
system, built on the Linux kernel
language as the basis for Android applications. However, Android does not use the J ava virtual
machine, instead using J ava bytecode as an intermediate step and ultimately targeting Android's
own Dalvik virtual machine.
Android also does not provide the full
library does include an independent implementation of a large subset of it. This led to a legal
dispute between Oracle and Google. On May 7, 2012, a San Francisco jury found that if APIs
could be copyrighted, then Google had infringed Oracle's copyrights by the use of J ava in
Android devices.
[39]
District J udge
cannot be copyrighted,
[40]
but this was reversed by the Circuit Court in May
Class libraries
This section does not cite
by adding citations to reliable sources
removed. (May 2013)
The J ava Class Libraryare the compiled
implementor to support application development in J ava. Examples of these
makes extensive use of J ava-related technology
and Android, Inc. have chosen to use J ava as a key pillar in the creation of the
sourcesmartphone operatingsystem. Although the Android operating
Linux kernel, was written largely in C, the Android SDK uses the J ava
language as the basis for Android applications. However, Android does not use the J ava virtual
machine, instead using J ava bytecode as an intermediate step and ultimately targeting Android's
Android also does not provide the full J ava SE standard library, although the Android class
library does include an independent implementation of a large subset of it. This led to a legal
dispute between Oracle and Google. On May 7, 2012, a San Francisco jury found that if APIs
hen Google had infringed Oracle's copyrights by the use of J ava in
District J udge William Haskell Alsupruled on May 31, 2012, that APIs
but this was reversed by the Circuit Court in May2014.
cite any references or sources. Please help improve this section
adding citations to reliable sources. Unsourced material may be challenged and
are the compiled bytecodesof source codedeveloped by the J RE
implementor to support application development in J ava. Examples of these
and Android, Inc. have chosen to use J ava as a key pillar in the creation of the Android
. Although the Android operating
uses the J ava
language as the basis for Android applications. However, Android does not use the J ava virtual
machine, instead using J ava bytecode as an intermediate step and ultimately targeting Android's
standard library, although the Android class
library does include an independent implementation of a large subset of it. This led to a legal
dispute between Oracle and Google. On May 7, 2012, a San Francisco jury found that if APIs
hen Google had infringed Oracle's copyrights by the use of J ava in
ruled on May 31, 2012, that APIs
2014.
[41][42]
. Please help improve this section
. Unsourced material may be challenged and
developed by the J RE
implementor to support application development in J ava. Examples of these libraries are:
o The core libraries, which include:
Many low level, GUI, Integration, Deployment and Tools J ava Platform
Standard Edition 7 Documentation
Collection librariesthat implement data structuressuch as lists,
dictionaries, trees, sets, queuesand double-ended queue, or stacks
XML Processing (Parsing, Transforming, Validating) libraries
Security
Internationalization and localizationlibraries
o The integration libraries, which allow the application writer to communicate with
external systems. These libraries include:
The J ava Database Connectivity(J DBC) API for database access
J ava Namingand Directory Interface(J NDI) for lookup and discovery
RMI and CORBA for distributed application development
J MX for managing and monitoring applications
o User interfacelibraries, 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) Swinglibraries, 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 the J ava virtual machine that is the means by
which the bytecodes of the J ava libraries and third party applications are executed
Plugins, which enable appletsto be run in Web browsers
J ava Web Start, which allows J ava applications to be efficiently distributed to end-users
across the Internet
Licensing and documentation.
Documentation
Main article: J avadoc
J avadocis a comprehensive documentation system, created by Sun Microsystems, used by many
J ava developers. It provides developers with an organized system for documenting their code.
J avadoccomments have an extra asterisk at the beginning, i.e. the tags are /** and */, whereas
the normal multi-line comments in J ava are set off with the tags /* and */.
Editions
See also: Free J ava implementations Class library
Java Editions
Java Card
Micro Edition
Standard Edition
Enterprise Edition
JavaFX (Merged to Java SE 8)
PersonalJava (discontinued)
Sun has defined and supports four editions of J ava targeting different application environments
and segmented many of its APIs
J ava Cardfor smartcards.
J ava Platform, Micro Edition
resources.
J ava Platform, Standard Edition
J ava Platform, Enterprise Edition
Internet environments.
The classesin the J ava APIs are organized into separate groups called
contains a set of related interfaces
description of the packages available.
The set of APIs is controlled by Sun Microsystems
Community Processprogram. Companies or individuals participating in this process can
influence the design and development of the APIs. This process has been a subject of
controversy.
Sun also provided an edition called
based J ava ME configuration-profile pairings.
Java Card
Micro Edition (ME)
Standard Edition (SE)
Enterprise Edition (EE)
(Merged to Java SE 8)
(discontinued)
v
t
e
Sun has defined and supports four editions of J ava targeting different application environments
so that they belong to one of the platforms. The platforms are:
for smartcards.
Platform, Micro Edition(J ava ME) targeting environments with limited
J ava Platform, Standard Edition(J ava SE) targeting workstation environments.
J ava Platform, Enterprise Edition(J ava EE) targeting large distributed enterprise or
in the J ava APIs are organized into separate groups called packages. Each pack
interfaces, classes and exceptions. Refer to the separate platforms for a
description of the packages available.
Sun Microsystemsin cooperation with others through the
program. Companies or individuals participating in this process can
influence the design and development of the APIs. This process has been a subject of
Sun also provided an edition called PersonalJ avathat has been superseded by later, standards
profile pairings.
Sun has defined and supports four editions of J ava targeting different application environments
belong to one of the platforms. The platforms are:
targeting environments with limited
tion environments.
targeting large distributed enterprise or
. Each package
ate platforms for a
in cooperation with others through the J ava
program. Companies or individuals participating in this process can
influence the design and development of the APIs. This process has been a subject of
that has been superseded by later, standards-

Das könnte Ihnen auch gefallen