Tuesday, February 5, 2019

Explanation of “ClassCastException” in Java?

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.
Object i = Integer.valueOf(42);
String s = (String)i;  

Rethrowing exceptions in Java without losing the stack trace?

catch (WhateverException e) {
    throw e;
}
will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.

Difference between java.lang.RuntimeException and java.lang.Exception

Generally RuntimeExceptions are exceptions that can be prevented programmatically. E.g NullPointerException, ArrayIndexOutOfBoundException. If you check for null before calling any method, NullPointerException would never occur. Similarly ArrayIndexOutOfBoundException would never occur if you check the index first. RuntimeException are not checked by the compiler, so it is clean code.
EDIT : These days people favor RuntimeException because the clean code it produces. It is totally a personal choice.

Keep getting java.lang.NoClassDefFoundError in Spring

The reason for this is, inside your jar you have only your classes without any dependencies.

Java string.split - by multiple character delimiter?

String.split takes a regular expression, in this case, you want non-word characters (regex \W) to be the split, so it's simply:
String input = "Hi,X How-how are:any you?";
String[] parts = input.split("[\\W]");

How to split a string in Java?

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

How do I convert a String to an int in Java?

For example, here are two ways:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
There is a slight difference between these methods:
  • valueOf returns a new or cached instance of java.lang.Integer
  • parseInt returns primitive int.