Programming 3 CSCI 2308 Chapter 4 Accessing Databases with JDBC PDF
Document Details
Uploaded by WellMadeSerpentine1417
Islamic University of Gaza
Dr. Abdelkareem Alashqar
Tags
Summary
This document is about accessing databases with JDBC, a key concept in Java programming, and discusses relational databases, tables, rows, columns, and other database-related concepts. The document provides information about the structured query language (SQL) and the design of JDBC, focusing on how to connect to databases, execute SQL statements, and manage scrollable result sets, metadata, and data display in JavaFX TableViews.
Full Transcript
Programming 3 CSCI 2308 Chapter 4 Accessing Databases with JDBC Topics Covered Introduction Structured Query Language (SQL) The Design of JDBC Registering the Driver Class Connecting to the Database Executing SQL Statements Scrollable & Updatable Resul...
Programming 3 CSCI 2308 Chapter 4 Accessing Databases with JDBC Topics Covered Introduction Structured Query Language (SQL) The Design of JDBC Registering the Driver Class Connecting to the Database Executing SQL Statements Scrollable & Updatable Result Sets Metadata Display Data In JavaFX TableView 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 2 Introduction A database is an organized collection of data. There are many different strategies for organizing data to facilitate easy access and manipulation. A Database Management System (DBMS) provides mechanisms for storing, organizing, retrieving and modifying data for many users. DBMS allows for the access and storage of data without concern for the internal representationCreated 19-Jan-25 of by:data. Dr. Abdelkareem Alashqar 3 Relational Database A relational database is a logical representation of data that allows the data to be accessed without consideration of its physical structure A relational database stores data in tables Tables are composed of rows, each describing a single entity (such as an employee) Rows are composed of columns in which values are stored. Primary key is a column (or group of columns) with a value (not null) that is unique for each row. Foreign key is a column in a table that matches the primary-key column in another table (referential integrity rule). 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 4 Entity-Relationship (ER) Diagram Shows the database tables (entities) and the relationships among them. Employee Employee_Proje Project EmployeeID 1 ∞ ct ∞ 1 ProjectID EName EmployeeID PName Department ProjectID Location Salary WorkedHours Primary Key Foreign Key 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 5 Employee Table: Sample Data ID Name Departmen Salary t Row { 2301 Ali 211 1200 2417 Huda 211 1400 4622 Maher 641 950 7810 Ahmad 431 1500 5196 Marwa 641 800 { { Primary Key Column 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 6 Structured Query Language (SQL) Structured Query Language (SQL) is a non- procedural language to access and manipulate the relational databases. Data Definition Language (DDL) Create, Alter, Drop database objects ̶ Tables, Views, Sequences, …etc Data Manipulation Language (DML) Insert, Update, Delete data to/from the tables Data Query Language (DQL) Select, to retrieve data from the tables 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 7 Structured Query Language (SQL) SQL keyword Description SELECT Retrieves data from one or more tables. FROM Tables involved in the query. Required in every SELECT. WHERE Criteria for selection that determine the rows to be retrieved, deleted or updated. Optional in a SQL query or a SQL statement. GROUP BY Criteria for grouping rows. Optional in a SELECT query. ORDER BY Criteria for ordering rows. Optional in a SELECT query. INNER JOIN Merge rows from multiple tables. INSERT Insert rows into a specified table. UPDATE Update rows in a specified table. DELETE Delete rows from a specified table. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 8 The Design of JDBC Java Database Connectivity (JDBC) is an application program interface (API). Java Application JDBC lets developers connect to a database and then use SQL. JDBC Driver Manager Using JDBC API enables developers Vender-Supported to change the underlying DBMS JDBC Driver without modifying the Java code that accesses the database. The ultimate goals of JDBC is to DB make possible the following: Enable Java applications to connect to database Enable programmers to manipulate 19-Jan-25 databases Created by: Dr. Abdelkareem Alashqar 9 JDBC Configuration Java programmers needs to gather a number of items before they can write the database program. Registering the Driver Class ̶ Each database has its own driver class that is registered by Class.forName() method Connecting to the Database ̶ Each database has its URL for Connection Executing SQL Statements ̶ Followed by fetching the ResultSet object 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 10 Registering the Driver Class Class.forName() method must be used to register the target database into the Java program. Class.forName("C") returns the Class object associated with the "C" class. Java developer must download the suitable driver,.jar file, and add it into the application reference libraries to be able to load the suitable driver. Examples Driver class for MySQL ̶ Class.forName("com.mysql.jdbc.Driver"); ̶ Class.forName("com.mysql.cj.jdbc.Driver"); //new Driver class for Oracle ̶ Class.forName("oracle.jdbc.driver.OracleDriver"); Driver class for MS SQL Server ̶ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDrive r"); 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 11 Connecting to the Database Java provides a special URL for each DBMS to enable the programmers to connect the desired database. Database URLs When connecting to a database, you must use various database-specific parameters such as host name, port number, and database name. The following table (next slide) contains the most used databases URLs 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 12 Connecting to the Database (cont.) RDBMS Database URL format MySQL jdbc:mysql://hostname:portNumber/databaseName ORACLE jdbc:oracle:thin:@hostname:portNumber:databaseName DB2 jdbc:db2:hostname:portNumber/databaseName PostgreSQL jdbc:postgresql://hostname:portNumber/databaseName Java DB/Apache jdbc:derby:dataBaseName (embedded) Derby jdbc:derby://hostname:portNumber/databaseName (network) Microsoft SQL jdbc:sqlserver://hostname:portNumber;databaseName=data Server BaseName Sybase jdbc:sybase:Tds:hostname:portNumber/databaseName 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 13 Connecting to the Database (cont.) Connecting the Database In Java program, database connection can be opened using Connection class (from the package java.sql) with code that is similar to the following example: String url = "jdbc:mysql://127.0.0.1:3306/myDB"; String username = "root"; String password = "toor"; Connection conn = DriverManager.getConnection(url,username,password); 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 14 Executing SQL Statements To execute a SQL statement, 1. Create a Statement object. To create statement objects, use the Connection object that you obtained from the call to DriverManager.getConnection() Connection conn = DriverManager.getConnection(…); Statement stat = conn.createStatement(); 2. Execute the Statement. To execute Statement call method which take SQL statement as string argument. ̶ ResultSet executeQuery(): to exectue DQL statement ̶ int executeUpdate(): to execute DDL/DML statement 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 15 Executing SQL Statements (cont.) To execute a SQL statement: First place the statement that you want to execute into a String. For example: String str = "UPDATE employee" + "SET salary = salary + salary*0.05" + " WHERE id = 7876"; Then call the suitable execute method of the Statement class. In the above example executeUpdate() is used. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 16 Executing SQL Statements (cont.) executeUpdate(str); It can execute SQL actions such as INSERT, UPDATE, and DELETE It also can execute DDL such as CREATE table and DROP table. It returns a count of rows that were affected by the SQL statement, or zero for statements that do not return a row count. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 17 Executing SQL Statements (cont.) executeQuery(str); It can execute SELECT queries. It returns an object of type ResultSet that be used to walk through the result one row at a time. ResultSet rs = stat.executeQuery("SELECT * FROM employee"); Fetching the ResultSet while ( rs.next() ) { //look at a row of the result set int eID = rs.getInt("id"); String eName = rs.getString("name"); double eSalary = rs.getDouble("salary"); System.out.println(eID+"\t "+eName+"\t "+eSalary); } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 18 Scrollable & Updatable Result Sets Connection method createStatement with two arguments receives the result set type and the result set concurrency. To obtain scrollable and updatable result sets from queries use the following Statement object: Statement stat = conn.createStatement(type, concurrency); type: determine the result set scrolling type ̶ Scrolling: let result set cursor to move backward as well as forward concurrency: determine if the result set can be used to update the database or not 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 19 Scrollable & Updatable Result Sets (cont.) The resultset type values: TYPE_FORWARD_ONLY The result set is NOT scrollable (default). TYPE_SCROLL_INSENSITI The result set is scrollable but NOT sensitive to VE database changes. TYPE_SCROLL_SENSITIV The result set is scrollable and sensitive to database E changes The resultset concurrency values: CONCUR_READ_ONLY The result set CANNOT be used to update the database (default). CONCUR_UPDATABLE The result set CAN be used to update the database. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 20 Scrollable & Updatable Result Sets (cont.) Example: Statement stat = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); After executing the query: ResultSet rs = stat.executeQuery(query) rs is a scrollable result set and it has a cursor that indicates the current position. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 21 Scrollable & Updatable Result Sets (cont.) Now, the cursor can be moved backward or forward by a number of rows by using the relative() method rs.relative(n); If n is positive, the cursor moves forward. If n is negative, it moves backward. If n is zero, the call has NO effect. If n outside the current set of rows then the cursor does not move and the method returns false. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 22 Scrollable & Updatable Result Sets (cont.) Alternatively, the cursor can be moved backward or forward by a number of rows by using the absolute() method to set the cursor to a particular row number rs.absolute(n); To move to the first row n = 1, and to move the last row n = -1. To get the current row number with the call getRow() method int currentRow = rs.getRow(); If the return value is 0, the cursor is not currently on a row It is either before the first row or after the last row. The convenience methods: first() & last() are also used. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 23 Scrollable & Updatable Result Sets (cont.) ResultSet.CONCUR_UPDATABLE means that the result set data can be edit and the changes automatically reflected in the database. Example 1: To raise (update) the salary for some employees String query = "SELECT * FROM employee"; ResultSet rs = stat.executeQuery(query); while (rs.next()) { if (...) { double increase =... ; double s = rs.getDouble("salary"); rs.updateDouble("salary", s + increase); rs.updateRow(); } } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 24 Scrollable & Updatable Result Sets (cont.) Example 2: Add a new row to the database rs.moveToInsertRow(); rs.updateInt("id", eID); rs.updateString("name", eName); rs.updateString("department", eDepartment); rs.updateDouble("salary", eSalary); rs.insertRow(); Example 3: To delete a row under the cursor rs.deleteRow(); The deleteRow() method immediately removes the row from both the result set and 19-Jan-25 the database. Created by: Dr. Abdelkareem Alashqar 25 Metadata JDBC can give additional information about the structure of a database and its tables. It can give a list of the tables in a particular database or the column names and types of a table. To find out more about the database, you request an object of type DatabaseMetaData from the database connection. DatabaseMetaData meta = connection.getMetaData(); 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 26 Metadata (cont.) ResultSetMetaData getMetaData() Gives the metadata associated with the current ResultSet columns. ̶ ResultSet rs = stat.executeQuery("SELECT * FROM employee"); ̶ ResultSetMetaData rsMetaData = rs.getMetaData(); int getColumnCount() Returns the number of columns in the current ResultSet object ̶ int ColumnsCount = rsMetaData.getColumnCount(); String getColumnName(int column) Gives the column name associated with the column index specified ̶ String columnName = rsMetaData.getColumnName(i); String getColumnClassName(int column) Gives the column datatype associated with the column index specified ̶ String columnType = rsMetaData.getColumnClassName(i); 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 27 Display Data in JavaFX TableView TableView is a control that displays data in rows and columns in a two-dimensional grid TableView, TableColumn, and TableCell are used to display and manipulate a table. TableView displays a table. TableColumn defines the columns in a table. TableCell represents a cell in the table. Creating a TableView is a multistep process. 1. Create an instance of TableView and associate data with the TableView 2. Create columns using the TableColumn class and set a column cell value factory to specify how to populate all cells within a single TableColumn 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 28 TableView App Example public void start(Stage primaryStage) throws Exception { TableView tblView = new TableView(); TableColumn tcID = new TableColumn("ID"); tcID.setCellValueFactory(new PropertyValueFactory("id")); TableColumn tcName = new TableColumn("Name"); tcName.setCellValueFactory(new PropertyValueFactory("name")); TableColumn tcDept = new TableColumn("Department"); tcDept.setCellValueFactory(new PropertyValueFactory("department")); TableColumn tcSalary= new TableColumn("Salary"); tcSalary.setCellValueFactory(new PropertyValueFactory("salary")); tblView.getColumns().addAll(tcID,tcName,tcDept,tcSalary); Continued … 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 29 TableView App Example (cont.) ObservableList employees = FXCollections.observableArrayList(); public class Employee { private Integer id; private String name; Button buttonView = new Button("Show"); private String department; buttonView.setOnAction(event -> { private Double salary; ResultSet rs; public Student() { }... //Setters and Getters employees.clear(); } try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ company","root","toor"); Statement = connection.createStatement(); rs = statement.executeQuery("Select * From Employee"); while(rs.next()){ Employee employee = new Employee(); employee.setID(rs.getInt("id")); Continued … 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 30 TableView App Example (cont.) employee.setName(rs.getString("name")); employee.setDepartment(rs.getString("department")); employee.setSalary(rs.getDouble("salary")); employees.add(employee); } } catch (SQLException ex) { ex.printStackTrace(); } tableView.setItems(employees); }); //End of button action VBox vBox = new VBox(10, tableView, buttonView); vBox.setAlignment(Pos.CENTER); vBox.setPadding(new Insets(10, 10, 10, 10)); Scene = new Scene(vBox, 300, 250); primaryStage.setTitle("TableView App"); primaryStage.setScene(scene); primaryStage.show(); 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 31 Display Data in JavaFX TableView The program creates a TableView. The TableView class is a generic class whose concrete type is Employee. Therefore, this TableView is for displaying Employee. The table data is an ObservableList< Employee >. The program creates a TableColumn for each column in the table. A PropertyValueFactory object is created and set for each column.This object is used to populate the data in the column. The PropertyValueFactory class is a generic class. ̶ S is for the class displayed in the TableView, and ̶ T is the class for the values in the column. The PropertyValueFactory object associates a property in class S with a column. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 32 Display Data in JavaFX TableView The program creates an ObservableList and associates it with the TableView. This ObservableList is filled with data from the table "employee" of "company" database. When you create a table in a JavaFX application, it is a best practice to define the data model in a class. The Employee class defines the data for TableView. Each property in the class defines a column in the table. This property should be defined as binding property with the getter and setter methods for 19-Jan-25 the value. Created by: Dr. Abdelkareem Alashqar 33 That’s it! 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 34 Programming 3 CSCI 2308 Chapter 7 Java Multithreading Topics Covered Introduction Concurrency vs Parallelism What is a Thread? Threads and Processes Thread Properties Thread States Thread & Runnable Synchronization Threads Pool & Executers Callable Interface 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 2 Introduction Multitasking: Multitasking refers to a computer's ability to perform multiple jobs concurrently سفن تقولا ̶ More than one program are running concurrently on the same machine Multitasking is divided into two types: Process-based: in which two or more programs runs concurrently. ̶ For example user can run Windows Calculator and Notepad at the same time. Thread-based: A single program can perform two or more tasks simultaneously. اعم ̶ For example MS Word can print while formatting is being done. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 3 Concurrency vs Parallelism Concurrency Parallelism 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 4 What is a Thread? A thread is a basic processing unit to which an operating system allocates صصخيprocessor time, and more than one thread (multithreading) can be executing code inside a process. Multithreading enables programmer to write a very efficient programs that make maximum use of CPU, because idle time لا تقصخواcan be kept to minimum. This is especially important for the interactive networked application because idle time is 19-Jan-25common. Created by: Dr. Abdelkareem Alashqar 5 Threads and Processes 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 6 Thread Properties Every Java program has at least one thread, the thread that executes the Java program. It is created when main method has been invoked in the desired Java class. Thread properties: A thread can be run ̶ It can be ready to run as soon as it begins execution. A running thread can be suspended (pause) which temporarily suspends its activity and it can be resumed. A thread can be blocked when waiting for a resource. ̶ Sleeps for a while At any time a thread can be terminated, which means the thread stops. ̶ Once stopped it cannot be resumed. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 7 Thread States Every Thread has a state and a Thread can be in one of the following: New: A state in which a thread has NOT been started. Runnable: A state in which a thread is executing. Blocked: A state in which a thread is waiting for a lock to access an object. Waiting: A state in which a thread is waiting indefinitely تجا ريغ امخمfor another thread to perform an action. Timed_waiting: A state in which a thread is waiting for up to a specified period of time for another thread to perform an action. Terminated: A state in which a thread has exited. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 8 Thread States 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 9 Creating Thread There are two ways to create our own Thread object: Sub-classing the Thread class and instantiating a new object of that class. ̶ This means extends the java.lang.Thread class Implementing the Runnable interface ̶ This means implements the java.lang.Runnable interface In both cases the run() method must be implemented. Since multiple inheritance doesn't allow us to extend more than one class at a time, implementing the Runnable interface may help us in thisCreated 19-Jan-25 situation. by: Dr. Abdelkareem Alashqar 10 Creating Thread Once Thread object has been created, its start method can be called to start the thread. When a thread is started, its run method is executed. Once the run method returns or throws an exception, the thread dies and will be garbage-collected. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 11 Thread & Runnable public class MyThread extends Thread { private int sleep; @Override public void run() { try { super.run(); for (int i = 0; i < 100; i++) { System.out.println(this.getName() +" "+i); Thread.sleep(sleep); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public MyThread(int sleep) { super(); this.sleep = sleep; } } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 12 Thread & Runnable public class MyRunnable implements Runnable { private int sleep; @Override public void run() { try { for (int i = 0; i < 100; i++) { System.out.println( "Runnable "+i); Thread.sleep(sleep); } } catch (InterruptedException e) { e.printStackTrace(); } } public MyRunnable(int sleep) { super(); this.sleep = sleep; } } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 13 Thread & Runnable MyThread t1 = new MyThread(100); t1.setName("t1"); t1.setPriority(Thread.MIN_PRIORITY); MyThread t2 = new MyThread(100); t2.setName("t2"); t2.setPriority(Thread.MAX_PRIORITY); //MyRunnable r1 = new MyRunnable(200); Thread t3 = new Thread(new MyRunnable(200)); t1.start(); t2.start(); //r1.run(); t3.start(); 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 14 Synchronization Synchronization in java is the capability to control the access of multiple threads to any shared resource. The synchronization is mainly used to to prevent thread interference. انم لخت ا to prevent consistency problem. تقملمما Mutual Exclusive, a thread synchronization, helps keep threads from interfering with one another while sharing data. This can be done by three ways in java: by synchronized method by synchronized block by static synchronization 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 15 Method Synchronization When a thread invokes a synchronized method, it automatically acquires the lock for that object (method) and releases it when the thread completes its task. public synchronized String getData(File f) { String s = ""; try { Scanner sc = new Scanner(f); while (sc.hasNextLine()) s += sc.nextLine()+"\n"; } catch (FileNotFoundException e) { e.printStackTrace(); } return s; } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 16 Block Synchronization Synchronized block can be used to perform synchronization on any specific resource of the method. Synchronized block is used to lock an object for any shared resource. Scope of synchronized block is smaller than the method. public void getData() { File f = new File("testfile.txt"); synchronized (f) { // synchronized (this) try { Scanner sc = new Scanner(f); while (sc.hasNextLine()) System.out.println(sc.nextLine()); } catch (FileNotFoundException e) { e.printStackTrace(); } } } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 17 Static Synchronization Making a static method as synchronized, the lock will be on the class not on object. Problem without static synchronization, there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock. public static synchronized String getData(File f) { String s = ""; try { Scanner sc = new Scanner(f);... 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 18 Threads Pool & Executers A thread pool is an instance of ExecutorService class. With an ExecutorService, you can submit task that will be completed in the future. There are five types of thread pools which can be created with the Executors class: 1. Single Thread Executor : A thread pool with only one thread. So all the submitted tasks will be executed sequentially. Executors.newSingleThreadExecutor() 2. Cached Thread Pool : A thread pool that creates as many threads it needs to execute the task in parrallel. The old available threads will be reused for the new tasks. If a thread is not used during 60 seconds, it will be terminated and removed from the pool. Executors.newCachedThreadPool() 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 19 Threads Pool & Executers … 3. Fixed Thread Pool : A thread pool with a fixed number of threads. If a thread is not available for the task, the task is put in queue waiting for an other task to ends. Executors.newFixedThreadPool() 4. Scheduled Thread Pool : A thread pool made to schedule future task. Executors.newScheduledThreadPool() 5. Single Thread Scheduled Pool : A thread pool with only one thread to schedule future task. Executors.newSingleThreadScheduledExecutor() 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 20 Threads Pool & Executers public static void main(String[] args) { ExecutorService s = Executors.newFixedThreadPool(3); for (int i =1; i = (greater Checks if the value of left operand is greater (A >= B) is not than or equal than or equal to the value of right operand, if true. to) yes then condition becomes true. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 12 Checks if the value of left operand is less than Basic Programming Concepts (cont.) Bitwise Operators Operator Description Example: A=60 B=13 Binary AND Operator copies a bit to the result if it (A & B) will give 12 which & (bitwise and) exists in both operands. is 00001100 Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which | (bitwise or) operand. is 00111101 Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which ^ (bitwise XOR) operand but not both. is 00110001 (~A ) will give -61 which ~ (bitwise Binary Ones Complement Operator is unary and is 11000011 in 2's compliment) has the effect of "flipping" bits. complement form due to a signed binary number. Binary Left Shift Operator. The left operands value A 2 will give 15 which >> (right shift) is moved right by the number of bits specified by is 00001111 the right operand. Shift right zero fill operator. The left operands value >>>19-Jan-25 (zero fill is moved right by the number Created of bits specified by: Dr. Abdelkareem Alashqarby A >>>2 will give 15 which 13 right shift) the right operand and shifted values are filled up is 00001111 Basic Programming Concepts (cont.) Logical Operators Operator Description Example: A=1 B=0 Called Logical AND operator. If both the && (logical and) operands are non-zero, then the condition (A && B) is false becomes true. Called Logical OR Operator. If any of the || (logical or) two operands are non-zero, then the (A || B) is true condition becomes true. Called Logical NOT Operator. Use to reverse the logical state of its operand. If ! (logical not) !(A && B) is true a condition is true then Logical NOT operator will make false. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 14 Basic Programming Concepts (cont.) Assignment Operators Operat Description Example or Simple assignment operator. Assigns values from right C = A + B will assign value of A + B = side operands to left side operand. into C Add AND assignment operator. It adds right operand to += C += A is equivalent to C = C + A the left operand and assign the result to left operand. Subtract AND assignment operator. It subtracts right -= operand from the left operand and assign the result to C -= A is equivalent to C = C – A left operand. Multiply AND assignment operator. It multiplies right *= operand with the left operand and assign the result to C *= A is equivalent to C = C * A left operand. /= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left C /= A is equivalent to C = C / A operand. Modulus AND assignment operator. It takes modulus %= using two operands and assign the result to left C %= A is equivalent to C = C % A operand. > 2 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 15 Basic Programming Concepts (cont.) The Conditional (Ternary) Operator Operato Description Example r Uses the boolean value of one expression int x = 2; ?: to decide which of two other expressions String result = x > 1 ? should be evaluated. "a" : "b"; 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 16 Basic Programming Concepts (cont.) Operators and its Precedence Operators Associativity []. () (method call) Left to right ! ~ ++ -- + (unary) – (unary) () (cast) new Right to left */% Left to right +- Left to right > >>> Left to right < >= instanceof Left to right == != Left to right & Left to right ^ Left to right | Left to right && Left to right || Left to right ?: Right to left = += -= *= /= %= &= |= ^= = >>>= Right to left 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 17 Basic Programming Concepts (cont.) Arrays Array is a data structure that stores a collection of values of the same type. // create an array of integers int anArray[] = new int; anArry = 20; int[] anArray = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; You access each individual value through an integer index. int[] a = new int; for (int i = 0; i < 100; i++) a[i] = i; // fills the array with 0 to 99 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 18 Basic Programming Concepts (cont.) Arrays Multidimensional arrays use more than one index to access array elements. They are used for tables and other more complex arrangements. int[][] a = new int; for (int i = 0; i < 100; i++) for (int j = 0; j < 100; j++) a[i][j] = i; // fills the array rows with 0 to 99 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 19 Basic Programming Concepts (cont.) Reference datatype: Strings Conceptually, Java strings are sequences of Unicode characters. String e = ""; // an empty string String greeting = "Hello"; Each quoted string is an instance of the String class: Some popular functions: length() charAt(n) indexOf(s) "+" sign to concatenate two strings substring(s, l) equals(), equalsIgnoreCase() startWith(), endWith() split() 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 20 Basic Programming Concepts (cont.) Control Flow if statement: switch Statement switch (choice) { if (condition) case 1: statement/block... else break; statement/block case 2:... break; default: //bad input... break; } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 21 Basic Programming Concepts (cont.) Control Flow for() statement: do…while() Statement for(var. ini.; con.; step) do Statement/block Statement/block while(condition); while() Statement while(condition) Statement/block 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 22 Java enum An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. E.g.: directions (values of NORTH, SOUTH, EAST, and WEST). Because they are constants, the names of an enum type's fields are in uppercase letters. public enum Directions { NORTH, SOUTH, EAST, WEST} public class Test{ public static void main(String[] args) { Directions dirc = Directions.NORTH; } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 23 Java enum (cont.) Another Example public enum Grade { public class Test{ A(2000), B(1500), public static void main(String[] args) C(1000), { D(500); Grade grade = Grade.A; //int salary = private int val; Grade.A.salary(); int salary = Grade(int val){ grade.salary(); this.val = val; } } public int salary(){ return val; } } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 24 Wrapper Classes Wrapper class in java provides the mechanism to convert primitive into object and object into primitive. Auto-boxing and auto-unboxing feature converts primitive into object and object into primitive automatically and vice-versa. Wrapper classes allow programmer to parse primitive data from String through the pre- defined methods. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 25 Wrapper Classes (cont.) public static void main(String args[]) { Primitive Wrapper // boxes int to an Integer object Type class Integer x = 5; // unboxes the Integer to a int boolean Boolean x = x + 10; char Character System.out.println(x); byte Byte //parsing data from String short Short double pi = Double.parseDouble("3.14"); } int Integer long Long float Float 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 26 Functions The function in Java is called method. A method is a named sequence of code that can be invoked by other Java code. A method takes some parameters, performs some computations تاساسحand then optionally returns a value (or object). Methods can be used as part of an expression statement. public float convertCelsius(float tempC) { return( ((tempC * 9.0f) / 5.0f) + 32.0 ); } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 27 Functions (cont.) A method signature specifies: The name of the method. The type and name of each parameter. The type of the value (or object) returned by the method. The checked exceptions thrown by the method. Various method modifiers. modifiers type name ( parameter list ) [throws public float convertCelsius (float tCelsius ) {} exceptions public ] boolean setUserInfo ( int i, int j, String name ) throws IndexOutOfBoundsException {} 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 28 Object Oriented Programming Object-oriented programming (or OOP for short) having replaced the "structured" procedural programming techniques The key to being most productive in OOP is to make each object responsible for carrying out a set of related tasks. Vocabulary of OOP A class is the template or blueprint from which objects are actually made. When you construct an object from a class, you are said to have created an instance of the class. Encapsulation is nothing more than combining data and behavior in one package and hiding the implementation of the data from the user of the object. ̶ The data in an object are called its instance fields. ̶ The procedures that operate on the data are called its methods. ̶ The instance fields values is current state of the object. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 29 Object Oriented Programming (cont.) UML Class to Java Code UML: Unified Modeling Java Code Language public class Rectangle { Rectangle private double width; private double length; - width : double public void setWidth(double w) { width = w; - length : double } public void setLength(double len) + setWidth(w : double) : void { length = len; + setLength(len : double): void } public double getWidth() + getWidth() : double { return width; + getLength() : double } + getArea() : double public double getLength() { return length; } public double getArea() { return length * width; } } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 30 Object Oriented Programming (cont.) Java Access Modifiers Java access modifiers are used to apply information hiding concepts. default (no private protected Public modifier) Same Class Yes Yes Yes Yes Same package Yes No Yes Yes subclass Same package Yes No Yes Yes non-subclass Different package No No Yes Yes subclass Different package No No No Yes non-subclass 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 31 Object Oriented Programming (cont.) static Modifier When a variable is declared with the keyword static, its called a class variable. Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables. All instances share the same copy of the variable. A class variable can be accessed directly with the class, 19-Jan-25 without the need to create a32 Created by: Dr. Abdelkareem Alashqar Object Oriented Programming (cont.) static Modifier When a method is declared with the keyword static, then it will belong to the class and not to the object(instance). It access only static data. It can not access non-static data (instance variables) It can call only other static methods It not call a non-static method from it. It can be accessed directly by the class name and doesn’t need any object It cannot refer to this or super keywords in anyway 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 33 Object Oriented Programming (cont.) final Keyword final variable final variables are nothing but constants. ̶ We cannot change the value of a final variable once it is initialized. final method A final method cannot be overridden. ̶ this means even though a sub class can call the final method of parent class without any issues but it cannot override it. We cannot extend a final class. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 34 Object Oriented Programming (cont.) Constructor A constructor has the same name as the class. A class can have more than one constructor. A constructor can take zero, one, or more parameters. A constructor has no return value. A constructor is always called with the new operator. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 35 Object Oriented Programming (cont.) Inheritance Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. extends is the keyword used to inherit the properties of a class. The figure in next slide shows the syntax of extends keyword. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 36 Object Oriented Programming (cont.) Inheritance 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 37 Object Oriented Programming (cont.) Inheritance PartTimeEmploy FullTimeEmploy Employee ee ee No No No Name Name Name Job Job Job WorkingHour HireDate HourRate Grade set... set... set... get… get… get… public class Employee { … public class FullTimeEmployee extemds Employess { … public class PartTimeEmployee extemds Employess { … 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 38 Object Oriented Programming (cont.) Overriding Overriding means to override the functionality of an existing method. The argument list should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. The access level cannot be more restrictive than the overridden method's access level. ̶ For example: If the superclass method is declared public then the overriding method in the sub class cannot be either private or protected. A method declared private cannot be overridden. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. Constructors cannot be overridden. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 39 Object Oriented Programming (cont.) Abstract Class A class which contains the abstract keyword in its declaration is known as abstract class. Abstract classes may or may not contain abstract methods ̶ i.e., methods without body ( public void get(); ) If a class has at least one abstract method, then the class must be declared abstract. If a class is declared abstract, it cannot be instantiated. To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.class Employee {... public abstract 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 40 Object Oriented Programming (cont.) Polymorphism Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any instance of sub-class is an instance the super-class is-a relationship 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 41 Object Oriented Programming (cont.) Interface An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. public interface NameOfInterface { // Any number of final, static fields // Any number of abstract method declarations } An interface does not contain any constructors and cannot be instantiated. All of the methods in an interface are abstract. The instance fields must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces. public class SubClass implements InterfaceClass {... 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 42 Exception Handling With exception handling a program can continue executing, rather than terminating, after dealing with a problem (run-time error). Exceptions are thrown (i.e., the exception occurs) by a method detects a problem and is unable to handle it. Stack trace: information displayed when an exception occurs and is not handled. In Java, all exceptions are represented by classes. All exception classes are derived from a class called Throwable 19-Jan-25 and Created by: Dr. Abdelkareem they constitute a43 Alashqar The Exception Hierarchy 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 44 Checked & Unchecked Exceptions Checked Exceptions: Inherit from Exception class but not from RuntimeException Compiler enforces catch-or-declare requirement Unchecked Exceptions: Inherit from class RuntimeException or class Error. Compiler does not check code to see if exception caught or declared. So, the programmer will does. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 45 The Main Block of Exception Handling At the core of exception handling are try and catch. finally is optional. try { // block of code to monitor for errors } catch (ExcepType1 exOb) { // handler for ExcepType1 } catch (ExcepType2 exOb) { // handler for ExcepType2 } finally{ //must executed code }... 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 46 throw & throws throw clause use to throw exception manually when a certain error detection. Example: if (amount > balance) throw new IllegalArgumentException("Amount exceeds balance"); balance = balance - amount The throws clause tells the caller of the method that it may encounter an Exception. Then the caller needs to handle the exception, or declare that the exception may be thrown. Example: public static int divid(int x, int y) throws Exception{ return x / y; } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 47 File I/O Data stored in variables and arrays is temporary It’s lost when a local variable goes out of scope or when the program terminates. For long-term retention of data, computers use files. Computers store files on secondary storage devices hard disks, flash drives, DVDs and more. Data maintained in files is persistent اتسم data because it exists beyond the duration of program execution. Text/Binary file: Text: Designed to be read by human. Binary: Designed to be read by computer (more efficient). 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 48 Text File Processing Write/read to/from text file public class TestDataText { public static void main(String[] args) throws IOException{ File file = new File("data.txt"); PrintWriter output = new PrintWriter(file); output.print("Ahamd CS 87.3"); output.close(); Scanner input = new Scanner(file); while(input.hasNext()) System.out.println(input.nextLine()); input.close(); } } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 49 Binary I/O Classes 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 50 Binary File Processing Write/Read to/from binary file public class TestDataStream { public static void main(String[] args) throws IOException{ DataOutputStream output = new DataOutputStream( new FileOutputStream("stud.dat")); output.writeUTF("Ahmad"); output.writeUTF("CS"); output.writeDouble(87.3); output.close(); DataInputStream input = new DataInputStream( new FileInputStream("stud.dat")); System.out.println(input.readUTF() + " " + input.readUTF() + " " + input.readDouble()); input.close(); } } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 51 Collections A collection is a data structure, actually an object that can hold references to other objects. Collections cannot manipulate variables of primitive types. They can manipulate objects of the type-wrapper classes, because every class ultimately derives from Object. Some Collections Framework Interfaces: List, Set, Map, Queue Each framework can be implemented by several classes. For example, List interface is implemented by ArrayList, LinkedList and Vector. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 52 ArrayList Processing public class ListColors { public static void main(String[] args) { List colors = new ArrayList(); colors.add("Red"); colors.add("Green"); colors.add("Blue"); for(String color : colors) System.out.println(color); } } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 53 Java lambda and Functional Programming Java lambda expressions are new in Java 8 and they are Java's first step into functional programming. A Java lambda expression is a function which can be created without belonging to any class, and can be passed around as if it was an object and executed on demand. Java lambda expressions are commonly used to implement simple event listeners / callbacks, or in functional programming with 19-Jan-25 the Java Streams API. Created by: Dr. Abdelkareem Alashqar 54 Java lambda and Functional Programming (cont.) Prior to Java SE 8, Java supported three programming paradigms: procedural programming, object-oriented programming, and generic programming. Java SE 8 adds: functional programming. Lambda expression anonymous method that is shorthand notation for implementing a functional interface. Can be used anywhere functional interfaces are expected. 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 55 Functional Interfaces: Example public class LambdaApp { public static void main(String[] args) { Operation operation1 = (num1,num2) -> {return num1 + num2; }; System.out.println(operation1.add(7, 5)); Operation operation2 = (str1,str2) -> { str1 = str1.substring(2); str2 = str2.substring(3, 7); Lambda return str1 + str2; expression }; System.out.println(operation2.add ("abcdefg","0123456789")); } private interface Operation{ T add(T x, T y); functional } interface } 19-Jan-25 Created by: Dr. Abdelkareem Alashqar 56 That’s it!