Java Basic Syntax
A Java program can be considered as a collection of objects that work together by invoking each other's methods. Below is a brief introduction to 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 with states like color, name, breed, and behaviors like wagging its tail, barking, and eating.
Class: A class is a blueprint that describes the behavior and state of a class of objects.
Method: A method is a behavior, and a class can have many methods. Logical operations, data manipulation, and all actions are completed within methods.
Instance Variable: Each object has unique instance variables, and the state of the object is determined by the values of these instance variables.
First Java Program
Here is a simple Java program that will output the string Hello World.
Example
public class HelloWorld {
/* First Java program
* It will output the string Hello World
*/
public static void main(String[] args) {
System.out.println("Hello World"); // Output Hello World
}
}
Below are the steps to save, compile, and run this program:
Open a code editor and add the above code.
Save the file with the name: HelloWorld.java.
Open a cmd command window and navigate to the location of the target file, assuming it's C:.
In the command line window, type
javac HelloWorld.java
and press Enter to compile the code. If there are no errors, the cmd command prompt will move to the next line (assuming the environment variables are set).Type
java HelloWorld
and press Enter to run the program.
You will see "Hello World" in the window.
$ javac HelloWorld.java
$ java HelloWorld
Hello World
If you encounter encoding issues, you can use the -encoding
option to compile with utf-8:
javac -encoding UTF-8 HelloWorld.java
java HelloWorld
Gif demonstration:
Basic Syntax
When writing Java programs, keep the following points in mind:
Case Sensitivity: Java is case-sensitive, which means identifiers Hello and hello are different.
Class Names: For all classes, the first letter of the class name should be capitalized. If the class name consists of multiple words, each word's first letter should be capitalized, for example, MyFirstJavaClass.
Method Names: All method names should start with a lowercase letter. If the method name contains multiple words, the first letter of each subsequent word should be 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 file name (remember Java is case-sensitive), and the file name extension should be .java. (If the file name and class name are not the same, a compilation error will occur).
Main Method Entry: All Java programs start execution from the public static void main(String[] args) method.
Java Identifiers
All components of Java require names. Class names, variable names, and method names are all called identifiers.
Regarding Java identifiers, note the following:
All identifiers should start with a letter (A-Z or a-z), a dollar sign ($), or an underscore (_).
After the first character, you can use letters (A-Z or a-z), dollar signs ($), underscores (_), or digits in any combination.
Keywords cannot be used as identifiers.
Identifiers are case-sensitive.
Valid identifier examples: age, $salary, _value, __1_value.
Invalid identifier examples: 123abc, -salary.
Java Modifiers
Like other languages, Java uses modifiers to modify methods and properties in classes. There are two types of modifiers:
Access Control Modifiers: default, public, protected, private.
Non-Access Control Modifiers: final, abstract, static, synchronized.
We will delve deeper into Java modifiers in later chapters.
Java Variables
Local Variables
Class Variables (Static Variables)
Member Variables (Non-Static Variables)
Java Arrays
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 arrays.
Java Enums
Java 5.0 introduced enums, which restrict variables to predefined values. Using enums can reduce bugs in the code.
For example, we are designing a program for a juice shop, which limits juice sizes to small, medium, and large. This means customers cannot order juice sizes outside of these three options.
Example
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: Enums can be declared separately or inside a class. Methods, variables, and constructors can also be defined within enums.
Java Keywords
Below is a list of Java keywords. These reserved words cannot be used as constants, variables, or any identifier names.
Category | Keyword | Description |
---|---|---|
Access Control | private | Private |
protected | Protected | |
public | Public | |
default | Default | |
Class, Method, and Variable Modifiers | abstract | Abstract |
class | Class | |
extends | Extends, Inheritance | |
final | Final, Immutable | |
implements | Implements (Interface) | |
interface | Interface | |
native | Native, Native Method (Non-Java Implementation) | |
new | New, Create | |
static | Static | |
strictfp | Strict, Precise | |
synchronized | Thread, Synchronized | |
transient | Transient | |
volatile | Volatile | |
Program Control Statements | break | Break Loop |
case | Define a Value for Switch Selection | |
continue | Continue | |
do | Run | |
else | Otherwise | |
for | Loop | |
if | If | |
instanceof | Instance | |
return | Return | |
switch | Select Based on Value | |
while | Loop | |
Error Handling | assert | Assert Expression is True |
catch | Catch Exception | |
finally | Execute Regardless of Exceptions | |
throw | Throw an Exception Object | |
throws | Declare an Exception May Be Thrown | |
try | Catch Exception | |
Package Related | import | Import |
package | Package | |
Basic Types | boolean | Boolean |
byte | Byte | |
char | Character | |
double | Double Precision Floating Point | |
float | Single Precision Floating Point | |
int | Integer | |
long | Long Integer | |
short | Short Integer | |
Variable Reference | super | Superclass, Super |
this | This Class | |
void | No Return Value | |
Reserved Keywords | goto | Keyword, But Cannot Be Used |
const | Keyword, But Cannot Be Used |
Note: Java's null is not a keyword, similar to true and false, it is a literal constant and cannot be used as an identifier.
Java Comments
Similar to C/C++, Java also supports single-line and multi-line comments. Characters within the comment are ignored by the Java compiler.
public class HelloWorld {
/* This is the first Java program
* It will output 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");
}
}
Java Blank Lines
Blank lines or lines with comments are ignored by the Java compiler.
Inheritance
In Java, a class can be derived from other classes. If you want to create a class and there already exists a class with the properties or methods you need, you can make the new class inherit from that class.
By using inheritance, you can reuse the methods and properties of an existing class without rewriting the code. The class being inherited from is called the superclass, and the derived class is called the subclass.
Interface
In Java, an interface can be understood as a protocol for communication between objects. Interfaces play a significant role in inheritance.
An interface only defines the methods that the derived class needs to use, but the actual implementation of the methods is left to the derived class.
Java Source Program vs. Compiled Execution
As shown in the diagram: ``` The next section introduces classes and objects in Java programming. Afterward, you will have a clearer understanding of classes and objects in Java.