1 / 133

Chapter Topics

Chapter Topics. Chapter 2 discusses the following main topics: The Parts of a Java Program The print and println Methods, and the Java API Variables and Literals Primitive Data Types Arithmetic Operators Combined Assignment Operators. Chapter Topics (Continued).

eannie
Download Presentation

Chapter Topics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter Topics Chapter 2 discusses the following main topics: The Parts of a Java Program The printand printlnMethods, and the Java API Variables and Literals Primitive Data Types Arithmetic Operators Combined Assignment Operators

  2. Chapter Topics (Continued) Creating named constants with final The String class Scope Comments Programming style Using the Scanner class for input Dialog boxes

  3. Parts of a Java Program A Java source code file (Simple.java) contains one or more Java classes. If more than one class is in a source code file, only one of them may be public. The public class and the source code’s filename must match. ex: A class named Simple must be in a file named Simple.java Each Java class can be separated into parts.

  4. Parts of a Java Program import java.util.Random; public class Methods01_5_1 { public static void main(String[] args) { displayNumber(); //calling a method System.out.println("\nThe obtained random number is " + displayRandomNumber()); } public static void displayNumber() { int number = 7; System.out.println(number); } public static int displayRandomNumber() { int number; . Random rand = new Random(); number = rand.nextInt(); return number; } }

  5. Parts of a Java Program import java.util.Random; public class Methods01_5_1 { public static void main(String[] args) { displayNumber(); //calling a method System.out.println("\nThe obtained random number is " + displayRandomNumber()); } public static void displayNumber() { int number = 7; System.out.println(number); } public static intdisplayRandomNumber() { int number; . Random rand = new Random(); /*declare a variable named rand of Random class. Create an instance of the Random class. Assign the address of the Random class to the variable rand.*/ number = rand.nextInt(); return number; } }

  6. Parts of a Java Program //Rectangle.java file. public class Rectangle { private double length; private double width; private double height; //Methods for Rectangle class's objects // The setLength method //The header for the setLength method: public void setLength(double len) { length = len; } // The setWidth method public void setWidth(double w) { width = w; } // The getLength method public double getLength() { return length; } //The getWidth method public double getWidth() { return width; } //The getArea method public double getArea() { return length*width; } }

  7. Parts of a Java Program //Rectangle.java file. public class Rectangle { private double length; private double width; private double height; //Methods for Rectangle class's objects // The setLength method //The header for the setLength method: public void setLength(double len) { length = len; } // The setWidth method public void setWidth(double w) { width = w; } // The getLength method public double getLength() { return length; } //The getWidth method public double getWidth() { return width; } //The getArea method public double getArea() { return length*width; } }

  8. Parts of a Java Program Give an example: a soure code (src) file: Simple.java To compile the example: javac Simple.java Notice the .java file extension is needed. This will result in a file named Simple.class being created. To run the example: java Simple Notice there is no file extension here. The java command assumes the extension is .class.

  9. What do I got? Project name: Simple (Simple.java) C:/users/ngp/workspace There is a folder icon, named Simple, which contains A folder .settings containing a file org.eclipse.jdt.core.prefs A folder bin – now is empty A folder src – now is empty A file .classpath A file .proj Java Class Name: Simple (Simple.class) In the folder src, could contain a folder with the name of package, then it contains a file Simple.java In the folder bin, could contain a folder with the name of package, then it contains a file Simple.class jdt – Java Development Tools

  10. Analyzing The Example package simple_Pbm; // This is a simple Java program. public class Simple{ public static void main(String[] args) { System.out.println(“Hi!”); }}

  11. Analyzing The Example Simple.java x public class Simple{ public static void main(String[] args){ //TODO Auto-generated method stub }} J Java file extension

  12. Analyzing The Example This is a Java comment. It is ignored by the compiler. This is the class headerfor the class Simple (Simple.class) // This is a simple Java program. public class Simple{ } This area is the body of the class Simple. All of the data and methods for this classwill be between these curly braces. public – a Java keyword, an access specifier, access to the class is unrestricted, open to the public. class – a Java keyword, indicates the beginning of a class definition. Simple – the class name, programmer-defined name.

  13. Analyzing The Example The Java source code file Simple.java (found in a folder namedsrc) is translated by Java compiler and created another file named Simple.class, containing byte code. (found this file in bin folder) The Byte code instructions are not machine language and cannot by directly executed by the CPU. The Java Virtual Machine (JVM) reads them and executes them as they are read. For this reason, JVM is called the interpreter. Source code file named Simple.java // This is a simple Java program. public class Simple{} The line of code tells the compiler that a publicly accessible class named Simple is being defined.

  14. Analyzing The Example Source code file named Simple.java in the src folder insider the folder Simple // This is a simple Java program. public class Simple //allows to create a file named Simple.class{//contained in the bin folder inside the folder Simple. } • A Java program must have at least one class definition. • We may create more than one class in a file (such as Simple.java), but we may have only one public class per Java file. • When a Java file has a public class, the name of the public class must be the same as the named of the file (without the .java file extension). • For example, the program has a public class named Simple, so it stored in a file named Simple.java.

  15. Analyzing The Example This is the method header for the main method. The main method is where a Java application begins. public class Simple{ } public static void main(String[] args){ } This area is the body of the main method. All of the actions to be completed during the main method will be between these curly braces. // This is a simple Java program.

  16. Analyzing The Example • This is the method header for the main method. • “main” is the name of the method. public class Simple{} public static void main(String[] args){ } the body of the main method. // This is a simple Java program.

  17. Analyzing The Example public class Simple{} public static void main(String [] args){ //class: System; object: out; method: println; System.out.println("Programming is great fun!"); } This is the Java Statement that is executed when the program runs. // This is a simple Java program.

  18. Analyzing The Example public class Simple{} public static void main(String [] args){ System.out.println("Programming is great fun!"); } This is the Java Statement that is executed when the program runs. // This is a simple Java program.

  19. Analyzing The Example public class Simple{} public static void main(String [] args){ System.out.println("Programming is great fun!"); } This is the Java Statement that is executed when the program runs. // This is a simple Java program. public This is the access modifier of main method. It has to be public so that java runtime system can call to execute this method, main. Java runtime is outside the current class Simple.

  20. Analyzing The Example public class Simple{} public static void main(String [] args){ System.out.println("Programming is great fun!"); } This is the Java Statement that is executed when the program runs. // This is a simple Java program. static When java runtime system starts, there is no object of the class present. This has to have static method to allow invocation from class. For the main method to be static, JVM can load the class into memory and call the main method. If main method won’t be static, JVM would not be able to call it because of there is no object of the class present.

  21. Analyzing The Example public class Simple{} public static void main(String [] args){ System.out.println("Programming is great fun!"); } This is the Java Statement that is executed when the program runs. // This is a simple Java program. void Java is platform independent language and the returned value by the main method may mean different things to different platforms. Java programming mandates that every method signature provide the return type. Java main method with return type “void” doesn’t return anything. Once main method is finished executing, java program terminates. There is nothing that can be done for the returned object by JVM. If we try to return something from main method, it will give compilation error as unexpected return value.

  22. Analyzing The Example public class Simple{} public static void main(String [] args){ System.out.println("Programming is great fun!"); } This is the Java Statement that is executed when the program runs. // This is a simple Java program. main This is the name of java main method. This name is fixed and when we start a java program, it looks for the main method. That is, as it's called by the JVM, the main method serves as the entry point for an application.

  23. Analyzing The Example public class Simple{} public static void main(String [] args){ System.out.println("Programming is great fun!"); } This is the Java Statement that is executed when the program runs. // This is a simple Java program. String[] args Java main method accepts a single argument of type String array, which is also called as java command line arguments.String [] arguments is a java array of String objects. This means that the main function expects an array of Strings. This array of strings typically holds all command line parameter arguments passed in when the program is run from the command line.

  24. Parts of a Java Program Comments The line is ignored by the compiler. The comment in the example is a single-line comment. Class Header The class header tells the compiler things about the class such as what other classes can use it (public) and that it is a Java class (class), and the name of that class (Simple). Curly Braces When associated with the class header, they define the scope of the class. When associated with a method, they define the scope of the method.

  25. Parts of a Java Program The main Method public static void main(String [] args) { …. } This line must be exactly the same as shown (except that the args variable name can be programmer defined). This is the line of code that the java command will run first. This method starts the Java program. Every Java application must have a main method. Java Statements When the program runs, the statements within the main method will be executed. Can you see what the line in the example will do?

  26. Java Statements There is only one line that ends with a semi-colon. System.out.println("Programming is great fun!"); It is the only Java statement in the program. The rest of the code is either a comment or other Java framework code. //This is a simple java program public class Simple { public static void main(String[] args) { System.out.println(“Programming is not fun at all!”); } }

  27. Analyzing The Example public class Simple{} public static void main(String [] args){ System.out.println("Programming is great fun!"); } This is the Java Statement that is executed when the program runs. // This is a simple Java program.

  28. Java Statements Comments are ignored by the Java compiler so they need no semi-colons. Other Java code elements that do not need semi-colons include: class headers Terminated by the code within its curly braces. method headers Terminated by the code within its curly braces. curly braces Part of framework code that needs no semi-colon termination.

  29. Short Review Java is a case-sensitive language. All Java programs must be stored in a file with a .java file extension. Comments are ignored by the compiler. A .java file may contain many classes but may only have onepublic class. If a .java file has a public class, the class must have the same name as the file.

  30. Short Review Java applications must have a main method. For every left brace, or opening brace, there must be a corresponding right brace, or closing brace. Statements are terminated with semicolons. Comments, class headers, method headers, and braces are not considered Java statements.

  31. Special Characters

  32. Console Output Many of the programs that you will write will run in a console window.

  33. Console Output The console window that starts a Java application is typically known as the standard output device. The standard input device is typically the keyboard. Java sends information to the standard output device by using a Java class (named System) stored in the standard Java library. System.out.println(“CS 16000-01 Intro to CS”);

  34. Console Output Java classes in the standard Java library are accessed using the Java Applications Programming Interface (API). The standard Java library is commonly referred to as the Java API.

  35. Console Output The previous example uses the line: System.out.println("Programming is great fun!"); This line uses the System class from the standard Java library. The System class contains methods and objects that perform system level tasks. The out object, a member of the System class, contains the methods print, println, and printf.

  36. Console Output The print and println methods actually perform the task of sending characters to the output device. The line: System.out.println("Programming is great fun!"); is pronounced: System dot out dot println… The value inside the parenthesis will be sent to the output device (in this case, a string).

  37. Console Output The println method places a newline character “\n”at the end of whatever is being printed out. The following lines: System.out.println("This is being printed out"); System.out.println("on two separate lines."); Would be printed out on separate lines since the first statement sends a newline command to the screen. System.out.println(“”);

  38. Console Output The print statement works very similarly to the println statement. However, the print statement does not put a newline character at the end of the output. The lines: System.out.print("These lines will be"); System.out.print("printed on"); System.out.println("the same line."); will output: These lines will beprintedonthe same line. Notice the odd spacing? Why are some words run together? System.out.print("These lines will be\n"); System.out.print("printed on "); System.out.println(“ the same line.\n"); // \n

  39. Console Output In the previous examples, we have been printing out strings of characters. Will see more print methods later. Some special characters can be put into the output.System.out.print( “ These lines will be ” + “printed on the ” + “the same line.\n” ); The \n in the string is an escape sequence that represents the newline character. Escape sequences allow the programmer to print characters that otherwise would be unprintable.

  40. Java Escape Sequences

  41. Java Escape Sequences The escape sequences are comprised of two characters; they are treated by the compiler as a single character. System.out.print("These are our to sellers:\n"); System.out.print("\t\"Computer games\"\n\t\"Coffee\"\n ); System.out.println("\t\"Aspirin\""); Would result in the following output: These are our top seller: "Computer games" "Coffee" "Asprin" With these escape sequences, complex text output can be achieved.

  42. Variables and Literals A variable is a named storage location in the computer’s memory. A literal is a value that is written into the code of a program. Programmers determine the number and type of variables a program will need. See example:Variable.java

  43. Variables and Literals 0x000 0x001 5 0x002 0x003 This is a string literal. It will be printed as is. The integer 5 will be printed out here. Notice no quote marks? This line is called a variable declaration. int value; The following line is known as an assignment statement. value = 5; int value; value = 5; System.out.println(“The value is” + value); The value 5 is stored in memory. System.out.print("The value is "); System.out.println(value);

  44. The + Operator The + operator can be used in two ways. as a concatenation operator as an addition operator If either side of the + operator is a string, the result will be a string. System.out.println("Hello " + "World"); System.out.println("The value is: " + +5);//… 5 System.out.println("The value is: " + value); System.out.println("The value is: " + ‘\n’ + -5); System.out.println("The value is: " + ‘/n’ + 5); … “Invalid character constant”

  45. String Concatenation Java commands that have string literals must be treated with care. A string literal value cannot span lines in a Java source code file. System.out.println(“This line is too long and now it has spanned more than one line, which will cause a syntax error to be generated by the compiler.”); … String literal is not properly closed by a double-quote

  46. String Concatenation The String concatenation operator can be used to fix this problem. System.out.println("These lines are " + "are now ok and will not " + “\ncause the error as before."); Console output: ? String concatenation can join various data types. System.out.println("We can join a string to " + "a number like this: " + 5); Console output: We can join a string to a number like this: 5

  47. String Concatenation The Concatenation operator can be used to format complex String objects. System.out.println("The following will be printed " + "in a tabbed format: " + "\n\tFirst = " + 5 * 6 + ", " + "\n\tSecond = " +(6 + 4) + "," + "\n\tThird = " + 16.7 + "."); Notice that if an addition operation is also needed, it must be put in parenthesis. Console output: The following… in a tabbed format: First = 30, Second = 10, Third = 16.7.

  48. Identifiers Identifiers are programmer-defined names for: classes variables …..(identifier, storage) methods Identifiers may not be any of the Java reserved keywords.

  49. Identifiers Identifiers must follow certain rules: An identifier may only contain: letters a–z or A–Z, the digits 0–9, underscores (_), or the dollar sign ($) The first character may not be a digit. Identifiers are case sensitive. itemsOrderedis not the same as itemsordered. Identifiers cannot include spaces.

More Related