610 likes | 816 Views
Java I. Chapter 2 Introduction to Java Applications. Java Applications Are A Series of Classes. • A Java Application must have the method main . • A Java Application begins executing at main . • Let’s look at details of an Application:. public class Welcome1 {
E N D
Chapter 2 Introduction to Java Applications
Java Applications Are A Series of Classes • A Java Applicationmust have the method main. • A Java Application begins executing at main. • Let’s look at details of an Application:
public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } } // end of class Welcome1 (use comments here if needed) • This is a basic Application. • Notice the comments. These are required in this course. Java is free form, but you’ll be happy if you get in the habit of documenting like this. • Also, whenever you type an opening curly bracket, type the closing one right away. • Your curly brackets must always--in this class--line up as shown.
public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } } • The line above in blue is the class definition for Welcome1. • Every class name must be Capitalized. • Notice, every scrap of code is within this class. • Since it is named Welcome1, this Application is saved in a file called Welcome1.java, spelled exactly the same. • The compiler will make a file called Welcome1.class.
public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } } • The word Welcome1 is an identifier. • An identifier is a user-defined word, which consists of: letters digits _ (underscore) $ (a dollar sign) • An identifier cannot begin with a digit.
public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } } • Notice that we put the word public before the word class. • This means the class can be called by anything. • The alternatives to public are discussed in Chapter 8.
public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } } • The method main is also declared public. • This should just be copied until Chapter 6*, when we know methods better. *(This course was created based on Deitel & Deitel’s “Java: How to Program (3rd Edition)”, which is still available used at places like www.amazon.com .
public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } } • void means nothing is returned to the operating system when the program finishes. • The ( String args[] ) works with “arguments” that were passed when the program was executed. • Although you cannot omit it ( String args[] ), we don’t discuss this topic just yet, so please copy it.
public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } } • The System.out.println puts the message in quotes on the command console. Also quoted as the standard output object. • If we used System.out.print, then the cursor would not do a carriage return / line feed after it prints the text. • Notice the opening and closing blue curly brackets. The unit of code enclosed in them is called a “block.” • It is also called the “body” of the method.
public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } } • You will find that you very rarely use this Standard output object. • Instead, you will use the GUI objects. • Notice in red the semicolon. ; All executable statements in Java ends in a semicolon.
public class Welcome1 { public static void main( String args[] ) { System.out.print( “Welcome ” ); System.out.println( “to Java!” ); } } • This will still produce the same text as the previous version.
public class Welcome1 { public static void main( String args[] ) { System.out.print( “Welcome\nto\nJava! ” ); } } • Notice the “ \n ”. The slash is an escape character. It tells the System object that whatever follows the slash is special: \n new line \t tab \r carriage return \\ backslash \” quote Welcome to Java!
First GUI: JOptionPane importjavax.swing.JOptionPane public class Welcome4 { public static void main( String args[] ) { JOptionPane.showMessageDialog( null, “Hi Java!” ); System.exit( 0 ) } } • This adds an import statement, which tells the compiler you want to use somebody else’s class. • The “ javax.swing ” is like a DOS path.
First GUI: JOptionPane import javax.swing.JOptionPane • You must know these classes, and how to use them. • This path helps the compiler find the class you wish to use. • The javax.swing portion of this name is called the “package.” • Classes in the same package have a connection we will explore later. • Suffice it to say that they are very chummy.
First GUI: JOptionPane import javax.swing.JOptionPane public class Welcome4 { public static void main( String args[] ) { JOptionPane.showMessageDialog( null, “Hi Java!” ); System.exit( 0 ) } } • The Statement JOptionPane.showMessageDialog means: “I want objectJOptionPane to perform its method showMessageDialog(). Also, I’m passing the data: “null” and “Hi Java!” In Java, we call that data “arguments.”
import javax.swing.JOptionPane; public class Welcome4 { public static void main( String args[] ) { JOptionPane.showMessageDialog( null, “Hi Java!” ); System.exit( 0 ); } } • System.exit( 0 ); This statement uses the method “exit” of class System to end the application. GUI Applications always require this statement to terminate correctly. • Class System is imported automatically, in package java.lang
Build An Application Addition • When you are building an Application, there is a set template for design that you automatically follow. • Get in the habit of doing exactly as will be done on the next few slides.
import javax.swing.JOptionPane; 1.) You tell the compiler to import any of the extra classes you will be using in your Application.
import javax.swing.JOptionPane; public class Addition { } // end of class Addition 2.) Define your class name, and right away place the opening and closing brackets--with the comment.
import javax.swing.JOptionPane; public class Addition { public static void main( String args[] ) { System.exit( 0 ); } } 3.) Add the main method, and the System.exit( 0 ) that you know it will require--include the comment.
import javax.swing.JOptionPane; public class Addition { public static void main( String args[] ) { String firstNumber, secondNumber; System.exit( 0 ); } } f 4.) Include any local variables you will need in this method. A local variable is visible and accessible only within the method.
import javax.swing.JOptionPane; public class Addition { public static void main( String args[] ) { String firstNumber, secondNumber; int number1, number2, sum; System.exit( 0 ); } } Notice, ‘int’ does not start with a capital letter. 5.) Now we have added three integer variables. They are not objects. They hold three integers--without any methods or classes. number1, number2 and number3 are called primitive variables.
import javax.swing.JOptionPane; public class Addition { public static void main( String args[] ) { String firstNumber, secondNumber; int number1, number2, sum; firstNumber = JOptionPane.showInputDialog( “First Num” ); secondNumber = JOptionPane.showInputDialog( “Second Num” ); String argument is received. String is returned by the method. • Look at the Java Documentation for the JOptionPane object. You will first see the hierarchy of this object within the Java object hierarchy: d
• This is the hierarchy for the JOptionPane. • We will cover “inheritance” starting in Chapter 8, but you need to begin learning these API class libraries. • The Class JOptionPane has several methods. A class’s methods are its capabilities. • For now, you should know that method showInputDialog() receives a String argument, and returns a String result.
import javax.swing.JOptionPane; public class Addition { public static void main( String args[] ) { String firstNumber, secondNumber; int number1, number2, sum; firstNumber = JOptionPane.showInputDialog( “First Num” ); secondNumber = JOptionPane.showInputDialog( “Second Num” ); • These InputDialog boxes are created by this code. • But, since they are Strings, we can’t add them.
import javax.swing.JOptionPane; public class Addition { public static void main( String args[] ) { String firstNumber, secondNumber; int number1, number2, sum; firstNumber = JOptionPane.showInputDialog( “First Num” ); secondNumber = JOptionPane.showInputDialog( “Second Num” ); • So, how do we get String “numbers” converted into actual integers that we can do addition on? • We need some Object that has a method capable of taking a String argument and returning an integer.
import javax.swing.JOptionPane; public class Addition { public static void main( String args[] ) { String firstNumber, secondNumber; int number1, number2, sum; firstNumber = JOptionPane.showInputDialog( “First Num” ); secondNumber = JOptionPane.showInputDialog( “Second Num” ); number1 = Integer.parseInt(firstNumber); number2 = Integer.parseInt( secondNumber ); sum = number1 + number2; • Integer is a class. Its method parseInt() takes a String argument and returns an int.
import javax.swing.JOptionPane; public class Addition { public static void main( String args[] ) { String firstNumber, secondNumber; int number1, number2, sum; firstNumber = JOptionPane.showInputDialog( “First Num” ); secondNumber = JOptionPane.showInputDialog( “Second Num” ); number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber); sum = number1 + number2; JOptionPane.showMessageDialog( null, “The Sum is: ” + sum, “Results”, JOPtionPane.PLAIN_MESSAGE ); System.exit( 0 ); } }
The method showMessageDialog of class JOptionPane takes four arguments: • null -- this will be explained in a later chapter • “The Sum is:” + sum --this converts the int sum into a String and concatenates it with the String “The Sum is:” • “Results” is the message displayed in the title bar. • JOptionPane.PLAIN_MESSAGE defines the icon.
For the icons, you have five alternate constants to choose from: JOptionPane.PLAIN_MESSAGE JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE JOptionPane.WARNING_MESSAGE JOptionPane.QUESTION_MESSAGE In Java, Constants are always all upper case, with words separated by underscores.
A Caution About String Concatenation • On the previous slide, we concatenated a String with an int: “The Sum is ” + sum. • Remember the sequence: first, sum was converted from an int to a String, and then that String was concatenated with the other String “The Sum is: ” • So, what would the following code produce? int number1 = 2; int number2 = 4; JOptionPane.showMessageDialog( null, “The Sum is: ” + number1 + number2, “Screwy Result”, JOptionPane.WARNING_MESSAGE );
Primitive Data Types • A variable called number1 actually refers to a place in memory where the value of the variable is stored. • Every variable in Java has a: name, type, size, and a value.
Primitive Data Types name Variable names must conform to the rules for identifiers: • they must begin with a letter, • after that they can contain digits, dollar signs and underscores. • Java uses Unicode for its characters, so any “letter” that is valid for a word in any world language is therefore valid for a name in Java.
Primitive Data Types type • The “type” appears before the identifier name. • The type can be one of the “primitive data types” or it can be any previously defined class. • You declare a variable and initialize it on the same line. int num1; num1 = 2; • This is a declaration. At this point, the name num1 refers to a location {a pointer} in the computer’s RAM where this variable is stored. • Because an int is declared, we know that four bytes are set aside. • Still, nothing is stored in it yet. int num1=2;
Primitive Data Types 1. size • When we assign a type [ int, String] to a variable, we are not only declaring a memory location. • We also decide how big of a number or character is able to be stored in that variable. 2. value • Finally, the value is what we want the variable to store.
Primitive Data Types • Java is a statically-typed language. That means, every variable must be declared as a type. In Java, there are 8 primitive types: • 6 of those refer to numbers --4 for integers types, --2 for floating-point types, • 1 is the character type char, used for characters* in Unicode encoding, and • 1 is a boolean type for true or false values. *Can be used as a numeric in some situations.
Primitive Data Types int • In contrast to C/C++, an int will always—no matter which operating system—contain a 4 byte value. • Because those 4 bytes are set in stone, you can be sure that every JVM that runs your program will be able to store the same size numbers. • int is the most commonly used number size. Range: -2,147,483,648 to 2,147,483,647 (over two billion)
Primitive Data Types short • In Java, a short is defined as a 2 byte value, no matter which operating system is used. • You would only use this for special situations, such as when speed is really crucial. Range: -32,768 to 32,767
Primitive Data Types long • A long is defined as an 8 byte value, no matter which operating system is used. Range: -9,223,372,036,854,775,808L to 9,223,372,036,854,775,807L • Please notice the upper-case Lsuffix is appended to any long. This is required. • Hexadecimal numbers have a prefix: 0x 0x1CFE.
Primitive Data Types byte • A byte is defined as 1 byte value, no matter which operating system is used. Range: -128 to 127 • Again, like a short, a byte is only used under rare circumstances.
Primitive Data Types float • A float is defined as a 4 byte value, no matter which operating system is used. Range: approximately 3.40282347E+38F ( 6-7 significant decimal digits ) • Because there are so few decimal places available, float is not used all that often.
Primitive Data Types double • A double is defined as an 8 byte value, no matter which operating system is used. Range: approximately 1.79769313486231570E+308 ( 15 significant decimal digits ) • “double is the one to have when you’re having more than one*—decimal place, that is.” • This is the most common choice for any decimal. • double is the default, notfloat, therefore, no special character is appended. (See red arrow.) * Apologies to Schaefer beer.
Primitive Data Types char • A char is defined as 2 bytes, no matter which operating system is used. A char type always refers to a character in the Unicode encoding scheme. [\uFFFF\u is the escape character syntax]About 65,536 different characters can be represented. • Single quotes denote a char constant ‘H’ is a char constant “H” is a string that happens to only contain a single character.
Primitive Data Types char • A char is defined as 2 bytes. A char type is a single Unicode character. [\uFFFF \u is the escape character syntax--65,536 different characters can be represented.] • Single quotes denote a single-letterchar constant ‘H’ is a char constant. “H” is a String that happens to only contain a single character--it is not a char. This is a syntax error! The compiler will complain.
Primitive Data Types boolean • A boolean type has only two values. • In contrast to C/C++, in Java 0 and 1 cannot stand in for true or false. • A boolean type must be assigned the value of the constants true or false. [Meaning, these exact lowercase words.]
Java Math Operators • Addition + • Subtraction - • Multiplication * • Division / • Modulus % All are binary operators, i.e., they work with two numbers. They are executed according to the rules for operator precedence. [page 1240] (There is no operator for exponentiation in Java)
Java Math Operators • Multiplication * • What happens if you multiply variables of different types? int x = 2; double y = 3.889, sum = 0.000; sum = y * x; • The integer will be temporarily converted to a double and two doubles will be multiplied. • Afterwards, the original integer is unchanged.
Java Math Operators • Rules for Temporary Conversions 1st Priority: If either of the operands is of type double, then the other one is converted to double for the calculation. 2nd Priority: Otherwise, if either of the operands is of type float, then the other one is converted to float for the calculation. 3rd Priority: Otherwise, if any of the operands is of type long, then the other one is converted to long for the calculation. Note: these conversions are automatic because none of them result in a loss of accuracy.
Java Math Operators • Static Casts So, what happens when you desire to convert a double to a float? Information will inevitably be lost. • You accomplish this using a cast. int x = 2, sum = 0; double y = 3.889; sum = (int)y * x; { sum is now equal to6 } • Here, a value of just 3 will be used for y. • If you want to round y, you a method from class Math: sum = (int)Math.round(y) * x;