Docsity

Advanced java programing, Exams of Computer Science

Partial preview of the text

Download Advanced java programing and more Exams Computer Science in PDF only on Docsity!

Advanced java i

Advanced java

  • 1 How to create and destroy objects Contents
    • 1.1 Introduction
    • 1.2 Instance Construction
      • 1.2.1 Implicit (Generated) Constructor
      • 1.2.2 Constructors without Arguments
      • 1.2.3 Constructors with Arguments
      • 1.2.4 Initialization Blocks
      • 1.2.5 Construction guarantee
      • 1.2.6 Visibility
      • 1.2.7 Garbage collection
      • 1.2.8 Finalizers
    • 1.3 Static initialization
    • 1.4 Construction Patterns
      • 1.4.1 Singleton
      • 1.4.2 Utility/Helper Class
      • 1.4.3 Factory
      • 1.4.4 Dependency Injection
    • 1.5 Download the Source Code
    • 1.6 What’s next
  • 2 Using methods common to all objects
    • 2.1 Introduction
    • 2.2 Methods equals and hashCode
    • 2.3 Method toString
    • 2.4 Method clone
    • 2.5 Method equals and == operator
    • 2.6 Useful helper classes
    • 2.7 Download the Source Code
    • 2.8 What’s next
  • 3 How to design Classes and Interfaces Advanced java iii
    • 3.1 Introduction
    • 3.2 Interfaces
    • 3.3 Marker Interfaces
    • 3.4 Functional interfaces, default and static methods
    • 3.5 Abstract classes
    • 3.6 Immutable classes
    • 3.7 Anonymous classes
    • 3.8 Visibility
    • 3.9 Inheritance
    • 3.10 Multiple inheritance
    • 3.11 Inheritance and composition
    • 3.12 Encapsulation
    • 3.13 Final classes and methods
    • 3.14 Download the Source Code
    • 3.15 What’s next
  • 4 How and when to use Generics
    • 4.1 Introduction
    • 4.2 Generics and interfaces
    • 4.3 Generics and classes
    • 4.4 Generics and methods
    • 4.5 Limitation of generics
    • 4.6 Generics, wildcards and bounded types
    • 4.7 Generics and type inference
    • 4.8 Generics and annotations
    • 4.9 Accessing generic type parameters
    • 4.10 When to use generics
    • 4.11 Download the Source Code
    • 4.12 What’s next
  • 5 How and when to use Enums and Annotations
    • 5.1 Introduction
    • 5.2 Enums as special classes
    • 5.3 Enums and instance fields
    • 5.4 Enums and interfaces
    • 5.5 Enums and generics
    • 5.6 Convenient Enums methods
    • 5.7 Specialized Collections: EnumSet and EnumMap
    • 5.8 When to use enums Advanced java iv
    • 5.9 Annotations as special interfaces
    • 5.10 Annotations and retention policy
    • 5.11 Annotations and element types
    • 5.12 Annotations and inheritance
    • 5.13 Repeatable annotations
    • 5.14 Annotation processors
    • 5.15 Annotations and configuration over convention
    • 5.16 When to use annotations
    • 5.17 Download the Source Code
    • 5.18 What’s next
  • 6 How to write methods efficiently
    • 6.1 Introduction
    • 6.2 Method signatures
    • 6.3 Method body
    • 6.4 Method overloading
    • 6.5 Method overriding
    • 6.6 Inlining
    • 6.7 Recursion
    • 6.8 Method References
    • 6.9 Immutability
    • 6.10 Method Documentation
    • 6.11 Method Parameters and Return Values
    • 6.12 Methods as API entry points
    • 6.13 Download the Source Code
    • 6.14 What’s next
  • 7 General programming guidelines
    • 7.1 Introduction
    • 7.2 Variable scopes
    • 7.3 Class fields and local variables
    • 7.4 Method arguments and local variables
    • 7.5 Boxing and unboxing
    • 7.6 Interfaces
    • 7.7 Strings
    • 7.8 Naming conventions
    • 7.9 Standard Libraries
    • 7.10 Immutability
    • 7.11 Testing
    • 7.12 Download the Source Code
    • 7.13 What’s next
  • 8 How and when to use Exceptions Advanced java v
    • 8.1 Introduction
    • 8.2 Exceptions and when to use them
    • 8.3 Checked and unchecked exceptions
    • 8.4 Using try-with-resources
    • 8.5 Exceptions and lambdas
    • 8.6 Standard Java exceptions
    • 8.7 Defining your own exceptions
    • 8.8 Documenting exceptions
    • 8.9 Exceptions and logging
    • 8.10 Download the Source Code
    • 8.11 What’s next
  • 9 Concurrency best practices
    • 9.1 Introduction
    • 9.2 Threads and Thread Groups
    • 9.3 Concurrency, Synchronization and Immutability
    • 9.4 Futures, Executors and Thread Pools
    • 9.5 Locks
    • 9.6 Thread Schedulers
    • 9.7 Atomic Operations
    • 9.8 Concurrent Collections
    • 9.9 Explore Java standard library
    • 9.10 Using Synchronization Wisely
    • 9.11 Wait/Notify
    • 9.12 Troubleshooting Concurrency Issues
    • 9.13 Download
    • 9.14 What’s next
  • 10 Built-in Serialization techniques
    • 10.1 Introduction
    • 10.2 Serializable interface
    • 10.3 Externalizable interface
    • 10.4 More about Serializable interface
    • 10.5 Serializability and Remote Method Invocation (RMI)
    • 10.6 JAXB
    • 10.7 JSON-P
    • 10.8 Cost of serialization
    • 10.9 Beyond Java standard library and specifications
    • 10.10Download the Source code
    • 10.11What’s next
  • 11 How to use Reflection effectively Advanced java vi
    • 11.1 Introduction
    • 11.2 Reflection API
    • 11.3 Accessing generic type parameters
    • 11.4 Reflection API and visibility
    • 11.5 Reflection API pitfalls
    • 11.6 Method Handles
    • 11.7 Method Argument Names
    • 11.8 Download the Source Code
    • 11.9 What’s next
  • 12 Dynamic languages support
    • 12.1 Introduction
    • 12.2 Dynamic Languages Support
    • 12.3 Scripting API
    • 12.4 JavaScript on JVM
    • 12.5 Groovy on JVM
    • 12.6 Ruby on JVM
    • 12.7 Python on JVM
    • 12.8 Using Scripting API
    • 12.9 Download Code
    • 12.10What’s next
  • 13 Java Compiler API
    • 13.1 Introduction
    • 13.2 Java Compiler API
    • 13.3 Annotation Processors
    • 13.4 Element Scanners
    • 13.5 Java Compiler Tree API
    • 13.6 Download
    • 13.7 What’s next
  • 14 Java Annotation Processors
    • 14.1 Introduction
    • 14.2 When to Use Annotation Processors
    • 14.3 Annotation Processing Under the Hood
    • 14.4 Writing Your Own Annotation Processor
    • 14.5 Running Annotation Processors
    • 14.6 Download the source code
    • 14.7 What’s next
  • 15 Java Agents Advanced java vii
    • 15.1 Introduction
    • 15.2 Java Agent Basics
    • 15.3 Java Agent and Instrumentation
    • 15.4 Writing Your First Java Agent
    • 15.5 Running Java Agents
    • 15.6 Download the source code
    • 15.7 What’s next

Advanced java ix

Preface

Learning the basics of Java is easy. But really delving into the language and studying its more advanced concepts and nuances is what will make you a great Java developer. The web is abundant with “soft”, “cheap”, “low end” Java tutorials, but what it is missing is material to really take you to the next level. This book is designed to help you make the most effective use of Java. It discusses advanced topics, including object creation, concurrency, serialization, reflection and many more. It will guide you through your journey to Java mastery!

Advanced java x

About the Author

Andriy completed his Master Degree in Computer Science at Zhitomir Institute of Engineering and Technologies, Ukraine. For the last fifteen years he has been working as the Consultant/Software Developer/Senior Software Developer/Team Lead for a many successful projects including several huge software systems for customers from North America and Europe. Through his career Andriy has gained a great experience in enterprise architecture, web development (ASP.NET, Java Server Faces, Play Framework), software development practices (test-driven development, continious integration) and software plat- forms (Sun JEE, Microsoft .NET), object-oriented analysis and design, development of the rich user interfaces (MFC, Swing, Windows Forms/WPF), relational database management systems (MySQL, SQL Server, PostgreSQL, Oracle), NoSQL solutions (MongoDB, Redis) and operating systems (Linux/Windows). Andriy has a great experience in development of distributed (multi-tier) software systems, multi-threaded applications, desktop applications, service-oriented architecture and rich Internet applications. Since 2006 he is actively working primarily with JEE / JSE platforms. As a professional he is always open to continuous learning and self-improvement to be more productive in the job he is really passioned about.

Advanced java 2 / 113

package com.javacodegeeks.advanced.construction;

public class NoArgConstructor { public NoArgConstructor() { // Constructor body here } }

This constructor will be called once new instance of the class is created using the new keyword. final NoArgConstructor noArgConstructor = new NoArgConstructor();

1.2.3 Constructors with Arguments

The constructors with arguments are the most interesting and useful way to parameterize new class instances creation. The following example defines a constructor with two arguments. package com.javacodegeeks.advanced.construction;

public class ConstructorWithArguments { public ConstructorWithArguments(final String arg1,final String arg2) { // Constructor body here } }

In this case, when class instance is being created using the new keyword, both constructor arguments should be provided. final ConstructorWithArguments constructorWithArguments = new ConstructorWithArguments( "arg1", "arg2" );

Interestingly, the constructors can call each other using the special this keyword. It is considered a good practice to chain constructors in such a way as it reduces code duplication and basically leads to having single initialization entry point. As an example, let us add another constructor with only one argument. public ConstructorWithArguments(final String arg1) { this(arg1, null); }

1.2.4 Initialization Blocks

Java has yet another way to provide initialization logic using initialization blocks. This feature is rarely used but it is better to know it exists. package com.javacodegeeks.advanced.construction;

public class InitializationBlock { { // initialization code here } }

In a certain way, the initialization block might be treated as anonymous no-arg constructor. The particular class may have multiple initialization blocks and they all will be called in the order they are defined in the code. For example: package com.javacodegeeks.advanced.construction;

public class InitializationBlocks {

Advanced java 3 / 113

{ // initialization code here } { // initialization code here }

}

Initialization blocks do not replace the constructors and may be used along with them. But it is very important to mention that initialization blocks are always called before any constructor. package com.javacodegeeks.advanced.construction;

public class InitializationBlockAndConstructor { { // initialization code here } public InitializationBlockAndConstructor() { } }

1.2.5 Construction guarantee

Java provides certain initialization guarantees which developers may rely on. Uninitialized instance and class (static) variables are automatically initialized to their default values.

Table 1.1: datasheet Type Default Value boolean False byte 0 short 0 int 0 long 0L char u float 0.0f double 0.0d object reference null

Let us confirm that using following class as a simple example: package com.javacodegeeks.advanced.construction;

public class InitializationWithDefaults { private boolean booleanMember; private byte byteMember; private short shortMember; private int intMember; private long longMember; private char charMember; private float floatMember; private double doubleMember; private Object referenceMember;

Advanced java 5 / 113

1.2.8 Finalizers

So far we have talked about constructors and objects initialization but have not actually mentioned anything about their counter- part: objects destruction. That is because Java uses garbage collection to manage objects lifecycle and it is the responsibility of garbage collector to destroy unnecessary objects and reclaim the memory. However, there is one particular feature in Java called finalizers which resemble a bit the destructors but serves the different purpose of performing resources cleanup. Finalizers are considered to be a dangerous feature (which leads to numerous side- effects and performance issues). Generally, they are not necessary and should be avoided (except very rare cases mostly related to native objects). A much better alternative to finalizers is the introduced by Java 7 language construct called try-with-resources and AutoCloseable interface which allows to write clean code like this: try ( final InputStream in = Files.newInputStream( path ) ) { // code here }

1.3 Static initialization

So far we have looked through class instance construction and initialization. But Java also supports class-level initialization constructs called static initializers. There are very similar to the initialization blocks except for the additional static keyword. Please notice that static initialization is performed once per class-loader. For example: package com.javacodegeeks.advanced.construction;

public class StaticInitializationBlock { static { // static initialization code here } }

Similarly to initialization blocks, you may include any number of static initializer blocks in the class definition and they will be executed in the order in which they appear in the code. For example: package com.javacodegeeks.advanced.construction;

public class StaticInitializationBlocks { static { // static initialization code here } static { // static initialization code here } }

Because static initialization block can be triggered from multiple parallel threads (when the loading of the class happens in the first time), Java runtime guarantees that it will be executed only once and in thread-safe manner.

1.4 Construction Patterns

Over the years a couple of well-understood and widely applicable construction (or creation) patterns have emerged within Java community. We are going to cover the most famous of them: singleton, helpers, factory and dependency injection (also known as inversion of control).

Advanced java 6 / 113

1.4.1 Singleton

Singleton is one of the oldest and controversial patterns in software developer’s community. Basically, the main idea of it is to ensure that only one single instance of the class could be created at any given time. Being so simple however, singleton raised a lot of the discussions about how to make it right and, in particular, thread-safe. Here is how a naive version of singleton class may look like: package com.javacodegeeks.advanced.construction.patterns;

public class NaiveSingleton { private static NaiveSingleton instance; private NaiveSingleton() { } public static NaiveSingleton getInstance() { if( instance == null ) { instance = new NaiveSingleton(); } return instance; } }

At least one problem with this code is that it may create many instances of the class if called concurrently by multiple threads. One of the ways to design singleton properly (but in non-lazy fashion) is using the static final property of the class. final property of the class. package com.javacodegeeks.advanced.construction.patterns;

public class EagerSingleton { private static final EagerSingleton instance = new EagerSingleton(); private EagerSingleton() { } public static EagerSingleton getInstance() { return instance; } }

If you do not want to waste your resources and would like your singletons to be lazily created when they are really needed, the explicit synchronization is required, potentially leading to lower concurrency in a multithreaded environments (more details about concurrency in Java will be discussing in part 9 of the tutorial, Concurrency best practices). package com.javacodegeeks.advanced.construction.patterns;

public class LazySingleton { private static LazySingleton instance; private LazySingleton() { } public static synchronized LazySingleton getInstance() { if( instance == null ) { instance = new LazySingleton(); } return instance; } }

Advanced java 8 / 113

public class Library implements BookFactory { @Override public Book newBook() { return new PaperBook(); } }

public class KindleLibrary implements BookFactory { @Override public Book newBook() { return new KindleBook(); } }

Now, the particular class of the Book is hidden behind BookFactory interface implementation, still providing the generic way to create books.

1.4.4 Dependency Injection

Dependency injection (also known as inversion of control) is considered as a good practice for class designers: if some class instance depends on the other class instances, those dependencies should be provided (injected) to it by means of constructors (or setters, strategies, etc.) but not created by the instance itself. Let us consider the following example: package com.javacodegeeks.advanced.construction.patterns;

import java.text.DateFormat; import java.util.Date;

public class Dependant { private final DateFormat format = DateFormat.getDateInstance(); public String format( final Date date ) { return format.format( date ); } }

The class Dependant needs an instance of DateFormat and it just creates one by calling DateFormat.getDateInstanc e() at construction time. The better design would be to use constructor argument to do the same thing: package com.javacodegeeks.advanced.construction.patterns;

import java.text.DateFormat; import java.util.Date;

public class Dependant { private final DateFormat format; public Dependant( final DateFormat format ) { this.format = format; } public String format( final Date date ) { return format.format( date ); } }

In this case the class has all its dependencies provided from outside and it would be very easy to change date format and write test cases for it.

Advanced java 9 / 113

1.5 Download the Source Code

  • You may download the source code here: com.javacodegeeks.advanced.java

1.6 What’s next

In this part of the tutorial we have looked at classes and class instances construction and initialization techniques, along the way covering several widely used patterns. In the next part we are going to dissect the Object class and usage of its well-known methods: equals, hashCode, toString and clone.