By convention, class names start with an uppercase letter.
Capitalize the first letter of each word in the name. ex) ComputeExpression
Capitalize all letters in constants, and use underscores to connect words.
final datatype CONSTANT_NAME = VALUE;
Use lowercase for the first word.
Capitalize the first letter of each subsequent word in the name.
A process that seeks to understand the problem and document in detail what the software system needs to do. This phase involves close interaction between users and designers.
Seeks to analyze the business process in terms of data flow, and to identify the system's input and output. Part of the analysis entails modeling the system's behavior. The model is intended to capture the essential elements of the system and to define services to the system.
The process of designing the system's component This phase involves the use of many levels of abstraction to decompose the problem into manageable components, identify classes and interfaces, and establish relationships among the classes and interfaces.
The essence of system analysis and design is input, process, and output. This is called IPO.
The process of translating the system design into programs. Seperate programs are written for each component and put to work together. The implementation involves coding, testing, and debugging.
Ensures that the code meets the requirements specification and weeds out bugs.
Deployment makes the project available for use. For a java program, this means installing it on a desktop or on the Web.
This requires periodic upgrades of the product to fix newly discovered bugs and incorporate changes.
All binary operators except assignment operators are left-associative. ex) a-b+c-d => ((a-b)+c)-d Assignment operators are right-associative. ex) a=b+=c=5 => a=(b+=(c=5))
Java provides many useful methods in the Math class for performing common mathematical functions.
Java characters use Unicode, and display of written texts in the world;s divers languages. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'.
There are methods like isDigit, isLetter, toLowerCase, etc.
Stirng is actually a predefined class in the Java library. The String type is not a primitive type. It is know as a reference type.
In String class, there are many useful and confortable methods.
The arrays are stored in a heap. In Array class, there are many useful and confortable methods.
OOP involves programming using objects. An object represents an entity in the real world that can be distinctly identified. ex) a student, a desk, a circle, etc. An object has a unique identity, statem and behaviors. The state of an object consists of a set of data fields. The behavior of an object is defined by a set of methods.
- variables to define data field
- methods to define behaviors
- constructors
After the assignment statement c1 = c2, c1 points to the same object referenced by c1 is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM.
Static variables are shared by all the instances of the class. Static methods are not tied to a specific object. Static constants are final variables shared by all the instances of the class.
- To protect data
- To make code easy to maintain
If the contents of an object cannot be changed once the object is created, the object is called an immutable object and its class is called an immutable class.
- For a class to be immutable, it must mark all data fields private and provide no mutator methods and no accessor methods that would return a reference to a mutable data field object.
- Class abstarction means to separate class implementation from the use of the class.
- The creator of the class provides a description of the class and let the user know how the class can be used.
- The user of the class does not need to know how the class is implemented. The detail of implementaion is encapsulated and hidden from the user.
- A class should describe a single entity, and all the class operations should logically fit together to support a coherent purpose. For example, you should not combine students and staff in the same class, because students and staff have different entities.
- A single entity with too many responsibilities can be broken into several classes to separate responsibilities.
- For example, the classes String, StringBuilder, and StringBuffer all deal with strings, but have different responsibilities.
- Classes are designed for reuse.
- Follow standard Java programming style and naming conventions.
- Choose informative names for classes, data fields, and methods.
- Always place the data declaration before the constructor, and place constructors before methods.
- Always provide a constructor and initialize variables to avoid programming errors.
- A class should use the private modifier to hide its data from direct access by clients.
- You can use get methods and set methods to provide users with access to the private data, but only to private data you want the user to see or to modify.
- A class should also hide methods not intended for client use.
- Make the fields or method protected if they are intended for extenders of the class.
- A property that is shared by all the instances of the class should be declared as a static property.
- Composition is actually a special case of the aggregation relationship.
- Aggregation models has-a relationships and represents an ownership relationship between two objects.
- The owner object is called an aggregating object and its class an aggregating class.
- The subject object is called an aggregated object and its class an aggregated class.
Boolean, Character, Short, Byte, Integer, Long, Float, Double
- The wrapper classes do not have no-arg constructors
- The instances of all wrapper classes are immutable. i.e., their internal values cannot be changed once the objects are created.
- A String object is immutable. i.e., its contents cannot be changed.
Since strings are immutable and are frequently used, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. Such an instance is called interned. For example, the following statements:
The calsses is an alternative to the String class. In general, a StirngBulder/StringBuffer can be used wherever a string is used.StringBuilder/StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created.
They are not inherited. They are invoked explicitly or implicitly.
Explicitly using the super keyword.
If the keyword super is not explicitly used, the superclass's no-arg constructor is automatically invoked. the compiler puts super() as the first statement in the constructor.
- To call a superclass constructor
- To call a superclass method
- Add new properties
- Add new methods
- Override the methods of the superclass
- An instance method can be overridden only if it is accessible
- Thus a private method cannot be overridden, because it is not accessible outside its own class.
- If a method defined in a subclass is private in its superclass, the two methods are completely unrelated.
- Like an instance method, a static method can be inherited.
- However, a static method cannot be overridden.
- If a static method defined in the superclass is redefined in subclass, the method defined in the superclass is hidden.
Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object.
- toString() method
Polymorphism means that a variable of a supertype can refer to a subtype object.
An object of a subtype can be used wherever its supertype value is required.
- Suppose an object o is an instance of classes : C1,C2,...,Cn-1 and Cn.
- C1 is most specific class, Cn is most general class. In java, Cn is the Object class.
- If o invokeds a method p, the JVM in turn searches the implementation for the method p in C1,C2,...,Cn-1, and Cn, until it is found.
- Once an implementation is found, the search stops and the first-found implementation is invoked.
You have already used the casting operator to convert variables of one primitive type to another. Casting can also be used to convert an object of one class type to another within an inheritance hierarchy.
- Why does the statement Object o = new Student() work and the statement Student b = o doesn’t?
- This is because a Student object is always an instance of Object, but an Object is not necessarily an instance of Student.
- Even though you can see that o is really a Student object, the compiler is not so clever to know it.
- To tell the compiler that o is a Student object, use an explicit casting.
- Ex) Student b= (Student)o;
- Explicit casting must be used when casting an object from a superclass to a subclass.
Use the instanceof operator to test whether an object is an instance of a class.
- A subclass may override a protected method in its superclass and change its visibility to public.
- However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass.
- The final class cannot be extended
- The final variable is a constant
- the final method cannot be overridden by its subclasses.
You can create an array to store objects. But the array’s size is fixed once the array is created. Java provides the ArrayList class that can be used to store an unlimited number of objects.
ArrayList is known as a generic class with a generic type E.
You can specify a concrete type to replace E when creating an ArrayList.
For example, the following statement creates an ArrayList and assigns its reference to variable cities.
This ArrayList object can be used to store strings.
ArrayList<String> cities = new ArrayList<String>();
ArrayList<String> cities = new ArrayList<>();
System errors are thrown by JVM and represented in the Error class. The Error class describes internal system error. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
- Runtime Exceptions
- RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
RuntimeException, Error and their subclasses are known as unchecked exceptions.
All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.
- Unchecked Exceptions
- In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. These are the logic errors that should be corrected in the program.
Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify.
An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.
You should use it to deal with unexpected error conditions.
Do not use it to deal with simple, expected situations.
try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
}
/* is better to be replaced by */
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
- Use the exception classes in the API whenever possible.
- Define custom exception classes if the predefined classes are not sufficient.
- Define custom exception classes by extending Exception or a subclass of Exception.
An assertion is a Java statement that enables you to assert an assumption about your program. An assertion contains a Boolean expression that should be true during program execution. Assertions can be used to assure program correctness and avoid logic errors.
- Assertion should not be used to replace exception handling. Exception handling deals with unusual circumstances during program execution. Assertions are to assure the correctness of the program.
- Do not use assertions for argument checking in public methods. Valid arguments that may be passed to a public method are considered to be part of the method’s contract.
- Use assertions to reaffirm assumptions. This gives you more confidence to assure correctness of the program.
The File class is a wrapper class for the file name and its directory path.
In order to perform I/O, you need to create objects using appropriate Java I/O classes.
Just like you can read data from a file on your computer, you can read data from a file on the Web.
URL url = new URL("www.google.com/index.html");
Scanner input = new Scanner(url.openStream());
Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. The advantage of binary files is that they are more efficient to process than text files.
Text I/O requires encoding and decoding. The JVM converts a Unicode to a file specific encoding when writing a character and coverts a file specific encoding to a Unicode when reading a character. Binary I/O does not require conversions.
- InputStream
- OutputStream
- FileInputStream
- To construct a FileInputStream, use the following constructors :
- public FileInputStream(String filename)
- public FileInputStream(File file)
- To construct a FileInputStream, use the following constructors :
- FileOutputStream
- To construct a FileOutputStream, use the following constructors :
- public FileOutputStream(String filename)
- public FileOutputStream(File file)
- public FileOutputStream(String filename, boolean append)
- public FileOutputStream(File file, boolean append)
- If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter.
- To construct a FileOutputStream, use the following constructors :
- FilterInputStream/FilterOutputStream
- Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters. FilterInputStream and FilterOutputStream are the base classes for filtering data. When you need to process primitive numeric types, use DataInputStream and DataOutputStream to filter bytes.
- DataInputStream
- DataOutputStream
- BufferedInputStream/BufferedOutputStream
- BufferedInputStream/BufferedOutputStream does not contain new methods. All the methods BufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream classes.
- public BufferedInputStream(InputStream in)
- public BufferedInputStream(InputStream in, int bufferSize)
- public BufferedOutputStream(OutputStream out)
- public BufferedOutputStream(OutputStream out, int bufferSize)
- ObjectInputStream/ObjectOutputStream
You can use input.available() to check it. input.available() == 0 indicates that it is the end of a file.
All of the streams you have used so far are known as read-only or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations.
Many methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream. For example, readInt(), readLong(), writeDouble(), readLine(), writeInt(), and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams.
A random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data.
Not all objects can be written to an output stream. Objects that can be written to an object stream is said to be serializable. So the class of a serializable object must implement Serializable.
The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable.
If an object is an instance of Serializable, but it contains non-serializable instance data fields, can the object be serialized? The answer is no. To enable the object to be serialized, you can use the transient keyword to mark these data fields to tell the JVM to ignore these fields when writing the object to an object stream.
public class Foo implements java.io.Serializable {
private int v1;
private static double v2;
private transient A v3 = new A();
}
class A { } // A is not serializable
- When an object of the Foo class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.
An array is serializable if all its elements are serializable. So an entire array can be saved using writeObject into a file and later restored using readObject.
Generics is the capability to parameterize types. With this capability, you can define a class or a method with generic types that can be substituted using concrete types by the compiler.
The key benefit of generics is to enable errors to be detected at compile time rather than runtime. A generic class or method permits you to specify allowable types of objects that the class or method may work with. If you attempt to use the class or method with an incompatible object, a compile error occurs.
public static <E> void print(E[] list) {
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
public static void main(String[] args ) {
Rectangle rectangle = new Rectangle(2, 2);
Circle circle = new Circle (2);
System.out.println("Same area? " + equalArea(rectangle, circle));
}
public static <E extends GeometricObject> boolean equalArea(E object1, E object2) {
return object1.getArea() == object2.getArea();
}
- Even if not extends but implements, use extends.
- ? (unbounded wildcard)
- ? extends T (bounded wildcard)
- ? super T (lower Bound wildcard)
- Cannot Create an Instance of a generic Type. e.g., new E()
- Generic Array Creation is Not Allowed. e.g., new E[100]
- A Generic Type Parameter of a Class Is Not Allowed in a Static Context.
- Exception Classes Cannot be Generic.
Reference
- Y. Daniel Liang, "Introduction to Java Programming, 10th Edition"