The Basics of The Java Language PDF
Document Details
Uploaded by Deleted User
Badji Mokhtar University - Annaba
2024
Dr. Sarra Namane
Tags
Summary
This presentation provides a beginner-friendly introduction to the Java programming language. It covers fundamental Java concepts, the Java environment, and various Java programming elements, with a focus on essential aspects for 2nd-year engineering students studying computer science.
Full Transcript
The basics of the Java language Dr. Sarra Namane Department of Computer Science Badji Mokhtar University, Annaba Class: 2nd Year Engineering Year: 2024/2025 Introduction In this first course, we will introduce and explain the basic Java concep...
The basics of the Java language Dr. Sarra Namane Department of Computer Science Badji Mokhtar University, Annaba Class: 2nd Year Engineering Year: 2024/2025 Introduction In this first course, we will introduce and explain the basic Java concepts that will be essential for our future Object-Oriented Programming (OOP) classes. As we move forward, we will gradually build on these concepts to deepen our understanding and expand our knowledge. Each upcoming lesson will build on what we've learned, helping us become more proficient in Java2 What is Java? Java is a programming language originally developed by Sun Microsystems and now under the stewardship of Oracle since its acquisition in 2010. It is both a compiled and interpreted language, known for its portability across different platforms. Java is open-source, which means its source code is freely available for use and modification. It is high-level and object-oriented, meaning it is designed to be easy to use and organized around objects. Java is very popular because it can run on any device that supports the Java Virtual Machine (JVM), making it ideal for creating applications that work on different platforms. Developers use Java to build various types of software, including 3 Strengths Simple: Easy to learn and use. Syntax similar to C/C++: Familiar to those with experience in C or C++. Supports development: Facilitates efficient software creation. Portable: Runs on any device with the Java Virtual Machine (JVM). Secure: Includes built-in security features to protect against vulnerabilities. Ensures high performance: Optimized for speed and efficiency. Robust: Handles errors and exceptions effectively to maintain stability. 4 The Java environment Java source code is compiled into bytecode during the compilation process. Bytecode cannot be directly executed by the machine. The Java Virtual Machine (JVM) understands bytecode. The JVM uses a Java interpreter to convert bytecode into platform-specific machine code. The JVM is platform-specific, with each platform having its own JVM. Once the correct JVM is installed, any Java bytecode can be executed. Bytecode is intermediate between source code and platform-independent machine language. 5 JAVA development Kit (JDK) Provides a Java compiler. Provides a Java Virtual Machine (JVM). Provides a set of libraries that facilitate programming. 6 The Virtual Machine (JVM) Bytecode Interpretation: The JVM interprets the bytecode generated during the compilation of Java source code. It translates this bytecode into instructions executable by the underlying machine. Memory Management: The JVM handles automatic memory management, including reclaiming memory used by objects that are no longer 7 Structure of a Java Program A basic Java program consists of several key components: Packages: These are namespaces that organize classes and interfaces. For example, import java.util.*; imports the utility package that contains useful classes like Scanner. Classes: The fundamental building block of Java programs. A class is a blueprint for objects. Every Java program must have at least one class, and the class name must match the file name. Methods: Functions or procedures inside a class that perform actions. The main method (public static8 An Example of Program Structure This example shows a basic Java program structure. It starts with a package declaration, followed by a class definition, and inside the class, a main method, which is the entry point of the program. Importance of public static void main(String[] args) Method: The main method is the entry point of any Java application. When you run a Java program, the Java Virtual Machine (JVM) looks for the main method and starts executing from there. public: The method is accessible from outside the class. static: The method belongs to the class, not instances of it. This allows the JVM to call the method without creating an object of the class. void: The method does not return any value. 9 Packages in Java Packages are divided into two categories: built-in Java packages and user-defined packages. To indicate that a class belongs to a user-defined package, we use the keyword "package." Otherwise, we use "import.“ A package can be seen as a folder where Java classes are stored. 10 Java Development environment Eclipse is an open- source IDE primarily used for Java development, though it supports other languages via plugins. It provides a comprehensive environment for coding, debugging, and testing Java Eclipse applications. Interface 11 Essential Features of Eclipse Code Editor: Syntax Highlighting: Differentiates keywords, data types, and other elements for easier readability. Code Completion: Suggests possible completions for partially typed statements, helping to speed up coding (Ctrl + Space to activate code completion, Enter or Tab to confirm the suggestion). Code Formatting: Automatically formats your code according to the selected style, ensuring consistency. Project Management: Workspace: Organizes your projects and resources in a structured manner. Debugging Tools: Breakpoints: Allow you to pause program execution at specific points. Step Execution: Step through code one line at a time to analyze the flow of the program. Variable Inspection: View the values of variables in real-time during 12 Eclipse Presentation in detail Eclipse is a powerful tool for Java developers, offering a wide array of features that streamline the development process. Its extensive plugin ecosystem and strong community support make it a go-to choice for both beginners and experienced developers. Interface: The Eclipse interface is designed to be intuitive for beginners, with several key areas that you'll interact with while coding in Java: Workbench: The main area of Eclipse is called the Workbench. It’s the overall window where you’ll find all the tools and views you need to develop your applications. The workbench can be customized to suit your preferences. Perspectives: Perspectives are pre-configured layouts that arrange the various views and editors to help you focus on specific tasks. The 13Java Eclipse Interface Project Explorer: Located on the left side, the Project Explorer view lists all your projects, files, and folders. It’s where you can easily navigate through your codebase and manage your resources. Editor Area: The large central section is the Editor Area. Here, you write and edit your Java code. Multiple files can be opened in tabs, allowing you to switch between them easily. Console: The Console view, typically located at the bottom, displays output from your program when you run or debug it. It also shows any errors or messages generated during the execution. Problems View: Also located at the bottom, the Problems View lists any errors or warnings in your code. It provides details like line numbers14 and Understanding Key Concepts in Java Development with Eclipse Project: A project in Eclipse is like a big folder that contains all your Java code, libraries, and resources. When you start a new project, Eclipse organizes everything you need for your application in one place. For example, if you were building a calculator app, you would create a "Calculator" project where all your code and files related to the calculator would be stored. Package: A package is a way to organize your Java classes inside a project. It’s like a subfolder within your project folder. Packages help you keep related classes together, making your code easier to manage. For instance, if you have classes that handle user input and classes that perform calculations in your calculator app, you might put them in separate packages like input and calculation. Class: A class is a blueprint for creating objects in Java. It defines what an object is and what it can do. For example, in your calculator app, you might have 15 a Understanding Key Concepts in Java Development with Eclipse (2) Object: An object is an instance of a class. When you create an object, you’re using the blueprint (the class) to build something specific. For example, if you have a Calculator class, creating an object from this class might represent a specific calculator you’re using in your app. Each object can have its own state and behavior, as defined by the class. Methods: Methods are blocks of code inside a class that perform specific actions. They define what an object can do. For instance, in the Calculator class, you might have methods like add, subtract, multiply, and divide. Each method would contain the code that 16 actually performs these operations when called. Steps to Create Your First Project in Eclipse 1. Open Eclipse: Start Eclipse on your computer. Once it loads, you’ll see the main workbench. 2. Create a New Project: Click on "File“ in the top menu. Select "New" and then choose "Java Project." 3. Name Your Project: In the window that appears, type a name for your project in the "Project Name" box (e.g., "MyFirstProject"). Click "Finish." 17 Steps to Create Your First Java Class 1. Open Your Project: In the Project Explorer on the left, find and expand your new project (e.g., "MyFirstProject"). Right-click on the "src" folder (this is where your Java files go). 2. Create a New Class: From the right-click menu, select "New" and then "Class." In the new window, give your class a name (e.g., "MyFirstClass"). Check the box that says "public static void main(String[] args)" to include the `main` method,18 Write and Test Your First Code 1. Write Your Code: After clicking "Finish," Eclipse will open your new class in the editor. Inside the `main` method, type the following code: System.out.println("Hello, World!"); 2. Run Your Code: To run your code, click the green play button at the top of the Eclipse window. You’ll see the output "Hello, World!“ appear in the Console at the bottom. 19 Primitive Data Types Java has eight primitive data types, which are the most basic data types that serve as the building blocks for data manipulation: Int: Stores integers without decimals, such as 123 or -456. It occupies 4 bytes of memory. Float: Stores floating-point numbers with decimals, such as 3.14 or -2.5. It occupies 4 bytes. Double: Stores double-precision floating-point numbers. It's more precise than float and occupies 8 bytes. Char: Stores a single character, such as 'a' or 'B'. It occupies 2 bytes. Boolean: Stores true or false values. It occupies 1 bit. Byte: Stores small integers between -128 and 127. It occupies 1 byte. 20 Examples of Primitive Data Types To declare a variable in Java, specify the type and name of the variable. You can also initialize it with a value. 21 The keyword “Final” In Java, the final keyword is used to declare constants When a variable is declared as final, it means that its value cannot be changed once it is assigned. Such variables are essentially constants. 22 Arithmetic Operators These operators perform basic mathematical operations. `+` (Addition): Adds two values. Example: int a = 5 + 3; // a is 8 `-` (Subtraction): Subtracts one value from another. Example: int b = 10 - 4; // b is 6 `*` (Multiplication): Multiplies two values. Example: int c = 7 * 2; // c is 14 `/` (Division): Divides one value by another. Example: int d = 20 / 4; // d is 5 23 Relational Operators These operators compare two values and return a boolean result (`true` or `false`). `==` (Equal to): Checks if two values are equal. Example: boolean isEqual = (5 == 5); // true `!=` (Not equal to): Checks if two values are not equal. Example: boolean isNotEqual = (5 != 3); // true `>` (Greater than): Checks if one value is greater than another. Example: boolean isGreater = (7 > 3); // true `=` (Greater than or equal to): Checks if one value is greater than or equal to another. Example: boolean isGreaterOrEqual = (8 >= 8); // true ` 3 && 8 > 6); // true `||` (Logical OR): Returns `true` if at least one condition is true. Example: boolean result = (5 < 3 || 8 > 6); // true `!` (Logical NOT): Reverses the boolean value. Example: boolean result = !(5 > 3); // false Assignment Operators and Shorthand `=` (Assignment): Assigns a value to a variable. Example: int x = 10; // x is 10 `+=` (Addition assignment): Adds a value to a variable and assigns the result. Example: x += 5; // x is now 15 `-=` (Subtraction assignment): Subtracts a value from a variable and assigns the result. Example: x -= 3; // x is now 12 25 Increment and Decrement These Operators operators increase or decrease a variable'svalue by one. `++` (Increment): Increases the value by 1. Example: int y = 5; y++; // y is now 6 `--` (Decrement): Decreases the value by 1. Example: int z = 5; z--; // z is now 4 https://learnwithkhurshid.com/50-best-mcqs-on- 26 increment-and-decrement-java/ Conditional Statements These statements execute different code based on conditions. `if` Statement: Executes a block of code if a condition is true. Example: int num = 10; if (num > 5) { System.out.println("Greater than 5"); } `else` Statement: Executes a block of code if the `if` condition is false. Example: if (num < 5) { System.out.println("Less than 5"); } else { System.out.println("Greater than or equal to 5"); } 27 Conditional Statements (2) `else if` Statement: Adds more conditions to check. Example: if (num > 10) { System.out.println("Greater than 10"); } else if (num == 10) { System.out.println("Equal to 10"); } else { System.out.println("Less than 10"); } `switch` Statement: Chooses one block of code to execute from multiple options. 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; default: System.out.println("Other day"); 28 Looping Structures These statements repeat code multiple times. `for` Loop: Repeats code a specific number of times. Example: for (int i = 0; i < 5; i++) { System.out.println(i); // Prints 0 to 4 } `while` Loop: Repeats code as long as a condition is true. Example: int i = 0; while (i < 5) { System.out.println(i); i++; } `do-while` Loop: Similar to `while`, but guarantees the loop runs at least once. Example: int i = 0; do { System.out.println(i); 29 Break and Continue Statements `break` Statement: Exits a loop immediately. Example: for (int i = 0; i < 10; i++) { if (i == 5) break; System.out.println(i); // Stops when i is 5 } `continue` Statement: Skips the current iteration and moves to the next. Example: for (int i = 0; i < 10; i++) { if (i == 5) continue; System.out.println(i); // Skips 5 } 30 Introduction to Arrays Defining and Initializing Arrays An array is a collection of values of the same type. 1. Single-Dimensional Array: int[] numbers = {1, 2, 3, 4, 5}; Array Initialization with Size: int[] numbers = new int; // Array with 5 elements numbers = 10; // Setting the first element to 10a Accessing and Modifying Array Elements Accessing: int firstElement = numbers; // Gets the first element (10) Modifying: numbers = 20; // Sets the second element to 20 2. Multi-Dimensional Arrays: Arrays can have more than one dimension, like a table of values. Two-Dimensional Array: int[][] matrix = {{1, 2, 3}, {4, 5,31 6}, Using Scanner class for User Input In Java, the `Scanner` class is used to capture user input. It can read different types of data, like integers, strings, and more. Example: 32 Method Methods in Java are blocks of code that perform a specific task and can be executed when called. They help organize code into reusable sections. Methods can accept parameters, perform operations, and optionally return a value. Components of a Method Modifiers: Define the access level and behavior of the method. Return Type: Specifies the type of value the method returns. If no value is returned, the return type is void. Method Name: A unique identifier for the method. Parameters: Optional inputs that the method can 33 Method (2) Modifiers: public (accessible from anywhere) Return Type: int (returns an integer value) Method Name: add Parameters: int a, int b Method Body: return a + b; (adds two numbers and returns the result) The sayHello() method is declared with the void keyword, which means it doesn't return any value. Instead, it performs an action—in this case, printing a34 Modifier A modifier defines the access level of classes, methods, and attributes. Common modifiers include: Public: Accessible from any other class. Private: Accessible only within the class where it is defined. Protected: Accessible within the same package and by subclasses. Default (no modifier): Accessible only within the same package. 35 QCM Which keyword is used to define a method that does not return any value? - A) static - B) void - C) this - D) final What does the `final` keyword do when used with a variable? - A) It makes the variable unmodifiable after initialization - B) It declares the variable as being accessible only within the method - C) It defines the variable as a static constant - D) It allows the variable to be modified at any time 36 QCM (2) What does System.out.println("Hello, World!"); do? a) Compiles the code. b) Prints Hello, World! to the console and moves the cursor to the next line. c) Prints Hello, World! to the console without moving the cursor to the next line. d) Prints an error message. Which of the following is true about System.out.println()? e) It prints the output without a newline character f) It is a method in the System class that outputs data to the console g) It is used to input data from the console 37 QCM (3) What is the output of the following code? a) Java30 b) Java1020 c) 30Java d) 1020Java Which of the following is the correct way to create a Scanner object for reading input from the console? e) Scanner input = new Scanner(); f) Scanner input = new Scanner(System.out); g) Scanner input = new Scanner(System.in); h) Scanner input = new Scanner(System.read()); 38 QCM (4) What is the purpose of the close() method in the Scanner class? a) To terminate the program b) To close the System.in input stream and free up resources c) To flush the console output d) To reset the scanner object for reuse 39 References https://www.geeksforgeeks.org/java/ https://www.tutorialspoint.com/java/index.htm https://www.simplilearn.com/tutorials/java-tutorial /what-is-java https://www.eclipse.org/downloads/ https://eclipseide.org/ https://www.youtube.com/watch?v=GaZuDecu82 U 40 41