Introduction to Java Java Translation Program Structure Classes and Objects Primitive data types Flow of Control Loops.

Download Introduction to Java Java Translation Program Structure Classes and Objects Primitive data types Flow of Control Loops.

Post on 05-Jan-2016

212 views

Category:

Documents

0 download

TRANSCRIPT

  • Introduction to JavaJava TranslationProgram StructureClasses and ObjectsPrimitive data typesFlow of ControlLoops

  • The Java compiler translates Java source code into a special representation called bytecode in the .class fileJava bytecode is not the machine language for any specific CPUAnother software tool, called an interpreter (in our case the Java Virtual Machine), executes the bytecodeJava is considered to be architecture-neutralThe Java compiler is not tied to any particular machineThe JVM can be implemented on any machineJava Translation

  • Java Program StructureIn the Java programming language:A program is made up of one or more classesA class contains zero or more attributesA class contains one or more methodsA method contains program statementsA Java application starts with a class containing a method called mainSee Lincoln.java (page 28)

  • Java Program Structurepublic class MyProgram{

    }// comments about the classclass headerclass bodyComments can be placed almost anywhere

  • Java Program Structurepublic class MyProgram{

    }// comments about the classpublic static void main (String[] args){

    }// comments about the methodmethod headermethod body

  • ObjectsAn object has:state - descriptive characteristicsbehaviors - what it can do (or what can be done to it)The state of a bank account includes its balanceThe behaviors associated with a bank account include the ability to get the balance, make deposits, and make withdrawalsNote that the behavior of an object might change its state, e.g. making a deposit will increase the balance

  • ClassesAn object is defined by a class representing a conceptA class is the blueprint for each instance of an objectMultiple objects can be created from the same classA class has attributes that define the state of each objectA class has methods that define the behavior of the objectThe class that contains the main method represents the starting point for a Java programThe program can and usually does contain more classes than just the one that contains the main method

  • Objects and ClassesA Class(The Concept)Johns Bank AccountBalance: $5,257.51Three objects(Three Instancesof the Concept)Bills Bank AccountBalance: $1,245,069.89Marys Bank AccountBalance: $16,833.27Multiple objectsof the same classBankAccount- balance: float

    + getBalance(): float+ deposit(float amount): bool+ withdraw(float amount): bool

  • Primitive DataThere are eight primitive data types in JavaFour of them represent integers:byte, short, int, longTwo of them represent floating point numbers:float, doubleOne of them represents characters:charAnd one of them represents boolean values:boolean

  • CharactersA char variable stores a single characterCharacter literals are delimited by single quotes:'a' 'X' '7' '$' ',' '\n'Example declarations:char topGrade = 'A';char terminator = ';', separator = ' ';Note the distinction between a primitive character variable, which holds only one character, and a String object, which can hold a sequence of multiple characters

  • BooleanA boolean value represents a true or false conditionThe reserved words true and false are the only valid values for a boolean typeboolean done = false;A boolean variable can represent any two states such as a light bulb being on or off boolean isOn = true;

  • Flow of ControlUnless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequenceSome programming statements allow us to:decide whether or not to execute a particular statementexecute a statement over and over, repetitivelyThese decisions are based on boolean expressions (or conditions) that evaluate to true or falseThe order of statement execution is called the flow of control

  • Conditional StatementsA conditional statement lets us choose which statement will be executed nextTherefore they are sometimes called selection statementsConditional statements give us the power to make basic decisionsThe Java conditional statements are the:if statementif-else statementswitch statement

  • The if StatementThe if statement has the following syntax:

    if ( condition ) statement;

  • The if-else StatementAn else clause can be added to an if statement to make an if-else statement

    If the condition is true, statement1 is executed; if the condition is false, statement2 is executedOne or the other will be executed, but not bothSee Wages.java (page 211)if ( condition ) statement1;else statement2;

  • Block StatementsSeveral statements can be grouped into a block statement delimited by braces

    A block statement can be used wherever a statement is called for in the Java syntaxif (total > MAX){ System.out.println ("Error!!"); errorCount++;}Now the increment will only occur when the if condition is true

  • The switch StatementThe general syntax of a switch statement is:switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ...

    }

  • Comparing CharactersTherefore, if we want to base a decision in our program on whether a character is a digit or not, we can use the following code:if (character >= 0 && character = A && character
  • Comparing StringsRemember that in Java a string is an objectWe cannot use the == operator to determine if the values of two strings are identical (character by character)The equals method can be called with strings to determine if two strings contain exactly the same characters in the same orderThe equals method returns a boolean resultif (name1.equals(name2)) System.out.println ("Same name");

  • Comparing StringsWe cannot use the relational operators to compare stringsThe String class contains a method called compareTo to determine if one string comes before anotherA call to name1.compareTo(name2)returns zero if name1 and name2 are equal (contain the same characters)returns a negative value if name1 is less than name2returns a positive value if name1 is greater than name2

  • Strings

    String is basically just a collection of characters.Thus, the string Martyn could be thought of as a 6-element array ('M', 'a', 'r', 't', 'y', 'n').The String class allows us to manipulate these data items.

  • Strings in javaString is a class in JavaStrings are constant (values cannot be changed after they are created)Set of characters "Lisa Simpson" is a string."A" is a string, 'A' is a character. Note the difference here. Character literals are delimited by single quotes and String literals are delimited by double quotes.

  • Methods on StringsThe String class provides methods to Return the character at a specific index (charAt) Return the index of a specific character (indexOf) Compare two strings (compareTo) Concatenate two strings (concat) Check the length of a string (length) Extract a sub-string (substring) Replace all instances of a character with another character (replace)

  • Repetition StatementsRepetition statements allow us to execute a statement or a block of statements multiple timesOften they are referred to as loopsLike conditional statements, they are controlled by boolean expressionsJava has three kinds of repetition statements:the while loopthe do loopthe for loopThe programmer should choose the right kind of loop for the situation

  • The while StatementExecute Loop_BodyStartwhile(Boolean_Expression)Loop_BodytruefalseEnd loopEvaluate Boolean_Expression

  • The do-while Statementtrue StartExecute Loop_Body

    doLoop_Bodywhile(Boolean_Expression);

    falseEnd loopEvaluate Boolean_Expression

  • The for Statementfor( Initialization_Action ; Boolean_Expression ; Update_Action)Loop_Body

    true StartExecute Initialization_ActionfalseEnd loopEvaluate Boolean_ExpressionExecute Loop_BodyExecute Update_Action

Recommended

View more >