The official Java documentation includes free online tutorials for learning the Java language, the core Java APIs and more. The language tutorials also provide worked answers to programming problems. Several more advanced tutorials and solutions are also available as sample projects on NetBeans.org.
The official Java tutorials are comprehensive and also a good choice for beginners. There are dedicated questions and exercises sections with a Check Your Answers button at the bottom of each page. The topics covered range from the basics up to intermediate-advanced areas, such as anonymous classes and lambda expressions.
There are various alternative sources of Java exercises online, such as LearnJavaOnline.org and JavaForStudents.co.uk. These websites provide some useful code snippets, but the official resources cover far more content.