Core Java Programming Intake 45 - Dec 2024 PDF

Document Details

BestKnownPennywhistle4241

Uploaded by BestKnownPennywhistle4241

CIC - Canadian International College

2024

Tags

Core Java Programming Java programming computer science

Summary

Core Java programming course intake 45, December 2024; an introduction to Java. This course covers the history and evolution of Java, including data types, variables and arrays, operators, control statements and string handling, modifiers, access specifiers, packages, and interfaces; wrapper classes, autoboxing, and inner classes, exception handling, generics and lambda expressions, method reference, Java Stream API, Java Collections, and multi-threading in Java.

Full Transcript

CORE JAVA PROGRAMMING AN INTRODUCTION TO JAVA 16-Dec-24 Copyright reserved ITI 2021 1 Course Duration and Evaluation Duration: 42 hours 7 Lectures (21 hours) 7 Labs (21 hours) Evaluation Criteria: 60% on labs activities and assignments 40% on wr...

CORE JAVA PROGRAMMING AN INTRODUCTION TO JAVA 16-Dec-24 Copyright reserved ITI 2021 1 Course Duration and Evaluation Duration: 42 hours 7 Lectures (21 hours) 7 Labs (21 hours) Evaluation Criteria: 60% on labs activities and assignments 40% on written exam after 7 days of the last lectures. Course videos: https://maharatech.gov.eg/course/view.php?id=2052 16-Dec-24 Copyright reserved ITI 2021 2 Agenda A. The History and Evolution of Java 4 B. An Overview of Java 23 C. Data Types, Variables and Arrays 66 D. Operators, Control Statements and String Handling 99 E. Modifiers, Access Specifiers, Packages and Interfaces 164 F. Wrapper Classes, Autoboxing and Inner Classes 224 G. Exception Handling 251 H. Generics and Lambda Expressions and Method Reference 299 I. Java Stream API 354 J. Java Collections 389 K. Multi-Threading in Java 473 16-Dec-24 3 Lesson 1 An Overview of Java’s History and Evolution 16-Dec-24 4 The History and Evolution of Java By the end of the 1980s and the early 1990s, object-oriented programming using C++ took hold. Within a few years, the World Wide Web and the Internet would reach critical mass, and this event would rapid another revolution in programming. Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called “Oak,” but was renamed “Java” in 1995 The original motivation for Java was not the Internet! Instead, the primary motivation was the need for a platform-independent (that is, architecture-neutral) language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls. many different types of CPUs are used as controllers. The trouble with C and C++ (and most other languages) is that they are designed to be compiled for a specific target. Although it is possible to compile a C++ program for just about any type of CPU, to do so requires a full C++ compiler targeted for that CPU. The problem is that compilers are expensive and time consuming to create. 16-Dec-24 5 The History and Evolution of Java An easier—and more cost-efficient—solution was needed. Gosling and others began work on a portable, platform-independent language that could be used to produce code that would run on a variety of CPUs under differing environments. This effort ultimately led to the creation of Java. A second, and ultimately more important, factor was emerging that would play a crucial role in the future of Java. This second force was, of course, the World Wide Web. However, with the emergence of the World Wide Web, Java was pushed to the forefront of computer language design, because the Web, too, demanded portable programs. Portable (platform-independent) programs is nearly as old as the discipline of programming itself, it had taken a back seat to other, more pressing problems. Further, because (at that time) much of the computer world had divided itself into the three competing camps of Intel, Macintosh, and UNIX, most programmers stayed within their fortified boundaries, and the urgent need for portable code was reduced. By 1993, it became obvious to members of the Java design team that the problems of portability frequently encountered when creating code for embedded controllers are also found when attempting to create code for the Internet. This realization caused the focus of Java to switch from consumer electronics to Internet programming. So, while the desire for an architecture-neutral programming language provided the initial spark, the Internet ultimately led to Java’s large-scale success. 16-Dec-24 6 The History and Evolution of Java Java derives much of its character from C and C++. This is by intent. The Java designers knew that using the familiar syntax of C and echoing the object-oriented features of C++ would make their language appealing to the legions of experienced C/C++ programmers. Java shares some of the other attributes that helped make C and C++ successful. Java was designed, tested, and refined by real, working programmers. It is a language grounded in the needs and experiences of the people who devised it. Thus, Java is a programmer’s language. Java is cohesive and logically consistent. except for those constraints imposed by the Internet environment, Java gives you, the programmer, full control. If you program well, your programs reflect it. If you program poorly, your programs reflect that, too. Java is not a language with training wheels. It is a language for professional programmers. The environmental change that prompted Java was the need for platform-independent programs designed for distribution on the Internet. Java also embodies changes in the way that people approach the writing of programs. For example, Java enhanced and refined the object-oriented paradigm used by C++, added integrated support for multithreading, and provided a library that simplified Internet access. 16-Dec-24 7 The History and Evolution of Java Java was the perfect response to the demands of the then newly emerging, highly distributed computing universe. Java was to Internet programming what C was to system programming: A revolutionary force that changed the world. 16-Dec-24 8 The History and Evolution of Java How Java Impacted the Internet The Internet helped pushing Java to the forefront of programming, and Java, in turn, had a deep effect on the Internet. In addition to simplifying web programming in general, Java innovated a new type of networked program called the applet that changed the way the online world thought about content. Java also addressed some of the trickiest issues associated with the Internet: portability and security. Let’s give some brief information about each of these: Java Applets Security Portability 16-Dec-24 9 The History and Evolution of Java How Java Impacted the Internet Java Applets At the time of Java’s creation, one of its most exciting features was the applet. An applet is a special kind of Java program that is designed to be transmitted over the Internet and automatically executed inside a Java-compatible web browser. They were typically used to display data provided by the server, handle user input, or provide simple functions, such as a loan calculator, that execute locally, rather than on the server. In essence, the applet allowed some functionality to be moved from the server to the client. In the early days of Java, applets were a crucial part of Java programming. Starting with JDK 9, applets are being phased out and deprecated, with other mechanisms supplying an alternative way of delivering dynamic, active programs via the Web. Security Portability 10 16-Dec-24 10 The History and Evolution of Java How Java Impacted the Internet Security As you are likely aware, every time you download a “normal” program, you are taking a risk, because the code you are downloading might contain a virus, Trojan horse, or other harmful code. Java achieved this protection by enabling you to confine an application to the Java execution environment and prevent it from accessing other parts of the computer. The ability to download programs with a degree of confidence that no harm will be done may have been one of the the most innovative aspect of Java at that time. 16-Dec-24 11 The History and Evolution of Java How Java Impacted the Internet Portability Portability is a major aspect of the Internet because there are many different types of computers and operating systems connected to it. If a Java program were to be run on virtually any computer connected to the Internet, there needed to be some way to enable that program to execute on different systems. The same code must work on all computers. Therefore, some means of generating portable executable code was needed. The same mechanism that helps ensure security also helps create portability. 16-Dec-24 12 Java’s Magic: The Bytecode The key that allows Java to solve both the security and the portability problems just described is that the output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). In essence, the original JVM was designed as an interpreter for bytecode. However, the fact that a Java program is executed by the JVM helps solve the major problems associated with web-based programs. 16-Dec-24 13 Java’s Magic: The Bytecode Translating a Java program into bytecode makes it much easier to run a program in a wide variety of environments because only the JVM needs to be implemented for each platform. Once the run-time package exists for a given system, any Java program can run on it. Remember, although the details of the JVM will differ from platform to platform, all understand the same Java bytecode. The fact that a Java program is executed by the JVM also helps to make it secure. Because the JVM is in control, it manages program execution. 16-Dec-24 14 Java’s Magic: The Bytecode It is possible for the JVM to create a restricted execution environment, called the sandbox, that contains the program, preventing unrestricted access to the machine. Although Java was designed as an interpreted language, there is nothing about Java that prevents on-the-fly compilation of bytecode into native code in order to boost performance. 16-Dec-24 15 The Java Buzzwords No discussion of Java’s history is complete without a look at the Java buzzwords. The key considerations were summed up by the Java team in the following list of buzzwords: Simple Secure Portable Object-oriented Robust Multithreaded Architecture-neutral Interpreted High performance Distributed Dynamic 16-Dec-24 16 Object- Simple Secure Portable oriented The Java Buzzwords Robust Multithreaded Architecture Interprete -neutral d High Distributed Dynamic Simple performance Java was designed to be easy for the professional programmer to learn and use effectively. If you already understand the basic concepts of object oriented programming, learning Java will be even easier. If you are an experienced C++ programmer, moving to Java will require very little effort. Object-Oriented The object model in Java is simple and easy to extend, while primitive types, such as integers, are kept as high- performance non objects. 16-Dec-24 17 Object- Simple Secure Portable oriented The Java Buzzwords Robust Multithreaded Architecture- neutral Interpreted High Distributed Dynamic performance Robust Because Java is a strictly typed language, it checks your code at compile time. However, it also checks your code at run time.  To better understand how Java is robust, consider two of the main reasons for program failure: memory management mistakes and mishandled exceptional conditions (that is, run-time errors). Multithreaded Java supports multithreaded programming, which allows you to write programs that do many things simultaneously. The Java run-time system comes with an elegant yet sophisticated solution for multiprocess synchronization that enables you to construct smoothly running interactive systems. 16-Dec-24 18 Object- Simple Secure Portable oriented The Java Buzzwords Robust Multithreaded Architecture -neutral Interpreted High Distributed Dynamic performance Architecture-neutral Their goal was “write once; run anywhere.” To a great extent, this goal was accomplished. Interpreted and High Performance Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. This code can be executed on any system that implements the Java Virtual Machine. The Java bytecode was carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a just-in-time compiler. 16-Dec-24 19 Object- Simple Secure Portable oriented The Java Buzzwords Robust Multithreaded Architecture- neutral Interpreted High Distributed Dynamic performance Distributed Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols. Java also supports Remote Method Invocation (RMI), this feature enables a program to invoke methods across a network. Dynamic Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve access to objects at run time. This makes it possible to dynamically link code in a safe and convenient manner. This is crucial to the robustness of the Java environment, in which small fragments of bytecode 16-Dec-24 may be dynamically updated on a running system. 20 The Evolution of Java 16-Dec-24 21 Agenda A. The History and Evolution of Java 4 B. An Overview of Java 23 C. Data Types, Variables and Arrays 66 D. Operators, Control Statements and String Handling 99 E. Modifiers, Access Specifiers, Packages and Interfaces 164 F. Wrapper Classes, Autoboxing and Inner Classes 224 G. Exception Handling 251 H. Generics and Lambda Expressions and Method Reference 299 I. Java Stream API 354 J. Java Collections 389 K. Multi-Threading in Java 473 16-Dec-24 22 An Overview of Java Object-Oriented Programming Object-oriented programming (OOP) is at the core of Java. OOP is so integral to Java that it is best to understand its basic principles before you begin writing even simple Java programs. 16-Dec-24 23 Computer Program Components These are the two paradigms that govern how a program is constructed. Computer Program Code Data The first way is called the process-oriented model. The second approach, called object-oriented programming 16-Dec-24 24 The Process-Oriented model The process oriented model can be thought of as code acting on data. Procedural languages such as C employ this model to considerable success. However, the problem with this approach appear as programs grow larger and more complex. 16-Dec-24 25 The Object-Oriented Programming Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code. We will be discussing the main characteristics of Object Oriented 16-Dec-24 26 Abstraction An essential element of object-oriented programming is abstraction. Humans manage complexity through abstraction. For example, people do not think of a car as a set of tens of thousands of individual parts. They think of it as a well-defined object with its own unique behavior. A powerful way to manage abstraction is through the use of hierarchical classifications. This allows you to layer the semantics of complex systems, breaking them into more manageable pieces. 16-Dec-24 27 Abstraction From the outside, the car is a single object. Once inside, you see that the car consists of several subsystems: steering, brakes, sound system, seat belts, heating, cellular phone, and so on. In turn, each of these subsystems is made up of more specialized units. Hierarchical abstractions of complex systems can also be applied to computer programs. The data from a traditional process-oriented program can be transformed by abstraction into its component objects. A sequence of process steps can become a collection of messages between these objects. 16-Dec-24 28 Abstraction Thus, each of these objects describes its own unique behavior. You can treat these objects as concrete entities that respond to messages telling them to do something. As you will see, object-oriented programming is a powerful and natural paradigm for creating programs that survive the changes accompanying the life cycle of any major software project, including conception, growth, and aging. 16-Dec-24 29 The Three OOP Principles All object-oriented programming languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, and polymorphism. In the following slides we will be discussing theses concepts briefly. 16-Dec-24 30 Encapsulation Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. In Java, the basis of encapsulation is the class. A class defines the structure and behavior (data and code) that will be shared by a set of objects. Each object of a given class contains the structure and behavior defined by the class. Thus, a class is a logical construct; an object has physical reality. 16-Dec-24 31 Encapsulation When you create a class, you will specify the code and data that constitute that class. The data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods. 16-Dec-24 32 Encapsulation- A Class Representation Public instance variables (not recommended) Public methods Private methods Private instance variables 16-Dec-24 33 Inheritance Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. Without the use of hierarchies, each object would need to define all of its characteristics explicitly. By use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. 16-Dec-24 34 Inheritance 16-Dec-24 35 Polymorphism Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be used for a general class of actions. The specific action is determine by the exact nature of the situation. More generally, the concept of polymorphism is often expressed by the phrase “one interface, multiple methods.” This means that it is possible to design a generic interface to a group of related activities. Consider a stack (which is a last-in, first-out list). You might have a program that requires three types of stacks. One stack is used for integer values, one for floating-point values, and one for characters. 16-Dec-24 36 Polymorphism It is the compiler’s job to select the specific action (that is, method) as it applies to each situation. You, the programmer, do not need to make this selection manually. You need only remember and utilize the general interface. The specific action would be determined depending on the calling object 16-Dec-24 37 First Java Program class Example { // Your program begins with a call to main(). public static void main(String args[]) { System.out.println("This is a simple Java program."); } } 16-Dec-24 38 First Java Program For this example, the name of the source file should be Example.java. In Java, a source file is officially called a compilation unit. It is a text file that contains (among other things) one or more class definitions. The Java compiler requires that a source file use the.java filename extension. 16-Dec-24 39 Compiling the Program To compile the Example program, execute the compiler, javac, specifying the name of the source file on the command line, as shown here: C:\>javac Example.java The javac compiler creates a file called Example.class that contains the bytecode version of the program. As discussed earlier, the Java bytecode is the intermediate representation of your program that contains instructions the Java Virtual Machine will execute. 16-Dec-24 40 Running the Program To actually run the program, you must use the Java application launcher called java. To do so, pass the class name Example as a command-line argument, as shown here: C:\>java Example When the program is run, the following output is displayed: C:\>This is a simple Java program. 16-Dec-24 41 First Sample Program Examined The program begins with the following lines: The Above lines are multiline comments that are considered as remarks for the developer, explaining the operation of the program to anyone who is reading its source code. 16-Dec-24 42 Java three Styles of Comments // Comment Single Line Comment 16-Dec-24 43 First Sample Program Examined The next line of code in the program is shown here: class Example { This line uses the keyword class to declare that a new class is being defined. Example is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly brace ({) and the closing curly brace (}). 16-Dec-24 44 First Sample Program Examined The next line of code is shown here: public static void main(String args[]) { As a general rule, a Java program begins execution by calling main( ). The public keyword is an access modifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. In this case, main( ) must be declared as public, since it must be called by code outside of its class when the program is started. 16-Dec-24 45 First Sample Program Examined The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java Virtual Machine before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value. String args[ ] declares a parameter named args, which is an array of instances of the class String. In this case, args receives any command-line arguments present when the program is executed. 16-Dec-24 46 First Sample Program Examined The next line of code is shown here. Notice that it occurs inside main( ). System.out.println("This is a simple Java program."); Output is actually accomplished by the built-in println( ) method. System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. 16-Dec-24 47 Second Short Program 100 class Example2 { the plus sign causes public static void main(String args[]) { the value of num to int num; // this declares a variable called num be appended to the string that precedes num = 100; // this assigns num the value 100 it System.out.println("This is num: " + num); num = num * 2; System.out.print("The value of num * 2 is "); System.out.println(num); } } 16-Dec-24 48 Two Control Statements- if statement The Java if statement works much like the if statement in any other language. It determines the flow of execution based on whether some condition is true or false. Its simplest form is shown here: if(condition) statement; Where condition is a boolean expression that evaluates either true or false if(num < 100) System.out.println("x is less than y"); if num contains a value that is less than 100, the conditional expression is true, and println( ) will execute. 16-Dec-24 49 If Statement Example class IfSample { public static void main(String args[]) { int x, y; x = 10; y = 20; if(x < y) System.out.println("x is less than y"); x = x * 2; if(x == y) System.out.println("x now equal to y"); x = x * 2; if(x > y) System.out.println("x now greater than y"); // this won't display anything if(x == y) System.out.println("you won't see this"); } } 16-Dec-24 50 Two Control Statements- the for Loop Loop statements are an important part of nearly any programming language because they provide a way to repeatedly execute some task. The simplest form of the for loop is shown here: for(initialization; condition; iteration) statement; The initialization portion of the loop sets a loop control variable to an initial value. The condition is a Boolean expression that tests the loop control variable. 16-Dec-24 51 Two Control Statements- the for Loop If the outcome of that test is true, statement executes and the for loop continues to iterate. If it is false, the loop terminates. The iteration expression determines how the loop control variable is changed each time the loop iterates. 16-Dec-24 52 For Loop Example This is x: 3 This is x: 4 class ForTest { This is x: 5 public static void main(String args[]) { This is x: 6 int x; This is x: 7 This is x: 8 for(x = 0; x>= Shift Right Assignment Shift Right zero fill >> Shift Right >>>= Assignment >>> Shift Right zero fill > 2 00001111 15 ~a 11000011 -61 16-Dec-24 104 Relational Operators The relational operators determine the relationship that one operand has to the other They determine equality and ordering. The relational operators are shown here: Operator Result Operator Result == Equal to < Less than != Not equal to >= Greater than or equal to > Greater than ) As of JDK 8, a new feature has been added to Java that profoundly enhances the expressive power of the language. This feature is the lambda expression. Not only do lambda expressions add new syntax elements to the language, they also streamline the way that certain common constructs are implemented. The addition of lambda expressions have also provided the catalyst for other new Java features (Default Methods-Method Reference). 16-Dec-24 116 Lambda Expression A lambda expression is, essentially, an anonymous (that is, unnamed) method. However, this method is not executed on its own. Instead, it is used to implement a method defined by a functional interface. Thus, a lambda expression results in a form of anonymous class. Lambda expressions are also commonly referred to as closures. A functional interface is an interface that contains one and only one abstract method 16-Dec-24 117 Lambda Expression The lambda expression introduces a new syntax element and operator into the Java language. The new operator, sometimes referred to as the lambda operator or the arrow operator, is –>. It divides a lambda expression into two parts. The left side specifies any parameters required by the lambda expression. On the right side is the lambda body, which specifies the actions of the lambda expression. 16-Dec-24 118 Single Lambda Expressions(Examples) () -> 98.6 It evaluates to a constant value. This lambda expression takes no parameters, thus the parameter list is empty. It returns the constant value 98.6. Therefore, it is similar to the following method: double myMeth() { return 98.6; } Of course the method defined by a lambda expression does not have a name ()-> Math.random()*100 This lambda expression obtains a pseudo-random value from Math.random( ), multiplies it by 100, and returns the result. It, too, does not require a parameter. 16-Dec-24 119 Single Lambda Expressions(Examples) When a lambda expression requires a parameter, it is specified in the parameter list on the left side of the lambda operator. Here is a simple example: (n) -> 1.0 / n (n) -> (n % 2)==0 This lambda expression returns the reciprocal Any valid type can be used as the return type of the value of n of a lambda expression. If n is 4.0 then the reciprocal is 0.25 The above lambda expression return boolean The type of n can be inferred so you don’t When a lambda expression has only one need to explicitly specify it. parameter, it is not necessary to surround the Like a named method, a lambda expression parameter name with parentheses when it is can specify as many parameters as needed specified on the left side. 16-Dec-24 120 Control Statements in Java Control Statements Selection Iteration Jump 16-Dec-24 121 Selection Statements  Selection Statements are also called Decision Making Statements. Selection Statements If switch statement statement 16-Dec-24 122 If Statements If Statements If- else –if Simple if If else Nested if Ladder 16-Dec-24 123 Simple if Syntax : if (condition) if(x < y) { System.out.println("x is less than y"); { } statement1; } Purpose: The statements will be evaluated if the value of the condition is true. 16-Dec-24 124 If else Syntax : if (condition) if(x < y) { { System.out.println("x is less than y"); statement1; }else { System.out.println("x is either equals } y or greater than y"); else } { statement2; } Purpose: The statement 1 is evaluated if the value of the condition is true otherwise statement 2 istrue. 16-Dec-24 125 If-else-if Ladder Syntax : if(condition) statements; else if(condition) statements; else if(condition) statements;...... else statements; 16-Dec-24 126 If-else-if example class IfElse { public static void main(String args[]) { int month = 4; // April String season; if(month == 12 || month == 1 || month == 2) season = "Winter"; else if(month == 3 || month == 4 || month == 5) season = "Spring"; else if(month == 6 || month == 7 || month == 8) season = "Summer"; else if(month == 9 || month == 10 || month == 11) season = "Autumn"; else season = “Unknown Month"; System.out.println("April is in the " + season + "."); } } 16-Dec-24 127 Nested if Syntax : if(condition){ A nested if is an if if(condition) statements.... statement that is the else target of another if or statements.... else. }else{ Nested ifs are very if(condition) common in statements.... else programming. statements.... } 16-Dec-24 128 Example class NestedIfDemo { public static void main(String args[]) { int i = 10; if (i == 10) { // First if statement if (i < 15) System.out.println("i is smaller than 15"); // Nested - if statement // Will only be executed if statement above // it is true if (i < 12) System.out.println("i is smaller than 12 too"); else System.out.println("i is greater than 15"); } } } 16-Dec-24 129 switch case Syntax : switch (expression) Purpose: The { case value 1 : statements N will be statement 1 ; evaluated if the break; case value 2 : value of the statement 2 ; expression matches break;... the value N. case value N : statement N ; break; default : statements ; break; } 16-Dec-24 130 Example class SwitchCaseDemo { public static void main(String args[]) { int i = 9; switch (i) { case 0: System.out.println("i is zero."); break; case 1: System.out.println("i is one."); break; case 2: System.out.println("i is two."); break; default: System.out.println("i is greater than 2."); } } } 16-Dec-24 131 Iteration Statements Each loop has four types of statements : while Initialization Condition checking Execution Increment / Decrement Iteration/Loops do while for 16-Dec-24 132 while loop Syntax int m=1; initialization while(final value) while(m

Use Quizgecko on...
Browser
Browser