How to convert String to Integer in Java?

Integer.parseInt(String s)
You can convert any String that represents number into signed decimal integer by passing String as an argument to method Integer.parseInt(String s). Following excerpt shows how you can convert String to Integer in Java.
public class StringToInteger {
    public static void main(String[] args) {
        String strNumber = "123";
        System.out.println("Number in String: " + strNumber);
        
        /**
         * javadoc:
         * Parses the string argument as a signed decimal integer. 
         * The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. 
         * The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the Integer.parseInt(java.lang.String, int) method.
         * 
         * Throws: NumberFormatException - if the string cannot be parsed as an integer. 
         */
        int intValue = Integer.parseInt(strNumber);
        System.out.println("int value: " + intValue);
        
        /* Increment value by 1 */
        intValue = intValue + 1;
        System.out.println("int value incremented: " + intValue);
    }
}

Output
Number in String: 123
int value: 123
int value increment: 124

Radix
Following table represent the numbering system in mathematics. Read more about it on wikipedia.
Base/Radix Name
10 Decimal system
12 DuoDecimal(dozenal) system
2 Binary numeral system
16 HexaDecimal system
8 Octal system
60 Sexagesimal system
64 MIME Base64
85 PostScript ASCII85
256 byte


How to iterate over stream and increment index value in Lambda Expression?

Lambda Expression + Java 8


Many of you having trouble for increment index value inside Lambda expression because of Local variable index defined in an enclosing scope must be final or effectively final. There is an alternative for that...

java.util.concurrent.atomic.AtomicInteger
An int value that may be updated atomically. See the java.util.concurrent.atomic package specification for description of the properties of atomic variables. An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an java.lang.Integer. However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
Java doc

Source Code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class LambdaIncrementIndexExample {

    public static void main(String[] args) {
        /* AtomicInteger in `stream()` */
        new LambdaIncrementIndexExample().UsingStream();

        /* AtomicInteger in `parallelStream()` */
        new LambdaIncrementIndexExample().UsingParallelStream();
    }

    /**
     * Example of using AtomicInteger in `stream()`
     */
    public void UsingStream() {
        /* Create object of AtomicInteger with initial value `0` */
        AtomicInteger atomicInteger = new AtomicInteger(0);

        /* Create list of names. */
        List<String> listNames = new ArrayList<String>(Arrays.asList("Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones", "Heer Thakor"));

        listNames.stream()
                 .filter(name -> name.endsWith("Thakor"))
                 .forEach(name -> {
                    /* Get the previous value of count and increment it by `1` */
                    atomicInteger.getAndIncrement();

                    /* Print the name */
                    System.out.println(name);
                 });
  
        /* Get value of `atomicInteger` */
        System.out.println("Total match found using `stream()`: " + atomicInteger.get());
        System.out.println("+++++++++++++++++++++++++++");
    }

    /**
     * Example of using AtomicInteger in `parallelStream()`
     */
    public void UsingParallelStream() {
        /* Create object of AtomicInteger with initial value `0` */
        AtomicInteger atomicInteger = new AtomicInteger(0);

        /* Create list of names. */
        List<String> listNames = new ArrayList<String>(Arrays.asList("Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones", "Heer Thakor"));

         listNames.parallelStream()
                  .filter(name -> name.endsWith("Thakor"))
                  .forEach(name -> {
                    /* Get the previous value of count and increment it by `1` */
                    atomicInteger.getAndIncrement();

                    /* Print the name */
                    System.out.println(name);
                  });
  
        /* Get value of `atomicInteger` */
        System.out.println("Total match found using `parallelStream()`: " + atomicInteger.get());
    }
}

Output
Vicky Thakor
Chirag Thakor
Heer Thakor
Total match found using `stream()`: 3
+++++++++++++++++++++++++++
Heer Thakor
Chirag Thakor
Vicky Thakor
Total match found using `parallelStream()`: 3


How to copy file in Java using FileInputStream and FileOutputStream?

This excerpt shows how you can copy content of source file to destination file using java.io.FileInputStream and java.io.FileOutputStream.

Source Code (Java 1.6 or less)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFileExample {

    public static void main(String[] args) {
        /* Create object of File for source file */
        File sourceFile = new File("D:\\Readme.txt");
        /* Create object of File for destination file */
        File destinationFile = new File("D:\\CopyReadme.txt");

        /* Create object of FileInputStream */
        FileInputStream objFileInputStream = null;
        /* Create object of FileOutputStream */
        FileOutputStream objFileOutputStream = null;

        /* Check if source file is exists or not */
        if (sourceFile.exists()) {
            try {
                /* Obtain FileInputStream of source file */
                objFileInputStream = new FileInputStream(sourceFile);

                /* Create destination file if not exists */
                if (!destinationFile.exists()) {
                    destinationFile.createNewFile();
                }

                /* Obtain FileOutputStream of destination file */
                objFileOutputStream = new FileOutputStream(destinationFile);
                
                /* Read content from source File. */
                int byteOfData;
                while ((byteOfData = objFileInputStream.read()) != -1) {
                    /* Write content to destination File. */
                    objFileOutputStream.write(byteOfData);
                }
                System.out.println("File Copied!");
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                /* Close FileInputStream and FileOutputStream */
                try {
                    if (objFileInputStream != null) {
                        objFileInputStream.close();
                    }

                    if (objFileOutputStream != null) {
                        objFileOutputStream.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        } else {
            System.out.println("Source file not found!");
        }
    }
}

Source Code (Java 1.7 or above)(try-with-resources
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFileExample {

    public static void main(String[] args) {
        /* Create object of File for source file */
        File sourceFile = new File("D:\\Readme.txt");
        /* Create object of File for destination file */
        File destinationFile = new File("D:\\CopyReadme.txt");

        /* Check if source file is exists or not */
        if (sourceFile.exists()) {

            /* Create destination file if not exists */
            if (!destinationFile.exists()) {
                try {
                    destinationFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            try (
                    /* Create object of FileInputStream */
                    FileInputStream objFileInputStream = new FileInputStream(sourceFile);
                    /* Create object of FileOutputStream */
                    FileOutputStream objFileOutputStream = new FileOutputStream(destinationFile);
                ) {
                    /* Read content from source File. */
                    int byteOfData;
                    while ((byteOfData = objFileInputStream.read()) != -1) {
                        /* Write content to destination File. */
                        objFileOutputStream.write(byteOfData);
                    }
                    System.out.println("File Copied!");
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Other References:
What is try-with-resources in Java 7 or above?
How to read file in Java?
How to read file using FileInputStream in Java?
How to read/parse XML file in Java?
How to write file in Java?
How to append text to an existing file in Java?

Using IntStream over for loop in Java 8

Stream API Java 8

We are using for-loop since we know Java. Billions of program running based on this for-loop but time has changed. Its not just creating program that gives us desired output but your program should be faster, utilize the hardware and perform at its pick level.

Java designers did some serious changes in Java8. Lambda expression and Stream API were introduced to in Java8 and that made programmers life much more easy than ever before.

Source code (Simple for-loop)
public class ForLoopExample {

    public static void main(String[] args) {
        /* Create String array */
        String[] arrayNames = {"Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones"};

        for (int i = 0; i < arrayNames.length; i++) {
            /*Filter name which ends with "Thakor". */
            if (arrayNames[i].endsWith("Thakor")) {
                /* Print name to console. */
                System.out.println(arrayNames[i]);
            }
        }
    }
}

Output
Vicky Thakor
Chirag Thakor

Sour code (IntStream)
import java.util.stream.IntStream;

public class IntStreamExample {

    public static void main(String[] args) {
        /* Loop through Array using IntStream */
        new IntStreamExample().UsingStream();

        /* Loop through Array using IntStream with ParallelStream. */
        new IntStreamExample().UsingParallelStream();
    }

    /**
     * Loop through Array using IntStream
     */
    public void UsingStream() {
        System.out.println("Using IntStream");
        System.out.println("------------------------------------------");

        /* Create String array */
        String[] arrayNames = {"Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones"};

        /**
         * - Start loop from "range(startInclusive {initial value}, endExclusive {upper limit}}
         * - Filter data.(If condition)
         * - forEach (value that matches filter condition)
         */
        IntStream.range(0, arrayNames.length)
                 .filter(i - > arrayNames[i].endsWith("Thakor"))
                 .forEach(i - > {
                    System.out.println(arrayNames[i]);
                 });
        System.out.println("+++++++++++++++++++++++++++");
    }

    /**
     * Loop through Array using IntStream with ParallelStream.
     * Note: Use it when you want to divide your task in multiple core of CPU and order doesn't matter for the operation.
     */
    public void UsingParallelStream() {
        System.out.println("Using IntStream with ParallelStream");
        System.out.println("------------------------------------------");

        /* Create String array */
        String[] arrayNames = {"Vicky Thakor", "Chirag Thakor", "Dave Hill", "Finn Jones"};

        /**
         * - Start loop from "range(startInclusive {initial value}, endExclusive {upper limit}}
         * - ParallelStream (Perform your task by dividing it in CPU core.) 
         * - Filter data. (If condition)
         * - forEach (value that matches filter condition)
         */
        IntStream.range(0, arrayNames.length)
                 .parallel()
                 .filter(i - > arrayNames[i].endsWith("Thakor"))
                 .forEach(i - >  {
                    System.out.println(arrayNames[i]);
                 });
        System.out.println("+++++++++++++++++++++++++++");
    }
}

Output
Using IntStream
------------------------------------------
Vicky Thakor
Chirag Thakor
+++++++++++++++++++++++++++
Using IntStream with ParallelStream
------------------------------------------
Chirag Thakor
Vicky Thakor
+++++++++++++++++++++++++++

Note:
Use ParallelStream only when you want to divide your task in multiple core of CPU and order doesn't matter for your operation.

How to read file using FileInputStream in Java?

Java 1.6 or less
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFileInputStreamExample {
    
    public static void main(String[] args) {
        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");

        /* Create object of FileInputStream */
        FileInputStream objFileInputStream = null;
        try {
            /**
             * A FileInputStream obtains input bytes from a file in a file system. What files
             * are available depends on the host environment.
             *
             * FileInputStream is meant for reading streams of raw bytes
             * such as image data. For reading streams of characters, consider using
             * FileReader.
             */
            objFileInputStream = new FileInputStream(objFile);
            
            /* Read content of File. */
            int byteOfData;
            while ((byteOfData = objFileInputStream.read()) != -1) {
                /* Print content of File. */
                System.out.print((char) byteOfData);
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            /* Close the FileInputStream */
            if (objFileInputStream != null) {
                try {
                    objFileInputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}

Java 1.7 or above(try-with-resources)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFileInputStreamExample {
    
    public static void main(String[] args) {
        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");
        
        try (
                /**
                 * A FileInputStream obtains input bytes from a file in a file system. What files
                 * are available depends on the host environment.
                 *
                 * FileInputStream is meant for reading streams of raw bytes
                 * such as image data. For reading streams of characters, consider using
                 * FileReader.
                 */
                FileInputStream objFileInputStream = new FileInputStream(objFile);
            ) {
            /* Read content of File. */
            int byteOfData;
            while ((byteOfData = objFileInputStream.read()) != -1) {
                /* Print content of File. */
                System.out.print((char) byteOfData);
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } 
    }
}

Other References:
What is try-with-resources in Java 7 or above?
How to read file in Java?
How to read/parse XML file in Java?
How to write file in Java?
How to append text to an existing file in Java?

How to append text to an existing file in Java?

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class AppendFileExample {

    public static void main(String[] args) {
        /* Content to write in File. */
        String strFileData = "This excerpt demonstrate how you can append content in existing File using Java.";

        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");

        try {
            /* Check if File exists at given location. */
            if (objFile.exists()) {
                /**
                 * Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data
                 * - fileName String The system-dependent filename.
                 * - append boolean if true, then data will be written to the end of the file rather than the beginning.
                 */
                FileWriter objFileWriter = new FileWriter(objFile.getAbsolutePath(), true);

                /* Create object of BufferedWriter. */
                BufferedWriter objBufferedWriter = new BufferedWriter(objFileWriter);

                /* Write content to File. */
                objBufferedWriter.write(strFileData);

                /* Close the BufferedWriter */
                objBufferedWriter.close();
                
                System.out.println("File modified!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Other References:
How to write file in Java?
How to read file in Java?
How to read/parse XML file in Java?

How to write file in Java?

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {

    public static void main(String[] args) {
        /* Content to write in File. */
        String strFileData = "This excerpt demonstrate file writing in Java.";

        /* Create object of File. */
        File objFile = new File("D:\\Readme.txt");

        try {
            /* If file not exists at given location then create new File. */
            if (!objFile.exists()) {
                objFile.createNewFile();
            }

            /* Create object of FileWriter. */
            FileWriter objFileWriter = new FileWriter(objFile.getAbsolutePath());

            /* Create object of BufferedWriter. */
            BufferedWriter objBufferedWriter = new BufferedWriter(objFileWriter);

            /* Write content to File. */
            objBufferedWriter.write(strFileData);

            /* Close the BufferedWriter */
            objBufferedWriter.close();
            
            System.out.println("File created!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Other References:
How to append text to an existing file in Java?
How to read file in Java?
How to read/parse XML file in Java?