Skip to main content

Command Palette

Search for a command to run...

Introduction to Java: Essential Fundamentals Explained

Published
8 min read
Introduction to Java: Essential Fundamentals Explained
Z

I'm GRIR Zouhair, a dedicated and experienced Full-Stack Developer from Morocco. With a strong passion for coding and a knack for solving complex problems, I excel in creating robust and scalable web applications. My expertise spans across both front-end and back-end technologies, allowing me to deliver comprehensive and seamless solutions.

Hello my name is zouhair, i believe there is no a single methodology for everyone to get start learning something so i would share with you my knowledge for learning java as blog, this devide my spesification into 3 parts which is : Java Fundamentals - Object-Oriented-Programming - Advanced Topics

1️⃣ Getting Started

  1. 💡
    What is, JDK , JRE and JVM and how Java get executed?

    JDK (Java Development Kit) is a software development environment that contains all the necessary tools for developing Java applications. The JDK compiles the code into bytecode, and the JRE (Java Runtime Environment) provides the JVM (Java Virtual Machine), which reads and executes the bytecode.

  2. 💡
    What is Anatomy of java program?

    Functions are called methods, and they must specify a data type like void, String, int, or boolean, followed by a descriptive name and parameters in parentheses. Every Java program must have a main method as the entry point, and this method (like all others) must be inside a class, since methods in Java belong to classes. Access modifiers like public or private control visibility. Java uses PascalCase for class names and camelCase for method names. Let’s code our first “Hello World!!!”.

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

2️⃣ fundamentals programming

  1. 💡
    what is a variable and constant and the diff between them?

    In Java, a variable is like a named box that stores a value. To create a variable, you need 5 elements: Data type (like int, String, boolean), Variable name (current example “box”), the assignment operator (=), the value 10, and finally a semicolon (;) to end the statement.

             int      box = 10;
             final    int pi = 3.14;
    

    A constant is similar, but its value must be initialized immediately and cannot be changed later. We declare it by the reserved word final.

  2. 💡
    what is the diff between Premetives and Reference Type?

    👉 Premetive types used to store a simple value for example :

     public class Main{
         public static void main(String[] args){
             byte       byteVariable = 10; // 1 byte
             short      shortVariable = 100; // 2 bytes
             int        integerVariable = 1000 // 4 bytes
             long       longVariable = 3_123_456_789L// 8 bytes
             float      floatVariable = 10.99F // 4 bytes
             double     doubleVariable = 10.99 // 8 bytes
             char       charVariable = 'Z'; // 2 bytes
             boolean    booleanVariable = true // 1 byte
         }
     }
    

    You can get a compilation error when using long or float types with large or decimal values, but you can fix it by adding the suffix L for long and F for float.

    👉 reference type used to store complex types, so the premetive types is no need to allocate memory for this variable instead of references that need to allocate memory and released by Garbage Collectore is a part of JVM

     public class Main{
         public static void main(String[] args){
            Date now = new Date(); //Date() → the constructor used to make a new object from that class
         }
     }
    

    👉 The Date class exists inside a package called java.util. The purpose of packages is to create a namespace for organizing classes.

    👉 We created a variable named now and used the new keyword to allocate memory and instantiate the Date class. So, now is an object (or instance) of the Date class.

    👉 In Java, a class defines a template or blueprint for creating objects, and an object is a specific instance of that class.
    👉 constructor in Java is a special method used to create and initialize an object.

  3. 💡
    how memory allocation works?

    We’ll create a reference type object Point that holds the values (1, 1). Then, we assign it to two variables, ptr1 and ptr2. After that, we change the values and observe what happens:

    The JVM will allocate memory to store the Point object let’s say the address of that memory is 100. Then, separate memory is allocated to store a reference (a pointer) to that address.

    This is the main difference between primitive types and reference types:

    • Primitive types store the actual value.

    • Reference types store the memory address of the object.

So in this example, both ptr1 and ptr2 point to the exact same Point object in memory.

    public class Main{
        public static void main(String[] args){
            Point ptr1 = new Point(1, 1); //Point(1, 1) is calling a constructor of the Point class.
            Point ptr2 = ptr1;
            System.out.println(ptr2); // java.awt.Point[x=1,y=1]
            ptr1.x = 4;
            ptr2.y = 8;
            System.out.println(ptr2); // java.awt.Point[x=4,y=8]
        }
    }
  1. 💡
    how can we use string and array?

    👉 string are a references type we create it and print our first hello world!!! like this :

String message = new String("Hello World!!!");

but this method may give you a warning of string redundant because in java there is an shorter way to initialize a stirng variable :

String message = "Hello World!!!";

i encourage you to manipulate the string by some methods like length() indexOf(“e“) trim() toUpperCase() , note that any method that modify string will always return new string object.

Escape sequences are special characters used to represent things like new lines (\n), tabs (\t), or quotes (\”) inside strings BackSlash (\) They start with a backslash \ .

  • 👉 arrays are also refrence type there is 2 method to declare it :

      //int[] numbers = {4, 9, 1} // First method
      int[] numbers = new int[2]; // Second method
      numbers[0] = 1;
      numbers[1] = 2;
      Array.sort(numbers);
      System.out.printlen(Array.toString(numbers));
    

    Arrays is a classes defined in java.util packages that allow us to use the toString() or sort() methods.

    how about if we wanna creata 2 demention array 2 row and 3 columns

      int[][] numbers = {{1,2,3}, {4,5,6}}; // First method
      //int[][] numbers = new int[2][3]; // Second method
      numbers[0][0] = 1;
      System.out.printlen(Array.deepToString(numbers));
    
    1. how can we cast?
  • 👉 Casting is taking the data type of a variable and changing it into another data type. So now, we must know the difference between 2 kinds of casting: implicit casting and explicit casting.

    • Implicit casting: Automatic conversion from a smaller to a larger type (like : int to double).

    • Explicit casting: Manual conversion from a larger to a smaller type, and it's done using cast syntax like this: (type) value (like (int) 9.7 becomes 9).

//implicit casting
short x = 1;
int y = x + 2; // output : 3
//explicit casting
double x = 1.1;
int y = (int)x + 2; // output : 3
// another explicit casting
String x = "1";
int y = Integer.ParseInt(x) + 2;
System.out.println(y);
  1. How can we read user input in Java?

    if you wanna read a user input you should use Scanner class define in (java.util) package

import java.util.Scanner;
Scanner scanner = new Scanner(System.in)

👉in System.in refere into System class has a field named in that make that reading input form a user. a field is a variable defined inside a class

scanner object has a bunch of methods to read and all them get start by next here is an example:

Scanner scanner = new Scanner(System.in); // Example 1
        System.out.print("enter you're age = ");
        byte age = scanner.nextByte();
        System.out.println("Your Age is = " + age);
         //Example 2
        System.out.print("enter you're full name = ");
        String name = scanner.nextLine().trim();
        System.out.println("Your Age is = " + name);

3️⃣ Control Flow

  1. what is comparison and logical operators ?

    👉 we use compare operators to compare the premetives values likes: == != >= <=
    👉 we use the logical operators represented by (&& refere into and) (|| refere into or)
    here is an example:

int x = 1;
int y = 1;
int temperature = 22;
boolean isWarm = temperature > 20 && temperature < 30
System.out.println(x == y) // boolean value : True
System.out.println(isWarm) // boolean value : True
  1. How do we deal with conditions in Java?

    Conditions are used to make decisions in code. Besides the traditional if-else statements

int number = 10;

if (number > 0) {
    System.out.println("Positive number");
} else if (number < 0) {
    System.out.println("Negative number");
} else {
    System.out.println("Zero");
}

👉Ternary operator – a shorthand way to write simple if-else statements:

int age = 18;
String result = (age >= 18) ? "Adult" : "Minor";

👉Switch case – used to check a variable against multiple possible values:

int day = 3;
switch (day) {
    case 1: System.out.println("Monday"); break;
    case 2: System.out.println("Tuesday"); break;
    default: System.out.println("Other day");
}
  1. How do we deal with loops in Java?

    Loops in Java are used to repeatedly execute a block of code as long as a specified condition is true. There are 4 different types of loops:

    👉for loop: Used when the number of iterations is known in advance.

// for loop
for (int i = 0; i <= 2; i++)
            System.out.println("Hello World!!");

👉while loop: Used when the number of iterations is not known, and the loop runs while a condition is true.

// while loop
Scanner scanner = new Scanner(System.in);
String input = "";
        while (true)
        {
            System.out.println("Input : ");
            input = scanner.next().toLowerCase();
            if (input.equals("pass"))
                    continue;
            if (input.equals("quit"))
                break;
            System.out.println(input);
        }

👉do-while loop: Similar to the while loop, but guarantees at least one iteration, even if the condition is false initially.

// do while loop
Scanner scanner = new Scanner(System.in);
String input = "";

do {
    System.out.println("Input: ");
    input = scanner.next().toLowerCase();
    if (input.equals("pass"))
        continue;
    if (input.equals("quit"))
        break;
    System.out.println(input);
} while (true);

👉for-each loop: Used to iterate over elements in an array or collection, and simplifies working with data structures.

//for each loop
String[] Fruits = {"Watermelon", "Ornag", "Lemon"};
        for (String Fruit : Fruits)
             System.out.println(Fruit);