CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.

Slides:



Advertisements
Similar presentations
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Advertisements

Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
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.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing.
Static Class Members Wrapper Classes Autoboxing Unboxing.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: IO *Standard Output *Formatting Decimal.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
1 CSE 142 Lecture Notes Interactive Programs with Scanner Chapter 4 Suggested reading: Suggested self-checks: Section 4.10 #1-4 These lecture.
Using Java's Math & Scanner class. Java's Mathematical functions (methods) (1)
Introduction to Java Java SE 8 for Programmers Paul Deitel Harvey Deitel Deitel Developer Series 2014.
Chapter 2 Section 2.2 Console Input Using The Scanner CLASS Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Using Classes BCIS 3680 Enterprise Programming. Overview 2  Using Classes  Using premade classes for input and output  Display output: System, JOptionPane.
Chapter 2 Console Input and Output Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Sahar Mosleh California State University San MarcosPage 1 System.out.println for console output System.out is an object that is part of the Java language.
Slides prepared by Rose Williams, Binghamton University Chapter 2 Console Input and Output.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
Java - Classes JPatterson. What is a class? public class _Alpha { public static void main(String [] args) { } You have been using classes all year – you.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
Using Classes and Objects Chapters 3 Creating Objects – Section 3.1 The String Class – Section 3.2 The Scanner Class – Section 2.6 Instructor: Scott Kristjanson.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
Variables and Types Java Part 3. Class Fields  Aka member variable, field variable, instance variable, class variable.  These are the descriptors of.
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Chapter 2 Console Input and Output Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Primitive Data Types int is a primitive data type A primitive data type is one that stores only a single piece of data. TypeStorageDescription int 4 bytes+ve.
Copyright © Curt Hill Simple I/O Input and Output using the System and Scanner Objects.
Variables and Constants Chapter 4 Review. Declaring Variables A variable is a name for a value stored in memory. Variables and constants are used in programs.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Scanner Review Java Foundations: Introduction to Programming and Data Structures.
CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 3 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer 1.
Interactive Programs Programs that get input from the user 1 In PowerPoint, click on the speaker icon then click the "Play" button to hear the narration.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 6_1 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Input/Output.
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Yanal Alahmad Java Workshop Yanal Alahmad
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
Chapter 3 Assignment Statement
I/O Basics.
INPUT STATEMENTS GC 201.
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Introduction to Classes and Methods
MSIS 655 Advanced Business Applications Programming
OBJECT ORIENTED PROGRAMMING I LECTURE 6 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Presentation transcript:

CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis 1

REVIEW MODIFIERS – Keyword static used in Method signature – Keyword static used in variable declaration – public, private, protected. Receiving Input Command Line Receiving Input via the Scanner – Keyboard. – Reading text file. Wrapper Classes. 2

Modifiers Modifiers are keywords that set visibility and or rights on members of a class. Some of the modifier keywords that we should be familiar from CS115 are: static public private – Some others that we will use in CS116 are: final abstract protected transient 3

The Keyword Static The keyword static can be applied to methods and also instance variables of a class. Applied to methods: Methods that have been declared static can be called by using the name of the class they belong to. Therefore we do not need to instantiate an object of that class in order to invoke its static methods. An example is the methods of the library class Math. If we look at the API all the methods of this class have the word static in their signature. That means that we can call method pow, as an example, by : double a= Math.pow(a, b); 4

Static applied to methods We have also seen static used in classes where there is a main method in addition to other methods. Rule: – If we want to invoke, from the main method, another method of the same class (that the main method belongs to) then that method has to be declared static. There is another way to call a non static method from the main (assuming that both are in the same class) by creating an object of the same class as the main and invoking the method by using the object. 5

Static applied to methods The previous rule applies to all methods which are static in a class and not just the main method! 6

Static applied to instance variables (attributes) of a class If an instance variable (field) is declared static then its value can be seen by all objects of the same class. i.e static int id=0; id++; the ++ after the identifier id means that the its value is incremented by one every time we execute the line of code id++ 7

Static Variables Thus if id=0; id++ causes a new value of id=1 calling id++ again causes a new value of id=2 And so on. If id is also declared static then every time we increment the value of id every object of the class sees the new value. 8

Static Variables Suppose that id is a static variable and that it belongs to class Student (template class). Suppose that in StudentClient we have instantiated the following objects: Student student1=new Student(); Student student2=new Student(); Student student3=new Student(); If the value of id=3 then all the student objects share the same value for id (that is 3). 9

Example of static variable public class Student { static int id=0; int currentID=0; String studentName=" "; public Student() { id++; currentID=id; studentName=“John Doe”; } public Student ( String sn) { Studentname=sn; } followed by accessor /mutator/toString() methods 10

Example of static variable We notice that in class Student – Every time the constructor is called the value of id is advanced by one with respect to its previous value. – Once the value of id is advanced its new value is assigned to a non static variable : currentID. – That is because the non static variables have values that are dedicated to each object and their values are not shared by all objects of the class. 11

Example of static variable public class StudentClient { public static void main(String [] args) { Student st1=new Student() // value of id=1 now for st1. Every time we call the constructor of the class Student id advances by 1 //Also,The value of id is passed to currentID =1 Student st2=new Student() // value of id=2 now for both st1 and st2, // currentID=1 for st1 but //currentID=2 for st2. Student st3=new Student() // value of id=3 for st1, st2, st3 // currentID=1 for st1 //currentID=2 for st2 //currentID=3 for st3 12

Example of static variable Therefore we could use the static variable id to track how many objects we have created for that class (i.e. the Student class). Notice that the new value of the static variable id is shared amongst all objects of the class. 13

Example of static variable The value of id is the same for each object student3 is created: 14 Student 1 id-=3 currentID=1 Student 2 Student 3 id-=3 currentID=2currentID=3 Since id is static all 3 objects see its new value when it changes (if a 4 th Student was to be created all 4 objects will have id=4). The variable currentID is not static therfore each object sees the value of currentID assigned for that object alone.

public and private Modifiers Keyword pubic can be applied to java elements: – Data fields (variables), methods, constructors an outer class, an inner class. – Rule: An element declared public is visible from another class. Keyword private can be applied to Java elements: – Data fields (variables), methods, constructors an inner class. Can not be applied to an outer class. – Rule: An element declared private is not visible from another class. Only to members of its own class. 15

RECEIVING INPUT Different ways to read input into our programs: – User provides input via Command Line when the java interpreter is called. – Read user provided input via the keyboard using the Scanner object during execution (interpretation) of the program (you should had learnt this in CS115). – Read a text file using the Scanner object (you should had learnt this in CS115). – We will learn later on in this course how to read different types of data files using streams (including writing new data into those files). 16

Command Line Input Command line implies that: – A DOS window is opened (cmd command from start menu or assecories->command prompt) – The command line path is pointingt o the path where the java program file (tehone with the main method) is located. 17

Command Line Input We can obtain input data for a program from the DOS window when we use the interpret command. This is called “command line “ input. i.e some path…………>java StudentClient arg1 arg2 arg3 Where arg1 arg2 arg3 are the 3 pieces of data (in this example) that will be read as individual Strings by the main method of the program. 18

Command Line Input This approach is only good as long as the class has a main method. The String array argument of the main method captures the values entered by the user. There is no pre determined number of data values that the user can enter from the command line. 19

Command Line Input Suppose that we have the class StudentClient and that it expects 3 inputs (called arguments) from command line: >java StudentClient arg1 arg 2 arg3 public class Student public static void main(String [] args) { String a=args[0]; String b=args[1]; String c=args[2]; 20

Command Line Input The Strings a, b, c now have the values that the user entered: i.e. >java StudentClient Joe, 20, 4.65 thus: a has the value Joe as a String b has the value 20 as a String c has the value 4.65 as a String 21

Command Line Input If we wanted to do arithmetic operations with the String versions of values 20 and 4.65 then we have to parse the String verions by using the appropriate wrapper class i.e int x= Integer.parseInt(b); results in the int version of the String 20 (int x=20) double y=Double.parseDouble( c ); results in the double version of the String 4.65 (double y=4.65) 22

Input Using the Scanner Class Sometimes we need to be able to capture input from the user while the program is running.. One way of providing input to the program is via the keyboard. A DOS window is required. Program should be interpreted from command line. The Scanner library class provides the functionality to allow us to capture keyboard input (and also read input from a file—we will cover the file reading later) Scanner class is part of the Library package java.util – Therefore we have to import the Scanner class 23

Receiving Input from the User Using the Scanner library class. Sometimes we need to prompt the user during the execution of the program so that input is provided after a specific set of instructions has been executed. The previous technique of making the input part of the command to start the execution WILL NOT work then. We can provide this functionality by using the Scanner library class. The user can be prompted to enter data, after the program starts execution, via the keyboard. The Scanner object will read the characters typed on the keyboard. 24

Input Using the Scanner Class Scanner class provides methods for reading byte, short, int, long, float, double, and String data types from the Java console (keyboard) and other sources (like a file). Scanner parses (separates) input into sequences of characters called tokens. By default, tokens are separated by standard white space characters (tab, space, newline, etc.) i.e in the String “My name is Joe” there are 4 tokens. The first token is the substring “My” and so on. 25

A Scanner Constructor Scanner( InputStream source ) creates a Scanner object for reading from source. If source is System.in, this instantiates a Scanner object for reading from the Java console (keyboard). (System.in is the keyboard) Example: Scanner scan = new Scanner( System.in ); scan then is the object that we are going to use to read characters from the keyboard if System.in has been passed to the constructor of the Scanner class. The Scanner class has methods that help us capture the user ‘s input (as an example from the keyboard or a file). 26

Scanner class methods Some of the methods are listed in the next slide. Connect to the link for the java API and study the methods of Scanner class. 27

Scanner next… Methods Return typeMethod name and argument list dataTypenextDataType( ) returns the next token in the input stream as a dataType. dataType can be byte, int, short, long, float, double, or boolean i.e nextDouble() or nextInt() Stringnext( ) returns the next token in the input stream as a String StringnextLine( ) returns the remainder of the line as a String 28

Prompting the User The next… methods do not prompt the user for an input value Use System.out.print to print the prompt, then call the next… method Example: 1. Scanner scan = new Scanner( System.in ); 2. System.out.print( "Enter your age > " ); 3. int age = scan.nextInt( ); In this example the user program stops execution after statement 2 is executed. The program waits for the user to type something (a number in this case) 29

Prompting the User On the DOS window we will see: C:\Users\George>java MyProgram Please enter your age > _ After the user enters a number (let us say that the user typed the number 19) and presses the Enter key, the program resumes execution and line 3 is executed. Line 3 reads what the user typed (19) as a String and at the same time converts it into an int data type. It assigns that data type (stores in memory) to the identifier age in this example. From there on the program continues with the execution of other instructions. It is possible that we may want to stop the program further down again and ask the user to enter another input. 30

Scanner Example Suppose that we want to read a String that a user of our program enters on the keyboard: import java.util.Scanner; class UsingScanner { public static void main(String[] args) { Scanner scan =new Scanner(System.in); System.out.println("Enter a decimal number"); String a=scan.next(); double d=Double.parseDouble(a); System.out.println(d); } 31

Scanner Example Interpreting this program has the following outcome: C:\CS115\Myexamples\ScannerExamples>java UsingScanner Enter a decimal number The number you entered is:12.34 Notice that after the statement “Enter a decimal number” is displayed, the program waits for the user to enter something on the keyboard. Notice that the next action is for the user to type on the keyboard. The program then prints the last statement “The number you entered is:12.34” 32

Scanner Example In the program the line: String a=scan.next(); captures whatever the user typed as a String data type (even if the user typed a number!) Our program converts the data type String represented by the identifier a to a double data type via the line: double d=Double.parseDouble(a); 33

Wrapper Classes We can always convert a String to a primitive data type using classes called “Wrapper classes”. In this example the class Double is the Wrapper class (notice that it is written with a capital D to differentiate it from the primitive data type double written with a lower case d). Its job is to convert a String to a double data type by invoking the method parseDouble that takes a primitive data type double as argument. 34

The Wrapper Classes “Wrap” the value of a primitive data type into an object Useful when methods require an object argument Also useful for converting Strings to an int or double 35

Wrapper Classes Primitive Data TypeWrapper Class doubleDouble floatFloat longLong intInteger shortShort byteByte charCharacter booleanBoolean 36

Back to Scanner We can capture the input from the keyboard directly as a numeric primitive data type instead of capturing it as a String first and then converting it (parsing it) to the particular numeric data type: i.e. Scanner scan =new Scanner(System.in); System.out.println("Enter a decimal number"); double a=scan.nextDouble(); 37

Using the nextDouble method with Scanner object import java.util.Scanner; class UsingScannerDouble { public static void main(String[] args) { Scanner scan =new Scanner(System.in); System.out.println("Enter a decimal number"); double d=scan.nextDouble(); System.out.println("The number you entered is:"+d); } Output: Enter a decimal numbner The number you entered is:

Text Reading Continue reviewing Chapter 7. 39