A Java program can be thought of as a collection of objects that work together by calling each other's methods. The following briefly introduces the concepts of classes, objects, methods and instance variables.
Object : An object is an instance of a class and has state and behavior. For example, a dog is an object. Its status includes: color, name, and breed; its behaviors include: wagging its tail, barking, eating, etc.
Class : A class is a template that describes the behavior and status of a class of objects.
Method : Method is behavior, and a class can have many methods. Logical operations, data modification, and all actions are completed in methods.
Instance variables : Each object has unique instance variables, and the state of the object is determined by the values of these instance variables.
Let's look at a simple Java program that will print the string Hello World
public class MyFirstJavaProgram {
/* The first Java program.
* It will print the string Hello World
*/
public static void main(String []args) {
System.out.println("Hello World"); // Print Hello World
}
}
Here's a step-by-step guide on how to save, compile, and run this program:
Open Notepad and add the above code;
Save the file name as: MyFirstJavaProgram.java;
Open the cmd command window and enter the location of the target file, assuming it is C:
Type javac MyFirstJavaProgram.java in the command line window and press enter to compile the code. If there are no errors in the code, the cmd command prompt will advance to the next line. (Assuming the environment variables are all set).
Then type java MyFirstJavaProgram and press the Enter key to run the program.
You will see Hello World in the window
C :> javac MyFirstJavaProgram.java
C :> java MyFirstJavaProgram
Hello World
When writing Java programs, you should pay attention to the following points:
Case sensitivity : Java is case sensitive, which means that the identifiers Hello and hello are different.
Class Name : For all classes, the first letter of the class name should be capitalized. If the class name consists of several words, the first letter of each word should be capitalized, for example, MyFirstJavaClass.
Method names : All method names should start with a lowercase letter. If the method name contains several words, the first letter of each subsequent word is capitalized.
Source file name : The source file name must be the same as the class name. When saving the file, you should use the class name as the filename (remember Java is case-sensitive) and the filename suffix .java. ( If the file name and class name are different, a compilation error will occur ).
Main method entry : All Java programs start execution from public static void main(String [] args)
method.
All components of Java require names. Class names, variable names, and method names are all called identifiers.
Regarding Java identifiers, there are the following points to note:
All identifiers should start with a letter (AZ or az), dollar sign ($), or underscore (_)
The first character can be followed by any combination of letters (AZ or az), dollar signs ($), underscores (_) or numbers.
Keywords cannot be used as identifiers
Identifiers are case sensitive
Examples of legal identifiers: age, $salary, _value, __1_value
Examples of illegal identifiers: 123abc, -salary
Like other languages, Java can use modifiers to modify methods and properties in classes. There are two main types of modifiers:
Access control modifiers: default, public, protected, private
Non-access control modifiers: final, abstract, static, synchronized and volatile
We will discuss Java modifiers in depth in later chapters.
There are mainly the following types of variables in Java:
local variables
Class variables (static variables)
Member variables (non-static variables)
Arrays are objects stored on the heap and can hold multiple variables of the same type. In later chapters, we will learn how to declare, construct, and initialize an array.
Java 5.0 introduced enumerations, which restrict variables to preset values. Using enumerations can reduce bugs in your code.
For example, we design a program for a juice shop that will limit juice to small, medium, and large cups. That means it doesn't allow customers to order juices other than those three sizes.
class FreshJuice {
enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
FreshJuiceSize size;
}
public class FreshJuiceTest {
public static void main(String args[]){
FreshJuice juice = new FreshJuice();
juice.size = FreshJuice.FreshJuiceSize.MEDIUM;
}
}
Note: Enumerations can be declared individually or inside a class. Methods, variables, and constructors can also be defined in enumerations.
Java reserved words are listed below. These reserved words cannot be used in the names of constants, variables, and any identifiers.
Keywords | describe |
---|---|
abstract | Abstract methods, modifiers of abstract classes |
assert | Assert whether the condition is met |
boolean | Boolean data type |
break | Break out of the loop or label code segment |
byte | 8-bit signed data type |
case | A condition of the switch statement |
catch | Use it with try to capture exception information |
char | 16-bit Unicode character data type |
class | Define class |
const | Not used |
continue | Do not execute the remainder of the loop body |
default | Default branch in switch statement |
do | Loop statement, the loop body will be executed at least once |
double | 64-bit double precision floating point number |
else | The branch executed when the if condition is not true |
enum | enumeration type |
extends | Indicates that one class is a subclass of another class |
final | Indicates that a value cannot be changed after initialization. Indicates that the method cannot be overridden, or that a class cannot have subclasses. |
finally | Designed to complete the execution of code, mainly for the robustness and integrity of the program, the code will be executed regardless of whether an exception occurs. |
float | 32-bit single precision floating point number |
for | for loop statement |
goto | Not used |
if | conditional statement |
implements | Indicates that a class implements the interface |
import | Import class |
instanceof | Test whether an object is an instance of a class |
int | 32-bit integer |
interface | Interface, an abstract type with only definitions of methods and constants |
long | 64-bit integer |
native | Representation methods are implemented in non-java code |
new | Allocate new class instance |
package | A series of related classes form a package |
private | Indicates private fields, methods, etc., which can only be accessed from within the class |
protected | Indicates that the field can only be accessed through the class or its subclasses or other classes in the same package. |
public | Represents common properties or methods |
return | method return value |
short | 16 digits |
static | Represents something defined at the class level and shared by all instances. |
strictfp | Floating point comparisons use strict rules |
super | Represents the base class |
switch | select statement |
synchronized | Represents a block of code that can only be accessed by one thread at a time |
this | Indicates calling the current instance or calling another constructor |
throw | throw an exception |
throws | Define exceptions that may be thrown by a method |
transient | Modify fields not to be serialized |
try | Indicates that the code block needs to handle exceptions or cooperates with finally to indicate that whether an exception is thrown, the code in finally will be executed. |
void | Mark method does not return any value |
volatile | Tag fields may be accessed simultaneously by multiple threads without synchronization |
while | while loop |
Similar to C/C++, Java also supports single-line and multi-line comments. Characters in comments will be ignored by the Java compiler.
public class MyFirstJavaProgram{
/* This is the first Java program *It will print Hello World
* This is an example of a multi-line comment */
public static void main(String []args){
// This is an example of a single line comment /* This is also an example of a single line comment */
System.out.println("Hello World");
}
}
Blank lines, or lines with only comments, are ignored by the Java compiler.
In Java, a class can be derived from other classes. If you are creating a class and there is already a class that has the properties or methods you need, then you can inherit the newly created class from that class.
Using inheritance, you can reuse methods and properties of existing classes without having to rewrite the code. The inherited class is called a super class, and the derived class is called a subclass.
In Java, an interface can be understood as a protocol for communication between objects. Interfaces play a very important role in inheritance.
The interface only defines the methods to be used by the derived class, but the specific implementation of the method completely depends on the derived class.
The next section introduces classes and objects in Java programming. Afterwards you will have a clearer understanding of classes and objects in Java.