Java Basic Concepts

Understanding the basic concepts of Java provides a solid foundation for learning and using the language effectively. It allows you to grasp the core principles and syntax of Java, which are building blocks for more advanced topics.

Object-Oriented Programming (OOP)

Java programming language is designed and built around the principles of Object-Oriented Programming (OOP). In Object-Oriented Programming, objects, which are instances of classes, are used to model and organize code. Everything in Java is treated as an object. Objects represent instances of classes, while classes serve as blueprints or templates for creating these objects. These objects can encapsulate data (attributes) and behavior (methods), and they interact with each other through well-defined interfaces. The key concepts of OOP, such as encapsulation, inheritance, and polymorphism, are fundamental to Java's design.

Java Source Files

Java source files are text files containing the human-readable source code of programs written in the Java programming language. These files typically have a .java file extension. Java source code is written using a syntax that adheres to the rules and conventions of the Java programming language.

Java Bytecode Files

To execute a Java program, it is necessary to compile the source code into bytecode using a Java compiler. The bytecode files are not human-readable have a .class file extension. These files serve as an intermediate representation of the source code. Bytecode can be executed on any system that has a compatible JVM, allowing Java applications to be "write once, run anywhere".

Hello World Program in Java

Let's begin with the "Hello World" program, typically the first program many programmers create in any programming language.

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Here's a breakdown and explanation of the above code:

  • public class MyClass { ... }: This defines a public class named MyClass. In Java, every program starts with a class definition.
  • public static void main(String[] args) { ... }: This is the main method where the execution of the program starts. It's a requirement for Java applications.
  • System.out.println("Hello, World!");: This line prints the text "Hello, World!" to the console. The System.out.println method is used to output data.

The Main Method

The main method is a special method that serves as the entry point for a Java application. It is the starting point from which the Java Virtual Machine (JVM) begins to execute a Java program.

The main method must have the following signature:

public static void main(String[] args){}

Let's break down the parts of the main method signature:

  • public: It specifies that the method can be accessed from anywhere in the program.
  • static: It indicates that the main method belongs to the class itself rather than an instance of the class. This allows the JVM to call the main method without creating an object of the class.
  • void: It indicates that the method does not return any value.
  • main: It is the name of the method. The JVM looks for a method with this name to start the execution of the program.
  • string [] args: This is the parameter of the main method. It is an array of strings that allows you to pass command-line arguments to your program.
  • { }: This signifies the body of the method. It is where the specific instructions and operations for the function are written. It encapsulates the set of statements defining the functionality of the method.

Methods

In Java, a method is a set of instructions written to perform a specific task. It is defined within a class and can contain any number of statements. The method is executed when it is called. Methods help you to organize code into logical units, where each unit has a distinct purpose or responsibility. Methods are designed to enhance code modularity, meaning the breaking down of a program into smaller, self-contained units. This makes the code easier to read and understand, maintainable, and reusable. Additionally, it improves the organization of the code, reduces redundancy, and makes it easier to identify and resolve issues.

Modifiers

A modifier in Java, modifies the properties of classes, constructors, methods or variables. There are two types of modifiers in Java:

  1. Access Modifiers: The access modifiers are used to restrict the scope of a class, constructor, method, variable or data member. There are four types of access modifiers in Java. They are the default, private, protected, and public. Here is an example of a method with a public access modifier which can be accessed from anywhere in the program:
  2. public int subtract(int a, int b) {
        int remaining = a - b;
        return remaining;
    }
  3. Non-access Modifiers: Java provides a group of non-access modifiers such as final, static, abstract, volatile, transient, synchronized, etc. The use of non-access modifiers gives special properties to variables, methods, and classes. However, they do not change the accessibility of variables, methods, and classes. Here is an example of a class and a method with the abstract non-access modifier:
  4. public abstract class Car {
       public abstract double speed();
    }

Semicolon

In Java, a semicolon is used to separate statements and therefore, every statement must end with a semicolon (;).

private String message = "Hello! how are you?";
System.out.println("Message = " + message);

Java is case-sensitive

Java is case-sensitive, which means it distinguishes between uppercase and lowercase letters when using identifiers such as variable names, method names, class names, and object names. Here are a few examples to demonstrate case sensitivity in Java:

Example 1:

int amount = 70;
int Amount = 90;

In this example, count and Count are two different variables.

Example 2:

public void displayMessage() {
   System.out.println("Hello world!");
}

public void DisplayMessage() {
   System.out.println("Hello Universe!");
}

In this example, we have two methods with the same name but different cases. Java treats them as separate methods.

Example 3:

public class Banktransaction {

}

public class BankTransaction {

}

In this example, we have two classes with the same name but different cases. Java treats the as separate classes.

Comments

In Java, comments are statements ignored by the compiler and interpreter. They help to understand the code better. Comments provide explanatory notes or information about the code, making it more readable and maintainable. In Java, there are two types of comments:

  1. Single-Line Comments: It starts with a double forward slash //.
  2. Multi-Line Comments: It starts with /* and ends with */.

Example:

public class CommentsExample {

  // This is a single line comment.

  /*
   *This is a multiline comment.
   *Compiler ignores this section of the code.
   */

}

Identifiers

An identifier is the name used for identifying a package, class, interface, method, or variable in the code. An identifier in Java is case-sensitive. A standard naming conventions should be followed when selecting names. An identifier can only include letters, numbers, the underscore _ and the dollar sign $. Identifiers must always begin with a letter, the underscore or a dollar sign.

An identifier should be named in such a way that makes their purpose obvious. Here is an example of some variables that hold the name, profession, and department of an employee:

//The class name Employee is identifier here
public class Employee {

  //The name, profession, and department is identifier here
  String name = "Peter";
  String profession = "programmer";
  String department = "IT";

  //This is a method where main is identifier here
  public static void main(String args []) {
    System.out.printf("My name is %s. I am a %s. My department is %.",
    name, profession, department);
   }
}

The output of the above code will be the following:

My name is Peter. I am a programmer. My department is IT.

Variables and Data Types

In Java, a variable is a name that acts as a container for storing a data value in a program, allowing your program to store and manipulate data dynamically. Each variable in Java is of a specific data type, and these data types specify the kind of data a variable can hold. Java supports various data types such as int, double, char, boolean, and more. Understanding how to declare and manipulate variables is essential for writing dynamic and flexible Java code.

Here are some examples of variables and data types in Java:

int age = 28; 
double salary = 75000.20;
char grade = 'A'; 
boolean isDeleted = true; 
String firstName = "John";

In this example, int, double, char, boolean, and String represent data types in Java, specifying the kind of data variables can hold. age, salary, grade, isDeleted, and firstName are variable names assigned to store values, such as 28 for the int type, indicating an age value. Similarly, 75000.20 is assigned to salary, 'A' to grade, true to isDeleted, and "John" to firstName, aligning with their respective data types.

Keywords

Keywords are reserved words which have predefined functions in Java. Keywords cannot be used as names for classes, variables, methods, or as any other identifier. There are around 57 reserved words in Java.

Here is the list of keywords available for use in Java:

abstract
assert
boolean
break
byte
case
catch
char
class
continue
default
do
double
else
enum
exports
extends
final
finally
float
for
if
implements
import
instanceof
int
interface
long
module
native
new
package
private
protected
public
requires
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while