Java Code Snippets

CodeOutputComment
System.out.print("Amigo");
System.out.println("Is The");
System.out.print("Best");

AmigoIs The Best

println doesn't start printing text from a new line. It prints text on the current line, but makes it so the next text will be printed on a new line.

int a, b, c;

int variables named a, b, c are created. These variables can store integers.

int a = 1 + 'b'; //99
String str = "sss" + a; //sss99 

When you add strings and numbers, the result is always a string. We can add character to integer.

String str = "abc"
StringBuilder(str).reverse().toString()

cba

Reverse a string using StringBuilder

String str = Arrays.stream(result)
        .mapToObj(String::valueOf)
        .collect(Collectors.joining())

For eg str = ['1','2','3'] then result "123" string

Concatenate array values to a String

Difference between

int[] arr = new int[]{2,4,6,7,9};

and

int[] arr = {2,4,6,7,9};

int[] arr = new int[]{2,4,6,7,9};

This approach combines the array declaration (int[] arr) with initialization using a new keyword (new). It explicitly allocates memory for the array of the specified size (5 elements in this case) and then initializes the elements with the provided values within curly braces {}.

int[] arr = {2,4,6,7,9};

This is a shorthand notation for array initialization. Java allows directly initializing the array with values within curly braces {} during declaration. Internally, Java still creates an array and assigns the provided values to its elements.

Essentially, both methods achieve the same result

Increment Operator ++i and i++

++i (Pre-increment):

  • The variable is incremented by 1 first.

  • The incremented value is returned and used in the expression.

i++ (Post-increment):

  • The current value of the variable is used in the expression first.

  • Then, the variable is incremented by 1.

Return sub-array

Arrays.copyOfRange(arr, start, end);

If we want to return a subarray of an int[] array in Java, we can use the Arrays.copyOfRange() method. This method allows you to create a new array that is a copy of a specified range of elements from the original array.

int[] arr = { 1, 2, 1, 3, 5, 1 };
System.out.println(Arrays.toString(arr));
List<Integer> arrList = IntStream.of(arr)
        .boxed()
        .collect(Collectors.toList());

To convert int array to ArrayList

int[] result = arrList.stream()
        .mapToInt(Integer::intValue)
        .filter(element -> element != key)
        .toArray();

Convert ArrayList back to int array

for (i = 0;i<10;i++) {
    System.out.print(i);
}
System.out.println();
for (i=0;i<10;++i) {
    System.out.print(i);
}

0123456789 0123456789

Both loops will print the same sequence of numbers because the difference between ++i and i++ only matters when the incremented value of i is being used within the same expression.

int i;
System.out.print(i);

Compile Error

System.out.println(s1 = "aaa"); // aaa
System.out.println(i = 10); // 10

Assignmnet operator while printing is valid

int[] arr = new int[10];
System.out.println(arr);

[I@hashcode (the actual hashcode will vary). This is not the actual content of the array, but a memory address and a hashcode representing the array object itself.

An array in Java is an object. It doesn't have a built-in way to directly print its contents using System.out.println(arr). When you try to print the array itself, Java prints the object representation, which includes:[I: This indicates the array's type. [I signifies an array of integers (int).

@: This symbol separates the type information from the hashcode.

hashcode: This is a unique identifier generated for the array object itself. It's used for internal memory management purposes.

public static void main(String[] args) {
    int[] arr = new int[10];
    System.out.println(arr[9]);
}

0

Array elements are initialized with default 0 value.

public class Application {
    static ArithmeticException e;
    public static void main(String[] args) {
        throw e;
    }
}

NullPointer Exception

public class Application {
    static ArithmeticException e = new ArithmeticException();
    public static void main(String[] args) {
        throw e;
    }
}

Arithmetic Excpetion

int[] result = {1,2,3};
List<Integer> arrList = IntStream.of(arr)
        .boxed()
        .collect(Collectors.toList());

Convert int[] to List<Integer>

Last updated