INTRODUCTION TO JAVA

Unit-1 :- Introduction to JAVA.

Overview

  • 1.1 Introduction to JAVA
  • 1.2 Properties of JAVA
  • 1.3 Comparison of JAVA with C++
  • 1.4Identifier,Literals,Operators,Variable,Keyword,Data Types.
  • 1.5 Branching : If-Else , Switch
  • 1.6 Looping : While, Do-while, For
  • 1.7 Type Casting

Introduction to JAVA.

1.1 Introduction to JAVA

  • Java is one of the most popular and widely-used programming languages today, known for its versatility, portability, and robust security features.
  •  Developed by Sun Microsystems in 1995, Java has become a cornerstone of the software development world.
  • It has powered applications across industries, ranging from mobile apps to enterprise-level systems, web applications, and even embedded systems.
  • Java was designed with the principle of “Write Once, Run Anywhere” (WORA), meaning that code written in Java can run on any platform that has a Java Virtual Machine (JVM), regardless of the underlying hardware or operating system.

Key Features of Java

1. Object-Oriented Programming (OOP):

  • Java is fundamentally an object-oriented programming language.
  • It uses objects and classes to model real-world entities. This promotes modularity, code reuse, and easy maintenance.
  • The core concepts of OOP in Java include inheritance, polymorphism, encapsulation, and abstraction. 

2. Platform Independence :

  • Java achieves platform independence through the JVM.
  • When Java code is compiled, it is converted into bytecode, which can run on any machine with a JVM, regardless of the operating system.
  • This makes Java a cross-platform language, a significant advantage in today’s diverse computing environments.

3. Syntax Similarity to C/C++:

  • Java’s syntax is closely related to that of C and C++, which makes it easier for developers familiar with these languages to transition to Java.
  • However, Java simplifies many aspects of C/C++, removing complex features like pointers and multiple inheritance.

4. Rich Standard Library:

  • Java offers a vast standard library that supports a wide range of functionalities, including networking, database connectivity (JDBC), graphical user interface (GUI) development (Swing and JavaFX), and more.
  • This comprehensive set of APIs allows developers to quickly build robust applications.

5.Automatic Memory Management (Garbage Collection):

  • One of Java’s key advantages is its automatic memory management.
  • The garbage collector (GC) automatically reclaims memory that is no longer in use, helping prevent memory leaks and other issues related to manual memory management, which is a common challenge in languages like C and C++.

6. Multithreading Support:

  • Java provides built-in support for multithreading, allowing developers to create applications that can perform multiple tasks concurrently.
  • This is particularly useful in scenarios where applications need to handle multiple tasks, such as serving multiple users or processing large datasets.

7. Security:

  • Java was designed with security in mind. The language includes several built-in mechanisms such as bytecode verification, runtime security checks, and a secure execution environment.
  • This makes Java a popular choice for web-based applications, where security is a top priority.

8. Distributed Computing:

  • Java supports distributed computing, allowing applications to run on a network. With technologies like Java RMI (Remote Method Invocation) and Java’s networking API, developers can create applications that communicate over the internet or a local network.

9. Portability and Scalability:

  • Because of its platform independence, Java is well-suited for applications that need to be portable across different systems.
  • Additionally, Java’s scalability makes it ideal for developing large-scale enterprise applications that need to grow with increasing demand.

Basic Structure of a Java Program

A basic Java program consists of the following components:

1. Class Declaration:

  • Every Java program is made up of one or more classes.
  • The class serves as a blueprint for creating objects.
  • The class declaration starts with the keyword class, followed by the class name.

2. Main Method:

  • Every Java application must have a main method, which serves as the entry point of the program. It is always written as: 
  • public static void main(String args[ ] )
  • This method is where the execution of the program begins.

3. Statements and Expressions:

  • Inside the class, developers write statements and expressions to define the behavior of the program. These can include variable declarations, assignments, loops, conditionals, method calls, etc

4. Output:

  • Java uses the System.out.println() method to display output to the user. For example:

 

Java Development Environment

To begin programming in Java, a developer needs the following:

1. Java Development Kit (JDK):

  • The JDK is a software development kit used to build Java applications. It includes the Java Runtime Environment (JRE), compilers, debuggers, and other development tools.

2.Integrated Development Environment (IDE):

  • While Java can be written using a simple text editor, most developers use an IDE for ease of coding, debugging, and managing large projects. Popular Java IDEs include IntelliJ IDEA, Eclipse, and NetBeans.

3. Java Virtual Machine (JVM):

  • The JVM is responsible for executing Java bytecode. It abstracts the underlying hardware and operating system, providing the platform-independent nature of Java.

Java in the Real World

Java is used in a variety of real-world applications, including:

1. Mobile Applications (Android):

  • Java is the primary language for developing Android applications. While Android development has adopted Kotlin as an alternative, Java remains a key player in mobile app development.

2.Web Applications:

  • Java is widely used in server-side web development, with frameworks like Spring, JavaServer Faces (JSF), and Hibernate enabling the creation of scalable, secure, and high-performance web applications.

3. Enterprise Software:

  • Java is the language of choice for large-scale enterprise applications. Many financial institutions, government agencies, and multinational corporations use Java to develop complex, mission-critical systems.

4. Big Data Technologies:

  • Java is a key component in big data technologies, such as Apache Hadoop and Apache Kafka, used for processing and analyzing massive datasets in distributed environments.

 

 

 

Java Compiler and Java Interpreter: A Detailed Overview

  • In the Java programming environment, two key components play a crucial role in the process of transforming source code into executable code: the Java. Compiler and the Java Interpreter
  • These components work together to ensure that Java programs can run efficiently across various platforms and hardware configurations, which is central to Java’s philosophy of “Write Once, Run Anywhere.”

Java Compiler

  • The Java Compiler is a software tool that translates Java source code, written in human-readable form, into bytecode.
  • The bytecode is an intermediate, platform-independent code that can be executed by the Java Virtual Machine (JVM), making Java a “platform-independent” language.
  • The compilation process is essential because it prepares the source code for execution in the JVM, which is responsible for running the bytecode on any platform.

Key Functions of the Java Compiler:

1. Source Code to Bytecode Conversion:

  • The primary function of the Java compiler is to take Java source files, with the .java extension, and convert them into bytecode files, with the .class extension.
  • The bytecode files are not specific to any machine architecture and can be executed by any JVM installed on a system, ensuring portability.

2. Syntax and Error Checking:

  • The Java compiler performs error checking as it converts the source code. If there are any syntax or semantic errors in the Java code, the compiler reports these errors to the programmer.
  • The errors could include missing semicolons, incorrect variable names, or other language-specific issues. This feature ensures that code adheres to Java’s strict rules before execution.

3. Optimization:

  • The compiler can perform certain optimizations to improve performance by reducing memory usage, making the bytecode more efficient, or rearranging instructions for faster execution.

4. Output:

  • After compiling, the output is a .class file, which contains the bytecode. This file is portable and can be executed on any system that has a JVM.

Process of Compilation:

  • Step 1: The programmer writes Java source code in a file with a .java extension.
  • Step 2: The source code is passed to the Java compiler, usually by using the javac command (for example, javac MyProgram.java).
  • Step 3: If the code has no errors, the compiler generates a bytecode file with a .class extension (e.g., MyProgram.class).
  • Step 4: The .class file can now be run on any platform with a JVM.

Example :- 

  • javac HelloWorld.java
  • java HelloWorld

Java Interpreter (JVM)

  • The Java Interpreter, often referred to as the Java Virtual Machine (JVM), is the runtime engine that executes Java bytecode.
  • Unlike traditional compilers that directly convert code to machine language, the JVM interprets the bytecode, either by directly executing it or by compiling it into native machine code using Just-In-Time (JIT) compilation.
  • The JVM is what allows Java to achieve its famous portability.
  • Java programs are compiled into bytecode that can run on any JVM, regardless of the underlying hardware or operating system.
  • The JVM abstracts the machine’s architecture and provides a standard execution environment.

Key Functions of the Java Interpreter (JVM):

1. Execution of Bytecode:

  • The JVM reads the compiled bytecode from .class files and executes it. It translates the bytecode into machine code specific to the host machine’s processor.

2. Memory Management:

  • The JVM manages the program’s memory, including the heap and stack. It handles memory allocation and deallocation automatically, which prevents issues such as memory leaks.

  • Java’s garbage collector runs in the background to reclaim memory that is no longer in use.

3. Just-In-Time (JIT) Compilation:

  • While the JVM interprets bytecode, it also uses JIT compilation to improve performance. The JIT compiler translates bytecode into native machine code at runtime, which allows Java programs to run faster after the initial interpretation phase.

  • This means that frequently executed code is compiled into machine language to avoid repeated interpretation, making execution more efficient.

4. Platform Independence:

  • The JVM enables Java’s key feature of portability. Since the JVM abstracts the underlying operating system and hardware, Java bytecode can run anywhere that a JVM is installed, whether on Windows, macOS, Linux, or other platforms.

5. Security:

The JVM plays a significant role in Java’s security. It performs runtime checks to ensure that the bytecode does not violate system security policies, preventing unauthorized access to system resources.

6. Exception Handling:

The JVM also manages Java’s robust exception handling mechanism. It ensures that exceptions are thrown, caught, and handled appropriately, ensuring that the program doesn’t crash unexpectedly during execution.

Process of Interpretation:

  • Step 1: The Java program is compiled into bytecode by the Java compiler.
  • Step 2: The JVM loads the bytecode and starts interpreting or compiling it into native code using the JIT compiler.
  • Step 3: The JVM executes the bytecode instructions and manages the program’s memory, including garbage collection and exception handling.

Java Compilation vs. Interpretation

Point of Differnce Java Compiler Java Interpreter
1.Purpose Translates Java source code to bytecode. Executes bytecode on the JVM.
2.Output Generates .class bytecode files Executes bytecode either directly or using JIT compilation.
3. Exceution Happens once before execution. Happens every time the program runs.
4. Performance Typically faster (one-time operation) . Can be slower without JIT optimization but improves with JIT.
5. Platform Dependency Platform-independent bytecode Platform-independent execution via JVM
6. Memory Management No memory management Manages memory automatically (including garbage collection).

Detailed Note on Java Programming Concepts: Identifiers, Literals, Operators, Variables, Keywords, and Data Types.

  • In Java programming, several fundamental concepts are crucial for writing functional and efficient code. These concepts include identifiers, literals, operators, variables, keywords, and data types.
  • . Understanding these elements is vital for any developer who wants to effectively work with Java, as they form the building blocks of all Java programs.

1. Identifiers 

  • An identifier is a name used to identify a variable, function, class, or any other user-defined item.
  • In Java, identifiers follow specific rules to ensure that they are valid.

Rules for Valid Identifiers:

  • Length: An identifier can be of any length.
  • Start with a letter: An identifier must begin with a letter (A-Z or a-z), an underscore (_), or a dollar sign ($). It cannot start with a digit (0-9).
  • Subsequent characters: After the first character, the identifier can contain letters, digits, underscores, or dollar signs.
  • Case-sensitive: Java is case-sensitive, meaning myVariable and myvariable are considered two different identifiers.
  • No reserved keywords: Identifiers cannot be the same as Java reserved keywords (e.g., int, class, if).
Example :- 

int age =25; // “age” is an identifier

String name = "John"; // "name" is an identifier

2. Literals

  • A literal is a constant value used directly in a program. Literals are fixed values that represent data and are used to assign values to variables or to specify parameters in expressions.

Types of Literals in Java:

  • Integer literals: Represent integer values (e.g., 10, -500, 0).
  • Floating-point literals: Represent real numbers (e.g., 3.14, -0.001, 1.0f).
  • Character literals: Represent a single character enclosed in single quotes (e.g., ‘a’, ‘1’, ‘#’).
  • String literals: Represent a sequence of characters enclosed in double quotes (e.g., “Hello”, “123”).
  • Boolean literals: Represent a boolean value (true or false).
  • Null literal: Represents a null value, used to denote that a reference variable does not point to any object (e.g., null).

Example:

int num = 100; // 100 is an integer literal
double pi = 3.14; // 3.14 is a floating-point literal
char letter = 'A'; // 'A' is a character literal
String greeting = "Hello, World!"; // "Hello, World!" is a string literal
boolean isJavaFun = true; // true is a boolean literal

3. Operators

  • In Java, operators are symbols used to perform operations on variables and values. Operators are essential for manipulating data and variables in programs.

Types of Operators in Java:

  • Arithmetic Operators: Used for mathematical operations
  • Additional  (+)
  • Subtraction (-)
  • Multiplication(*) 
  • Division (/)
  • Modules(%)
4. Variables :- 
  • A variable is a container for storing data values. In Java, every variable must be declared with a specific data type.
  • Variables are used to hold data that can be manipulated throughout the program.
Rules for Declaring Variables:
  • Must start with a letter, underscore, or dollar sign.
  • Cannot start with a number.
  • Cannot be a keyword (reserved word in Java).
  • Case-sensitive.
5. Keywords :- 
  • Keywords are reserved words in Java that have predefined meanings and cannot be used as identifiers.
  • These words are part of the Java syntax and define the structure and behavior of programs.

6. Data Types :- 

Primitive Data Types:

  • These represent basic types of data and are the most fundamental types in Java. They are predefined in Java and are not objects.
    • byte: 8-bit integer, range from -128 to 127.
    • short: 16-bit integer, range from -32,768 to 32,767.
    • int: 32-bit integer, range from -2^31 to 2^31-1.
    • long: 64-bit integer, range from -2^63 to 2^63-1.
    • float: 32-bit floating-point number.
    • double: 64-bit floating-point number.
    • char: Single 16-bit Unicode character.
    • boolean: Represents true or false values.

Reference Data Types:

  • These are types that refer to objects and arrays.
  • They do not store the actual data but rather a reference to the data.
    • String: A sequence of characters.
    • Arrays: A collection of variables of the same type.
    • Objects: Instances of classes.

Detailed Note on Branching in Java:

  • Branching in programming refers to the ability to control the flow of execution depending on certain conditions.
  • In Java, branching is achieved using conditional statements like if-else and switch.
  • These control structures allow the program to make decisions, executing different blocks of code based on certain conditions.
  • Understanding how to use these branching statements efficiently is fundamental to writing logic in Java.

1. if-else Statement :- 

  • The if-else statement is one of the most commonly used conditional constructs in Java.

  •  It allows a program to evaluate a condition (an expression that results in a boolean value), and based on whether the condition is true or false, execute a specific block of code.

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

    
public class IfElseExample {
    public static void main(String[] args) {
        int number = 10;

        if (number > 0) {
            System.out.println("The number is positive.");
        } else {
            System.out.println("The number is not positive.");
        }
    }
}

    

TRY IT YOURSELF.

if-else if Statement. 

  • In cases where there are multiple conditions to evaluate, the if-else statement can be extended using else if.
  • This allows the program to check several conditions sequentially.
  • Syntax.
if (condition1) {
    // Code for condition1
} else if (condition2) {
    // Code for condition2
} else if (condition3) {
    // Code for condition3
} else {
    // Code for when none of the above conditions are true
}
    
    
public class IfElseExample {
    public static void main(String[] args) {
        int number = 10;

        if (number > 0) {
            System.out.println("The number is positive.");
        } else {
            System.out.println("The number is not positive.");
        }
    }
}
    

Nested if-else.

  • It is also possible to use an if-else statement inside another if-else statement. This is called nested if-else.
  • Example.
public class IfElseIfExample {
    public static void main(String[] args) {
        int marks = 85;

        if (marks >= 90) {
            System.out.println("Grade: A+");
        } else if (marks >= 80) {
            System.out.println("Grade: A");
        } else if (marks >= 70) {
            System.out.println("Grade: B");
        } else if (marks >= 60) {
            System.out.println("Grade: C");
        } else {
            System.out.println("Grade: F");
        }
    }
}

    

TRY THIS YOURSELF.

switch Statement.

  • The switch statement is another control flow structure in Java that allows multi-way branching.
  • Unlike if-else, which can evaluate multiple conditions one by one, switch is more efficient when you need to compare a single variable against multiple constant values (like numbers or strings).
  • The switch statement evaluates an expression, and depending on the result, it will execute the corresponding block of code that matches one of the cases.
  • If no match is found, the default case is executed, if defined.

  • Syntax.
    switch (expression) {
    case value1:
        // Code to execute if expression == value1
        break;
    case value2:
        // Code to execute if expression == value2
        break;
    case value3:
        // Code to execute if expression == value3
        break;
    default:
        // Code to execute if no case matches
}

    
  • Expression: The variable or expression that is evaluated.
  • Case: A potential value that the expression might match. If a match is found, the corresponding block is executed.
  • Break: Stops the execution of the switch statement once a case is executed. Without break, the execution continues into the next case (this is known as “fall-through”).
  • Default: A block of code that runs if no case matches the expression. The default block is optional.
  • Example.
int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    case 6:
        System.out.println("Saturday");
        break;
    case 7:
        System.out.println("Sunday");
        break;
    default:
        System.out.println("Invalid day");
}

    

Switch with Strings.

  • Starting from Java 7, the switch statement can also be used with String types. This allows you to match strings directly in the switch cases.

  • Example

 

String fruit = "Apple";
switch (fruit) {
    case "Apple":
        System.out.println("Fruit is an Apple");
        break;
    case "Banana":
        System.out.println("Fruit is a Banana");
        break;
    default:
        System.out.println("Unknown fruit");
}

    

Comparing if-else and switch.

  • While both if-else and switch serve the purpose of conditional branching, they have some differences:

 

Aspect if-else switch
Number of conditions Can handle complex, compound conditions. Handles a single expression with multiple constant values.
Use case Used when conditions are complex or involve ranges. Best for fixed, discrete values like integers or strings.
Performance May be slower for large numbers of conditions. Typically faster for many conditions, as it uses jump tables.
Flexibility More flexible, can handle any type of expression. Limited to specific data types (e.g., integers, enums, strings).
Default Case Does not have a default equivalent. Has an optional default case.

Looping in Java: While, Do-While, and For Loops.

  • loops are used to execute a block of code repeatedly based on a condition
  • Java provides several types of loops, allowing developers to perform repetitive tasks efficiently.
  • The three most commonly used loops in Java are the while loop, the do-while loop, and the for loop.
  • Each loop serves a different purpose depending on the scenario, and understanding how to use them is essential for writing effective Java programs.

1. While Loop.

  • The while loop in Java is used when you want to execute a block of code repeatedly as long as a given condition remains true.
  • The condition is checked before each iteration, meaning that if the condition is false initially, the code inside the loop will not execute even once.
  • Syntax.

 

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

    
  • Condition: This is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the loop continues to execute. If it’s false, the loop terminates.
  • Loop body: The block of code that runs as long as the condition is true.
  • Example.
int i = 0;
while (i < 5) {
    System.out.println("i is: " + i);
    i++;  // Increment to avoid infinite loop
}
    

Characteristics of the While Loop:.

  • The condition is evaluated before the loop body is executed, so if the condition is false initially, the body will not execute.
  • It is ideal when the number of iterations is not known in advance, and the loop continues as long as a condition is true.

2. Do-while Loop.

  • The do-while loop is similar to the while loop, but with one key difference: in a do-while loop, the condition is checked after the loop body executes.
  • This ensures that the loop body is always executed at least once, even if the condition is false initially.
  • Syntax:

do {
    // Code to be executed
} while (condition);

    
  • Condition: Just like in the while loop, the condition is a boolean expression that is evaluated after each iteration of the loop. If the condition is true, the loop continues; if it is false, the loop stops.
  • Loop body: The block of code that is executed at least once and then repeatedly, based on the condition.
  • Example.
int i = 0;
do {
    System.out.println("i is: " + i);
    i++;  // Increment to avoid infinite loop
} while (i < 5);
   
    

Characteristics of the Do-while Loop:

  • The loop body is executed at least once, regardless of whether the condition is true or false at the beginning.
  • It is useful when you want to execute the loop body at least once, such as when prompting a user for input and ensuring that the code runs initially.

3. For Loop.

  • The for loop is typically used when the number of iterations is known beforehand.
  • It provides a compact way to initialize a loop variable, define the condition, and update the loop variable in one statement.
  • Syntax:

for (initialization; condition; update) {
    // Code to be executed as long as the condition is true
}
    

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.