Integrative Programming and Technologies 1 PDF
Document Details
Uploaded by Deleted User
Laguna University
NUMERIANO B. AGUADO
Tags
Summary
This document is a course outline for "Integrative Programming and Technologies 1" at Laguna University. It covers topics like systems integration, communication mechanisms, data standardization, inter-systems communication, data mapping, exchange, and an overview of programming languages.
Full Transcript
Integrative Programming and Technologies 1 NUMERIANO B. AGUADO VISION Laguna University shall be a socially responsive educational institution of choice providing holistically developed individuals in the Asia-Pacific Regio...
Integrative Programming and Technologies 1 NUMERIANO B. AGUADO VISION Laguna University shall be a socially responsive educational institution of choice providing holistically developed individuals in the Asia-Pacific Region MISSION Laguna University is committed to produce academically prepared and technically skilled individuals who are socially and morally upright Course Code: IT-2104 Course Description: This course looks at systems integration with focus on communication mechanisms and data standardization. Major topics include inter-systems communication, data mapping and exchange, integrative coding, scripting techniques, and an overview of programming languages Course Intended Learning Outcomes (CILO): At the end of this course, the students should be able to: 1. Design, develop and test a program that uses a messaging service that sends asynchronous messages across the network. 2. Design, develop and test program that uses SAX or DOM to parse an XML document, XSL and XSLT to transform a data stream from one format to another 3. Write, debug and test script using an operating scripting language to facilitate the management of an operating system Course Requirements: ▪ Assessment Tasks - 60% ▪ Major Exams - 40% _________ Periodic Grade 100% Final Grade = 30% Midterm Grade + 70% (60% Final ATs + 40% Final Exam) Table of Contents Module 1: Overview of Java Programming Language Introduction 1 Learning Objectives 1 Lesson 1: What is Java 2 Lesson 2: Processing of Java Program 9 Lesson 3: Programming with the Problem Analysis, Coding, and 10 Execution Cycle Lesson 4: Programming Methodologies 12 Assessment Task 14 Summary 16 References 16 Module 2: Java Program Editors Introduction 17 Learning Objectives 17 Lesson 1: Program Editors 17 Assessment Task 22 Summary 22 References 23 Module 3: Basic Elements of Java Introduction 24 Learning Objectives 24 Lesson 1: Basic of Java Program 25 Lesson 2: Variables in Java 30 Lesson 3: Data Types in Java 34 Lesson 4: Operators in Java 40 Lesson 5: Input (read) Statement 52 Lesson 6: Package, Classes, Methods and the import Statement 53 Lesson 7: Creating a Java Application Program 54 Assessment Task 56 Summary 57 References 58 Module 4: Objects and Input/Output Introduction 59 Learning Objectives 59 Lesson 1: Objects and Reference Variables 59 Lesson 2: Input/Output 63 Lesson 3: Parsing numeric strings 70 Lesson 4: File I/O in Java 73 Assessment Task 83 Summary 86 References 86 MODULE 1 OVERVIEW OF JAVA PROGRAMMING LANGUAGE Introduction Internet activities is so popular now a days. It is a part of life to most people if not all. Students regularly “surf” the internet and use computers to design their classroom projects. Generally, people use the internet to look up information and to communicate with each other. These internet activities are all made possible by the availability of different software, known as computer programs. Software is developed by using programming languages. The JAVA programming language is especially well suited for the development of software to accomplish specific desired tasks. The main objective of this module is to teach students how to write programs in Java Programming language. It is useful to understand the basics of language programming: basic terminologies, and different components of a computer, which most of you are familiar with or acquainted with. Before we begin programming, we must understand Java language overview Learning Outcomes 1. At the end of this module, students should be able to: 2. Understand what Java Programming Language is; 3. Learn about evolution of programming languages; 4. Examine high-level programming language; 5. Understand the different program editors; 6. Rediscover compiler and what it does; 7. Learn what an algorithm is and explore problem solving techniques; 8. Become familiar with structured and object-oriented programming design methodologies. 1 Lesson 1. What is Java (Javapoint, n.d.) Java is an object-oriented, class-based, concurrent, secured and general-purpose computer-programming language. Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure programming language. Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime environment (JRE) and API, it is called a platform. History of Java The history of Java is very interesting. Java was originally designed for interactive television, but it was too advanced technology for the digital cable television industry at the time. The history of Java starts with the Green Team. Java team members (also known as Green Team), initiated this project to develop a language for digital devices such as set-top boxes, televisions, etc. However, it was suited for internet programming. Later, Java technology was incorporated by Netscape. The principles for creating Java programming were "Simple, Robust, Portable, Platform- independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object- Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the early '90s. Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. There are given significant points that describe the history of Java. 1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team. 2) Initially designed for small, embedded systems in electronic appliances like set-top boxes. 3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was.gt. 4) After that, it was called Oak and was developed as a part of the Green project. 5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany, Romania, etc. 6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies. Evolution of Programming Languages The most basic computer language is machine language. It provides program instructions in bits, though most computers perform the same kinds of operations, the designers of 2 different CPUs sometimes choose different sts of binary codes to perform those operations. Because of this, the machine language of one computer is not necessarily the same as the machine language of another computer. The only uniformity and similarity among computers, all data are stored and manipulated as a binary code. Please visit this site for more information about evolution of programming languages: https://www.extremetech.com/computing/91572-the-evolution-of-computer-languages- infographic#:~:text=Programming%20languages%2C%20believe%20it%20or,%2Dcard%2Dprogrammable%20Jacqua rd%20loom.&text=LISP%20(LISt%20Processor)%2C%20ALGOL,say%2C%20the%20rest%20is%20history. ❖ Features of Java The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. Java is guaranteed to be Write Once, Run Anywhere. Java is − Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model. Platform Independent − Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master. Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. 3 Multithreaded − With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process. High Performance − With the use of Just-In-Time compilers, Java enables high performance. Distributed − Java is designed for the distributed environment of the internet. Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time. ❖ Structure of Java Program Java is an object-oriented programming, platform independent, and secure programming language that makes it popular. Using the Java programming language, we can develop a wide variety of applications. So, before diving in depth, it is necessary to understand the basic structure of Java program in detail. In this section, we have discussed the basic structure of a Java program. At the end of this section, you will be able to develop the Hello world Java program, easily. Let's see which elements are included in the structure of a Java program. A typical structure of a Java program contains the following elements: Documentation Section Package Declaration Import Statements Interface Section Class Definition Class Variables and Variables Main Method Class Methods and Behaviors Documentation Section - The documentation section is an important section but optional for a Java program. It includes basic information about a Java program. The information 4 includes the author's name, date of creation, version, program name, company name, and description of the program. It improves the readability of the program. Whatever we write in the documentation section, the Java compiler ignores the statements during the execution of the program. To write the statements in the documentation section, we use comments. The comments may be single-line, multi- line, and documentation comments. Single-line Comment: It starts with a pair of forwarding slash (//). For example: //First Java Program Multi-line Comment: It starts with a. We write between these two symbols. For example: 1. Documentation Comment: It starts with the delimiter (. For example: 1. Package Declaration The package declaration is optional. It is placed just after the documentation section. In this section, we declare the package name in which the class is placed. Note that there can be only one package statement in a Java program. It must be defined before any class and interface declaration. It is necessary because a Java class can be placed in different packages and directories based on the module they are used. For all these classes package belongs to a single parent directory. We use the keyword package to declare the package name. For example: 1. package javatpoint; //where javatpoint is the package name 2. package com.javatpoint; //where com is the root directory and javatpoint is the subd irectory Import Statements The package contains the many predefined classes and interfaces. If we want to use any class of a particular package, we need to import that class. The import statement represents the class stored in the other package. We use the import keyword to import the class. It is written before the class declaration and after the package statement. We use the import statement in two ways, either import a specific class or import all classes of a 5 particular package. In a Java program, we can use multiple import statements. For example: 1. import java.util.Scanner; //it imports the Scanner class only 2. import java.util.*; //it imports all the class of the java.util package 3. Interface Section It is an optional section. We can create an interface in this section if required. We use the interface keyword to create an interface. An interface is a slightly different from the class. It contains only constants and method declarations. Another difference is that it cannot be instantiated. We can use interface in classes by using the implements keyword. An interface can also be used with other interfaces by using the extends keyword. For example: 1. interface car 2. { 3. void start(); 4. void stop(); 5. } 6. Class Definition In this section, we define the class. It is vital part of a Java program. Without the class, we cannot create any Java program. A Java program may conation more than one class definition. We use the class keyword to define the class. The class is a blueprint of a Java program. It contains information about user-defined methods, variables, and constants. Every Java program has at least one class that contains the main() method. For example: 1. class Student //class definition 2. { 3. } 4. Class Variables and Constants In this section, we define variables and constants that are to be used later in the program. In a Java program, the variables and constants are defined just after the class definition. The variables and constants store values of the parameters. It is used during the execution 6 of the program. We can also decide and define the scope of variables by using the modifiers. It defines the life of the variables. For example: 1. class Student //class definition 2. { 3. String sname; //variable 4. int id; 5. double percentage; 6. } 7. Main Method Class In this section, we define the main() method. It is essential for all Java programs. Because the execution of all Java programs starts from the main() method. In other words, it is an entry point of the class. It must be inside the class. Inside the main method, we create objects and call the methods. We use the following statement to define the main() method: 1. public static void main(String args[]) 2. { 3. } 4. For example: 1. public class Student //class definition 2. { 3. public static void main(String args[]) 4. { 5. //statements 6. } 7. } 8. You can read more about the Java main() method here. Methods and behavior In this section, we define the functionality of the program by using the methods. The methods are the set of instructions that we want to perform. These instructions execute at runtime and perform the specified task. For example: 1. public class Demo //class definition 2. { 3. public static void main(String args[]) 4. { 5. void display() 6. { 7. System.out.println("Welcome to javatpoint"); 8. } 9. //statements 7 10. } 11. } 12. When we follow and use the above elements in a Java program, the program looks like the following. CheckPalindromeNumber.java 1. 2. //Author's name: Mathew 3. 6. //imports the Scanner class of the java.util package 7. import java.util.Scanner; 8. //class definition 9. public class CheckPalindromeNumber 10. { 11. //main method 12. public static void main(String args[]) 13. { 14. //variables to be used in program 15. int r, s=0, temp; 16. int x; //It is the number variable to be checked for palindrome 17. Scanner sc=new Scanner(System.in); 18. System.out.println("Enter the number to check: "); 19. //reading a number from the user 20. x=sc.nextInt(); 21. //logic to check if the number id palindrome or not 22. temp=x; 23. while(x>0) 24. { 25. r=x%10; //finds remainder 26. s =(s*10)+r; 27. x=x/10; 28. } 29. if(temp==s) 30. System.out.println("The given number is palindrome."); 31. else 32. System.out.println("The given number is not palindrome."); 33. } 34. } 35. Output: 8 Lesson 2. Processing of Java Program (Malik, 2012) Java has two types of programs – applications and applets. The following is an example of Java application program: 1. //My First Program 2. public class MyFirstJavaProgram { 3. public static void main(String[ ] args) { 4. System.out.println(“My First java Program!”); 5. } 6. } If you run or execute the program code, it will display the following line on your screen: My First Java Program! It is noted that computer understand only machine language, therefore, before we run the program successfully, the program code must be first translated into machine code. So in this section we will review the steps required to execute the program written in Java. The flowchart below illustrates how program is executed: Figure 1.1 Processing of Java Program The following steps are carried on first before the program executes and display its output: 9 Step 1. Use text editor like Notebook or other IDEs available to write your Java program code following the rules or syntax of the language. The program is called source program. The program must be saved in a text file named ClassName.java, where the ClassName is the name of the Java class contained in the file. For example, in the Java program written above, in the name (public) class containing the Java program is MyFirstJavaProgram. So, the program must be saved as MyFirstJavaProgram.java if not so we will get an error. Source Program is a program written in a high-level language. Step 2. Program must be written in a correct syntax before it is compiled or translated into a program equivalent bytecode. The compiler checks the source program for syntax error/s and if no error found the compiler translate the source code into a bytecode otherwise it will move back to editor to correct syntax. Once it is OK the program is saved in the file with an extension of.class. It will store in a file as MyFirstJavaProgram.class by the compiler. Step 3. To run the Java application program, the.class file must be loaded into computer memory. The program is automatically loaded and is done by Java loader. Step 4. The next step is to run the Java program. In addition to connecting the bytecode from various classes, the loader also loads your Java program’s bytecode into main memory. As the classes are loaded the bytecode verifier verifies that the bytecode for the class is valid and does not violate Java’s security restrictions. Step 5. Finally, a program called interpreter translates each bytecode instruction into our computer’s machine language and then execute it. Interpreter: a program that reads and translates each bytecode instruction into your computer’s machine language for execution. Lesson 3. Programming with the Problem Analysis, Coding, and Execution Cycle Programming is a process of problem solving. Different people use different techniques to solve problems. Several problems are already outlined and easy to follow. They solve the problem ang give insight into how the solution was reached. Such problem techniques can be easily modified if the domain of the problem changes. 10 To be a skillful problem solver, and to become a skillful programmer, an individual must use good problem-solving techniques. One common problem-solving technique includes analyzing a problem, outlining the problem requirements, and designing steps , called an algorithm, to solve the problem. Algorithm: A step-by-step problem-solving process in which a solution is arrived at in a finite amount of time. In the programming environment, the problem-solving process involves the following steps: 1. Analyze the problem and outline the problem requirements and its solutions. 2. Design an algorithm to solve the problem. 3. Implement the algorithm in the programming language, --such as Java. 4. Verify if the algorithm works. 5. Maintain the program by using and improving it and modifying it if the problem domain changes. To develop a program to solve problem, one must start analyzing the problem, the outlining the problem and the options for solution. The design the algorithm, write the program instructions in a high-level language, or code the program, and enter the program into a computer system. Analyzing the problem is the most important step in the process. This step requires we do the following: 1. Thoroughly understand the problem. 2. Know the problem requirements. Requirements can include whether the program requires interaction with the user, whether it manipulates data, whether it produces output and what the output looks like. If the program manipulates data, one must know what the data are and how they are represented. To do this, you need to look at sample data. 3. If the program produces output, one should know how the results should be generated and formatted. 11 4. If the problem is complex, divide the problem into subproblems and repeat steps 1 and 2 by analyzing each subproblem and understanding each subproblem’s requirements. Also, should know how the subproblems relate to each other. 5. Design an algorithm to solve the problem. Once the algorithm is done, check its correctness. Use sample data to check, use mathematical analysis to test its correctness. Integrate subproblem solution if there is. 6. Once done with the algorithm, convert it into a high-level language. Use IDE to enter it into computer following the correct syntax. Compile the program code to check its correctness syntactically. 7. Execute the program. Lesson 4. Programming Methodologies Two of the most popular approaches to programming design are the Structured approach and the Object-Oriented approach. Difference Between Structured and Object-Oriented Programming (Pediaa, 2019) - The main difference between structured and object-oriented programming is that structured programming is a programming paradigm which divides the code into modules or function; it allows developing a program using a set of modules or functions, while object oriented programming is a programming paradigm based on the concept of objects, which contain data in the form of fields known as attributes, and code in the form of procedures known as methods; it allows constructing a program using a set of objects and their interactions. Structured Programming - Structured Programming divides a program into a set of functions or modules. Modular programming is another name for this. These functions have statements embraced inside curly braces. Each of these functions performs a subtask. Usually, as each function represents a specific functionality, it is easier for the programmer to test and debug the code, but this can differ depending on the program. C language and Pascal are two common structured programming languages. 12 In the structured programming C, the user can create his own user-defined functions. The main function calls the other functions. It indicates the execution of the program. When there is a function call, the control is passed to that function. After completing the function, the control passes back to the main program. Moreover, a variable inside a function is a local variable, and global variables are accessible by all the functions. Object-Oriented Programming - Object-oriented programming allows the programmer to represent real-world scenarios using objects. An object is any entity that has states and behaviors. States represent the attributes or data of an object, whereas the methods represent the behaviors of objects. Student, Employee, Book etc. are objects. These objects interact with other objects by passing messages. Furthermore, a class is a blueprint for creating an object. It is necessary to have a class to create objects. For example, to create an Employee object, there should be an Employee class. In addition to classes and objects, there are four major pillars in OOP. They are as follows. Encapsulation – Binds or combines properties and methods into a single unit Inheritance – Allows a class to use properties and methods of an already existing class Polymorphism – Allows an object to perform in multiple ways – Overloading and overriding are two ways of achieving polymorphism. Abstraction – Hides the internal details and displays only the functionalities to the user – Moreover, abstract classes and interfaces help to achieve abstraction. Overall, object-oriented programming makes it easier to develop the program. Furthermore, it provides data security, maintainability, and code reusability. 13 Assessment Task 1-1 Test your knowledge. Give and discuss in writing your answer to the following questions: Why do you need to translate a program written in a high level language into machine language? Why would you prefer to write s program on high level language rather than aa machine language? What are the advantages of problem analysis and algorithm design over directly writing a program in a high level language? Design an algorithm to find the weighted average of four scores. The four test scores and their respective weights are given in the following format: Test score1 weightTestScore1 …. ….. For example, a simple data is as follows: 75 0.20 95 0.35 85 0.15 65 0.30 14 Assessment Task 1-2 Test your knowledge. Give and discuss in writing your answer to the following questions: To make profit, the price of the items sold in a furniture store are marked up by 80%. After making up the prices each item is put on sale at a discount of 10%. Design an algorithm to find the selling price of an item sold at the furniture store. What information do you need to find the selling price? Suppose that the cost of sending an international fax is calculated as follows: Service charges 3.00, (0.20 per page for the first 10 pages, and 0.10 for each additional page). Design an algorithm that ask the user to enter the number of pages to be faxed. The algorithm then uses the number of pages to calculate the amount due. 15 Summary We have discussed about software using Java programming languages. We have learned that JAVA programming language is especially well suited for the development of software to accomplished specific desired tasks. It was presented to you on how this module taught us and students on how to write programs in Java Programming language. It was stated how it is useful to understand the basics of language programming: basic terminologies, and different components of a computer, which most of you are familiar or acquainted with. References Javapoint. (2021). Retrieved 7 January 2021, from https://www.javatpoint.com/java-tutorial Malik, D.S. , 2012, Java Programming: From Problem Analysis to Program Design. 5th Edition, 2012, Cengage Learning Asia Pte Ltd. Pediaa (2019). Retrieved 7 January 2021, from https://pediaa.com/what-is-the-difference- between-structured-and-object-oriented-programming/#Structured%20Programm 16 MODULE 2 JAVA PROGRAM EDITORS Introduction Java is one of the leading programming languages. Widely employed for developing robust and secure desktop apps, enterprise applications, mobile apps, and web applications. For us to be able to write Java program codes, Text editors are needed. There are various available text editors that we can use like Notepad, Notepad++, and the like. However, we can use a lot more editor which are commonly called Integrated Development Environment (IDE) available in the Internet. They may be commercial or Open-Source application which are most often free for use. Eclipse, IntelliJ IDEA, and NetBeans are the big three IDEs designed for Java program development. Moreover, there are numerous other IDEs for developing apps effectively used for Java. Learning Outcomes At the end of this module, students should be able to: 1. Learn the different text editors for Java; 2. Understand how these editors are use; 3. Compare and examine the capabilities these IDEs; 4. Familiarize with the different IDEs; and 5. Use independently the IDE of their choice. Lesson 1. Program Editors (Hackr.io, 2021) Program editors are commonly used in writing programming code. They are called Integrated Development Environment (IDE). Java is one of the leading programming languages. Widely employed for developing robust and secure desktop apps, enterprise applications, mobile apps, and web applications. 17 There is a multitude of free Java IDEs available for working with Java. While Eclipse, IntelliJ IDEA, and NetBeans are the big three of Java, there are numerous other IDEs for developing apps effectively using Java. 1. Eclipse Platform– Linux/macOS/Solaris/Windows First Released – November 2001 A dedicated Java IDE, Eclipse gets listed as one of the big three of Java IDEs. The modern integrated development environment is available in both desktop and cloud editions. The cloud edition of the Eclipse, named Eclipse Che, allows programmers to develop apps via a web browser. Both editions of the Eclipse IDE equip with required/additional functionality utilizing plugins. There is an array of plugins available for the IDE on the Eclipse Marketplace. To facilitate the incremental compilation of Java code, Eclipse comes with a custom compiler. For Java programmers looking to develop specific functionality for Eclipse, a PDE (Plugin Development Environment) is available. To help Java developers hasten the application development, Eclipse flaunts powerful tools for charting, modelling, reporting, and testing. Eclipse supports application development in several programming languages via plugins. C, C++, Clojure, Groovy, Haskell, JavaScript, Julia, Perl, PHP, Ruby, Rust, and Scala are some of the various programming languages supported by Eclipse. Features: a runtime core, a collection of libraries, a modelling and control language, a development environment, interfaces for embedding into host environments, interfaces to third-party solvers. 18 2. NetBeans Platform– Linux/macOS/Solaris/Windows First Released – 1997 Another name in the big three of Java IDEs is NetBeans. It is also free java ide. NetBeans is the official IDE for Java 8. The open-source IDE facilitates Java programmers to build desktop, mobile, and web applications by offering a range of potent tools and features. In addition to being available for a variety of platforms, NetBeans also comes in a feature- limited OS-independent version. Each novel version of the NetBeans boasts an improved and reworked Java editor. By highlighting Java code syntactically and semantically, it makes it easier for Java programmers to build custom software apps. Inbuilt tools in NetBeans makes it possible to refactor the code as well as writing bug-free code. To design and develop GUIs for Java SE, a GUI Builder is put on offer by NetBeans. The dedicated Java IDE is available in 28 different languages. NetBeans has extensions available for working in C, C++, HTML5, JavaScript, PHP, and other programming languages. Features: Cross-platform support Multiple language support Visual debugger NetBeans Profiler Static analysis tools Project management Code editor Batch code analyzers Code converters 19 3. IntelliJ IDEA Platform– Linux/macOS/Windows First Released – January 2001 IntelliJ IDEA is one of the big three of Java IDEs. It is available in 2 different editions, an Apache 2 Licensed community edition, and a proprietary commercial edition. To allow developers to dive deeper into the Java code, IntelliJ IDEA boasts cross-language refactoring and data flow analysis features. Other features offered by IntelliJ IDEA that eases the life of a Java developer are chain completion, language injection, smart completion, and static member completion. In addition to supporting Java and a galore of Java frameworks, IntelliJ IDEA also provides support for other JVM-based programming languages, such as Kotlin. Features: Smart completion Chain completion Static members completion Data flow analysis Language injection Cross-language refactorings Detecting duplicates Inspections and quick-fixes 4. JCreator Platform– Linux (via Wine) / Windows First Released – N/A 20 Developed by Xerox Software, JCreator is yet another lightweight Java IDE. JCreator flaunts an interface much similar to Microsoft’s Visual Studio. It is available in three distinct variants; Lite Edition, Pro Edition, and Life-Pro Edition. Unlike leading Java IDEs that are developed using Java, JCreator is developed entirely in C++. Furthermore, it doesn’t require a JRE for executing Java code. For this particular reason, the developer community advocates that JCreator is faster than most conventional Java-based IDEs. The paid version of JCreator comes with Ant support, code wizards, and a debugger. Unlike the leading Java IDEs, JCreator has no advanced features. Also, extensibility via 3rd-party plugins is unavailable. On the flip side, it is small and fast, making it ideal for newbies starting with Java. Features: Selection Margin Virtual Folders-Based Projects Line Numbers & File Difference File Properties Viewer Color Syntax Selection Integrated CVS Undo & Redo Functions Class & Interface Wizard Visible Tabs & Spaces Implement Interface Wizard Search & Replace Engine Insert Bean Methods Automatic Indention Project/Folder/File Building Text Formatting Capabilities Execute & Build Project Advanced Editing Commands JDK Tools Comment Selections JDK Profiles Code Folding JDK Debugger Block Selection Classpath Management Colored Bracket Matching Libraries Code Templates Code Identifier Word Wrap Code Completion Spellcheck Code Refractory Tabbed Documents Optimize Imports Docked Toolbars & Workspaces Import Suggestion Full-Screen Mode User Class Coloring Intelligent Docking Assistants Source Code Navigation File Templates Runtime Configurations Workspace Structure Java Console Mounted Projects 21 As we can see, there are abundant of IDE options available for Java developers, ranging from fully-featured commercial software to free and open-source ones. The selection of the Java IDE depends on your current project and personal preference. For our practices we will use Elipse as a standard for our Java Programming Language class. The more a developer knows, the better options there are to choose from. Which Java IDE do you think is the best? For download and installation to your computer, please visit the IDE home pages and download the application. Assessment Task 2 Test your skill. Given the different IDEs, you are given the task written below: Download and install one IDE of your choice for you to use in our Java programming course. Please consider creating a work place folder, where you are to save all your projects and programs to do in our course. Be sure to configure the PATH accordingly. Note: ask your instructor of what IDE you are to install. This is important so as to use a standard IDE in your class. Summary We were introduced the different IDEs we are free to use. These are useful in the development of Java program as we were told for us to be able to write Java program codes, Text editors are needed. As discussed, aside from the various available text editors that we can use like Notepad, Notepad++, we can use a lot more editor which are commonly called Integrated Development Environment (IDE) available in the Internet. They may be commercial or Open-Source application which are most often free for use. 22 Reference Hacker.io. (2021). Most Popular Java IDE for Coding. Retrieved 7 January 2021, from https://hackr.io/blog/best-java-ides 23 MODULE 3 BASIC ELEMENTS OF JAVA Introduction In this Module we learn the basics of Java. As we begin learning the Java programming language, two basic questions naturally arises: First, what is a computer program? Next is, what is programming? To answer, a computer program or program, is a sequence of statements intended to accomplish a task. Programming, on the other hand is a process of planning and creating a program. Those declaration tells the truth, but not the whole truth, about programming. It might take an entire book to give a satisfactory explanation of programming. An analogy might help us gain a better understanding of the nature of programming; thus, we will use topic on which almost everyone has some knowledge…cooking. A recipe is also a program and everyone with some cooking experience can agree on the following: It is easier to follow a recipe than to create one. There are bad and good recipes. Some recipes are easy to follow and some that are hardly to follow. Some recipes produce reliable results, and some are not. To create good new recipes, we must have significant knowledge and understanding of cooking. The points cited above can also be applied in programming. Let us take the cooking analogy. As there are many ways to learn cooking, there are also several ways to learn programming. Learning a programming is like learning to become a chef. A chef cannot be a good chef by just merely reading the recipes. The same is true in programming. We must have the fundamental knowledge of the language; we are able to execute and test the program we wrote to make sure that each program we do does what it is supposed to do. 24 Learning Outcomes At the end of this module, students should be able to: 1. Become familiar with the basic components of Java program such as methods, special symbols, and identifiers. 2. Explore primitive data types. 3. Understand arithmetic operators. 4. Examine how program evaluates arithmetic expressions including mixed expressions. 5. Learn about type casting. 6. Understand how to input data into memory by using input statements. 7. Examine ways to output using output statements. 8. Learn how to import packages and why they are necessary. 9. Learn how to understand correct syntax and discover how to create Java application program. Lesson 1 – Basic of Java Program (Singh, 2013) Before we start learning Java, let us get familiar with common java terms. Java Virtual Machine (JVM) - This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program execution. To recall, the phases are as follows: we write the program, then we compile the program and finally we run the program. 1. Writing of the program is of course done by java programmer like you and me. 2. Compilation of program is done by javac compiler, javac is the primary java compiler included in java development kit (JDK). It takes java program as input and generates java bytecode as output. 3. In third phase, JVM executes the bytecode generated by compiler. This is called program run phase. Now that we understood that the primary function of JVM is to execute the bytecode produced by compiler. Each operating system has different JVM, however the output they produce after execution of bytecode is same across all operating systems. That is why we call java as platform independent language. 25 Bytecode - As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it can be executed by JVM. The bytecode is saved in a.class file by compiler. Java Development Kit (JDK) - While explaining JVM and bytecode, we used the term JDK. As the name suggests this is complete java development kit that includes JRE (Java Runtime Environment), compilers and various tools like JavaDoc, Java debugger etc. To create, compile and run Java program we would need JDK installed on our computer. Java Runtime Environment (JRE) - JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on your system, you can run a java program however you won’t be able to compile it. JRE includes JVM, browser plugins and applets support. When you only need to run a java program on your computer, you would only need JRE. These are the basic java terms that confuses beginners in java. For complete java glossary refer this link: https://docs.oracle.com/javase/tutorial/information/glossary.html Java Virtual Machine (JVM), Difference JDK, JRE & JVM – Core Java Java is a high level programming language. A program written in high level language cannot be run on any machine directly. First, it needs to be translated into that particular machine language. The javac compiler does this thing, it takes java program (.java file containing source code) and translates it into machine code (referred as byte code or.class file). Java Virtual Machine (JVM) is a virtual machine that resides in the real machine (your computer) and the machine language for JVM is byte code. This makes it easier for compiler as it must generate byte code for JVM rather than different machine code for each type of machine. JVM executes the byte code generated by compiler and produce output. JVM is the one that makes java platform independent. So, now we understood that the primary function of JVM is to execute the byte code produced by compiler. Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems. Which means that the byte code generated on Windows can be run on Mac OS and vice versa. That is 26 why we call java as platform independent language. The same thing can be seen in the diagram below: Figure 3.1. Different Operating systems with different JVM JVM Architecture Figure 3.2. JVM Architecture How JVM works: Class Loader: The class loader reads the.class file and save the byte code in the method area. Method Area: There is only one method area in a JVM which is shared among all the classes. This holds the class level information of each.class file. Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for each.class file. Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary variables. 27 PC Registers: This keeps the track of which instruction has been executed and which one is going to be executed. Since instructions are executed by threads, each thread has a separate PC register. Native Method stack: A native method can access the runtime data areas of the virtual machine. Native Method interface: It enables java code to call or be called by native applications. Native applications are programs that are specific to the hardware and OS of a system. Garbage collection: A class instance is explicitly created by the java code and after use it is automatically destroyed by garbage collection for memory management. JVM Vs JRE Vs JDK JRE: JRE is the environment within which the java virtual machine runs. JRE contains Java virtual Machine (JVM), class libraries, and other files excluding development tools such as compiler and debugger which means you can run the code in JRE but you can’t develop and compile the code in JRE. JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE. Figure 3.3. JRE Architecture JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler, debugger etc. 28 Figure 3.4. JRE Architecture Simple Java Program: 1. public class MyFirstJavaProgram { 2. public static void main(String[ ] args){ 3. System.out.println("This is my first program in java"); 4. }//End of main 5. }//End of FirstJavaProgram Class 6. Output: This is my first program in java Closer look to the First Java Program Now that we have understood how to run a java program, let have a closer look at the program we have written above. 1. public class MyFirstJavaProgram { 2. This is the first line of our java program. Every java application must have at least one class definition that consists of class keyword followed by class name. When we say keyword, it means that it should not be changed, we should use it as it is. However, the class name can be anything. We have made the class public by using public access modifier, we need to know now that a java file can have any number of classes but it can have only one public class and the file name should be same as public class name. 1. public static void main(String[ ] args) { 2. 29 This is our next line in the program, let us break it down to understand it: public: This makes the main method public that means that we can call the method from outside the class. static: We do not need to create object for static methods to run. They can run itself. void: It does not return anything. main: It is the method name. This is the entry point method from which the JVM can run our program. (String[ ] args): Used for command line arguments that are passed as strings. 1. System.out.println("This is my first program in java"); 2. This method prints the contents inside the double quotes into the console and inserts a newline after. Lesson 2 – Variables in Java (Singh, 2013) A variable is a name which is associated with a value that can be changed. For example when we write int i=10; here variable name is i which is associated with value 10, int is a data type that represents that this variable can hold integer values. Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a combination of "vary + able" that means its value can be changed. How to Declare a variable in Java To declare a variable, follow this syntax: 1. data_type variable_name = value; 2. here value is optional because in java, you can declare the variable first and then later assign the value to it. For example: Here num is a variable and int is a data type. We will discuss the data type in next so do not worry too much about it, just understand that int data type allows this num variable to hold integer values. 1. int num; 30 2. Similarly, we can assign the values to the variables while declaring them, like this: 1. char ch = 'A'; 2. int number = 100; 3. or we can do it like this: 4. char ch; 5. int number; 6. ch = 'A'; 7. number = 100; 8. Variables naming convention in java Variables naming cannot contain white spaces, for example: int num ber = 100; is invalid because the variable name has space in it. Variable name can begin with special characters such as $ and _ As per the java coding standards the variable name should begin with a lower case letter, for example int number; For lengthy variables names that has more than one words do it like this: int smallNumber; int bigNumber; (start the second word with capital letter). Variable names are case sensitive in Java. Types of Variables in Java There are three types of variables in Java. Local variable Static (or class) variable Instance variable Figure 3.5 – Java Data Types 31 Static (or class) Variable Static variables are also known as class variable because they are associated with the class and common for all the instances of class. For example, If we create three objects of a class and access this static variable, it would be common for all, the changes made to the variable using one of the object would reflect when we access it through other objects. Example of static variable 1. public class StaticVarExample { 2. public static String myClassVar="class or static variable"; 3. 4. public static void main(String args[ ]){ 5. StaticVarExample obj = new StaticVarExample(); 6. StaticVarExample obj2 = new StaticVarExample(); 7. StaticVarExample obj3 = new StaticVarExample(); 8. 9. //All three will display "class or static variable" 10. System.out.println(obj.myClassVar); 11. System.out.println(obj2.myClassVar); 12. System.out.println(obj3.myClassVar); 13. 14. //changing the value of static variable using obj2 15. obj2.myClassVar = "Changed Text"; 16. 17. //All three will display "Changed Text" 18. System.out.println(obj.myClassVar); 19. System.out.println(obj2.myClassVar); 20. System.out.println(obj3.myClassVar); 21. } 22. } 23. Output: class or static variable class or static variable class or static variable Changed Text Changed Text Changed Text As we can see all three statements displayed the same output irrespective of the instance through which it is being accessed. That’s is why we can access the static variables without using the objects like this: 1. System.out.println(myClassVar); 2. Do note that only static variables can be accessed like this. This does not apply for instance and local variables. 32 Instance variable Each instance(objects) of class has its own copy of instance variable. Unlike static variable, instance variables have their own separate copy of instance variable. We have changed the instance variable value using object obj2 in the following program and when we displayed the variable using all three objects, only the obj2 value got changed, others remain unchanged. This shows that they have their own copy of instance variable. Example of Instance variable 1. public class InstanceVarExample { 2. String myInstanceVar="instance variable"; 3. 4. public static void main(String args[]){ 5. InstanceVarExample obj = new InstanceVarExample(); 6. InstanceVarExample obj2 = new InstanceVarExample(); 7. InstanceVarExample obj3 = new InstanceVarExample(); 8. 9. System.out.println(obj.myInstanceVar); 10. System.out.println(obj2.myInstanceVar); 11. System.out.println(obj3.myInstanceVar); 12. 13. obj2.myInstanceVar = "Changed Text"; 14. 15. System.out.println(obj.myInstanceVar); 16. System.out.println(obj2.myInstanceVar); 17. System.out.println(obj3.myInstanceVar); 18. } 19. } 20. Output: instance variable instance variable instance variable instance variable Changed Text instance variable Local Variable These variables are declared inside method of the class. Their scope is limited to the method which means that we cannot change their values and access them outside of the method. In this example, we have declared the instance variable with the same name as local variable, this is to demonstrate the scope of local variables. 33 Example of Local variable 1. public class VariableExample { 2. // instance variable 3. public String myVar="instance variable"; 4. 5. public void myMethod(){ 6. // local variable 7. String myVar = "Inside Method"; 8. System.out.println(myVar); 9. } 10. public static void main(String args[]){ 11. // Creating object 12. VariableExample obj = new VariableExample(); 13. 14. 19. System.out.println("Calling Method"); 20. obj.myMethod(); 21. System.out.println(obj.myVar); 22. } 23. } 24. Output: Calling Method Inside Method instance variable If we had not declared the instance variable and only declared the local variable inside method then the statement System.out.println(obj.myVar); would have thrown compilation error. As you cannot change and access local variables outside the method. Lesson 3 – Data Types in Java (Singh, 2013) Data type defines the values that a variable can take, for example if a variable has int data type, it can only take integer values. In java we have two categories of data types: 1) Primitive data types 2) Non-primitive data types – Arrays and Strings are non-primitive data types. Here we will discuss primitive data types and literals in Java. 34 Table 3.1 Java Data Types Java is a statically typed language. A language is statically typed, if the data type of a variable is known at compile time. This means that you must specify the type of the variable (Declare the variable) before you can use it. In the previous topic about Java Variables, we learned how to declare a variable, lets recall it: int num; So, in order to use the variable num in our program, we must declare it first as shown above. It is a good programming practice to declare all the variables (that you are going to use) in the beginning of the program. 1) Primitive data types In Java, we have eight primitive data types: boolean, int, char, long, byte, float short, double. Java developers included these data types to maintain the portability of java as the size of these primitive data types do not change from one operating system to another. 35 byte, short, int and long data types are used for storing whole numbers. float and double are used for fractional numbers. char is used for storing characters(letters). boolean data type is used for variables that holds either true or false. byte: This can hold whole number between -128 and 127. Mostly used to save memory and when you are certain that the numbers would be in the limit specified by byte data type. Default size of this data type: 1 byte. Default value: 0 Example: 1. class JavaExample { 2. public static void main(String[ ] args) { 3. byte num; 4. num = 113; 5. System.out.println(num); 6. } 7. } 8. Output: 113 Try the same program by assigning value assigning 150 value to variable num, you would get type mismatch error because the value 150 is out of the range of byte data type. The range of byte as I mentioned above is -128 to 127. short: This is greater than byte in terms of size and less than integer. Its range is -32,768 to 32767. Default size of this data type: 2 byte short num = 45678; int: Used when short is not large enough to hold the number, it has a wider range: - 2,147,483,648 to 2,147,483,647 36 Default size: 4 byte Default value: 0 Example: 1. class JavaExample { 2. public static void main(String[ ] args) { 3. short num; 4. num = 150; 5. System.out.println(num); 6. } 7. } 8. Output: 150 The byte data type could not hold the value 150 but a short data type can because it has a wider range. long: Used when int is not large enough to hold the value, it has wider range than int data type, ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. size: 8 bytes Default value: 0 Example: 1. class JavaExample { 2. public static void main(String[ ] args) { 3. long num = -12332252626L; 4. System.out.println(num); 5. } 6. } 7. Output: -12332252626 double: Sufficient for holding 15 decimal digits size: 8 bytes 37 Example: 1. class JavaExample { 2. public static void main(String[ ] args) { 3. double num = -42937737.9d; 4. System.out.println(num); 5. } 6. } 7. Output: -4.29377379E7 float: Sufficient for holding 6 to 7 decimal digits size: 4 bytes 1. class JavaExample { 2. public static void main(String[ ] args) { 3. float num = 19.98f; 4. System.out.println(num); 5. } 6. } 7. Output: 19.98 boolean: holds either true of false. 1. class JavaExample { 2. public static void main(String[ ] args) { 3. boolean b = false; 4. System.out.println(b); 5. } 6. } 7. Output: False 38 char: holds characters. size: 2 bytes 1. class JavaExample { 2. public static void main(String[ ] args) { 3. char ch = 'Z'; 4. System.out.println(ch); 5. } 6. } 7. Output: Z Literals in Java A literal is a fixed value that we assign to a variable in a Program. int num=10; Here value 10 is a Integer literal. char ch = 'A'; Here A is a char literal Integer Literal Integer literals are assigned to the variables of data type byte, short, int and long. byte b = 100; short s = 200; int num = 13313131; long l = 928389283L; Float Literals Used for data type float and double. double num1 = 22.4; float num2 = 22.4f; Note: Always suffix float value with the “f” else compiler will consider it as double. Char and String Literal Used for char and String type. char ch = 'Z'; String str = "BeginnersBook"; 39 Lesson 4. Operators in Java (Singh, 2013) One of the most important features of a computer is its ability yo calculate. We use operands and operator in an expression. An operator is a character that represents an action, for example + is an arithmetic operator that represents addition. There are two types of expression: a) unary and b) binary Unary – an expression that uses unary operator where an operator has only one operand, situated either on its left or right. Binary – an expression that uses binary operator where an operator has two operands placed on both its sides. Ternary - the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is true followed by a colon ( : ), and finally the expression to execute if the condition is false. Types of Operator in Java 1. Basic Arithmetic Operators 2. Assignment Operator 3. Auto-increment and Auto-decrement Operators 4. Logical Operators 5. Comparison (relational) operators 6. Bitwise Operators 7. Ternary Operator Basic Arithmetic Operators Table 4.1 Arithmetic Operators 40 Example of Arithmetic Operators 1. public class ArithmeticOperatorDemo { 2. public static void main(String args[]) { 3. int num1 = 100; 4. int num2 = 20; 5. 6. System.out.println("num1 + num2: " + (num1 + num2) ); 7. System.out.println("num1 - num2: " + (num1 - num2) ); 8. System.out.println("num1 * num2: " + (num1 * num2) ); 9. System.out.println("num1 / num2: " + (num1 / num2) ); 10. System.out.println("num1 % num2: " + (num1 % num2) ); 11. } 12. } 13. Output: num1 + num2: 120 num1 - num2: 80 num1 * num2: 2000 num1 / num2: 5 num1 % num2: 0 2) Assignment Operators Table 4.2 Assignment Operators 41 Assignments operators in java are: =, +=, -=, *=, /=, %= num2 = num1 would assign value of variable num1 to the variable. num2+=num1 is equal to num2 = num2+num1 num2-=num1 is equal to num2 = num2-num1 num2*=num1 is equal to num2 = num2*num1 num2/=num1 is equal to num2 = num2/num1 num2%=num1 is equal to num2 = num2%num1 Example of Assignment Operators 1. public class AssignmentOperatorDemo { 2. public static void main(String args[]) { 3. int num1 = 10; 4. int num2 = 20; 5. 6. num2 = num1; 7. System.out.println("= Output: "+num2); 8. 9. num2 += num1; 10. System.out.println("+= Output: "+num2); 11. 12. num2 -= num1; 13. System.out.println("-= Output: "+num2); 14. 15. num2 *= num1; 16. System.out.println("*= Output: "+num2); 17. 18. num2 /= num1; 19. System.out.println("/= Output: "+num2); 20. 21. num2 %= num1; 22. System.out.println("%= Output: "+num2); 23. } 24. } 25. 42 Output: = Output: 10 += Output: 20 -= Output: 10 *= Output: 100 /= Output: 10 %= Output: 0 3) Auto-increment and Auto-decrement Operators (Unary Operators) Table 4.3 Unary Operators The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.: incrementing/decrementing a value by one negating an expression inverting the value of a boolean ++ and - - num++ is equivalent to num=num+1; num - - is equivalent to num=num-1; Example of Auto-increment and Auto-decrement Operators 1. public class AutoOperatorDemo { 2. public static void main(String args[]){ 3. int num1=100; 4. int num2=200; 5. num1++; 6. num2--; 7. System.out.println("num1++ is: "+num1); 8. System.out.println("num2-- is: "+num2); 9. } 10. } 11. Output: num1++ is: 101 num2-- is: 199 43 4) Logical Operators Logical Operators are used with binary variables. They are mainly used in conditional statements and loops for evaluating a condition. Table 4.4 Logical Operators Let’s say we have two boolean variables b1 and b2. b1&&b2 will return true if both b1 and b2 are true else it would return false. b1||b2 will return false if both b1 and b2 are false else it would return true. !b1 would return the opposite of b1, that means it would be true if b1 is false and it would return false if b1 is true. Example of Logical Operators 1. public class LogicalOperatorDemo { 2. public static void main(String args[]) { 3. boolean b1 = true; 4. boolean b2 = false; 5. 6. System.out.println("b1 && b2: " + (b1&&b2)); 7. System.out.println("b1 || b2: " + (b1||b2)); 8. System.out.println("!(b1 && b2): " + !(b1&&b2)); 9. } 10. } 11. 12. Output: b1 && b2: false b1 || b2: true !(b1 && b2): true 5) Comparison (Relational) operators Table 4.5 Comparison Operators 44 We have six relational operators in Java: ==, !=, >, =, returns true if left side is greater than right. < returns true if left side is less than right side. >= returns true if left side is greater than or equal to right side. num2 ){ 18. System.out.println("num1 is greater than num2"); 19. } 20. else{ 21. System.out.println("num1 is not greater than num2"); 22. } 23. if( num1 >= num2 ){ 24. System.out.println("num1 is greater than or equal to num2"); 25. } 26. else{ 27. System.out.println("num1 is less than num2"); 45 28. } 29. if( num1 < num2 ){ 30. System.out.println("num1 is less than num2"); 31. } 32. else{ 33. System.out.println("num1 is not less than num2"); 34. } 35. if( num1 2 is right shift operator that moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent to 00000010 Example of Bitwise Operators 1. public class BitwiseOperatorDemo { 2. public static void main(String args[]) { 3. 4. int num1 = 11; 5. int num2 = 22; 6. int result = 0; 7. 8. result = num1 & num2; 9. System.out.println("num1 & num2: "+result); 10. 11. result = num1 | num2; 47 12. System.out.println("num1 | num2: "+result); 13. 14. result = num1 ^ num2; 15. System.out.println("num1 ^ num2: "+result); 16. 17. result = ~num1; 18. System.out.println("~num1: "+result); 19. 20. result = num1 > 2; 22. System.out.println("num1 >> 2: "+result); 23. } 24. } 25. Output: num1 & num2: 2 num1 | num2: 31 num1 ^ num2: 29 ~num1: -12 num1 > 2: 2 There are six bitwise Operators: &, |, ^, ~, num1 = 11; num2 = 22; Bitwise operator performs bit by bit processing. num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if both bits are equal, else it returns 0. In our case it would return: 2 which is 00000010 because in the binary form of num1 and num2 only second last bits are matching. num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either bit is 1, else it returns 0. In our case it would return 31 which is 00011111 num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they are not equal, else it returns 0. In our example it would return 29 which is equivalent to 00011101 ~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our example it would return -12 which is signed 8 bit equivalent to 11110100 48 num1 2; 22. System.out.println("num1 >> 2: "+result); 23. } 24. } 25. Output: num1 & num2: 2 num1 | num2: 31 num1 ^ num2: 29 ~num1: -12 num1 > 2: 2 7) Ternary Operator This operator evaluates a boolean expression and assign the value based on the result. Syntax: variable num1 = (expression) ? value if true : value if false If the expression results true then the first value before the colon (:) is assigned to the variable num1 else the second value is assigned to the num1. Example of Ternary Operator 49 1. public class TernaryOperatorDemo { 2. 3. public static void main(String args[]) { 4. int num1, num2; 5. num1 = 25; 6. 10. num2 = (num1 == 10) ? 100: 200; 11. System.out.println( "num2: "+num2); 12. 13. 17. num2 = (num1 == 25) ? 100: 200; 18. System.out.println( "num2: "+num2); 19. } 20. } 21. Output: num2: 200 num2: 100 Operator Precedence in Java This determines which operator needs to be evaluated first if an expression has more than one operator. Operator with higher precedence at the top and lower precedence at the bottom. Unary Operators ++ – – ! ~ Multiplicative * /% Additive + – Shift > >>> Relational > >= < >= <