The fields and methods of the math class cannot be directly accessed as they are static.
The "static" Variables/MethodsYou can apply modifier " Show
Each instance maintains its own storage. As the result, each instance variable/method has its own copy in the instances and not shared among different instances. To reference an instance variable/method, you need to identify the instance, and reference it via A Non- The usage of
(I believe that the keyword " UML Notation: ExamplesCounting the number of instance created - Instance variable won't work!Suppose that we want to count the number of instances created. Using an instance variable doesn't work?! public class Circle { public int count = 0; private double radius; public Circle(double radius) { this.radius = radius; ++count; } public static void main(String[] args) { Circle c1 = new Circle(1.1); System.out.println("count is: " + c1.count); Circle c2 = new Circle(2.2); System.out.println("count is: " + c2.count); Circle c3 = new Circle(3.3); System.out.println("count is: " + c3.count); } } This is because Use a static variable to count the number of instancesWe need to use a " CircleWithStaticCount.javapublic class CircleWithStaticCount { public static int count = 0; private double radius; public CircleWithStaticCount(double radius) { this.radius = radius; ++count; } public static void main(String[] args) { CircleWithStaticCount c1 = new CircleWithStaticCount(1.1); System.out.println("count is: " + c1.count); System.out.println("count is: " + CircleWithStaticCount.count); CircleWithStaticCount c2 = new CircleWithStaticCount(2.2); System.out.println("count is: " + CircleWithStaticCount.count); System.out.println("count is: " + c1.count); System.out.println("count is: " + c2.count); CircleWithStaticCount c3 = new CircleWithStaticCount(3.3); System.out.println("count is: " + CircleWithStaticCount.count); System.out.println("count is: " + c1.count); System.out.println("count is: " + c2.count); System.out.println("count is: " + c3.count); } } Using static variables/methods as "global" variables and "utility" methodsAnother usage of " Non- Within a class definition, a public class StaticTest { private static String msgStatic = "Hello from static"; private String msgInstance = "Hello from non-static"; public static void main(String[] args) { System.out.println(msgStatic); compilation error: non-static variable xxx cannot be referenced from a static context } } If a class has only
one single instance (known as singleton design pattern), it could be more efficient to use
The Static InitializerA static initializer is a block of codes labeled public class StaticInitializerTest { static int number; static { number = 88; System.out.println("running static initializer..."); } public static void main(String[] args) { System.out.println("running main()..."); System.out.println("number is: " + number); } } During the class loading, JVM allocates
the The Class LoaderEvery JVM has a built-in class loader (of type The class loader loads a class only once, so there is only one During the class loading, the class loader also allocates the public class ClassLoaderTest { private static int number1 = 11; static { System.out.println("running static initializer..."); number1 = 99; number2 = 88; System.out.println("number1 is " + number1); } private static int number2 = 22; public static void main(String[] args) { System.out.println("running main()..."); System.out.println("in main(): number1 is " + number1 + ", number2 is: " + number2); } } The Instance InitializerSimilarly, you could use the so-called instance initializer, which runs during the instantiation process, to initialize an instance. Instance initializer is rarely-used. For example, class Foo { int number; { System.out.println("running instance initializer..."); number = 99; } public Foo() { System.out.println("running constructor..."); System.out.println("number is: " + number); } } public class InstanceInitializerTest { public static void main(String[] args) { Foo f1 = new Foo(); Foo f2 = new Foo(); } } The "Instantiation" ProcessThe sequence of events when a new object is instantiated via the
For example, class Foo { public int number1 = 11; { number1 = 33; number2 = 44; } public int number2 = 22; public Foo() { System.out.println("running Foo()..."); } public Foo(int number1, int number2) { System.out.println("running Foo(int, int)..."); this.number1 = number1; this.number2 = number2; } } public class InstantiationTest { public static void main(String[] args) { Foo f1 = new Foo(); System.out.println("number1 is " + f1.number1 + ", number2 is " + f1.number2); Foo f2 = new Foo(55, 66); System.out.println("number1 is " + f2.number1 + ", number2 is " + f2.number2); } } The "final" Class/Variable/MethodYou can
declare a class, a variable or a method
final Variables of Primitive Type vs. Reference Type
final vs. abstract
Package, Import, Classpath & JARIf I have a class called A package, like a library, is a collection of classes, and other related entities such as interfaces, errors, exceptions, annotations, and enums. UML Notation: Packages are represented in UML notation as tabbed folders, as illustrated. Package name (e.g., Packages are used for:
Package Naming ConventionA package name is made up of the reverse of the domain Name (to ensure uniqueness) plus your own organization's project name separated by dots. Package names are in lowercase. For example, suppose that your Internet Domain Name is " The prefix " Package Directory StructureThe "dots" in a package name correspond to the directory structure for storing the class files. For example, the JVM can locate your class files only if the package base directory and the fully-qualified name are given. The package base directory is provided in the so-called classpath (to be discussed later). The "dot" does not mean sub-package (there is no such thing as sub-package). For example, moduleJDK 9 introduces a hierarchical level called "module" on top of packages, which will not be covered in this article. The "import" StatementThere are two ways to reference a class in your source codes:
The compiler, when encounter a unresolved classname, will search the The The import packagename.classname; import packagename.* You can import java.util.Scanner; import java.awt.Graphics; You can also import java.util.*; import java.awt.*; import java.awt.event.*; Using wildcard may result in slightly fewer source lines. It has no impact on the resultant bytecode. It is not recommended as it lacks clarity and it may lead to ambiguity if two packages have classes of the same names. The Java
core language package There is also no need for Take note that the The "import static" Statement (JDK 1.5)Prior to JDK 1.5, only classes can be "imported" - you can omit the package name for an imported class. In JDK 1.5, the
The import static packagename.classname.staticVariableName; import static packagename.classname.staticMethodName; import static packagename.classname.*; Take note that Creating PackagesTo put a class as part of a package, include a package com.zzz.test;
public class HelloPackage {
public static void main(String[] args) {
System.out.println("Hello from a package...");
}
} You can create and use package in IDE (such as Eclipse/NetBeans) easily, as the IDE takes care of the details. You can simply create a new package, and then create a new class inside the package. Compiling Classes in PackageTo compile classes in package using JDK, you need to use " > javac -d e:\myproject HelloPackage.java The " Running Classes in PackageTo run the program, you need to set your current working directory at the package base directory (in this case " e:\myproject> java com.zzz.test.HelloPackage It is important to take note that you shall always work in the package base directory and issue fully-qualified name. As mentioned, if you use an IDE, you can compile/run the classes as usual. IDE will take care of the details. The Default Unnamed PackageSo far, all our examples do not use a Java Archive (JAR)An Java application typically involves many classes. For ease of distribution, you could bundles all the class files and relevant resources into a single file, called JAR (Java Archive) file. JAR uses the famous "zip" algorithm for compression. It is modeled after Unix's "tar" (Tape ARchive) utility. You can also include your digital signature (or certificate) in your JAR file for authentication by the recipients. JDK provides an utility
called " > jar cvf myjarfile.jar c1.class ... cn.class ExampleTo place the earlier class e:\myproject> jar cvf hellopackage.jar com\zzz\test\HelloPackage.class added manifest adding: com/zzz/test/HelloPackage.class(in = 454) (out= 310)(deflated 31%) Read "Java Archive (JAR)" for more details. Classpath - Locating Java Class FilesJava allows you to store your class
files anywhere in your file system. To locate a class, you need to provide the package base directory called classpath (short for user class search path) and the fully-qualified name. For example, given that the package base directory is When the Java compiler or runtime needs a class (given its fully-qualified name), it searches for it from the classpath. You could specify the
classpath via the command-line option A classpath may contain many entries (separated by Example on Package, Classpath and JARIn this example, we shall kept the source files and class files in separate directories - " com.zzz.geometry.CircleLet's create a class called package com.zzz.geometry; public class Circle { public String toString() { return "This is a Circle"; } } To compile the > javac -d d:\zzzpackages\bin Circle.java
com.zzz.geometry.CylinderNext, create a class called package com.zzz.geometry; public class Cylinder extends Circle { public String toString() { return "This is a Cylinder"; } } No To compile the > javac -d d:\zzzpackages\bin -cp d:\zzzpackages\bin Cylinder.java
com.yyy.animal.CatCreate another class called package com.yyy.animal; public class Cat { public String toString() { return "This is a Cat!"; } } Again, use > javac -d d:\yyypackages\bin Cat.java
myTest.testWe shall write a package mytest; import com.zzz.geometry.Circle; import com.zzz.geometry.Cylinder; import com.yyy.animal.Cat; public class Test { public static void main(String[] args) { Circle circle = new Circle(); System.out.println(circle); Cylinder cylinder = new Cylinder(); System.out.println(cylinder); Cat cat = new Cat(); System.out.println(cat); } } To compile the > javac -d d:\testpackages\bin -cp d:\zzzpackages\bin;d:\yyypackages\bin Test.java
To run the > java -cp .;d:\zzzpackages\bin;d:\yyypackages\bin mytest.Test Jarring-up com.zzz.geometry packageNow, suppose that we decided to jar-up the > jar cvf d:\jars\geometry.jar com\zzz\geometry\*.class added manifest adding: com/zzz/geometry/Circle.class(in = 300) (out= 227)(deflated 24%) adding: com/zzz/geometry/Cylinder.class(in = 313) (out= 228)(deflated 27%) > jar cvf d:\jars\geometry.jar . added manifest adding: com/(in = 0) (out= 0)(stored 0%) adding: com/zzz/(in = 0) (out= 0)(stored 0%) adding: com/zzz/geometry/(in = 0) (out= 0)(stored 0%) adding: com/zzz/geometry/Circle.class(in = 300) (out= 227)(deflated 24%) adding: com/zzz/geometry/Cylinder.class(in = 313) (out= 228)(deflated 27%) To run > java -cp .;d:\jars\geometry.jar;d:\yyypackages\bin mytest.Test Separating Source Files and ClassesFor ease of distribution (without source files), the source files and class files are typically kept in separate directories.
Two Classes of the Same Classname?Suppose that
we have two How JVM Find ClassesReference: JDK documentation on "How classes are found". To locate a class (given its fully-qualified name), you need to locate the base directory or the JAR file. The JVM searches for classes in this order:
The user classes are searched in this order:
The JVM puts the classpath is the system property System.out.println(System.getProperty("java.class.path")); javac|java's command-line option -classpath or -cpI have demonstrated the
command-line option The CLASSPATH Environment VariableAlternatively, you could also provide your classpath entries in the Read
"Environment Variables (PATH, CLASSPATH, JAVA_HOME)" for more details about It is recommended that you use the More Access Control Modifiers – protected and default package-privateJava has four access control modifiers for class/variable/method. Besides the
Java Source FileA Java source file must have the file type of " The source file shall contain statements in this order:
Each The top-level class must be either Dissecting the Hello-worldLet us re-visit the "Hello-world" program, which is reproduced below:
System.out.println()If you check the JDK API specification, you will find that:
The figure illustrate the classes involved in
Take note that each of the dot ( ExampleAs an example, the reference "
Nested and Inner ClassesRead "Nested and Inner Classes". More on Variables and ReferencesTypes of VariablesThe type of a variable determines what kinds of value the variable can hold and what operations can be performed on the variable. Java is a "strong-type" language, which means that the type of the variables must be known at compile-time. Java has three kinds of types:
A primitive variable holds a primitive value (in this storage). A reference variable holds a reference to an object or array in the heap, or Java implicitly defines a reference type for each possible array type - one for each of the eight primitive types and an object array. Scope & Lifetime of VariablesThe scope of a variable refers to the portion of the codes that the variable can be accessed. The lifetime refers to the span the variable is created in the memory until it is destroyed (garbage collected). A variable may exist in memory but not accessible by certain codes. Java supports three types of variables of different lifetimes: Automatic Variable (or Local Variable): Automatic Variables include method's local variables and method's parameters. Automatic variables are created on entry to the method and are destroyed when the method exits. The scope of automatic variables of a method is inside the block where they are defined. Local variable cannot have access modifier (such as For example, public class AutomaticVariableTest { public static void main(String[] args) { for (int i = 0; i < 10; ++i) { System.out.println(i); } int j = 0; for (j = 0; j < 10; ++j) { System.out.println(j); } System.out.println(j); int k = 1; do { int x = k*k; ++k; System.out.println(k); } while (x < 100); } } Member variable (or Instance variable) of a Class: A member variable of a class is created when an instance is created, and it is destroyed when the object is destroyed (garbage collected). Static variable (or Class variable) of a Class: A Variable InitializationAll class member and
You can use them without assigning an initial value. Automatic variables are not initialized, and must be explicitly assigned an initial value before it can be referenced. Failure to do so triggers a compilation error "variable xxx might not have been initialized". Array InitializerArray's elements are also initialized once the array is allocated (via the For example, String[] strArray = new String[2]; for (String str: strArray) { System.out.println(str); } You can also use the so-called array initializer to initialize the array during declaration. For example, int[] numbers = {11, 22, 33}; String[] days = {"Monday", "Tuesday", "Wednesday"}; Circle[] circles = {new Circle(1.1), new Circle(2.2), new Circle(3.3)}; float[][] table = {{1.1f, 2.2f, 3.3f}, {4.4f, 5.5f, 6.6f}, {7.7f, 8.8f, 9.9f}}; int[][] data = {{1, 4, 8}, {2, 3}, {4, 8, 1, 5}}; Stack/Heap and Garbage CollectorWhere Primitives and Objects Live?Primitive types, such as Reference types, such as objects and arrays, are created in the "heap" at runtime (via the For automatic variable of reference type: the reference is local (allocated in the method stack), but the object is allocated in the heap. Stack and heap are typically located at the opposite ends of the data memory, to facilitate expansion. Object ReferencesWhen a Java object is constructed via the In some JVM implementations, this object reference is simply the address of the object in the heap. However, the JVM specification does not specify how the object reference shall be implemented as long as it can uniquely identify the object. Many JVM implementations use so-called double indirection, where the object reference is the address of an address. This approach facilitates the garbage collector (to be explained next) to relocate objects in the heap to reduce memory fragmentation. Objects are created via the
For primitives stored in the stack, compiler can determine how long the item lasts and destroy it once it is out of scope. For object in heap, the compiler has no knowledge of the creation and lifetime of the object. In C++, you must destroy the heap's objects yourself in your program once the objects are no longer in use (via In Java, you don't have to destroy and de-allocate the objects yourself. JVM has a built-in process called garbage collector that automatically releases the memory for an object when there is no more reference to that object. The garbage collector runs in a low priority thread. An object is eligible for garbage collection when there is no more
references to that object. Reference that is held in a variable is dropped when the variable has gone out of its scope. You may also explicitly drop an object reference by setting the object reference to If a new reference is assigned to a reference variable (e.g., via System.gc() & Runtime.gc()You can explicitly ask for garbage collection by calling static methods Pitfalls of JavaJava's garbage collector frees you from worrying about memory
management of objects (no more However, garbage collector does has its drawbacks:
Many programmers prefer to use C++ for game programming and animation, as these programs could create millions of objects in a short span. Managing memory efficiently is critical, instead of relying on garbage collector. There are some (imperfect) solutions to memory management in Java, e.g.,
This solution shall remain imperfect until the Java designers decided to allow programmers to manage the storage, which is not likely. More on MethodsPassing Arguments into Methods - By Value vs. By ReferenceRecall that a method receives arguments from the caller, performs operations defined in the method body, and returns a piece of result or To differentiate the parameters inside and outside the method, we have:
For example: public static double getArea(double radius) { return radius * radius * Math.PI; } public static void main(String[] args) { double r = 1.2; System.out.println(getArea(r)); System.out.println(getArea(3.4)); } In the above method definition, Passing Primitive-type Argument into Method - Pass-by-ValueIf the argument is a primitive type (e.g., For example,
In caller, before calling the method, the value is: 10 Inside method, before operation, the value is 10 Inside method, after operation, the value is 11 In caller, after calling the method, the value is: 10 Although the variables are called number in the caller as well as in the method's formal parameter, they are two different copies with their own scope. Passing Reference-Type Argument into Method - Also Pass-by-ValueIf the argument is a reference type (e.g., an array or an instance of a class), a copy of the reference is created and passed into the method. Since the caller's object and the method's parameter have the same reference, if the method changes the member variables of the object, the changes are permanent and take effect outside the method. For example,
In caller, before calling the method, the object is "Hello" Inside method, before change, the object is "Hello" Inside method, after change, the object is "Hello, world" In caller, after calling the method, the object is "Hello, world" If a method affect values outside the method itself other than the value returned, we say that the method has side-effect. Side effects may not be obvious by reading the method's codes, and must be handled with extreme care, and should be avoided if feasible. Proper comments should be provided in the method's header. Re-assigning the Reference inside the MethodSince a copy of the reference is passed into the method, if the method re-assigns the reference to the argument, the caller's object and the argument will not have the same reference. Change in the argument will not be reflected in the caller's object. For example,
In caller, before calling the method, the object is "Hello" Inside method, before change, the object is "Hello" Inside method, after change, the object is "world peace" In caller, after calling the method, the object is "Hello" Reference-Type Argument - Pass-by-Reference or Pass-by-value?As the object parameter can be modified inside the method, some people called it pass-by-reference. However, in Java, a copy of reference is passed into the method, hence, Java designers called it pass-by-value. Passing a Primitive as a One-Element Array?Primitive-type parameters are passed-by-value. Hence, the method is not able to modify the caller's copy. If you wish to let the method to modify the caller's copy, you might pass the primitive-type parameter as a one-element array, which is not recommended. Method Overloading vs. OverridingAn overriding method must have the same argument list; while an overloading method must have different argument list. You override a method in the subclass. You typically overload a method in the same class, but you can also overload a method in the subclass. A overriding method:
A overloading method:
Frequently-Used Packages in JDK APIJDK API is huge and consists of many packages (refer to JDK API specification). These are the frequently-used packages:
Package java.lang Frequently-used Classes" Frequently-used classes in "
java.lang.String, StringBuilder & StringBufferRead "Java String is Special". Wrapper Classes for Primitive TypesThe designers of Java language retain the primitive types in an object-oriented language, instead of making everything object, so as to improve the runtime efficiency and performance. However, in some situations, an object is required instead of a primitive value. For examples,
JDK provides the so-called
wrapper classes that wrap primitive values into objects, for each of the eight primitive types - Wrapper Classes are ImmutableEach of the wrapper classes contains a private member variable that holds the primitive value it wraps. The wrapped value cannot be changed. In other words, all the wrapper classes are immutable. Wrap via ConstructorsEach of the wrapper classes has a constructor that takes in the data type it wraps. For examples: Integer aIntObj = new Integer(5566); Double aDoubleObj = new Double(55.66); Character aCharObj = new Character('z'); Boolean aBooleanObj = new Boolean(true); All wrapper classes, except Static factory method valueOf() (JDK 5)The constructors had been deprecated in JDK 9. You should use
For examples, the following public static Integer valueOf(int i) public static Integer valueOf(String s) public static Integer valueOf(String s, int radix) For example, public class WrapperClassTest { public static void main(String[] args) { Integer iObj2 = Integer.valueOf(22); System.out.println(iObj2); Integer iObj3 = Integer.valueOf("33"); System.out.println(iObj3); Integer iObj4 = Integer.valueOf("1ab", 16); System.out.println(iObj4); Integer iObj5 = 44; int i5 = iObj5; System.out.println(i5); } } Unwrap via xxxValue() methodsThe public byte byteValue() public short shortValue() public abstract int intValue() public abstract long longValue() public abstract float floatValue() public abstract double doubleValue() Similarly, the public char charValue() public boolean booleanValue() ExampleInteger intObj = new Integer(556677); int i = intObj.intValue(); short s = intObj.shortValue(); byte b = intObj.byteValue(); Double doubleObj = new Double(55.66); double d = doubleObj.doubleValue(); int i1 = doubleObj.intValue(); Character charObj = new Character('z'); char c = charObj.charValue(); Boolean booleanObj = new Boolean(false); boolean b1 = booleanObj.booleanValue(); Constants - MIN_VALUE, MAX_VALUE and SIZEAll wrapper classes (except public static final type MIN_VALUE public static final type MAX_VALUE public static final int SIZE public static final int MAX_EXPONENT public static final int MIN_EXPONENT For examples: System.out.println(Integer.MAX_VALUE); System.out.println(Integer.MIN_VALUE); System.out.println(Integer.SIZE); System.out.println(Double.MAX_VALUE); System.out.println(Double.MIN_VALUE); System.out.println(Double.SIZE); System.out.println(Double.MAX_EXPONENT); System.out.println(Double.MIN_EXPONENT); Static Methods for Parsing StringsEach of the wrapper classes (except public static byte parseByte(String s) throws NumberFormatException public static short parseShort(String s) throws NumberFormatException public static int parseInt(String s) throws NumberFormatException public static long parseLong(String s) throws NumberFormatException public static float parseFloat(String s) throws NumberFormatException public static double parseDouble(String s) throws NumberFormatException public static boolean parseBoolean(String s) For examples: int i = Integer.parseInt("5566"); i = Integer.parseInt("abcd"); i = Integer.parseInt("55.66"); double d = Double.parseDouble("55.66"); Auto-Boxing & Auto-Unboxing (JDK 1.5)Prior to JDK 1.5, the programmers have to explicitly wrap a primitive value into an object, and explicitly unwrap an object to get a primitive value. For example, Integer intObj = new Integer(5566); int i = intObj.intValue(); Double doubleObj = new Double(55.66); double d = doubleObj.doubleValue(); The pre-JDK 1.5 approach involves quite a bit of code to do the wrapping and unwrapping. Why not ask the compiler to do the wrapping and unwrapping automatically? JDK 1.5 introduces a new feature called auto-boxing and unboxing, where the compiler could do the wrapping and unwrapping automatically for you based on their contexts. For example: Integer intObj = 5566; int i = intObj; Double doubleObj = 55.66; double d = doubleObj; With the auto-boxing and unboxing, your can practically ignore the distinction between a primitive and its wrapper object. java.lang.Math - Mathematical Functions & ConstantsThe public static double Math.PI; public static double Math.E; public static double Math.random(); public static double Math.sin(double x); public static double Math.exp(double x); public static double Math.log(double x); public static double Math.pow(double x, double y); public static double Math.sqrt(double x); For examples: double radius = 1.1; double area = radius * radius * Math.PI; int number = (int)Math.pow(2, 3); Take note that java.lang.Object - The Common Java Root Class
Java adopts a single common root class approach in its design, to ensure that all Java classes have a set of common baseline properties. The Object class defines and implements all these common attributes and behaviors that are necessary of all the Java objects running under the JVM. For example,
The public boolean equals(Object obj); public int hashCode(); protected Object clone(); protected void finalize(); public String toString(); public final Class getClass(); public final void wait(...); public final void notify(); public final void notifyAll();
java.lang.SystemThe The
java.lang.RuntimeEvery Java program is associated with an instance of
Package java.util Frequently-Used Classesjava.util.RandomAlthough Exampleimport java.util.Random; public class TestRandomClass { public static void main(String[] args) { Random random = new Random(); for (int i = 0; i < 10; ++i) { System.out.print(random.nextInt(100) + " "); } System.out.println(); System.out.println(random.nextDouble()); System.out.println(random.nextFloat()); Random anotherRandom = new Random(12345); for (int i = 0; i < 10; ++i) { System.out.print(anotherRandom.nextInt(100) + " "); } System.out.println(); } } Example: Simulating throw of 3 dice. import java.util.Random; public class DiceSimulation { public static void main(String[] args) { Random random = new Random(); int[] diceScores = new int[3]; int totalScore = 0; for (int i = 0; i < diceScores.length; ++i) { diceScores[i] = random.nextInt(6) + 1; } System.out.print("The dice are:"); for (int diceScore : diceScores) { totalScore += diceScore; System.out.print(" " + diceScore); } System.out.println(); System.out.println("The total score is " + totalScore); if (diceScores[0] == diceScores[1]) { if (diceScores[0] == diceScores[2]) { System.out.println("It's a 3-of-a-kind"); } else { System.out.println("It's a pair"); } } else { if (diceScores[0] == diceScores[2] || diceScores[1] == diceScores[2]) { System.out.println("It's a pair"); } } if ((diceScores[0] > diceScores[1] + diceScores[2]) || (diceScores[1] > diceScores[0] + diceScores[2]) || (diceScores[2] > diceScores[0] + diceScores[1])) { System.out.println("It's a special"); } } } java.util.Scanner & java.util.Formatter (JDK 1.5)Read "Formatted-text I/O". java.util.ArraysThe For examples,
Example: See "Collection Framework". java.util.CollectionSee "Collection Framework". Package java.text Frequently-Used ClassesThe [TODO] compare with (JDK 1.5) The java.text.NumberFormatThe
String myString = NumberFormat.getInstance().format(myNumber); The available factory methods are: public static final NumberFormat getInstance(); public static final NumberFormat getInstance(Locale l); public static final NumberFormat getNumberInstance(); public static final NumberFormat getNumberInstance(Locale l); public static final NumberFormat getIntegerInstance(); public static final NumberFormat getIntegerInstance(Locale l); public static final NumberFormat getCurrencyInstance(); public static final NumberFormat getCurrencyInstance(Locale l); public static final NumberFormat getPercentInstance(); public static final NumberFormat getPercentInstance(Locale l); The default currency format rounds the number to two decimal places; the default percent format rounds to the nearest integral percent; the default integer format rounds to the nearest integer. Example 1
United States: 123,456,789.123 France: 123 456 789,123 Japan: 123,456,789.123 United States: $123,456,789.12 France: 123 456 789,12 € Japan: ¥123,456,789 Example 2In this example, we use
You can also use the public Number parse(String source) throws ParseException java.text.DecimalFormatThe To use a double d = -12345.789 DecimalFormat format = new DecimalFormat("$#,###,##0.00"); System.out.println(format.format(d)); format.applyPattern("#,#00.0#;(#,#00.0#)"); To use a double d = -12345.789; NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN); if(nf instanceof DecimalFormat) { DecimalFormat df = (DecimalFormat) nf; df.applyPattern("##,#00.00#"); System.out.println(df.format(d)); } java.text.DateFormatThe Read "Date and Time". To format a date/time for the current locale, use one of the myString = DateFormat.getDateInstance().format(myDate); The available factory methods for getting a public static final DateFormat getTimeInstance(); public static final DateFormat getTimeInstance(int timeStyle); public static final DateFormat getTimeInstance(int timeStyle, Locale l) public static final DateFormat getDateInstance(); public static final DateFormat getDateInstance(int dateStyle); public static final DateFormat getDateInstance(int dateStyle, Locale l) public static final DateFormat getDateTimeInstance(); public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle); public static final DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale l); public static final DateFormat getInstance(); The exact display for each style depends on the locales, but in general,
You can also use the public Date parse(String source) throws ParseException java.text.SimpleDateFormatThe You can construct a public SimpleDateFormat(String pattern); public SimpleDateFormat(String pattern, Locale locale); For example, [TODO] Writing JavadocA great feature in Java is the documentation can be integrated with the source codes, via the so-called JavaDoc (Java Documentation) comments. In other languages, documentation typically is written in another file, which easily gets out-of-sync with the source codes. JavaDoc comments begin with You can use JDK utility With JavaDoc comments, you can keep the program documentation inside the same source file instead of using another documentation file. This provides ease in synchronization. JavaDoc comments and API documentation are important for others to re-use your program. Write JavaDoc comments while you are writing the program. Do not leave them as after-thought. ExampleLet's add the JavaDoc comments to all the public class Circle { private double radius; private String color; public Circle() { radius = 1.0; color = "blue"; } public Circle(double radius, String color) { this.radius = radius; this.color = color; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double getArea() { return radius * radius * Math.PI; } public String toString() { return "Circle[radius=" + radius + ", color=" + color + "]"; } } You can produce the standard API documentation, via JDK utility javadoc Circle.java Browse the resultant API, by opening the " MiscellaneousAre private members inherited by the subclasses?NO. Study the following example: class A { private void foo() { System.out.println("Class A runs private method foo()"); } } class B extends A { public void foo() { System.out.println("Class B runs public method foo()"); } } public class PrivateInheritanceTest { public static void main(String[] args) { A a1 = new A(); B b1 = new B(); b1.foo(); A a2 = new B(); } } static methods are inherited but cannot be overridden in subclassesReferences:
Study the following examples, class A { public static void foo() { System.out.println("A runs foo()"); } public static void bar() { System.out.println("A runs bar()"); } } class B extends A { public static void foo() { System.out.println("B runs foo()"); } public void bar() {} compilation error: bar() in B cannot override bar() in A public void hello() { foo(); bar(); } public static void helloStatic() { foo(); bar(); } } public class StaticInheritanceTest { public static void main(String[] args) { A a = new A(); a.foo(); A.foo(); a.bar(); A.bar(); B b = new B(); b.foo(); B.foo(); b.bar(); B.bar(); b.hello(); b.helloStatic(); B.helloStatic(); A a1 = new B(); a1.foo(); a1.bar(); } } In summary:
LINK TO JAVA REFERENCES & RESOURCES Can be accessed from any static method in the class?A static method can access only static data. It is a method which belongs to the class and not to the object(instance). A static method can access only static data. It cannot access non-static data (instance variables).
Why a static method Cannot access the instance variables and instance methods of a class?A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.
Why can't this be used in static methods?The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method.
What are static variables and methods?Static variables belong to the class, with all objects of a class sharing a single static variable. Static methods are associated with the class, not objects of the class. Static variables are used with the class name and the dot operator, since they are associated with a class, not objects of a class.
|