CompSci 100E JB1.1 Java Basics (ala Goodrich & Tamassia)  Everything is in a class  A minimal program: public class Hello { public static void main(String[]

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Programming Languages and Paradigms The C Programming Language.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
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.
Lecture 2: Object Oriented Programming I
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
11-Jun-15 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Terms and Rules Professor Evan Korth New York University (All rights reserved)
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Review Java.
String Escape Sequences
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Sahar Mosleh California State University San MarcosPage 1 A for loop can contain multiple initialization actions separated with commas Caution must be.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
CPS120: Introduction to Computer Science Decision Making in Programs.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Copyright Curt Hill Variables What are they? Why do we need them?
Chapter 2 Variables.
CompSci Primitive Types  Primitive Types (base types)  Built-in data types; native to most hardware  Note: not objects (will use mostly first.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
By Mr. Muhammad Pervez Akhtar
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
Java-02 Basic Concepts Review concepts and examine how java handles them.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
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.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
CompSci 100E cs. duke CompSci 100E Dietolf (Dee) Ramm
Information and Computer Sciences University of Hawaii, Manoa
Chapter 2 Variables.
3 Introduction to Classes and Objects.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Multiple variables can be created in one declaration
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Chapter 8 JavaScript: Control Statements, Part 2
Chapter 6 Control Statements: Part 2
Recap Week 2 and 3.
Expressions and Assignment
elementary programming
Chapter 2 Programming Basics.
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Programming Language
In this class, we will cover:
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Variables.
Just Enough Java 17-May-19.
Problem 1 Given n, calculate 2n
Corresponds with Chapter 5
Presentation transcript:

CompSci 100E JB1.1 Java Basics (ala Goodrich & Tamassia)  Everything is in a class  A minimal program: public class Hello { public static void main(String[] args) { System.out.println(”Hello Computer Science”); }  Output?  Where?  Do colors mean something?  Identify the pieces...

CompSci 100E JB1.2 Java Basics Objects  Every object is an instance of a class (which defines its type)  Objects contain data (state) and function (methods)  State  Stored in instance variables (fields, members)  Can be base types (e.g. integers) or instances of (objects) of other classes  Function  Expressed as methods (subroutines, functions, procedures…)  These define the behavior of objects of this class

CompSci 100E JB1.3 Java Basics  Declaring a Class: public class Counter { protected int count; Counter() { count = 0; } public int getCount() { return count; } public void incCount() { count = count + 1; } public void decCount() { count = count – 1; }  Identify the methods by kind  Constructor  Accessor  Mutator (modifier)  Note Syntax from this and previous examples  Braces  Semicolons  Parentheses  Indentifiers ...

CompSci 100E JB1.4 Java Basics  Class Modifiers  Abstract, final, public, default  Reserved Words  May not be used as identifiers  Shown in red by Eclipse and many of our examples  See table in text (p4) or in any Java text  Comments  For human consumption: ignored by compiler  Inline comments: // o Effective for rest (to end) of current line  Block comments: /* */ o Effective between start and stop groups

CompSci 100E JB1.5 Java Basics  Primitive Types (base types)  Built-in data types; native to most hardware  Note: not objects (will use mostly first four) boolean (1bit) int (4 bytes) double (8 bytes) char (2 bytes)  Constants/Literals (by example): boolean f = false; int i = 32769; double d = ; char c = ’x’; byte (1 byte = 8 bits) short (2 bytes) long (8 bytes) float (4 bytes) byte b = 33; short s = 21; long l = 289L; float = F;

CompSci 100E JB1.6 Java Basics  Creating and Using Objects (Example) public class Example { public static void main(String[] args) { Counter c; // Counter defined on a previous slide Counter d = new Counter(); c = new Counter(); System.out.println(”c = ” + c.getCount() + ” d = ” + d.getCount()); c.incCount(); d.decCount(); System.out.println(”c = ” + c.getCount() + ” d = ” + d.getCount()); d = c; // what does this really mean??? c.incCount(); d.incCount(); System.out.println(”c = ” + c.getCount() + ” d = ” + d.getCount()); }

CompSci 100E JB1.7 Java Basics  String Objects  string is a sequences of characters ( char ) o Unicode (16 bit)  String is a built-in class o Constants: ”this is an example”  String Concatenation ( + ) String s = ”Happy birthday to you.”; s = s + ”\n” + s; System.out.println(s); // what ?

CompSci 100E JB1.8 Java Basics  Object References  When creating object with new, get location or address of new object  Typically assign this to a reference variable: Counter c = new Counter();  Every object reference variable refers to object or null  Null is an important value that indicates object not created or not available.  Can have multiple references to same object  Access members of class using dot operator (“. ”). Counter c = new Counter(); c.incCount();  May have multiple methods with same name but different signature: e.g.: c.incCount(); c.incCount(5);

CompSci 100E JB1.9 Java Basics  Instance Variables  Classes have 0 or more instance variables o Also called fields o Keep state of object  May be primitive type o E.g. int, double  May be reference type (object) o E.g., String, Counter, (an array),...  If public can: o Access or alter reference variables using dot operator Counter c = new Counter(); System.out.println(c.count + ” = ” + c.getCount());

CompSci 100E JB1.10 Java Basics  Variables Modifiers: scope  public o Anyone can access  protected o Only subclass or same package may access  private o Only methods of same class may access  (omitted) default o Anyone in same package may access  Other Variable Modifiers  static o Associated with whole class, shared among instances  final o Must be initialized, then not changed: CONSTANT

CompSci 100E JB1.11 Java Basics - Methods  Methods  Like functions, procedure, subroutines,...  Has header and body  Syntax: modifiers type name(parameter_declarations){ method_body }  Modifiers like those of variables: opublic, private, protected, static, final  Type is return type and give type of information being passed back  Name is any valid Java identifier name  Parameters define type of info being passed into method

CompSci 100E JB1.12 Java Basics - Methods  Method modifiers  public: anyone can invoke (call)  protected: only called from subclass of same package  private: only called from same class  (omitted) (default): only called from same package  abstract: has no code (dealt with in subclass)  final: cannot be overridden in subclass  static: associated with class, not with instance  Return types  Use void is no information to be returned ( procedure )  Use actual type of information to be returned ( function ) o requires return statement(s) o only one item returned (may be compound object, e.g., array)

CompSci 100E JB1.13 Java Basics - Methods  Parameters  Parameter list may be empty (parentheses still required).  Parameter list consists of comma separated pairs of types and parameter names. public void setAge(String name, int age){…}  Constructors  Used to initialize new objects  Has same name as class and no return type public Counter() { count = 0; } public Professor(String aName, String aDept){ name = aName; department = aDept; }

CompSci 100E JB1.14 Java Basics  Using a Constructor  Invoked using a new operator o Examples: Professor compSciProf = new Professor(”Jeff Chase”, ”Computer Science”); Counter tally = new Counter();  Class may have multiple constructors as long a signatures are different  If class has no constructors defined, then a default constructor is used that does not initialize anything

CompSci 100E JB1.15 Java Basics - Methods  The main Method  Required for an Application o This is a stand-alone Java program o Typically invoked from a command line o Must include the following code: public static void main(String[] args){ // main body of the main method } o (The parameter name args can actually be any name you choose.) o Argument may be used to pass command line arguments to the program.

CompSci 100E JB1.16 Java Basics - Methods  Blocks and Local Variables  Body of a method is a block: a sequence of statements and declarations enclosed in braces ( { } ); o Blocks may have blocks nested inside o Variables declared with a block are known only in that block o These variables care called local variables o (We say their scope is limited to that block.) o (Method parameters are also local to that method.) o Examples: public static int sumThree(int a, int b, int c){ int sum; int partsum = a + b; sum = partsum + c; return sum; } o a, b, c, sum, and partsum are all local to that method

CompSci 100E JB1.17 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null, the only object literal available o Boolean: true or false o Integer: e.g., 127, -13, 42, or 0 create 32-bit integers  For 64-bit long append L or l, e.g., 17L o Floating Point: or 0.0 or 2.1E16 for 64-bit doubles  For 32-bit float append F or f, e.g., 2.56F or 0.5e-12f o Character: e.g., ’A’, ’Z’, ’w’, ’$’, ’%’ for 16 bit Unicode  control: ’\n’, ’\b’, ’\f’, ’\t’, ’\r’  escape : ’\’’, ’\\’, ’\”’ o Strings: e.g., ”How are things?” or ”” (null string)  Use mostly same control and escape characters as char

CompSci 100E JB1.18 Java Basics - Expressions  Operators  Arithmetic o +, -, *, /, % ( remainder or mod )  Increment/Decrement o e.g., k++, k--, ++k, --k  Logical (results in boolean value) o =, > o Used only for numbers except == and != o For boolean only: !, &&, ||  String Concatenation o “I’m “ “ years old and live in “ + city  Assignment o variable = expression o variable op= expression o ( shorthand for: variable = variable op expression )

CompSci 100E JB1.19 Java Basics - Expressions  Operator Precedence  Determines order of operation  See table in text  For arithmetic, matches grammar school learning o multiplication and division before addition and subtraction o what is the value of / 9.0 * 27.0 ? o (what is the value for the integer version?)  Parentheses override precedence rules (and don’t do harm when not needed)  For equal precedence (e.g., * and / ) work strictly left to right except for assignment and prefix operations which work right to left  Precedence rules same as for C and C++

CompSci 100E JB1.20 Java Basics - Expressions  Casting  Allows us to change the type of the value of an expression  (Type change must be reasonable and supported.)  Simple example: double x = 5.5, y = ; int k = (int) x; int m = (int) y; double z = (double) k; // what is in x, y, z, k, m ?  Implicit Casting  When an int expression is assigned to a double, casting is automatic (no information is lost). o (double cast at end of previous example not needed)  When double is on one side of an operator and int at other, int is automatically cast to a double before op is used. 5 / 9 * (68 – 32) vs. 5.0 / 9 * (68 – 32)

CompSci 100E JB1.21 Java Basics - Expressions  Autoboxing/Unboxing  Since Java 5.0, there is automatic casting between primitive types and their related Object types (also called wrapper classes ).  Simple examples: Double d = 2.9; used to require: Double d = new Double(2.9); and double x = d; used to require double x = d.doubleValue();

CompSci 100E JB1.22 Java Basics – Control of Flow  If Statement  if (boolean_exp) { what_to_do_if_true }  if (boolean_exp) { what_to_do_if_true } else { what_to_do_if_false }  if (1 st _boolean_exp) { what_to_do_if_1 st _true } else if (2 nd _boolean_exp){ what_to_do_if_2nd_true } else { what_to_do_if_all_false }

CompSci 100E JB1.23 Java Basics – Control Flow  Switch Statement  switch (int_type_exp) { case CONST1: action_for_CONST1; break; case CONST1: action_for_CONST1; break; case CONST2: action_for_CONST2; break; case CONST3: action_for_CONST3; break;... default: action_for_no_match; break; }

CompSci 100E JB1.24 Java Basics – Control Flow  Switch Statement Example  switch (stars) { case 4: message = ”truly exceptional”; break; case 3: message = ”quite good”; break; case 2: message = ”fair”; break; case 1: case 0: message = ”forget it”; break; default: message = ”no info found”; break; }

CompSci 100E JB1.25 Java Basics – Loops  While Loops  Syntax initialize while (boolean_exp) { work_to_be_done update }  Example int counter = 10; while (counter > 0) { System.out.println(counter); counter--; } System.out.println(”Blast Off!”);  What is the output?  What if we exchange order of two statements in loop?

CompSci 100E JB1.26 Java Basics – Loops  For Loops  Syntax for (intialization; boolean_exp; update) { work_to_be_done }  Example for (int counter = 10; counter > 0; counter--) { System.out.println(counter); } System.out.println(”Blast Off!”);  What is the output?  When is update performed?  What is value of counter after loop?

CompSci 100E JB1.27 Java Basics – Loops  Do-While Loops  Syntax initialize do { work_to_be_done update } while (boolean_exp); o NOTE REQUIRED SEMICOLON!!!  Example int counter = 10; do { System.out.println(counter); counter-- ; } while (counter > 0); System.out.println(”Blast Off!”);

CompSci 100E JB1.28 Java Basics – Loops  Which Kind of Loop Do I Use?  While Loop o Don’t know how often it’s going be o Update can be anywhere in the loop body  For Loop o Know how often in advance o All information controlling loop together, in front  Do-While Loop o Least popular o Often used with data input  What is the minimum number of times each of these loop? o while? o for? o do-while?

CompSci 100E JB1.29 Java Basics – Control Flow  Returning from a Method  Executing a return statements means you exit from the the method. Subsequent statements are ignored!  void Methods o Implicit return at end of body  Can make it explicit o Can have other return statements as logic dictates  Functions (non-void Methods) o Require return as last statement (with argument of correct type) o Can have other return statements as logic dictates

CompSci 100E JB1.30 Java Basics – Control Flow  Break Statement  Use to exit from loop or switch o One level only! o With nested loops, only leave loop immediately surrounding break  Continue Statement  Use to go to the end of a loop, ignoring remaining statements o Loop continues with next iteration (if needed) o One level only! o With nested loops, only got to end of loop immediately surrounding continue