ocpjp

How exactly does String.split() method in Java work when regex is provided?

霸气de小男生 提交于 2019-11-26 09:52:00
问题 I\'m preparing for OCPJP exam and I ran into the following example: class Test { public static void main(String args[]) { String test = \"I am preparing for OCPJP\"; String[] tokens = test.split(\"\\\\S\"); System.out.println(tokens.length); } } This code prints 16. I was expecting something like no_of_characters + 1. Can someone explain me, what does the split() method actually do in this case? I just don\'t get it... 回答1: It splits on every "\\S" which in regex engine represents \S non

Java SneakyThrow of exceptions, type erasure

删除回忆录丶 提交于 2019-11-26 09:44:53
问题 Can someone explain this code? public class SneakyThrow { public static void sneakyThrow(Throwable ex) { SneakyThrow.<RuntimeException>sneakyThrowInner(ex); } private static <T extends Throwable> T sneakyThrowInner(Throwable ex) throws T { throw (T) ex; } public static void main(String[] args) { SneakyThrow.sneakyThrow(new Exception()); } } It may seems strange, but this doesn\'t produce a cast exception, and permits to throw a checked exception without having to declare it in the signature,

Why can not I add two bytes and get an int and I can add two final bytes get a byte?

谁说胖子不能爱 提交于 2019-11-26 02:37:39
问题 public class Java{ public static void main(String[] args){ final byte x = 1; final byte y = 2; byte z = x + y;//ok System.out.println(z); byte a = 1; byte b = 2; byte c = a + b; //Compiler error System.out.println(c); } } If the result of an expression involving anything int-sized or smaller is always an int even if the sum of two bytes fit in a byte. Why does it happen when we add two final bytes that fit in a byte? There is no compiler error. 回答1: From the JLS 5.2 Assignment Conversion In