In this lesson, you will learn all about object-oriented programming within Java.
this self-referencestatic elementsIn general, the concept of an object is: a collection of data along with the functions to work with that data
In Java, all code must be written inside object definitions
Methods can work with any fields of an object, as well as any other method
A constructor is a function that defines the steps necessary to instantiate one object of that class
Each class should generally be defined in its own file if it is to be used by other classes
.java extensionThe data members of a class may be any type of data, objects or primitives
It is traditional in Java that only class names begin with capital letters
firstName) Like this Java tutorial? Try our self-paced online Java courses, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
For a whirlwind tour of Object-Oriented Programming (OOP), an object-oriented language isĀ supposed to include three major concepts:
Encapsulation - that data and the functions to work with that data are contained within the same entity; encapsulation includes another concept: data hiding or protection - where direct access to data is restricted in favor of methods that manipulate the data
Polymorphism - that there can be different forms of the same thing, so that you could have one variable that could store several different types of objects; or a method that accepts no arguments and another method with the exact same name that accepts an integer argument (and maybe another that accepts a string and a double-precision argument, etc.).
Inheritance - that an object definition can use another object definition as a starting point and build upon that base object (in which case the original object definition is called the base class, parent class, or superclass and the new class is called the derived class, the child class, or subclass, respectively) - note that a derived class can be used as a base for further inheritance, creating a chain
Java uses all three of these concepts
Java does not allow any code that is not part of an object - all code in your program must be inside a class definition
Java forces inheritance on every class - if you do not explicitly inherit
from a class, then by default Java assumes that you are inheriting from the
class called Object (which does not do much, but does have several
useful methods)
Object,
since whatever class you inherit from must have inherited from something,
which would be either Object or something that inherited from
something, etc.ObjectLike this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
An object-oriented program replaces the concept of a linear sequence of steps with steps that create instances of classes, connect them together, and set them to communicate with each other
For example, in an HR/Payroll application, we might have object classes that represent employees, dependents, checks, departments, financial accounts, etc
The act of creating a check for an employee could trigger a number of actions:
Encapsulation is the concept that the data and operations that work on or with that data are bundled together into one unit - the object
Objects are said to have state and behavior
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
In a procedural program, the executable code is usually kept in a separate area from the data values.
In an object-oriented program, it will appear to the programmer that the data values are kept with the executable code.
Encapsulation is often said to include the concept of data hiding, where the data elements of an object are not directly visible to the outside world. Instead, methods are provided to retrieve and set the values of the data elements.
One way to view an object-oriented environment is as a messaging system.
Objects can send each other messages by calling their methods. In the following
example, the code sends object p three messages, first to
set its first name value to "James", then to set its last name
to "Berger", and finally to ask it what the full name is (the
result of which it passes on in a message to System.out, requesting
that it be printed).
Person p = new Person();
p.setFirstName("James");
p.setLastName("Berger");
System.out.println(p.getFullName());
This discussion applies to object types that have already been defined; we will look at how to define object types later.
When an object is actually created and stored, that is known as an instance of the class
The keyword new is almost always used to instantiate an object:
StringBuffer sb = new StringBuffer("Hello World");
sb now holds an instantiated StringBuffer object
(StringBuffer is a class from the Java API)String does not require the new keyword,
text in quotes automatically becomes a String object:String s = "Hello World";
To use an object, we need an expression that provides a reference to the object:
. ) following an object reference gives
access to the elements of that objectString class has a method toUpperCase() that
returns an uppercase version of the text, we can now call that method to
get our message in uppercase:s.toUpperCase();
Hello.java program as follows:System.out.println(s.toUpperCase());
Hello.java to print the message in
uppercaseLike this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
When you create an object, it occupies some memory location that the JVM allocates at runtime.
If you then have a reference and set it equal to that object, the variable's memory location stores the numeric address of the memory location where the object is stored (often it is said that it points to the object's memory location; it is more appropriate to say that it references the object).
If you set one object variable equal to another, you do not have two copies of the object - you have one object and two variables that point to that object.
If you had the following:
MyClass myObject = new MyClass(); MyClass yourObject = myObject;
You would not end up with two copies of the same data, you would end up with two references to the same object (since all you really did was store another copy of the original object's memory address)
So, if you then changed the properties of myObject, the properties
as seen through yourObject would change as well.
Note: there is a clone() method available to copy an object's
contents to a new object.
Although this is a technicality, it is an important one: certain Java classes are immutable, or final; that is, they cannot be changed once they are created. Note that:
String objects are immutable, as are the wrapper classes that
hold primitive data types inside objects.String reference variable to a new value,
but what you are doing is setting the reference to point to a different
object.String, they would be unchanged - this follows
from how references work, but is counter to how some languages work. In the following code, the new keyword creates an object, in
this case a new StringBuffer object.
public class References {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = null;
sb2 = sb1;
sb2.append(" World");
System.out.println(sb1);
}
}
StringBuffer object containing
the text Hello, then creates a reference variable called sb1 that
points to that new object.sb2 that
points to nothing (it is set to null).sb2 to point to the same object
that sb1 points to.
sb2; the effect of this change is
seen via sb1 as well
A reference is a simple form of expression. References that result from
more complex expressions may be used as well. For, example, with an array
of String references called names, a method for one element
can be called in this manner:
names[1].toUpperCase()
Similarly, if a method returns a reference, a method may be called directly on the returned value.
public class ReferencesChained {
public static void main(String[] args) {
String ending = "World";
StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = null;
sb2 = sb1;
sb2.append(" ").append(ending);
System.out.println(sb1);
}
}
The StringBuffer.append method returns a reference to the
same StringBuffer object, so that another call to append
or any other method can be chained to the result.
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
The basic syntax for defining a class is:
[modifiers] class ClassName {
(field definitions, constructors, and methods go here)
}
Example (for overall format only, we will examine the pieces later):
public class BookBasic {
private int itemCode;
private String title;
public int getItemCode() {
return itemCode;
}
public void setItemCode (int newItemCode) {
if (newItemCode > 0) itemCode = newItemCode;
}
public String getTitle() {
return title;
}
public void setTitle (String newTitle) {
title = newTitle;
}
public void display() {
System.out.println(itemCode + " " + title);
}
}
Normally the access term for the class should be public, which
means that the class can be used in other classes.
public class definition must be in a file with a name
that matches the class name, but classes with other access levels do not
have that requirement.Class definitions may have different access levels - this determines where an object of the class may be instantiated or otherwise used.
public.All data and function members in a class are available to any code written for that class.
There are four possible access states. Three are declared with access keywords:
public - the member may be freely accessed by code from
any other class.protected - the member may not be accessed by code from
any other class, except:
private - the member may not be accessed by code in any
class, including classes that inherit from this one.Then there is the fourth possibility, the default access used if you use no access word at all. Note that:
Example - the example shown previously defines a class that will
be publicly available, so that any class could instantiate one. The class listed below can use that class in its code, but cannot directly
access the title or itemCode fields, so it must
call the setTitle and setItemCode methods to
set property values, and getTitle and getItemCode to
retrieve values:
public class UseBookBasic {
public static void main(String[] args) {
BookBasic b = new BookBasic();
b.setItemCode(5011);
b.setTitle("Fishing Explained");
System.out.println(b.getItemCode() + " " + b.getTitle());
System.out.print("From display: ");
b.display();
}
}
Like this Java tutorial? Try our self-paced online Java courses, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
What the access terms control is where the name of the item may be written in your code. Note that:
public, then the name of the item may be
written within code for any other class. private, then the name of the item may not
be written within the code for any other class.protected, then the name of the item may
not be written within the code for any other class, except one that extends
this class, or a class in the same package.For example:
public, then you can write the
name of the class in code in some other class (so you can use the class).private, then you can't write the name in any
other class, so you couldn't use it (in fact, a private class
definition can only be used in one very special situation, to be covered
later).For another example:
public, and contains a public element,
you can write the name of the class in another class, and you can write
the name of the element in that class as well - and if the element is private,
then you can't write its name, so you can't use it.UseBookBasic class code, which has a BookBasic variable b,
can use b.getItemCode() and b.setItemCode(5011),
but not b.itemCode. Note: this does not mean that a private item cannot be affected by
the code in another class; it just can't have its name written in that other
class.
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
Data members are added using an access specifier, a data type keyword, and the field name.
[modifiers] class ClassName {
[modifiers] dataType fieldName1, fieldName2, . . .;
modifiers] dataType fieldName3 = value, . . .;
(etc.)
}
boolean value a 0 bit means false) .null if not given a specific initial value (null is
a keyword). Revisiting our BookBasic example:
class BookBasic {
private int itemCode;
private String title;
. . .
}
itemCode and a reference
to a String object called title.private.Methods may be added in a similar manner. Nnote that in Java, unlike C++, the method body must be defined when the function is declared - you can't postpone that until later.
[modifiers] class ClassName {
[modifiers] dataType fieldName1, fieldName2, . . . ;
[modifiers] dataType fieldName3 = value, . . . ;
[modifiers] returnType methodName(paramType paramName, . . . ) {
[method body code goes here]
}
[more methods here]
Methods may freely access all data and function members of the class.
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
It is considered a good practice to have fields be private,
with access provided by "set and get" methods that are public.
Java has a naming convention that, for a field named value,
there should be methods setValue (accepting a parameter of the
same type as value) and getValue() which would
return a value whose type is the same as value). Note that:
boolean true/false values, the convention
also uses is and has as prefixes for the get
methods (as in isEnabled() for a field called enabled). It is also considered a good practice to reuse existing methods for any
steps that work with data in a way other than simple retrieval. If we had, for example, a method that accepted both itemCode and title,
we would call the setItemCode() and setTitle() methods
rather than access those fields directly. That way if our approach to setting a value changes, the effect is automatically
applied through all methods that do that.
public void setItemCodeTitle (int newItemCode, String newTitle) {
setItemCode(newItemCode);
setTitle(newTitle);
}
There is no requirement that the elements of a class be in any specific order. Any field or method can be accessed from a method, even if the referenced element is declared later. The compiler makes a pass through the code to identify all the elements, and then goes back through the code again armed with that information.
The most common practice is to list fields first, then constructors, then get/set methods, and then all the other methods. (There is a less commonly held belief that fields should be listed last.) Generally the static fields are listed before the non-static ones.
If there are dependencies between fields due to the value of one field being used to initialize another field, then that would impose an order on those fields.
private int range = 100; private Random r = new Random(); private int answer = r.nextInt(range); // answer must come after range and r, // since it depends on them
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
If you follow the standard naming conventions, you are most of the way to creating a Java Bean class. Note that:
String variable containing
the class name.Rectangle class,
for example, with height and width properties that were int,
the tool wouldn't know how to call a constructor that took both parameters
(which is the height and which is the width?). Like this Java tutorial? Try our self-paced online Java courses, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
Properties are defined by public get and set methods, and usually
map to private fields.
public class Rectangle {
private int height;
private int width;
public Rectangle() { }
public int getHeight() {
return height;
}
public void setHeight(int newHeight) {
height = newHeight;
}
public int getWidth() {
return width;
}
public void setWidth(int newWidth) {
width = newWidth;
}
public int getArea() {
return height * width;
}
}
The class has a constructor that takes no parameters, plus methods to get and set the height and width. The area is a read-only property that is not backed by a field - it is calculated each time it is needed.
public class UseRectangle {
public static void main(String[] args) {
Rectangle r = new Rectangle();
r.setHeight(100);
r.setWidth(250);
System.out.println(
"Rectangle of height " + r.getHeight() +
" and width " + r.getWidth() +
" has an area of " + r.getArea());
}
}
This is a simple main class to create and use a Rectangle.
A Java Server Page might use a similar approach to populate the height
and width from values submitted from a form, and send back a page
showing the area.
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
Every class should have at least one method: the constructor. This specifies code that must run to instantiate (usually to initialize) a new object from the class definition.
The constructor is a function with the same name as the class.
[modifiers] class ClassName {
[modifiers] ClassName(paramType paramName, . . . ) {
[code goes here]
}
}
public (but
in some circumstances involving inheritance they are sometimes protected or private). The methods in an object are available at construction time. While a constructor could set field values directly, it is considered a better practice to call the set methods to store any values. That way, any validation necessary on the data can be accomplished without duplicating the validating code.
public class BookWithConstructor {
private int itemCode;
private String title;
public BookWithConstructor(int newItemCode, String newTitle) {
setItemCode(newItemCode);
setTitle(newTitle);
}
public int getItemCode() {
return itemCode;
}
public void setItemCode (int newItemCode) {
if (newItemCode > 0) itemCode = newItemCode;
}
public String getTitle() {
return title;
}
public void setTitle (String newTitle) {
title = newTitle;
}
public void display() {
System.out.println(itemCode + " " + title);
}
}
Note how the constructor can make use of the existing methods.
public class UseBookWithConstructor {
public static void main(String[] args) {
BookWithConstructor b =
new BookWithConstructor(5011, "Fishing Explained");
b.display();
}
}
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
You instantiate an object from a class using the new keyword.
objectReferenceVariable = new ClassName(parameters);
new BookWithConstructor(1234, "Help is on the Way").display(); System.out.println(new Integer(5));
When a new instance is created, the following sequence of events takes place (note that this includes only concepts we have covered thus far; later, we will expand the sequence as we cover additional topics):
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
If you create no constructors at all, you will get a default constructor that accepts no arguments and does nothing (but at least you can use it to instantiate an object).
If you write a constructor that accepts arguments, then you lose the default constructor. Note that:
BookWithConstructor
c = new BookWithConstructor();.Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
Methods can be overloaded to have several versions, all with the same name. Note that:
[modifiers]returnType methodName(paramList) { . . . }
[modifiers]returnType methodName(differentParamList) { . . . }
Constructors are often overloaded, so that an object can be instantiated from different combinations of parameters.
This is an example of polymorphism - the concept that the same name may have several forms. Method overloading produces a functional polymorphism, since the same method name can be used in different ways. While polymorphism is mainly used to describe having one variable that can store different but related types due to inheritance, the concept also applies to overloaded methods at a smaller scale.
The combination of the method name and pattern of types in the parameter list is called the function signature. Within a class, every method and constructor must have a unique signature. Note that the return type is not considered part of the signature.
It is not required to keep the same return type for different versions of
the same method. For example, the Math class has multiple max methods
to determine the maximum of two parameters passed in. As you might expect,
they are:
public static double max(double a, double b) public static float max(float a, float b) public static int max(int a, int b) public static long max(long a, long b)
While technically this is not considered overloading, that is a minor issue of semantics.
Continuing our example:
public class BookMultiConstructor {
private int itemCode;
private String title;
public BookMultiConstructor(int newItemCode, String newTitle) {
setItemCode(newItemCode);
setTitle(newTitle);
}
public BookMultiConstructor(String newTitle) {
setItemCode(0);
setTitle(newTitle);
}
---- C O D E O M I T T E D ----
}
public class UseBookMultiConstructor {
public static void main(String[] args) {
BookMultiConstructor b =
new BookMultiConstructor(5011, "Fishing Explained");
b.display();
// note the immediate call to a method on a new instance
new BookMultiConstructor("Dogs I've Known").display();
}
}
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
this Keyword The this keyword provides a reference to the current
object. It is used to resolve name conflicts.
If you have a method that receives an input parameter String s,
but s is already a member variable String reference.
class X {
String s;
public void setS(String s) {
this.s = s;
}
}
s is a local variable
that will disappear when the function ends.s member field.s by
using the this reference to resolve s as
the one that belongs to this object.The this keyword is also used when the object's code needs to pass a reference to itself to the
outside. Say you are creating MyClass. Some other class, YourClass, has a public method called useMyClass that
needs a reference to a MyClass object; in other words, something
like:
public void useMyClass(MyClass x) { . . . }
Your code for MyClass could do:
YourClass yC = new YourClass(); yC.useMyClass(this);
The this keyword is also used in a constructor function to
call another constructor from the same class.
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
this to Call Another ConstructorAs we have seen, to avoid duplicating code in different functions, any function in a class may call other functions in that class.
this keyword is used instead of the name of the constructor,
then arguments are passed in a normal fashion. The following example uses this to provide the object with
a reference to itself, as well as to chain to another constructor:
public class BookUsingThis {
private int itemCode;
private String title;
public BookUsingThis(int itemCode, String title) {
setItemCode(itemCode);
setTitle(title);
}
public BookUsingThis(String title) {
this(0, title);
}
---- C O D E O M I T T E D ----
}
The constructor that only accepts the title calls the other constructor, passing 0 as the item code. It would also be possible to set up the chain of constructors in the reverse direction, as in:
public BookUsingThis(int itemCode, String title) {
this(title);
setItemCode(itemCode);
}
public BookUsingThis(String title) {
setTitle(title);
}
This approach is good if the default values of the fields (either zero or as set by an initializer) are acceptable - note that the constructor that accepts only title never sets the item code.
public class UseBookUsingThis {
public static void main(String[] args) {
BookUsingThis b = new BookUsingThis(5011, "Fishing Explained");
b.display();
new BookUsingThis("Dogs I've Known").display();
}
}
The second book uses the constructor that accepts only the title. Since
the new operator results in a reference to the book, we
can chain a call to display to that result.
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
static Elements The keyword static states that one and only one of this element
should be available at all times - whether there is one object of the class
instantiated, many objects, or none at all
[modifiers] static dataType fieldName; [modifiers] static returnType methodName(paramType paramName, . . .)
If a data member is static, there is one memory location that
is shared among all instances of a class.
If a method is static and public, then it is
available even when no objects have been instantiated.
static fields, you may want to have methods to work with
those fields. It would make sense that those methods be static as well.Math - they have to be part of
a class, but you wouldn't want to have to instantiate some special object
just to generate a single random number or calculate a cosine.
Random class. static,
since it is not guaranteed that they will exist when the function is called.double x = Math.random(); double y = Math.sqrt(x);
Like this Java tutorial? Try our self-paced online Java courses, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
main MethodNow we can see that main, as a static method,
can be run without any instance of the class. In fact, no instance is created
automatically - the JVM only needs to load the class into memory.
If you create a class that has fields or methods not marked as static,
and try to access them from main, you will get a rather cryptic
error message about a non-static element referenced from a static context.
The problem is that there isn't necessarily an instance of your class in
memory, or there may be more than one. To call a non-static element, you
must first create an instance and access the element for that instance.
The following example draws from the GUI world, where the JFrame class
has a setVisible method that this class inherits. The main method
creates an instance of its own class to display.
import javax.swing.*;
public class MyGUI extends JFrame{
public static void main(String[] args) {
MyGUI gui = new MyGUI();
gui.setVisible(true);
}
}
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
Java takes care of reclaiming memory that is no longer in use.
Your program is not making memory-allocation calls directly to the operating system - the JVM requests a fairly large block at start time, and handles memory allocation from that block. Note that:
When an object is no longer reachable through your code, it becomes subject to garbage collection. Note that:
You can request garbage collection by calling System.gc(). Note that this may not have any effect; it is not guaranteed to run
when you ask - the call is merely a request.
You can specify code to run when an object is collected by writing a finalize() method
in a class. Note that:
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
As you have seen, Java programs may involve a large number of files.
Packages help organize files within a program, as well as to collect objects into groups to improve reusability of code.
A package structure is a tree structure that maps to a folder/directory structure. Note that:
To assign a class to a package, use a package statement as the
first non-blank, non-comment line of code.
Code |
Effect |
|---|---|
package test;
|
Puts this class in the package called |
package test.util;
|
Puts this class in the package called |
The accepted convention is that package names be all lowercase.
Example
package test;
public class XYZ { . . . }
XYZ.java should be in a directory called test that
is located within a directory listed in our CLASSPATH.test.XYZ. When the compiler and JVM look for the files, they will search every CLASSPATH entry
for a directory called test containing XYZ.java (or XYZ.class,
if that is what is needed).
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
The default behavior of the compiler in JDK 1.4 and later is to compile source code in a directory structure into class files in the same structure. Note that:
-d option with javac to put
the class files into a separate, parallel directory structure.
javac -d rootofstructure *.java
rootofstructure. To run an executable Java class that belongs to a package, your command
prompt should be at the directory level that matches the root of
the package structure. You would then treat the class name as packagename.ClassName.
Example - the directory C:\MyProject is the root level of
a package structure, and the main class, XYZ.class, is in the
package called test (therefore test is a subdirectory
of MyProject).
To run XYZ.class, the command line would look like the following:
C:\MyProject>java test.XYZ
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
Once a package structure is created, all classes in it must be referenced with respect to the root of the structure. You have two choices:
Say your directory C:\Bookstore is the root of your project.
UseBookInPackage.java (the main class).types, which contains BookInPackage.java.packageThe BookInPackage class would start like this:
package types;
public class BookInPackage {
. . .
}
The package statement must be the first non-comment, non-blank line in the file.
In UseBookInPackage.java, you could import the entire types package,
or just the class(es) you need
import types.*;
or
import types.BookInPackage;
then
public class UseBookInPackage {
public static void main(String[] args) {
BookInPackage b = new BookInPackage("My Favorite Programs");
. . .
}
}
Or, instead of importing, you could explicitly reference the class by its full name, which precedes the class name with the package structure (using a dot character as the directory separator)
public class UseBookInPackage {
public static void main(String[] args) {
types.BookInPackage b = new types.BookInPackage("My Favorite Programs");
. . .
}
}
This approach is necessary if your program uses two classes with the same
name (such as java.sql.Date and java.util.Date).
All classes in the Java API are in packages. We have not had to deal with
imports to this point because the package java.lang is special - it does
not need to be imported. (This is where System, String,
the numeric wrapper classes like Integer, and a few more generally
useful classes reside.)
The package at the root level is called the default package.
main Class is in a Package If your main class is in a package, then it must be compiled and run from the root of the structure.
For example, say your directory C:\Bookstore is the root of
your project, but it contains no classes.
It contains a subdirectory called bookstore, which contains Bookstore.java (the
main class)
package bookstore; public class Bookstore { . . . }
types directory, the remainder
of the code would be as before - we could import our types.Book class. To compile the program from the C:\Bookstore directory, use
the standard operating system directory separator character:
javac bookstore\Bookstore.java
To run the program, you must be in the C:\Bookstore directory,
use the dot character as the separator character:
java bookstore.Bookstore
Note that the preferred practice is to have no classes in the default package.
static ImportsJava 5 introduced the static import, which enables you to import the static elements of a class. This can be used both for fields (usually constants) and methods. The syntax is:
import static packages.Class.element; import static packages.Class.*;
These will import the specified elements so that they may be used within the current class, not only without the fully qualified package structure, but without even needing the class name.
import static java.lang.Math.*;
public class TestStaticImport {
public static void main(String[] args) {
double sin90 = sin(PI / 2);
double sqrt = sqrt(4);
System.out.println("Sine of 90 degrees is " + sin90);
System.out.println("Square root of 4.0 is " + sqrt);
}
}
We have imported every static element from java.lang.Math,
giving us access to Math.PI, Math.sin(double),
and Math.sqrt(double). Notice that the local variable sqrt does
not conflict with the imported method, since without the parentheses
for the parameter list, we are using the variable, with parentheses we
are calling the method. If we did write a sqrt method in
this class, that method would take precedence over the imported method;
calling sqrt would invoke our local method, and we
would need to qualify the call to sqrt as Math.sqrt in
order to use the Math version.
It is a recommended convention that classes created for external distribution
use a package structure that begins with the creating organization's domain
name in reverse order (for example, there are a few non-standard classes
in the API provided by Sun that are in the com.sun package).
Sun recommends that package names be in all lowercase.
Package access does not necessarily limit you to working in the same directory; you could have the same directory structure from a different root point in the classpath.
Java 5 added a new syntax for variable argument lists, called varargs. This enables you to write methods that take a variable number of arguments, in addition to any fixed arguments, as long as the variable arguments are all of the same type.
type..., as in int...public class Varargs {
public static void showDataOnly(int... values) {
for (int i = 0; i < values.length; i++) {
System.out.println(" " + values[i]);
}
}
public static void showDataWithMessage(String message, int... values) {
System.out.println(message);
showDataOnly(values);
}
public static void main(String[] args) {
System.out.println("Below printed from showDataOnly");
showDataOnly(2, 4, 5, 1, 7);
showDataWithMessage(
"This printed with showDataWithMessage", 2, 4, 5, 1, 7);
showDataWithMessage("No values this time");
int[] data = { 4, 5, 1, 3 };
showDataWithMessage("This time we passed an array", data);
}
}
There are two varargs methods. The first has only the one varargs parameter, values. Within its code, values can be
treated as an array. When we call the method, we can pass it any number of integer values, 0 or more.
The second method takes one String, followed by the varargs parameter. When we call it, we must pass at least the message, and can pass any number
of integers after that. Note that the second method prints the message, and then delegates printing the values to the first method.
In main, we also try another approach, which is to pass an array for the varargs parameter. This also works. Because of this, it is not legal to write a method overloads like myMethod(int[] x) and myMethod(int... x), since they could both be invoked by passing an array, even though the array version could not be invoked by passing a comma-separated list of values!
Console Class from Java 6 The Console class provides an easy way to access the keyboard.
Since not all hardware running Java might actually have a console, or a program
might have been launched using some automated process like a background job
scheduler for which a console would not be available, earlier versions did
not supply this. Starting with Java 6, if a console is available to the JVM,
the System.console() method will return an instance of the Console class, otherwise, it will return null. (Unfortunately, Eclipse is one environment for which a console is not available, due to the way that your programs are launched within it.)
Console Class Methods |
||
|---|---|---|
void
|
flush()
|
Flushes the console and forces any buffered output to be written immediately. |
Console
|
format(String format, Object...args)
|
Writes a formatted string to this console's output stream using the specified format string and arguments. Returns this instance so that method calls may be chained. |
Console
|
printf(String format, Object...args)
|
A convenience method to write a formatted string to this console's output stream using the specified format string and arguments. Returns this instance so that method calls may be chained. |
Reader
|
reader()
|
Retrieves the unique Reader object associated with this
console. |
String
|
readLine()
|
Reads a single line of text from the console. |
String
|
readLine(String format, Object...args)
|
Provides a formatted prompt, then reads a single line of text from the console. |
char[]
|
readPassword()
|
Reads a password or passphrase from the console with echoing disabled. |
char[]
|
readPassword(String format, Object...args)
|
Provides a formatted prompt, then reads a password or passphrase from the console with echoing disabled. |
PrintWriter
|
writer()
|
Retrieves the unique PrintWriter object associated with
this console. |
String and PrintStream MethodsThe format method listed above is also available as a static method in the String class, and, for convenience, in the PrintStream class (of which System.out is an instance). String.format returns the formatted String result, while the PrintStream version prints the formatted result and returns the PrintStream reference for chaining.
PrintStream also has the printf method, which again returns its own reference after printing the output.
The discussion below is a brief overview of formatting strings. The String class documentation of the format method has a link to a full discussion of all the formatting options.
The methods that accept a format string use the varargs (variable
argument list) syntax added in Java 5. The format string contains placeholders,
indicated by the % signs,
at which values will be substituted. The values used will be any additional
parameters you pass to the method as indicated by the Object... parameter.
The percent sign is followed by one or more symbols that determine the type
and format of the output for that value. Format specifiers are of the form:
%[argument_index$][flags][width][.precision]conversion
Where (in order of importance/frequency of use):
d: integer f: floating pointe: floating point in scientific notation s: string b: boolean (using true and false as output strings) tY:a four-digit yearty: a two-digit yeartm: a two digit month numbertB: a full month nametb: a three-letter month name abbreviationtd: a two-digit day of month (with leading zero if necessary) te: a one or two digit day of monthtD: a date formatted as month/day/year (as in 02/05/2010) tr: a time formatted as hours:minutes:seconds AM/PM (as
in 09:05:00 AM) %% prints a single percent sign. %n produces a platform-specific end-of line sequence. Note that many of the controls are locale-specific, so that month names, day names, the use of comma and dot for thousands or decimal separator, etc., will be determined by the machines locale setting.
import java.io.Console;
import java.util.Date;
public class TestConsole {
public static void main(String[] args) {
Console console = System.console();
// using unformatted I/O
String name = console.readLine("What is your name? ");
console.printf("Hello, " + name + "\n\n");
// using formatted I/O
int age = Integer.parseInt(
console.readLine("Tell me %s, how old are you? ", name));
console.printf("Wow, you don't look a day over %d!%n%n", age - 10);
// using formatted date/time
console.printf("Today is %tD%nand it is now %tr%n%n",
new Date(), new Date());
// using argument order indicators
console.printf("Today is %1$tD%nand it is now %1$tr%n%n",
new Date());
}
}
The first output concatenates strings to substitute values. The second uses a formatting string with a series of substitution values instead.
The third output line supplies the same date twice, in order to print two different parts of it, while the fourth output uses the parameter index so that we need only supply the date once.
So, in the formatting method parameter list, String format, Object...args, the format string is the first parameter, and the values to be formatted are the rest. Because their type is Object, they can actually be any type of object. But, how come it accepts primitives like integers? Hold onto that thought for just a while longer, we will cover that later in this lesson.
Java input is very "low-level" - it deals with raw bytes of data, but, we can use classes designed to make input easier.
Also, in general, input is error-prone, requiring our program to handle exceptions,
situations requiring special attention. Even though the keyboard will never
throw an exception, as an instance of input stream, its methods are marked
as throwing IOException.
Since it would be nice to have interactive programs, the following code gives an example of reading data from the keyboard.
import java.io.*;
public class InputTest {
public static void main(String[] args)
throws Exception {
BufferedReader in =
new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter a string");
String s = in.readLine();
System.out.println("Enter an integer");
int i = Integer.parseInt(in.readLine());
System.out.println("Enter a character");
char c = (char) in.read();
System.out.println("s=" + s + " i=" + i + " c=" + c);
}
}
Briefly:
import statement enables you to use classes not in
the default set (in this case the input-related classes) - the API documentation
lists the package for each class.System.in is filtered using
an InputStreamReader, which allows it to recognize input as
text characters (the basic InputStream is plugged into a more
complex object that does additional processing).InputStreamReader is plugged into a BufferedReader that
buffers keyboard input until it recognizes the Enter keystroke.readLine(), and characters can
be read using read() (note that they are read as integers,
thus the typecast).static method
of the Integer class.mainthrow an exception (much more
on exceptions later). The following class, KeyboardReader.java, can be used to read
from the keyboard:
package util;
import java.io.*;
public class KeyboardReader {
private static BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
public KeyboardReader() { }
public static String getPromptedString(String prompt) {
String response = null;
System.out.print(prompt);
try {
response = in.readLine();
} catch (IOException e) {
System.out.println("IOException occurred");
}
return response;
}
public static char getPromptedChar(String prompt) {
return getPromptedString(prompt).charAt(0);
}
public static int getPromptedInt(String prompt) {
return Integer.parseInt(getPromptedString(prompt));
}
public static float getPromptedFloat(String prompt) {
return Float.parseFloat(getPromptedString(prompt));
}
public static double getPromptedDouble(String prompt) {
return Double.parseDouble(getPromptedString(prompt));
}
}
The approach shown above is used in a class with all static elements.
A static BufferedReader is created when the class is loaded,
and used by a set of static methods that retrieve specific
types of data from the keyboard (String, char, int, float,
and double).
The getPromptedString method prints the prompt and retrieves
the String entered in response. It handles the IOException that readLine is
specified as throwing (even though the keyboard can never actually throw
that exception, the methods in the classes involved, like BufferedReader and InputStream (used
behind the scenes), can throw those exceptions when used with other types
of streams, like those coming from files. This is one case where inheritance
can actually get in the way, by adding a bit of complexity as the cost
of having a system that will work for all types of input streams.
Since all keyboard input starts as a String, the methods
to retrieve other types of data reuse getPromptedString,
and then process the result to obtain the required type of data. One
benefit of this approach is that the potential for an exception has been
handled, so we don't have to worry about that again in these methods.
Since many organizations have not yet migrated to Java 6, the remainder
of the demos and exercises use KeyboardReader. (Plus, it
has a few extras that Console does not, like the parsing of numeric values.)
Feel free to modify these to use Console I/O
if you are an a Java 6 environment - you might want to create a revised
KeyboardReader that uses the Console methods, for example.
Like this Java tutorial? Try our self-paced online Java courses, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
String, StringBuffer, and StringBuilderJava has three primary classes for working with text.
The String class is optimized for retrieval of all or part
of the string, but not for modification (it is assumed to be written once
and read many times). Note that:
String object is immutable, that is, its
contents cannot be changed.toUpperCase() that seem like they would change
the contents actually return a brand-new String object with
the new contents. The StringBuffer and StringBuilder classes are
optimized for changes. Note that:
StringBuilder is
not safe for multithreaded applications while StringBuffer is
(but StringBuilder is faster because of that). append(String s) and other forms accepting various primitive
data types and a form that accepts another StringBuffer object.insert(int position, String s) to insert text at (in
front of) the specified position; again, various forms for different
types of data. delete(int start, int end) to delete characters from
the start position up to but not including the end position. toString() will convert the contents of the object to
a String object. this reference, (a reference
to the same object) - this enables chaining of method calls:
StringBuffer sb = new StringBuffer();
sb.append("Hello").append(" World");
System.out.println(sb.toString());Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
Java documentation can be created as part of the source code. If you embed javadoc comments in your code the javadoc documentation engine supplied with the jdk will create a set of interlinked HTML pages, one for each class.
A javadoc comment is a block comment beginning with /**, and
ending with */
<em> and <code> are often
used, as well as lists.@,
such as:
@param documents a method or constructor parameter.@return documents a return value.{@link BookWithJavadoc} creates a hyperlink to the specified
class page.javadoc options filelist
Command line options include:
-d destinationdirectory to produce the output in a specific
directory, which need not already exist (default is current directory). public, package,
and protected elements)
-private
-package
-protected
-public
The file list can use file names, package names, wildcards, like *.java (separate
multiple elements with spaces).
The following command places the output in a subdirectory docs of the current
directory, and documents the "default package" and the employees package
(use this in the upcoming exercise):
javadoc -d docs -private employees *.java
See Sun's How To reference for more information.
/**
* Represents a Book in inventory,with an item code and a price
*/
public class BookWithJavadoc {
/**
* The book's item code
*/
private int itemCode;
/**
* The title of the book
*/
private String title;
/**
* Creates a book instance.
* @param itemCode the book's item code. It is expected
* that the value will be non-negative; a negative value
* will be rejected.
* @param title the title of the book
*/
public BookWithJavadoc(int itemCode, String title) {
setItemCode(itemCode);
setTitle(title);
}
/**
* Creates a book instance, The item code will be set to 0.
* @param title the title of the book
*/
public BookWithJavadoc(String title) {
setItemCode(0);
setTitle(title);
}
/**
* Retrieves the item code for the book.
* @return the book's item code
*/
public int getItemCode() {
return itemCode;
}
/**
* Sets the item code for the book. It is expected that the value will
* be non-negative; a negative value will be rejected.
* @param itemCode the book's item code
*/
public void setItemCode (int itemCode) {
if (itemCode > 0) this.itemCode = itemCode;
}
/**
* Retrieves the title of the book.
* @return the title of the book
*/
public String getTitle() {
return title;
}
/**
* Sets the title of the book.
* @param title the title of the book
*/
public void setTitle (String title) {
this.title = title;
}
public void display() {
System.out.println(itemCode + " " + title);
}
}
Even though some of the documentation will often be trivial, parameters and return values should always be documented. Any restrictions on parameter values, such as the non-negative parameters, should be mentioned.
/**
* Tests the {@link BookWithJavadoc} class.
*/
public class UseBookWithJavadoc {
/**
* Tests the {@link BookWithJavadoc} class.
*/
public static void main(String[] args) {
BookWithJavadoc b = new BookWithJavadoc(5011, "Fishing Explained");
b.display();
}
}
Note the use of the {@link} tag, since nothing else (parameter
or return types) would mention the BookWithJavadoc class
otherwise.
Like this Java tutorial? Try our self-paced online Java course, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
Since it is sometimes useful to treat a primitive value as if it were an object, the API provides a set of wrapper classes that store a primitive value inside an object, and also have useful methods for that type of primitive. Note that:
BigDecimal and BigInteger.Number class
that all this group of classes extend):
public byte byteValue()
public short shortValue()
public int intValue()
public long longValue()
public float floatValue()
public double doubleValue()
Boolean has public boolean booleanValue()Character has public char charValue()Primitive Type |
Storage Size |
Wrapper Class |
Comments |
|---|---|---|---|
boolean
|
1 bit
|
Boolean
|
Not usable mathematically, but can be used with logical and bitwise operators |
char
|
16 bits
|
Character
|
Unsigned, not usable for math without converting to int |
byte
|
8 bits
|
Byte
|
Signed |
short
|
16 bits
|
Short
|
Signed |
int
|
32 bits
|
Integer
|
Signed |
long
|
64 bits
|
Long
|
Signed |
float
|
32 bits
|
Float
|
Signed |
double
|
64 bits
|
Double
|
Signed |
void
|
None
|
||
| N/A | object reference |
BigInteger
|
Can store arbitrarily large or small values - cannot
be used with math operators like +, -, etc.,
but have methods to perform those operations. |
BigDecimal
|
Up through Java 1.4, you were required to explicitly code the construction of a wrapper class object from your primitive value, and to explicitly retrieve the primitive value:
int x = 33; Integer xObj = new Integer(x); // then, later on int y = xObj.intValue();
While you can still take this approach, Java 1.5 added Autoboxing, where the primitive to object conversion and the reverse conversion will occur automatically (the compiler will put in the necessary steps)
int x = 33; Integer xObj = x; // then, later on int y = xObj;
Now, back to the formatting methods and the Object..., parameter.
Because of autoboxing, it can accept primitives, which will be boxed into
wrapper objects. Hence, an int can
now be used as an Object value for the varargs parameter - the compiler will add code to box the int into an Integer, which is then acceptable as the Object expected by the method.
While a useful coding convenience, there are some tricky rules regarding autoboxing when combined with implicit typecasting and method overloading, which are beyond the scope of this course.
Like this Java tutorial? Try our self-paced online Java courses, which includes videos and exercises in addition to the content in this Java tutorial. Not sure if you want to pay for that? Register for a free demo of the course.
This page was last updated on 2013-01-03
All pages and graphics in this Java Tutorial is copyright 2013 and are the property of Webucator, Inc. unless otherwise specified. The purpose of this website is to help you learn Java on your own and use of the website implies your agreement to our Terms of Service.