Java i lecture_2
Upcoming SlideShare
Loading in...5
×
 

Java i lecture_2

on

  • 265 views

 

Statistics

Views

Total Views
265
Views on SlideShare
265
Embed Views
0

Actions

Likes
0
Downloads
4
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • White Space Characters

Java i lecture_2 Java i lecture_2 Presentation Transcript

  • Java I--Copyright © 2000-2004 Tom Hunter
  • Java I--Copyright © 2000-2004 Tom HunterChapter 2Introduction to JavaApplications
  • Java I--Copyright © 2000-2004 Tom Hunter• A Java Application must have the methodmain.• A Java Application begins executing atmain.• Let’s look at details of an Application:Java Applications AreA Series of Classes
  • Java I--Copyright © 2000-2004 Tom Hunterpublic class Welcome1{public static void main( String args[] ){System.out.println( “Welcome to Java!” );} // end of main()} // end of class Welcome1• 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 habitof documenting like this.• Also, whenever you type an opening curly bracket, typethe closing one right away.• Your curly brackets must always--in this class--line up asshown.
  • Java I--Copyright © 2000-2004 Tom Hunterpublic class Welcome1{public static void main( String args[] ){System.out.println( “Welcome to Java!” );} // end of main()} // end of class Welcome1• The line above in blue is the class definition forWelcome1.• Every class name must be Capitalized.• Notice, every scrap of code is within this class.• Since it is named Welcome1, this Application is saved ina file called Welcome1.java, spelled exactly the same.• The compiler will make a file called Welcome1.class.
  • Java I--Copyright © 2000-2004 Tom Hunterpublic class Welcome1{public static void main( String args[] ){System.out.println( “Welcome to Java!” );} // end of main()} // end of class Welcome1• The word Welcome1 is an identifieridentifier.• An identifieridentifier is a user-defined word, which consists of:lettersdigits_ (underscore)$ (a dollar sign)• An identifier cannot begin with a digit.
  • Java I--Copyright © 2000-2004 Tom Hunterpublic class Welcome1{public static void main( String args[] ){System.out.println( “Welcome to Java!” );} // end of main()} // end of class Welcome1• Notice that we put the word public before the wordclass.• This means the class can be called by anything.• The alternatives to public are discussed in Chapter 8.
  • Java I--Copyright © 2000-2004 Tom Hunterpublic class Welcome1{public static void main( String args[] ){System.out.println( “Welcome to Java!” );} // end of main()} // end of class Welcome1• The method main is also declared public.• This should just be copied until Chapter 6, when weknow methods better.
  • Java I--Copyright © 2000-2004 Tom Hunterpublic class Welcome1{public static void main( String args[] ){System.out.println( “Welcome to Java!” );} // end of main()} // end of class Welcome1• void means nothing is returned to the operating systemwhen 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.
  • Java I--Copyright © 2000-2004 Tom Hunterpublic class Welcome1{public static void main( String args[] ){System.out.println( “Welcome to Java!” );} // end of main()} // end of class Welcome1• The System.out.println puts the message inquotes on the command console.• If we used System.out.print, then the cursor wouldnotnot do a carriage return / line feed after it prints the text.• Notice the opening and closing blue curly brackets. Theunit of code enclosed in them is called a “block.”• It is also called the “body” of the method.This is called theStandard outputobject.
  • Java I--Copyright © 2000-2004 Tom Hunterpublic class Welcome1{public static void main( String args[] ){System.out.println( “Welcome to Java!” );} // end of main()} // end of class Welcome1• You will find that you very rarely use thisStandard output object.• Instead, you will use the GUI objects.• Notice in red the semicolon. ; All executablestatements in Java ends in a semicolon.
  • Java I--Copyright © 2000-2004 Tom Hunterpublic class Welcome1{public static void main( String args[] ){System.out.print( “Welcome ” );System.out.println( “to Java!” );} // end of main()} // end of class Welcome1• This will still produce the same text as theprevious version.
  • Java I--Copyright © 2000-2004 Tom Hunterpublic class Welcome1{public static void main( String args[] ){System.out.print( “WelcomentonJava! ” );} // end of main()} // end of class Welcome1• Notice the “ n ”. The slash is an escapecharacter. It tells the System object that whateverfollows the slash is special:n new linet tabr carriage return backslash” quoteWelcometoJava!
  • Java I--Copyright © 2000-2004 Tom Hunterimport javax.swing.JOptionPanepublic class Welcome4{public static void main( String args[] ){JOptionPane.showMessageDialog( null, “Hi Java!” );System.exit( 0 )} // end of main()} // end of class Welcome1First GUI: JOptionPane• This adds an import statement, which tells thecompiler you want to use somebody else’s class.• The “ javax.swing ” is like a DOS path.
  • Java I--Copyright © 2000-2004 Tom Hunterimport javax.swing.JOptionPane• You must know these classes, and how to use them.• This path helps the compiler find the class you wish touse.• The javax.swing portion of this name is called the“package.”• Classes in the same package have a connection we willexplore later.• Suffice it to say that they are very chummy.First GUI: JOptionPane
  • Java I--Copyright © 2000-2004 Tom HunterFirst GUI: JOptionPaneimport javax.swing.JOptionPanepublic class Welcome4{public static void main( String args[] ){JOptionPane.showMessageDialog( null, “Hi Java!” );System.exit( 0 )} // end of main()} // end of class Welcome1• The Statement JOptionPane.showMessageDialog means:“I want object JOptionPane to perform its methodshowMessageDialog(). Also, I’m passing the data:“null” and “Hi Java!” In Java, we call that data“arguments.”
  • Java I--Copyright © 2000-2004 Tom Hunterimport javax.swing.JOptionPane;public class Welcome4{public static void main( String args[] ){JOptionPane.showMessageDialog( null,“Hi Java!” );System.exit( 0 );} // end of main()} // end of class Welcome4• System.exit( 0 ); This statement uses themethod “exit” of class System to end the application.GUI Applications always require this statement toterminate correctly.• Class System is imported automatically, in packagejava.lang
  • Java I--Copyright © 2000-2004 Tom HunterBuild An Application• When you are building an Application, there is a settemplate for design that you automatically follow.• Get in the habit of doing exactly as will be done on thenext few slides.Addition
  • Java I--Copyright © 2000-2004 Tom Hunterimport javax.swing.JOptionPane;1.) You tell the compiler to import any of the extraclasses you will be using in your Application.
  • Java I--Copyright © 2000-2004 Tom Hunterimport javax.swing.JOptionPane;public class Addition{} // end of class Addition2.) Define your class name, and right away place theopening and closing brackets--with the comment.
  • Java I--Copyright © 2000-2004 Tom Hunterimport javax.swing.JOptionPane;public class Addition{public static void main( String args[] ){System.exit( 0 );} // end of main()} // end of class Addition3.) Add the main method, and the System.exit( 0 )that you know it will require--include the comment.
  • Java I--Copyright © 2000-2004 Tom Hunterimport javax.swing.JOptionPane;public class Addition{public static void main( String args[] ){String firstNumber,secondNumber;System.exit( 0 );} // end of main()} // end of class Addition4.) Include any local variables you will need in thismethod. A local variable is visible and accessible onlywithin the method.These two are “String” references. That means theyhave the potential to point to objects of type String.However, at this point, they point to nothing.They are empty references.f
  • Java I--Copyright © 2000-2004 Tom Hunterimport javax.swing.JOptionPane;public class Addition{public static void main( String args[] ){String firstNumber,secondNumber;int number1,number2,sum;System.exit( 0 );} // end of main()} // end of class Addition5.) Now we have added three integer variables. They arenot objects. They hold three integers--without anymethods or classes. number1, number2 andnumber3 are called primitive variables.Notice,‘int’ does notstart with acapitalletter.
  • Java I--Copyright © 2000-2004 Tom Hunterimport 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” );• Look at the Java Documentation for theJOptionPane object. You will first see the hierarchyof this object within the Java object hierarchy:String argumentis received.dString isreturnedby themethod.
  • Java I--Copyright © 2000-2004 Tom Hunter• This is the hierarchy forthe JOptionPane.• We will cover “inheritance”starting in Chapter 8, but youneed 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 methodshowInputDialog()receives a String argument, andreturns a String result.
  • Java I--Copyright © 2000-2004 Tom Hunterimport 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
  • Java I--Copyright © 2000-2004 Tom Hunterimport 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 intoactual integers that we can do addition on?• We need some Object that has a method capable oftaking a String argument and returning an integer.
  • Java I--Copyright © 2000-2004 Tom Hunterimport 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.
  • Java I--Copyright © 2000-2004 Tom Hunterimport 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 );} // end of main()} // end of class AdditionThe method showMessageDialog of classJOptionPane takes four arguments:• null -- this will be explained in a later chapter• “The Sum is:” + sum --this converts the int sum into aString 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_MESSAGEJOptionPane.ERROR_MESSAGEJOptionPane.INFORMATION_MESSAGEJOptionPane.WARNING_MESSAGEJOptionPane.QUESTION_MESSAGEIn Java, Constants are always all upper case, with words separatedby underscores.
  • Java I--Copyright © 2000-2004 Tom HunterA Caution About String Concatenation• On the previous slide, we concatenated a String withan int: “The Sum is ” + sum.• Remember the sequence: first, sum was convertedfrom an int to a String, and then that String wasconcatenated 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 );
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Types• A variable called number1 actually refers to a place inmemory where the value of the variable is stored.• Every variable in Java has a:name,type,size, and avalue.
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data TypesnameVariable names must conform to the rules for identifiers:• they must begin with a letter,• after that they can contain digits, dollar signs andunderscores.• Java uses Unicode for its characters, so any“letter” that is valid for a word in any worldlanguage is therefore valid for a name in Java.
  • Java I--Copyright © 2000-2004 Tom Hunterint num1=2;• You declare a variable andinitialize it on the same line.• This is a declaration. At this point,the name num1 refers to a location{a pointer} in the computer’s RAMwhere this variable is stored. •Because an int is declared, weknow that four bytes are set aside.• Still, nothing is stored in it yet.Primitive Data Typestype• The “type” appears before the identifier name.• The type can be one of the “primitive data types” or itcan be any previously defined class.int num1;num1 = 2;
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typessize• When we assign a type [ int, String] to avariable, we are not only declaring a memorylocation.• We also decide how big of a number or characteris able to be stored in that variable.
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typesvalue• Finally, the value is what we want the variableto store.
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Types• Java is a Strongly-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 charactersin Unicode encoding, and• 1 is a boolean type for true or false values.
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typesint• In contrast to C/C++, an int will always--nomatter which operating system--take 4 bytesof storage space.• Because those 4 bytes are set in stone, you can besure that every JVM that runs your programwill 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)
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typesshort• In Java, a short is defined as 2 bytes, no matterwhich operating system is used.• You would only use this for special situations,such as when speed is really crucial.{ For VB programmers, a short is whatyou’ve come to think of as an int . }Range:-32,768 to 32,767
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typeslong• A long is defined as 8 bytes, no matterwhich operating system is used.Range:-9,223,372,036,854,775,808L to9,223,372,036,854,775,807L• Please notice the upper-case L suffix is appended to anylong. This is required.• Hexadecimal numbers have a prefix: 0x0x1CFE.
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typesbyte• A byte is defined as 1 byte, no matterwhich operating system is used.Range:-128 to 127• Again, like a short, a byte is only used underrare circumstances.
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typesfloat• A float is defined as 4 bytes, no matterwhich 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.
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typesdouble• A double is defined as 8 bytes, no matterwhich operating system is used.Range:approximately ±1.79769313486231570E+308( 15 significant decimal digits )• “double is the one to have when you’re havingmore than one--decimal place, that is.”• This is the most common choice for any decimal.• double is the default, not float, therefore, nospecial character is appended. (See red arrow.)
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typeschar• A char is defined as 2 bytes, no matter whichoperating system is used. A char type always refersto 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 asingle character.
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typeschar• A char is defined as 2 bytes. A char type is asingle Unicode character.[uFFFF u is the escape character syntax--65,536different characters can be represented.]• Single quotes denote a single-letter char constant‘H’ is a char constant.“H” is a String that happens to only contain asingle character--it is not a char.This is a syntax error! The compiler willcomplain.
  • Java I--Copyright © 2000-2004 Tom HunterPrimitive Data Typesboolean• A boolean type has only two values.• In contrast to C/C++, in Java 0 and 1 cannotstand in for true or false.• A boolean type must be assigned the value of theconstants true or false.[Meaning, these exact lowercase words.]
  • Java I--Copyright © 2000-2004 Tom HunterJava Math Operators• Addition +• Subtraction -• Multiplication *• Division /• Modulus %All are binary operators, i.e., they work with twonumbers. They are executed according to the rules foroperator precedence. [page 1240](There is no operator for exponentiation in Java)
  • Java I--Copyright © 2000-2004 Tom Hunter• Multiplication *• What happens if you multiply variables of different types?Java Math Operatorsint x = 2;double y = 3.889, sum = 0.000;sum = y * x;• The integer will be temporarily converted to adouble and two doubles will be multiplied.• Afterwards, the original integer is unchanged.
  • Java I--Copyright © 2000-2004 Tom Hunter• Rules for Temporary Conversions1st Priority: If either of the operands is of type double, then the otherone 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, thenthe other one is converted to long for the calculation.Note: these conversions are automatic because none of them result in aloss of accuracy.Java Math Operators
  • Java I--Copyright © 2000-2004 Tom Hunter• Static CastsSo, what happens when you desire to convert a double to afloat? Information will inevitably be lost.• You accomplish this using a cast.Java Math Operatorsint x = 2, sum = 0;double y = 3.889;sum = (int)y * x;{ sum is now equal to 6 }• Here, a value of just 3 will be used for y.• If you want to round y, you a method from classMath:sum = (int)Math.round(y) * x;
  • Java I--Copyright © 2000-2004 Tom HunterJava Math Operators• Division /• Division can lead to unexpected results:If both operands are integers, then the result of thedivision is also an integer.Any fractional part of the division is discarded.Therefore: 17/3 = 5
  • Java I--Copyright © 2000-2004 Tom HunterJava Math Operators• Modulus %• The modulus operator is confusing at first, buteventually it becomes your good friend.In contrast to the division operator, it returns theremainder of any division. The modulus operator canonly be used when both operands are integers.17 % 3 = 2You say this “17 modulus 3 equals 2”
  • Java I--Copyright © 2000-2004 Tom HunterComparison Operators• These are used for selection structures:equality ==not equal !=greater than >less than <greater than or equal >=less than or equal <=
  • Java I--Copyright © 2000-2004 Tom HunterComparison Operators• The equality operator is a common source of mistakes:equality ==Note that two equal signs are always used.The single equal sign [ = ] is only used forassignment, that is, assigning the value on the right to thevariable on the left.num1 = 33;
  • Java I--Copyright © 2000-2004 Tom HunterComparison Operators• When you make a compound symbol using the equalsign, the equal sign is always on the right:equality ==not equal !=greater than or equal >=less than or equal <=
  • Java I--Copyright © 2000-2004 Tom Hunter“if” Statement Syntax• Decision Making •The if exactly mirrors C/C++, and it has three variants:1.) if( expression )statement;2.) if( expression )statement;elsestatement;3.) if( expression )statement;else if( expression )statement;elsestatement;
  • Java I--Copyright © 2000-2004 Tom Hunterif( expression )statement;if( expression ){statement1;statement2;}“if” Statement Syntax• Simple if •The “expression” must be something that uses thecomparison operators and resolves to either true or false.• The statement is executed if the expression is true.• Only one statement can be made conditional withoutbrackets. If you wish to conditionally execute more thanone statement, you use brackets to create a block.
  • Java I--Copyright © 2000-2004 Tom Hunterif( expression )statement;elsestatement;“if” Statement Syntax• Simple if/else •If the “expression” is true, the if branch executes, if not,the else branch executes.
  • Java I--Copyright © 2000-2004 Tom Hunterif( expression ){statement1;statement2;} else{statement3;statement4; }“if” Statement Syntax• Simple if/else •If the “expression” is true, the if branch executes, if not,the else branch executes.if( expression ){statement1;statement2;} //end of if else{statement3;statement4; } //end of elseDon’t bother to label theclosing brackets unlessyou have a really long if.Still you should always lineup your brackets.
  • Java I--Copyright © 2000-2004 Tom Hunter“if” Statement Syntaxif( expression )statement;else if( expression )statement;elsestatement;• Compact if/else if/ else •To prevent your nested ‘if’s from marching across thepage, you can use this nested if. You can go on nestingthem as long as you like, and the last one is just an else.