Java Basic
Last updated
Last updated
This part is mainly the about the Java Basic Knowledge from Y. Daniel Liang's Intro to Java Programming and Data Structures.
This part is too easy so there is not so much to mention.
The Java language specification is a technical definition of the Java programming language's syntax and semantics.
The application program interface (API), also known as library, contains predefined classes and interfaces for developing Java programs.The API is still expanding.
Java SE, Java EE and ME
Java Standard Edition a.k.a Java SE.
Java Enterprise Edition a.k.a Java EE.
Java Micro Edition a.k.a Java ME.
The Java Development Kit (JDK), consists of a set of separate programs, each invoked from a command line, for compiling, running and testing Java programs.
The program for running Java programs is known as JRE (Java Runtime Environment). Instead of using JDK directly, you can use some other development tools (Eclipse etc) that provide an integrated development environment (IDE).
In this book, we will use Java SE 8. And Oracle releases each version of Java SE with a JDK. For Java SE 8, the JDK is called JDK 1.8 (a.k.a Java 8 or JDK 8).
As the name suggests (a simple java program), it's very simple. No need to write anything.
You save a Java programin in a .java file and compile it into a .class file. The .class file is executed by the Java Virtual Machine (JVM)
javac Source.java
In this step, your source code will be compiled into the java bytecode file with a .class
extension. This java bytecode is a low-level language and it is similar to machine instructions but is architecture neutral and can run on any platform that has a Java Virtual Machine (JVM).
java Source.class
Now, you may use the JVM, which is an interpreter to execute the bytecode.
Nothing important.
The plus sign +
can also be a string concatenation operator. e.g.
To read in Java, we can use
Note that .nextDouble()
method can be changed to other types, like .nextInt()
.
3. To name a constant in Java, we can use the keyword final
Note that a constant must be declared and initialized in the same statement.
In Java, there is a boolean
datatype and the boolean variable can be either true
or false
. You cannot regard nonzero value as true and zero as false as you do in C!
In Java, we also have dangling else
ambiguity problem, which is very similar to C. That is the else
clause will always match the most recent unmatched if
clause in the same block.
This code snippet is equivalent the code below:
In Java, we must also pay attention to the equality test of two floating-point values. For example,
In this code snippet, the final output is false
since x actually is 0.50000001
. To avoid this problem, we can set , where is a very small value, to test that whehter x is approximate to 0.5 or not.
The Math
class is very useful. To use that class, you don't need to import. Just use Math.method_name()
to invoke the method you want to use.
In Java, character is always enclosed in single quotation marks ' '
. And string is always enclosed in double quotation marks " "
. And a char in Java takes 2 bytes.
The Character
class is also very useful, it contains some functions help you decide whether a character is uppercase or lowercase etc, which is a bit similar to ctype.h
in C.
In Java, there is a data type called String
so that you can define the string as follows
The string methods can only be invoked from a specific string instance. For example
In Java, ' '
, \t
, \f
, \r
and \n
are called whitespace characters.
To read a string from console, we can use either .next()
or .nextLine()
. The difference is that .next()
will read individual elements seperated by whitespace characters while the .nextLine()
read elements seperated by an entire line only.
Loops in Java are totally the same with C. Nothing to record.
The meaning and use of method in Java is similar to the use of function in C.
A "Call Stack", a.k.a execution stack, runtime stack or machine stack, is often shortened to just "the stack".
In Java, the overloading methods enables you to define the methods with the same name as long as their parameter lists are different. For example,
Due to this property, the compiler will find the method that best matches a method invocation. But the ambiguous invocation may also appear and the compiler will output a compile error if encounters the ambiguous invocation.
Create the array reference variable. This is similar to creating a pointer in C.
Note that when defining the reference variable, there is no need to specify the length of the array.
Create the array. This is similar to allocate memory and then store the starting address of that memory in the pointer variable in C.
We can also combine the step 1 and step 2 together
Things to Note:
When you create an array, the array elements are automatically initialized to zero for numeric types, false for boolean types.
The Initializer must be used in one line.
Java supports a convenient way to iterate through the elements of an array. This is known as the enhanced for loop or the foreach loop. For example,
The e
is the variable that will be assigned to each element of the array in each iteration.
In Java, the array supports variable-length, which means the following is valid.
In Java, when passing an array to a method, the reference of the array is passed to the method. For example:
In this example, we pass an anonymous array to the method printArray()
.
java.util.Array
LibraryIn Java, the java.util.Array
class contains many useful methods, likeing sorting and searching.
In Java, when you pass command-line arguments, these arguements are stored at the String array called args
and you can use args[index]
to access each argument and the index starts from 0.
To create a two-dimensional array using an array initializer, we can use the syntax below
In Object-oriented programming (OOP), an object represents an entity in the real world that can be distinctly identified.
An object hsa a unique identity, state, and behavior.
Identity: The name of the object
State: It's often represented by data fields. For example, a circle object has a data field radius
.
Behavior: The methods of the object. For example, a circle object has methods getArea()
and getPerimeter()
.
Objects of the same type are defined using a common class. An object is an instance of a class. A class is also a data type. You can use it to declare object reference variables.
A Circle
class example
Only one class in the file can be a public class. Furthermore, the public class must have the same name as the file.
Constructors have three peculiarities:
A constructor must have the same name as the class itself.
Constructors do not have a return type -- not even void
.
Constructors are invoked using the new
operator when an object is created. Constructors play the role of initializing objects.
A class may be defined without constructors. In this case, a public no-arg constructor with an empty body is implicitly defined in the class.
In this code,
Circle
is a reference type. myCircle
is an object reference variable which can hold the reference to a Circle
object. new Circle()
creates an object and assigns its reference to myCircle
.
In the class Circle
, the data field radius
is referred to as an instance variable because it is dependent on a specific instance. For the same reason, the method getArea
is referred to as an instance method because you can invoke it only on a specific instance.
Note that we can use Math.methodName(arguments)
to invoke a method in the Math
class because these methods are static methods. But we cannot do the same on our Circle
class.
The difference between variables of Primitive Types and Reference Types
For a variable of a primitive type, the value is of the primitive type.
For a variable of a reference type, the value is a reference to where an object is located.
In Java, the objects that are no longer useful are called garbage, and will be collected automatically by the Java Runtime system.
In the UML diagram, the class name is placed at the top, the data field in the middle, and the methods at the bottom.
In UML diagram, static variables and methods are underlined.
Instance Variables belong to instances and have memory storage independent of one another. Static variables are shared by all the instances of the same class.
To define a static vairable or method, we usually add the keyword static
at the front,
Constants in a class are shared by all objects of the class. Thus, constants should be declared as final static
.
Instance variables and methods are accessed via a reference variable (or basically an initialized object). Static variables and methods can be accessed from a reference variable or from their class name.
However, it is recommended to use ClassName.staticMethod()
to invoke a static method and ClassName.staticVariable
to access a static variable. This improves readability because this makes static methods and data easy to spot.
Instance method:
Can access instance variables and invoke instance methods directly.
Can access static variables and invoke static methods directly.
Static method:
Can access static variables and invoke static methods directly.
Cannot access instance variables or invoke instance methods directly.
However, a static method can access an instance variable or invoke an instance method through an object reference.
Design Guide (To decide whether a variable or a method should be instance or static)
A variable or method that is dependent on a specific instance of the class should be an instance variable or method.
A variable or method that is not dependent on a specific instance of the class should be a static variable or method.
A visibility modifier (public
, private
...) specifies how data fields and methods in a class can be accessed from outside the class. There is no restriction on accessing data fields and methods inside the class.
private: The private modifier restricts access to its defining class, which makes methods and data fields accessible only from within its own class.
default: If you didn't specify public
or private
, it should be the default modifier. It restricts access to the package.
public: The public modifier enables unrestricted access, which means the method or data field can be accessed from any other classes.
To declare data fields as private using private
modifier is known as data field encapsulation. After that, we should provide a getter method or accessor to return its value and a setter method or mutator to set its value. These two methods must be public
.
From now on, all data fields should be declared private, and all constructors and methods should be defined public, unless specified otherwise.
Passing an object is actually passing the reference of the object (which basically is the location of the object in the heap).
Java uses exactly one mode of passing arguments: pass-by-value. When an object is passed to a method, this value passed is a reference to a object.
Objects are stored in a heap. But the variable to store the reference is in the stack.
An array of objects is an array of reference variables.
When an array of objects is created using the new
operator,
each element in the array is a reference variable with a default value of null
. We need to use another loop to create objects for each element in the array using new
operator.
For a class to be immutable, it must meet the following requirements:
All data fields are private.
There can't be any mutator methods for data fields
No accessor methods can return a reference to a data field that is mutable (which means an object can be in the data field).
Instance and static variables in a class are referred to as the class's variables or data fields. A variable defined inside a method is referred to as a local variable.
The scope of a class's variable is the entire class, regardless of where the variables are declared.
If a local variable has the same name as a class's variable, the local variable takes precedence and the class's variable with the same name is hidden.
this
ReferenceThe this
keyword refers to the object itself.
Using this
to Reference Data Fields,
In this code snippet, this.radius
just refers to the radius in the data field. If you use the following,
The first radius
is the parameter since it has higher precedence than the class variable (data field radius). This will be wrong. To summarize, this
keyword gives us a way to reference the object that invokes an instance method.
Using this
to Invoke a Constructor The this
keyword can be used to invoke another constructor of the same class.
In this code snippet, this(1.0)
will invoke the first constructor with a double
argument.
Note that java requires that this(arg-list)
statement appear first in the constructor before any other executable statements.
Using this(arg-list)
can make a constructor with no or fewer arguments invoke a constructor with more arguments, which can simplify coding and make the class easier to read and to maintain.