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

Slides:



Advertisements
Similar presentations
1 Variables and Data Types. 2 Variable Definition a location in memory, referenced by a name (identifier), where data of a given type can be stored, changed,
Advertisements

Programming Languages and Paradigms The C Programming Language.
CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
Lecture 2 Introduction to C Programming
Introduction to C Programming
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Chapter 2: Introduction to C++.
JavaScript, Third Edition
Introduction to C Programming
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Introduction to Object-Oriented Programming
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Java and Object-Oriented Programming AJSS Computer Camp Department of Information Systems and Computer Science Ateneo de Manila University.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Loops and Iteration for Statements, while Statements and do-while Statements.
Classes CS 21a: Introduction to Computing I First Semester,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)
November 1, 2015ICS102: Expressions & Assignment 1 Expressions and Assignment.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 2 Variables.
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
Java-02 Basic Concepts Review concepts and examine how java handles them.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
ICS102 Lecture 1 : Expressions and Assignment King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Chapter 2 Variables.
Yanal Alahmad Java Workshop Yanal Alahmad
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Edited by JJ Shepherd
Expressions and Assignment
elementary programming
Chapter 2: Introduction to C++.
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Classes CS 21a: Introduction to Computing I
In this class, we will cover:
Primitive Types and Expressions
Unit 3: Variables in Java
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Variables.
Programming Languages and Paradigms
Loops and Iteration CS 21a: Introduction to Computing I
Presentation transcript:

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

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

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

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)

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

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

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

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

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 )

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

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 amount variable is destroyed when the method completes

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

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;

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

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

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();

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 …

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

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!

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

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

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, Operations: usual arithmetic operations +, -, *, /, % negative numbers obtained using - as prefix

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 b0b b1b1 1 2 b2b b3b b4b b5b b6b b7b = = = Range 0 to 2 n - 1 Note: In Java, a byte is actually signed, and has a range of -128 to The last bit has a place value of -128 instead of 128. More on this later…

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 , 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, , E10 ( ), 2.1e-3 (0.0021) Operations: arithmetic ops (division?) float: lower precision (fewer digits)

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 = ; public static final double DIME_VALUE = 0.10;

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

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

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?

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

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.

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(),...

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

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

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?

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

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

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

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

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;

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

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

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

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

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

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;

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