1 Programming section 3 2 Importing classes purpose packages CLASSPATH creating and using a package.

Slides:



Advertisements
Similar presentations
ACM/JETT Workshop - August 4-5, Classes, Objects, Equality and Cloning.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Written by: Dr. JJ Shepherd
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
Chapter 3 - Java Programming With Supplied Classes1 Chapter 3 Java Programming With Supplied Classes.
Chapter 10.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Grade 12 Computer Studies HG
1 Programming Section 11 James King 12 August 2003.
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.
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
ArrayList, Multidimensional Arrays
Java 2 More Java Then Starbucks ;-). Important Terms Primitive Data – Basic, built-in values (characters & numbers) Data Type – Used to talk about values.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
From C++ to Java A whirlwind tour of Java for C++ programmers.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Strings Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
Introduction to Java Java Translation Program Structure
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
1 Programming Week 2 2 Inheritance Basic Java Language Section.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 7: Characters, Strings, and the StringBuilder.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Copyright Curt Hill Variables What are they? Why do we need them?
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
CS 139-Programming Fundamentals Lecture 11B - Arrays Adapted from a presentation by Dr. Rahman Fall 2014.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Classes Dwight Deugo Nesa Matic
Pointers *, &, array similarities, functions, sizeof.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Written by: Dr. JJ Shepherd
OOP Basics Classes & Methods (c) IDMS/SQL News
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Java Programming Language Lecture27- An Introduction.
Sections 10.1 – 10.4 Introduction to Arrays
Computer Organization and Design Pointers, Arrays and Strings in C
Array, Strings and Vectors
String class.
CS230 Tutorial Week 3.
Arrays in C.
Object Oriented Programming (OOP) LAB # 8
Java Programming Language
Introduction to Data Structure
Java Programming Language
Java Basics Data Types in Java.
Review: libraries and packages
Arrays and ArrayLists.
Presentation transcript:

1 Programming section 3

2 Importing classes purpose packages CLASSPATH creating and using a package

3 Importing classes Purpose Serious Java programming deals with many classes … … and so some sort of organisation is needed. Organisation in Java is achieved using the concept of a package (c.f. the use of folders or directories to organise files). A program can import classes from a package

4 Importing classes Packages Packages are collections of classes and sub-packages. (c.f. directories can hold files and subdirectories) The standard package or collection of classes used in Java is called java.lang

5 Importing classes Standard classes Standard classes in java.lang can be used directly e.g. System.out.println(“Hello world”);  out is a member variable (attribute) of the System class. It is of class PrintStream  println is a method of the PrintStream class

6 Importing classes A number of package classes If a number of classes required are in some other package then import all the public classes in the package. e.g. import java.awt.*; : Font f = new Font();

7 Importing classes Name clashes This fails if FTP is in both packages import com.naviseek.web.*; import com.prefect.http.*; : FTP out = new FTP(); This succeeds since ambiguity removed : com.prefect.http.FTP out = new com.prefect.http.FTP();

8 Protecting methods and attributes Basic Java Language Section

9 Protecting Your Class Usually you don’t want other objects directly changing your attributes because if you modify the type of name of the attributes you have to modify the other classes… So you can protect any method or attribute from outside interference.. by providing a setter to change its value You can also protect parts of your class using private and protected in their declaration

10 Problems with Accessing attributes directly class Hero { int bullets=10; } Hero h=new Hero(); h.bullets=-20; This is a silly value for the number of bullets but because the variable is accessed directly no error checking can be performed by the hero class

11 Using setters to change attributes class hero { int bullets=0; void set_Bullets(int b) { bullets=b; } Hero h=new Hero(); h.set_Bullets(-20); before we change the bullets attribute we could add error checking to detect bad values for b

12 Protecting Your Class Private – this means the method or attribute is not available outside the class it is defined in not even subclasses can access it Protected – only subclasses and classes in the same package can access it Public - anyone can access it Any class can always access the attributes and methods it defines

13 Protection class Hero { protected int bullets; public set_Bullets(int b) { bullets = b } private boolean spy; } now bullets cannot be accessed from outside the class from another package directly so the setter must be used to modify bullets and can provide error checking

14 Example of protection package examples; class Example1 { void doit() { Hero john = new Hero(); john.set_bullets(10); // legal because set_Bullets is public john.bullets=20; // illegal because height is protected john.spy=true; // illegal because spy is private }

15 Protection with inheritance package examples; class Hero2 extends Hero { void doit() { set_bullets(10); // legal because grow is public bullets=20; // legal because height is protected and we are a subclass of Person spy=true; // illegal because spy is private }

16 Arrays Mass Storage

17 Arrays Arrays allow large numbers of simple data types such as int or instances of classes to be easily accessed. int array[]=new int[10]; array[0]=4; array[9]=1234; System.out.println(array[0]); indicates that the array will hold 10 items accessing an element of an array also uses [] arrays start at 0 this is the last element of the array indicates variable is an array

18 Arrays holding Objects Arrays can also hold instances of a class or any of its subclass Monster array[]=new Monster[10]; array[0]=new Monster(); array[9]=new Dragon(); array[0].take_damage(); indicates that the array will hold 10 instances of the Monster class or subclass Dragon is a subclass of Monster so this is fine array[0] is an instance of Monster so we can call take_damage on it

19 Dangers of Arrays of Objects with an array of simple types such as ints every element in the array exists even if we don’t assign a value to them int array[]=new int[2]; System.out.println(array[0]); with an array of Objects elements are null until we assign an instance to them Monster array[]=new Monster[2]; array[0].take_damage(); null pointer exception! no problem!!

20 Initialising Object Arrays unlike arrays of simple types arrays of any type of object require each element to be instantiated and inserted into the array... Monster array[]=new Monster[2]; array[0]=new Monster(); array[1]=new Monster(); array[0].take_damage();

21 Finding the number of elements in an array Fortunately we can ask the array how long it is using.length int array[]=new int[10]; int index; for (index=0;index<array.length;index=index+1) { array[index]=0; } Now we can make the array bigger or smaller and the code will not crash and will initialise the entire array

22 Problems with Arrays I The single biggest problem with an array is that it is not variable length. You have to declare the length of the array as a constant and you can not tag on extra elements int array[]=new array[20]; array[30]=1234; array out of bounds exception!

23 Problems with arrays II You also can not remove elements in an array even if they are no longer needed. For instance suppose I have an array of 4 Monsters which the Hero is fighting. If the Hero kills 2 it would be nice to remove two from the array... the only thing you can do is to replace the dead instance with null.

24 Strings Mass Storage

25 Strings The String class allows you to store and manipulate sequences of characters Like chars, Strings are case sensitive so “hello” is not the same as “Hello” Strings are in fact Objects The length method tells you the length of a string in chars e.g. “hello”.length()==5 You can get a copy of the character at any position in a string using charAt() “hello”.charAt(0)==‘h’ “hello”.charAt(4)==‘o’

26 Relationship between String and Arrays It is possible to get a copy of the contents of a String as a char array String s="hello world"; char con[]=new char[s.length()]; s.getChars(0,s.length(),con,0); make sure the array is large enough to store the entire String Starting char in the Stringending char +1 in the String array to copy chars into starting position in the array

27 Relationship between String and Arrays It is also possible to create a string from a char array String s="hello world"; char con[]=new char[s.length()]; s.getChars(0,s.length(),con,0); con[0]='H'; s=new String(con); System.out.println(s); However, manipulating char arrays is not easy so in general it is better to manipulate the String by keeping it in its String format

28 Manipulating Strings There are many manipulation functions defined for the string object one of the most useful is subString You can get a copy of part of a string using subString “hello”.subString(0,2)==“hel” “hello”.substring(2,3)==“ll” starting index ending index

29 Adding to your String Unlike arrays, Strings can be appended and pre-pended to easily String s=“world”; s=“hello “+s; s=s+”!”; This gives the String “hello world!”

30 Seeing if Two Strings are Equal using == For simple types you can use == and != to see if something is equal or not equal. == and != do not work correctly for objects String s=“hello there”; String s1=“hello there”; s==s is true s1==s1 is true s==s1 is false!!!!!!!!!!!!!! This is because for objects == and != check where the instance is in memory and not the contents of the instances

31 Seeing if Two Strings are Equal using equals To see if two Strings are identical you need to use equals() or equalsIgnoreCase() String s=“hello there”; String s1=“hello there”; s.equals(s) is true s.equals(s1) is true This is because equals and equalsIgnoreCase check the contents of the instances and not their locations in memory

32 Converting other types into Strings Java will convert almost any simple type into a String for you String s=“”; int i=166; s=“”+i; This does not work for Objects because Java can not work out how to convert an object into a String “” converts a copy of i into a String “” is an empty String

33 Converting Strings into other types. Java provides static methods in classes called Integer, Long, Float and Double to help you: int i=Integer.parseInt("100"); long l=Long.parseLong("100"); float f=Float.parseFloat("100"); double d=Double.parseDouble("100"); If and only if the entire String looks like another type can the conversion take place. int i=Integer.parseInt(“hello 100"); Exception

34 More String Functions There are many more String manipulation functions than we have time for to look at here Take a look at the Java documentation for the String class and have some fun!