Java Programming Introduction PDF
Document Details
Uploaded by LightHeartedSwamp
Tags
Summary
This document introduces Java programming, focusing on object-oriented programming (OOP) concepts. It provides an overview of OOP history, elements, and how to structure solutions to problems.
Full Transcript
سنتعاون مع ًا خالل هذا الفصل دلراسة مقرر الربجمة غرضية التوجه Reference Java How to Program Deitel & Deitel 9th Edition (6th+ editions are ok) 2 Lecture 1 Outline History of OOP Concept of Object Oriente...
سنتعاون مع ًا خالل هذا الفصل دلراسة مقرر الربجمة غرضية التوجه Reference Java How to Program Deitel & Deitel 9th Edition (6th+ editions are ok) 2 Lecture 1 Outline History of OOP Concept of Object Oriented Programming Object Oriented Approach Object & Classes Some of OOP Languages Java Language History of OOP prof. Alan Kay Kay is one of the fathers of the idea of (OOP), which he named. From To Biological cell Programming world Concept of Object Oriented Programming Object-oriented programming (OOP) is a programming paradigm that uses “Objects “and their interactions to design applications. OOP is an approach to program organization and development. Concept of Object Oriented Programming OOP allows us to decompose a problem into number of entities called Objects and then build Attributes(data or variables) and Methods (functions) around these entities. Example: Think about a Chess board program Name solution space entities Elephant King Entities Soldier Etc. Object Oriented Approach Problem Space the place where the problem exists such as a business Solution Space the place where you’re implementing that solution such as a computer Establish Problem Solution The space space Association Object Oriented Approach OOP allows you to describe the problem by the problem terms itself, rather than by the computer terms. The alternative to modeling the machine is to model the problem you’re trying to solve When you read the code, you’re reading words that also express the problem. Object & Classes Object is a software module that has state and behavior. is contained within its is implemented member variables through its methods Objects interact with one another by sending each other messages. Object & Classes OOP programs will create many different objects from templates known as Classes. is an instance of a class Object’s object class is the object's type The OOP languages environment comes with many classes that you can use in Or you can write your programs your own Some of OOP Languages Most modern programming languages are supporting the OOP concept in its app, and the most famous are: C++ , Microsoft’s Visual Basic, Java , C# (based on C++ and Java, and developed for integrating the Internet and the web into computer applications). Java Language What is Java? Java is a popular programming language. It is used for: Mobile applications (specially Android apps) Desktop applications Web applications Games Database connection And much, much more! Java Language Why use Java? Java is an object oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs. Java works on different platforms (Windows, Mac, Linux, etc.) Java Language A key goal of Java is to be able to write programs that will run on a great variety of computer systems and computer-control devices. This is called “write once, run anywhere” Java Language This is satisfied by JVM(Java Virtual Machine). A virtual machine (VM) is a software application that simulates a computer. Java Language Java programs go through two compilation phases: i. One in which source code is translated into bytecodes (for portability across JVMs on different computer platforms) ii. A second in which, during execution, the bytecodes are translated into machine language for the actual computer on which the program executes. Java Language At the next Lecture Basic Structure of Java program Lecture 2 Outline Basic Structure of Java program Java Classes/Objects Java Class Attributes Java constructor Java Packages Java Data Type Java Operators Java I/O Basic Structure of Java program As we say Java is an object oriented language, so: Every Java program consists of at least one class that you define. Every line of code that runs in Java must be inside a class class keyword introduces a class declaration and is immediately followed by the class name. Basic Structure of Java program The general syntax of class in java is:.... these points class Name refer to { instructions like //Attributes import packages //Methods public static void main(String args[]) { //some of statements } } The name of the java file must match the class name. When saving the file, save it using the class name and add ".java" to the end of the filename Java Classes/Objects To create a class in java, use the keyword class. public class Main{ int x=5; } To create an object of Main class, specify the class name, followed by the object name, and use the keyword new public static void main(String [ ] args) { Main myobj = new Main(); } Java Class Attributes class attributes are variables within a class. Example: Create a class called "Main" with two integer attributes: x and y: public class Main { int x ; int y; } Java Class Attributes You can access attributes by creating an object of the class, and by using the dot syntax (.) Example: Create an object called "myObj" and print the value of x: public class Main { int x = 5; public static void main(String[] args) { Main myObj = new Main(); System.out.println(myObj.x); } } Java Class Attributes OR You can assign attribute You can override existing values values public class Main { public class Main { int x; int x = 10; public static void public static void main(String[] args) { main(String[] args) { Main myObj = new Main(); Main myObj = new Main(); myObj.x = 40; myObj.x = 25; System.out.println(myObj.x); System.out.println(myObj.x); } } } } Java constructor A constructor in Java is a special method that is used to initialize objects. the constructor name must match the class name, and it cannot have a return type (like void). The constructor is called when the object is created. Java constructor All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. Constructors can also take parameters, which is used to initialize attributes. Java constructor Example: Create a constructor: public class Main { int x; public Main() { x = 5; } public static void main(String[] args) { Main myObj = new Main(); // Create an object of class Main (This will call the constructor) System.out.println(myObj.x); } } Java Packages A package in Java is used to group related classes. The Java API is a library of prewritten classes. The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package. To use a class or a package from the library, you need to use the import keyword Java Packages Import a Class: If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code: import java.util.Scanner; // import a single class In the example above, java.util is a package, while Scanner is a class of the java.util package. To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class. Java Packages Import a Package: There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes. To import a whole package, end the sentence with an asterisk sign (*). The following example will import ALL the classes in the java.util package: import java.util.*; //import the whole package Java Data Type Data types are divided into two groups: Primitive data types - includes byte, short, int, long, float, double, boolean and char Non-primitive data types - such as String, Arrays and Classes Java Operators Operators are used to perform operations on variables and values. Java divides the operators into the following groups: Arithmetic operators Assignment operators Comparison operators Logical operators Java Operators Java I/O Java I/O (Input and Output) is used to process the input and produce the output. Java uses the concept of a stream to make I/O operation. A stream is a sequence of data. The data can come from many sources, such as the user at the keyboard or a file on disk. Java I/O In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow. We’ll care about two abstract classes of Streams: InputStream: is used to read data from a source. OutputStream: is used for writing data to a destination. Java I/O The previous classes are in java.io package, which contains all the classes required for input and output operations. When a Java program begins executing, in fact, it creates three stream objects that are associated with devices: System.in (standard input object), System.out (standard output object) and System.err. Java I/O System.out.println(“hello”); out is a (public println() is an is a built-in static final) overloaded class name variable of type method defined in PrintStream the PrintStream declared in the class. System class Java I/O Java Scanner Class: of the java.util package is used to read input data from different sources like input streams, files. A Scanner enables a program to read data (e.g., numbers and strings) for use in a program. Before using a Scanner, you must create it and specify the source of the data. Java I/O Enter your name: Adam import java.util.Scanner; My name is Adam class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // takes input from the keyboard String name = input.nextLine(); System.out.println("My name is " + name); // prints the name }//end main function }//end class Main Java I/O Java Scanner Methods to Take Input: Examples Example 1: Our next application reads (or inputs) two integers typed by a user at the keyboard, computes their sum and displays it. import java.util.Scanner; public class Addition { public static void main( String[ ] args ) { Scanner input = new Scanner( System.in ); int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 Examples System.out.print( "Enter first integer: " ); number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); number2 = input.nextInt(); // read second number from user sum = number1 + number2; // add numbers, then store total in sum System.out.print( "Sum is " + sum ); // display sum } // end method main } // end class Addition Examples Example 2: write a program in java language to display the following shape: * ** *** **** what about a general case? Examples public class displaystars{ public static void main( String[ ] args ) { for(int i=1;i0; j--) System.out.print(“*”); System.out.println(); } }//end main }//end class Notice Also check out: java if – else java switch java while-loop java for – loop java Break/Continue java arrays Homework write a program in java language to display the following shape: * ** *** **** what about a general case? At the next Lecture Java String Java Math Java Methods Java Recursion Lecture 3 Outline Java Methods Java Recursion Java String Java Math Java Methods A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions. The idea of methods appears in all programming languages, although sometimes it goes under the name functions and sometimes under the name procedures. Java Methods Why use methods? To reuse code: define the code once, and use it many times. A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). J a va provides some pre-defined methods, such as println() but you can also create your own methods to perform certain actions. Java Methods Within a class, we can refer directly to its member variables: class Box { double width, height, depth; void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); }} Java Methods Parameters increase generality and applicability of a method: 1) method without parameters int square() { return 10*10; } 2) method with parameters int square(int i) { return i*i; } Parameter: a variable receiving value at the time the method is invoked. Argument: a value passed to the method when it is invoked. Java Recursion Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve. Java Recursion Example: Use recursion to add all positive integer of the numbers up to k. public class Main { public static void main(String[] args) { int result = sum(10); System.out.println(result); } public static int sum(int k) { if (k > 0) { return k + sum(k - 1); } else { return 0; } } } Java Recursion J u s t as loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion. Infinite recursion is when the function never stops calling itself. Every recursive function should have a Stopping condition, which is the condition where the function stops calling itself. In the previous example, the stopping condition is when the parameter k becomes 0. Java Recursion The Fibonacci series is a sequence of numbers where each // Java Program to implement number is the sum of the two preceding ones, usually // Fibonacci Series starting with 0 and 1. The sequence typically looks like this: import java.io.*; 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,... // Driver Function class GFG { The mathematical formula for the Fibonacci sequence can be defined recursively as: // Function to return Fibonacci value static int Fib(int N) F(0) = 0 { if (N == 0 || N == 1) F(1) = 1 return N; return Fib(N - 1) + Fib(N - 2); } F(n) = F(n-1) + F(n-2) for n > 1 // Main function public static void main(String[] args) { // Fibonacci of 3 System.out.println("Fibonacci of " + 3 + " " + Fib(3)); // Fibonacci of 4 System.out.println("Fibonacci of " + 4 + " " + Fib(4)); // Fibonacci of 5 System.out.println("Fibonacci of " + 5 + " " + Fib(5)); } } Java Recursion Explanation: 1. Base Case: The recursion stops when n is 0 or 1, returning 1. 2. Recursive Case: For any other positive integer n, the method calls itself with n - 1 and multiplies the result by n. Java Recursion Exercise: writ a recursion method which represent the following algorithm: 𝟏 𝒊𝒇 𝒏 = 𝟎 𝒙𝒏 = 𝒙 ∗ 𝒙𝒏−𝟏 𝒐𝒕𝒉𝒆𝒓𝒘𝒊𝒔𝒆 Think about a lower cost algorithm? i.e. with out for loop… Exercise Create a class called Invoice that a hardware store might use to represent a n invoice for a n item sold at the store. An Invoice should include four pieces of information: a part number (type String), a part description (type String), a quantity of the item being purchased (type int) and a price per item (double). Your class should have a constructor that initializes the four instance variables. In addition, provide a method named getInvoiceAmount that calculates the invoice amount (i.e.,multiplies the quantity by the price per item), then returns the amount as a double value. If the quantity is not positive, it should be set to 0. If the price per item is not positive, it should be set to 0.0 Write a test application named InvoiceTest that demonstrates class Invoice’s capabilities. Java Strings Strings are used for storing text. String is probably the most commonly used class in Java's class library. The obvious reason for this is that strings are a very important part of programming. The first thing to understand about strings is that every string you create is actually an object of type String Java Strings Ways of Creating a String There are two ways to create a string in J ava : String literal(string variable). String s = “ J ava Programming”; //The variable is initialized with the string J a va Programming. Using new keyword String s = new String (“Java Programming”); //Here, when we create a string object, the String() constructor is invoked. Java Strings Memory allotment of String Whenever a String Object is created as a literal, the object will be created in the String constant pool. J ava String Pool: J a va String pool refers to collection of Strings which are stored in heap memory. In this, when we try to declare a new String object, the J V M checks whether the value already exists in the String pool or not. If it exists, the same value is assigned to the new object. This feature allows J a va to use the heap space efficiently. Java Strings String ss = new String(“Apple”); “Apple” In J a va , String objects are immutable. Immutable simply means unmodifiable or unchangeable. Java Strings Example: / / create a string String example = "Hello! "; //add another string "World" to the previous string example example.concat(" World"); //Here, we are using the concat() method to add another string World to the previous string. It looks like we are able to change the value of the previous string. However, this is not true. The first string "Hello! " remains unchanged System.out.print(example); //will print Hello! because strings are immutable objects Java Strings Now it can be understood by the diagram given aside. “Hello!” Here “Hello!” is not changed but a new “Hello! example World” object is created with “Hello!World”. That is why String is known as immutable. Java Strings But if we explicitly assign it to the reference variable, it will refer to "Hello!World" object. for example: String example = "Hello! "; //add another string "World" to the previous string example example=example.concat(" World"); System.out.print(example); //will print Hello!World Java Strings Memory allotment of String The string can also be declared using a new operator i.e. dynamically allocated. In case of String are dynamically allocated they are assigned a new memory location in the heap. This string will not be added to String constant pool. Java Strings java defines one operator for String objects: +. It is used to concatenate two strings. For example, this statement String myString = "I" + " like " + "Java."; results in myString containing "I like Java." Java Strings The String class contains several methods that you can use. Here are a few. You can: test two strings for equality by using equals() method. obtain the length of a string by calling the length( ) method. obtain the character at a specified index within a string by calling charAt( ) method. join two strings in J a va using the concat() method. Java Strings Example: show the output of this program class StringDemo2 { public static void main(String args[ ]) { String str1 = "First String"; String str2 = "Second String"; System.out.println("Length of str1: " + str1.length( )); System.out.println ("Char at index 3 in str1: " + str1.charAt(3)); String str3 = str1; Java Strings if(str1.equals(str2)) System.out.println("str1 == str2"); else System.out.println("str1 != str2"); if(str1.equals(str3)) System.out.println("str1 == str3"); else System.out.println("str1 != str3"); } } This program generates the following output: Length of str1: 12 Char at index 3 in str1: s str1 != str2 str1 == str3 String class constructors Line 12 instantiates a new String object using class String's no-argument constructor and assigns its reference to s1. The new String object contains no characters (the empty string) and has a length of 0. Line 13 instantiates a new String object using class String's constructor that takes a String object as an argument and assigns its reference to s2. The new String object contains the same sequence of characters as the String object s that is passed as an argument to the constructor. String Methods length, charAt and getChars String methods length, charAt and getChars return the length of a string, obtain the character at a specific location in a string and retrieve a set of characters from a string as a char array, respectively. String comparisons. Line 15 uses String method length to determine the number of characters in string s1. Like arrays, strings always know their own length. The statement at lines 20-21 print the characters of the string s1 in reverse order (and separated by spaces). String method charAt (line 21) returns the character at a specific position in the string. Method charAt receives an integer argument that is used as the index and returns the character at that position. Like arrays, the first element of a string is at position 0. Line 24 uses String method getChars to copy the characters of a string into a character array. The first argument is the starting index in the string from which characters are to be copied. The second argument is the index that is one past the last character to be copied from the string. The third argument is the character array into which the characters are to be copied. The last argument is the starting index where the copied characters are placed in the target character array. Next, line 28 prints the char array contents one character at a Java Math The J ava Math class has many methods that allows you to perform mathematical tasks on numbers. for example: The Math. m ax(x,y) method can be used to find the highest value of x and y: The Math. min(x,y) method can be used to find the lowest value of x and y: The Math.sqrt(x) method returns the square root of x: The Math. abs(x) method returns the absolute (positive) value of x Math class methods: Class java.lang.Math At the next Lecture Java Modifiers Composition هجوتالةيضرغ ةمجبرال Lecture 4 Outline Java Modifiers Composition Java Modifiers We divide modifiers into two groups: Access Modifiers - controls the access level. Non-Access Modifiers - do not control access level, but provides other functionality. Java Modifiers Access Modifiers: For classes you can use either public or default: Modifier Description The class is accessible by any public other class default The class is only accessible by classes in the same package. This is used when you don't specify a modifier Java Modifiers For attributes, methods and constructors, you can use the one of the following: Modifier Description The code is accessible for all public classes private The code is only accessible within the declared class protected The code is accessible in the same package and subclasses Java Modifiers Non-Access Modifiers: For classes you can use either final or abstract: Modifier Description The class cannot be inherited by final other classes abstract The class cannot be used to create objects (To access an abstract class, it must be inherited from another class) Java Modifiers For attributes and methods, you can use the one of the following: Modifier Description Attributes and methods cannot be final overridden/modified static Attributes and methods belongs to the class, rather than an object abstract C a n only be used in a n abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. The body is provided by the subclass (inherited from) Java Modifiers Example: what the run’s result of following program? public class Main { final int x = 10; final double PI = 3.14; public static void main(String[] args) { Main myObj = new Main(); myObj.x = 50; // will generate an error: cannot assign a value to a final variable myObj.PI = 25; System.out.println(myObj.x); } } Java Modifiers J ava static method(or a class method): If you apply static keyword with any method, it is known as static method. A static method belongs to the class rather than the object of a class. A static method can be invoked without the need for creating an instance of a class. A static method can access static data member and can change the value of it. Java Modifiers J ava static variable: If you declare any variable as static, it is known as a static variable. The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. Java Modifiers Example: what the run’s result of following program? public class Main { // Main method // Static method public static void main(String[ ] args) { static void myStaticMethod() { myStaticMethod(); System.out.println("Static methods myPublicMethod(); can be called without creating Main myObj = new Main(); objects"); } myObj.myPublicMethod(); } // Public method } public void myPublicMethod() { // will generate an error: System.out. println("Public methods non-static method myPublicMethod() cannot be must be called by creating objects"); referenced from a static context myPublicMethod(); } Exercise: Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form realPart + imaginaryPart * i Use floating-point variables to represent the private data of the class. Provide a constructor that enables a n object of this class to be initialized when it’s declared. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform the following operations: a) A static method for add two complex numbers(one of them is the invoking object). b) Print Complex numbers in the form (realPart, imageinaryPart). In main method define two complex numbers with a n initial values, then print their s u m in Cartesian form(Show advantage of class methods). Types of Relationship among Classes in Java There are three most common relationships among classes in Java that are as follows: a. Dependence (“Uses-A”) b. Association (“Has-A”) c. Inheritance (“Is-A”) Association (aggregation, Dependences composition) Inheritance Has-A relationship Aggregation Aggregation: represents a “has-a” relationship, where one class contains objects of another class as part of its internal structure. It is a way to represent the relationship between objects when one object is composed of or contains other objects. “a larger entity that is composed of smaller can exist independently” Here’s an example of aggregation in Java: class Department { private String name; In this example: The University class has a list public Department(String name) { of Department objects, representing this.name = name;} the departments within the // Other department-related methods} university. class University { The University can add, remove, private String name; or modify departments, but the private List departments; // Aggregation departments themselves are independent entities that can exist public University(String name) { outside the university. this.name = name; this.departments = new ArrayList();} public void addDepartment(Department department) { departments.add(department);} // Other university-related methods} Has-A relationship Composition Composition: implies a stronger relationship where one class (the whole) is composed of other classes or objects (the parts)[A c l a s s c a n have references to objects of other c l a s s e s a s me mb e r s ] , and the parts cannot exist independently outside the whole. “when the whole is destroyed, its parts are also destroyed.” Here’s an example of composition in Java: class Room { private String name; public Room(String name) { In this example: this.name = name;} // Other room-related methods} The House class creates and owns a list of Room objects as its parts. class House { Rooms are created and managed by private List rooms; // Composition the house, and they cannot exist independently outside the house. public House() { If the house is destroyed, the this.rooms = new ArrayList(); rooms are also destroyed. rooms.add(new Room("Living Room")); rooms.add(new Room("Bedroom")); rooms.add(new Room("Kitchen"));} public List getRooms() { return rooms;}// Other house-related methods} Has-A relationshipComposition - Example Write a program in java Language which describe the following information: C l a s s Date declares about 3 variables month, day and year to represent a date , The constructor receives three int parameters. Taking into consideration accept a validation(correct) value only. Class Employee declares about 3 variables firstName , lastName are references to the String Object, birthDate and hireDate (are references to Date objects), the constructor recieves four parameters. Class EmployeeTest creates two Date objects to represent an Employee’s birthday and hire date,, respectively. Creates an Employee and initializes its instance variables by passing to constructor two String (representing the Employee’s first and last names) and two Date objects( representing the birthday and hire date) class Date { int month; // 1-12 int day; // 1-31 based on month int year; // any year static final int[ ] daysPerMonth = {0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // days in each month Date( int theMonth, int theDay, int theYear ) { month = checkMonth( theMonth ); // validate month year = theYear; // could validate year day = checkDay( theDay ); // validate day System.out.printf("Date object constructor for date %s\n", this ); } int checkMonth( int testMonth ) { if ( testMonth > 0 && testMonth 0 && testDay