Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo.

Similar presentations


Presentation on theme: "Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo."— Presentation transcript:

1 Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University

2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 2 Java Basics Now that you’ve gotten an overview of programming in Java, it’s time to see specific things that you can do in Java and how you write code for these using OOP Methods Variables Identifiers Primitive Types Expressions Operators Statements Strings

3 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 3 Methods Describes a specific behavior for a class A method defines a sequence of instructions (or statements) to be carried out when that method is called

4 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 4 Method composition Has a signature and body The method’s signature is written as: Syntax: ( ) Example: public void deposit( int amount ) The method body Statements or instructions inside the curly braces (block of code)

5 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 5 Calling methods Other objects can “call” an object’s methods This means that that object will carry out all the instructions written in the method To call a method, you use what is known as the “dot notation” x.doSomething(…) means call the “doSomething” method of x

6 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 6 Variables Variable: a storage location with a name can contain data of a given type can change value as the program runs Using variables Declare Establish its data type and initial value Can also be thought of as “creating the space” for the value Set/change its value (through assignments) Use/display its value

7 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 7 Attributes and Local Variables Generally, there are 2 kinds of variables in Java Each kind differs from the other in lifetime and “scope” restrictions on places in your code where the variable exists and can be accessed Attributes (aka fields, or instance variables) Scope within a class more “permanent” Local variables Scope within a method for temporary use

8 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 8 Attributes aka fields, or instance variables Defined in the body of the class, outside of any methods (syntax: ;) Storage space exists as long as owner exists Instance variables belong to a particular instance of an object (e.g., balance of BankAccount) There’s also such a thing as a class variable or static variable shared by all instances of a class more on this later

9 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 9 Local Variables Defined inside a method Temporary storage that is only available while you are running that method Think of it as “scratchpad” storage Parameters are special local variables hold the input values to a method, e.g., the amount variable in public void deposit( int amount )

10 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 10 BankAccount Example BankAccount int balance BankAccount() (constructor) int getBalance() void deposit( int amount ) public class BankAccount { private int balance; public BankAccount() { this.balance = 0; } public int getBalance() { return this.balance; } public void deposit( int amount ) { this.balance = this.balance + amount; } … } BankAccount.java acct1: BankAccount 0 balance Suppose acct1 already exists, and another object calls … acct1.deposit( 100 ); What happens? A variable named amount is created with value 100 and passed as the parameter to deposit. (It also becomes a local variable within deposit.) Read the value of this.balance, add to value of amount, and store the value into this.balance again 100 amount 0 100

11 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 11 BankAccount Example BankAccount int balance BankAccount() (constructor) int getBalance() void deposit( int amount ) public class BankAccount { private int balance; public BankAccount() { this.balance = 0; } public int getBalance() { return this.balance; } public void deposit( int amount ) { this.balance = this.balance + amount; } … } BankAccount.java acct1: BankAccount 0 balance Suppose acct1 already exists, and another object calls … acct1.deposit( 100 ); What happens? A variable named amount is created with value 100 and passed as the parameter to deposit. (It also becomes a local variable within deposit.) Read the value of this.balance, add to value of amount, and store the value into this.balance again 0 100 amount variable is destroyed when the method completes

12 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 12 Statements Statements are “instructions” that tell the program to “do something” One or more statements comprise the body of a method Some kinds of statements in Java: Declarations Assignments Method return Output statements Conditional statements Loops Exception Handling Statements usually have to end with a ; Except when ending in } for conditionals, loops, exceptions

13 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 13 Declaration Creates the storage space for a variable Used when declaring fields in a class and when declaring local variables in a method Generally, in the form of ; Optional: initial assignment e.g., double interest; int withdrawalLimit = 20000;

14 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 14 Assignment Assigns a value to the variable Generally, in the form = ; e.g., this.balance = this.balance + amount; The left-hand side (variable name) must be a variable Because you will assign a value to it Cannot be a method or a constant or an expression that does not specify a variable as a storage space The right-hand side can be any expression that results in the same type as the left-hand side variable If the types are different, the compiler gives you an error In C, the compiler usually does NOT give an error. That is why Java is easier to program in than C

15 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 15 Java keyword: new Use new to create instances of a class Calls the constructor of the class b = new BankAccount(); A valid expression representing the object created

16 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 16 Method Return When inside a method, you can exit the method and return a value by saying: return ; Where is an expression that has the same type as the return type of the method signature Quits the method immediately The caller of the method gets the return value (and possibly it to another variable) e.g., bobBalance = bobAccount.getBalance();

17 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 17 Output Statements There is a special method called System.out.println( … ) that can print different types of data E.g., System.out.println( “Hello World” ); int x = 2 + 3; System.out.println( x ); // what will this print? We won’t need to use much for now because BlueJ allows us to directly see values of variables But useful for debugging …

18 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 18 Identifiers An identifier is a name in a Java program used for variables, classes, methods,... Rules in forming an identifier: consists of letters and digits, $, _ should start with letter or underscore canNOT contain spaces Examples: ateneo score5 total_credit bigBlue _one4three x if Some identifiers are reserved words

19 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 19 Java Conventions for Identifiers Class names Start with a capital letter, capitalize first letters of succeeding words Examples: HelloAgain, ComputePriceApplet Variable and method names Start with a lowercase letter, capitalize first letters of succeeding words aka “camelCase” Examples: dimeCount, unitPriceInDollars, onButtonPressed Constants All uppercase, use _ in between words Examples: PI, MAX_ELEMENT Note: Do not use $ in your names, even if you can!

20 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 20 Data Types Describes “what” a variable can contain Helps a compiler impose rules Some primitive data types in Java: int, char, float, long, double, boolean Each primitive type also have a proper syntax for expressing literals e.g., 234 is an integer literal, ‘A’ is a character literal, 2.1e-3 is a double floating point literal

21 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 21 Understanding Data Types Important components of a data type: Range of values Literals Possible operations

22 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 22 The int Data Type Range: -2,147,483,648 to 2,147,483,647 The range is limited because these are the numbers that can be represented by a 32-bit binary number Literals sequence of digits Examples: 22, 16, 1, 426, 0, 12900 Operations: usual arithmetic operations +, -, *, /, % negative numbers obtained using - as prefix

23 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 23 Binary Numbers Humans can naturally count up to 10 values, But computers can count only up to 2 values (OFF and ON, or 0 and 1) Humans use decimal, computers use binary Example: an 8-bit number is called a byte 0 2020 b0b0 0 2121 b1b1 1 2 b2b2 0 2323 b3b3 0 2424 b4b4 1 2525 b5b5 1 2626 b6b6 0 2727 b7b7 01100100 2 = 2 6 + 2 5 + 2 2 = 64 + 32 + 4 = 100 10 Range 0 to 2 n - 1 Note: In Java, a byte is actually signed, and has a range of -128 to +127. The last bit has a place value of -128 instead of 128. More on this later…

24 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 24 The double Data Type Values: decimal numbers Range: 4.94e-324 to 1.80e+308 Limited precision: n.nnnnnnnnnnnnnnn... X 10 (+/-)mmm Even though you can specify up to 10 308, you don’t actually get 308 digits of precision, just a few (check how many) Again, this is because we are limited (in this case, to 64 bits) Literals (examples) 100.5, 0.33333, 200000.0 -8E10 (-80000000000), 2.1e-3 (0.0021) Operations: arithmetic ops (division?) float: lower precision (fewer digits)

25 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 25 Constants Literal values in a program Appear often enough and may be associated with an appropriate name Declare at the level of the methods (right after the opening curly brace for the class) Prefix the declaration with public static final Examples (note naming convention) public static final int MAX = 100; public static final double PI = 3.1415926; public static final double DIME_VALUE = 0.10;

26 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 26 Operators and Expressions

27 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 27 Operators in Java Arithmetic operators +, -, *, /, % Special operators (, ) performs grouping = (assignment) Other operators

28 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 28 Understanding Operators Operands count (binary/unary) type Return value Calculation performed value and type returned Effects does this operator cause a change in the value of a variable?

29 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 29 Example: % Modulo (aka “mod”) or Remainder operator Operands Binary operation Both operands are ints Returns: the (int) remainder when left operand is divided by the right operand Effects: none

30 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 30 Another Example: = Assignment Operator Operands Binary operation Left operand must be a variable Returns: the value of the right operand Effect: value of left variable becomes set to the value of the right operand Note that a = b = c = 0; is valid.

31 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 31 Other Operators Increment and decrement operators ++, -- post- or pre- Assignment operators +=, -=, *=, /=, … “Built-in” Functions not really operators (but similar) Math.abs(), Math.sqrt(), Math.pow(),...

32 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 32 Post-increment Operator: ++ Example: number++ Operands Unary operator Operand must be a variable Returns: the original value of the operand Effect: variable is incremented Note: the variable is incremented after its value is returned

33 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 33 Pre-increment Operator: ++ Example: ++number Operands Unary operator Operand must be a variable Returns: the new (incremented) value of the operand Effect: variable is incremented Note: the variable is incremented before its value is returned

34 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 34 About ++ Notice that a++; and ++a; are similar return value is ignored in both cases could be used as shorthands for a = a + 1; But they are not the same! Difference is seen when the return value is useda = 5; b = a++;b = ++a;// values of a & b?

35 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 35 Decrement Operator: -- Analogous definitions for Post-decrementnumber-- Pre-decrement--number

36 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 36 Assignment Operators There is a shorthand for constructs such as sum = sum + number; sum += number; += is an operator: such an operator exists for virtually every arithmetic operator +=, -=, *=, /=, %=,... effect: variable is updated returned value: the updated value

37 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 37 Built-in Functions Provided in Java to provide for more complex operations Example: Math.pow() double result = Math.pow( 5.5, 3.0 ); can be viewed as a binary operation that calculates some power of a number javap java.lang.Math prints a list of available math functions

38 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 38 Operand Types vs Result Type There are cases where the type of the result differs from the types of the operands Examples division between an int and a double returns a double Math.round() has an operand (argument) that is a float but returns an int

39 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 39 Caveats on Operand types Be Careful! For arithmetic operators, return value depends on types Example double x = 5 / 2; // puts 2 (not 2.5) in x Why? because 5 is an int, and 2 is an int Fix? double x = 5.0 / 2;

40 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 40 Casting Primitive Types int a = 5; int b = 2; double x = a / b; Problem: still returns 2 Fix? Do a “cast” tells Java to change data type double x = (double)a / (double)b Note: casting can also be used for rounding (down) int x = Math.sqrt( 2.0 ); // won’t work int x = (int)Math.sqrt( 3.0 ); // returns 1 int x = (int)Math.round( Math.sqrt( 3.0 ) ); // returns 2

41 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 41 Strings and Concatenation Consider the statement: System.out.println( “Hello” ); “Hello” is of type String The + operation can be used for String concatenation works between Strings, and also between Strings and primitive types Examples System.out.println( “basket” + “ball” ); System.out.println( “the sum is ” + sum ); // sum is first converted to a String

42 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 42 Expressions Expression a sequence of variables, literals, operators, and/or method/function calls has a return value and type Uses right operand of an assignment argument for System.out.println() Expression-statement an expression terminated by a semicolon

43 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 43 Statements

44 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 44 So far … Variable contains data Expression sequence of variables, operators, literals, and function calls has return value used for operations on data Statement tells Java to actually carry out the computation may contain expressions is included in the body of a method

45 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 45 Statements in Java Declarations Example: double distance = 3.5; Expression-statements Examples: x = 5; area = PI * radius * radius; ++count; a = b = c = 0; result = Math.pow( 2.0, 0.5 ) / 3;

46 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L4: Java Basics Slide 46 Statements, continued Input and output statements are in fact expression-statements Examples x = JOptionPane.showInputDialog( “Enter x” ); System.out.println( answer ); contain function calls Other statements Decision statements (conditional execution) Loops Others


Download ppt "Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo."

Similar presentations


Ads by Google