Java: Tips and Tricks
You can check object type in Java by using the
instanceofkeyword. 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 anintdata type. To learn how to check object type, follow these four steps.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.
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.
You can throw an exception in Java by using the
throwkeyword. 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.Java has many built-in exception classes, such as
NullPointerExceptionandIllegalArgumentException. At times however, you might want to create your own exception class. For example, as opposed to throwingIllegalArgumentExceptionwhen a 0 is detected as a divisor during a division operation, you might wish to throw aDivideByZeroException. 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.A derived Java class can call a constructor in its base class using the
superkeyword. 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.The
Comparator.comparingmethod, introduced in Java 8, returns a Comparator object that will use the specified field as the sort key. TheComparatorinterface is a functional interface in Java 8, and the method implemented is thecomparemethod. Therefore, thecomparemethod is implemented by thecomparingmethod using the specified key. To learn how to use theComparator.comparingmethod, follow these seven steps.At times you might need to read console input provided by the user from the keyboard. The
System.infield 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 useSystem.inin Java, follow these four steps.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.
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
ZonedDateTime, theZoneOffset, or theZoneIdclass. Each class is located in thejava.timepackage. To understand how to add a time zone to a date/time object in Java 8, follow these four steps.An exception can be rethrown in a
catchblock. This action will cause the exception to be passed to the calling method. If the rethrow operation occurs in themainmethod 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 thecatchblock. To learn how to rethrow an exception in Java, follow these four steps.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
instanceofoperator. To learn how to use theinstanceofoperator with a Java generic class, follow these four steps.In Java programming, instantiating an object means to create an instance of a class. To instantiate an object in Java, follow these seven steps.
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.
A derived class is a Java class that inherits properties from its super class. For example, an
Employeeclass might be derived from aPersonclass. Therefore theEmployeeclass could inherit first name and last name properties fromPerson, its super class. The following eight steps show how to write a derived class in Java.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.
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.
An implementation of an interface is a Java program that references the interface using the
implementskeyword. 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.To test whether two objects are equal, a developer should provide an
equalsmethod. 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 theequalsmethod, follow these four steps.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.
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.
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.
Displaying the contents of a directory in Java can be accomplished using the
Fileclass. This class provides thelistFilesmethod that returns a list ofFileobjects 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.The
Collectorsclass 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.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.
The limit method of the
Streamclass 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.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.
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.
The ordering of a tree set in Java can be dictated using implementations of either the
ComparableorComparatorinterface.In Java, the
breakstatement causes the execution of a loop to stop. The loop can be afor,while, ordo...whileloop. To understand how to break out of a loop, follow these four steps.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
thiskeyword. To write a program that usesthisin this manner, follow these seven steps.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.
To reference a variable in a Java program, you must first declare it. To declare a variable, follow these four steps.
A derived Java class can override a method in its base class. For example, a means of payment method in a
Personclass might return a generic message; e.g., "Person is paid monthly". In theEmployeeclass, 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.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.iopackage that assist the developer in using serialized objects. To learn how to use serialized objects in Java, follow these seven steps.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.
Single abstract method interfaces are well-known to Java developers. For example, the
Runnableinterface contains one abstract method calledrun. 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 theRunnableinterface when instantiating aThreadobject). In this tutorial, we'll create a functional interface that contains one abstract method to generate a greeting.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
ArrayListandVectorclasses are implementations of theListinterface. Therefore the bounds of the generic parameter are the implementations ofList. To learn how to write type parameters with multiple bounds in Java, follow these four steps.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.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.
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
mapmethod of theStreamclass. 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 themapmethod, follow these four steps.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.
The
whileloop in Java executes one or more statements after testing the loop continuation condition at the start of each iteration. Thedo whileloop, however, tests the loop continuation condition after the first iteration has completed. Therefore, thedo whileloop guarantees one execution of the loop logic whereas thewhiledoes not. To understand how to code each of these loops, follow these eight steps.The
finallyblock is coded after a try catch block. The statements in thefinallyblock are executed unconditionally, i.e., regardless of whether an exception was thrown. To learn how to use thefinallyblock in Java, follow these five steps.The for-each loop was introduced in Java 5. Actually, the loop is a
forloop 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.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.
The
continuestatement 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 afor,while, ordo...whileloop. To understand how to continue the execution of a loop, follow these four steps.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.
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.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.
