Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings
public class BasicsDemo { public static void main(String[] args) { int sum = 0; for (int current = 1; current <= 10; current++) { sum += current; } System.out.println("Sum = " + sum); }
Variables and Data Types Variables contain data that can change during program execution type name All Variables have type, name, scope Two Major Categories (Type): –Primitive –Reference Purity: Format and Size
// integers byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = Integer.MAX_VALUE; long largestLong = Long.MAX_VALUE; // real numbers float largestFloat = Float.MAX_VALUE; double largestDouble = Double.MAX_VALUE; // other primitive types char aChar = 'S'; boolean aBoolean = true;
Variable Type Determines Values Variable can have Determines Operations that can be performed on a variable Primitive: Single value of appropriate size and format Reference to value or set of values that variable represents (classes, interfaces, arrays)
Primitive Data Types
Variable Names Program refers to variable value by name Composed of Unicode Characters Must not use keywords or boolean literals (true or false) Unique within scope Convention: begin with lowercase More than one word, capitalize
Scope Block of code where variable is accessible Determined by location in program Four Categories –Member Variable –Local Variable –Method Parameter –Exception-Handler Parameter
Member Variable is a member of a class or object which can be declared anywhere in a class, but not in a method. Local Variables are declared anywhere in a method. Method Parameters are used to pass values to methods (arguments) Exception-handler Parameters are arguments to exception handling methods.
Variable Initialization Local and member variables can be initialized when declared. final keyword: value cannot change after initialization. Variables must be initialized before use Good Programming Practice to do it at declaration
Operators Perform a function Unary, binary, tertiary, … Unary: Prefix or Postfix (++i, i++) Binary: Infix (a + b) Returns a value Arithmetic, Bitwise and Logical, Assignment
Expressions The Workers Application of an operator is an expression An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to a single value. Precedence
Control Flow while if-then-else switch for loops continue
Arrays and Strings Array Declaration: Array is an class, so an array object must be instantiated (new) Instantiation allocates memory to the object Arrays can contain any valid Java data type String objects, not character arrays Concantenation operator (+)