ou can use the [`java.lang.instrument` package](http://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html).

Compile and put this class in a JAR:

```java<br>import java.lang.instrument.Instrumentation;<br><br>public class ObjectSizeFetcher {<br>    private static Instrumentation instrumentation;<br><br>    public static void premain(String args, Instrumentation inst) {<br>        instrumentation = inst;<br>    }<br><br>    public static long getObjectSize(Object o) {<br>        return instrumentation.getObjectSize(o);<br>    }<br>}<br><br>```

Add the following to your `MANIFEST.MF`:

```java<br>Premain-Class: ObjectSizeFetcher<br><br>```

Use the `getObjectSize()` method:

```java<br>public class C {<br>    private int x;<br>    private int y;<br><br>    public static void main(String [] args) {<br>        System.out.println(ObjectSizeFetcher.getObjectSize(new C()));<br>    }<br>}<br><br>```

Invoke with:

```java<br>java -javaagent:ObjectSizeFetcherAgent.jar C<br>```


```java<br>import java.lang.instrument.Instrumentation;<br><br>public class ObjectSizeFetcher {<br>    private static Instrumentation instrumentation;<br><br>    public static void premain(String args, Instrumentation inst) {<br>        instrumentation = inst;<br>    }<br><br>    public static long getObjectSize(Object o) {<br>        return instrumentation.getObjectSize(o);<br>    }<br>}<br><br>```


### *Method Detail*

- addTransformerRegisters the supplied transformer. All future class definitions will be seen by the transformer, except definitions of classes upon which any registered transformer is dependent. The transformer is called when classes are loaded, when they are [redefined](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html#redefineClasses-java.lang.instrument.ClassDefinition...-). and if `canRetransform` is true, when they are [retransformed](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html#retransformClasses-java.lang.Class...-). See [`ClassFileTransformer.transform`](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/ClassFileTransformer.html#transform-java.lang.ClassLoader-java.lang.String-java.lang.Class-java.security.ProtectionDomain-byte:A-) for the order of transform calls. If a transformer throws an exception during execution, the JVM will still call the other registered transformers in order. The same transformer may be added more than once, but it is strongly discouraged -- avoid this by creating a new instance of transformer class.

    ```<br>    void addTransformer(ClassFileTransformer transformer,<br>                        boolean canRetransform)<br>    ```

    This method is intended for use in instrumentation, as described in the [class specification](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html).

    **Parameters:**`transformer` - the transformer to register`canRetransform` - can this transformer's transformations be retransformed**Throws:**[`NullPointerException`](https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html) - if passed a `null` transformer[`UnsupportedOperationException`](https://docs.oracle.com/javase/8/docs/api/java/lang/UnsupportedOperationException.html) - if `canRetransform` is true and the current configuration of the JVM does not allow retransformation ([`isRetransformClassesSupported()`](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html#isRetransformClassesSupported--) is false)**Since:**1.6


Coding from the hip, it would be something like:

```java<br>java.lang.reflect.Method method;<br>try {<br>  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);<br>} catch (SecurityException e) { ... }<br>  catch (NoSuchMethodException e) { ... }<br><br>```

The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give `methodName`).

Then you invoke that method by calling

```java<br>try {<br>  method.invoke(obj, arg1, arg2,...);<br>} catch (IllegalArgumentException e) { ... }<br>  catch (IllegalAccessException e) { ... }<br>  catch (InvocationTargetException e) { ... }<br><br>```

Again, leave out the arguments in `.invoke`, if you don't have any. But yeah. Read about [Java Reflection](http://java.sun.com/docs/books/tutorial/reflect/index.html)


```java<br>java.lang.reflect.Method method;<br>try {<br>  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);<br>} catch (SecurityException e) { ... }<br>  catch (NoSuchMethodException e) { ... }<br><br>```


# **Trail: The Reflection API**

## **Uses of Reflection**

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

**Extensibility Features**An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.**Class Browsers and Visual Development Environments**A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.**Debuggers and Test Tools**Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.

## **Drawbacks of Reflection**

Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

**Performance Overhead**Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.**Security Restrictions**Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.**Exposure of Internals**Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing `private` fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.


Yes, it is a shorthand form of

```java<br>int count;<br>if (isHere)<br>    count = getHereCount(index);<br>else<br>    count = getAwayCount(index);<br><br>```

It's called the **conditional operator**. Many people (erroneously) call it *the ternary operator*, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there *could* be another ternary operator, whereas there can only be one *conditional operator*.

The official name is given in the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25):

> §15.25 Conditional Operator ? :
>
>
> The conditional operator `? :` uses the boolean value of one expression to decide which of two other expressions should be evaluated.
>

Note that both branches must lead to methods with return values:

> It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
>
>
> *In fact, by the grammar of expression statements ([§14.8](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.8)), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.*
>

So, if `doSomething()` and `doSomethingElse()` are void methods, you cannot compress this:

```java<br>if (someBool)<br>    doSomething();<br>else<br>    doSomethingElse();<br><br>```

into this:

```java<br>someBool ? doSomething() : doSomethingElse();<br><br>```

Simple words:

```java<br>booleanCondition ? executeThisPartIfBooleanConditionIsTrue : ex<br>```


```java<br>int count;<br>if (isHere)<br>    count = getHereCount(index);<br>else<br>    count = getAwayCount(index);<br><br>```


## 15.25. Conditional Operator

The conditional operator `? :` uses the boolean value of one expression to decide which of two other expressions should be evaluated.

*ConditionalExpression:[ConditionalOrExpressionConditionalOrExpression](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-ConditionalOrExpression) `?` [Expression](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-Expression) `:` [ConditionalExpression](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-ConditionalExpression)[ConditionalOrExpression](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-ConditionalOrExpression) `?` [Expression](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-Expression) `:` [LambdaExpression](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-LambdaExpression)*

The conditional operator is syntactically right-associative (it groups right-to-left). Thus, `a?b:c?d:e?f:g` means the same as `a?b:(c?d:(e?f:g))`.

The conditional operator has three operand expressions. `?` appears between the first and second expressions, and `:` appears between the second and third expressions.

**The first expression must be of type `boolean` or `Boolean`, or a compile-time error occurs.**

**It is a compile-time error for either the second or the third operand expression to be an invocation of a `void` method.**

*In fact, by the grammar of expression statements ([§14.8](https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.8)), it is not permitted for a conditional expression to appear in any context where an invocation of a `void` method could appear.*

There are three kinds of conditional expressions, classified according to the second and third operand expressions: *boolean conditional expressions*, *numeric conditional expressions*, and *reference conditional expressions*. The classification rules are as follows:

- If both the second and the third operand expressions are *boolean expressions*, the conditional expression is a boolean conditional expression.

    For the purpose of classifying a conditional, the following expressions are boolean expressions:

    - An expression of a standalone form ([§15.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.2)) that has type `boolean` or `Boolean`.
    - A parenthesized `boolean` expression ([§15.8.5](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.5)).
    - A class instance creation expression ([§15.9](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.9)) for class `Boolean`.
    - A method invocation expression ([§15.12](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12)) for which the chosen most specific method ([§15.12.2.5](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5)) has return type `boolean` or `Boolean`.

        *Note that, for a generic method, this is the type before instantiating the method's type arguments.*

    - A `boolean` conditional expression.
- If both the second and the third operand expressions are *numeric expressions*, the conditional expression is a numeric conditional expression.

    For the purpose of classifying a conditional, the following expressions are numeric expressions:

    - An expression of a standalone form ([§15.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.2)) with a type that is convertible to a numeric type ([§4.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2), [§5.1.8](https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.8)).
    - A parenthesized numeric expression ([§15.8.5](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.5)).
    - A class instance creation expression ([§15.9](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.9)) for a class that is convertible to a numeric type.
    - A method invocation expression ([§15.12](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12)) for which the chosen most specific method ([§15.12.2.5](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5)) has a return type that is convertible to a numeric type.
    - A numeric conditional expression.
- Otherwise, the conditional expression is a reference conditional expression.

The process for determining the type of a conditional expression depends on the kind of conditional expression, as outlined in the following sections.


By an "anonymous class", I take it you mean [anonymous inner class](http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html).

An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.

I tend to use it as a shortcut for attaching an event listener:

```java<br>button.addActionListener(new ActionListener() {<br>    @Override<br>    public void actionPerformed(ActionEvent e) {<br>        // do something<br>    }<br>});<br><br>```

Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements `ActionListener` -- I can just instantiate an anonymous inner class without actually making a separate class.

I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.


```java<br>button.addActionListener(new ActionListener() {<br>    @Override<br>    public void actionPerformed(ActionEvent e) {<br>        // do something<br>    }<br>});<br><br>```


# **Inner Class Example**

To see an inner class in use, first consider an array. In the following example, you create an array, fill it with integer values, and then output only values of even indices of the array in ascending order.

The [`DataStructure.java`](https://docs.oracle.com/javase/tutorial/java/javaOO/examples/DataStructure.java) example that follows consists of:

- The `DataStructure` outer class, which includes a constructor to create an instance of `DataStructure` containing an array filled with consecutive integer values (0, 1, 2, 3, and so on) and a method that prints elements of the array that have an even index value.
- The `EvenIterator` inner class, which implements the `DataStructureIterator` interface, which extends the [`Iterator](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)<` [`Integer](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html)>` interface. Iterators are used to step through a data structure and typically have methods to test for the last element, retrieve the current element, and move to the next element.
- A `main` method that instantiates a `DataStructure` object (`ds`), then invokes the `printEven` method to print elements of the array `arrayOfInts` that have an even index value.

`public class DataStructure {

    // Create an array
    private final static int SIZE = 15;
    private int[] arrayOfInts = new int[SIZE];

    public DataStructure() {
        // fill the array with ascending integer values
        for (int i = 0; i < SIZE; i++) {
            arrayOfInts[i] = i;
        }
    }

    public void printEven() {

        // Print out values of even indices of the array
        DataStructureIterator iterator = this.new EvenIterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
    }

    interface DataStructureIterator extends java.util.Iterator<Integer> { }

    // Inner class implements the DataStructureIterator interface,
    // which extends the Iterator<Integer> interface

    private class EvenIterator implements DataStructureIterator {

        // Start stepping through the array from the beginning
        private int nextIndex = 0;

        public boolean hasNext() {

            // Check if the current element is the last in the array
            return (nextIndex <= SIZE - 1);
        }

        public Integer next() {

            // Record a value of an even index of the array
            Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);

            // Get the next even element
            nextIndex += 2;
            return retValue;
        }
    }

    public static void main(String s[]) {

        // Fill the array with integer values and print out only
        // values of even indices
        DataStructure ds = new DataStructure();
        ds.printEven();
    }
}`<br><br>The output is:<br><br>`0 2 4 6 8 10 12 14`


A common pattern is to use

```java<br>try (BufferedReader br = new BufferedReader(new FileReader(file))) {<br>    String line;<br>    while ((line = br.readLine()) != null) {<br>       // process the line.<br>    }<br>}<br><br>```

You can read the data faster if you assume there is no character encoding. e.g. ASCII-7 but it won't make much difference. It is highly likely that what you do with the data will take much longer.

EDIT: A less common pattern to use which avoids the scope of `line` leaking.

```java<br>try(BufferedReader br = new BufferedReader(new FileReader(file))) {<br>    for(String line; (line = br.readLine()) != null; ) {<br>        // process the line.<br>    }<br>    // line is not visible here.<br>}<br><br>```

---

UPDATE: In Java 8 you can do

```java<br>try (Stream<String> stream = Files.lines(Paths.get(fileName))) {<br>        stream.forEach(System.out::println);<br>}<br><br>```

NOTE: You have to place the Stream in a [try-with-resource](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) block to ensure the #close method is called on it, otherwise the underlying file handle is never closed until GC does it much later.


```java<br>try (BufferedReader br = new BufferedReader(new FileReader(file))) {<br>    String line;<br>    while ((line = br.readLine()) != null) {<br>       // process the line.<br>    }<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();
    }
}`

However, this example might have a resource leak. A program has to do more than rely on the garbage collector (GC) to reclaim a resource's memory when it's finished with it. The program must also release the resoure back to the operating system, typically by calling the resource's `close` method. However, if a program fails to do this before the GC reclaims the resource, then the information needed to release the resource is lost. The resource, which is still considered by the operaing system to be in use, has leaked.


You can use the ScriptEngine class and evaluate it as a Javascript string.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("4*5");

There may be a better way, but this one works.


```java<br>ScriptEngineManager manager = new ScriptEngineManager();<br>ScriptEngine engine = manager.getEngineByName("js");<br>Object result = engine.eval("4*5");<br><br>```


## Interface ScriptEngine

- **All Known Implementing Classes:**[AbstractScriptEngine](https://docs.oracle.com/javase/8/docs/api/javax/script/AbstractScriptEngine.html)

    ---

    ```<br>    public interfaceScriptEngine<br>    ```

    `ScriptEngine` is the fundamental interface whose methods must be fully functional in every implementation of this specification.These methods provide basic scripting functionality. Applications written to this simple interface are expected to work with minimal modifications in every implementation. It includes methods that execute scripts, and ones that set and get values.The values are key/value pairs of two types. The first type of pairs consists of those whose keys are reserved and defined in this specification or by individual implementations. The values in the pairs with reserved keys have specified meanings.The other type of pairs consists of those that create Java language Bindings, the values are usually represented in scripts by the corresponding keys or by decorated forms of them.

    **Since:**1.6


From the [`Object.toString`](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#toString%28%29) docs:

> Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
>
>
> The `toString` method for class `Object` returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
>

```java<br>getClass().getName() + '@' + Integer.toHexString(hashCode())<br><br>```

Example:

```java<br>String[] mystr ={"a","b","c"};<br>System.out.println("mystr.toString: " + mystr.toString());<br><br>output:- mystr.toString: [Ljava.lang.String;@13aaa14a<br>```


```java<br>String[] mystr ={"a","b","c"};<br>System.out.println("mystr.toString: " + mystr.toString());<br><br>output:- mystr.toString: [Ljava.lang.String;@13aaa14a<br>```


### toString

```<br>publicStringtoString()<br>```

Returns a string representation of the object. In general, the `toString` method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The `toString` method for class `Object` returns a string consisting of the name of the class of which the object is an instance, the at-sign character ``@`', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:<br><br> `getClass().getName() + '@' + Integer.toHexString(hashCode())`

**Returns:**a string representation of the object.


As of **Java 8**, there is an officially supported API for Base64 encoding and decoding. In time this will probably become the default choice.

The API includes the class [`java.util.Base64`](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html) and its nested classes. It supports three different flavors: basic, URL safe, and MIME.

Sample code using the "basic" encoding:

```java<br>import java.util.Base64;<br><br>byte[] bytes = "Hello, World!".getBytes("UTF-8");<br>String encoded = Base64.getEncoder().encodeToString(bytes);<br>byte[] decoded = Base64.getDecoder().decode(encoded);<br>String decodedStr = new String(decoded, StandardCharsets.UTF_8);<br><br>```

The [documentation for `java.util.Base64`](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html) includes several more methods for configuring encoders and decoders, and for using different classes as inputs and outputs (byte arrays, strings, ByteBuffers, java.io streams).


```java<br>import java.util.Base64;<br><br>byte[] bytes = "Hello, World!".getBytes("UTF-8");<br>String encoded = Base64.getEncoder().encodeToString(bytes);<br>byte[] decoded = Base64.getDecoder().decode(encoded);<br>String decodedStr = new String(decoded, StandardCharsets.UTF_8);<br><br>```


## Class Base64

- [java.lang.Object](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html)
- java.util.Base64
- This class consists exclusively of static methods for obtaining encoders and decoders for the Base64 encoding scheme. The implementation of this class supports the following types of Base64 as specified in [RFC 4648](http://www.ietf.org/rfc/rfc4648.txt) and [RFC 2045](http://www.ietf.org/rfc/rfc2045.txt).

    ```<br>    public classBase64<br>    extendsObject<br>    ```

    - **Basic**

        Uses "The Base64 Alphabet" as specified in Table 1 of RFC 4648 and RFC 2045 for encoding and decoding operation. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.

    - **URL and Filename safe**

        Uses the "URL and Filename safe Base64 Alphabet" as specified in Table 2 of RFC 4648 for encoding and decoding. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.

    - **MIME**

        Uses the "The Base64 Alphabet" as specified in Table 1 of RFC 2045 for encoding and decoding operation. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return `'\r'` followed immediately by a linefeed `'\n'` as the line separator. No line separator is added to the end of the encoded output. All line separators or other characters not found in the base64 alphabet table are ignored in decoding operation.

    Unless otherwise noted, passing a `null` argument to a method of this class will cause a [`NullPointerException`](https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html) to be thrown.

    **Since:**1.8


In Java 8 you can use the [`Supplier`](https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html) functional interface to achieve this pretty easily:

```java<br>class SomeContainer<E> {<br>  private Supplier<E> supplier;<br><br>  SomeContainer(Supplier<E> supplier) {<br>    this.supplier = supplier;<br>  }<br><br>  E createContents() {<br>    return supplier.get();<br>  }<br>}<br><br>```

You would construct this class like this:

```java<br>SomeContainer<String> stringContainer = new SomeContainer<>(String::new);<br><br>```

The syntax `String::new` on that line is a [constructor reference](https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html).

If your constructor takes arguments you can use a lambda expression instead:

```java<br>SomeContainer<BigInteger> bigIntegerContainer<br>    = new SomeContainer<>(() -> new BigInteger(1));<br>```


```java<br>class SomeContainer<E> {<br>  private Supplier<E> supplier;<br><br>  SomeContainer(Supplier<E> supplier) {<br>    this.supplier = supplier;<br>  }<br><br>  E createContents() {<br>    return supplier.get();<br>  }<br>}<br><br>```


## Interface Supplier<T>

- **Type Parameters:**`T` - the type of results supplied by this supplierRepresents a supplier of results.

    **Functional Interface:**This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

    ---

    ```<br>    @FunctionalInterface<br>    public interfaceSupplier<T><br>    ```

    There is no requirement that a new or distinct result be returned each time the supplier is invoked.

    This is a [functional interface](https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html) whose functional method is [`get()`](https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html#get--).

    **Since:**1.8


Straight from the API Specifications for the [`ClassCastException`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassCastException.html):

> Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
>

So, for example, when one tries to cast an `Integer` to a `String`, `String` is not an subclass of `Integer`, so a `ClassCastException` will be thrown.

```java<br>Object i = Integer.valueOf(42);<br>String s = (String)i;            // ClassCastException thrown<br>```


```java<br>Object i = Integer.valueOf(42);<br>String s = (String)i;            // ClassCastException thrown<br>```


## Class ClassCastException

```<br>java.lang.Objectjava.lang.Throwablejava.lang.Exceptionjava.lang.RuntimeExceptionjava.lang.ClassCastException<br>```

!https://docs.oracle.com/javase/1.5.0/docs/api/resources/inherit.gif

!https://docs.oracle.com/javase/1.5.0/docs/api/resources/inherit.gif

!https://docs.oracle.com/javase/1.5.0/docs/api/resources/inherit.gif

!https://docs.oracle.com/javase/1.5.0/docs/api/resources/inherit.gif

**All Implemented Interfaces:**[Serializable](https://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html)

---

`public class **ClassCastException**extends [RuntimeException](https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/RuntimeException.html)`

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a `ClassCastException`:

> Object x = new Integer(0);
     System.out.println((String)x);
>

**Since:**JDK1.0**See Also:**[Serialized Form](https://docs.oracle.com/javase/1.5.0/docs/api/serialized-form.html#java.lang.ClassCastException)

---

Constructor Summary

---

```<br>ClassCastException()<br>```

Constructs a

```<br>ClassCastException<br>```

with no detail message.

---

```<br>ClassCastException(String s)<br>```

Constructs a

```<br>ClassCastException<br>```

with the specified detail message.

---

Method Summary

---

Methods inherited from class java.lang.[Throwable](https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Throwable.html)

---

```<br>fillInStackTrace,getCause,getLocalizedMessage,getMessage,getStackTrace,initCause,printStackTrace,printStackTrace,printStackTrace,setStackTrace,toString<br>```

---

Methods inherited from class java.lang.[Object](https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html)

---

```<br>clone,equals,finalize,getClass,hashCode,notify,notifyAll,wait,wait,wait<br>```

---


A simple example to illustrate how `java.util.Scanner` works would be reading a single integer from `System.in`. It's really quite simple.

```java<br>Scanner sc = new Scanner(System.in);<br>int i = sc.nextInt();<br><br>```

To retrieve a username I would probably use [`sc.nextLine()`](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine%28%29).

```java<br>System.out.println("Enter your username: ");<br>Scanner scanner = new Scanner(System.in);<br>String username = scanner.nextLine();<br>System.out.println("Your username is " + username);<br><br>```

You could also use [`next(String pattern)`](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28java.lang.String%29) if you want more control over the input, or just validate the `username` variable.

You'll find more information on their implementation in the [API Documentation for `java.util.Scanner`](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)


```java<br>System.out.println("Enter your username: ");<br>Scanner scanner = new Scanner(System.in);<br>String username = scanner.nextLine();<br>System.out.println("Your username is " + username);<br><br>```


- nextLineAdvances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

    ```<br>    publicString nextLine()<br>    ```

    Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

    **Returns:**the line that was skipped**Throws:**[`NoSuchElementException`](https://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html) - if no line was found[`IllegalStateException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalStateException.html) - if this scanner is closed


- Add each number in the range sequentially in a [list](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/List.html) structure.
- [Shuffle](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Collections.html#shuffle(java.util.List)) it.
- Take the first 'n'.

Here is a simple implementation. This will print 3 unique random numbers from the range 1-10.

```java<br>import java.util.ArrayList;<br>import java.util.Collections;<br><br>public class UniqueRandomNumbers {<br><br>    public static void main(String[] args) {<br>        ArrayList<Integer> list = new ArrayList<Integer>();<br>        for (int i=1; i<11; i++) list.add(i);<br>        Collections.shuffle(list);<br>        for (int i=0; i<3; i++) System.out.println(list.get(i));<br>    }<br>}<br><br>```

---

The first part of the fix with the original approach, as Mark Byers pointed out in an answer now deleted, is to use only a single `Random` instance.

That is what is causing the numbers to be identical. A `Random` instance is seeded by the current time in milliseconds. For a particular **seed value,** the 'random' instance will return the exact same **sequence of *pseudo random* numbers.**


```java<br>import java.util.ArrayList;<br>import java.util.Collections;<br><br>public class UniqueRandomNumbers {<br><br>    public static void main(String[] args) {<br>        ArrayList<Integer> list = new ArrayList<Integer>();<br>        for (int i=1; i<11; i++) list.add(i);<br>        Collections.shuffle(list);<br>        for (int i=0; i<3; i++) System.out.println(list.get(i));<br>    }<br>}<br><br>```


### shuffle

```<br>public static void shuffle(List<?> list)<br>```

Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.

The hedge "approximately" is used in the foregoing description because default source of randomness is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm would choose permutations with perfect uniformity.

This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the "current position". Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.

This method runs in linear time. If the specified list does not implement the [`RandomAccess`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/RandomAccess.html) interface and is large, this implementation dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a "sequential access" list in place.

**Parameters:**`list` - the list to be shuffled.**Throws:**[`UnsupportedOperationException`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/UnsupportedOperationException.html) - if the specified list or its list-iterator does not support the `set` operation.


**Code :**

```java<br>public class JavaApplication {<br>  public static void main(String[] args) {<br>    System.out.println("Working Directory = " + System.getProperty("user.dir"));<br>  }<br>}<br><br>```

*This will print the absolute path of the current directory from where your application was initialized.*

---

**Explanation:**

From the [documentation](https://docs.oracle.com/javase/7/docs/api/java/io/File.html):

`java.io` package resolve relative pathnames using current user directory. The current directory is represented as system property, that is, `user.dir` and is the directory from where the JVM was invoked.


```java<br>public class JavaApplication {<br>  public static void main(String[] args) {<br>    System.out.println("Working Directory = " + System.getProperty("user.dir"));<br>  }<br>}<br><br>```


java.io

## Class File

- [java.lang.Object](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html)
- java.io.File
- **All Implemented Interfaces:**[Serializable](https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html), [Comparable](https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html)<[File](https://docs.oracle.com/javase/7/docs/api/java/io/File.html)>An abstract representation of file and directory pathnames.The first name in an abstract pathname may be a directory name or, in the case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name in an abstract pathname denotes a directory; the last name may denote either a directory or a file. The *empty* abstract pathname has no prefix and an empty name sequence.

    ---

    ```<br>    public classFile<br>    extendsObject<br>    implementsSerializable,Comparable<File><br>    ```

    User interfaces and operating systems use system-dependent *pathname strings* to name files and directories. This class presents an abstract, system-independent view of hierarchical pathnames. An *abstract pathname* has two components:

    1. An optional system-dependent *prefix* string, such as a disk-drive specifier, `"/"` for the UNIX root directory, or `"\\\\"` for a Microsoft Windows UNC pathname, and
    2. A sequence of zero or more string *names*.

    The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default *separator character*. The default name-separator character is defined by the system property `file.separator`, and is made available in the public static fields [`separator`](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#separator) and [`separatorChar`](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#separatorChar) of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.

    A pathname, whether abstract or in string form, may be either *absolute* or *relative*. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the `java.io` package always resolve relative pathnames against the current user directory. This directory is named by the system property `user.dir`, and is typically the directory in which the Java virtual machine was invoked.

    The *parent* of an abstract pathname may be obtained by invoking the [`getParent()`](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#getParent()) method of this class and consists of the pathname's prefix and each name in the pathname's name sequence except for the last. Each directory's absolute pathname is an ancestor of any File object with an absolute abstract pathname which begins with the directory's absolute pathname. For example, the directory denoted by the abstract pathname "/usr" is an ancestor of the directory denoted by the pathname "/usr/local/bin".

    The prefix concept is used to handle root directories on UNIX platforms, and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms, as follows:

    - For UNIX platforms, the prefix of an absolute pathname is always `"/"`. Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix `"/"` and an empty name sequence.
    - For Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier consists of the drive letter followed by `":"` and possibly followed by `"\\"` if the pathname is absolute. The prefix of a UNC pathname is `"\\\\"`; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix.

    Instances of this class may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a *partition*. A partition is an operating system-specific portion of storage for a file system. A single storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may contain multiple partitions. The object, if any, will reside on the partition named by some ancestor of the absolute form of this pathname.

    A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as *access permissions*. The file system may have multiple sets of access permissions on a single object. For example, one set may apply to the object's *owner*, and another may apply to all other users. The access permissions on an object may cause some methods in this class to fail.

    Instances of the `File` class are immutable; that is, once created, the abstract pathname represented by a `File` object will never change.

    ### Interoperability with `java.nio.file` package

    The [`java.nio.file`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/package-summary.html) package defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems. This API may be used to overcome many of the limitations of the `java.io.File` class. The [`toPath`](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#toPath()) method may be used to obtain a [`Path`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html) that uses the abstract path represented by a `File` object to locate a file. The resulting `Path` may be used with the [`Files`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) class to provide more efficient and extensive access to additional file operations, file attributes, and I/O exceptions to help diagnose errors when an operation on a file fails.

    **Since:**JDK1.0**See Also:**[Serialized Form](https://docs.oracle.com/javase/7/docs/api/serialized-form.html#java.io.File)


Java 8 ([2014](https://www.oracle.com/java/technologies/javase/8-whats-new.html)) solves this problem using streams and lambdas in one line of code:

```java<br>List<Person> beerDrinkers = persons.stream()<br>    .filter(p -> p.getAge() > 16).collect(Collectors.toList());<br><br>```

Here's a [tutorial](http://zeroturnaround.com/rebellabs/java-8-explained-applying-lambdas-to-java-collections/).

Use [`Collection#removeIf`](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-) to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate):

```java<br>persons.removeIf(p -> p.getAge() <= 16);<br><br>```

---

[lambdaj](https://code.google.com/archive/p/lambdaj/) allows filtering collections without writing loops or inner classes:

```java<br>List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),<br>    greaterThan(16)));<br><br>```

Can you imagine something more readable?

**Disclaimer:** I am a contributor on lambdaj


```java<br>List<Person> beerDrinkers = persons.stream()<br>    .filter(p -> p.getAge() > 16).collect(Collectors.toList());<br><br>```


- removeIf

    ```<br>    default boolean removeIf(Predicate<? superE> filter)<br>    ```

    Removes all of the elements of this collection that satisfy the given predicate. Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller.

    **Implementation Requirements:**The default implementation traverses all elements of the collection using its [`iterator()`](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#iterator--). Each matching element is removed using [`Iterator.remove()`](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#remove--). If the collection's iterator does not support removal then an `UnsupportedOperationException` will be thrown on the first matching element.**Parameters:**`filter` - a predicate which returns `true` for elements to be removed**Returns:**`true` if any elements were removed**Throws:**[`NullPointerException`](https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html) - if the specified filter is null[`UnsupportedOperationException`](https://docs.oracle.com/javase/8/docs/api/java/lang/UnsupportedOperationException.html) - if elements cannot be removed from this collection. Implementations may throw this exception if a matching element cannot be removed or if, in general, removal is not supported.**Since:**1.8


see https://stackoverflow.com/a/20906602/314283

Java does appear to be well behind the eight-ball compared to C#. This utility method shows the way to do in Java SE 6 using the [Calendar.add method](http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#add%28int,%20int%29) (presumably the only easy way).

```java<br>public class DateUtil<br>{<br>    public static Date addDays(Date date, int days)<br>    {<br>        Calendar cal = Calendar.getInstance();<br>        cal.setTime(date);<br>        cal.add(Calendar.DATE, days); //minus number would decrement the days<br>        return cal.getTime();<br>    }<br>}<br><br>```

To add one day, per the question asked, call it as follows:

```java<br>String sourceDate = "2012-02-29";<br>SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");<br>Date myDate = format.parse(sourceDate);<br>myDate = DateUtil.addDays(myDate, 1);<br>```


```java<br>String sourceDate = "2012-02-29";<br>SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");<br>Date myDate = format.parse(sourceDate);<br>myDate = DateUtil.addDays(myDate, 1);<br>```


### add

```<br>public abstract voidadd(int field,<br>                         int amount)<br>```

Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:`add(Calendar.DAY_OF_MONTH, -5)`.
**Parameters:**`field` - the calendar field.`amount` - the amount of date or time to be added to the field.**See Also:**[`roll(int,int)`](https://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#roll(int,%20int)), [`set(int,int)`](https://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#set(int,%20int))


You could use `printf()` with `%f`:

```java<br>double dexp = 12345678;<br>System.out.printf("dexp: %f\n", dexp);<br><br>```

This will print `dexp: 12345678.000000`. If you don't want the fractional part, use

```java<br>System.out.printf("dexp: %.0f\n", dexp);<br><br>```

0 in `%.0f` means 0 places in fractional part i.e no fractional part. If you want to print fractional part with desired number of decimal places then instead of 0 just provide the number like this `%.8f`. By default fractional part is printed up to 6 decimal places.

This uses the format specifier language explained in the [documentation](http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax).

The default `toString()` format used in your original code is spelled out [here](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#toString%28double%29).


```java<br>double dexp = 12345678;<br>System.out.printf("dexp: %f\n", dexp);<br><br>```


### Format String Syntax

Every method which produces formatted output requires a *format string* and an *argument list*. The format string is a [`String`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html) which may contain fixed text and one or more embedded *format specifiers*. Consider the following example:

> Calendar c = ...;
   String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
>

This format string is the first argument to the

```<br>format<br>```

method. It contains three format specifiers "

```<br>%1$tm<br>```

", "

```<br>%1$te<br>```

", and "

```<br>%1$tY<br>```

" which indicate how the arguments should be processed and where they should be inserted in the text. The remaining portions of the format string are fixed text including

```<br>"Dukes Birthday: "<br>```

and any other spaces or punctuation. The argument list consists of all arguments passed to the method after the format string. In the above example, the argument list is of size one and consists of the

[`Calendar`](https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html)

object

```<br>c<br>```

.

- The format specifiers for general, character, and numeric types have the following syntax:

    > %[argument_index$][flags][width][.precision]conversion
    >

    The optional *argument_index* is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "`1$`", the second by "`2$`", etc.

    The optional *flags* is a set of characters that modify the output format. The set of valid flags depends on the conversion.

    The optional *width* is a non-negative decimal integer indicating the minimum number of characters to be written to the output.

    The optional *precision* is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.

    The required *conversion* is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

- The format specifiers for types which are used to represents dates and times have the following syntax:

    > %[argument_index$][flags][width]conversion
    >

    The optional *argument_index*, *flags* and *width* are defined as above.

    The required *conversion* is a two character sequence. The first character is `'t'` or `'T'`. The second character indicates the format to be used. These characters are similar to but not completely identical to those defined by GNU `date` and POSIX `strftime(3c)`.

- The format specifiers which do not correspond to arguments have the following syntax:

    > %[flags][width]conversion
    >

    The optional *flags* and *width* is defined as above.

    The required *conversion* is a character indicating content to be inserted in the output.


You can use any of the following options based on the requirements.

## [`Scanner`](http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html) class

```java<br>import java.util.Scanner;<br>//...<br>Scanner scan = new Scanner(System.in);<br>String s = scan.next();<br>int i = scan.nextInt();<br><br>```

---

## [`BufferedReader`](http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html) and [`InputStreamReader`](http://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html) classes

```java<br>import java.io.BufferedReader;<br>import java.io.InputStreamReader;<br>//...<br>BufferedReader br = new BufferedReader(new InputStreamReader(System.in));<br>String s = br.readLine();<br>int i = Integer.parseInt(s);<br><br>```

---

### [`DataInputStream`](http://docs.oracle.com/javase/8/docs/api/java/io/DataInputStream.html) class

```java<br>import java.io.DataInputStream;<br>//...<br>DataInputStream dis = new DataInputStream(System.in);<br>int i = dis.readInt();<br><br>```

The `readLine` method from the `DataInputStream` class has been *deprecated*. To get String value, you should use the previous solution with BufferedReader

---

### [`Console`](http://docs.oracle.com/javase/8/docs/api/java/io/Console.html) class

```java<br>import java.io.Console;<br>//...<br>Console console = System.console();<br>String s = console.readLine();<br>int i = Integer.parseInt(console.readLine());<br><br>```

Apparently, this method does not work well in some IDEs.


```java<br>import java.util.Scanner;<br>//...<br>Scanner scan = new Scanner(System.in);<br>String s = scan.next();<br>int i = scan.nextInt();<br><br>```


## Class Scanner

- [java.lang.Object](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html)
- java.util.Scanner
- **All Implemented Interfaces:**[Closeable](https://docs.oracle.com/javase/8/docs/api/java/io/Closeable.html), [AutoCloseable](https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html), [Iterator](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)<[String](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html)>A simple text scanner which can parse primitive types and strings using regular expressions.

    ---

    ```<br>    public final classScanner<br>    extendsObject<br>    implementsIterator<String>,Closeable<br>    ```

    A `Scanner` breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

    For example, this code allows a user to read a number from System.in:

    > Scanner sc = new Scanner(System.in);
         int i = sc.nextInt();
    >

    As another example, this code allows `long` types to be assigned from entries in a file `myNumbers`:

    > Scanner sc = new Scanner(new File("myNumbers"));
          while (sc.hasNextLong()) {
              long aLong = sc.nextLong();
          }
    >

    The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

    > String input = "1 fish 2 fish red fish blue fish";
         Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
         System.out.println(s.nextInt());
         System.out.println(s.nextInt());
         System.out.println(s.next());
         System.out.println(s.next());
         s.close();
    >

    prints the following output:

    > 1
         2
         red
         blue
    >

    The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:

    > String input = "1 fish 2 fish red fish blue fish";
         Scanner s = new Scanner(input);
         s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
         MatchResult result = s.match();
         for (int i=1; i<=result.groupCount(); i++)
             System.out.println(result.group(i));
         s.close();
    >

    The default whitespace delimiter used by a scanner is as recognized by [`Character`](https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html).[`isWhitespace`](https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-). The [`reset()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#reset--) method will reset the value of the scanner's delimiter to the default whitespace delimiter regardless of whether it was previously changed.

    A scanning operation may block waiting for input.

    The [`next()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#next--) and [`hasNext()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNext--) methods and their primitive-type companion methods (such as [`nextInt()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextInt--) and [`hasNextInt()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNextInt--)) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.

    The [`findInLine(java.lang.String)`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#findInLine-java.lang.String-), [`findWithinHorizon(java.lang.String, int)`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#findWithinHorizon-java.lang.String-int-), and [`skip(java.util.regex.Pattern)`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#skip-java.util.regex.Pattern-) methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.

    When a scanner throws an [`InputMismatchException`](https://docs.oracle.com/javase/8/docs/api/java/util/InputMismatchException.html), the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

    Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern "\\s+" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern "\\s" could return empty tokens since it only passes one space at a time.

    A scanner can read text from any object which implements the [`Readable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Readable.html) interface. If an invocation of the underlying readable's [`Readable.read(java.nio.CharBuffer)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Readable.html#read-java.nio.CharBuffer-) method throws an [`IOException`](https://docs.oracle.com/javase/8/docs/api/java/io/IOException.html) then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via the [`ioException()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#ioException--) method.

    When a `Scanner` is closed, it will close its input source if the source implements the [`Closeable`](https://docs.oracle.com/javase/8/docs/api/java/io/Closeable.html) interface.

    A `Scanner` is not safe for multithreaded use without external synchronization.

    Unless otherwise mentioned, passing a `null` parameter into any method of a `Scanner` will cause a `NullPointerException` to be thrown.

    A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the [`useRadix(int)`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#useRadix-int-) method. The [`reset()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#reset--) method will reset the value of the scanner's radix to `10` regardless of whether it was previously changed.


Use:

```java<br>public void listFilesForFolder(final File folder) {<br>    for (final File fileEntry : folder.listFiles()) {<br>        if (fileEntry.isDirectory()) {<br>            listFilesForFolder(fileEntry);<br>        } else {<br>            System.out.println(fileEntry.getName());<br>        }<br>    }<br>}<br><br>final File folder = new File("/home/you/Desktop");<br>listFilesForFolder(folder);<br><br>```

The [Files.walk](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption...-) API is available from Java 8.

```java<br>try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {<br>    paths<br>        .filter(Files::isRegularFile)<br>        .forEach(System.out::println);<br>}<br><br>```

The example uses the [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) pattern recommended in the API guide. It ensures that no matter circumstances, the stream will be closed.


```java<br>public void listFilesForFolder(final File folder) {<br>    for (final File fileEntry : folder.listFiles()) {<br>        if (fileEntry.isDirectory()) {<br>            listFilesForFolder(fileEntry);<br>        } else {<br>            System.out.println(fileEntry.getName());<br>        }<br>    }<br>}<br><br>final File folder = new File("/home/you/Desktop");<br>listFilesForFolder(folder);<br><br>```


- walkReturn a `Stream` that is lazily populated with `Path` by walking the file tree rooted at a given starting file. The file tree is traversed *depth-first*, the elements in the stream are [`Path`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html) objects that are obtained as if by [`resolving`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html#resolve-java.nio.file.Path-) the relative path against `start`.In other words, it visits all levels of the file tree.

    ```<br>    public staticStream<Path> walk(Path start,<br>    FileVisitOption... options)<br>                             throwsIOException<br>    ```

    This method works as if invoking it were equivalent to evaluating the expression:

    > walk(start, Integer.MAX_VALUE, options)
    >

    The returned stream encapsulates one or more [`DirectoryStream`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/DirectoryStream.html)s. If timely disposal of file system resources is required, the `try`-with-resources construct should be used to ensure that the stream's [`close`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#close--) method is invoked after the stream operations are completed. Operating on a closed stream will result in an [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html).

    **Parameters:**`start` - the starting file`options` - options to configure the traversal**Returns:**the [`Stream`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html) of [`Path`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html)**Throws:**[`SecurityException`](https://docs.oracle.com/javase/8/docs/api/java/lang/SecurityException.html) - If the security manager denies access to the starting file. In the case of the default provider, the [`checkRead`](https://docs.oracle.com/javase/8/docs/api/java/lang/SecurityManager.html#checkRead-java.lang.String-) method is invoked to check read access to the directory.[`IOException`](https://docs.oracle.com/javase/8/docs/api/java/io/IOException.html) - if an I/O error is thrown when accessing the starting file.**Since:**1.8**See Also:**[`walk(Path, int, FileVisitOption...)`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-int-java.nio.file.FileVisitOption...-)


You can try using [System.arraycopy()](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy%28java.lang.Object,%20int,%20java.lang.Object,%20int,%20int%29)

```java<br>int[] src  = new int[]{1,2,3,4,5};<br>int[] dest = new int[5];<br><br>System.arraycopy( src, 0, dest, 0, src.length );<br><br>```

But, probably better to use clone() in most cases:

```java<br>int[] src = ...<br>int[] dest = src.clone();<br>```


```java<br>int[] src  = new int[]{1,2,3,4,5};<br>int[] dest = new int[5];<br><br>System.arraycopy( src, 0, dest, 0, src.length );<br><br>```


- arraycopyCopies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by `src` to the destination array referenced by `dest`. The number of components copied is equal to the `length` argument. The components at positions `srcPos` through `srcPos+length-1` in the source array are copied into positions `destPos` through `destPos+length-1`, respectively, of the destination array.

    ```<br>    public static void arraycopy(Object src,<br>                 int srcPos,<br>    Object dest,<br>                 int destPos,<br>                 int length)<br>    ```

    If the `src` and `dest` arguments refer to the same array object, then the copying is performed as if the components at positions `srcPos` through `srcPos+length-1` were first copied to a temporary array with `length` components and then the contents of the temporary array were copied into positions `destPos` through `destPos+length-1` of the destination array.

    If `dest` is `null`, then a `NullPointerException` is thrown.

    If `src` is `null`, then a `NullPointerException` is thrown and the destination array is not modified.

    Otherwise, if any of the following is true, an `ArrayStoreException` is thrown and the destination is not modified:

    - The `src` argument refers to an object that is not an array.
    - The `dest` argument refers to an object that is not an array.
    - The `src` argument and `dest` argument refer to arrays whose component types are different primitive types.
    - The `src` argument refers to an array with a primitive component type and the `dest` argument refers to an array with a reference component type.
    - The `src` argument refers to an array with a reference component type and the `dest` argument refers to an array with a primitive component type.

    Otherwise, if any of the following is true, an `IndexOutOfBoundsException` is thrown and the destination is not modified:

    - The `srcPos` argument is negative.
    - The `destPos` argument is negative.
    - The `length` argument is negative.
    - `srcPos+length` is greater than `src.length`, the length of the source array.
    - `destPos+length` is greater than `dest.length`, the length of the destination array.

    Otherwise, if any actual component of the source array from position `srcPos` through `srcPos+length-1` cannot be converted to the component type of the destination array by assignment conversion, an `ArrayStoreException` is thrown. In this case, let ***k*** be the smallest nonnegative integer less than length such that `src[srcPos+`*k*`]` cannot be converted to the component type of the destination array; when the exception is thrown, source array components from positions `srcPos` through `srcPos+`*k*`-1` will already have been copied to destination array positions `destPos` through `destPos+`*k*`-1` and no other positions of the destination array will have been modified. (Because of the restrictions already itemized, this paragraph effectively applies only to the situation where both arrays have component types that are reference types.)

    **Parameters:**`src` - the source array.`srcPos` - starting position in the source array.`dest` - the destination array.`destPos` - starting position in the destination data.`length` - the number of array elements to be copied.**Throws:**[`IndexOutOfBoundsException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html) - if copying would cause access of data outside array bounds.[`ArrayStoreException`](https://docs.oracle.com/javase/7/docs/api/java/lang/ArrayStoreException.html) - if an element in the `src` array could not be stored into the `dest` array because of a type mismatch.[`NullPointerException`](https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html) - if either `src` or `dest` is `null`.


Since Java 1.5, [`String.format()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-) can be used to left/right pad a given string.

```java<br>public static String padRight(String s, int n) {<br>     return String.format("%-" + n + "s", s);<br>}<br><br>public static String padLeft(String s, int n) {<br>    return String.format("%" + n + "s", s);<br>}<br><br>...<br><br>public static void main(String args[]) throws Exception {<br> System.out.println(padRight("Howto", 20) + "*");<br> System.out.println(padLeft("Howto", 20) + "*");<br>}<br><br>```

And the output is:

```java<br>Howto               *<br>               Howto*<br>```


```java<br>public static String padRight(String s, int n) {<br>     return String.format("%-" + n + "s", s);<br>}<br><br>public static String padLeft(String s, int n) {<br>    return String.format("%" + n + "s", s);<br>}<br><br>...<br><br>public static void main(String args[]) throws Exception {<br> System.out.println(padRight("Howto", 20) + "*");<br> System.out.println(padLeft("Howto", 20) + "*");<br>}<br><br>```


- formatReturns a formatted string using the specified format string and arguments.

    ```<br>    public staticString format(String format,<br>    Object... args)<br>    ```

    The locale always used is the one returned by [`Locale.getDefault()`](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#getDefault--).

    **Parameters:**`format` - A [format string](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax)`args` - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java™ Virtual Machine Specification. The behaviour on a `null` argument depends on the [conversion](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax).**Returns:**A formatted string**Throws:**[`IllegalFormatException`](https://docs.oracle.com/javase/8/docs/api/java/util/IllegalFormatException.html) - If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the [Details](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#detail) section of the formatter class specification.**Since:**1.5**See Also:**[`Formatter`](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html)


Neither of them. If you define it, it's not the default.

The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are `String`, `int` and `int`, and that the class itself is public:

```java<br>public Module()<br>{<br>  super();<br>  this.name = null;<br>  this.credits = 0;<br>  this.hours = 0;<br>}<br><br>```

This is exactly the same as

```java<br>public Module()<br>{}<br><br>```

And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.

See the [Java specifications](https://docs.oracle.com/javase/specs/), specifically: Section [8.8.9. Default Constructor](https://docs.oracle.com/javase/specs/jls/se22/html/jls-8.html#jls-8.8.9) of *Java Language Specification*.

> If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:
>
> - The default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access (§6.6).
> - The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).
> - The default constructor has no `throws` clause.

### Clarification

Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because

- the question got the defaults wrong, and
- the constructor has exactly the same effect whether they are included or not.


```java<br>public Module()<br>{<br>  super();<br>  this.name = null;<br>  this.credits = 0;<br>  this.hours = 0;<br>}<br><br>```


If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:

- The default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access ([§6.6](https://docs.oracle.com/javase/specs/jls/se22/html/jls-6.html#jls-6.6)).
- The default constructor has no formal parameters, except in a non-`private` inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class ([§8.8.1](https://docs.oracle.com/javase/specs/jls/se22/html/jls-8.html#jls-8.8.1), [§15.9.2](https://docs.oracle.com/javase/specs/jls/se22/html/jls-15.html#jls-15.9.2), [§15.9.3](https://docs.oracle.com/javase/specs/jls/se22/html/jls-15.html#jls-15.9.3)).
- The default constructor has no `throws` clause.
- If the class being declared is the primordial class `Object`, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

The form of the default constructor for an anonymous class is specified in [§15.9.5.1](https://docs.oracle.com/javase/specs/jls/se22/html/jls-15.html#jls-15.9.5.1).


Java will always try to use the most specific applicable version of a method that's available (see [JLS §15.12.2](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5)).

`Object`, `char[]` and `Integer` can all take `null` as a valid value. Therefore all 3 version are applicable, so Java will have to find the most specific one.

Since `Object` is the super-type of `char[]`, the array version is more specific than the `Object`-version. So if only those two methods exist, the `char[]` version will be chosen.

When both the `char[]` and `Integer` versions are available, then **both** of them are more specific than `Object` but none is more specific than the other, so Java can't decide which one to call. In this case you'll have to explicitly mention which one you want to call by casting the argument to the appropriate type.

Note that in practice this problem occurs far more seldom than one might think. The reason for this is that it only happens when you're explicitly calling a method with `null` or with a variable of a rather un-specific type (such as `Object`).

On the contrary, the following invocation would be perfectly unambiguous:

```java<br>char[] x = null;<br>doSomething(x);<br><br>```

Although you're still passing the value `null`, Java knows exactly which method to call, since it will take the type of the variable into account.


```java<br>char[] x = null;<br>doSomething(x);<br><br>```


**15.12.2.5. Choosing the Most Specific Method**

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the *most specific* method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

One fixed-arity member method named `m` is *more specific* than another member method of the same name and arity if all of the following conditions hold:

- The declared types of the parameters of the first member method are T1, ..., Tn.
- The declared types of the parameters of the other method are U1, ..., Un.
- If the second method is generic, then let R1 ... Rp (*p* ≥ 1) be its type parameters, let Bl be the declared bound of Rl (1 ≤ *l* ≤ *p*), let A1 ... Ap be the type arguments inferred ([§15.12.2.7](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.7)) for this invocation under the initial constraints Ti << Ui (1 ≤ *i* ≤ *n*), and let Si = Ui`[`R1=A1,...,Rp=Ap`]` (1 ≤ *i* ≤ *n*).

    Otherwise, let Si = Ui (1 ≤ *i* ≤ *n*).

- For all *j* from 1 to *n*, Tj `<:` Sj.
- If the second method is a generic method as described above, then Al `<:` Bl`[`R1=A1,...,Rp=Ap`]` (1 ≤ *l* ≤ *p*).


`split(delimiter)` by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of `split(delimiter, limit)` with `limit` set to negative value like

```java<br>String[] split = data.split("\\|", -1);<br><br>```

Little more details:

`split(regex)` internally returns result of `split(regex, 0)` and in [documentation](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-int-) of this method you can find (emphasis mine)

> The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
>
>
> If the limit `n` is *greater than zero* then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
>
> If `n` is **non-positive** then the pattern will be applied as many times as possible and the array can have any length.
>
> If `n` is **zero** then the pattern will be applied as many times as possible, the array can have any length, and **trailing empty strings will be discarded**.
>

**Exception**:

It is worth mentioning that removing trailing empty string makes sense *only if such empty strings were created by the split mechanism*. So for `"".split(anything)` since we can't split `""` farther we will get as result `[""]` array.

It happens because split didn't happen here, so `""` despite being empty and trailing represents *original* string, not empty string which was *created* by splitting process.


```java<br>String[] split = data.split("\\|", -1);<br><br>```


The `limit` parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit *n* is greater than zero then the pattern will be applied at most *n* - 1 times, the array's length will be no greater than *n*, and the array's last entry will contain all input beyond the last matched delimiter. If *n* is non-positive then the pattern will be applied as many times as possible and the array can have any length. If *n* is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.


From **JDK 7** you can use [`Files.readAllBytes(Path)`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllBytes(java.nio.file.Path)).

Example:

```java<br>import java.io.File;<br>import java.nio.file.Files;<br><br>File file;<br>// ...(file is initialised)...<br>byte[] fileContent = Files.readAllBytes(file.toPath());<br>```


```java<br>import java.io.File;<br>import java.nio.file.Files;<br><br>File file;<br>// ...(file is initialised)...<br>byte[] fileContent = Files.readAllBytes(file.toPath());<br>```


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

    ```java<br>    public static byte[] readAllBytes(Path path)<br>                               throwsIOException<br>    ```

    Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.

    **Parameters:**`path` - the path to the file**Returns:**a byte array containing the bytes read from the file**Throws:**[`IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) - if an I/O error occurs reading from the stream[`OutOfMemoryError`](https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html) - if an array of the required size cannot be allocated, for example the file is larger that `2GB[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.


*Edit*: as of Java 8, [lambda expressions](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) are a nice solution as [other](https://stackoverflow.com/a/19624032/21849) [answers](https://stackoverflow.com/a/25005082/21849) have pointed out. The answer below was written for Java 7 and earlier...

---

Take a look at the [command pattern](http://en.wikipedia.org/wiki/Command_pattern).

```java<br>// NOTE: code not tested, but I believe this is valid java...<br>public class CommandExample<br>{<br>    public interface Command<br>    {<br>        public void execute(Object data);<br>    }<br><br>    public class PrintCommand implements Command<br>    {<br>        public void execute(Object data)<br>        {<br>            System.out.println(data.toString());<br>        }<br>    }<br><br>    public static void callCommand(Command command, Object data)<br>    {<br>        command.execute(data);<br>    }<br><br>    public static void main(String... args)<br>    {<br>        callCommand(new PrintCommand(), "hello world");<br>    }<br>}<br><br>```

*Edit:* as [Pete Kirkham points out](https://stackoverflow.com/questions/2186931/java-pass-method-as-parameter/2186993#2186993), there's another way of doing this using a [Visitor](http://en.wikipedia.org/wiki/Visitor_pattern). The visitor approach is a little more involved - your nodes all need to be visitor-aware with an `acceptVisitor()` method - but if you need to traverse a more complex object graph then it's worth examining.


```java<br>// NOTE: code not tested, but I believe this is valid java...<br>public class CommandExample<br>{<br>    public interface Command<br>    {<br>        public void execute(Object data);<br>    }<br><br>    public class PrintCommand implements Command<br>    {<br>        public void execute(Object data)<br>        {<br>            System.out.println(data.toString());<br>        }<br>    }<br><br>    public static void callCommand(Command command, Object data)<br>    {<br>        command.execute(data);<br>    }<br><br>    public static void main(String... args)<br>    {<br>        callCommand(new PrintCommand(), "hello world");<br>    }<br>}<br><br>```


One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.

The previous section, [Anonymous Classes](https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html), shows you how to implement a base class without giving it a name. Although this is often more concise than a named class, for classes with only one method, even an anonymous class seems a bit excessive and cumbersome. Lambda expressions let you express instances of single-method classes more compactly.


Using [`java.io.File`](https://docs.oracle.com/javase/9/docs/api/java/io/File.html):

```java<br>File f = new File(filePathString);<br>if(f.exists() && !f.isDirectory()) {<br>    // do something<br>}<br>```


```java<br>File f = new File(filePathString);<br>if(f.exists() && !f.isDirectory()) {<br>    // do something<br>}<br>```


```<br>public classFile<br>extendsObject<br>implementsSerializable,Comparable<File><br>```

An abstract representation of file and directory pathnames.

User interfaces and operating systems use system-dependent *pathname strings* to name files and directories. This class presents an abstract, system-independent view of hierarchical pathnames. An *abstract pathname* has two components:

1. An optional system-dependent *prefix* string, such as a disk-drive specifier, `"/"` for the UNIX root directory, or `"\\\"` for a Microsoft Windows UNC pathname, and
2. A sequence of zero or more string *names*.

The first name in an abstract pathname may be a directory name or, in the case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name in an abstract pathname denotes a directory; the last name may denote either a directory or a file. The

*empty*

abstract pathname has no prefix and an empty name sequence.

The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default *separator character*. The default name-separator character is defined by the system property `file.separator`, and is made available in the public static fields [`separator`](https://docs.oracle.com/javase/9/docs/api/java/io/File.html#separator) and [`separatorChar`](https://docs.oracle.com/javase/9/docs/api/java/io/File.html#separatorChar) of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.


FileChannel.lock is probably what you want.

```java<br>try (<br>    FileInputStream in = new FileInputStream(file);<br>    java.nio.channels.FileLock lock = in.getChannel().lock();<br>    Reader reader = new InputStreamReader(in, charset)<br>) {<br>    ...<br>}<br><br>```

(Disclaimer: Code not compiled and certainly not tested.)

Note the section entitled "platform dependencies" in the [API doc for FileLock](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/channels/FileLock.html#pdep).


```java<br>try (<br>    FileInputStream in = new FileInputStream(file);<br>    java.nio.channels.FileLock lock = in.getChannel().lock();<br>    Reader reader = new InputStreamReader(in, charset)<br>) {<br>    ...<br>}<br><br>```


## Platform dependencies

This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.

Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified. The native file-locking facilities of some systems are merely *advisory*, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity. On other systems native file locks are *mandatory*, meaning that if one program locks a region of a file then other programs are actually prevented from accessing that region in a way that would violate the lock. On yet other systems, whether native file locks are advisory or mandatory is configurable on a per-file basis. To ensure consistent and correct behavior across platforms, it is strongly recommended that the locks provided by this API be used as if they were advisory locks.

On some systems, acquiring a mandatory lock on a region of a file prevents that region from being [`*mapped into memory*`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/channels/FileChannel.html#map(java.nio.channels.FileChannel.MapMode,long,long)), and vice versa. Programs that combine locking and mapping should be prepared for this combination to fail.

On some systems, closing a channel releases all locks held by the Java virtual machine on the underlying file regardless of whether the locks were acquired via that channel or via another channel open on the same file. It is strongly recommended that, within a program, a unique channel be used to acquire all locks on any given file.

Some network filesystems permit file locking to be used with memory-mapped files only when the locked regions are page-aligned and a whole multiple of the underlying hardware's page size. Some network filesystems do not implement file locks on regions that extend past a certain position, often 230 or 231. In general, great care should be taken when locking files that reside on network filesystems.

**Since:**1.4


Indeed rather use [`ExecutorService`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html) instead of `Timer`, here's an [SSCCE](http://sscce.org/):

```java<br>package com.stackoverflow.q2275443;<br><br>import java.util.concurrent.Callable;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br>import java.util.concurrent.Future;<br>import java.util.concurrent.TimeUnit;<br>import java.util.concurrent.TimeoutException;<br><br>public class Test {<br>    public static void main(String[] args) throws Exception {<br>        ExecutorService executor = Executors.newSingleThreadExecutor();<br>        Future<String> future = executor.submit(new Task());<br><br>        try {<br>            System.out.println("Started..");<br>            System.out.println(future.get(3, TimeUnit.SECONDS));<br>            System.out.println("Finished!");<br>        } catch (TimeoutException e) {<br>            future.cancel(true);<br>            System.out.println("Terminated!");<br>        }<br><br>        executor.shutdownNow();<br>    }<br>}<br><br>class Task implements Callable<String> {<br>    @Override<br>    public String call() throws Exception {<br>        Thread.sleep(4000); // Just to demo a long running task of 4 seconds.<br>        return "Ready!";<br>    }<br>}<br><br>```

Play a bit with the `timeout` argument in [`Future#get()`](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html#get%28long,%20java.util.concurrent.TimeUnit%29) method, e.g. increase it to 5 and you'll see that the thread finishes. You can intercept the timeout in the `catch (TimeoutException e)` block.

**Update:** to clarify a conceptual misunderstanding, the `sleep()` is **not** required. It is just used for SSCCE/demonstration purposes. Just do **your** long running task right there in place of `sleep()`. Inside your long running task, you should be checking if the thread is not [interrupted](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupted()) as follows:

```java<br>while (!Thread.interrupted()) {<br>    // Do your long running task here.<br>}<br>```


```java<br>package com.stackoverflow.q2275443;<br><br>import java.util.concurrent.Callable;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br>import java.util.concurrent.Future;<br>import java.util.concurrent.TimeUnit;<br>import java.util.concurrent.TimeoutException;<br><br>public class Test {<br>    public static void main(String[] args) throws Exception {<br>        ExecutorService executor = Executors.newSingleThreadExecutor();<br>        Future<String> future = executor.submit(new Task());<br><br>        try {<br>            System.out.println("Started..");<br>            System.out.println(future.get(3, TimeUnit.SECONDS));<br>            System.out.println("Finished!");<br>        } catch (TimeoutException e) {<br>            future.cancel(true);<br>            System.out.println("Terminated!");<br>        }<br><br>        executor.shutdownNow();<br>    }<br>}<br><br>class Task implements Callable<String> {<br>    @Override<br>    public String call() throws Exception {<br>        Thread.sleep(4000); // Just to demo a long running task of 4 seconds.<br>        return "Ready!";<br>    }<br>}<br><br>```


An [`Executor`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executor.html) that provides methods to manage termination and methods that can produce a [`Future`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html) for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The [`shutdown()`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#shutdown()) method will allow previously submitted tasks to execute before terminating, while the [`shutdownNow()`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#shutdownNow()) method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

Method submit extends base method [`Executor.execute(java.lang.Runnable)`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executor.html#execute(java.lang.Runnable)) by creating and returning a [`Future`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html) that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class [`ExecutorCompletionService`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html) can be used to write customized variants of these methods.)

The [`Executors`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html) class provides factory methods for the executor services provided in this package.

### Usage Examples

Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured

[`Executors.newFixedThreadPool(int)`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int))

factory method:

```<br> class NetworkService implements Runnable {<br>   private final ServerSocket serverSocket;<br>   private final ExecutorService pool;<br><br>   public NetworkService(int port, int poolSize)<br>       throws IOException {<br>     serverSocket = new ServerSocket(port);<br>     pool = Executors.newFixedThreadPool(poolSize);<br>   }<br><br>   public void run() { // run the service<br>     try {<br>       for (;;) {<br>         pool.execute(new Handler(serverSocket.accept()));<br>       }<br>     } catch (IOException ex) {<br>       pool.shutdown();<br>     }<br>   }<br> }<br><br> class Handler implements Runnable {<br>   private final Socket socket;<br>   Handler(Socket socket) { this.socket = socket; }<br>   public void run() {<br>     // read and service request on socket<br>   }<br> }<br>```