Java tutorials & examples

Java Hello World

Here is a basic hello world java program. Run the following to compile and run it. $ javac $ java HelloWorld

Java System.out.print and println

System.out.println example println will append a new line after the string. System.out.print example print will not append a new line after the string.

Java System.out.format examples

System.out.format method format multiple arguments based on format string. Basic example print integer 8 characters in width print float with 2 digits after decimal point

Java – static and instance variables

Static variables are created once for a class and shared by all instances. Static variable is created the moment class is loaded. static variable example read more

Java – this keyword

Using this to access a field In case a field is shadowed by method or constructor parameter, the field can be accessed using this keyword. read more

Java – initialize string array

Initialize string array using curly braces {}

Java – string prefix match using startsWith

Java String startsWith(String prefix) example: To specify offset use startsWith(String prefix, int toffset)

Java – compare strings

Case sensitive comparison Compare strings using firstString.compareTo(secondString). Positive outcome means firstString > secondString and so on. Case insensitive comparison – compareToIgnoreCase

Java – string to int example

Java – array basics

Initialize arrat and print length Access element at specific index Access non existing index This will throw Index Out Of Bounds Exception

Java – two dimensional array example

Java – two dimentional array example

Java – array for-each loop

Java – fill an array using java.util.Arrays

Fill all values in an array Fill range in an array

Java – equals vs ==

String method equals check if both references points objects with same values stored in them. Operator == check if both references points to same object.

Java – print exception as string examples

Print exception stack trace Print exception short description

Java – Arrays.sort custom Comparator example

Java – create inline Comparator example