🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

L_02_Java Fundamentals.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Transcript

Platform Independent Learning IT304021 Faculty of Information Technology University of Vocational Technology Ratmalana, Sri Lanka Ms. DMS Sathsara (Visiting Lecturer) Course Outline Introduction to Object-Oriented Programming (OOP) Introduct...

Platform Independent Learning IT304021 Faculty of Information Technology University of Vocational Technology Ratmalana, Sri Lanka Ms. DMS Sathsara (Visiting Lecturer) Course Outline Introduction to Object-Oriented Programming (OOP) Introduction to Java Java Basics Inheritance and Interfaces Exception Handling AWT Components & Swing Java Fundamentals - Class Declare a Class - Syntax Java Fundamentals - Variable Variable A variable, in the most general sense, is a storage location paired with an associated symbolic name, which contains some known or unknown quantity of information referred to as a value. Variables are used to store data that your program can manipulate. They have different types depending on the programming language you are using (such as integers, strings, objects, etc.), and their scope can be local to a function, global to a module, or somewhere in between. Local Variable vs. Instance Variable Local Variable: ○ A local variable is declared inside a method, constructor, or block and can only be accessed within that method, constructor, or block. ○ Its lifetime is limited to the execution of the block in which it is declared. Instance Variable: ○ An instance variable is a type of variable declared within a class but outside any method, constructor, or block. ○ It is tied to a specific instance (object) of the class, meaning that each object has its own copy of the instance variable. Local Variable vs. Instance Variable Scope ○ Local Variable: The scope of a local variable is limited to the method, constructor, or block in which it is declared. It cannot be accessed outside of this scope. ○ Instance Variable: The scope of an instance variable is the entire class, except for static methods. It can be accessed by all methods, constructors, and blocks in the class, as long as they directly belong to the instance of the class. Local Variable vs. Instance Variable Lifetime ○ Local Variable: The lifetime of a local variable is limited to the execution of the method, constructor, or block. It gets created when the block is entered and destroyed when the block is exited. ○ Instance Variable: The lifetime of an instance variable spans the life of the object. It is initialized when the object is created and destroyed when the object is garbage collected. Local Variable vs. Instance Variable Accessibility ○ Local Variable: Local variables do not have access modifiers. Their accessibility is inherently limited to the block in which they are declared. ○ Instance Variable: Instance variables can have access modifiers (like private, public, or protected in Java), which determine how they can be accessed from outside the class. Local Variable vs. Instance Variable Initialization ○ Instance Variable: Instance variables have default values if they are not explicitly initialized (e.g., 0 for integers, null for object references in Java). ○ Local Variable: Local variables do not have default values and must be initialized before use. Attempting to use an uninitialized local variable will result in a compile-time error in many programming languages. Example public class MyClass { private int instanceVar; // Instance variable public MyClass(int value) { int localVar = value; // Local variable this.instanceVar = localVar; // Assigns the value of the local variable to the instance variable } public void printValues() { System.out.println("Instance Variable: " + instanceVar); // Accessing instance variable // This method does not have access to localVar because it's a local variable in the constructor } } Java Fundamentals - Method Method() A method is a block of code that performs a specific task. It is defined within a class (in object-oriented programming) and is capable of acting on the data contained in objects of that class or performing operations related to those objects. Methods are fundamental to the encapsulation and abstraction concepts in object- oriented programming, allowing complex operations to be hidden behind simple method calls. Method() - Characteristics Methods encapsulate specific behaviors of a class and hide their internal implementation from the outside world. This allows for modular, maintainable, and scalable code. Once a method is written, it can be called multiple times from different parts of a program or even from different programs, promoting code reusability. Methods can accept parameters, allowing you to pass data to them. Parameters provide methods with the flexibility to operate on different data without needing to change the method's code. Methods can return values. The return type of a method specifies the type of value the method returns to the caller. If a method does not return any value, its return type is often void. Method() - Defining public int add(int a, int b) { return a + b; } In this example, ○ `public` is the access modifier, ○ `int` is the return type (indicating that the method returns an integer), ○ `add` is the method name, ○ `int a, int b` are the parameters it accepts, ○ The code block `{ return a + b; }` is the body of the method, defining what it does. Method() - Calling public void demoAdd() { int sum = add(5, 7); System.out.println("The sum is: " + sum); } Java Fundamentals - output Output Formatting `System.out.println` is commonly used to display the output of a program to the console. It automatically appends a newline character (`\n`) after printing the provided expression, which moves the cursor to the next line. If you do not want to move to the next line after printing, you can use `System.out.print` instead, which does not append a newline character. Debugging: Print the values of variables or expressions to understand program flow and detect errors. Logging: Output messages to track the behavior of the program during runtime. User interface: Display information or feedback to users in console-based applications. Output Formatting System.out.println(expression); Parameters: ○ `expression`: The data or expression to be printed. It can be of any data type, including primitive types (int, float, double, etc.), objects, or strings. Behavior: ○ Prints the string representation of the provided expression to the standard output stream. ○ After printing, it moves the cursor to the next line. Output Formatting Example: int num = 10; String name = "John"; double pi = 3.14159; System.out.println("Number: " + num); // Prints: Number: 10 System.out.println("Name: " + name); // Prints: Name: John System.out.println("PI: " + pi); // Prints: PI: 3.14159 Output Formatting Output formatting in Java refers to the process of controlling and modifying the appearance of output data (such as numbers and text) when displaying it to the user, typically through the console or a file. Java provides several ways to format output, including ○ `printf` method, ○ `String.format` method, and ○ `DecimalFormat` class. These tools allow programmers to specify the exact format in which data should be presented, such as the number of decimal places in floating-point numbers, aligning text, padding, including commas in large numbers, and more. Output Formatting `printf` Method ○ The `printf` method belongs to the `PrintStream` class (and by extension to the `System.out` object, which is an instance of `PrintStream`). ○ It allows formatted strings to be written to the output stream. ○ The `printf` method uses format specifiers that start with a `%` character and specify the type and format of the data to be displayed. ○ After the format string, you provide the variables to be formatted. ○ Example: System.out.printf("Name: %s, Age: %d, Salary: %.2f\n", "John Doe", 30, 12345.678); Output Formatting `String.format` Method ○ The `String.format` method works similarly to `printf` but returns a formatted string instead of printing it to the console. ○ This is useful when you want to format text before using it in a different context (e.g., in a GUI or storing it in a variable). ○ Example: String formattedString = String.format("Height: %.1f cm", 172.3); System.out.println(formattedString); Output Formatting `DecimalFormat` Class ○ The `DecimalFormat` class in the `java.text` package offers more flexibility and control over number formatting. ○ It allows for the formatting of numbers based on custom patterns, such as specifying the number of decimal places, grouping separators, and even currency symbols. ○ Example: import java.text.DecimalFormat; DecimalFormat decimalFormat = new DecimalFormat("#,###.00"); System.out.println(decimalFormat.format(1234567.89)); Activity "Can you create a Java program that consists of three distinct methods to read a Celsius temperature from the keyboard, convert this temperature to Fahrenheit, and finally print the converted temperature? The conversion formula to use is: Fahrenheit = (Celsius * 9/5) + 32." Activity "Can you develop a Java program that accomplishes the following tasks? The program should prompt the user to input three integer values from the keyboard. Once the input is received, it should calculate the total sum and the average of these values. To guide your development process, begin with a top-down design approach to outline the structure and flow of your program. Then, proceed to implement your solution according to the design you've outlined." Java Fundamentals - Input Input from keyboard Reading input from the user in Java is commonly done using the Scanner class, which is part of the java.util package. This class provides various methods to read different types of input, including `int`, `double`, `String`, and more, from the standard input stream (usually the keyboard). Steps to Read Input from the Keyboard ○ Import the Scanner Class: import `Scanner` class from the `java.util` package. ○ Create an Instance of Scanner: Create an instance of the `Scanner` class, passing `System.in` as an argument to its constructor. `System.in` is an input stream connected to the keyboard input. ○ Use Scanner Methods to Read Input: Use the appropriate method of the `Scanner` instance to read the input. (`nextInt()` , `nextDouble()`,`nextLine()` ) ○ Close the Scanner: It's a good practice to close the `Scanner` instance once you're done with it to free up resources. Example -Input from keyboard import java.util.Scanner; // Import the Scanner class public class InputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Create a Scanner object System.out.println("Enter your name: "); // Read a string input String name = scanner.nextLine(); // Read the user's name System.out.println("Enter your age: "); int age = scanner.nextInt(); // Read an integer input System.out.println("Hello, " + name + "! You are " + age + " years old."); // Output scanner.close(); // Close the scanner } } Activity "Can you create a Java program that prompts the user to input two integer values, calculates the average of these two values, and then prints the result to the console?" Answer import java.util.Scanner; public class AverageCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the first integer: "); int firstNumber = scanner.nextInt(); System.out.println("Enter the second integer: "); int secondNumber = scanner.nextInt(); double average = (firstNumber + secondNumber) / 2.0; System.out.println("The average of " + firstNumber + " and " + secondNumber + " is: " + average); scanner.close(); } } Java Fundamentals - Operators Operators in Java Unary Operators Unary operators require only one operand to perform an operation. They perform various operations such as incrementing/decrementing a value, negating an expression, or inverting the value of a boolean. Increment (++): Increases the value of its operand by 1. If the operator is placed before the operand (e.g., ++x), it's a prefix increment; if it's placed after the operand (e.g., x++), it's a postfix increment. Examples ○ Decrement (--): Decreases the value of its operand by 1. Similar to the increment operator, it can be a prefix (--x) or postfix (x--) decrement. ○ Logical NOT (!): Inverts the value of a boolean operand. If the operand is true, the result of the operation is false, and vice versa. Binary Operators Binary operators require two operands to perform an operation. They are used to perform arithmetic, equality, relational, and logical operations, among others. Examples: ○ Addition (+): Adds the values of its two operands. ○ Subtraction (-): Subtracts the right operand from the left operand. ○ Multiplication (*): Multiplies the values of its two operands. ○ Division (/): Divides the left operand by the right operand. ○ Modulus (%): Returns the remainder of dividing the left operand by the right operand. ○ Equal to (==): Checks if the value of two operands is equal. If so, the condition becomes `true`. ○ Not Equal to (!=): Checks if the value of two operands is not equal. If so, the condition becomes `true`. Arithmetic Operators Assignment Operators Comparison Operators Logical Operators Java Fundamentals - Decision Making and Branching If….else Use the else statement to specify a block of code to be executed if the condition is false. Syntax: if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false } If….else Example int time = 20; if (time < 18) { System.out.println("Good day."); } else { System.out.println("Good evening."); } // Outputs "Good evening." If….else Example int time = 22; if (time < 10) { System.out.println("Good morning."); } else if (time < 18) { System.out.println("Good day."); } else { System.out.println("Good evening."); } // Outputs "Good evening." Shorthand If….else Syntax variable = (condition) ? expressionTrue : expressionFalse; Example int time = 20; String result = (time < 18) ? "Good day." : "Good evening."; System.out.println(result); Switch Statements Instead of writing many if..else statements, you can use the switch statement. The switch statement selects one of many code blocks to be executed: Syntax switch(expression) { case x: // code block break; case y: // code block break; Default: // code block } Switch Statements int day = 4; switch (day) { case 1: System.out.println("Monday"); Break; case 2: System.out.println("Tuesday"); Break; …. case 7: System.out.println("Sunday"); Break; } // Outputs "Thursday" (day 4) While Loop Repeatedly executes a block of statements as long as a given condition is `true`. It is used when the number of iterations is not known before the loop starts. The condition is evaluated before the execution of the loop's body; if the condition evaluates to `true`, the body of the loop is executed. This process repeats until the condition becomes `false`. If the condition is `false` at the first evaluation, the body of the loop will not be executed at all. Syntax while (condition) { // Statements to be executed as long as the condition is true } While Loop Example: int counter = 1; while (counter

Tags

java programming object-oriented programming variables
Use Quizgecko on...
Browser
Browser