`==` tests for reference equality (whether they are the same object).

`.equals()` tests for value equality (whether they contain the same data).

[Objects.equals()](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals(java.lang.Object,%20java.lang.Object)) checks for `null` before calling `.equals()` so you don't have to (available as of JDK7, also available in [Guava](https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained#equals)).

Consequently, if you want to test whether two strings have the same value you will probably want to use `Objects.equals()`.

```java<br>// These two have the same value<br>new String("test").equals("test") // --> true<br><br>// ... but they are not the same object<br>new String("test") == "test" // --> false<br><br>// ... neither are these<br>new String("test") == new String("test") // --> false<br><br>// ... but these are because literals are interned by<br>// the compiler and thus refer to the same object<br>"test" == "test" // --> true<br><br>// ... string literals are concatenated by the compiler<br>// and the results are interned.<br>"test" == "te" + "st" // --> true<br><br>// ... but you should really just call Objects.equals()<br>Objects.equals("test", new String("test")) // --> true<br>Objects.equals(null, "test") // --> false<br>Objects.equals(null, null) // --> true<br><br>```

From the Java Language Specification [JLS 15.21.3. Reference Equality Operators `==` and `!=`](https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.21.3):

> While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters (§3.10.5, §3.10.6). The contents of two strings s and t can be tested for equality by the method invocation s.equals(t).
>

You almost **always** want to use `Objects.equals()`. In the **rare** situation where you **know** you're dealing with [interned](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#intern--) strings, you *can* use `==`.

From [JLS 3.10.5. *String Literals*](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5):

> Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
>

Similar examples can also be found in [JLS 3.10.5-1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#d5e1634).

### Other Methods To Consider

[String.equalsIgnoreCase()](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equalsIgnoreCase-java.lang.String-) value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see [this question](https://stackoverflow.com/questions/44238749/equalsignorecase-not-working-as-intended).

[String.contentEquals()](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#contentEquals-java.lang.CharSequence-) compares the content of the `String` with the content of any `CharSequence` (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.


```java<br>// These two have the same value<br>new String("test").equals("test") // --> true<br><br>// ... but they are not the same object<br>new String("test") == "test" // --> false<br><br>// ... neither are these<br>new String("test") == new String("test") // --> false<br><br>// ... but these are because literals are interned by<br>// the compiler and thus refer to the same object<br>"test" == "test" // --> true<br><br>// ... string literals are concatenated by the compiler<br>// and the results are interned.<br>"test" == "te" + "st" // --> true<br><br>// ... but you should really just call Objects.equals()<br>Objects.equals("test", new String("test")) // --> true<br>Objects.equals(null, "test") // --> false<br>Objects.equals(null, null) // --> true<br><br>```


### Method Detail

- equals

    ```<br>    public static boolean equals(Object a,<br>    Object b)<br>    ```

    Returns `true` if the arguments are equal to each other and `false` otherwise. Consequently, if both arguments are `null`, `true` is returned and if exactly one argument is `null`, `false` is returned. Otherwise, equality is determined by using the [`equals`](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)) method of the first argument.

    **Parameters:**`a` - an object`b` - an object to be compared with `a` for equality**Returns:**`true` if the arguments are equal to each other and `false` otherwise**See Also:**[`Object.equals(Object)`](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object))


Since Java 5 you can use [`Arrays.toString(arr)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#toString(int%5B%5D)) or [`Arrays.deepToString(arr)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#deepToString(java.lang.Object%5B%5D)) for arrays within arrays. Note that the `Object[]` version calls `.toString()` on each object in the array. The output is even decorated in the exact way you're asking.

Examples:

- Simple Array:

    ```java<br>    String[] array = new String[] {"John", "Mary", "Bob"};<br>    System.out.println(Arrays.toString(array));<br>    <br>    ```

    Output:

    ```java<br>    [John, Mary, Bob]<br>    <br>    ```

- Nested Array:

    ```java<br>    String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};<br>    // Gives undesired output:<br>    System.out.println(Arrays.toString(deepArray));<br>    // Gives the desired output:<br>    System.out.println(Arrays.deepToString(deepArray));<br>    <br>    ```

    Output:

    ```java<br>    [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]<br>    [[John, Mary], [Alice, Bob]]<br>    <br>    ```

- `double` Array:

    ```java<br>    double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };<br>    System.out.println(Arrays.toString(doubleArray));<br>    <br>    ```

    Output:

    ```java<br>    [7.0, 9.0, 5.0, 1.0, 3.0 ]<br>    <br>    ```

- `int` Array:

    ```java<br>    int[] intArray = { 7, 9, 5, 1, 3 };<br>    System.out.println(Arrays.toString(intArray));<br>    <br>    ```

    Output:

    ```java<br>    [7, 9, 5, 1, 3 ]<br>    ```


<br>    ```java<br>    String[] array = new String[] {"John", "Mary", "Bob"};<br>    System.out.println(Arrays.toString(array));<br>    <br>    ```


- toString

    public static [String](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html) toString(int[] a)

    Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets (`"[]"`). Adjacent elements are separated by the characters `", "` (a comma followed by a space). Elements are converted to strings as by `String.valueOf(int)`. Returns `"null"` if `a` is `null`.

    **Parameters:**`a` - the array whose string representation to return**Returns:**a string representation of `a`**Since:**1.5


Use the appropriately named method [`String#split()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#split(java.lang.String)).

```java<br>String string = "004-034556";<br>String[] parts = string.split("-");<br>String part1 = parts[0]; // 004<br>String part2 = parts[1]; // 034556<br><br>```

Note that `split`'s argument is assumed to be a [regular expression](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#sum), so remember to escape [special characters](https://www.regular-expressions.info/characters.html) if necessary.

> there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".
>

For instance, to split on a period/dot `.` (which means "[any character](https://www.regular-expressions.info/dot.html)" in regex), use either [backslash `\`](https://www.regular-expressions.info/characters.html) to escape the individual special character like so `split("\\.")`, or use [character class `[]`](https://www.regular-expressions.info/charclass.html) to represent literal character(s) like so `split("[.]")`, or use [`Pattern#quote()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#quote(java.lang.String)) to escape the entire string like so `split(Pattern.quote("."))`.

```java<br>String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.<br><br>```

To test beforehand if the string contains certain character(s), just use [`String#contains()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#contains(java.lang.CharSequence)).

```java<br>if (string.contains("-")) {<br>    // Split it.<br>} else {<br>    throw new IllegalArgumentException("String " + string + " does not contain -");<br>}<br><br>```

Note, this does not take a regular expression. For that, use [`String#matches()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#matches(java.lang.String)) instead.

If you'd like to retain the split character in the resulting parts, then make use of [positive lookaround](https://www.regular-expressions.info/lookaround.html). In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing `?<=` group on the pattern.

```java<br>String string = "004-034556";<br>String[] parts = string.split("(?<=-)");<br>String part1 = parts[0]; // 004-<br>String part2 = parts[1]; // 034556<br><br>```

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing `?=` group on the pattern.

```java<br>String string = "004-034556";<br>String[] parts = string.split("(?=-)");<br>String part1 = parts[0]; // 004<br>String part2 = parts[1]; // -034556<br><br>```

If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of `split()` method.

```java<br>String string = "004-034556-42";<br>String[] parts = string.split("-", 2);<br>String part1 = parts[0]; // 004<br>String part2 = parts[1]; // 034556-42<br>```


```java<br>String string = "004-034556";<br>String[] parts = string.split("-");<br>String part1 = parts[0]; // 004<br>String part2 = parts[1]; // 034556<br><br>```


- splitSplits this string around matches of the given [regular expression](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#sum).

    public [String](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html)[] split([String](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html) regex)

    This method works as if by invoking the two-argument [`split`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#split(java.lang.String,int)) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

    The string `"boo:and:foo"`, for example, yields the following results with these expressions:

    > RegexResult:{ "boo", "and", "foo" }o{ "b", "", ":and:f" }
    >

    **Parameters:**`regex` - the delimiting regular expression**Returns:**the array of strings computed by splitting this string around matches of the given regular expression**Throws:**[`PatternSyntaxException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/PatternSyntaxException.html) - if the regular expression's syntax is invalid**Since:**1.4**See Also:**
        ◦ [`Pattern`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html)


### The theory (for the language lawyers and the mathematically inclined):

`equals()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object))) must define an equivalence relation (it must be *reflexive*, *symmetric*, and *transitive*). In addition, it must be *consistent* (if the objects are not modified, then it must keep returning the same value). Furthermore, `o.equals(null)` must always return false.

`hashCode()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode())) must also be *consistent* (if the object is not modified in terms of `equals()`, it must keep returning the same value).

The **relation** between the two methods is:

> Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
>

### In practice:

If you override one, then you should override the other.

Use the same set of fields that you use to compute `equals()` to compute `hashCode()`.

Use the excellent helper classes [EqualsBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html) and [HashCodeBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html) from the [Apache Commons Lang](http://commons.apache.org/lang/) library. An example:

```java<br>public class Person {<br>    private String name;<br>    private int age;<br>    // ...<br><br>    @Override<br>    public int hashCode() {<br>        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers<br>            // if deriving: appendSuper(super.hashCode()).<br>            append(name).<br>            append(age).<br>            toHashCode();<br>    }<br><br>    @Override<br>    public boolean equals(Object obj) {<br>       if (!(obj instanceof Person))<br>            return false;<br>        if (obj == this)<br>            return true;<br><br>        Person rhs = (Person) obj;<br>        return new EqualsBuilder().<br>            // if deriving: appendSuper(super.equals(obj)).<br>            append(name, rhs.name).<br>            append(age, rhs.age).<br>            isEquals();<br>    }<br>}<br><br>```

### Also remember:

When using a hash-based [Collection](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html) or [Map](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html) such as [HashSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html), [LinkedHashSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html), [HashMap](http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html), [Hashtable](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html), or [WeakHashMap](http://download.oracle.com/javase/1.4.2/docs/api/java/util/WeakHashMap.html), make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, [which has also other benefits](http://www.javapractices.com/topic/TopicAction.do?Id=29).


```java<br>public class Person {<br>    private String name;<br>    private int age;<br>    // ...<br><br>    @Override<br>    public int hashCode() {<br>        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers<br>            // if deriving: appendSuper(super.hashCode()).<br>            append(name).<br>            append(age).<br>            toHashCode();<br>    }<br><br>    @Override<br>    public boolean equals(Object obj) {<br>       if (!(obj instanceof Person))<br>            return false;<br>        if (obj == this)<br>            return true;<br><br>        Person rhs = (Person) obj;<br>        return new EqualsBuilder().<br>            // if deriving: appendSuper(super.equals(obj)).<br>            append(name, rhs.name).<br>            append(age, rhs.age).<br>            isEquals();<br>    }<br>}<br><br>```


- equalsIndicates whether some other object is "equal to" this one.

    ```<br>    public boolean equals(Object obj)<br>    ```

    The `equals` method implements an equivalence relation on non-null object references:

    - It is *reflexive*: for any non-null reference value `x`, `x.equals(x)` should return `true`.
    - It is *symmetric*: for any non-null reference values `x` and `y`, `x.equals(y)` should return `true` if and only if `y.equals(x)` returns `true`.
    - It is *transitive*: for any non-null reference values `x`, `y`, and `z`, if `x.equals(y)` returns `true` and `y.equals(z)` returns `true`, then `x.equals(z)` should return `true`.
    - It is *consistent*: for any non-null reference values `x` and `y`, multiple invocations of `x.equals(y)` consistently return `true` or consistently return `false`, provided no information used in `equals` comparisons on the objects is modified.
    - For any non-null reference value `x`, `x.equals(null)` should return `false`.

    The `equals` method for class `Object` implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values `x` and `y`, this method returns `true` if and only if `x` and `y` refer to the same object (`x == y` has the value `true`).

    Note that it is generally necessary to override the `hashCode` method whenever this method is overridden, so as to maintain the general contract for the `hashCode` method, which states that equal objects must have equal hash codes.

    **Parameters:**`obj` - the reference object with which to compare.**Returns:**`true` if this object is the same as the obj argument; `false` otherwise.**See Also:**[`hashCode()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()), [`HashMap`](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html)


That's the hard way, and those `java.util.Date` setter methods have been deprecated since Java 1.1 (1997). Moreover, the whole `java.util.Date` class was de-facto deprecated (discommended) since introduction of `java.time` API in Java 8 (2014).

Simply format the date using [`DateTimeFormatter`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html) with a pattern matching the input string ([the tutorial is available here](https://docs.oracle.com/javase/tutorial/datetime/iso/format.html)).

In your specific case of "January 2, 2010" as the input string:

1. "January" is the full text month, so use the `MMMM` pattern for it
2. "2" is the short day-of-month, so use the `d` pattern for it.
3. "2010" is the 4-digit year, so use the `yyyy` pattern for it.

```java<br>String string = "January 2, 2010";<br>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);<br>LocalDate date = LocalDate.parse(string, formatter);<br>System.out.println(date); // 2010-01-02<br><br>```

Note: if your format pattern happens to contain the time part as well, then use [`LocalDateTime#parse(text, formatter)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDateTime.html#parse(java.lang.CharSequence,java.time.format.DateTimeFormatter)) instead of [`LocalDate#parse(text, formatter)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDate.html#parse(java.lang.CharSequence,java.time.format.DateTimeFormatter)). And, if your format pattern happens to contain the time zone as well, then use [`ZonedDateTime#parse(text, formatter)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/ZonedDateDate.html#parse(java.lang.CharSequence,java.time.format.DateTimeFormatter)) instead.

Here's an extract of relevance from [the javadoc](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html), listing all available format patterns:

| Symbol | Meaning | Presentation | Examples |
| --- | --- | --- | --- |
| G | era | text | AD; Anno Domini; A |
| u | year | year | 2004; 04 |
| y | year-of-era | year | 2004; 04 |
| D | day-of-year | number | 189 |
| M/L | month-of-year | number/text | 7; 07; Jul; July; J |
| d | day-of-month | number | 10 |
| Q/q | quarter-of-year | number/text | 3; 03; Q3; 3rd quarter |
| Y | week-based-year | year | 1996; 96 |
| w | week-of-week-based-year | number | 27 |
| W | week-of-month | number | 4 |
| E | day-of-week | text | Tue; Tuesday; T |
| e/c | localized day-of-week | number/text | 2; 02; Tue; Tuesday; T |
| F | week-of-month | number | 3 |
| a | am-pm-of-day | text | PM |
| h | clock-hour-of-am-pm (1-12) | number | 12 |
| K | hour-of-am-pm (0-11) | number | 0 |
| k | clock-hour-of-am-pm (1-24) | number | 0 |
| H | hour-of-day (0-23) | number | 0 |
| m | minute-of-hour | number | 30 |
| s | second-of-minute | number | 55 |
| S | fraction-of-second | fraction | 978 |
| A | milli-of-day | number | 1234 |
| n | nano-of-second | number | 987654321 |
| N | nano-of-day | number | 1234000000 |
| V | time-zone ID | zone-id | America/Los_Angeles; Z; -08:30 |
| z | time-zone name | zone-name | Pacific Standard Time; PST |
| O | localized zone-offset | offset-O | GMT+8; GMT+08:00; UTC-08:00; |
| X | zone-offset 'Z' for zero | offset-X | Z; -08; -0830; -08:30; -083015; -08:30:15; |
| x | zone-offset | offset-x | +0000; -08; -0830; -08:30; -083015; -08:30:15; |
| Z | zone-offset | offset-Z | +0000; -0800; -08:00; |

Do note that it has several [predefined formatters](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#predefined) for the more popular patterns. So instead of e.g. `DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);`, you could use `DateTimeFormatter.RFC_1123_DATE_TIME`. This is possible because they are, on the contrary to `SimpleDateFormat`, thread safe. You could thus also define your own, if necessary.

For a particular input string format, you don't need to use an explicit `DateTimeFormatter`: a standard [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date, like 2016-09-26T17:44:57Z, can be parsed directly with [`LocalDateTime#parse(text)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDateTime.html#parse(java.lang.CharSequence)) as it already uses the [`ISO_LOCAL_DATE_TIME`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME) formatter. Similarly, [`LocalDate#parse(text)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDate.html#parse(java.lang.CharSequence)) parses an ISO date without the time component (see [`ISO_LOCAL_DATE`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE)), and [`ZonedDateTime#parse(text)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/ZonedDateTime.html#parse(java.lang.CharSequence)) parses an ISO date with an offset and time zone added (see [`ISO_ZONED_DATE_TIME`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#ISO_ZONED_DATE_TIME)).

---

## Pre-Java 8

In case you're not on Java 8 yet, or are forced to use `java.util.Date`, then format the date using [`SimpleDateFormat`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/SimpleDateFormat.html) using a format pattern matching the input string.

```java<br>String string = "January 2, 2010";<br>DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);<br>Date date = format.parse(string);<br>System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010<br><br>```

Note the importance of the explicit `Locale` argument. If you omit it, then it will use the [default locale](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Locale.html#getDefault()) which is not necessarily English as used in the month name of the input string. If the locale doesn't match with the input string, then you would confusingly get a `java.text.ParseException` even though when the format pattern seems valid.

Here's an extract of relevance from [the javadoc](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/SimpleDateFormat.html), listing all available format patterns:

| Letter | Date or Time Component | Presentation | Examples |
| --- | --- | --- | --- |
| G | Era designator | Text | AD |
| y | Year | Year | 1996; 96 |
| Y | Week year | Year | 2009; 09 |
| M/L | Month in year | Month | July; Jul; 07 |
| w | Week in year | Number | 27 |
| W | Week in month | Number | 2 |
| D | Day in year | Number | 189 |
| d | Day in month | Number | 10 |
| F | Day of week in month | Number | 2 |
| E | Day in week | Text | Tuesday; Tue |
| u | Day number of week | Number | 1 |
| a | Am/pm marker | Text | PM |
| H | Hour in day (0-23) | Number | 0 |
| k | Hour in day (1-24) | Number | 24 |
| K | Hour in am/pm (0-11) | Number | 0 |
| h | Hour in am/pm (1-12) | Number | 12 |
| m | Minute in hour | Number | 30 |
| s | Second in minute | Number | 55 |
| S | Millisecond | Number | 978 |
| z | Time zone | General time zone | Pacific Standard Time; PST; GMT-08:00 |
| Z | Time zone | RFC 822 time zone | -0800 |
| X | Time zone | ISO 8601 time zone | -08; -0800; -08:00 |

Note that the patterns are case sensitive and that text based patterns of four characters or more represent the full form; otherwise a short or abbreviated form is used if available. So e.g. `MMMMM` or more is unnecessary.

Here are some examples of valid `SimpleDateFormat` patterns to parse a given string to date:

| Input string | Pattern |
| --- | --- |
| 2001.07.04 AD at 12:08:56 PDT | yyyy.MM.dd G 'at' HH:mm:ss z |
| Wed, Jul 4, '01 | EEE, MMM d, ''yy |
| 12:08 PM | h:mm a |
| 12 o'clock PM, Pacific Daylight Time | hh 'o''clock' a, zzzz |
| 0:08 PM, PDT | K:mm a, z |
| 02001.July.04 AD 12:08 PM | yyyyy.MMMM.dd GGG hh:mm aaa |
| Wed, 4 Jul 2001 12:08:56 -0700 | EEE, d MMM yyyy HH:mm:ss Z |
| 010704120856-0700 | yyMMddHHmmssZ |
| 2001-07-04T12:08:56.235-0700 | yyyy-MM-dd'T'HH:mm:ss.SSSZ |
| 2001-07-04T12:08:56.235-07:00 | yyyy-MM-dd'T'HH:mm:ss.SSSXXX |
| 2001-W27-3 | YYYY-'W'ww-u |

An important note is that `SimpleDateFormat` is **not** thread safe. In other words, you should never declare and assign it as a static or instance variable and then reuse it from different methods/threads. You should always create it brand new within the method local scope.


```java<br>String string = "January 2, 2010";<br>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);<br>LocalDate date = LocalDate.parse(string, formatter);<br>System.out.println(date); // 2010-01-02<br><br>```


# Class DateTimeFormatter

[java.lang.Object](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html)

java.time.format.DateTimeFormatter

---

public final class **DateTimeFormatter**extends [Object](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html)

Formatter for printing and parsing date-time objects.

This class provides the main application entry point for printing and parsing and provides common implementations of `DateTimeFormatter`:

- Using predefined constants, such as [`ISO_LOCAL_DATE`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE)
- Using pattern letters, such as `uuuu-MMM-dd`
- Using localized styles, such as `long` or `medium`

More complex formatters are provided by [`DateTimeFormatterBuilder`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatterBuilder.html).

The main date-time classes provide two methods - one for formatting, `format(DateTimeFormatter formatter)`, and one for parsing, `parse(CharSequence text, DateTimeFormatter formatter)`.

For example:

> LocalDate date = LocalDate.now();
  String text = date.format(formatter);
  LocalDate parsedDate = LocalDate.parse(text, formatter);
>


Use [`setRoundingMode`](http://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html#setRoundingMode(java.math.RoundingMode)), set the [`RoundingMode`](http://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html) explicitly to handle your issue with the half-even round, then use the format pattern for your required output.

Example:

```java<br>DecimalFormat df = new DecimalFormat("#.####");<br>df.setRoundingMode(RoundingMode.CEILING);<br>for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {<br>    Double d = n.doubleValue();<br>    System.out.println(df.format(d));<br>}<br><br>```

gives the output:

```java<br>12<br>123.1235<br>0.23<br>0.1<br>2341234.2125<br><br>```

---

**EDIT**: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:

```java<br>Double d = n.doubleValue() + 1e-6;<br><br>```

To round down, subtract the accuracy.


```java<br>DecimalFormat df = new DecimalFormat("#.####");<br>df.setRoundingMode(RoundingMode.CEILING);<br>for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {<br>    Double d = n.doubleValue();<br>    System.out.println(df.format(d));<br>}<br><br>```


## Class DecimalFormat

- [java.lang.Object](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html)
- [java.text.Format](https://docs.oracle.com/javase/8/docs/api/java/text/Format.html)[java.text.NumberFormat](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html)java.text.DecimalFormat
- **All Implemented Interfaces:**[Serializable](https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html), [Cloneable](https://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html)`DecimalFormat` is a concrete subclass of `NumberFormat` that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

    ---

    ```<br>    public classDecimalFormat<br>    extendsNumberFormat<br>    ```

    To obtain a `NumberFormat` for a specific locale, including the default locale, call one of `NumberFormat`'s factory methods, such as `getInstance()`. In general, do not call the `DecimalFormat` constructors directly, since the `NumberFormat` factory methods may return subclasses other than `DecimalFormat`. If you need to customize the format object, do something like this:

    > NumberFormat f = NumberFormat.getInstance(loc);
     if (f instanceof DecimalFormat) {
         ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
     }
    >

    A `DecimalFormat` comprises a *pattern* and a set of *symbols*. The pattern may be set directly using `applyPattern()`, or indirectly using the API methods. The symbols are stored in a `DecimalFormatSymbols` object. When using the `NumberFormat` factory methods, the pattern and symbols are read from localized `ResourceBundle`s.


*First a disclaimer beforehand: the posted code snippets are all basic examples. You'll need to handle trivial `IOException`s and `RuntimeException`s like `NullPointerException`, `ArrayIndexOutOfBoundsException` and consorts yourself.*

*In case you're developing for Android instead of Java, note also that since introduction of API level 28, cleartext HTTP requests are [disabled by default](https://developer.android.com/about/versions/pie/android-9.0-changes-28#tls-enabled). You are encouraged to use `HttpsURLConnection`. When really necessary, cleartext can be enabled in the Application Manifest.*

---

### Preparing

We first need to know at least the URL and the charset. The parameters are optional and depend on the functional requirements.

```java<br>String url = "http://example.com";<br>String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()<br>String param1 = "value1";<br>String param2 = "value2";<br>// ...<br><br>String query = String.format("param1=%s&param2=%s",<br>    URLEncoder.encode(param1, charset),<br>    URLEncoder.encode(param2, charset));<br><br>```

The query parameters must be in `name=value` format and be concatenated by `&`. You would normally also [URL-encode](http://en.wikipedia.org/wiki/Percent-encoding) the query parameters with the specified charset using [`URLEncoder#encode()`](http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html#encode-java.lang.String-java.lang.String-).

The `String#format()` is just for convenience. I prefer it when I would need the String concatenation operator `+` more than twice.

---

### Firing an [HTTP GET](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) request with (optionally) query parameters

It's a trivial task. It's the default request method.

```java<br>URLConnection connection = new URL(url + "?" + query).openConnection();<br>connection.setRequestProperty("Accept-Charset", charset);<br>InputStream response = connection.getInputStream();<br>// ...<br><br>```

Any query string should be concatenated to the URL using `?`. The [`Accept-Charset`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2) header may hint the server what encoding the parameters are in. If you don't send any query string, then you can leave the `Accept-Charset` header away. If you don't need to set any headers, then you can even use the [`URL#openStream()`](http://docs.oracle.com/javase/8/docs/api/java/net/URL.html#openStream%28%29) shortcut method.

```java<br>InputStream response = new URL(url).openStream();<br>// ...<br><br>```

Either way, if the other side is an [`HttpServlet`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html), then its [`doGet()`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html#doGet%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29) method will be called and the parameters will be available by [`HttpServletRequest#getParameter()`](http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29).

For testing purposes, you can print the response body to [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29) as below:

```java<br>try (Scanner scanner = new Scanner(response)) {<br>    String responseBody = scanner.useDelimiter("\\A").next();<br>    System.out.println(responseBody);<br>}<br><br>```

---

### Firing an [HTTP POST](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5) request with query parameters

Setting the [`URLConnection#setDoOutput()`](http://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setDoOutput%28boolean%29) to `true` implicitly sets the request method to POST. The standard HTTP POST as web forms do is of type `application/x-www-form-urlencoded` wherein the query string is written to the request body.

```java<br>URLConnection connection = new URL(url).openConnection();<br>connection.setDoOutput(true); // Triggers POST.<br>connection.setRequestProperty("Accept-Charset", charset);<br>connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);<br><br>try (OutputStream output = connection.getOutputStream()) {<br>    output.write(query.getBytes(charset));<br>}<br><br>InputStream response = connection.getInputStream();<br>// ...<br><br>```

Note: whenever you'd like to submit a HTML form programmatically, don't forget to take the `name=value` pairs of any `<input type="hidden">` elements into the query string and of course also the `name=value` pair of the `<input type="submit">` element which you'd like to "press" programmatically (because that's usually been used in the server side to distinguish if a button was pressed and if so, which one).

You can also cast the obtained [`URLConnection`](http://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html) to [`HttpURLConnection`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html) and use its [`HttpURLConnection#setRequestMethod()`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#setRequestMethod%28java.lang.String%29) instead. But if you're trying to use the connection for output you still need to set [`URLConnection#setDoOutput()`](http://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setDoOutput%28boolean%29) to `true`.

```java<br>HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();<br>httpConnection.setRequestMethod("POST");<br>// ...<br><br>```

Either way, if the other side is an [`HttpServlet`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html), then its [`doPost()`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html#doPost%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29) method will be called and the parameters will be available by [`HttpServletRequest#getParameter()`](http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29).

---

### Actually firing the HTTP request

You can fire the HTTP request explicitly with [`URLConnection#connect()`](http://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#connect%28%29), but the request will automatically be fired on demand when you want to get any information about the HTTP response, such as the response body using [`URLConnection#getInputStream()`](http://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#getInputStream%28%29) and so on. The above examples does exactly that, so the `connect()` call is in fact superfluous.

---

### Timeouts

You can use [`URLConnection#setConnectTimeout()`](https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setConnectTimeout-int-) to set the connect timeout and [`URLConnection#setReadTimeout()`](https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setReadTimeout-int-) to set the read timeout.

The default is basically "no timeout". So you'd like to set these yourself. For example:

```java<br>httpConnection.setConnectTimeout(3000); // 3s<br>httpConnection.setReadTimeout(6000); // 6s<br><br>```

There's however a caveat with the read timeout when using Sun/Oracle based JRE. It will silently retry the reading before throwing the timeout exception, most probably merely to have any successfull reading ready in the cache. See also [Android (Java) HttpURLConnection silent retry on 'read' timeout](https://stackoverflow.com/questions/27094544/android-java-httpurlconnection-silent-retry-on-read-timeout/37675253#37675253) This is okayish for GET, but absolutely wrong for POST. In case you're using a Sun/Oracle based JRE, you'll want to turn off that as follows:

```java<br>System.setProperty("sun.net.http.retryPost", "false")<br><br>```

In case you're writing for Android, above will not work, you'll need this work around on POST:

```java<br>httpConnection.setChunkedStreamingMode(0);<br><br>```

This will only slightly impact the performance. In case that's undesireable, then consider switching to a different HTTP client such as [OkHttp](https://square.github.io/okhttp/).

---

### Gathering HTTP response information

1. [HTTP response status](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html):

You need an [`HttpURLConnection`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html) here. Cast it first if necessary.

```java<br>    int status = httpConnection.getResponseCode();<br><br>```

1. [HTTP response headers](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html):

    ```java<br>     for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {<br>         System.out.println(header.getKey() + "=" + header.getValue());<br>     }<br>    <br>    ```

2. [HTTP response encoding](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17):

When the `Content-Type` contains a `charset` parameter, then the response body is likely text based and we'd like to process the response body with the server-side specified character encoding then.

```java<br>    String contentType = connection.getHeaderField("Content-Type");<br>    String charset = null;<br><br>    for (String param : contentType.replace(" ", "").split(";")) {<br>        if (param.startsWith("charset=")) {<br>            charset = param.split("=", 2)[1];<br>            break;<br>        }<br>    }<br><br>    if (charset != null) {<br>        try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {<br>            for (String line; (line = reader.readLine()) != null;) {<br>                // ... System.out.println(line)?<br>            }<br>        }<br>    } else {<br>        // It's likely binary content, use InputStream/OutputStream.<br>    }<br><br>```

---

### Maintaining the session

The server side session is usually backed by a cookie. Some web forms require that you're logged in and/or are tracked by a session. You can use the [`CookieHandler`](http://docs.oracle.com/javase/8/docs/api/java/net/CookieHandler.html) API to maintain cookies. You need to prepare a [`CookieManager`](http://docs.oracle.com/javase/8/docs/api/java/net/CookieManager.html) with a [`CookiePolicy`](http://docs.oracle.com/javase/8/docs/api/java/net/CookiePolicy.html) of [`ACCEPT_ALL`](http://docs.oracle.com/javase/8/docs/api/java/net/CookiePolicy.html#ACCEPT_ALL) before sending all HTTP requests.

```java<br>// First set the default cookie manager.<br>CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));<br><br>// All the following subsequent URLConnections will use the same cookie manager.<br>URLConnection connection = new URL(url).openConnection();<br>// ...<br><br>connection = new URL(url).openConnection();<br>// ...<br><br>connection = new URL(url).openConnection();<br>// ...<br><br>```

Note that this is known to not always work properly in all circumstances. If it fails for you, then best is to manually gather and set the cookie headers. You basically need to grab all `Set-Cookie` headers from the response of the login or the first `GET` request and then pass this through the subsequent requests.

```java<br>// Gather all cookies on the first request.<br>URLConnection connection = new URL(url).openConnection();<br>List<String> cookies = connection.getHeaderFields().get("Set-Cookie");<br>// ...<br><br>// Then use the same cookies on all subsequent requests.<br>connection = new URL(url).openConnection();<br>for (String cookie : cookies) {<br>    connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);<br>}<br>// ...<br><br>```

The `split(";", 2)[0]` is there to get rid of cookie attributes which are irrelevant for the server side like `expires`, `path`, etc. Alternatively, you could also use `cookie.substring(0, cookie.indexOf(';'))` instead of `split()`.

---

### Streaming mode

The [`HttpURLConnection`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html) will by default buffer the *entire* request body before actually sending it, regardless of whether you've set a fixed content length yourself using `connection.setRequestProperty("Content-Length", contentLength);`. This may cause `OutOfMemoryException`s whenever you concurrently send large POST requests (e.g. uploading files). To avoid this, you would like to set the [`HttpURLConnection#setFixedLengthStreamingMode()`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#setFixedLengthStreamingMode%28int%29).

```java<br>httpConnection.setFixedLengthStreamingMode(contentLength);<br><br>```

But if the content length is really not known beforehand, then you can make use of chunked streaming mode by setting the [`HttpURLConnection#setChunkedStreamingMode()`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#setChunkedStreamingMode%28int%29) accordingly. This will set the HTTP [`Transfer-Encoding`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.41) header to `chunked` which will force the request body being sent in chunks. The below example will send the body in chunks of 1 KB.

```java<br>httpConnection.setChunkedStreamingMode(1024);<br><br>```

---

### User-Agent

It can happen that [a request returns an unexpected response, while it works fine with a real web browser](https://stackoverflow.com/questions/13670692/403-forbidden-with-java-but-not-web-browser). The server side is probably blocking requests based on the [`User-Agent`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43) request header. The `URLConnection` will by default set it to `Java/1.6.0_19` where the last part is obviously the JRE version. You can override this as follows:

```java<br>connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7.<br><br>```

Use the User-Agent string from a [recent browser](http://www.useragentstring.com/pages/useragentstring.php).

---

### Error handling

If the HTTP response code is `4nn` (Client Error) or `5nn` (Server Error), then you may want to read the `HttpURLConnection#getErrorStream()` to see if the server has sent any useful error information.

```java<br>InputStream error = ((HttpURLConnection) connection).getErrorStream();<br><br>```

If the HTTP response code is -1, then something went wrong with connection and response handling. The `HttpURLConnection` implementation is in older JREs somewhat buggy with keeping connections alive. You may want to turn it off by setting the `http.keepAlive` system property to `false`. You can do this programmatically in the beginning of your application by:

```java<br>System.setProperty("http.keepAlive", "false");<br><br>```

---

### Uploading files

You'd normally use [`multipart/form-data`](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2) encoding for mixed POST content (binary and character data). The encoding is in more detail described in [RFC2388](http://www.faqs.org/rfcs/rfc2388.html).

```java<br>String param = "value";<br>File textFile = new File("/path/to/file.txt");<br>File binaryFile = new File("/path/to/file.bin");<br>String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.<br>String CRLF = "\r\n"; // Line separator required by multipart/form-data.<br>URLConnection connection = new URL(url).openConnection();<br>connection.setDoOutput(true);<br>connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);<br><br>try (<br>    OutputStream output = connection.getOutputStream();<br>    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);<br>) {<br>    // Send normal param.<br>    writer.append("--" + boundary).append(CRLF);<br>    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);<br>    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);<br>    writer.append(CRLF).append(param).append(CRLF).flush();<br><br>    // Send text file.<br>    writer.append("--" + boundary).append(CRLF);<br>    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);<br>    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!<br>    writer.append(CRLF).flush();<br>    Files.copy(textFile.toPath(), output);<br>    output.flush(); // Important before continuing with writer!<br>    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.<br><br>    // Send binary file.<br>    writer.append("--" + boundary).append(CRLF);<br>    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);<br>    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);<br>    writer.append("Content-Transfer-Encoding: binary").append(CRLF);<br>    writer.append(CRLF).flush();<br>    Files.copy(binaryFile.toPath(), output);<br>    output.flush(); // Important before continuing with writer!<br>    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.<br><br>    // End of multipart/form-data.<br>    writer.append("--" + boundary + "--").append(CRLF).flush();<br>}<br><br>```

If the other side is an [`HttpServlet`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html), then its [`doPost()`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html#doPost%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29) method will be called and the parts will be available by [`HttpServletRequest#getPart()`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#getPart%28java.lang.String%29) (note, thus **not** `getParameter()` and so on!). The `getPart()` method is however relatively new, it's introduced in Servlet 3.0 (Glassfish 3, Tomcat 7, etc.). Prior to Servlet 3.0, your best choice is using [Apache Commons FileUpload](http://commons.apache.org/fileupload) to parse a `multipart/form-data` request. Also see [this answer](https://stackoverflow.com/questions/2422468/upload-big-file-to-servlet/2424824#2424824) for examples of both the FileUpload and the Servelt 3.0 approaches.

---

### Dealing with untrusted or misconfigured HTTPS sites

*In case you're developing for Android instead of Java, **be careful**: the workaround below may save your day if you don't have correct certificates deployed during development. But you should not use it for production. These days (April 2021) Google will not allow your app be distributed on Play Store if they detect insecure hostname verifier, see https://support.google.com/faqs/answer/7188426.*

Sometimes you need to connect an HTTPS URL, perhaps because you're writing a web scraper. In that case, you may likely face a `javax.net.ssl.SSLException: Not trusted server certificate` on some HTTPS sites who doesn't keep their SSL certificates up to date, or a `java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found` or `javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name` on some misconfigured HTTPS sites.

The following one-time-run `static` initializer in your web scraper class should make `HttpsURLConnection` more lenient as to those HTTPS sites and thus not throw those exceptions anymore.

```java<br>static {<br>    TrustManager[] trustAllCertificates = new TrustManager[] {<br>        new X509TrustManager() {<br>            @Override<br>            public X509Certificate[] getAcceptedIssuers() {<br>                return null; // Not relevant.<br>            }<br>            @Override<br>            public void checkClientTrusted(X509Certificate[] certs, String authType) {<br>                // Do nothing. Just allow them all.<br>            }<br>            @Override<br>            public void checkServerTrusted(X509Certificate[] certs, String authType) {<br>                // Do nothing. Just allow them all.<br>            }<br>        }<br>    };<br><br>    HostnameVerifier trustAllHostnames = new HostnameVerifier() {<br>        @Override<br>        public boolean verify(String hostname, SSLSession session) {<br>            return true; // Just allow them all.<br>        }<br>    };<br><br>    try {<br>        System.setProperty("jsse.enableSNIExtension", "false");<br>        SSLContext sc = SSLContext.getInstance("SSL");<br>        sc.init(null, trustAllCertificates, new SecureRandom());<br>        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());<br>        HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);<br>    }<br>    catch (GeneralSecurityException e) {<br>        throw new ExceptionInInitializerError(e);<br>    }<br>}<br><br>```

---

### Last words

The [Apache HttpComponents HttpClient](http://hc.apache.org/httpcomponents-client-ga/) is *much* more convenient in this all :)

- [HttpClient Tutorial](http://hc.apache.org/httpcomponents-client-ga/tutorial/html/)
- [HttpClient Examples](http://hc.apache.org/httpcomponents-client-ga/examples.html)

---

### Parsing and extracting HTML

If all you want is parsing and extracting data from HTML, then better use a HTML parser like [Jsoup](http://jsoup.org/).

- [What are the pros/cons of leading HTML parsers in Java](https://stackoverflow.com/questions/3152138/what-are-the-pros-and-cons-of-the-leading-java-html-parsers/3154281#3154281)
- [How to scan and extract a webpage in Java](https://stackoverflow.com/questions/2835505/how-to-scan-a-website-or-page-for-info-and-bring-it-into-my-program/2835555#2835555)


```java<br>URLConnection connection = new URL(url + "?" + query).openConnection();<br>connection.setRequestProperty("Accept-Charset", charset);<br>InputStream response = connection.getInputStream();<br>// ...<br><br>```


- encodeTranslates a string into `application/x-www-form-urlencoded` format using a specific encoding scheme. This method uses the supplied encoding scheme to obtain the bytes for unsafe characters.

    ```<br>    public staticString encode(String s,<br>    String enc)<br>                         throwsUnsupportedEncodingException<br>    ```

    ***Note:** The [World Wide Web Consortium Recommendation](http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars) states that UTF-8 should be used. Not doing so may introduce incompatibilities.*

    **Parameters:**`s` - `String` to be translated.`enc` - The name of a supported [character encoding](https://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html#charenc).**Returns:**the translated `String`.**Throws:**[`UnsupportedEncodingException`](https://docs.oracle.com/javase/8/docs/api/java/io/UnsupportedEncodingException.html) - If the named encoding is not supported**Since:**1.4**See Also:**[`URLDecoder.decode(java.lang.String, java.lang.String)`](https://docs.oracle.com/javase/8/docs/api/java/net/URLDecoder.html#decode-java.lang.String-java.lang.String-)


I have to ask a question in return: is your `GenSet` "checked" or "unchecked"? What does that mean?

- **Checked**: *strong typing*. `GenSet` knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a `Class<E>` argument, and methods will throw an exception when they are passed arguments that are not of type `E`. See [`Collections.checkedCollection`](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#checkedCollection%28java.util.Collection,%20java.lang.Class%29).
    - > in that case, you should write:

    ```java<br>    public class GenSet<E> {<br>    <br>        private E[] a;<br>    <br>        public GenSet(Class<E> c, int s) {<br>            // Use Array native method to create array<br>            // of a type only known at run time<br>            @SuppressWarnings("unchecked")<br>            final E[] a = (E[]) Array.newInstance(c, s);<br>            this.a = a;<br>        }<br>    <br>        E get(int i) {<br>            return a[i];<br>        }<br>    }<br>    <br>    ```

- **Unchecked**: *weak typing*. No type checking is actually done on any of the objects passed as argument.
    - > in that case, you should write

    ```java<br>    public class GenSet<E> {<br>    <br>        private Object[] a;<br>    <br>        public GenSet(int s) {<br>            a = new Object[s];<br>        }<br>    <br>        E get(int i) {<br>            @SuppressWarnings("unchecked")<br>            final E e = (E) a[i];<br>            return e;<br>        }<br>    }<br>    <br>    ```

    Note that the component type of the array should be the [*erasure*](http://docs.oracle.com/javase/tutorial/java/generics/erasure.html) of the type parameter:

    ```java<br>    public class GenSet<E extends Foo> { // E has an upper bound of Foo<br>    <br>        private Foo[] a; // E erases to Foo, so use Foo[]<br>    <br>        public GenSet(int s) {<br>            a = new Foo[s];<br>        }<br>    <br>        ...<br>    }<br>    <br>    ```

All of this results from a known, and deliberate, weakness of generics in Java: it was implemented using erasure, so "generic" classes don't know what type argument they were created with at run time, and therefore can not provide type-safety unless some explicit mechanism (type-checking) is implemented.


```java<br>    public class GenSet<E> {<br>    <br>        private Object[] a;<br>    <br>        public GenSet(int s) {<br>            a = new Object[s];<br>        }<br>    <br>        E get(int i) {<br>            @SuppressWarnings("unchecked")<br>            final E e = (E) a[i];<br>            return e;<br>        }<br>    }<br>    <br>    ```


- checkedCollectionReturns a dynamically typesafe view of the specified collection. Any attempt to insert an element of the wrong type will result in an immediate [`ClassCastException`](https://docs.oracle.com/javase/7/docs/api/java/lang/ClassCastException.html). Assuming a collection contains no incorrectly typed elements prior to the time a dynamically typesafe view is generated, and that all subsequent access to the collection takes place through the view, it is *guaranteed* that the collection cannot contain an incorrectly typed element.may be replaced temporarily by this one:Running the program again will cause it to fail at the point where an incorrectly typed element is inserted into the collection, clearly identifying the source of the problem. Once the problem is fixed, the modified declaration may be reverted back to the original.

    ```<br>    public static <E>Collection<E> checkedCollection(Collection<E> c,<br>    Class<E> type)<br>    ```

    The generics mechanism in the language provides compile-time (static) type checking, but it is possible to defeat this mechanism with unchecked casts. Usually this is not a problem, as the compiler issues warnings on all such unchecked operations. There are, however, times when static type checking alone is not sufficient. For example, suppose a collection is passed to a third-party library and it is imperative that the library code not corrupt the collection by inserting an element of the wrong type.

    Another use of dynamically typesafe views is debugging. Suppose a program fails with a `ClassCastException`, indicating that an incorrectly typed element was put into a parameterized collection. Unfortunately, the exception can occur at any time after the erroneous element is inserted, so it typically provides little or no information as to the real source of the problem. If the problem is reproducible, one can quickly determine its source by temporarily modifying the program to wrap the collection with a dynamically typesafe view. For example, this declaration:

    ```<br>    Collection<String> c = new HashSet<String>();<br>    <br>    ```

    ```<br>    Collection<String> c = Collections.checkedCollection(<br>             new HashSet<String>(), String.class);<br>    <br>    ```

    The returned collection does *not* pass the hashCode and equals operations through to the backing collection, but relies on `Object`'s `equals` and `hashCode` methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.

    The returned collection will be serializable if the specified collection is serializable.

    Since `null` is considered to be a value of any reference type, the returned collection permits insertion of null elements whenever the backing collection does.

    **Parameters:**`c` - the collection for which a dynamically typesafe view is to be returned`type` - the type of element that `c` is permitted to hold**Returns:**a dynamically typesafe view of the specified collection**Since:**1.5


```java<br>for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {<br>    String item = i.next();<br>    System.out.println(item);<br>}<br><br>```

Note that if you need to use `i.remove();` in your loop, or access the actual iterator in some way, you cannot use the `for ( : )` idiom, since the actual iterator is merely inferred.

As was noted by Denis Bueno, this code works for any object that implements the [`Iterable` interface](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html).

If the right-hand side of the `for (:)` idiom is an array rather than an `Iterable` object, the internal code uses an int index counter and checks against `array.length` instead. See the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2).

```java<br>for (int i = 0; i < someArray.length; i++) {<br>    String item = someArray[i];<br>    System.out.println(item);<br>}<br>```


```java<br>for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {<br>    String item = i.next();<br>    System.out.println(item);<br>}<br><br>```


- `public interface **Iterable<T>**`

    Implementing this interface allows an object to be the target of the "for-each loop" statement. See [**For-each Loop**](https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html)

    **Since:**1.5**See The Java™ Language Specification:**14.14.2 The enhanced for statement

- *Method Summary***All MethodsInstance MethodsAbstract MethodsDefault Methods**Modifier and TypeMethod and Description`default void[**forEach**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer-)([**Consumer**](https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html)<? super [**T**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html)> action)`Performs the given action for each element of the `Iterable` until all elements have been processed or the action throws an exception.[**`Iterator**](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)<[**T**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html)>[**iterator**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#iterator--)()`Returns an iterator over elements of type `T`.`default [**Spliterator**](https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html)<[**T**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html)>[**spliterator**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#spliterator--)()`Creates a [**`Spliterator`**](https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html) over the elements described by this `Iterable`.


Are you doing this for logging purposes? If so there are [several libraries for this](http://en.wikipedia.org/wiki/Java_logging_framework). Two of the most popular are [Log4j](http://logging.apache.org/log4j/) and [Logback](http://logback.qos.ch/).

## Java 7+

For a one-time task, the [Files class](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) makes this easy:

```java<br>try {<br>    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);<br>}catch (IOException e) {<br>    //exception handling left as an exercise for the reader<br>}<br><br>```

**Careful**: The above approach will throw a `NoSuchFileException` if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both `CREATE` and `APPEND` options, which will create the file first if it doesn't already exist:

```java<br>private void write(final String s) throws IOException {<br>    Files.writeString(<br>        Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),<br>        s + System.lineSeparator(),<br>        StandardOpenOption.CREATE, StandardOpenOption.APPEND<br>    );<br>}<br><br>```

However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a `BufferedWriter` is faster:

```java<br>try(FileWriter fw = new FileWriter("myfile.txt", true);<br>    BufferedWriter bw = new BufferedWriter(fw);<br>    PrintWriter out = new PrintWriter(bw))<br>{<br>    out.println("the text");<br>    //more code<br>    out.println("more text");<br>    //more code<br>} catch (IOException e) {<br>    //exception handling left as an exercise for the reader<br>}<br><br>```

**Notes:**

- The second parameter to the `FileWriter` constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
- Using a `BufferedWriter` is recommended for an expensive writer (such as `FileWriter`).
- Using a `PrintWriter` gives you access to `println` syntax that you're probably used to from `System.out`.
- But the `BufferedWriter` and `PrintWriter` wrappers are not strictly necessary.

---

## Older Java

```java<br>try {<br>    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));<br>    out.println("the text");<br>    out.close();<br>} catch (IOException e) {<br>    //exception handling left as an exercise for the reader<br>}<br><br>```

---

## Exception Handling

If you need robust exception handling for older Java, it gets very verbose:

```java<br>FileWriter fw = null;<br>BufferedWriter bw = null;<br>PrintWriter out = null;<br>try {<br>    fw = new FileWriter("myfile.txt", true);<br>    bw = new BufferedWriter(fw);<br>    out = new PrintWriter(bw);<br>    out.println("the text");<br>    out.close();<br>} catch (IOException e) {<br>    //exception handling left as an exercise for the reader<br>}<br>finally {<br>    try {<br>        if(out != null)<br>            out.close();<br>    } catch (IOException e) {<br>        //exception handling left as an exercise for the reader<br>    }<br>    try {<br>        if(bw != null)<br>            bw.close();<br>    } catch (IOException e) {<br>        //exception handling left as an exercise for the reader<br>    }<br>    try {<br>        if(fw != null)<br>            fw.close();<br>    } catch (IOException e) {<br>        //exception handling left as an exercise for the reader<br>    }<br>}<br>```


```java<br>try {<br>    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);<br>}catch (IOException e) {<br>    //exception handling left as an exercise for the reader<br>}<br><br>```


### Method Detail

- newInputStreamOpens a file, returning an input stream to read from the file. The stream will not be buffered, and is not required to support the [`mark`](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#mark(int)) or [`reset`](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#reset()) methods. The stream will be safe for access by multiple concurrent threads. Reading commences at the beginning of the file. Whether the returned stream is *asynchronously closeable* and/or *interruptible* is highly file system provider specific and therefore not specified.

    ```<br>    public staticInputStream newInputStream(Path path,<br>    OpenOption... options)<br>                                      throwsIOException<br>    ```

    The `options` parameter determines how the file is opened. If no options are present then it is equivalent to opening the file with the [`READ`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#READ) option. In addition to the `READ` option, an implementation may also support additional implementation specific options.

    **Parameters:**`path` - the path to the file to open`options` - options specifying how the file is opened**Returns:**a new input stream**Throws:**[`IllegalArgumentException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html) - if an invalid combination of options is specified[`UnsupportedOperationException`](https://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html) - if an unsupported option is specified[`IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) - if an I/O error occurs[`SecurityException`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html) - In the case of the default provider, and a security manager is installed, the [`checkRead`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkRead(java.lang.String)) method is invoked to check read access to the file.

- newOutputStreamOpens or creates a file, returning an output stream that may be used to write bytes to the file. The resulting stream will not be buffered. The stream will be safe for access by multiple concurrent threads. Whether the returned stream is *asynchronously closeable* and/or *interruptible* is highly file system provider specific and therefore not specified.

    ```<br>    public staticOutputStream newOutputStream(Path path,<br>    OpenOption... options)<br>                                        throwsIOException<br>    ```

    This method opens or creates a file in exactly the manner specified by the [`newByteChannel`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newByteChannel(java.nio.file.Path,%20java.util.Set,%20java.nio.file.attribute.FileAttribute...)) method with the exception that the [`READ`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#READ) option may not be present in the array of options. If no options are present then this method works as if the [`CREATE`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#CREATE), [`TRUNCATE_EXISTING`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#TRUNCATE_EXISTING), and [`WRITE`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#WRITE) options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing [`regular-file`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#isRegularFile(java.nio.file.Path,%20java.nio.file.LinkOption...)) to a size of `0` if it exists.

    **Usage Examples:**

    ```<br>         Path path = ...<br>    <br>         // truncate and overwrite an existing file, or create the file if<br>         // it doesn't initially exist<br>         OutputStream out = Files.newOutputStream(path);<br>    <br>         // append to an existing file, fail if the file does not exist<br>         out = Files.newOutputStream(path, APPEND);<br>    <br>         // append to an existing file, create file if it doesn't initially exist<br>         out = Files.newOutputStream(path, CREATE, APPEND);<br>    <br>         // always create new file, failing if it already exists<br>         out = Files.newOutputStream(path, CREATE_NEW);<br>    <br>    ```

    **Parameters:**`path` - the path to the file to open or create`options` - options specifying how the file is opened**Returns:**a new output stream**Throws:**[`IllegalArgumentException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html) - if `options` contains an invalid combination of options[`UnsupportedOperationException`](https://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html) - if an unsupported option is specified[`IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) - if an I/O error occurs[`SecurityException`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html) - In the case of the default provider, and a security manager is installed, the [`checkWrite`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkWrite(java.lang.String)) method is invoked to check write access to the file. The [`checkDelete`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkDelete(java.lang.String)) method is invoked to check delete access if the file is opened with the `DELETE_ON_CLOSE` option.


From the [Java Tutorial](http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html):

> Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
>

Static nested classes are accessed using the enclosing class name:

```java<br>OuterClass.StaticNestedClass<br><br>```

For example, to create an object for the static nested class, use this syntax:

```java<br>OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();<br><br>```

Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:

```java<br>class OuterClass {<br>    ...<br>    class InnerClass {<br>        ...<br>    }<br>}<br><br>```

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

```java<br>OuterClass outerObject = new OuterClass()<br>OuterClass.InnerClass innerObject = outerObject.new InnerClass();<br><br>```

see: [Java Tutorial - Nested Classes](http://download.oracle.com/javase/tutorial/java/javaOO/nested.html)

For completeness note that there is also such a thing as an [inner class *without* an enclosing instance](https://stackoverflow.com/questions/20468856/is-it-true-that-every-inner-class-requires-an-enclosing-instance):

```java<br>class A {<br>  int t() { return 1; }<br>  static A a =  new A() { int t() { return 2; } };<br>}<br><br>```

Here, `new A() { ... }` is an *inner class defined in a static context* and does not have an enclosing instance.


<br>```java<br>class OuterClass {<br>    ...<br>    class InnerClass {<br>        ...<br>    }<br>}<br><br>```


# **Nested Classes**

The Java programming language allows you to define a class within another class. Such a class is called a *nested class* and is illustrated here:

`class OuterClass {<br>    ...<br>    class NestedClass {<br>        ...<br>    }<br>}`

---

**Terminology:**

Nested classes are divided into two categories: non-static and static. Non-static nested classes are called

*inner classes*

. Nested classes that are declared

```<br>static<br>```

are called

*static nested classes*

.

---

`class OuterClass {<br>    ...<br>    class InnerClass {<br>        ...<br>    }<br>    static class StaticNestedClass {<br>        ...<br>    }<br>}`

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the `OuterClass`, a nested class can be declared `private`, `public`, `protected`, or *package private*. (Recall that outer classes can only be declared `public` or *package private*.)


There are two types of array.

## One Dimensional Array

Syntax for default values:

```java<br>int[] num = new int[5];<br><br>```

Or (less preferred)

```java<br>int num[] = new int[5];<br><br>```

Syntax with values given (variable/field initialization):

```java<br>int[] num = {1,2,3,4,5};<br><br>```

Or (less preferred)

```java<br>int num[] = {1, 2, 3, 4, 5};<br><br>```

Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.

## Multidimensional array

### Declaration

```java<br>int[][] num = new int[5][2];<br><br>```

Or

```java<br>int num[][] = new int[5][2];<br><br>```

Or

```java<br>int[] num[] = new int[5][2];<br><br>```

### Initialization

```java<br> num[0][0]=1;<br> num[0][1]=2;<br> num[1][0]=1;<br> num[1][1]=2;<br> num[2][0]=1;<br> num[2][1]=2;<br> num[3][0]=1;<br> num[3][1]=2;<br> num[4][0]=1;<br> num[4][1]=2;<br><br>```

Or

```java<br> int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };<br><br>```

### Ragged Array (or Non-rectangular Array)

```java<br> int[][] num = new int[5][];<br> num[0] = new int[1];<br> num[1] = new int[5];<br> num[2] = new int[2];<br> num[3] = new int[3];<br><br>```

So here we are defining columns explicitly.

**Another Way:**

```java<br>int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };<br><br>```

## For Accessing:

```java<br>for (int i=0; i<(num.length); i++ ) {<br>    for (int j=0;j<num[i].length;j++)<br>        System.out.println(num[i][j]);<br>}<br><br>```

Alternatively:

```java<br>for (int[] a : num) {<br>  for (int i : a) {<br>    System.out.println(i);<br>  }<br>}<br><br>```

Ragged arrays are multidimensional arrays.

For explanation see multidimensional array detail at [the official java tutorials](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)


```java<br>int[] num = new int[5];<br><br>```


# **Arrays**

An *array* is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the `main` method of the "Hello World!" application. This section discusses arrays in greater detail.

An array of 10 elements.

!https://docs.oracle.com/javase/tutorial/figures/java/objects-tenElementArray.gif

Each item in an array is called an *element*, and each element is accessed by its numerical *index*. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

The following program, [`ArrayDemo`](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/examples/ArrayDemo.java), creates an array of integers, puts some values in the array, and prints each value to standard output.

`class ArrayDemo {
    public static void main(String[] args) {
        // declares an array of integers
        int[] anArray;

        // allocates memory for 10 integers
        anArray = new int[10];

        // initialize first element
        anArray[0] = 100;
        // initialize second element
        anArray[1] = 200;
        // and so forth
        anArray[2] = 300;
        anArray[3] = 400;
        anArray[4] = 500;
        anArray[5] = 600;
        anArray[6] = 700;
        anArray[7] = 800;
        anArray[8] = 900;
        anArray[9] = 1000;

        System.out.println("Element at index 0: "
                           + anArray[0]);
        System.out.println("Element at index 1: "
                           + anArray[1]);
        System.out.println("Element at index 2: "
                           + anArray[2]);
        System.out.println("Element at index 3: "
                           + anArray[3]);
        System.out.println("Element at index 4: "
                           + anArray[4]);
        System.out.println("Element at index 5: "
                           + anArray[5]);
        System.out.println("Element at index 6: "
                           + anArray[6]);
        System.out.println("Element at index 7: "
                           + anArray[7]);
        System.out.println("Element at index 8: "
                           + anArray[8]);
        System.out.println("Element at index 9: "
                           + anArray[9]);
    }
}`<br><br>The output from this program is:<br><br>`Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000`

In a real-world programming situation, you would probably use one of the supported *looping constructs* to iterate through each element of the array, rather than write each line individually as in the preceding example. However, the example clearly illustrates the array syntax. You will learn about the various looping constructs (`for`, `while`, and `do-while`) in the [Control Flow](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html) section.


```java<br>String myString = "1234";<br>int foo = Integer.parseInt(myString);<br><br>```

If you look at the [Java documentation](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Integer.html#parseInt(java.lang.String)) you'll notice the "catch" is that this function can throw a `NumberFormatException`, which you can handle:

```java<br>int foo;<br>try {<br>   foo = Integer.parseInt(myString);<br>}<br>catch (NumberFormatException e) {<br>   foo = 0;<br>}<br><br>```

(This treatment defaults a malformed number to `0`, but you can do something else if you like.)

Alternatively, you can use an `Ints` method from the Guava library, which in combination with Java 8's `Optional`, makes for a powerful and concise way to convert a string into an int:

```java<br>import com.google.common.primitives.Ints;<br><br>int foo = Optional.ofNullable(myString)<br> .map(Ints::tryParse)<br> .orElse(0)<br>```


```java<br>int foo;<br>try {<br>   foo = Integer.parseInt(myString);<br>}<br>catch (NumberFormatException e) {<br>   foo = 0;<br>}<br><br>```


- parseInt

    ```<br>    public static int parseInt(String s) throwsNumberFormatException<br>    ```

    Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign `'-'` (`'\u002D'`) to indicate a negative value or an ASCII plus sign `'+'` (`'\u002B'`) to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the [`parseInt(java.lang.String, int)`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Integer.html#parseInt(java.lang.String,int)) method.

    **Parameters:**`s` - a `String` containing the `int` representation to be parsed**Returns:**the integer value represented by the argument in decimal.**Throws:**[`NumberFormatException`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/NumberFormatException.html) - if the string does not contain a parsable integer.


My favorite way to read a small file is to use a BufferedReader and a StringBuilder. It is very simple and to the point (though not particularly effective, but good enough for most cases):

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
}
Some has pointed out that after Java 7 you should use try-with-resources (i.e. auto close) features:

try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
}
When I read strings like this, I usually want to do some string handling per line anyways, so then I go for this implementation.

Though if I want to actually just read a file into a String, I always use Apache Commons IO with the class IOUtils.toString() method. You can have a look at the source here:

http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html

FileInputStream inputStream = new FileInputStream("foo.txt");
try {
    String everything = IOUtils.toString(inputStream);
} finally {
    inputStream.close();
}
And even simpler with Java 7:

try(FileInputStream inputStream = new FileInputStream("foo.txt")) {
    String everything = IOUtils.toString(inputStream);
    // do something with everything string
}


```java<br>BufferedReader br = new BufferedReader(new FileReader("file.txt"));<br>try {<br>    StringBuilder sb = new StringBuilder();<br>    String line = br.readLine();<br><br>    while (line != null) {<br>        sb.append(line);<br>        sb.append(System.lineSeparator());<br>        line = br.readLine();<br>    }<br>    String everything = sb.toString();<br>} finally {<br>    br.close();<br>}<br><br>```


# **The try-with-resources Statement**

The `try`-with-resources statement is a `try` statement that declares one or more resources. A *resource* is an object that must be closed after the program is finished with it. The `try`-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements `java.lang.AutoCloseable`, which includes all objects which implement `java.io.Closeable`, can be used as a resource.

The following example reads the first line from a file. It uses an instance of `FileReader` and `BufferedReader` to read data from the file. `FileReader` and `BufferedReader` are resources that must be closed after the program is finished with it:

        `static String readFirstLineFromFile(String path) throws IOException {
            **try (FileReader fr = new FileReader(path);
                 BufferedReader br = new BufferedReader(fr))** {
                return br.readLine();
            }
        }`<br><br>In this example, the resources declared in the `try`-with-resources statement are a `FileReader` and a `BufferedReader`. The declaration statements of these resources appear within parentheses immediately after the `try` keyword. The classes `FileReader` and `BufferedReader`, in Java SE 7 and later, implement the interface `java.lang.AutoCloseable`. Because the `FileReader` and `BufferedReader` instances are declared in a `try`-with-resource statement, they will be closed regardless of whether the `try` statement completes normally or abruptly (as a result of the method `BufferedReader.readLine` throwing an `IOException`).<br><br>Prior to Java SE 7, you can use a `finally` block to ensure that a resource is closed regardless of whether the `try` statement completes normally or abruptly. The following example uses a `finally` block instead of a `try`-with-resources statement:<br><br>`static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {

    FileReader fr = new FileReader(path);
    BufferedReader br = new BufferedReader(fr);
    try {
        return br.readLine();
    } finally {
        br.close();
        fr.close();
    }
}`


*Note that each of the code samples below may throw `IOException`. Try/catch/finally blocks have been omitted for brevity. See [this tutorial](https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html) for information about exception handling.*

*Note that each of the code samples below will overwrite the file if it already exists*

Creating a text file:

```java<br>PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");<br>writer.println("The first line");<br>writer.println("The second line");<br>writer.close();<br><br>```

Creating a binary file:

```java<br>byte data[] = ...<br>FileOutputStream out = new FileOutputStream("the-file-name");<br>out.write(data);<br>out.close();<br><br>```

**Java 7+** users can use the [`Files`](http://docs.oracle.com/javase/7/docs/api/index.html?java/nio/file/Files.html) class to write to files:

Creating a text file:

```java<br>List<String> lines = Arrays.asList("The first line", "The second line");<br>Path file = Paths.get("the-file-name.txt");<br>Files.write(file, lines, StandardCharsets.UTF_8);<br>//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);<br><br>```

Creating a binary file:

```java<br>byte data[] = ...<br>Path file = Paths.get("the-file-name");<br>Files.write(file, data);<br>//Files.write(file, data, StandardOpenOption.APPEND);<br>```


```java<br>PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");<br>writer.println("The first line");<br>writer.println("The second line");<br>writer.close();<br><br>```


Use [`LocalDateTime#parse()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDateTime.html#parse(java.lang.CharSequence,java.time.format.DateTimeFormatter)) (or [`ZonedDateTime#parse()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/ZonedDateTime.html#parse(java.lang.CharSequence,java.time.format.DateTimeFormatter)) if the string happens to contain a time zone part) to parse a `String` in a certain pattern into a `LocalDateTime`.

```java<br>String oldstring = "2011-01-18 00:00:00.0";<br>LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));<br><br>```

Then use [`LocalDateTime#format()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDateTime.html#format(java.time.format.DateTimeFormatter)) (or [`ZonedDateTime#format()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/ZonedDateTime.html#format(java.time.format.DateTimeFormatter))) to format a `LocalDateTime` into a `String` in a certain pattern.

```java<br>String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));<br>System.out.println(newstring); // 2011-01-18<br><br>```

**Or**, when you're not on Java 8 yet, use [`SimpleDateFormat#parse()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/DateFormat.html#parse(java.lang.String)) to parse a `String` in a certain pattern into a `Date`.

```java<br>String oldstring = "2011-01-18 00:00:00.0";<br>Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);<br><br>```

Then use [`SimpleDateFormat#format()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/DateFormat.html#format(java.util.Date)) to format a `Date` into a `String` in a certain pattern.

```java<br>String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);<br>System.out.println(newstring); // 2011-01-18<br><br>```

### See also:

- [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion/)

---

**Update**: as per your failed attempt which you added to the question after this answer was posted; the patterns are **case sensitive**. Carefully read the [`java.text.SimpleDateFormat` javadoc](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/SimpleDateFormat.html) what the individual parts stands for. So stands for example `M` for months and `m` for minutes. Also, years exist of four digits `yyyy`, not five `yyyyy`. Look closer at the code snippets I posted here above.


```java<br>String oldstring = "2011-01-18 00:00:00.0";<br>LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));<br><br>```


- parseObtains an instance of `LocalDateTime` from a text string using a specific formatter.

    public static [LocalDateTime](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDateTime.html) parse([CharSequence](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/CharSequence.html) text,
     [DateTimeFormatter](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html) formatter)

    The text is parsed using the formatter, returning a date-time.

    **Parameters:**`text` - the text to parse, not null`formatter` - the formatter to use, not null**Returns:**the parsed local date-time, not null**Throws:**[`DateTimeParseException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeParseException.html) - if the text cannot be parsed


## Read all text from a file

Java 11 added the [readString()](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path,java.nio.charset.Charset)) method to read small files as a `String`, preserving line terminators:

```java<br>String content = Files.readString(path, encoding);<br><br>```

For versions between Java 7 and 11, here's a compact, robust idiom, wrapped up in a utility method:

```java<br>static String readFile(String path, Charset encoding)<br>  throws IOException<br>{<br>  byte[] encoded = Files.readAllBytes(Paths.get(path));<br>  return new String(encoded, encoding);<br>}<br><br>```

## Read lines of text from a file

Java 7 added a [convenience method to read a file as lines of text,](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29) represented as a `List<String>`. This approach is "lossy" because the line separators are stripped from the end of each line.

```java<br>List<String> lines = Files.readAllLines(Paths.get(path), encoding);<br><br>```

Java 8 added the [`Files.lines()`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-) method to produce a `Stream<String>`. Again, this method is lossy because line separators are stripped. If an `IOException` is encountered while reading the file, it is wrapped in an [`UncheckedIOException`](https://docs.oracle.com/javase/8/docs/api/java/io/UncheckedIOException.html), since `Stream` doesn't accept lambdas that throw checked exceptions.

```java<br>try (Stream<String> lines = Files.lines(path, encoding)) {<br>  lines.forEach(System.out::println);<br>}<br><br>```

This `Stream` does need a [`close()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#close--) call; this is poorly documented on the API, and I suspect many people don't even notice `Stream` has a `close()` method. Be sure to use an ARM-block as shown.

If you are working with a source other than a file, you can use the [`lines()`](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--) method in `BufferedReader` instead.

## Memory utilization

If your file is small enough relative to your available memory, reading the entire file at once might work fine. However, if your file is too large, reading one line at a time, processing it, and then discarding it before moving on to the next could be a better approach. Stream processing in this way can eliminate the total file size as a factor in your memory requirement.

## Character encoding

One thing that is missing from the sample in the original post is the character encoding. This encoding generally can't be determined from the file itself, and requires meta-data such as an HTTP header to convey this important information.

The [`StandardCharsets`](https://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html) class defines some constants for the encodings required of all Java runtimes:

```java<br>String content = readFile("test.txt", StandardCharsets.UTF_8);<br><br>```

The platform default is available from [the `Charset` class](https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html#defaultCharset%28%29) itself:

```java<br>String content = readFile("test.txt", Charset.defaultCharset());<br><br>```

There are some special cases where the platform default is what you want, but they are rare. You should be able justify your choice, because the platform default is not portable. One example where it might be correct is when reading standard input or writing standard output.

---

Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the "edited" link on this answer.


```java<br>try (Stream<String> lines = Files.lines(path, encoding)) {<br>  lines.forEach(System.out::println);<br>}<br><br>```


### readString

```<br>public staticString readString(Path path,Charset cs) throwsIOException<br>```

Reads all characters from a file into a string, decoding from bytes to characters using the specified

[charset](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/charset/Charset.html)

. The method ensures that the file is closed when all content have been read or an I/O error, or other runtime exception, is thrown.

This method reads all content including the line separators in the middle and/or at the end. The resulting string will contain line separators as they appear in the file.

**API Note:**This method is intended for simple cases where it is appropriate and convenient to read the content of a file into a String. It is not intended for reading very large files.**Parameters:**`path` - the path to the file`cs` - the charset to use for decoding**Returns:**a String containing the content read from the file**Throws:**[`IOException`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/IOException.html) - if an I/O error occurs reading from the file or a malformed or unmappable byte sequence is read[`OutOfMemoryError`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/OutOfMemoryError.html) - if the file is extremely large, for example larger than `2GB[SecurityException](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/SecurityException.html)` - In the case of the default provider, and a security manager is installed, the [`checkRead`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/SecurityManager.html#checkRead(java.lang.String)) method is invoked to check read access to the file.**Since:**11