SOFTWARE AND PROGRAMMING 1 Revision Lecture 11/5/2011: Review of concepts involved in lectures and exam Review of questions in previous exam papers (they.

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

1 Lecture 23/2/11 Working with an array Array of user-defined objects (if time permits) 2 MARCH, next Wednesday: Reading week - No lecture , but.
SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11& ) Lab: B43, MB321, MB536 6:00-7:30 (from ) [each student must have obtained.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
Java: How to Program Methods Summary Yingcai Xiao.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Fundamental Programming Structures in Java: Strings.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
Understanding class definitions Looking inside classes.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
COMP More About Classes Yi Hong May 22, 2015.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
SOFTWARE AND PROGRAMMING 1 Lecture: Gor B4 7:40-9:00 (from ) Lab: SH131, BBK536 6:00-7:30 (from ) [each student must have obtained access.
NSIT,Jetalpur CORE JAVA CONCEPTS SURABHI MISHRA (LCE)NSIT.
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.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.
Chapter 8: Arrays.
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 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
 2005 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
SOFTWARE AND PROGRAMMING 1 Lecture 7/5/8: Review of concepts involved in lectures and exam Lecture 14/5/8: Review of questions in previous exam papers.
SOFTWARE AND PROGRAMMING 1 Lecture 2, 2011 Instructor: Prof. Boris Mirkin DCSIS, room 744, tel Labs: from 26/1,
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
F27SA1 Software Development 1 3. Java Programming 2 Greg Michaelson.
SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: Ms Mihaela Cocea (from ) Room London Knowledge Lab Emerald.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Procedural programming in Java Methods, parameters and return values.
Chapter 4: Control Structures II
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 Programming Week 2 2 Inheritance Basic Java Language Section.
August 6, 2009 Data Types, Variables, and Arrays.
SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11& ) Lab: B43, MB321, MB536 6:00-7:30 (from ) [each student must have obtained.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: (from ) Ms Mihaela Cocea Room London Knowledge Lab Emerald.
SEEM Java – Basic Introduction, Classes and Objects.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
1 Lecture 16/2/11: Contents Local variable Array: the concept Working with an array An advert: Reading week 2 March. No lecture. All are welcome to room.
1 Lecture 9/3/11: Contents Array of user-defined objects 2D array.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Methods main concepts – method call – object 's methods – actual parameters – method declaration – formal parameters – return value other concepts – method.
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
SOFTWARE AND PROGRAMMING 1 Lecture 2, 2010 Labs start : DCSIS room 131 LAB SH room B29 Lecture EACH student must have obtained.
SOFTWARE AND PROGRAMMING 1 Advert : NO TEST1 on 7/02: TEST1 will be 14/02 Lab: SH131, BBK536 6:00-7:30 (from ) [each student must have obtained.
Information and Computer Sciences University of Hawaii, Manoa
Topic: Classes and Objects
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Methods Chapter 6.
User input We’ve seen how to use the standard output buffer
In this class, we will cover:
Presentation transcript:

SOFTWARE AND PROGRAMMING 1 Revision Lecture 11/5/2011: Review of concepts involved in lectures and exam Review of questions in previous exam papers (they are posted on SP1 site, for example, - see in menu on the left) PLEASE BRING YOUR QUESTIONS on the exam questions !!! Will try to address them all

2 Fundamental concepts How a Java program works Class; object; instance Method; constructor Parameter Variable (local, static, instance) Expression Control structures: looping, branching Input/output Data type, including that user-defined Array, 2D array

3 Objects and classes Classes: program templates –represent all objects of a kind (example: “student”) Object = instance –A template copy to represent a specific element of the class (“an individual student”) –Instances are created with the so-called constructors, explicitly in JDK or somewhat easier in BlueJ

4 Variables, methods and parameters classes contain data stored in the so- called variables and operations which can be invoked (they are called methods in Java) methods may have inputs (they are called parameters in Java) to get additional data needed to get them executed

5 Structure of a method modifiers return-type name ( parameter-list ) { statements; return variable/expression; //if return type is not void } Modifiers: –static - method/variable that belongs to class as whole and is shared by all –public - method/variable that is accessible from anywhere –private - method/variable that is accessible from only within the class Output’s typeInputs

6 Constructor Constructor is a special method that –Has the same name as the class –No return type (nor “return”) –Is called with modifier “new” to reserve a memory space for an object of class type (an instance) List of parameters, as well as the block, can be user defined The constructor with no parameters is available by default (like Const(){ }; )

7 Assigning values Values are stored into fields (and other variables) via assignment statements: –variable = expression; –price = ticketCost; The value on the right is assigned to a variable on the left. A variable stores a single value, so any previous value is lost.

8 Variable It provides for multiple uses of the same program A variable is a name for a location in memory that can hold data. Variables are declared and/or initialised A variable declaration includes the following: –A data type that identifies the type of data that is stored in the variable –An identifier that is the variable’s name –An optional assigned initial value

9 Scope of a variable: - The range of statements that can access the variable. It stretches from the declaration point to the end of the block containing the declaration Q: WHAT is BLOCK ? (part within curly braces{…} ) Q: WHAT is DECLARATION? (type name ; 3-part command)

10 Type casting The unifying type can be overridden by explicitly stating a type cast: Place the desired type result in parentheses followed by the variable or constant to be cast (int) 6.0+7=13 Example: int bankbalance=931786; float weeklybudget = (float) bankbalance /4;

11 Static and instance variables Static variable:belongs to its class, and it is shared by all class instances, with the same value Instance variable:a class variable without the “static” modifier, is shared by all class instances, but its values can differ in different instances Local variable: is created within a method or instance in a { } block. Its scope is limited within the block.

12 Loop for for(int var=1;var<=st;var++) % no ‘;’ here!!! { do operation depending on var } var++ is var=var+1, not var=var+2; Two types of parentheses: (loop specified) and {body to do} The expression in () consists of three items in this order: –initialising the counting variable once, –variable update, and –stop-condition First, –var is intialised, –stop-condition is tested; if true, block {} is executed, if no, the program proceeds further on, after the block { } –control returns to ( ) After control returns to ( ), –var is updated; –stop-condition is checked; if true, block {} is executed, then control returns to ( ), if no, the program proceeds further on, after the block { }

13 Loop while for(init; test; update){ statements } All three in the parentheses refer to a counter that is initialised, updated and tested over reaching the pre-specified threshold Structure of while loop, less rigid – init, test and update are not necessarily based on counter: init; while(test){ statements; update } Similar elements: ( ), { }, initialisation, test condition (not necessarily involving the counter!), and update

14 Double loop class AddTable{ public static void main(String[ ] args){ int sum; for (int ite1=1;ite1<3; ite1++) { //loop1 for (int ite2=1;ite2<5; ite2++) { //loop2 sum=ite1+ite2; System.out.print(sum +" ");} //loop2 System.out.println();} //loop1 } //method main ends } //class ends

15 Java branching structure : if( ) … else if( ) … else if( ) … else if(BooleanExpr1) Statement1; (e.g. Tax=2;) else if(BooleanExpr2) Statement2; (e.g. Tax=18;) else Statement3; (e.g. Tax=7;) Note: No (Boolean Expression) at else

16 Input/Output TextIO class TextIO.java, added to the directory that contains your class, eases input of data from the keyboard To input an integer: int UsInput = TextIO.getInt(); Computer will wait for the user to type in an integer value to UsInput.

17 Input with Scanner class import java.util.* class PrintDot{ int num=0; public static void main(String[ ] args){ Scanner scap = new Scanner(System.in); System.out.println(“How many dots to print? “); num=scap.nextInt(); for (ik=0; ik<num; ik++) System.out.print(‘.’); System.out.println(); } //end of main//end } //end of class//end

18 Strings(1) Declaring a String Object String variable An object of the class String – The class String is defined in java.lang.String and is automatically imported into every program Create a String object by using the keyword new and the String constructor method String aGreeting = new String(“Hello”); or String aGreeting = “Hello”;

19 Strings(2) Comparing String Values Strings are never actually changed; instead new Strings are created and String variables hold the new addresses; A part of the Java system called the garbage collector will discard the unused strings It is impossible to make a simple comparison of Strings; thus a number of methods are: – equals() method i f s1 and s2 are declared and initialised as String: s1.equals(s2) true if s1 and s2 are exactly the same sequences of characters NEVER s1==s2 !!! This is wrong, == applies to numbers only.

20 Class Math Math.pi  =3.14…,the ratio of the circumference to its diameter Math.abs(a) a if a >= 0, or -a if a < 0 Math.log(a) the natural logarithm (base e) of a Math.sqrt(a) square root of a Math.pow(a,b)a b, if b is integer then a b =a  a  …  a (b times) Math.random() pseudorandom number: double within interval [0.0, 1.0) (zero included, unity not) How to use it to generate a random integer between 1 and 6 (inclusive), to mimic casting a dice? double aa=Math.random(); //aa, a real number between 0 and 1 int an= 6*aa; //a real number between 0 and 6 int rand=(int) an; // whole number between 0 and 5 int randw=rand+1; // whole number betw. 1 and 6 Casting in Java: converting from higher number types to lower types int randw= (int) (6*Math.random()+1); How to generate a random integer between 10 and 20 inclusive? Answer: int rdt= (int) (11*Math.random()+10);

21 Math.random() pseudorandom number: double within interval [0.0, 1.0) (zero included, unity not) How to use it to generate a random integer between 1 and 6 (inclusive), to imitate casting a dice?

22 Array (1) Array is an indexed list of elements of the same type A string array nam[ ] : contains both entries and index. String nam[] ={“John”,“Paul”,“George”,“Ringo”}; Index is Length (the number of entries) is 4 An integer array age[ ]: int age[ ]= {23, 32, 19, 30, 25, 25, 23, 30}; Index is Length is 8

23 Array (2) bmi[ ]=new double[5]; for (int I = 0; I < 5; I + +) bmi[I]=weight[I] / (height[I]  height[I]); If we do not know the length of student arrays or it is variable: bmi[ ]=new double[height.length]; for (int I = 0; I < height.length; I + +) bmi[I]=weight[I] / (height[I]  height[I]);

24 User defined type Follows classes: - Oblong and OblongTester, sections 6.3 and 7.2, Charatan and Kans, “Java in two semesters” - Counter and CounterTest, sections , Pohl and McDowell, “Java by dissection” - Employee and TwoEmployee, p , Ch.3, Farrell, “Java programming”

25 2D arrays Summary sales: int sum =0; for (int shop = 0; shop < 4; shop ++) for(int day = 0; day < 7; day ++) sum = sum + sales[shop][day]; As a method: public int sum( int[][] a) { int total = 0; for (int row = 0; row < a.length; row ++) for( int col = 0; col < a[0].length; col ++) total = total + a [row][col]; return total; }

26 Array of user-defined type(1) The setting: We have a number of applicants for whom we have separate, but matching, lists of names and id’s organised as arrays. We would like to develop a new type for an Applicant to hold all individual data of the applicant, in this case just id and name, but it can have as many attributes as it takes. With this new type, we would like to organise a list of applicants as an array of this type

27 Array of user-defined type(2) To develop an array of applicants, we need –A named class, say Appl, with variables declared to hold all individual applicant data (A); –A constructor in this class that would take values from the arrays holding id and name information (B); –Representation of the id and name arrays (C); –Generation of an instance of array of new type, Appl (D); –Feeding the Id’s and names into the Appl array (E); We can show that this does work by printing out data of all the entries in the Appl array.

28 Array of user-defined type(3) class Appl{ public int ids; public String nms; public Appl(int iden, String nnn){ ids=iden; nms=nnn;} static int[] iden(){ int ii[]={12, 15, 22, 18, 11}; return ii;} static String[] namen(){ String jj[]={"Aa", "Bb", "Cc", "Dd", "Ee"}; return jj;}

29 Array of user-defined type(4) public static void main(String[] args){ int id[]=iden(); String name[]=namen(); Appl[] many=new Appl[id.length]; for(int i=0;i<id.length;i++) many[i]=new Appl(id[i],name[i]); //many – array of Appl type objects. Check: for(int i=0;i<name.length;i++){ System.out.println(i +"th applicant data:"); System.out.println("Id: "+many[i].ids); System.out.println("Name: "+many[i].nms); System.out.println(); } }