Exploring the Core of Java: A Comprehensive Guide ( PART - 1 )

Introduction:

Java, a programming language known for its portability, versatility, and robustness, has been a cornerstone in the world of software development for decades. At the heart of Java lies "Core Java" – the foundational elements that form the basis of the language. In this blog post, we'll take a deep dive into Core Java, exploring its key features, significance, and how it continues to be a driving force behind countless applications.

Key Features of Core Java:

  1. Platform Independence:

    1. Achieved through the "Write Once, Run Anywhere" (WORA) philosophy.

    2. Code written in Core Java can run on any Java-enabled platform without modifications.

  2. Object-Oriented Programming (OOP):

    1. Deeply rooted in OOP principles.

    2. Supports encapsulation, inheritance, and polymorphism.

    3. Facilitates modular, reusable, and maintainable code design.

  3. Java Standard Edition (Java SE) Libraries:

    1. Inclusion of rich Java SE libraries.

    2. Provides essential functionalities for I/O operations, networking, collections, etc.

    3. Simplifies common programming tasks and encourages code reuse.

  4. Multithreading:

    1. Crucial support for multithreading.Enables concurrent execution of multiple threads.

    2. Enhances responsiveness and efficiency through parallel processing.

  5. Exception Handling:

    1. Vital mechanism for gracefully handling errors and exceptions.

    2. Improves the reliability and robustness of Java applications.

First Java Program - Hello World in Java:

Let's start at the beginning with the traditional "Hello World" program. This simple example introduces you to the basic syntax and structure of a Java program. We'll letter discuss the main method, class declaration, and how to compile and run your first Java application.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
//save with .java extension

class keyword is used to declare a class in Java.

public keyword is an access modifier that represents visibility. It means it is visible to all.

static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method.

main() method is executed by the JVM, so it doesn't require creating an object to invoke the main() method. So, it saves memory.

void is the return type of the method. It means it doesn't return any value. o main represents the starting point of the program.

String[] args or String args[] is used for command line argument.

System.out.println() is used to print statements. Here, System is a class, out is an object of the PrintStream class, println() is a method of the PrintStream class.

What happens at runtime?

  1. Compilation: Java code is compiled into bytecode.

  2. JVM: Bytecode is executed by the Java Virtual Machine.

  3. Class Loading: Bytecode is loaded into memory.

  4. Execution: The program starts running, beginning with the main method.

  5. Memory Allocation: JVM allocates memory for objects and variables.

  6. Exception Handling: Exception handling manages errors during runtime.

  7. Multithreading: Support for concurrent execution of threads.

  8. Dynamic Linking/Loading: Classes can be loaded dynamically.

  9. Reflection: The program can examine/modify its structure at runtime.

  10. Termination: The program completes tasks or exits due to an error.

Q. Is it possible to save a Java source file with a filename different from the class name?

Yes, if the class is not public.

Q. Can you have multiple classes in a java source file?

Yes, like the figure given below illustrates:

Difference between JDK, JRE, and JVM:

JDK (Java Development Kit): The JDK is a software development kit that provides tools and libraries necessary for developing Java applications. It includes the JRE (Java Runtime Environment), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other development tools. The JDK is intended for developers who need to compile and run Java programs. It includes the JRE and additional tools to facilitate the development process.

JRE (Java Runtime Environment): The JRE is a subset of the JDK and is used for running Java applications. It includes the Java Virtual Machine (JVM), which is responsible for executing Java bytecode, as well as core libraries and components required for running Java applications. The JRE does not contain development tools like compilers and debuggers; it is designed for end-users who only need to run Java applications.

JVM (Java Virtual Machine): The JVM is a virtual machine that provides an execution environment for Java bytecode. It abstracts the underlying hardware and operating system, allowing Java programs to be platform-independent. The JVM interprets or compiles Java bytecode into native machine code at runtime. It is an integral part of both the JDK and the JRE. The JVM manages memory, provides runtime services, and ensures the portability of Java applications.

Variables and Data Types:

In Java, a VARIABLE is a container or a storage location in memory that holds a value. Variables are used to store and manipulate data in a program. In Java, variables must be declared before they are used, specifying the variable's type and name.

int age = 25; // declares and initializes the 'age' variable with the value 25

There are three types of variables in Java: local, instance, and static.

  1. Local Variable A variable declared inside the body of the method is called a local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. A local variable cannot be defined with a "static" keyword.

  2. Instance Variable A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.

  3. Static variable A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class.

DATA TYPES: Java is a statically typed language, meaning you must declare the data type of a variable before using it. We'll explore the various primitive data types (int, float, char, boolean) and how to declare and initialize variables.

// Primitive Data Types
byte age = 25;
short distance = 10000;
int population = 1000000;
long largeNumber = 123579012345L; //Note: Use 'L' to denote a long literal

float temperature = 98.6f; // Note: Use 'f' to denote a float literal
double price = 99.99;

char grade = 'A';

boolean isJavaFun = true;

// Reference Data Types
String greeting = "Hello, Java!";
int[] numbers = {1, 2, 3, 4, 5}; // Array of integers

Operators in Java:

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

1) Arithmetic Operators:

  • Addition (+): Adds two values.

    • int sum = 5 + 3; // sum is 8
  • Subtraction (-): Subtracts the right operand from the left operand.

    • int difference = 7 - 4; // difference is 3
  • Multiplication (*): Multiplies two values.

    • int product = 2 * 6; // product is 12
  • Division (/): Divides the left operand by the right operand.

    • double quotient = 8.0 / 2.0; // quotient is 4.0
  • Modulus (%): Returns the remainder of the division.

    • int remainder = 9 % 4; // remainder is 1

2) Relational Operators:

  • Equal to (==): Checks if two values are equal.

    • boolean isEqual = (5 == 5); // isEqual is true
  • Not equal to (!=): Checks if two values are not equal.

    • boolean isNotEqual = (3 != 7); // isNotEqual is true
  • Greater than (>): Checks if the left operand is greater than the right operand.

    • boolean isGreaterThan = (10 > 6); // isGreaterThan is true
  • Less than (<): Checks if the left operand is less than the right operand.

    • boolean isLessThan = (2 < 5); // islessthan is true
  • Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right operand.

    • boolean isGreaterOrEqual = (8 >= 8); // isGreaterOrEqual is true
  • Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.

    • boolean isLessOrEqual = (4 <= 4); // isLessOrEqual is true

3. Logical Operators:

  • Logical AND (&&): Returns true if both conditions are true.

    • boolean bothTrue = (true && true); // bothTrue is true
  • Logical OR (||): Returns true if at least one condition is true.

    • boolean eitherTrue = (true || false); // eitherTrue is true
  • Logical NOT (!): Returns true if the condition is false, and vice versa.

    • boolean notTrue = !true; // notTrue is false

4. Assignment Operators:

  • Assignment (=): Assigns the value on the right to the variable on the left.

    • int x = 10; // assigns the value 10 to variable x
  • Compound Assignment (+=, -=, *=, /=, %=): Operates and assigns the result to the variable.

    • int y = 5; y += 3; // equivalent to y = y + 3; // y is now 8

5. Unary Operators:

  • Unary Plus (+): Represents positive values (rarely used).

    • int positiveValue = +5; // positiveValue is 5
  • Unary Minus (-): Represents negative values.

    • int negativeValue = -7; // negativeValue is -7
  • Increment (++): Increases the value of a variable by 1.

    • int count = 3; count++; // equivalent to count = count + 1; // count is now 4
  • Decrement (--): Decreases the value of a variable by 1.

    • int score = 9; score--; // equivalent to score = score - 1; // score is now 8

6. Bitwise Operators:

  • Bitwise AND (&):

    • This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of input values, i.e., if both bits are 1, it gives 1, else it shows 0.

        int a = 5;                       // binary: 0000 0101
        int b = 3;                       // binary: 0000 0011
        int result = a & b; // result is 1, binary: 0000 0001
        //explanation 
        Bitwise AND Operation of 5 and 3
          0101
        & 0011
         ________
          0001  = 1 (In decimal)
      
  • Bitwise OR (|):

    • This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e., if either of the bits is 1, it gives 1, else it shows 0.

        int a = 5;                       // binary: 0000 0101
        int b = 7;                       // binary: 0000 0111
        int result = a | b; // result is 7, binary: 0000 0111
        //explanation 
        Bitwise OR Operation of 5 and 7
          0101
        | 0111
         ________
          0111  = 7 (In decimal)
      
  • Bitwise XOR (^):

    • This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input values, i.e., if corresponding bits are different, it gives 1, else it shows 0.

        int a = 5;                       // binary: 0000 0101
        int b = 7;                       // binary: 0000 0111
        int result = a ^ b; // result is 2, binary: 0000 0010
        //explanation 
        Bitwise XOR Operation of 5 and 7
          0101
        ^ 0111
         ________
          0010  = 2 (In decimal)
      

7. Shift Operators:

  • Signed Left Shift ( << )

    • The left shift operator moves all bits by a given number of bits to the left.

        int a = 5;                       // binary: 0000 0101
        int b = 3;                       // binary: 0000 0011
        int result = a << b; // result is 40, binary: 0000 0001
        //explanation 
        5 << 3 is
        5 = 00000101
        Three to the left = 00000101 -> 00101___
        Fill in the 0s    = 00101000
        Convert to decimal = 40
      
  • Signed Right Shift ( >> )

    • The right shift operator moves all bits by a given number of bits to the right.

        int a = 20;              
        int b = 2;             
        int result = a >> b; // result is 5
        //explanation 
        20 >> 2 is
        20 = 00010100
        Two to the right  = 00010100 -> __000101
        Fill in the 0s    = 00000101
        Convert to decimal = 5
      
  • Unsigned Right Shift ( >>> )

  • It is the same as the signed right shift, but the vacant leftmost position is filled with 0 instead of the sign bit.

      int a = -88;              
      int b = 2;             
      int result = a >>> b; // result is 42
      //explanation 
      -88 >>> 2 is
      -88 = 10101000
      Two to the right  = 10101000 -> __101010
      Fill in the 0s    = 00101010
      Convert to decimal = 42
    

8. Ternary Operator (? :):

  • The ternary operator is a shorthand way to write an if-else statement in a single line.

      int x = 10;
      int y = 5;
      int result = (x > y) ? x : y;
      // If x is greater than y, result is assigned the value of x, 
      //otherwise, it's assigned the value of y.
    

Java Keywords

In Java, keywords are reserved words that have a specific meaning and functionality within the language. These words cannot be used as identifiers (such as variable names or method names) because they are reserved for specific purposes. Here is a list of Java keywords as of my knowledge cutoff in January 2022:

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

Note:

  • Some keywords like goto and const are reserved for potential future use and are not currently used in the language.

  • enum was introduced in Java 5 to define enumerated types.

  • assert became a keyword in Java 1.4 for assertions.

  • strictfp is used to restrict floating-point calculations to ensure portability across different platforms.

Keep in mind that the list may be updated with newer Java versions, and it's always a good practice to refer to the official Java documentation for the most up-to-date information.

Control Flow Statements:

Control flow statements in Java are used to manage the order in which statements are executed in a program. These statements enable you to make decisions, repeat code execution, and control the flow of your program. The main control flow statements in Java are:

1. Conditional Statements:

a. if Statement:

if (condition) {
    // Code to be executed if the condition is true
} else {
    // Code to be executed if the condition is false
}

b. if-else if-else Statement:

if (condition1) {
    // Code to be executed if condition1 is true
} else if (condition2) {
    // Code to be executed if condition2 is true
} else {
    // Code to be executed if none of the conditions are true
}

c. Switch Statement:

switch (expression) {
    case value1:
        // Code to be executed if expression equals value1
        break;
    case value2:
        // Code to be executed if expression equals value2
        break;
    // Additional cases as needed
    default:
        // Code to be executed if expression doesn't match any case
}

2. Looping Statements:

a. for Loop:

for (int i = 0; i < 5; i++) {
    // Code to be repeated as long as the condition (i < 5) is true
}

b. while Loop:

while (condition) {
    // Code to be repeated as long as the condition is true
}

c. do-while Loop:

do {
    // Code to be repeated at least once, and then as -
    // long as the condition is true
} while (condition);

c. Java for-each loop:

for(data_type var : array_name/collection_name){
//statements
}

3. Branching Statements:

a. break Statement:

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // Exits the loop when i equals 5
    }
    // Code inside the loop
}

b. continue Statement:

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        continue; // Skips the rest of the loop and continues with the next iteration when i equals 5
    }
    // Code inside the loop
}

c. return Statement:

public int add(int a, int b) {
    return a + b; // Returns the sum of a and b
}

Conclusion:

As we conclude this first part of our exploration into the fascinating world of Core Java, I hope you've enjoyed delving into the intricacies and insights shared. We've covered some ground, but the journey is far from over.

Read Part 2

0
Subscribe to my newsletter

Read articles from Prajjwal Pratap Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prajjwal Pratap Singh
Prajjwal Pratap Singh

Software Engineer | Tech Enthusiast | Blogger 👋 Hey there! I'm Prajjwal Pratap Singh, a passionate software engineer with a love for turning ideas into reality through code. I thrive in the world of technology, constantly exploring new concepts and tools to enhance my skills. 🚀 As a software engineer, I specialize in Core Java and AWS DevOps. 📚 Beyond coding, I'm an avid tech enthusiast who believes in the power of continuous learning. Whether it's diving into the latest programming languages, exploring cutting-edge frameworks, or staying updated on industry trends, I'm always hungry for knowledge. 📝 On this blog, I share my insights, experiences, and learnings in the ever-evolving landscape of software development. From coding tutorials to tech reviews and thought pieces on the future of technology, you'll find a variety of content that reflects my journey in the tech world. 🌐 Connect with me on social media for more tech updates, and don't hesitate to reach out if you have questions or just want to geek out about the latest in tech. Thanks for stopping by, and happy coding! 🚀✨