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!
==Control structures== ===Conditional statements=== ====<code>if</code> statement==== {{Main|Conditional (computer programming)#C-like languages}} [[Conditional (computer programming)|if statements]] in Java are similar to those in C and use the same syntax: <syntaxhighlight lang="java"> if (i == 3) { doSomething(); } </syntaxhighlight> <code>if</code> statement may include optional <code>else</code> block, in which case it becomes an if-then-else statement: <syntaxhighlight lang="java"> if (i == 3) { doSomething(); } else { doSomethingElse(); } </syntaxhighlight> Like C, else-if construction does not involve any special keywords, it is formed as a sequence of separate if-then-else statements: <syntaxhighlight lang="java"> if (i == 3) { doSomething(); } else if (i == 2) { doSomethingElse(); } else { doSomethingDifferent(); } </syntaxhighlight> Also, a [[?:]] operator can be used in place of simple if statement, for example <syntaxhighlight lang="java"> int a = 1; int b = 2; int minVal = (a < b) ? a : b; </syntaxhighlight> ====<code>switch</code> statement==== [[Switch statement]]s in Java can use <code>byte</code>, <code>short</code>, <code>char</code>, and <code>int</code> (not <code>long</code>) primitive data types or their corresponding wrapper types. Starting with J2SE 5.0, it is possible to use [[Enumerated type|enum types]]. Starting with Java SE 7, it is possible to use Strings.<ref>{{Cite web|title=The switch Statement (The Javaβ’ Tutorials > Learning the Java Language > Language Basics)|url=https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html|access-date=August 15, 2021|website=docs.oracle.com|archive-date=March 15, 2010|archive-url=https://web.archive.org/web/20100315060844/http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html|url-status=live}}</ref> Other [[reference type]]s cannot be used in <code>switch</code> statements. Possible values are listed using <code>case</code> labels. These labels in Java may contain only constants (including enum constants and string constants). Execution will start after the label corresponding to the expression inside the brackets. An optional <code>default</code> label may be present to declare that the code following it will be executed if none of the case labels correspond to the expression. Code for each label ends with the <code>break</code> keyword. It is possible to omit it causing the execution to proceed to the next label, however, a warning will usually be reported during compilation. <syntaxhighlight lang="java"> 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; } </syntaxhighlight> =====<code>switch</code> expressions===== Since Java 14 it has become possible to use switch expressions, which use the new arrow syntax: <syntaxhighlight lang="java"> var result = switch (ch) { case 'A' -> Result.GREAT; case 'B', 'C' -> Result.FINE; default -> throw new ThisIsNoGoodException(); }; </syntaxhighlight> Alternatively, there is a possibility to express the same with the <code>yield</code> statement, although it is recommended to prefer the arrow syntax because it avoids the problem of accidental fall throughs. <syntaxhighlight lang="java"> var result = switch (ch) { case 'A': yield Result.GREAT; case 'B': case 'C': yield Result.FINE; default: throw new ThisIsNoGoodException(); }; </syntaxhighlight> ===Iteration statements=== 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 Boolean, meaning C's<syntaxhighlight lang="c"> while (1) { doSomething(); } </syntaxhighlight>results in a compilation error. ====<code>while</code> loop==== {{Main|While loop}} In the <code>while</code> loop, the test is done before each iteration. <syntaxhighlight lang="java"> while (i < 10) { doSomething(); } </syntaxhighlight> ====<code>do ... while</code> loop==== In the <code>do ... while</code> loop, the test is done after each iteration. Consequently, the code is always executed at least once. <syntaxhighlight lang="java"> // doSomething() is called at least once do { doSomething(); } while (i < 10); </syntaxhighlight> ====<code>for</code> loop==== <code>for</code> 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. <syntaxhighlight lang="java"> for (int i = 0; i < 10; i++) { doSomething(); } // A more complex loop using two variables for (int i = 0, j = 9; i < 10; i++, j -= 3) { doSomething(); } </syntaxhighlight> Like C, all three expressions are optional. The following loop is infinite: <syntaxhighlight lang="java"> for (;;) { doSomething(); } </syntaxhighlight> ====Enhanced <code>for</code> loop==== {{Main|Enhanced for loop}} [[enhanced for loop|Enhanced <code>for</code> loop]]s have been available since [[J2SE 5.0]]. This type of loop uses built-in iterators over arrays and collections to return each item in the given collection. Every element is returned and reachable in the context of the code block. When the block is executed, the next item is returned until there are no items remaining. Unlike [[C Sharp (programming language)|C#]], this kind of loop does not involve a special keyword, but instead uses a different notation style. <syntaxhighlight lang="java"> for (int i : intArray) { doSomething(i); } </syntaxhighlight> ===Jump statements=== ====Labels==== Labels are given points in code used by <code>break</code> and <code>continue</code> statements. The Java <code>goto</code> keyword cannot be used to jump to specific points in code. <syntaxhighlight lang="java"> start: someMethod(); </syntaxhighlight> ====<code>break</code> statement==== The <code>break</code> statement breaks out of the closest loop or <code>switch</code> statement. Execution continues in the statement after the terminated statement, if any. <syntaxhighlight lang="java"> for (int i = 0; i < 10; i++) { while (true) { break; } // Will break to this point } </syntaxhighlight> It is possible to break out of the outer loop using labels: <syntaxhighlight lang="java"> outer: for (int i = 0; i < 10; i++) { while (true) { break outer; } } // Will break to this point </syntaxhighlight> ====<code>continue</code> statement==== The <code>continue</code> statement discontinues the current iteration of the current control statement and begins the next iteration. The following <code>while</code> loop in the code below reads characters by calling <code>getChar()</code>, skipping the statements in the body of the loop if the characters are spaces: <syntaxhighlight lang="java"> int ch; while (ch == getChar()) { if (ch == ' ') { continue; // Skips the rest of the while-loop } // Rest of the while-loop, will not be reached if ch == ' ' doSomething(); } </syntaxhighlight> Labels can be specified in <code>continue</code> statements and <code>break</code> statements: <syntaxhighlight lang="java"> outer: for (String str : stringsArr) { char[] strChars = str.toCharArray(); for (char ch : strChars) { if (ch == ' ') { /* Continues the outer cycle and the next string is retrieved from stringsArr */ continue outer; } doSomething(ch); } } </syntaxhighlight> ====<code>return</code> statement==== The <code>return</code> statement is used to end method execution and to return a value. A value returned by the method is written after the <code>return</code> keyword. If the method returns anything but <code>void</code>, it must use the <code>return</code> statement to return some value. <syntaxhighlight lang="java"> void doSomething(boolean streamClosed) { // If streamClosed is true, execution is stopped if (streamClosed) { return; } readFromStream(); } int calculateSum(int a, int b) { int result = a + b; return result; } </syntaxhighlight> <code>return</code> statement ends execution immediately, except for one case: if the statement is encountered within a <code>try</code> block and it is complemented by a <code>finally</code>, control is passed to the <code>finally</code> block. <syntaxhighlight lang="java"> void doSomething(boolean streamClosed) { try { if (streamClosed) { return; } readFromStream(); } finally { /* Will be called last even if readFromStream() was not called */ freeResources(); } } </syntaxhighlight> ===Exception handling statements=== ====<code>try-catch-finally</code> statements==== Exceptions are managed within <code>try</code> ... <code>catch</code> blocks. <syntaxhighlight lang="java"> try { // Statements that may throw exceptions methodThrowingExceptions(); } catch (Exception ex) { // Exception caught and handled here reportException(ex); } finally { // Statements always executed after the try/catch blocks freeResources(); } </syntaxhighlight> The statements within the <code>try</code> block are executed, and if any of them throws an exception, execution of the block is discontinued and the exception is handled by the <code>catch</code> block. There may be multiple <code>catch</code> blocks, in which case the first block with an exception variable whose type matches the type of the thrown exception is executed. Java SE 7 also introduced multi-catch clauses besides uni-catch clauses. This type of catch clauses allows Java to handle different types of exceptions in a single block provided they are not subclasses of each other. <syntaxhighlight lang="java"> try { methodThrowingExceptions(); } catch (IOException | IllegalArgumentException ex) { //Both IOException and IllegalArgumentException will be caught and handled here reportException(ex); } </syntaxhighlight> If no <code>catch</code> block matches the type of the thrown exception, the execution of the outer block (or method) containing the <code>try</code> ... <code>catch</code> 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 <code>catch</code> block is found within one of the currently active methods. If the exception propagates all the way up to the top-most <code>main</code> method without a matching <code>catch</code> block being found, a textual description of the exception is written to the standard output stream. The statements within the <code>finally</code> block are always executed after the <code>try</code> and <code>catch</code> blocks, whether or not an exception was thrown and even if a <code>return</code> statement was reached. Such blocks are useful for providing cleanup code that is guaranteed to always be executed. The <code>catch</code> and <code>finally</code> blocks are optional, but at least one or the other must be present following the <code>try</code> block. ====<code>try</code>-with-resources statements==== <code>try</code>-with-resources statements are a special type of <code>try-catch-finally</code> statements introduced as an implementation of the [[dispose pattern]] in Java SE 7. In a <code>try</code>-with-resources statement the <code>try</code> keyword is followed by initialization of one or more resources that are released automatically when the <code>try</code> block execution is finished. Resources must implement <code>java.lang.AutoCloseable</code>. <code>try</code>-with-resources statements are not required to have a <code>catch</code> or <code>finally</code> block unlike normal <code>try-catch-finally</code> statements. <syntaxhighlight lang="java"> try (FileOutputStream fos = new FileOutputStream("filename"); XMLEncoder xEnc = new XMLEncoder(fos)) { xEnc.writeObject(object); } catch (IOException ex) { Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex); } </syntaxhighlight> Since Java 9 it is possible to use already declared variables: <syntaxhighlight lang="java"> FileOutputStream fos = new FileOutputStream("filename"); XMLEncoder xEnc = new XMLEncoder(fos); try (fos; xEnc) { xEnc.writeObject(object); } catch (IOException ex) { Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex); } </syntaxhighlight> ====<code>throw</code> statement==== The <code>throw</code> statement is used to throw an exception and end the execution of the block or method. The thrown exception instance is written after the <code>throw</code> statement. <syntaxhighlight lang="java"> void methodThrowingExceptions(Object obj) { if (obj == null) { // Throws exception of NullPointerException type throw new NullPointerException(); } // Will not be called, if object is null doSomethingWithObject(obj); } </syntaxhighlight> ===Thread concurrency control=== Java has built-in tools for [[Thread (computing)|multi-thread programming]]. For the purposes of thread [[Synchronization (computer science)|synchronization]] the <code>synchronized</code> statement is included in Java language. To make a code block synchronized, it is preceded by the <code>synchronized</code> keyword followed by the lock object inside the brackets. When the executing thread reaches the synchronized block, it acquires a [[mutual exclusion]] lock, executes the block, then releases the lock. No threads may enter this block until the lock is released. Any non-null reference type may be used as the lock. <syntaxhighlight lang="java"> /* Acquires lock on someObject. It must be of a reference type and must be non-null */ synchronized (someObject) { // Synchronized statements } </syntaxhighlight> ===<code>assert</code> statement=== <code>assert</code> statements have been available since [[J2SE 1.4]]. These types of statements are used to make [[assertion (computing)|assertion]]s in the source code, which can be turned on and off during execution for specific classes or packages. To declare an assertion the <code>assert</code> keyword is used followed by a conditional expression. If it evaluates to <code>false</code> when the statement is executed, an exception is thrown. This statement can include a colon followed by another expression, which will act as the exception's detail message. <syntaxhighlight lang="java"> // If n equals 0, AssertionError is thrown assert n != 0; /* If n equals 0, AssertionError will be thrown with the message after the colon */ assert n != 0 : "n was equal to zero"; </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)