Java Review Rem Collier. A Statement I have been asked to do these Lectures at YOUR request. They are to help YOU with any Java question that you have.

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
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.
Java review and more. Class Header  Public class Welcome  Case sensitive  Body of the class must be enclosed by braces.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
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.
Some basic I/O.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
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.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
CSC3170 Introduction to Database Systems
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
1 Course Lectures Available on line:
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
SOFTWARE TECHNOLOGY - I CONSTANTS VARIABLES DATA TYPES.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
The Java Programming Language
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
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.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Introduction to Java Java Translation Program Structure
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Objects and Classes Mostafa Abdallah
Chapter 5 Programming with Objects and Classes OO Programming Concepts OO Programming Concepts Declaring and Creating Objects Declaring and Creating Objects.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
1 Chapter 6 Programming with Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
A High Flying Overview CS139 – Fall 2006 How far we have come.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
OOP Basics Classes & Methods (c) IDMS/SQL News
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
I/O in java and Revision. 2 I/O in Java Many packages and libraries associated with Java provide sophisticated ways to input and output information, e.g.:
IAS 1313: OBJECT ORIENTED PROGRAMMING Week 3: Data Type, Control Structure and Array Prepared by: Mrs Sivabalan1.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Information and Computer Sciences University of Hawaii, Manoa
Java Review Rem Collier.
Objects, Classes, Program Constructs
I/O Basics.
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Chap 2. Identifiers, Keywords, and Types
Chapter 6 Objects and Classes
LCC 6310 Computation as an Expressive Medium
Presentation transcript:

Java Review Rem Collier

A Statement I have been asked to do these Lectures at YOUR request. They are to help YOU with any Java question that you have. –E.g. How to do File Input / Output How to do User Input How to do Searching / Sorting To succeed, they need YOUR input. –Tell me what problems you are having, and I will try to help you!

Programming in Java In Java, a program generally has the following structure: –Declaring variables/ initializations E.g. int balance; –Processing reading inputs process inputs show output –Exit the program

Data Types – Variables & Initializations String for strings of letters e.g. String LastName = “Kim”; char for characters e.g. char alphabet = ‘A’; byte, short, int, and long for integer numbers e.g. int number = 3; float & double for real numbers e.g. double pi = boolean for logical e.g. boolean check = true;

Expressions and Operators Expressions: ( ), *,/, +, - Operators: &&forAND || for OR ! for NOT == for equal != for NOT equal

Selection Statements if statementex) if (A>B) { System.out.println(“A>B”); } if…else statementex) if (A>B) { System.out.println(“A>B”); } else { System.out.println(“A<=B”); } switch Statement ex) switch (A) { case 1: { System.out.println(“A=1”); break; } case 2: { System.out.println(“A=2”); break; } … default: { System.out.println(“A Undefined”); } }

Repetitions(while, do while, and for) An example adding all numbers between 1 to 100 Using While: // Variable Declaration & Initialization int sum = 0; int count = 0; // Processing while (count <= 1000) { sum = sum + count; count = count +1; //same as count++ } // Output System.out.println(“Sum: “ + sum);

Repetitions(while, do while, and for) Using do-while: // Variable Declaration & Initialization int sum =0; int count =0; // Processing do { sum = sum + count; count = count +1; //same as count++ } while (count <=1000); Using for: // Variable Declaration & Initialization int sum =0; // Processing for (int count =0; count <= 100; count++) { sum = sum +count; }

Introducing Methods Method Structure A method is a collection of statements that are grouped together to perform an operation.

Declaring Methods /** * This method returns the maximum of two numbers num1 the first number num2 the second number either num1 or num2 */ int max(int num1, int num2) { if (num1 > num2) { return num1; } else { return num2; }

Passing Parameters /** * This method prints a message a specified number * of times. message the message to be printed n the number of times the message is to be * printed */ void nPrintln(String message, int n) { for (int i=0; i<n; i++) { System.out.println(message); }

The main method One of these methods is required for every program you write. –If your program does not have one, then you cannot run it. The main method has a very specific syntax: public static void main(String[] args) { // Your code goes here! } For example: public static void main(String[] args) { System.out.println(“Hello World!”); }

An Example Program class MyProgram { /** * This method prints a message a specified number * of times. message the message to be printed n the number of times the message is to be * printed */ void nPrintln(String message, int n) { for (int i=0; i<n; i++) { System.out.println(message); } } public static void main(String[] args) { nPrintln(“Hello World!”, 10); } }

Your Turn… How do you write a program that prints: “I am the coolest programmer” twenty times on the screen

Declaring Array Variables Option A: –Syntax: datatype[] arrayname; –Example: int[] myList; Option B: –Syntax: datatype arrayname[]; –E xample: int myList[];

Creating Arrays –Syntax: arrayName = new datatype[arraySize]; –Example: myList = new int[10];

Declaring and Creating in One Step Option A: –Syntax : datatype[] arrayname = new datatype[arraySize]; –Example : double[] myList = new double[10]; Option B: –Syntax: datatype arrayname[] = new datatype[arraySize]; –Example : double myList[] = new double[10];

Initializing Arrays Using a loop: for (int i = 0; i < myList.length; i++) { myList[i] = (double)i; } Declaring, creating, and initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5};

Searching Arrays /** * This method searches a specified array for a value. array the array to be searched value the value to be searched for true if the value is in the array, false * otherwise */ boolean contains(double[] array, double value) { boolean found = false; int index = 0; while ((index <= array.length) && !found) { if (array[index] == value) { found = true; } return found; }

Again, your turn… How do you write a program that searches through the following list of numbers: 23.2, 12.1, 34.3, 6.8, 4.0, 34.5, 22.7, 313.6, 12.5, 81.2, 56.3, 363.3, 135.5, 176.4, 5.3, 44.2, 76.5, 29.1, 2.7, 24.5, -42.0, 23.19, , 0.0, 9.9, 564.3, 235.0, 83.16, 43.38, 1.2, to see whether 2.7 is in the list. Now write a program to check whether 8.1 is in the same list.

Object-Oriented Programming in Java Java programs are formed from a set of classes. –A class is a container for code. –Whenever you create a program, you write your code inside one or more classes. Some of the classes you will use in your programs are pre- written and are provided as part of the Java Application Programming Interfaces (APIs). –See Other classes you must write yourself.

Object-Oriented Programming in Java When we run a Java Program, we may create objects. Objects are instances of classes. –Classes describes a general set of features. –Objects specify concrete values for those features. For example: –Let us start with a general description of a car: A Car has four wheels, an engine, a chassis, a colour, some doors … –The next two descriptions refer to particular cars. My car is brown and has a 2 litre engine, a Saab chassis, and five doors. Peter has a yellow car with a 1.4 litre engine, a VW Polo chassis, and three doors.

How does this relate to Java? The general description of a Car is like a class in Java – a general description of what constitutes a car. Both my car and Peter’s car are described in terms of the general description of a car (i.e. the colour, engine size, chassis type, number of doors). These particular cars are like objects in Java - a concrete instance of the general description of a Car. Note: The number of wheels is the same for all cars. –We call things that are the same for all cars constants.

Data Attributes Methods, and Messages Classes contain two types of feature: –Data attributes describe the information that a class contains (for example the colour of a car, the type of chassis, etc.) –Methods describe operations that can be performed by instances (objects) of the class (for example, a Bank Account class may include methods to withdraw or deposit cash). To get an object to perform a method we send a message: –This message must be sent to that object identifying the method to be performed. –This message should also include any data (parameters) required by the method.

Class Declaration class Circle { public double radius = 1.0; /** * This method calculates the area of the circle. the area of the circle */ public double findArea() { return radius*radius* ; } Data attribute Method

Declaring Object Variables Syntax: ClassName objectName; Example: Circle myCircle;

Creating Objects Syntax: objectName = new ClassName(); Example: myCircle = new Circle();

Declaring/Creating Objects in a Single Step Syntax: ClassName objectName = new ClassName(); Example: Circle myCircle = new Circle();

Accessing Objects Referencing the object’s data: –Syntax: objectName.data –Example: myCircle.radius Referencing the object’s method (sending a message): –Syntax: objectName.method(…) –Example: myCircle.findArea()

Constructors Constructors are special methods that are called upon creation of an object. –Their purpose is to initialise objects as they are created. Syntax: ClassName(…) { // Initialisation code goes here! } Example: Circle(double r) { radius = r; }

Constructors Example (cont): Circle() { radius = 1.0; } We can specify which constructor to use when we create a new object. Example: myCircle = new Circle(5.0);

Modifiers By default, the class, variable, or data can be accessed by any class in the same package. public The class, data, or method is visible to any class in any package. private The data or methods can be accessed only by the declaring class.

An Example Program class TestCircle { public static void main(String[] args) { Circle myCircle = new Circle(); System.out.println("The area of the circle of radius " + myCircle.radius + " is " + myCircle.findArea()); } class Circle { double radius = 1.0; /** * This method calculates the area of the circle. the area of the circle */ double findArea() { return radius*radius* ; }

Packages There are thousands (if not tens of thousands) of Java classes. –Finding the right one can be difficult (i.e. I want a class that does file input…) –Finding a meaningful name can be difficult (think of yahoo usernames!) Packages are used to organise Java classes. –Packages are like domain names – they are hierarchical (e.g. packages can have sub-packages, which can have sub-packages, and so on…). –There are five basic Java packages: java.langClasses that are part of the basic language (e.g. Strings) java.ioClasses that do input and output java.netClasses for networking java.awtClasses for creating Graphical Interfaces java.utilGeneral Utility Classes –So, if I want a class that does file input, I look in the input/output (io) package!

Referencing Classes in Different Packages If we want to use a class that is in a package (with the exception of those in the java.lang package), we need to declare our intention at the top of the program. We do this with an import statement –For example: import java.io.PrintStream; –If we want to use multiple classes from a single package we can use the following statement: import java.io.*; This means “any class”

Some Useful Java Classes One of the most useful sets of Java classes are the input/output (io) classes. –These classes are located in the java.io package and are part of the default Java API. –These classes allow programs to perform input/output in a variety of ways. There are many different types of io class. –You are not expected to know them all intimately, but you should know how to do a few basic things with them (e.g. User input, File input/output, etc.)

System.out You have already used an io class implicitly when you write information to the screen. System.out refers to a data attribute of the System class. –This attribute is an instance of the class PrintStream. –This class is used for output only. The PrintStream class includes a method, println, that prints a string to the specified output. –We don’t know where this output comes from! –We don’t need to know – we just need to know where it goes to (i.e. the screen).

Handling User Input To get input from the user, we use another data attribute of the System class: System.in This attribute is an instance of the InputStream class. –The InputStream class is not easy to use (it works only with bytes). –To make things easier, we can wrap the input stream in other io classes. In particular, we use two classes: –InputStreamReader. This class converts the byte stream into a character stream (this is much more useful – honestly!). –BufferedReader. This class buffers data from the enwrapped stream, allowing smoother reading of the stream (it doesn’t wait for the program to ask for the next character in the stream).

Handling User Input To wrap an io object, we create a new io object, passing the old io object into the constructor. –For example, to wrap System.in within an InputStreamReader, we write: new InputStreamReader(System.in) To use the BufferedReader (which, remember, is an optimisation), we wrap the InputStreamReader object we created above. –For example: new BufferedReader(new InputStreamReader(System.in)) Once we have a BufferedReader, we can use a nice method it provides called readLine() which reads a line of text! –This makes life much easier!

Handling User Input Now that we have a way of reading a line of text from the System input stream (i.e. the keyboard), how do we use it? public String readString() { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String line = null; try { line = in.readLine(); while (line == null) { line = in.readLine(); } } catch (IOException ie) { System.out.println(“The following problem occurred “ + “when reading input: “ + ie); } return line; }

More Help - Books “Java How to Program by Deitel & Deitel” Introduction to Java Programming by Daniel Liang An Introduction to Java programming with Java by Thomas Wu Easier books can be found in course.com

More Help - Websites –Loads of free tutorials –Java Documentation for all Java classes –Free registration –Tech support, training, articles, resources, links –Java directory page –Thousands of applets and resources – –All-around Java resource –References, games, downloads, talk to experts...