FazBrowse Wikipedia Viewer | Main Page |
Search Wikipedia:
|
Viewing: https://en.wikipedia.org/wiki/Java_syntax#Varargs

Java syntax

Contents
    Identifier
    Keywords
        Keywords
        Reserved identifiers
        Unused
        Type inference
    Code blocks
    Comments
    Universal types
        java.lang.Record
        java.lang.Throwable
        java.lang.Math
    Modules
    Iteration statements
        for loop
    Jump statements
        Labels
        continue statement
        try-with-resources statements
        throw statement

A snippet of Java code.

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

The syntax is mostly derived from C and C++. Unlike C++, Java has no global functions or variables, but has data members which are also regarded as global variables. All code belongs to classes and all values are objects. The only exception is the primitive data types, which are not considered to be objects for performance reasons (though can be automatically converted to objects and vice versa via autoboxing). Some features like operator overloading or unsigned integer data types are omitted to simplify the language and avoid possible programming mistakes.

The Java syntax has been gradually extended in the course of numerous major JDK releases, and now supports abilities such as generic programming and anonymous functions (function literals, called lambda expressions in Java). Since 2017, a new JDK version is released twice a year.

voidmain(){ IO.println("Hello World!"); }

Identifier

edit

An identifier is the name of an element in the code. There are certain standard naming conventions to follow when selecting names for elements. Identifiers in Java are case-sensitive.

An identifier can contain:

Type inference

edit
importjava.io.FileOutputStream; // stream will have the FileOutputStream type as inferred from its initializer varstream=newFileOutputStream("file.txt"); // An equivalent declaration with an explicit type FileOutputStreamstream=newFileOutputStream("file.txt");

However, unlike C++, the return type of a function cannot be inferred.

Code blocks

edit

The separators voiddoSomething(){ inta; { intb; a=1; } a=2; b=3;// Illegal because the variable b is declared in an inner scope.. }

Comments

edit

Java has three kinds of comments: traditional comments, end-of-line comments and documentation comments.

Traditional comments, also known as block comments, start with /* and end with */, they may span across multiple lines. This type of comment was derived from C and C++.

/** * This is a documentation comment. * * @author John Doe */

Universal types

edit

Classes in the package java.lang.Object is Java's top type. It is implicitly the superclass of all classes that do not declare any parent class (thus all classes in Java inherit from java.lang.Object). All values can be converted to this type, although for primitive values this involves autoboxing.

java.lang.Record

edit

All records implicitly extend edit

All enumerated types (enums) in Java implicitly extend java.lang.Class is a class that represents a class or interface in the application at runtime. It cannot be constructed via direct instantiation, but is rather created by the JVM when a class is derived from the bytes of a .class file. A class literal can be obtained through X.class on such a class X. For instance, String.class returns Class<String>. An unknown class being modeled can be represented as Class<?> (where ? denotes a wildcard).

While X.class appears to be accessing a field named "java.lang.CharSequence, so chars in the java.lang.String can be accessed by the method charAt().

java.lang.Throwable

edit

java.lang.Exception is the supertype of all exception classes and extends java.lang.Throwable. It is used to indicate conditions that a reasonable application may have reason to catch.

java.lang.Math

edit

java.io.InputStream is a fully qualified class name for the class InputStream which is located in the package .java extension and put into nested folders corresponding to the package name. The above class org.wikipedia.examples.Foo will have the following path: org/wikipedia/examples/Foo.java.

Modules

edit
module-info.java at the root of the module's source-file hierarchy. The JDK will verify dependencies and interactions between modules both at compile-time and runtime.

For example, the following module declaration declares that the module org.wikipedia.bar depends on another org.wikipedia.baz module, and exports the following packages: org.wikipedia.bar.alpha and org.wikipedia.bar.beta:

/** * This form of importing classes makes all classes * in package java.util available by name, could be used instead of the * import declaration in the previous example. */ importjava.util.*;

A wildcard import may possibly import nothing, if no symbols exist in that package. For example, statements like

This type of declaration has been available since J2SE 5.0. Static import declarations allow access to static members defined in another class, interface, annotation, or enum; without specifying the class name:

publicenumColors{ RED,BLUE,GREEN };

It is possible to use static import declarations in another class to retrieve the enum constants:

importjava.sql.*; importjavax.sql.*; // Remaining indirect exports from java.logging, java.transaction.xa, and java.xml

Similarly, if(i==3){ doSomething(); }else{ doSomethingElse(); }

Like C, else-if construction does not involve any special keywords, it is formed as a sequence of separate if-then-else statements:

switch(ch){ case'A': doSomething();// Triggered if ch == 'A' break; case'B': case'C': doSomethingElse();// Triggered if ch == 'B' or ch == 'C' break; default: doSomethingDifferent();// Triggered in any other case break; }

Unlike C and C++, whose switch only supports integral types, Java's switch supports strings:

Resultresult=switch(ch){ case'A': yieldResult.GREAT; case'B': case'C': yieldResult.FINE; default: thrownewException(); };
Pattern matching
edit

The switch block can be used for pattern matching. Cases can be guarded with a when clause.

c when c.isEmpty() ->\n IO.println(\"An empty collection of some kind\");\n case String s when s.length() > 50 ->\n IO.println(\"A string longer than 50 characters\");\n case String s ->\n IO.println(\"A string: \" + s);\n default ->\n IO.println(\"Some other object\");\n }\n}\n"}}'>importjava.util.Collection; voidhandleInput(Objectobj){ switch(obj){ caseCollection<?>cwhenc.isEmpty()-> IO.println("An empty collection of some kind"); caseStringswhens.length()>50-> IO.println("A string longer than 50 characters"); caseStrings-> IO.println("A string: "+s); default-> IO.println("Some other object"); } }

Records can be pattern matched over like so:

\n IO.println(\"The point is on the diagonal line at \" + x);\n case Point(int x, int y) when x > 0 && y > 0 ->\n IO.println(\"The point is somewhere in the first quadrant\");\n case Point p ->\n IO.println(\"The point is somewhere else\");\n default ->\n IO.println(\"Not a point\");\n }\n}\n"}}'>record Point(intx,inty){} voidlocatePoint(Objectobj){ switch(obj){ casePoint(intx,inty)whenx==y-> IO.println("The point is on the diagonal line at "+x); casePoint(intx,inty)whenx>0&&y>0-> IO.println("The point is somewhere in the first quadrant"); casePointp-> IO.println("The point is somewhere else"); default-> IO.println("Not a point"); } }

Nested patterns are supported, like the following example. A "wildcard" placeholder, expressed with _, is used to suppress a variable or object that does not need identification.

50.0 ->\n System.out.printf(\"The box '%s' is too tall to fit on the shelf!\", label);\n case Box(String label, _) ->\n System.out.printf(\"The box '%s' fits standard dimensions.\");\n default ->\n IO.println(\"Not a box.\");\n }\n}\n"}}'>record Dimensions(doublewidth,doubleheight){} record Box(Stringlabel,Dimensionsdims){} voidinspectBox(Objectobj){ switch(obj){ caseBox(Stringlabel,Dimensions(_,doubleheight))whenheight>50.0-> System.out.printf("The box '%s' is too tall to fit on the shelf!",label); caseBox(Stringlabel,_)-> System.out.printf("The box '%s' fits standard dimensions."); default-> IO.println("Not a box."); } }

Iteration statements

edit

Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true. Since J2SE 5.0, Java has four forms of such statements. The condition must have type boolean or // doSomething() is called at least once do{ doSomething(); }while(i<10);

for loop

edit

for loops in Java include an initializer, a condition and a counter expression. It is possible to include several expressions of the same kind using comma as delimiter (except in the condition). However, unlike C, the comma is just a delimiter and not an operator.

for(inti:intArray){ doSomething(i); }

Jump statements

edit

Labels

edit

Labels are given points in code used by break and continue statements. While goto is a reserved keyword in Java, it cannot be used to jump to specific points in code (in fact, it has no use at all).

outer: for(inti=0;i<10;i++){ while(true){ breakouter; } } // Will break to this point

continue statement

edit

The continue statement discontinues the current iteration of the current control statement and begins the next iteration. The following while loop in the code below reads characters by calling getChar(), skipping the statements in the body of the loop if the characters are spaces:

voiddoSomething(booleanstreamClosed){ // If streamClosed is true, execution is stopped if(streamClosed){ return; } readFromStream(); } intcalculateSum(inta,intb){ intresult=a+b; returnresult; }

return statement ends execution immediately, except for one case: if the statement is encountered within a try block and it is complemented by a finally, control is passed to the finally block.

importjava.net.HttpRetryException; importjava.net.http.HttpTimeoutException; voidmakeRequest()throwsHttpRetryException,HttpTimeoutException{ // ... } voidmain(String[]args){ try{ methodThrowingExceptions(); }catch(HttpRetryException|HttpTimeoutExceptione){ // Both HttpRetryException and HttpTimeoutException will be caught and handled here // This in fact reduces to just java.io.IOException. reportException(e); } }

If no catch block matches the type of the thrown exception, the execution of the outer block (or method) containing the try-catch statement is discontinued, and the exception is passed up and outside the containing block (or method). The exception is propagated upwards through the call stack until a matching catch block is found within one of the currently active methods. If the exception propagates all the way up to the top-most main method without a matching catch block being found, a textual description of the exception is written to the standard output stream.

The statements within the finally block are always executed after the try and catch blocks, whether or not an exception was thrown and even if a return statement was reached. Such blocks are useful for providing cleanup code that is guaranteed to always be executed.

The catch and finally blocks are optional, but at least one or the other must be present following the try block.

try-with-resources statements

edit

try-with-resources statements are a special type of try-catch-finally statements introduced as an implementation of the dispose pattern in Java SE 7. In a try-with-resources statement the try keyword is followed by initialization of one or more resources that are released automatically when the try block execution is finished. Resources must implement importjava.beans.XMLEncoder; importjava.io.FileOutputStream; importjava.io.IOException; importjava.util.logging.Level; importjava.util.logging.Logger; FileOutputStreamfos=newFileOutputStream("filename"); XMLEncoderxEnc=newXMLEncoder(fos); try(fos;xEnc){ xEnc.writeObject(object); }catch(IOExceptione){ Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE,null,e); }

throw statement

edit

The throw statement is used to throw an exception and end the execution of the block or method. The thrown exception instance is written after the throw statement.

Java offers threads of execution through the class Threadt=newThread(()->{ IO.println("Running"); }); t.start();

Daemon threads are threads which run in the background, for example garbage collectors or monitoring threads. The JVM exits when only daemon threads remain.

The current thread may be accessed with the currentThread() method.

Historically, an error java.lang.concurrent, as well as atomicity features (java.lang.Thread, another class


View original on Wikipedia | Back | FazBrowse Home