Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Module 2: The Java Programming Language Brief Background The Java programming language was created in 1991 by James Gosling et al. of Sun Microsystems. Initially called Oak, in honor of the tree outside Gosling's window, its name was changed to Java because there was already a language called...

Module 2: The Java Programming Language Brief Background The Java programming language was created in 1991 by James Gosling et al. of Sun Microsystems. Initially called Oak, in honor of the tree outside Gosling's window, its name was changed to Java because there was already a language called Oak. The original motivation for Java was the need for platform independent language that could be embedded in various consumer electronic products like toasters and refrigerators. One of the first projects developed using Java was a personal hand-held remote control named Star 7. At about the same time, the World Wide Web and the Internet were gaining popularity. Gosling et al. realized that Java could be used for Internet programming.  developed in early 1990s by James Gosling et. al. as the programming language component of the Green Project at Sun Microsystems  originally named Oak and intended for programming networked “smart” consumer electronics  launched in 1995 as a “programming language for the Internet”; quickly gained popularity with the success of the World Wide Web  currently used by millions of software developers and powers billions of devices worldwide, from computers to mobile phones  design goals o simple: derived from C/C++, but easier to learn o secure: built-in support for compile-time and run-time security o distributed: built to run over networks o object-oriented: built with OO features from the start o robust: featured memory management, exception handling, etc. o portable: “write once, run anywhere'' (WORA) o interpreted: “bytecodes” executed by the Java Virtual Machine o multithreaded, dynamic, high-performance, architecture-neutral The Java Technology As a programming language, Java can be used to create all kinds of applications that may be created using any other conventional programming language. As a development environment, Java technology provides a suite of tools: a compiler, an interpreter, a documentation generator, a class file packaging tool, and so on. Java technology applications are typically general-purpose programs that run on any machine where the Java runtime environment (JRE) is installed. There are two main deployment environments: The JRE, supplied by the Java Software Development Kit (SDK), that contains the complete set of class files for all the Java technology packages, which includes basic language classes, GUI component classes, and so on. The other Computer Programming 1 SLU-SAMCIS 1|P age main deployment environment is the web browser. Most commercial browsers supply a Java technology interpreter and runtime environment. The Java Programming Process The following figure describes the process of compiling and executing a Java program. The programming process summarized in the figure does not include the problem analysis and program design. It is assumed that the programmer has algorithm that is to be implemented using the Java programming language. The first step in creating a Java program is writing a program using a text editor. Examples of text editors that can be used are notepad, vi, emacs, pico, etc. The written program is saved in a file and is stored with a name that has the extension.java. The saved program is called the source code or source program. After creating and saving the Java program, the source code is compiled by using the Java Compiler. The output of this process is a file called a bytecode and is automatically saved in a file with the same name as the source file except that the extension is.class. The compilation cannot be completed unless there are no syntax errors in the program. This said, the compilation process may display descriptive messages regarding errors in the program (syntax errors). The programmer should fix the syntax errors, then, the programmer restarts the compilation process. A bytecode is a special machine language that can be understood by the Java Virtual Machine (JVM). The bytecode is independent of any particular computer hardware, so any computer with a Java interpreter can execute the compiled Java program(bytecode), no matter what type of computer the program was compiled on. The Java Virtual Machine is an imaginary machine that is implemented by emulating software on a real machine. The JVM provides the hardware platform specifications to which you compile all Java technology code. This specification enables the Java software to be platform- independent because the compilation is done for a generic machine known as the JVM. The.class file (bytecode) is interpreted by the Java interpreter that converts the bytecodes in the file into the machine language of the particular computer that is being used. To reiterate, the table and figure (next page) show the processes performed when creating a program using the Java programming language. Computer Programming 1 SLU-SAMCIS 2|P age Computer Programming 1 SLU-SAMCIS 3|P a ge Java Platform  Java Virtual Machine, or JVM: a virtual machine, usually implemented as a program, which interprets the bytecodes produced by the Java compiler; the JVM converts the bytecode instructions to equivalent machine language code of the underlying hardware; compiled Java programs can be executed on any device that has a JVM Image source: The Java Tutorials Bundle  Java Application Programming Interfaces, or Java API: large collection of ready-made software components that provide many useful capabilities; The Java API has predefined library classes in it, organized in packages Examples of Java API Class Library Packages java.lang : basic language functionality java.io : input and output capabilities Computer Programming 1 SLU-SAMCIS 4|P a ge java.util : utility classes, collection classes java.net : network access java.sql : database access java.awt, javax.swing : graphical user interfaces java.beans : reusable components  Java Platform Tools and Utilities javac - compiler java - bytecode interpreter (JVM) jdb - debugger javadoc - documentation tool jar - archive utility Version History  May 1995 : product launching  Jan 1996 : JDK 1.0 (initial release)  Feb 1997 : JDK 1.1  Dec 1998 : J2SE 1.2 (a.k.a Java 2 Platform, codename Playground)  May 2000 : J2SE 1.3 (codename Kestrel)  Feb 2002 : J2SE 1.4 (codename Merlin, first release under the Java Community Process as JSR 59)  Sep 2004 : J2SE 5.0 (a.k.a. Java 5, codename Tiger, JSR 176)  Java SE 6 (codename Mustang, JSR 270, released late 2006)  Java SE 7 (codename Dolphin, for release 2008)  … and more versions came along the way.  Java 8 introduced the concept of a Lambda Expression (Anonymous functions)  Java 14 is the most current stable version Java Platform Editions  Java SE or Standard Edition - basic Java platform development  Java EE or Enterprise Edition - development of distributed multi-tier applications for enterprise-scale use  Java ME, or Micro Edition - development of applications targeted on resource constrained devices such as cell phones, PDAs, and other appliances  Java Card - this technology allows small Java-based applications, such as applets, to run securely on smart cards and other similar small- memory devices. Computer Programming 1 SLU-SAMCIS 5|P age Types of Java Programs  stand-alone applications  applets : small Java programs embedded in web pages and designed to run on web browsers  servlets : applications that provide dynamic content capabilities for web servers  portlets : pluggable user interface components used in web portals  MIDlets : applications designed to run on Mobile Information Devices such as cell phones and PDAs For our Computer Programming 1 course, we will be creating simple stand-alone applications. You should check the separate file that provides the instructions on how you can install the environment you will be using for the programming exercises. For reference the Visual Studio Code will be used to code your Java programs. Note that if the code does not provide a package statement, it means that you will place the source code file from within the workspace you have defined. From the instruction provided, the workspace defined is 9300-2021_Dela Cruz, Juan which means that all source code files having no package statement must be placed within this location. For the purpose of organization, it will be best to place sample codes within a specific folder (package) so that you will easily identify your activity files from those of the example codes. In this regard, feel free to place all sample codes provided in this material into their appropriate folder location/s (package/s). Example of a program written in Java The following is an example of a Java program. This program should be saved in a file named HelloPhilippines.java. Problem: Write a program that prints Hello World! Hello Philippines on the output screen Algorithm: Input: None Output: Message “Hello World! Hello Philippines” Process: 1. Print Hello World! Hello Philippines 2. End Computer Programming 1 SLU-SAMCIS 6|P age import java.lang.*; public class HelloPhilippines { public static void main(String[] args) { // prints the string "Hello world! Hello Philippines!" on the screen System.out.println("Hello world! Hello Philippines!"); // Let the program end System.exit(0); } } The first line of the code, import java.lang.*; indicates that any existing program that is in a package called lang may be accessed/used in the program. This is an optional statement because any java program will have automatic access to the java.lang package. It is, however, a good programming practice to include the import java.lang.* statement in order to imply that the programmer is aware that the program is using some programs in the said package. The second line of the code public class HelloPhilippines begins the class declaration. The line indicates that the name of the class is HelloPhilippines. In Java, a class has a block of codes. All codes should be placed inside a class declaration. We do this by using the class keyword. In addition, the class uses an access specifier public, which indicates that our class is accessible to other classes from other packages (A package is a collection of classes). Packages and access specifiers will be discussed further under a future topic. The next line which contains a curly brace { indicates the start of a block. In this code, we placed the curly brace at the next line after the class declaration, however, we can also place this next to the first line of our code. So, we could actually write our code as: public class HelloPhilippines { or public class HelloPhilippines { The next three lines compose a Java comment. A comment is a remark given to explain a part of a code. It is not part of the logic of the program that the computer needs to process, but it is used for documentation purposes. It is good programming practice to add comments to your code. A comment must be enclosed by the delimiters “”. Anything within these delimiters are ignored by the Java compiler, and are treated as comments or notes. Computer Programming 1 SLU-SAMCIS 7|P age The next line, public static void main(String[] args) { or can also be written as, public static void main(String[] args) { indicates the name of one method in the HelloPhilippines class which is the main method. The main method is the starting point whenever a Java program is executed. All executable programs except Applets written in Java have a main method. Make sure to follow the exact signature of the main method. The method’s name should be spelled with lowercase letters and there is a following parenthesis enclosing String[] args. The next line is also a Java comment, //prints the string "Hello world! Hello Philippines!" on the screen There are two ways of including comments in the program. The first one is by placing the comment inside , and the other one is by writing // at the start of the comment. It must be noted that // is a one-line comment delimiter which means the comment should not continue on the next line. The next line, System.out.println("Hello world! Hello Philippines"); prints the text “Hello World! Hello Philippines” on the screen. The command System.out.println(), prints the text enclosed by quotation on the screen. The next line, System.exit(0); tells the computer to close the program. This statement is also optional because the program closes anyway when there are no more statements to be executed. Again, it is suggested that the statement be included for the programmer to imply that he/she is aware of the flow of execution of the program. The last two lines, each of which contains a curly brace, are used to close the block of codes for the main method and class respectively. Coding Guidelines:  The filename for a Java program should always end with the.java extension.  The filename should match the name of the public class. So for example, if the name of your public class is HelloPhilippines, you should save it in a file called HelloPhilippines.java. Note that a space is NOT included in the name of the class even if the name is composed of two words. By convention the name of a class should begin with a capital letter followed by small letters. If the name of the class is formed out of more than one word, every first letter of the word should be in capital letter form. This style of giving a name is called Pascal-case.  You should write comments in your code explaining what a certain class does, or what a certain method does. Computer Programming 1 SLU-SAMCIS 8|P age A Programming Style that is practiced by some programmers is using a run method It is suggested that you follow a programming style that will minimize the statements in the main method of your program. Instead of putting several statements in the block of code for the main method, the statements are in a run method. The run method is then invoked/called by the main method. In fact, other methods may be included such that these other methods are, in turn, invoked/called by the run method/other methods. Consider the following version of the HelloPhilippines program. import java.lang.*; public class HelloPhilippinesB { public static void run() { //prints the string "Hello world! Hello Philippines!" System.out.println("Hello world! Hello Philippines"); } // end of run method public static void main(String[] args) { run(); // Call the static run method System.exit(0); // Let the program close } // end of main method } // end of HelloPhilippinesB class ( end of program) The program may also be written in the following form. import java.lang.*; import java.io.*; public class HelloPhilippinesC { public void run() throws IOException { //prints the string "Hello world! Hello Philippines!" System.out.println("Hello world! Hello Philippines"); } // end of run method public static void main(String[] args) { HelloPhilippinesC myProgram; try { // the following statement instantiates the Hello class myProgram = new HelloPhilippinesC(); myProgram.run(); // call the non-static run method } // end of try block catch (Exception e) { e.printStackTrace(); } // end of catch block System.exit(0); // Let the program close } // end of main method } // end of HelloPhilippinesC class ( end of program) Computer Programming 1 SLU-SAMCIS 9|P age The involvement of try and catch in the program is a mechanism for Exception Handling. Exception Handling has something to do with letting the computer deal with anticipated problems when the program is executed. Exception Handling will be discussed in a future lesson. In the meantime, the above sample code can just serve as a template and that the template can just be copied. If the problem being solved is considerably complex, the run method may invoke other methods that are included in the class/program. This approach allows any reader to easily follow the program. Java Comments Comments are notes written to a code for documentation purposes. Those text are not part of the program and does not affect the flow of the program. Java supports three types of comments: single line comments, multiline comments and special javadoc comments. Single Line Comments Single line comments start with //. The text from the characters // to the end of the line is ignored by the compiler since the text after // is treated as a comment. For example, // This is a single line comment Multiline Comments Multiline comments start with a. All texts in between the two delimiters are treated as comments. The text from the characters are ignored by the compiler. Unlike single line comments, it can span multiple lines. For example, Special Javadoc Comments Special Javadoc comments are used for generating an HTML documentation for Java programs. You can create a javadoc comment by starting the line with. The text within the is intended to be processed by the Javadoc program. The Javadoc program is used to automatically create a formatted document for the java program. Like multiline comments, it can also span lines. It can also contain certain tags to add more information. For example, Computer Programming 1 SLU-SAMCIS 10 | P a g e Comments do not nest, i.e., that is, the characters have no special meaning in comments that begin with //, and the characters // has no special meaning in comments that begin with boolean result; char option; option = 'C'; //assign 'C' to option double grade = 0.0; } // end of the run method public static void main(String[] args) { run(); // Invoke the static run method System.exit(0); // Let the program close } // end of the main method } // end of the VariableDemo2 class Computer Programming 1 SLU-SAMCIS 19 | P a g e Below is an equivalent program with a run method. (Filename: VariableDemo3.java) import java.lang.*; import java.io.*; public class VariableDemo3 { public void run() throws IOException { boolean result; char option; option = 'C'; // assign 'C' to option double grade = 0.0; } // end of the run method public static void main(String[] args) { VariableDemo3 myDemo; try { myDemo = new VariableDemo3(); // Instantiate the VariabeDemo3 class myDemo.run(); // Invoke the non-static run method } catch (Exception e) { e.printStackTrace(); } System.exit(0); } // end of the main method } // end of the VariableDemo3 class Coding Guidelines: 1. It always good to initialize your variables as you declare them. 2. Use descriptive names for your variables. Like for example, if you want to have a variable that contains a grade for a student, name it as, grade and not just some random letters you choose. 3. Declare one variable per line of code. For example, the variable declarations, double exam = 0; double quiz = 10; double grade = 0; is preferred over the declaration, double exam = 0, quiz = 10, grade = 0; Reading values from the keyboard For some applications, values to be assigned to variables are entered through the keyboard during program execution. Java provides a mechanism for connecting the keyboard to the program. Getting Inputs from the Input Device For some applications, values assigned to variables are entered through the keyboard during program execution. Computer Programming 1 SLU-SAMCIS 20 | P a g e Java provides mechanisms for reading values from input devices. One mechanism is using the Scanner class which is in the java.util package. Using the Scanner class to reading values from the keyboard Include the statement, import java.util.Scanner; in your program then include the variable declaration and instantiation statement Scanner scanner = new Scanner(System.in); in the block/body of a method that performs the input reading. The import statement must be placed above the class declaration. (The import statement must be before public class ProgramName) Assuming that the program has the following statements: import java.util.Scanner; Scanner keyboard = new Scanner(System.in); int age = 0; double rate = 0.0; The statement to let an integer value be assigned to age through the keyboard is age = keyboard.nextInt(); or age = Integer.parseInt(keyboard.nextLine()); // preferred way The statement to let a double value be assigned to rate through the keyboard is rate = keyboard.nextDouble(); or rate = Double.parseDouble(keyboard.nextLine()); // preferred way When the nextLine() method is used, anything entered through the keyboard is recognized as a string as far as the computer is concerned. (When 19 is entered, 19 is seen by the computer as a string) When the string is passed to the parseInt() method, the string becomes an integer. Hence, age = Integer.parseInt(keyboard.nextLine()); The same holds for a floating point value (i.e. number with decimal digits). Hence, rate = Double.parseDouble(keyboard.nextLine()); The other methods that may be used where appropriate are parseByte(), parseShort(), parseLong(), parseFloat() Note: An Exception object (i.e. NumberFormatException) is thrown by the parse method when it is given a string that cannot be converted into a number. For good Java programs, Exception handling where possible is implemented. Exception Handling is tackled in a future lesson. For now, assume that you will always be careful when entering input values so that the program execution will not result to a problem. Computer Programming 1 SLU-SAMCIS 21 | P a g e Outputting the value held by a Variable Using System.out.print and/or System.out.println. In order to output the value of a certain variable, the following program statements may be used. System.out.println() System.out.print() The following program illustrates how the value of a variable is shown on the screen. (Filename: OutputVariable1.java) import java.lang.*; public class OutputVariable1 { public static void main(String[] args) { int value = 10; char x; x = 'A'; System.out.println(value); System.out.println(); // skip a line System.out.println("The value of x = " + x); System.exit(0); } // end of the main method } // end of the OutputVariable1 class Equivalent program with a run method. (Filename: OutputVariable2.java) import java.lang.*; public class OutputVariable2 { public static void run() { int value = 10; char x; x = 'A'; System.out.println(value); System.out.println(); // skip a line System.out.println("The value of x = " + x); } public static void main(String[] args) { run(); // call the static run method System.exit(0); } } Equivalent program with a run method. (Filename: OutputVariable3.java) import java.lang.*; import java.io.*; public class OutputVariable3 { public void run() throws IOException { int value = 10; char x; x = 'A'; System.out.println(value); System.out.println(); // skip a line System.out.println("The value of x = " + x); } Computer Programming 1 SLU-SAMCIS 22 | P a g e public static void main( String[] args ) { OutputVariable3 mySample; try { mySample = new OutputVariable3(); mySample.run(); // call the non-static run method } catch (Exception e) { e.printStackTrace(); } System.exit(0); } } The program will output the following text on screen, 10 The value of x = A System.out.println() vs. System.out.print() What is the difference between the commands System.out.println() and System.out.print()? The first one appends a newline at the end of the data to output, while the latter doesn't. Consider the statements, System.out.print("Hello "); System.out.print("world!"); These statements will output the following on the screen, Hello world! Now consider the following statements, System.out.println("Hello "); System.out.println("world!"); These statements will output the following on the screen, Hello world! Reference Variables vs. Primitive Variables There are two types of variables that Java programs may have. These are reference variables and primitive variables. Primitive variables are variables that store primitive data types (literals). They store data in the actual memory location of where the variable is. Reference variables are variables that store an address of a memory location. It points to another memory location where the actual data is located. When you declare a variable of a certain class, you are actually declaring a reference variable to an object of that certain class. Computer Programming 1 SLU-SAMCIS 23 | P a g e For example, suppose we have two variables with data types int and String. int num = 10; String name = "Hello" Suppose, the illustration shown below is the actual memory of your computer, wherein you have the address of the memory cells, the variable name and the data they hold. Memory Variable Data Address Name 1001 num 10 : : 1563 name Address(2000) : : : : 2000 "Hello" As you can see, for the primitive variable num, the data is on the actual location of where the variable is. For the reference variable name, the variable just holds the address of another memory location where the actual data is. Operators In Java, there are different types of operators. There are arithmetic operators, relational operators, logical operators and conditional operators. These operators follow a precedence rule so that the compiler will know which operator to evaluate first in case multiple operators are used in one statement. Symbolic Constants A symbolic constant is used when the value involved should not change. Instead of using a literal value, declare as final a variable and assign a value as illustrated below. Illustration: final double PI = 3.141592654; // PI is a symbolic constant double area, radius; // area and radius are variables. : : : radius = 2.0; area = radius * radius * PI; PI = 3.1416; // semantic error! you cannot assign a value to a constant (final)! Computer Programming 1 SLU-SAMCIS 24 | P a g e 3.141592654 is a “magic number”. In programming, it is best to avoid using magic numbers. Besides, using a symbolic constant (named constant) simplifies the task of modifying should the value of the constant is changed. Arithmetic operators Here are the basic arithmetic operators that can be used in creating your Java programs, Operator Use Description + op1 + op2 Adds op1 and op2 * op1 * op2 Multiplies op1 by op2 / op1 / op2 Divides op1 by op2 % op1 % op2 Computes the remainder when op1 is divided by op2 - op1 - op2 Subtracts op2 from op1 Arithmetic operations and their functions Here's a sample program that uses the operators. (Filename: ArithmeticDemo.java) import java.lang.*; public class ArithmeticDemo { public static void main(String[] args) { // a few numbers int i = 37; int j = 42; double x = 27.475; double y = 7.22; System.out.println("Variable values..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" x = " + x); System.out.println(" y = " + y); //adding numbers System.out.println("Adding..."); System.out.println(" i + j = " + (i + j)); System.out.println(" x + y = " + (x + y)); // subtracting numbers System.out.println("Subtracting..."); System.out.println(" i - j = " + (i - j)); System.out.println(" x - y = " + (x - y)); // multiplying numbers System.out.println("Multiplying..."); System.out.println(" i * j = " + (i * j)); System.out.println(" x * y = " + (x * y)); Computer Programming 1 SLU-SAMCIS 25 | P a g e // dividing numbers System.out.println("Dividing..."); System.out.println(" i / j = " + (i / j)); System.out.println(" x / y = " + (x / y)); // computing the remainder resulting from dividing numbers System.out.println("Computing the remainder..."); System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); //mixing types System.out.println("Mixing types..."); System.out.println(" j + y = " + (j + y)); System.out.println(" i * x = " + (i * x)); } // end of the main method } // end of the class Equivalent Program (Filename: ArithmeticDemoB.java) import java.lang.*; public class ArithmeticDemoB { public static void run() { // a few numbers int i = 37; int j = 42; double x = 27.475; double y = 7.22; System.out.println("Variable values..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" x = " + x); System.out.println(" y = " + y); // adding numbers System.out.println("Adding..."); System.out.println(" i + j = " + (i + j)); System.out.println(" x + y = " + (x + y)); // subtracting numbers System.out.println("Subtracting..."); System.out.println(" i - j = " + (i - j)); System.out.println(" x - y = " + (x - y)); // multiplying numbers System.out.println("Multiplying..."); System.out.println(" i * j = " + (i * j)); System.out.println(" x * y = " + (x * y)); // dividing numbers System.out.println("Dividing..."); System.out.println(" i / j = " + (i / j)); System.out.println(" x / y = " + (x / y)); Computer Programming 1 SLU-SAMCIS 26 | P a g e // computing the remainder resulting from dividing numbers System.out.println("Computing the remainder..."); System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); // mixing types System.out.println("Mixing types..."); System.out.println(" j + y = " + (j + y)); System.out.println(" i * x = " + (i * x)); } public static void main(String[] args) { run(); // call the static run method System.exit(0); } // end of the main method } // end of the class Equivalent Program (Filename: ArithmeticDemoC.java) import java.lang.*; import java.io.*; public class ArithmeticDemoC { public void run() throws IOException { // a few numbers int i = 37; int j = 42; double x = 27.475; double y = 7.22; System.out.println("Variable values..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" x = " + x); System.out.println(" y = " + y); // adding numbers System.out.println("Adding..."); System.out.println(" i + j = " + (i + j)); System.out.println(" x + y = " + (x + y)); // subtracting numbers System.out.println("Subtracting..."); System.out.println(" i - j = " + (i - j)); System.out.println(" x - y = " + (x - y)); // multiplying numbers System.out.println("Multiplying..."); System.out.println(" i * j = " + (i * j)); System.out.println(" x * y = " + (x * y)); // dividing numbers System.out.println("Dividing..."); System.out.println(" i / j = " + (i / j)); System.out.println(" x / y = " + (x / y)); // computing the remainder resulting from dividing numbers System.out.println("Computing the remainder..."); System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); Computer Programming 1 SLU-SAMCIS 27 | P a g e // mixing types System.out.println("Mixing types..."); System.out.println(" j + y = " + (j + y)); System.out.println(" i * x = " + (i * x)); } public static void main(String[] args) { ArithmeticDemoC myProgram; try { myProgram = new ArithmeticDemoC(); myProgram.run(); // Call the non-static run method } catch (Exception e) { e.printStackTrace(); } System.exit(0); } } Here is the sample output of the program, Variable values... i = 37 j = 42 x = 27.475 y = 7.22 Adding... i + j = 79 x + y = 34.695 Subtracting... i - j = -5 x - y = 20.255 Multiplying... i * j = 1554 x * y = 198.37 Dividing... i / j = 0 x / y = 3.8054 Computing the remainder... i % j = 37 x % y = 5.815 Mixing types... j + y = 49.22 i * x = 1016.58 Note: When an integer and a floating-point number are used as operands to a single arithmetic operation, the result is a floating point. The integer is implicitly converted to a floating-point number before the operation takes place. Computer Programming 1 SLU-SAMCIS 28 | P a g e The following is another sample program. The program reads an input from the user at runtime. (Filename: CircleArea.java) Problem: Write a program for computing the area of a circle with a specified radius. Algorithm: Input: radius of the circle Output: area of the circle Process: 1. Display a message that describes the application 2. Let radius represent the radius of the circle 3. Let area represent the area of the circle 4. Display a prompt message for the user to enter the radius 5. Read the radius 6. Compute the area where area = pi * radius * radius 7. Display the radius and area of the circle 8. End the program import java.lang.*; import java.util.Scanner; public class CircleArea { public static void main(String[] args) { // reference to the keyboard as source of input Scanner keyboard = new Scanner(System.in); double radius, area; // display message prompting the user to input the radius of the circle System.out.println("\nThis program will compute the area of a circle."); System.out.print("Enter the radius of the circle:"); // The radius of the circle is an input from the keyboard radius = keyboard.readDouble(); // compute the area of the circle area = Math.PI * radius * radius; // display the area on the screen System.out.println("The area of the circle with radius =" + radius + " is: " + area); System.exit(0); } // end of the main method } // end of the class Equivalent Program (Filename: CircleAreaB.java) import java.lang.*; import java.util.Scanner; public class CircleAreaB { Computer Programming 1 SLU-SAMCIS 29 | P a g e public static void run(){ // reference to the keyboard as source of input Scanner keyboard = new Scanner(System.in); double radius, area; // display message prompting the user to input the radius of the circle System.out.println("\nThis program will compute the area of a circle."); System.out.print("Enter the radius of the circle:"); // The radius of the circle is an input from the keyboard radius = keyboard.readDouble(); // compute the area of the circle area = Math.PI * radius * radius; // display the area on the screen System.out.println("The area of the circle with radius =" + radius + " is: " + area); } public static void main (String[] args){ run(); // call the static run method System.exit(0); } // end of the main method } // end of the class Equivalent Program (Filename: CircleAreaC.java) import java.lang.*; import java.util.Scanner; import java.io.*; public class CircleAreaC { // reference to the keyboard as source of input Scanner keyboard = new Scanner(System.in); private void run() throws Exception { double radius, area; // display message prompting the user to input the radius of the circle System.out.println("\nThis program will compute the area of a circle."); System.out.print("Enter the radius of the circle:"); // The radius of the circle is an input from the keyboard radius = keyboard.readDouble(); // compute the area of the circle area = Math.PI * radius * radius; // display the area on the screen System.out.println("The area of the circle with radius =" + radius + " is: " + area); } Computer Programming 1 SLU-SAMCIS 30 | P a g e public static void main (String[] args){ CircleAreaC myProgram; try { myProgram = new CircleAreaC(); myProgram.run(); // call the non-static run method } catch(Exception e) { e.printStackTrace(); } System.exit(0); } } Increment and Decrement operators Aside from the basic arithmetic operators, Java also includes a unary increment operator (++) and unary decrement operator (--). Increment and decrement operators increase and decrease a value stored in a number variable by 1. For example, the expression, count = count + 1; // increment the value of count by 1 is equivalent to, count++; Operator Use Description Increments op by 1; evaluates to the value of op before it ++ op++ was incremented Increments op by 1; evaluates to the value of op after it ++ ++op was incremented Decrements op by 1; evaluates to the value of op before it -- op-- was decremented Decrements op by 1; evaluates to the value of op after it -- --op was decremented Increment and Decrement operators The increment and decrement operators can be placed before or after an operand. When used before an operand, it causes the variable to be incremented or decremented by 1, and then the new value is used in the expression in which it appears. For example, int i = 10, int j = 3; int k = 0; k = ++j + i; // will result to k = 4+10 = 14 Computer Programming 1 SLU-SAMCIS 31 | P a g e When the increment and decrement operators are placed after the operand, the old value of the variable will be used in the expression where it appears. For example, int i = 10, int j = 3; int k = 0; k = j++ + i; // will result to k = 3+10 = 13 Coding Guideline: Always keep expressions containing increment and decrement operators simple and easy to understand. Relational operators Relational operators compare two values and determine the relationship between those values. The output of evaluation is either of the boolean values true or false. Operator Use Description > op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equal to op2 < op1 < op2 op1 is less than op2 j)); // false System.out.println(" j > i = " + (j > i)); // true System.out.println(" k > j = " + (k > j)); // false // greater than or equal to System.out.println("Greater than or equal to..."); System.out.println(" i >= j = " + (i >= j)); // false System.out.println(" j >= i = " + (j >= i)); // true System.out.println(" k >= j = " + (k >= j)); // true // less than System.out.println("Less than..."); System.out.println(" i < j = " + (i < j)); // true System.out.println(" j < i = " + (j < i)); // false System.out.println(" k < j = " + (k < j)); // false // less than or equal to System.out.println("Less than or equal to..."); System.out.println(" i i = " + (j > i)); // true System.out.println(" k > j = " + (k > j)); // false Computer Programming 1 SLU-SAMCIS 33 | P a g e // greater than or equal to System.out.println("Greater than or equal to..."); System.out.println(" i >= j = " + (i >= j)); // false System.out.println(" j >= i = " + (j >= i)); // true System.out.println(" k >= j = " + (k >= j)); // true // less than System.out.println("Less than..."); System.out.println(" i < j = " + (i < j)); // true System.out.println(" j < i = " + (j < i)); // false System.out.println(" k < j = " + (k < j)); // false // less than or equal to System.out.println("Less than or equal to..."); System.out.println(" i i = " + (j > i)); // true System.out.println(" k > j = " + (k > j)); // false // greater than or equal to System.out.println("Greater than or equal to..."); System.out.println(" i >= j = " + (i >= j)); // false System.out.println(" j >= i = " + (j >= i)); // true System.out.println(" k >= j = " + (k >= j)); // true // less than System.out.println("Less than..."); System.out.println(" i < j = " + (i < j)); // true System.out.println(" j < i = " + (j < i)); // false System.out.println(" k < j = " + (k < j)); // false // less than or equal to System.out.println("Less than or equal to..."); System.out.println(" i

Use Quizgecko on...
Browser
Browser