Document Details

Uploaded by Deleted User

University of Sulaimani

2024

Ako Muhammad Abdullah

Tags

Java programming Fundamentals computer science

Summary

This document is course material on Fundamentals of Programming. It introduces Java programs, objects, methods, and key features. This document is from University of Sulaimani in Iraq, for the 2024-2025 academic year and includes sections on variables, their types, and initialization.

Full Transcript

Chapter One Variables What is Java? Java is a popular, high-level, object-oriented programming language that is widely used for building applications ranging from web and mobile to enterprise systems. o It is known for its platform independence, meaning Java programs can r...

Chapter One Variables What is Java? Java is a popular, high-level, object-oriented programming language that is widely used for building applications ranging from web and mobile to enterprise systems. o It is known for its platform independence, meaning Java programs can run on any device that has a Java Virtual Machine (JVM). o Oracle owns it, and numerous devices run Java. 3 Applications of Java o Web Applications: Using technologies like Spring, Hibernate, and JSP/Servlets. o Mobile Applications: Android apps are primarily developed in Java. o Enterprise Systems: Java is widely used for enterprise solutions (e.g., banking, insurance). o Embedded Systems: Java can run on small devices like smart cards. o Scientific Applications: Used in simulations, modeling, and data analysis. o Gaming: Many 2D/3D games are developed using Java frameworks like LibGDX. 4 Key Features of Java o Platform-Independent: Java code is compiled into bytecode, which can run on any system with a JVM. o Object-Oriented: Java is based on objects representing real-world entities with attributes (states) and behaviors (methods). o Robust and Secure: Java has strong memory management, exception handling, and built-in security features to protect applications. o Simple and Easy to Learn: Java syntax is similar to C/C++ but eliminates complex features like pointers and manual memory management. 5 Key Features of Java o Multi-threaded: Java supports concurrent programming, allowing multiple threads to execute simultaneously for better performance. o Open-source and free o Distributed and Network-Centric: Java includes APIs to support networking and distributed systems, making it ideal for web and enterprise applications. 6 Popular Java Editors write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following: o Notepad − On Windows machine, you can use any simple text editor like Notepad++ (Recommended for this tutorial), TextPad. o Netbeans − A Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html. o Eclipse − A Java IDE developed by the eclipse open- source community and can be downloaded from https://www.eclipse.org/. 7 Java – Basic Syntax Java program can be defined as a collection of objects that communicate via invoking each other's methods. Java is an object-oriented programming language. o Object: An object in Java is an instance of a class that has state (data or properties) and behavior (actions or methods). Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class. 8 Java – Basic Syntax (Cont’d) o Multiple objects can be created of one class: 9 Java – Basic Syntax (Cont’d) o Class: A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports. Create a Class: To create a class, use the keyword class: 10 Java – Basic Syntax (Cont’d) o Methods: A method is a block of code that performs a specific task. A class can contain many methods.  Advantage of Method Code Reusability Code Optimization 11 Java – Basic Syntax (Cont’d) The basic syntax of Java includes rules and structures for writing Java programs. Here's an overview: 1. Structure of a Simple Java Program // This is a comment public class MyClass { // Class declaration public static void main(String[] args) { // Main method // Statements go here System.out.println("Hello, World!"); // Prints a message } } 12 Java – Basic Syntax (Cont’d) 2. Key Components of Java Syntax a. Class Declaration: A Java program must have at least one class. The class name should match the file name (e.g., MyClass in MyClass.java). public class MyClass { // Class content } b. Main Method: The starting point for every Java application. Syntax: public static void main(String[] args) { // Code to execute 13 } Java – Basic Syntax (Cont’d) c. Statements: Java statements end with a semicolon (;). Example: System.out.println("Hello, World!"); d. Comments: Single-line // This is a single-line comment Multi-line 14 Java – Basic Syntax (Cont’d) 3. Key Syntax Rules Case Sensitivity: Java is case-sensitive (e.g., MyClass and myclass are different). Class Names: Should start with an uppercase letter (e.g., MyClass). Method Names: Should start with a lowercase letter (e.g., main). File Name: Must match the class name containing the main method (e.g., MyClass.java for MyClass). 4. Example Java Program // Example of a simple Java program public class MyClass { // Class name matches the file name public static void main(String[] args) { // Main method // Print statement System.out.println("Welcome to Java!"); }} 15 Working of Java 16 Bytecode Bytecode in Java is an intermediate machine-independent code. It is a set of instructions for Java Virtual Machine and it acts pretty similar to the assembler in C++. In general, bytecode is a code that lies between low-level and high-level language. The only essential requirement for running the bytecode is the installation of the Java Runtime Environment (JRE) in any platform. The bytecode is not processed by the processor. It is processed by the Java Virtual Machine (JVM). The job of the JVM is to call all the required resources to compile the Java program and make the bytecode independent. 17 Working of Java Bytecode o Program (Source Code): Program is a.java file. It consists of the code that you have written. o Compiler: Compiler complies the.java file and generate.class file. o Bytecode: The.class file contains the bytecode. Now, we can run the.class file in any of the other platforms. o JVM: JVM runs the bytecode without considering a processor. o Machine Code: the machine generates its own machine code in which the byte code is running. That means, its own machine-dependent code to run the.java file. 18 Variables Variable is a data container that saves the data values during Java program execution. Every variable is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory location name of the data. A variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. In Java, all the variables must be declared before use. 19 Variable Declaration o We can declare variables in java as pictorially depicted below as a visual aid. o From the image, it can be easily observed that while declaring a variable, we need to take care of two things that are: Datatype: Type of data that can be stored in this variable. Dataname: Name was given to the variable. o In this way, a name can only be given to a memory location. It can be assigned values in two ways: Variable Initialization Assigning value by taking input 20 Variable Declaration (Cont’d) It can be perceived with the help of three components that are as follows: o Datatype: Type of data that can be stored in this variable. o Variable_name: Name given to the variable. o Value: It is the initial value stored in the variable. 21 General Rules for Naming Variables The general rules for naming variables are: Names can contain letters, digits, underscores, and dollar signs Names must begin with a letter Names should start with a lowercase letter and it cannot contain whitespace Names can also begin with $ and _. Names are case sensitive ("myVar" and "myvar" are different variables) Reserved words (like Java keywords, such as int or boolean) cannot be used as names 22 Types of Variables There are three types of variables in Java: o Local Variables o Instance Variables o Static Variables Also, In Java, there are different types of variables based on data types, for example: String: stores text, such as "Hello". String values are surrounded by double quotes int: stores integers (whole numbers) float: stores floating point numbers. char: stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes boolean: stores values with two states: true or false 23 Local Variables o Local Variables: A variable defined within a block or method or constructor is called a local variable. These variables are created when the block is entered, or the function is called and destroyed after exiting from the block or when the call returns from the function. The scope of these variables exists only within the block in which the variable is declared. i.e., we can access these variables only within that block. Initialization of the local variable is mandatory before using it in the defined scope. 24 Instance Variables o Instance variables: Instance variables are non-static variables and are declared in a class outside any method, constructor, or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifiers, for instance, variables. If we do not specify any access specifier, then the default access specifier will be used. Initialization of Instance Variable is not Mandatory. Its default value is 0 Instance Variable can be accessed only by creating objects. 25 Static Variables o Static Variables: Static variables are also known as Class variables. These variables are declared similarly as instance variables. The difference is that static variables are declared using the static keyword within a class outside any method constructor or block. Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create. Static variables are created at the start of program execution and destroyed automatically when execution ends. 26 Static Variables (Cont’d) Initialization of Static Variable is not Mandatory. Its default value is 0 If we access the static variable like the Instance variable (through an object), the compiler will show the warning message, which won’t halt the program. The compiler will replace the object name with the class name automatically. If we access the static variable without the class name, the compiler will automatically append the class name. 27 Syntax: Static and instance variables 28 Variable Initialization In Java, variable initialization refers to the process of assigning an initial value to a variable when it is declared or at some later point before it is used. Java requires variables to be initialized before they are accessed to avoid compilation errors. Types of Variable Initialization 1. Explicit Initialization Assigning a value to a variable at the time of declaration. int x = 10; // Explicit initialization String name = "John Doe"; 29 Variable Initialization (Cont’d) 2. Default Initialization (for Instance and Class Variables) Instance and static variables are automatically initialized to default values if not explicitly initialized. Local variables are not automatically initialized and must be explicitly initialized before use. o Default values: Numeric types (int, double, etc.): 0 char: '\u0000' (null character) boolean: false Reference types (String, custom objects): null public class Demo { int number; // Defaults to 0 boolean isActive; // Defaults to false String text; // Defaults to null } 30 Variable Initialization (Cont’d) 3. Static Initialization Block Used to initialize static variables with more complex logic. public class StaticInitialization { static int value; static { value = 42; // Static initialization block }} 4. Dynamic Initialization Initializing variables at runtime based on logic or inputs. int num = (int) (Math.random() * 100); // Dynamic initialization 31 Variable Initialization (Cont’d) 5. Initialization Using Constructors Instance variables can be initialized using constructors when an object is created. public class Person { String name; int age; // Constructor public Person(String name, int age) { this.name = name; this.age = age; } } // Example Person person = new Person("Alice", 30); 32 Examples of Variable Initialization public class InitializationExample { // Instance variable (default initialized) int instanceVar; // Static variable (default initialized) static double staticVar; public static void main(String[] args) { // Local variable (must be explicitly initialized) int localVar = 10; // Printing values InitializationExample example = new InitializationExample(); System.out.println("Instance Variable: " + example.instanceVar); // 0 System.out.println("Static Variable: " + staticVar); // 0.0 System.out.println("Local Variable: " + localVar); // 10 }} 33 Some Examples of Variables o Syntax type variableName = value; Where type is one of Java's types (such as int or String), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable. o To create a variable that should store text, look at the following example: Create a variable called name of type String and assign it the value "John": String name = "John"; System.out.println(name); 34 Some Examples of Variables o To create a variable that should store a number, look at the following example: Create a variable called myNum of type int and assign it the value 15: int myNum = 15; System.out.println(myNum); o declare a variable without assigning the value, and assign the value later: int myNum; myNum = 15; System.out.println(myNum); 35 Some Examples of Variables o Note that if a new value assign to an existing variable, it will overwrite the previous value: int myNum = 15; myNum = 20; // myNum is now 20 System.out.println(myNum); o A demonstration of how to declare variables of other types: int myNum = 5; float myFloatNum = 5.99f; char myLetter = 'D'; boolean myBool = true; String myText = "Hello"; 36 Display Variables o The println() method is often used to display variables. o To combine both text and a variable, use the + character: String name = "John"; System.out.println("Hello " + name); o + character can also use to add a variable to another variable: String firstName = "John "; String lastName = "Doe"; String fullName = firstName + lastName; System.out.println(fullName); 37 Display Variables (Cont’d) o For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables here): int x = 5; int y = 6; System.out.println(x + y); // Print the value of x + y From the example above, you can expect: x stores the value 5 y stores the value 6 Then println() method uses to display the value of x + y, which is 11 38 Declare Many Variables o To declare more than one variable of the same type, use a comma-separated list: int x = 5, y = 6, z = 50; System.out.println(x + y + z); 39 Java Identifiers o All Java variables must be identified with unique names. o These unique names are called identifiers. o Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). o Note: It is recommended to use descriptive names in order to create understandable and maintainable code: // Good int minutesPerHour = 60; // OK, but not so easy to understand what m actually is int m = 60; 40

Use Quizgecko on...
Browser
Browser