Java: Tips and Tricks
Here we provide a list of free articles and tutorials of tips and tricks that will make you more effective with Java.
How Default Base Class Constructors Are Used with Inheritance
A derived Java class does not inherit a constructor from its base class. If a base class has a default constructor, i.e., a constructor with no arguments, then that constructor is automatically called when a derived class is instantiated if the derived class has its own default constructor. A default constructor is automatically provided by the compiler if no constructors are present in the Java source code. To understand how default constructors are used with inheritance, follow these 10 steps.
How to Add a Time Zone in the Java 8 Date/Time API
When working with date and time objects in Java 8 you will probably need to add a time zone sooner or later. A time zone can be expressed as an offset from UTC (Coordinated Universal Time, or the time at the prime meridian running through Greenwich, England), a time zone ID (e.g., "America/New York"), or a time zone name (e.g., EST). In order to add a time zone you will need the
ZoneOffset, or the
ZoneId class. Each class is located in the
java.time package. To understand how to add a time zone to a date/time object in Java 8, follow these four steps.
How to Add Type and Repeating Annotations to Code in Java 8
Java developers typically need to store objects of a given type in a data structure such as an array. An efficient technique to achieve this goal is available in Java 8 by adding type and repeating annotations to your Java application. The type annotation permits the developer to use an annotation in place of a class reference. The repeating annotation,
@Repeatable, calls out an annotated class that serves as the container for the objects. To understand how to add type and repeating annotations to Java 8 code, follow these 10 steps.
How to Break a Loop in Java
In Java, the
break statement causes the execution of a loop to stop. The loop can be a
do...while loop. To understand how to break out of a loop, follow these four steps.
How to Call an Interface Method in Java
In order to call an interface method from a Java program, the program must first instantiate the interface implementation program. A method can then be called using the implementation object. To learn how to call an interface method in Java, follow these 10 steps.
How to Check Object Type in Java
You can check object type in Java by using the
instanceof keyword. Determining object type is important if you're processing a collection such as an array that contains more than one type of object. For example, you might have an array with string and integer representations of numbers. You would need to determine the object type in order to store a given array item as an
int data type. To learn how to check object type, follow these four steps.
How to Compare Two Objects with the equals Method in Java
To test whether two objects are equal, a developer should provide an
equals method. The logic in the method can determine if the two objects are equal and return true, or return false otherwise. To compare two objects with the
equals method, follow these four steps.
How to Compile Packages in Java
When a Java class is stored in a package, you must include the path that corresponds to the package in the compile. To learn how to compile a Java class in a package and successfully run a Java program to test your work, follow these nine steps.
How to Continue a Loop in Java
continue statement causes the execution of an iteration of a loop to stop, but allows the loop to continue with the next iteration. The loop can be a
do...while loop. To understand how to continue the execution of a loop, follow these four steps.
How to Create a Derived Class in Java
A derived class is a Java class that inherits properties from its super class. For example, an
Employee class might be derived from a
Person class. Therefore the
Employee class could inherit first name and last name properties from
Person, its super class. The following eight steps show how to write a derived class in Java.
How to Create a Jar File in Java
A Java class can be stored in a jar (Java Archive) file. The classes in a jar file are stored in a compressed format, much like a zip file. A jar file is a portable container of classes. To understand how to create a jar file in Java, follow these seven steps.
How to Create a Java Bean
A Java bean is a Java class that has private member variables, public getter and setter methods, and a zero-argument, public constructor (supplied automatically by the compiler). To create a Java bean, follow these seven steps.
How to Create a Method in Java
A method is a unit of code that you call in a Java program. A method can support arguments and usually returns a value. To create a method in Java, follow these four steps.
How to Create an Exception Class in Java
Java has many built-in exception classes, such as
IllegalArgumentException. At times however, you might want to create your own exception class. For example, as opposed to throwing
IllegalArgumentException when a 0 is detected as a divisor during a division operation, you might wish to throw a
DivideByZeroException. This exception class does not exist in the Java core API, but you can create one yourself. The seven steps below will show you how to create an exception class in Java.
How to Create an Interface Definition in Java
An interface definition specifies one or more methods by signature (method return type, name, and arguments). The interface does not contain implementation logic for the methods with the exception of any methods marked as
default. Therefore, the actual coding of a method can be deferred until a Java program is written to implement an interface and specify method logic for the non-default methods listed in the interface. To create an interface definition in Java, follow these three steps.
How to Create a Reference to an Object in Java
A reference to an existing object in Java can be created simply by equating a variable to the object. To create a reference to an object in Java, follow these four steps.
How to Declare Variables in Java
To reference a variable in a Java program, you must first declare it. To declare a variable, follow these four steps.
How to Display the Contents of a Directory in Java
Displaying the contents of a directory in Java can be accomplished using the
File class. This class provides the
listFiles method that returns a list of
File objects for a given directory. The objects may represent files or subdirectories. To understand how to display the contents of a directory in Java, follow these four steps.
How to Filter Distinct Elements from a Collection in Java 8
A collection might contain duplicate entries. What if we wanted to display the collection as distinct elements? In other words, we wish to filter the collection so that only distinct elements are displayed. This goal can be accomplished by applying the distinct method to the stream produced from the collection. To learn how to filter distinct elements from a collection, follow these four steps.
How to Format Date and Time in the Java 8 Date/Time API
Java 8 introduces a date and time formatter for use with the new date and time objects. The formatter permits you to build a pattern that can be applied to date time, date and time objects in order to display the object in a meaningful way. To learn how to format date and time objects in Java 8, follow these four steps.
How to Group and Partition Collectors in Java 8
Collectors class in Java 8 provides methods for grouping and partitioning data stored in collections. Grouping permits you to organize data that shares a common field value, e.g. department. Partitioning allows you to divide the data into two categories, or partitions. One partition satisfies the partitioning criteria whereas the other partition does not. For example, we might separate sales data into a partition that met or exceeded a sales goal and a partition that did not. Our case study below will apply grouping and partitioning technology to a collection of musical instruments.
How to Handle Java Files with Streams
Streams permit the Java developer to handle files. In other words, a file can be read or created by the use of streams. To read a file, a file input stream reader can be combined with a buffered reader. A record from the file can then be presented to an application. To create a file, a file output writer can be combined with a print writer object to write a stream of data to a file. To learn how to handle Java files with streams, follow these four steps.
How to Implement an Interface in Java
An implementation of an interface is a Java program that references the interface using the
implements keyword. The program is required to provide method logic for all non-default methods. Optionally, the program can provide an implementation of a default method defined in the interface. To create an interface implementation in Java, follow these six steps.
How to Implement Functional Interfaces in Java 8
Single abstract method interfaces are well-known to Java developers. For example, the
Runnable interface contains one abstract method called
run. In Java 8, single abstract method interfaces are known as functional interfaces. The benefit of a functional interface is that a developer can specify an anonymous implementation wherever a reference to the interface is required (for example, passing an implementation of the
Runnable interface when instantiating a
Thread object). In this tutorial, we'll create a functional interface that contains one abstract method to generate a greeting.
How to Instantiate an Object in Java
In Java programming, instantiating an object means to create an instance of a class. To instantiate an object in Java, follow these seven steps.
How to Map Elements Using the Map Method in Java 8
Imagine you have a collection of temperature readings in Celsius that you need to convert to Fahrenheit. Prior to Java 8 you would be required to iterate through the collection and convert each temperature reading individually. In Java 8, the conversion of each temperature can be done in just one line of code. The key to achieving this goal is to use the
map method of the
Stream class. This method maps (i.e., translates) each element of a collection based on a given lambda or method reference. To learn how to map elements using the
map method, follow these four steps.
How to Override Base Class Methods with Derived Class Methods in Java
A derived Java class can override a method in its base class. For example, a means of payment method in a
Person class might return a generic message; e.g., "Person is paid monthly". In the
Employee class, however, we can be more specific; e.g., "Employee is paid semi-monthly by W-2". Accordingly, in the derived class, we would desire to override the base class payment method. Learn how to override a base class method by following these 10 steps.
How to Prevent Race Conditions in Java 8
A race condition occurs in programming when two or more execution threads modify a shared, or critical, resource. Race conditions can result in run time errors that are difficult to isolate and to repair. The term "race" is used because the threads can be regarded as racing each other to complete operations on a variable or other shared resource. In Java 8, race conditions can be prevented by enforcing single threading through methods that modify shared resources. To learn how to prevent race conditions in Java 8, follow these eight steps.
How to Reduce the Size of the Stream with the Limit Method in Java 8
The limit method of the
Stream class introduced in Java 8 allows the developer to limit the number of elements that will be extracted from a stream. The limit method is useful in those applications where the user wishes to process only the initial elements that occur in the stream. To learn how to reduce the size of the stream with the limit method, follow these five steps.
How to Rethrow an Exception in Java
An exception can be rethrown in a
catch block. This action will cause the exception to be passed to the calling method. If the rethrow operation occurs in the
main method then the exception is passed to the JVM and displayed on the console. The purpose of the rethrow operation is to get the attention of the outside world that an exception has occurred and at the same time perform any contingency logic (such as logging) in the
catch block. To learn how to rethrow an exception in Java, follow these four steps.
How to Set PATH from JAVA_HOME
The JAVA_HOME environment variable can be used to set the PATH so that the compiler and runtime launcher can be accessed from a command prompt. To set the PATH variable using JAVA_HOME, follow these five steps.
How to Skip Elements with the Skip Method in Java 8
If you need to bypass a certain number of elements in a collection, you can apply the skip method to a stream produced from the collection in Java 8. The following four steps show how to skip elements using the skip method.
How to Throw an Exception in Java
You can throw an exception in Java by using the
throw keyword. This action will cause an exception to be raised and will require the calling method to catch the exception or throw the exception to the next level in the call stack. To learn how to throw an exception in Java, follow these four steps.
How to Use Basic Generics Syntax in Java
You can create a class in Java that defines one or more placeholders for data type. The placeholders are known as generics because the class is not determined until compile time. Generics are notated by angle brackets (< and >). For example, we might wish to create a class that contains a method that accepts an argument of any data type and displays the value of the argument. Because we don't know the data type when we are developing the class, we must use a generic for the method argument data type. To apply basic generics syntax in Java, follow these four steps.
How to Use Comparable and Comparator in Java
The ordering of a tree set in Java can be dictated using implementations of either the
How to Use Serialized Objects in Java
What if you created an object in Java and wanted to make it permanent so you can continue working on the object at a later time? The solution is to serialize the object and then write it to a file. When you need the object in the future, you can then read the object back into memory from the file. Java provides several classes in the
java.io package that assist the developer in using serialized objects. To learn how to use serialized objects in Java, follow these seven steps.
How to Use System.in in Java
At times you might need to read console input provided by the user from the keyboard. The
System.in field permits you to read input from the keyboard. The input can be converted into a stream of characters and then buffered so that all characters up to but not including the Enter key can be presented to the program. To learn how to use
System.in in Java, follow these four steps.
How to Use the Comparator.comparing Method in Java 8
Comparator.comparing method, introduced in Java 8, returns a Comparator object that will use the specified field as the sort key. The
Comparator interface is a functional interface in Java 8, and the method implemented is the
compare method. Therefore, the
compare method is implemented by the
comparing method using the specified key. To learn how to use the
Comparator.comparing method, follow these seven steps.
How to Use the finally Block in Java
finally block is coded after a try catch block. The statements in the
finally block are executed unconditionally, i.e., regardless of whether an exception was thrown. To learn how to use the
finally block in Java, follow these five steps.
How to Use the instanceof Operator with a Generic Class in Java
From time to time you might want to know the data type of a parameter passed to method in a Java generic class. For example, imagine that you wish to write a method to identify whether a String or an Integer was received as an argument. You could accomplish this task using the
instanceof operator. To learn how to use the
instanceof operator with a Java generic class, follow these four steps.
How to Use the super Keyword to Call a Base Class Constructor in Java
A derived Java class can call a constructor in its base class using the
super keyword. In fact, a constructor in the derived class must call the super's constructor unless default constructors are in place for both classes. To understand how to use the super keyword to call a base class constructor, follow these 10 steps.
How to Use the this Keyword to Call Another Constructor in Java
A Java class may have more than one constructor. Usually the assignments made in each constructor overlap. To eliminate redundant assignment statements, the developer can call another constructor by using the
this keyword. To write a program that uses
this in this manner, follow these seven steps.
How to Work with Properties in Java
A property in Java can be used to store a value and associate that value with a key. A common application of properties is storing user preferences. For example, a nickname can be stored in a properties file and retrieved at a later time by using a key of "nickName". To learn how to work with properties in Java, follow these four steps.
How to Write a Block of Code in Java
Program code in a Java program is contained in a block. A block begins with an open curly brace symbol and ends with a close curly brace symbol. As an example, we might write a block of code that contains a variable definition and some console print statements. To write a block of code, follow these four steps.
How to Write an Arithmetic Expression in Java
An arithmetic expression in Java is a sequence of numeric literals and/or numeric variables separated by arithmetic operators. The result of an arithmetic expression is a number. To create an arithmetic expression and test your expression, follow these four steps.
How to Write a Unit Test in Java
A unit test in Java gives the developer the opportunity to test an object. For example, you might want to verify that a Person object contains the expected person name or perhaps the correct email address. In addition, you may want to verify that a property is not null.
How to Write Comments in Java
A comment in a Java program is one or more lines of text. A comment may be single line, multi-line or Javadoc. To practice writing each type of comment, follow these four steps.
How to Write for-each Loops in Java
The for-each loop was introduced in Java 5. Actually, the loop is a
for loop with a
: placed between a variable and a data structure such as an array. Each item of the data structure is stored in the variable per loop iteration. The loop terminates when the final item has been processed. To understand how to write for-each loops in Java, follow these four steps.
How to Write Type Parameters with Multiple Bounds in Java
A generic type can be bounded with multiple class data types. The class types that qualify are subclasses of a specified data type or implementations of an interface. For example, we might wish to create a vector or array list and call a method in a generic class to process the data. Both the
Vector classes are implementations of the
List interface. Therefore the bounds of the generic parameter are the implementations of
List. To learn how to write type parameters with multiple bounds in Java, follow these four steps.
How to Write while and do while Loops in Java
while loop in Java executes one or more statements after testing the loop continuation condition at the start of each iteration. The
do while loop, however, tests the loop continuation condition after the first iteration has completed. Therefore, the
do while loop guarantees one execution of the loop logic whereas the
while does not. To understand how to code each of these loops, follow these eight steps.