Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 1 Sun Certified Java 1.4 Programmer Chapter 1 Notes Gary Lance

Slides:



Advertisements
Similar presentations
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Advertisements

1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Java Syntax Primitive data types Operators Control statements.
Primitive Data Types byte, short, int, long float, double char boolean Are all primitive data types. Primitive data types always start with a small letter.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
CS102--Object Oriented Programming Review 1: Chapter 1 – Chapter 7 Copyright © 2008 Xiaoyan Li.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Prepared by Uzma Hashmi Instructor Information Uzma Hashmi Office: B# 7/ R# address: Group Addresses Post message:
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
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.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 8, page 1 Sun Certified Java 1.4 Programmer Chapter 8 Notes Gary Lance
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Pemrograman Dasar Arrays PTIIK - UB. Arrays  An array is a container object that holds a fixed number of values of a single type.  The length of an.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
Defining Classes II. Today’s topics  Static methods  Static variables  Wrapper classes  References  Class parameters  Copy constructor.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 3, page 1 Sun Certified Java 1.4 Programmer Chapter 3 Notes Gary Lance
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
JAVA COURSE 1 Computer Engineering Association. Compile your first program Public class Hello{ public class Hello(){ System.out.println(“Hello”); } puclic.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Developed at Sun Microsystems in 1991 James Gosling, initially named “OAK” Formally announced java in 1995 Object oriented and cant write procedural.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Peyman Dodangeh Sharif University of Technology Spring 2014.
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.
Classes, Interfaces and Packages
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
OOP Basics Classes & Methods (c) IDMS/SQL News
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Last Revision. Question1 Novice Java programmers often write code similar to, class C { public int x;... }... C[] a = new C[10]; for(int i = 0; i < a.length;
Object Oriented Programming Lecture 2: BallWorld.
Java Programming Language Lecture27- An Introduction.
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.
Topic: Classes and Objects
Chapter No. : 1 Introduction to Java.
Class Structure 15-Jun-18.
Some Eclipse shortcuts
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
An Introduction to Java – Part I, language basics
Tonga Institute of Higher Education
Arrays in Java.
Java Programming Language
CSC 111 Exam 3 Review Fall 2005.
Review for Midterm 3.
CS 240 – Advanced Programming Concepts
Presentation transcript:

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 1 Sun Certified Java 1.4 Programmer Chapter 1 Notes Gary Lance

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 2 Your Objective Your Name

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 3 Getting Java to Run Create a folder on the desktop. (Suggestion – its name should be your name, or part of it). My folder is “glance”. RMB on “cmd.com” in WINNT/System, drag to your folder, release and select “copy to folder”. RMB on MS-DOS, and change properties – “start-in” to name of folder.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 4 Environmental Variables Create “User-variable” named “CLASSPATH”, if it doesn’t exist. Append your folder name to “value”. If there is already a “CLASSPATH”, at end of string, put “;”, and then the path to your folder. For system variables, edit “PATH” or “path” to include path to “lib” folder of the Java jdk (which is in the Sun folder”

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 5 Java Conventions All variables will always start with a small letter. All class names will start with a capital letter. All final strings will consist of capital letters and underscores ‘_’ only. Variables and class names that are compound will have “camel code”. Java is case-sensitive, so ‘Person’ and ‘person’ are not the same. There can only be ONE public class per file, and the name of that file MUST be the name of that class, with “.java” appended to its end. A Java file can have any number of non-public classes. Package names should begin with a lowercase letter.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 6 Integer Primitives NOTE: 8 bits = 1 byte TypeWidth in bits (bytes) MIN_VALUEMAX_VALUE byte8 (1)-2 7 (-128) (127) short16 (2)-2 15 ( ) (32,767) int32 (4)-2 31 (-2,147,483,648) (2,147,483,647) long64 (8)-2 63 (-9,223,372,036,854,775,808L) (9,223,372,036,854,775,807L)

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 7 Other Primitives TypeWidth in bits (bytes) MIN_VALUEMAX_VALUE float32 (4) e e+38 double64 (8) e e+308 char16 (2)0x00xffff booleanN/AIs either true or false

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 8 Default Values for Member Variables TypeDefault Value booleanfalse char‘\u0000’ integers0 floating points0.00F or 0.00 object referencesnull

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 9 Problems What is wrong with these assignment statements? char e = -29; float d = 25.9; int i = 50000; short s = i;

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 10 Statement Basics Equal “draws from the right”: int a, b, c; a = b = c = 10; 1.c is assigned the value 10 2.b is assigned the value held by c 3.a is assigned the value held by b

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 11 Arrays int[] key; // declares a reference ‘key’ that can hold int values We haven’t discussed references yet, but for now, know that a reference will eventually hold the address of the beginning location of “something”. Here, the “something” is the beginning of the location where the array ‘key’ will eventually be stored.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 12 Arrays int[] key = new int[100];// array holding 100 primitive types ‘int’ Recall that ‘=‘ draws from the right. 1.Memory is created that can hold 100 ints. (How many bytes is this?) The memory for an array will always be consecutive. Arrays are 0-based. The O/S returns an address which is where the start of the array is in memory. 2.Each element of the array has its default value (0, in this case). 3.A variable ‘key’ is declared which can old the address of an array of int. 4.The address of the array returned by the O/S becomes the value of ‘key’.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 13 Arrays, ctd To get the number of elements that can be stored in the array ‘keys’: keys.length This is a special Java syntax for arrays. The ‘.’ between ‘keys’ and ‘length’ does not have the same meaning when appending a dot to an object reference. Note: “length” does not have “()” after it. This will often be confused with the method “length()” of the String class, which returns the number of chars in the String object.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 14 Initializing Arrays of Primitives int[] intArray = new int[3]; intArray[0] = 1; intArray[1] = 89; intArray[2] = 789; double[] dblArray = {1.2, 3.4, 5.6}; int[] scores; scores = new int[]{1, 89, 789}; What is wrong with the next statements? // Anonymous array creation float[] floatArray;// declare a reference floatArray float f1 = 1.1, f2 = 3.3, f3 = 5.5; floatArray = new float[]{f1, f2, f3};

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 15 Explain This Code private static void println( float[] array ){ for(int i = 0; i < array.length; i++){ System.out.print( array[i] ); if( i != array.length - 1) System.out.print(", "); } System.out.println(); }

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 16 Multi-Dimensional Arrays A 2-Dimensional array is just an array of arrays. That is, each first index will hold an array. You can then generalize this concept for higher dimensional arrays. // Create a 2-dimensional array twoDeeArray1, // specifying all the storage immediately int[][] twoDeeArray1 = new int[10][5]; // The above is really a short way to do the following int[][] twoDeeArray2 = new int[10][]; for(int i = 0; i < twoDeeArray2.length; i++) twoDeeArray2[i] = new int[5];

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 17 Initialize Multidimensional Array int[][] dimArray = { {1,2,3}, {4,5}, {6,7,8,9,10,11} }; 1.What is dimArray[0]? It is a ___ to a ___ element array. 2.What is dimArray[1]? It is a ___ to a ___ element array. 3.What is dimArray[2]? It is a ___ to a ___ element array. 4.What is the value of dimArray[2][4]?

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 18 Person Class class Person { private String firstName; private String lastName; // CONSTRUCTOR public Person(String firstName, String lastName){ setFirstName(firstName); setLastName(lastName); } // ACCESSORS public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } // MUTATORS public void setFirstName(String firstName){ this.firstName = firstName; } public void setLastName(String lastName){ this.lastName = lastName; } We need a simple class in order to demonstrate how to create arrays of objects. We will cover more details about classes soon...

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 19 Person[] persons Create one Person object, and call it ‘joe’. Person joe = new Person(“Joe”, “Smith”); What if we want to store names of 10 people? (Is the code below ok?) Person[] person = new Person[10]; person[0] = new Person(“Gary”, “Lance”); person[1] = new Person(“Shan”, “Nawaz”); person[2] = new Person(“Abe”, “Lincoln”);... person[10] = new Person(“Doesn’t”, “Exist”);

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 20 Person Array Populate person2 with anonymous Person objects. Person[] person2 = { new Person(“a”, “b”), new Person(“c”, “d”) };

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 21 Basic Inheritance Everything Is An Object. public class Person {...} Person implicitly extends Object: public class Person extends Object {...} Person is thus a “special” Object, having the instance variables and methods of Person, as well as the functionality of Object (through the public methods of Object).

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 22 Inheritance class Vehicle { protected float weight;// protected means subclasses have copies protected int numDoors;// of these variables for their data. You should not protected int numTires;// redefine them in subclasses. // Constructor public Vehicle(float weight, int numDoors, int numTires){ this.weight = weight; this.numDoors = numDoors; this.numTires = numTires; } // A BIKE IS A VEHICLE, BUT A VEHICLE IS NOT A BIKE. class Bike extends Vehicle { private int numSpokes; // Constructor public Bike(int numSpokes, float weight, int numDoors, int numTires){ super(weight, numDoors, numTires);// calls constructor of superclass this.numSpokes = numSpokes; }

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 23 Inheritance A [superclass] reference can hold a reference to either 1.a reference of the same class 2.a reference to a subclass Vehicle v = new Vehicle(); // holds ref. to Vehicle (ok) Bike b = new Bike(); // holds ref. to Bike (ok) v = b;// ok, since v is a superclass ref. b = v;// runtime error (page 309). Why?

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 24 Given the previous definitions of classes Vehicle and Bike, what is wrong with this code? Vehicle[] vehicles = new Vehicle[2]; vehicles[0] = new Vehicle(); vehicles[1] = new Bike(); Constructors

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 25 Constructors Answer: If you define a constructor that has parameters, and you do not define a no-argument (or default) constructor, then if you create an object with the default constructor, you will get a compiler error. The Solution: (1) use an existing constructor, (2) define a no-argument constructor, or (3) do not use the no-argument constructor when creating an object of that class.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 26 Vehicle[] vehicles = new Vehicle[2]; // weight, numDoors, numTires vehicles[0] = new Vehicle(1000, 4, 4); // numSpokes, weight, numDoors, numTires vehicles[1] = new Bike(200, 75, 0, 2); Constructors

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 27 class Vehicle with Default Constructor and toString() class Vehicle { protected float weight; protected int numDoors; protected int numTires; public Vehicle(){ } public Vehicle(float weight, int numDoors, int numTires){ this.weight = weight; this.numDoors = numDoors; this.numTires = numTires; } public String toString(){ return "(weight, numDoors, numTires) = (" + weight + ", " + numDoors + ", " + numTires + ")"; }

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 28 class Bike with Default Constructor and toString() class Bike extends Vehicle { private int numSpokes; public Bike(){ } public Bike(int numSpokes, float weight, int numDoors, int numTires){ super(weight, numDoors, numTires); this.numSpokes = numSpokes; } public String toString(){ return "(numSpokes, weight, numDoors, numTires) = (" + numSpokes + ", " + weight + ", " + numDoors + ", " + numTires + ")"; }

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 29 What is Printed? // Create Vehicle array Vehicle[] vehicles = new Vehicle[2]; vehicles[0] = new Vehicle(); vehicles[1] = new Bike(); // Print out vehicles[0] and vehicles[1] System.out.println( vehicles[0].toString() ); System.out.println( vehicles[1] );

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 30 Instance (or member) Variables Defined within a class, represent the data that defines the objects of that class. For example, class Vehicle has three instance variables: weight, numDoors and numTires. class Bike has four instance variables: those of Vehicle, and numSpokes. RECALL: The default value of object references is null.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 31 Don’t Forget To Initialize Objects Before Using Them ‘null’ is a valid value for an object reference, but you can’t send messages to it. public class Book { private String title; public String getTitle(){ return title; } public static void main(String[] args){ Book b = new Book();// create Book object String s = b.getTitle();// s = _____? String t = s.toLowerCase();// Is this an error? }

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 32 Bad Way to Correct main(), in this example. public class Book { private String title; public String getTitle(){ return title; } public static void main(String[] args){ Book b = new Book(); String s = b.getTitle(); if( s != null)// why is this stupid? Because s always is null. String t = s.toLowerCase(); }

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 33 Other Ways to Correct main() public class Book { private String title; public Book(){// default constructor title = “”;// short for: title = new String(“”); }... } public class Book { private String title = “”;... }

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 34 Local Variables do NOT Behave Like Instance Variables public class Book { private String title; private int numPages; public String getTitle(){ return title; } public static void main(String[] args){ int numPages; System.out.println( numPages ); // compiler error – not initialized }

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 35 Command Line Arguments class Test { public static void main(String[] args){ int length = args.length; System.out.println(length); // Are the next statements valid? for(int i = 0; i < length; i++) System.out.println(args[i]); }

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 36 What is the Output? java Test java Test a java Test a “b” java Test 1 2 c

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 37 Problem 1.Create an array ‘person’ of ten Person objects, and store the references to 10 Person objects in that array. 2.Create another array ‘personRev’ that can hold 10 Person objects. 3.Copy the references of person into personRev, but in reverse order. Use a for- loop.

Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 38 End of Chapter 1