Adam Gerber, PhD, SCJP Evaluations 50% homework 20% final project (take home) 20% two in-class quizzes (not announced, so come.

Slides:



Advertisements
Similar presentations
DATA TYPES, VARIABLES, ARITHMETIC. Variables A variable is a “named container” that holds a value. A name for a spot in the computer’s memory This value.
Advertisements

Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
Air Force Institute of Technology Electrical and Computer Engineering
Advanced Java Programming Adam Gerber, PhD, SCJP office: Ryerson CS Lab 4 th Floor office hrs: 3:30-5:30pm Wed.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Lab#1 (14/3/1431h) Introduction To java programming cs425
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Session 1 CS-240 Data Structures Binghamton University Dick Steflik.
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Bit Operations C is well suited to system programming because it contains operators that can manipulate data at the bit level –Example: The Internet requires.
A bit can have one of two values: 0 or 1. The C language provides four operators that can be used to perform bitwise operations on the individual bits.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations System-oriented Programming, B. Hirsbrunner,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Prepared by Uzma Hashmi Instructor Information Uzma Hashmi Office: B# 7/ R# address: Group Addresses Post message:
Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.
Creating a class. Fields (instance variables) Fields are the data defined in the class and belonging to each instantiation (object). Fields can change.
Georgia Institute of Technology Introduction to Java, and DrJava Barb Ericson Georgia Institute of Technology Aug 2005.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Java Tutorial. Object-Oriented Programming Concepts Object –a representation of some item state  fields/members and should be encapsulated behavior 
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
The Java Programming Language
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
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.
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
Creating a class. Fields (instance variables) Fields are the data defined in the class and belonging to each instantiation (object). Fields can change.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Copyright Curt Hill Variables What are they? Why do we need them?
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
COMP Primitive and Class Types Yi Hong May 14, 2015.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Duke CPS From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea l What it is ä O-O language, not a hybrid (cf. C++)
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
Adam Gerber, PhD, SCJP office: Ryerson 154 office hrs: 3:30-5:30 Tuesday.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Lecture 2 agenda flip teaching install p4merge rename project packages review git review Android Studio (Vinny) layouts and resources java event model.
CIS 338: VB Variables Dr. Ralph D. Westfall April, 2011.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Object Oriented Programming Lecture 2: BallWorld.
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.
Today… Continue Building Expressions: –Literals –Constants –Casting –Array Declaration –Operators and Operator Precedence –Keywords Winter 2016CMPE212.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Evaluations 50% homework 20% final project (take home)
Information and Computer Sciences University of Hawaii, Manoa
A variable is a name for a value stored in memory.
Working with Java.
Java Primer 1: Types, Classes and Operators
CISC124 Labs start this week in JEFF 155: Meet your TA.
Starting JavaProgramming
Fall 2018 CISC124 2/15/2019 CISC124 TA names and s will be added to the course web site by the end of the week. Labs start next week in JEFF 155:
Winter 2019 CMPE212 4/7/2019 CMPE212 – Reminders
Chap 2. Identifiers, Keywords, and Types
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
Review of Java Fundamentals
Presentation transcript:

Adam Gerber, PhD, SCJP

Evaluations 50% homework 20% final project (take home) 20% two in-class quizzes (not announced, so come to class prepared) 10% class participation Late homework/final project is penalized 5% every day late; no exceptions.

Turning in Assignments Tar you project using eclipse. Right click the project, select Export… choose Archive File Save in tar format, create Directory structure See video called eclipseTar.avi posted to course web- page. Homework file naming: hw + + “-” +.tar Homework examples: hw1-smith.tar, hw2-smith.tar Final project file naming example: fp-smith.tar to Jing Tie and cc me,

Criteria for evaluation on homework and final project 1/ does the program perform per spec 40% 2/ is the algorithm elegant/efficient or clumsy/wasteful 30% 3/ have you handled exceptions properly 20% 4/ code style; naming variables, formatting, ease of reading, documented 10%

What is Java?

What Sun (now Oracle) says about Java “…we designed Java as closely to C++ as possible in order to make the system more comprehensible. Java omits many rarely used, poorly understood, confusing features of C++ that, in our experience, bring more grief than benefit.”

What is Java? Java is modeled after C++ The majority of runtime errors in a C++ program are due to improper memory management (memory leaks). Java is a memory-managed environment. In practice, that means you don’t have to worry about de-allocating memory when an object or primitive falls out of scope. Java is Write Once Read Anywhere (WORA). A java program can run on any platform that has a JVM.

Architecture Neutral Java Code is compiled to.class files which are interpreted as bytecode by the JVM. (.NET does this too; only you’re trapped in an MS op system.)

Strictly OO Java is strictly Object-Oriented. Java code must be encapsulated inside a class. No procedural programming; and no spaghetti code.

No operator overloading Exception to no Java Op-Overloading … int nOne = 2; int nTwo = 7; String sName = “Fourteen”; System.out.println(sName + nTwo * nOne); … >Fourteen14

Implementation Independence A java int is ALWAYS 32bits; regardless of operating system. A java long is ALWAYS 64bits. Etc. The same is not true of C/C++.

No Pointers There are no pointers in Java Instead Java uses references; which for all intents and purposes, behave like pointers. We will discuss references in detail later.

Core Language Features

Java Keywords *not used ** added in 1.2 *** added in 1.4 **** added in 5.0

Order of Precedence: PEDMAS Operator Precedence OperatorsPrecedence postfixexpr++ expr-- unary++expr --expr +expr -expr ~ ! multiplicative* / % additive+ - shift > >>> relational = instanceof equality== != bitwise AND& bitwise exclusive OR^ bitwise inclusive OR| logical AND&& logical OR|| ternary? : assignment= += -= *= /= %= &= ^= |= >= >>>=

Wrapper Classes Every primitive has a corresponding Wrapper class. For example; double has Double, int has Integer, boolean has Boolean, char has Character, etc. These wrapper classes can be very useful when storing values in collections which require you to use objects, not primitives.

Java Primitive Data Types boolean 1-bit. May take on the values true and false only. true and false are defined constants of the language and are not the same as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value. Booleans may not be cast into any other type of variable nor may any other variable be cast into a boolean. byte 1 signed byte (two's complement). Covers values from -128 to 127. short 2 bytes, signed (two's complement), -32,768 to 32,767 int 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like all numeric types ints may be cast into other numeric types (byte, short, long, float, double). When lossy casts are done (e.g. int to byte) the conversion is done modulo the length of the smaller type. long 8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. float 4 bytes, IEEE 754. Covers a range from e-45 to e+38 (positive or negative). Like all numeric types floats may be cast into other numeric types (byte, short, long, int, double). When lossy casts to integer types are done (e.g. float to short) the fractional part is truncated and the conversion is done modulo the length of the smaller type. double 8 bytes IEEE 754. Covers a range from e-324d to e+308d (positive or negative). char 2 bytes, unsigned, Unicode, 0 to 65,535 Chars are not the same as bytes, ints, shorts or Strings.

Java Primitives (integers) TypeSigned?BitsBytesLowestHighest bytesigned shortsigned , ,767 intsigned ,147,483, ,147,483,647 longsigned , 223,372,036,854,775, ,223,372,036,85 4,775,807

How Java Stores positive Integers -2 (bits -1) to 2 (bits -1) – The above is a binary representation of the number 19 stored in a byte (8 bits). The range of a byte is: -128 to 127.

TypeSigned?BitsBytesLowestHighest booleann/a11falsetrue char unsigned Unicode '\u0000' '\uffff' float signed exponent and mantissa 324 ± e-45 ± e+38 with 6 to 7 significant digits of accuracy. double signed exponent and mantissa 648 ± e-324 ± e+308 with 14 to 15 significant digits of accuracy. Java Primitives (others)

Prefix and Postfix Unary Operators when a prefix expression (++x or --x) is used as part of an expression, the value returned is the value calculated after the prefix operator is applied int x = 0; int y = 0; y = ++x; // result: y=1, x=1 when a postfix expression (x++ or x--) is used as part of an expression, the value returned is the value calculated before the postfix operator is applied int x = 0; int y = 0; y = x++; // result: y=0, x=1

Primitives versus Objects nomenclature and conventions PrimitivesObjects In code, primitives are represented by variables. Variables have two properties; name and type. In code, Objects are represented by references. References have two properties; name and type. A variable name (aka variable) is lower_case or camel_case, such as: area, distanceToFinish, width, surfaceArea, etc. A reference name (aka reference) is lower_case or camel_case, such as: student, dinnerTable, deskTop, tabbedFrame, bankAccount, account etc. A variable type is the name of the primitive it represents, such as: boolean, byte, short, int, long, char, etc. (lower_case) A reference type is the name of the class it represents, such as: Rectangle, House, Car, StringBuilder, Math, ArrayList, etc. (UPPER_CASE) For primitive and Object fields, I use standard camelCase. The reason is that the IDE will generate getters and setters for me. For local variables and Objects, I tend to use prefixes. One-letter prefix for primitives; and three letters prefix for objects: nCounter, nC, datBirthDay, strFirstName, bFlag, dPrice, etc.

Eclipse IDE

Imports and the Java API Determine the version of Java you’re using. From the cmd line> java –version java.lang.* is automatically imported. This default behavior is know as ‘convention over configuration’. So Eclipse is very good about importing packages and catching compile-time errors. To use the javadoc for the core Java API; F1 – JDK\src.zip To see source code; F3

Using the debugger Perspectives; Java and Debug Setting breakpoints Setting conditional breakpoints Step-over F6, and Step-in F5 Watch expressions

Java Doc Generate default JavaDocs. Using decorations/tags. Project || Generate JavaDoc. – In Eclipse; navigate to JDK\bin\javadoc.exe to configure. Scope; public to private methods Use F1 to pull up your javadocs.

Naming conventions

Naming fields - suggestions boolean gender byte policyExpiry int students long population float totalTax double distanceToMoon Person director ArrayList shapes Use generic camel case for fields of classes. This is because the IDE will generate getters and setters for you automatically.

Naming local variables - suggestions boolean b bFlag byte y yAge char c cFirst short s sRosterSize int n nStudents; nC long l lPopulation float f fPrice double d dDistanceToMoon

Naming local references - suggestions Person per perDirector String str strFirstName Rectangle rec recShape1 Bee bee beeDrone

Naming local arrays and collections - suggestions Array of boolean barAnswers Array of byte yarAges Array of int narIdentities Array of Person perStudents Array of String strCountries Collection of Bee beeDrones Collection of Athlete athPlayers Collection of Cactus cacSaguaros NOT cacCacti

Why use a naming convention? metadata is immediately discernable just by looking at the local variable or local reference name. This makes your code easy to read and debug. Primitives always have one letter prefix; nNumber References have three letter prefix; perDirector. Arrays and collections have three letter prefix + s postfix: beeDrones; strCountries.

Attacking the problem 1/ Diagramming 2/ Psuedocode 3/ Implement in Java

Psuedocode Psuedocode is an intermediate language It describes an algorithm elegantly If you write proper pseudocode; implementing your algorithm is easy! Use diagrams to visualize the data structures in conjunction with pseudocode.

How to read psuedocode //processString(strParam) take string as parameter //initialize an int nPow to zero; and nResult to zero //for each char in string (iterate over the string backwards) exclude the sign bit //if char is either 1 or 0 (ignore spaces) //if the char is 1 //increment the result by 2^nPow //increment nPow //return nResult When writing psuedocode; Indent for either: 1/ looping logic such as do…while, while, for 2/ branching logic such as; if/else, case/switch Draw boxes around the groups if you need to.

How Java Stores positive Integers -2 (bits -1) to 2 (bits -1) – The above is a binary representation of the number 19 stored in a byte (8 bits). The range of a byte is: -128 to 127.

Diagramming See blackboard...

Class Object A blueprint is to a house as a class is to an object Class = Blueprint

Class Objects

Class Object A blueprint is to a car as a class is to an object Class = Blueprint

Class Objects

Spot the “class” here

Primitives versus Objects memory PrimitivesObjects Variables store values and are allocated memory depending on their type. How much?...refer to Java Primitives slide. References store memory addresses. The size of the allocation for the object reference is VM specific, but is usually the native pointer size; 32bits in 32-bit VM, and 64bits in a 64-bit VM. Garbage collected when out-of-scope. Passed into methods by valuePassed into methods by reference

Using the new Keyword Unless you use the ‘new’ keyword, nothing has been instantiated and the object does NOT exist in memory. (the exception is static; which we’ll talk about later)

pass by value pass by reference Action: Tell my accountant how much I intend to spend on a new car. Change in net worth: no change. Action: Swipe debit card and enter pin at the Bently dealership. Change in net worth: -125k.

Control structures Branching logic if if-else switch ternary Looping for while do…while break / continue

Object heirarchies You can also see the API online. Determine the version you using by typing> java –version Class hierarchies. The Object class is the grand-daddy of ALL java classes. Every class inherits methods from Object. And from all its other ancestry. Even if you create a class that extends no other classes, you still extend Object by default.

Some tools for your homework