Just Enough JavaVariablesSome Java data typesDeclaring variablesAssignment statementsCommentsMethodsOrganization of a classArithmetic expressionsBoolean expressionsSpacesString concatenationif statementsCompound statementswhile loopsIndentation and spacingMethod callsA complete programThe EndJan 14, 2019Just Enough Java2VariablesA variable is a “box” that holds dataEvery variable has a nameExamples: name, age, address, isMarriedVariables start with a lowercase letterIn multiword variables, each new word is capitalized Every variable has a type of value that it can holdFor example,name might be a variable that holds a String (sequence of characters)age might be a variable that holds an integer valueisMarried might be a variable that holds a boolean (true or false) value3Some Java data typesIn Java, the four most important primitive (simple) types are:int variables hold integer valuesdouble variables hold floating-point numbers, that is, numbers containing a decimal pointboolean variables hold a true or false valuechar variables hold single charactersAnother important type is the StringA String is an Object, not a primitive typeA String is composed of zero or more chars4Declaring variablesEvery variable that you use in a program must be declared (in a declaration)The declaration specifies the type of the variableThe declaration may give the variable an initial valueExamples:int age;int count = 0;double distance = 37.95;boolean isReadOnly = true;String greeting = "Welcome to CIT 591";String outputLine;5Assignment statementsValues can be assigned to variables by assignment statementsThe syntax is: variable = expression;The expression must be of the same type as the variableThe expression may be a simple value or it may involve computationExamples:name = "Dave";count = count + 1;area = (4.0 / 3.0) * 3.1416 * radius * radius;isReadOnly = false;When a variable is assigned a value, the old value is discarded and totally forgotten6CommentsA comment is a note to any human reading the program; comments are ignored by JavaA comment starts with // and goes to the end of the lineA comment may be put after a statement (on the same line) to say something about that one statementA comment may be put on a line by itself, to say something about the following statementsExample:// Swap the values of x and ytemp = x; // save old value of x in tempx = y; // replace old value of x with yy = temp; // this many comments is just silly7MethodsA method is a named group of declarations and statementsvoid tellWhatYearItIs( ) { int year = 2005; System.out.println("Hello in " + year + "!");}We “call,” or “invoke” a method by naming it in a statement:tellWhatYearItIs( );This should print out Hello in 2005!8Organization of a classA class may contain data declarations and methods (and constructors, which are like methods), but not statementsA method may contain (temporary) data declarations and statementsA common error:•class Example {•int variable ; // simple declaration is OK•int anotherVariable= 5; // declaration with initialization is OK•variable = 5; // statement! This is a syntax errorvoid someMethod( ) {• int yetAnotherVariable; //declaration is OK• yetAnotherVariable = 5; // statement inside method is OK}•}9Arithmetic expressionsArithmetic expressions may contain:+ to indicate addition- to indicate subtraction* to indicate multiplication/ to indicate division% to indicate remainder of a division (integers only) parentheses ( ) to indicate the order in which to do thingsAn operation involving two ints results in an intWhen dividing one int by another, the fractional part of the result is thrown away: 14 / 5 gives 2Any operation involving a double results in a double:3.7 + 1 gives 4.710Boolean expressionsArithmetic comparisons result in a boolean value of true or falseThere are six comparison operators:< less than<= less than or equals> greater than>= greater than or equals== equals!= not equalsThere are three boolean operators:&& “and”--true only if both operands are true|| “or”--true if either operand is true! “not”--reverses the truth value of its one operandExample: (x > 0) && !(x > 99)“x is greater than zero and is not greater than 99”11SpacesYou should put a single space around every binary operator, including comparisons and =Example: perimeter=2*(width+height);Do not put spaces just inside parentheses:perimeter = 2 * (width + height); //badThese are style rules, not Java rulesIf you break these rules, your program will still compile OK, but you will lose points if we notice12String concatenationYou can concatenate (join together) Strings with the + operatorExample: fullName = firstName + " " + lastName;In fact, you can concatenate any value with a String and that value will automatically be turned into a StringExample:System.out.println("There are " + count + " apples.");Be careful, because + also still means additionint x = 3;int y = 5;System.out.println(x + y + " != " + x + y);The above prints 8 != 35“Addition” is done left to right--use parentheses to change the order13if statementsAn if statement lets you choose whether or not to execute one statement, based on a boolean conditionSyntax: if (boolean_condition) statement;Example:if (x < 100) x = x + 1; // adds 1 to x, but only if x is less than 100C programmers take note: The condition must be booleanAn if statement may have an optional else part, to be executed if the boolean condition is falseSyntax: if (boolean_condition) statement; else statement;Example:if (x >= 0 && x < limit) y = x / limit;else System.out.println("x is out of range: " + x);14Compound statementsMultiple statements can be grouped into a single statement by surrounding them with braces, { }Example: if (score > 100) { score = 100; System.out.println("score has been adjusted"); }Unlike other statements, there is no semicolon after a compound statementBraces can also be used around a single statement, or no statements at all (to form an “empty” statement)It is good style to always use braces in the if part and else part of an if statement, even if the surround only a single
View Full Document