Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Java syntax
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Reference types== Reference types include class types, interface types, and array types. When the constructor is called, an object is created on the heap and a reference is assigned to the variable. When a variable of an object gets out of scope, the reference is broken and when there are no references left, the object gets marked as garbage. The garbage collector then collects and destroys it some time afterwards. A reference variable is <code>null</code> when it does not reference any object. ===Arrays=== Arrays in Java are created at runtime, just like class instances. Array length is defined at creation and cannot be changed. <syntaxhighlight lang="java"> int[] numbers = new int[5]; numbers[0] = 2; numbers[1] = 5; int x = numbers[0]; </syntaxhighlight> ====Initializers==== <syntaxhighlight lang="java"> // Long syntax int[] numbers = new int[] {20, 1, 42, 15, 34}; // Short syntax int[] numbers2 = {20, 1, 42, 15, 34}; </syntaxhighlight> ====Multi-dimensional arrays==== In Java, multi-dimensional arrays are represented as arrays of arrays. Technically, they are represented by arrays of references to other arrays. <syntaxhighlight lang="java"> int[][] numbers = new int[3][3]; numbers[1][2] = 2; int[][] numbers2 = {{2, 3, 2}, {1, 2, 6}, {2, 4, 5}}; </syntaxhighlight> Due to the nature of the multi-dimensional arrays, sub-arrays can vary in length, so multi-dimensional arrays are not bound to be rectangular unlike C: <syntaxhighlight lang=Java> int[][] numbers = new int[2][]; //Initialization of the first dimension only numbers[0] = new int[3]; numbers[1] = new int[2]; </syntaxhighlight> ===Classes=== [[Class (computer programming)|Classes]] are fundamentals of an object-oriented language such as Java. They contain members that store and manipulate data. Classes are divided into ''top-level'' and ''nested''. Nested classes are classes placed inside another class that may access the private members of the enclosing class. Nested classes include ''member classes'' (which may be defined with the ''static'' modifier for simple nesting or without it for inner classes), ''local classes'' and ''anonymous classes''. ====Declaration==== {| class="wikitable" |- ! Top-level class |<syntaxhighlight lang="java"> class Foo { // Class members } </syntaxhighlight> |- !Inner class |<syntaxhighlight lang="java"> class Foo { // Top-level class class Bar { // Inner class } } </syntaxhighlight> |- !Nested class |<syntaxhighlight lang="java"> class Foo { // Top-level class static class Bar { // Nested class } } </syntaxhighlight> |- ! Local class |<syntaxhighlight lang="java"> class Foo { void bar() { class Foobar {// Local class within a method } } } </syntaxhighlight> |- ! Anonymous class |<syntaxhighlight lang="java"> class Foo { void bar() { new Object() {// Creation of a new anonymous class extending Object }; } } </syntaxhighlight> |} ====Instantiation==== Non-static members of a class define the types of the [[instance variable]]s and methods, which are related to the objects created from that class. To create these objects, the class must be instantiated by using the <code>new</code> operator and calling the class constructor. <syntaxhighlight lang="java"> Foo foo = new Foo(); </syntaxhighlight> ====Accessing members==== Members of both instances and static classes are accessed with the <code>.</code> (dot) operator. '''Accessing an instance member'''<br/> Instance members can be accessed through the name of a variable. <syntaxhighlight lang="java"> String foo = "Hello"; String bar = foo.toUpperCase(); </syntaxhighlight> '''Accessing a static class member'''<br/> Static members are accessed by using the name of the class or any other type. This does not require the creation of a class instance. Static members are declared using the <code>static</code> modifier. <syntaxhighlight lang="java"> public class Foo { public static void doSomething() { } } // Calling the static method Foo.doSomething(); </syntaxhighlight> ====Modifiers==== Modifiers are keywords used to modify declarations of types and type members. Most notably there is a sub-group containing the access modifiers. * '''<code>abstract</code>''' - Specifies that a class only serves as a base class and cannot be instantiated. * '''<code>static</code>''' - Used only for member classes, specifies that the member class does not belong to a specific instance of the containing class. * '''<code>final</code>''' - Classes marked as <code>final</code> cannot be extended from and cannot have any subclasses. * '''<code>strictfp</code>''' - Specifies that all floating-point operations must be carried out conforming to [[IEEE 754]] and forbids using enhanced precision to store intermediate results. =====Abstract class===== {{Excerpt|Abstract type #Java}} =====Final class===== {{Excerpt|final (Java)#Final classes}} =====Access modifiers===== The ''access modifiers'', or ''inheritance modifiers'', set the accessibility of classes, methods, and other members. Members marked as <code>public</code> can be reached from anywhere. If a class or its member does not have any modifiers, default access is assumed. <syntaxhighlight lang="java"> public class Foo { int go() { return 0; } private class Bar { } } </syntaxhighlight> The following table shows whether code within a class has access to the class or method depending on the accessing class location and the modifier for the accessed class or class member: {| class="wikitable" style="text-align: center;" !width="20%"|Modifier !width="20%"|Same class or nested class !width="20%"|Other class inside the same package !width="20%"|Extended Class inside another package !width="20%"|Non-extended inside another package |- !<code>private</code> |yes |no |no |no |- !default (package private) |yes |yes |no |no |- !<code>protected</code> |yes |yes |yes |no |- !<code>public</code> |yes |yes |yes |yes |- |} [[File:JavaAccessSpecifier.jpg|thumb|This image describes the class member scope within classes and packages.]] ====Constructors and initializers==== A [[Constructor (object-oriented programming)|constructor]] is a special method called when an object is initialized. Its purpose is to initialize the members of the object. The main differences between constructors and ordinary methods are that constructors are called only when an instance of the class is created and never return anything. Constructors are declared as common methods, but they are named after the class and no return type is specified: <syntaxhighlight lang="java"> class Foo { String str; Foo() { // Constructor with no arguments // Initialization } Foo(String str) { // Constructor with one argument this.str = str; } } </syntaxhighlight> Initializers are blocks of code that are executed when a class or an instance of a class is created. There are two kinds of initializers, ''static initializers'' and ''instance initializers''. Static initializers initialize static fields when the class is created. They are declared using the <code>static</code> keyword: <syntaxhighlight lang="java"> class Foo { static { // Initialization } } </syntaxhighlight> A class is created only once. Therefore, static initializers are not called more than once. On the contrary, instance initializers are automatically called before the call to a constructor every time an instance of the class is created. Unlike constructors instance initializers cannot take any arguments and generally they cannot throw any [[Exception handling#Checked exceptions|checked exceptions]] (except in several special cases). Instance initializers are declared in a block without any keywords: <syntaxhighlight lang="java"> class Foo { { // Initialization } } </syntaxhighlight> Since Java has a garbage collection mechanism, there are no [[Destructor (computer science)|destructors]]. However, every object has a <code>finalize()</code> method called prior to garbage collection, which can be [[method overriding|overridden]] to implement finalization. ====Methods==== All the statements in Java must reside within [[Method (computer programming)|methods]]. Methods are similar to functions except they belong to classes. A method has a return value, a name and usually some parameters initialized when it is called with some arguments. Similar to C++, methods returning nothing have return type declared as <code>void</code>. Unlike in C++, methods in Java are not allowed to have [[default argument]] values and methods are usually overloaded instead. <syntaxhighlight lang="java"> class Foo { int bar(int a, int b) { return (a*2) + b; } /* Overloaded method with the same name but different set of arguments */ int bar(int a) { return a*2; } } </syntaxhighlight> A method is called using <code>.</code> notation on an object, or in the case of a static method, also on the name of a class. <syntaxhighlight lang="java"> Foo foo = new Foo(); int result = foo.bar(7, 2); // Non-static method is called on foo int finalResult = Math.abs(result); // Static method call </syntaxhighlight> The <code>throws</code> keyword indicates that a method throws an exception. All checked exceptions must be listed in a comma-separated list. <syntaxhighlight lang="java"> void openStream() throws IOException, myException { // Indicates that IOException may be thrown } </syntaxhighlight> =====Modifiers===== * '''<code>abstract</code>''' - [[Abstract method]]s can be present only in [[abstract class]]es, such methods have no body and must be overridden in a subclass unless it is abstract itself. * '''<code>static</code>''' - Makes the method static and accessible without creation of a class instance. However static methods cannot access non-static members in the same class. * '''<code>final</code>''' - Declares that the method cannot be overridden in a subclass. * '''<code>native</code>''' - Indicates that this method is implemented through [[JNI]] in platform-dependent code. Actual implementation happens outside Java code, and such methods have no body. * '''<code>strictfp</code>''' - Declares strict conformance to [[IEEE 754]] in carrying out floating-point operations. * '''<code>synchronized</code>''' - Declares that a thread executing this method must acquire monitor. For <code>synchronized</code> methods the monitor is the class instance or <code>java.lang.Class</code> if the method is static. * Access modifiers - Identical to those used with classes. ======Final methods====== {{Excerpt|final (Java)#Final methods}} =====Varargs===== {{Main|Variadic function#In Java}} This language feature was introduced in [[J2SE 5.0]]. The last argument of the method may be declared as a variable arity parameter, in which case the method becomes a variable arity method (as opposed to fixed arity methods) or simply [[variadic function|varargs]] method. This allows one to pass a variable number of values, of the declared type, to the method as parameters - including no parameters. These values will be available inside the method as an array. <syntaxhighlight lang="java"> void printReport(String header, int... numbers) { //numbers represents varargs System.out.println(header); for (int num : numbers) { System.out.println(num); } } // Calling varargs method printReport("Report data", 74, 83, 25, 96); </syntaxhighlight> ====Fields==== Fields, or [[class variable]]s, can be declared inside the class body to store data. <syntaxhighlight lang="java"> class Foo { double bar; } </syntaxhighlight> Fields can be initialized directly when declared. <syntaxhighlight lang="java"> class Foo { double bar = 2.3; } </syntaxhighlight> =====Modifiers===== * '''<code>static</code>''' - Makes the field a static member. * '''<code>final</code>''' - Allows the field to be initialized only once in a constructor or inside initialization block or during its declaration, whichever is earlier. * '''<code>transient</code>''' - Indicates that this field will not be stored during [[serialization]]. * '''<code>volatile</code>''' - If a field is declared <code>volatile</code>, it is ensured that all threads see a consistent value for the variable. ====Inheritance==== Classes in Java can only [[Inheritance (object-oriented programming)|inherit]] from ''one'' class. A class can be derived from any class that is not marked as <code>final</code>. Inheritance is declared using the <code>extends</code> keyword. A class can reference itself using the <code>this</code> keyword and its direct superclass using the <code>super</code> keyword. <syntaxhighlight lang="java"> class Foo { } class Foobar extends Foo { } </syntaxhighlight> If a class does not specify its superclass, it implicitly inherits from <code>java.lang.Object</code> class. Thus all classes in Java are subclasses of <code>Object</code> class. If the superclass does not have a constructor without parameters the subclass must specify in its constructors what constructor of the superclass to use. For example: <syntaxhighlight lang="java"> class Foo { public Foo(int n) { // Do something with n } } class Foobar extends Foo { private int number; // Superclass does not have constructor without parameters // so we have to specify what constructor of our superclass to use and how public Foobar(int number) { super(number); this.number = number; } } </syntaxhighlight> =====Overriding methods===== Unlike C++, all non-<code>final</code> methods in Java are [[Virtual function|virtual]] and can be overridden by the inheriting classes. <syntaxhighlight lang="java"> class Operation { public int doSomething() { return 0; } } class NewOperation extends Operation { @Override public int doSomething() { return 1; } } </syntaxhighlight> =====Abstract classes===== An [http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.1.1 Abstract Class] is a class that is incomplete, or is to be considered incomplete, so cannot be instantiated. A class C has abstract methods if any of the following is true: * C explicitly contains a declaration of an abstract method. * Any of C's superclasses has an abstract method and C neither declares nor inherits a method that implements it. * A direct superinterface of C declares or inherits a method (which is therefore necessarily abstract) and C neither declares nor inherits a method that implements it. * A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class. <syntaxhighlight lang="java"> package org.dwwwp.test; /** * @author jcrypto */ public class AbstractClass { private static final String hello; static { System.out.println(AbstractClass.class.getName() + ": static block runtime"); hello = "hello from " + AbstractClass.class.getName(); } { System.out.println(AbstractClass.class.getName() + ": instance block runtime"); } public AbstractClass() { System.out.println(AbstractClass.class.getName() + ": constructor runtime"); } public static void hello() { System.out.println(hello); } } </syntaxhighlight> <syntaxhighlight lang="java"> package org.dwwwp.test; /** * @author jcrypto */ public class CustomClass extends AbstractClass { static { System.out.println(CustomClass.class.getName() + ": static block runtime"); } { System.out.println(CustomClass.class.getName() + ": instance block runtime"); } public CustomClass() { System.out.println(CustomClass.class.getName() + ": constructor runtime"); } public static void main(String[] args) { CustomClass nc = new CustomClass(); hello(); //AbstractClass.hello();//also valid } } </syntaxhighlight> Output: <syntaxhighlight lang="text"> org.dwwwp.test.AbstractClass: static block runtime org.dwwwp.test.CustomClass: static block runtime org.dwwwp.test.AbstractClass: instance block runtime org.dwwwp.test.AbstractClass: constructor runtime org.dwwwp.test.CustomClass: instance block runtime org.dwwwp.test.CustomClass: constructor runtime hello from org.dwwwp.test.AbstractClass </syntaxhighlight> ====Enumerations==== This language feature was introduced in [[J2SE 5.0]]. Technically enumerations are a kind of class containing enum constants in its body. Each enum constant defines an instance of the enum type. Enumeration classes cannot be instantiated anywhere except in the enumeration class itself. <syntaxhighlight lang="java"> enum Season { WINTER, SPRING, SUMMER, AUTUMN } </syntaxhighlight> Enum constants are allowed to have constructors, which are called when the class is loaded: <syntaxhighlight lang="java"> public enum Season { WINTER("Cold"), SPRING("Warmer"), SUMMER("Hot"), AUTUMN("Cooler"); Season(String description) { this.description = description; } private final String description; public String getDescription() { return description; } } </syntaxhighlight> Enumerations can have class bodies, in which case they are treated like anonymous classes extending the enum class: <syntaxhighlight lang="java"> public enum Season { WINTER { String getDescription() {return "cold";} }, SPRING { String getDescription() {return "warmer";} }, SUMMER { String getDescription() {return "hot";} }, FALL { String getDescription() {return "cooler";} }; } </syntaxhighlight> ===Interfaces=== [[Interface (Java)|Interfaces]] are types which contain no fields and usually define a number of methods without an actual implementation. They are useful to define a contract with any number of different implementations. Every interface is implicitly abstract. Interface methods are allowed to have a subset of access modifiers depending on the language version, <code>strictfp</code>, which has the same effect as for classes, and also <code>static</code> since Java SE 8. <syntaxhighlight lang="java"> interface ActionListener { int ACTION_ADD = 0; int ACTION_REMOVE = 1; void actionSelected(int action); } </syntaxhighlight> ====Implementing an interface==== An interface is implemented by a class using the <code>implements</code> keyword. It is allowed to implement more than one interface, in which case they are written after <code>implements</code> keyword in a comma-separated list. A class implementing an interface must override all its methods, otherwise it must be declared as abstract. <syntaxhighlight lang="java"> interface RequestListener { int requestReceived(); } class ActionHandler implements ActionListener, RequestListener { public void actionSelected(int action) { } public int requestReceived() { } } //Calling method defined by interface RequestListener listener = new ActionHandler(); /*ActionHandler can be represented as RequestListener...*/ listener.requestReceived(); /*...and thus is known to implement requestReceived() method*/ </syntaxhighlight> ====Functional interfaces and lambda expressions==== These features were introduced with the release of Java SE 8. An interface automatically becomes a functional interface if it defines only one method. In this case an implementation can be represented as a lambda expression instead of implementing it in a new class, thus greatly simplifying writing code in the [[functional programming|functional style]]. Functional interfaces can optionally be annotated with the <code>[[@FunctionalInterface]]</code> annotation, which will tell the compiler to check whether the interface actually conforms to a definition of a functional interface. <syntaxhighlight lang="java"> // A functional interface @FunctionalInterface interface Calculation { int calculate(int someNumber, int someOtherNumber); } // A method which accepts this interface as a parameter int runCalculation(Calculation calculation) { return calculation.calculate(1, 2); } // Using a lambda to call the method runCalculation((number, otherNumber) -> number + otherNumber); // Equivalent code which uses an anonymous class instead runCalculation(new Calculation() { @Override public int calculate(int someNumber, int someOtherNumber) { return someNumber + someOtherNumber; } }) </syntaxhighlight> Lambda's parameters types do not have to be fully specified and can be inferred from the interface it implements. Lambda's body can be written without a body block and a <code>return</code> statement if it is only an expression. Also, for those interfaces which only have a single parameter in the method, round brackets can be omitted.<ref>{{Cite web|title=Lambda Expressions (The Javaβ’ Tutorials > Learning the Java Language > Classes and Objects)|url=https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html|access-date=August 8, 2021|website=docs.oracle.com|archive-date=June 16, 2020|archive-url=https://web.archive.org/web/20200616055353/https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html|url-status=live}}</ref> <syntaxhighlight lang="java"> // Same call as above, but with fully specified types and a body block runCalculation((int number, int otherNumber) -> { return number + otherNumber; }); // A functional interface with a method which has only a single parameter interface StringExtender { String extendString(String input); } // Initializing a variable of this type by using a lambda StringExtender extender = input -> input + " Extended"; </syntaxhighlight> ====Method references==== It is not necessary to use lambdas when there already is a named method compatible with the interface. This method can be passed instead of a lambda using a method reference. There are several types of method references: {| class="wikitable" |- ! Reference type !! Example !! Equivalent lambda |- | Static || <code>Integer::sum</code> || <code>(number, otherNumber) -> number + otherNumber</code> |- | Bound || <code>"LongString"::substring</code> || <code>index -> "LongString".substring(index)</code> |- | Unbound || <code>String::isEmpty</code> || <code>string -> string.isEmpty()</code> |- | Class constructor || <code>ArrayList<String>::new</code> || <code>capacity -> new ArrayList<String>(capacity)</code> |- | Array constructor || <code>String[]::new</code> || <code>size -> new String[size]</code> |} The code above which calls <code>runCalculation</code> could be replaced with the following using the method references: <syntaxhighlight lang="java> runCalculation(Integer::sum); </syntaxhighlight> ====Inheritance==== Interfaces can inherit from other interfaces just like classes. Unlike classes it is allowed to inherit from multiple interfaces. However, it is possible that several interfaces have a field with the same name, in which case it becomes a single ambiguous member, which cannot be accessed. <syntaxhighlight lang="java"> /* Class implementing this interface must implement methods of both ActionListener and RequestListener */ interface EventListener extends ActionListener, RequestListener { } </syntaxhighlight> ====Default methods==== Java SE 8 introduced default methods to interfaces which allows developers to add new methods to existing interfaces without breaking compatibility with the classes already implementing the interface. Unlike regular interface methods, default methods have a body which will get called in the case if the implementing class does not override it. <syntaxhighlight lang="java"> interface StringManipulator { String extendString(String input); // A method which is optional to implement default String shortenString(String input) { return input.substring(1); } } // This is a valid class despite not implementing all the methods class PartialStringManipulator implements StringManipulator { @Override public String extendString(String input) { return input + " Extended"; } } </syntaxhighlight> ====Static methods==== {{Main|Method (computer programming)#Static methods}} Static methods is another language feature introduced in Java SE 8. They behave in exactly the same way as in the classes. <syntaxhighlight lang="java"> interface StringUtils { static String shortenByOneSymbol(String input) { return input.substring(1); } } StringUtils.shortenByOneSymbol("Test"); </syntaxhighlight> ====Private methods==== Private methods were added in the Java 9 release. An interface can have a method with a body marked as private, in which case it will not be visible to inheriting classes. It can be called from default methods for the purposes of code reuse. <syntaxhighlight lang="java"> interface Logger { default void logError() { log(Level.ERROR); } default void logInfo() { log(Level.INFO); } private void log(Level level) { SystemLogger.log(level.id); } } </syntaxhighlight> ====Annotations==== {{Main|Java annotation}} Annotations in Java are a way to embed [[metadata]] into code. This language feature was introduced in [[J2SE 5.0]]. =====Annotation types===== Java has a set of predefined annotation types, but it is allowed to define new ones. An annotation type declaration is a special type of an interface declaration. They are declared in the same way as the interfaces, except the <code>interface</code> keyword is preceded by the <code>@</code> sign. All annotations are implicitly extended from <code>java.lang.annotation.Annotation</code> and cannot be extended from anything else. <syntaxhighlight lang="java"> @interface BlockingOperations { } </syntaxhighlight> Annotations may have the same declarations in the body as the common interfaces, in addition they are allowed to include enums and annotations. The main difference is that abstract method declarations must not have any parameters or throw any exceptions. Also they may have a default value, which is declared using the <code>default</code> keyword after the method name: <syntaxhighlight lang="java"> @interface BlockingOperations { boolean fileSystemOperations(); boolean networkOperations() default false; } </syntaxhighlight> =====Usage of annotations===== Annotations may be used in any kind of declaration, whether it is package, class (including enums), interface (including annotations), field, method, parameter, constructor, or local variable. Also they can be used with enum constants. Annotations are declared using the <code>@</code> sign preceding annotation type name, after which element-value pairs are written inside brackets. All elements with no default value must be assigned a value. <syntaxhighlight lang="java"> @BlockingOperations(/*mandatory*/ fileSystemOperations, /*optional*/ networkOperations = true) void openOutputStream() { //Annotated method } </syntaxhighlight> Besides the generic form, there are two other forms to declare an annotation, which are shorthands. ''Marker annotation'' is a short form, it is used when no values are assigned to elements: <syntaxhighlight lang="java"> @Unused // Shorthand for @Unused() void travelToJupiter() { } </syntaxhighlight> The other short form is called ''single element annotation''. It is used with annotations types containing only one element or in the case when multiple elements are present, but only one elements lacks a default value. In single element annotation form the element name is omitted and only value is written instead: <syntaxhighlight lang="java"> /* Equivalent for @BlockingOperations(fileSystemOperations = true). networkOperations has a default value and does not have to be assigned a value */ @BlockingOperations(true) void openOutputStream() { } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)