Review Java.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Types, Variables and Operators Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2013.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
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.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
JavaScript, Third Edition
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Basic Elements of C++ Chapter 2.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Fundamental concepts in Java. Lesson plan Variable declaration, assign statement & practice Design document & practice.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
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 Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
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.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Copyright Curt Hill Variables What are they? Why do we need them?
Java Programming, Second Edition Chapter Two Using Data Within a Program.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
By Mr. Muhammad Pervez Akhtar
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
A Sample Program public class Hello { public static void main(String[] args) { System.out.println( " Hello, world! " ); }
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
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.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
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.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Basic Elements of C++.
Object Oriented Programming
Multiple variables can be created in one declaration
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Basic Elements of C++ Chapter 2.
Type Conversion, Constants, and the String Object
Starting JavaProgramming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 2 Edited by JJ Shepherd
Chapter 2: Basic Elements of Java
Fundamentals 2.
Expressions and Assignment
elementary programming
Introduction to Java Applications
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Classes, Objects and Methods
Chap 2. Identifiers, Keywords, and Types
Introduction to Java By Prakash G Asnani
Presentation transcript:

Review Java

Objectives To understand the essentials of object- oriented programming in Java To review the primitive data types of Java, how to use the control structures of Java To learn how to use predefined classes such as Math, JOptionPane, String, StringBuffer, and StringTokenizer To review how to write and document your own Java classes Appendix A: Introduction to Java

Chapter Objectives (continued) To understand how to use arrays in Java To learn how to perform I/O in Java using simple dialog windows To learn how to perform I/O in Java using streams Appendix A: Introduction to Java

Compiling and Executing a Java Program Appendix A: Introduction to Java

Classes and Objects The class is the fundamental programming unit Every program is written as a collection of classes Class definitions are stored in separate files with the extension .java and the file name must be the same as the class name A class is a named description for a group of entities A class is a general description of a group of entities that all have the same characteristics; each entity is an object Appendix A: Introduction to Java

The Java API Java consists of small core language augmented by an extensive collection of packages Each package contains a collection of related Java classes, such as: Swing AWT util Appendix A: Introduction to Java

Review of Java fundamentals Template for Class Definition class { } Import Statements Class Comment Class Name Data Members Methods (incl. Constructor)

Primitive Data Types and Reference Variables Java distinguishes two kinds of entities Primitive types: data is stored in primitive type variables Objects: are associated with reference variables which store an object’s address Appendix A: Introduction to Java

Primitive Data Types Represent numbers, characters, and Boolean values Integers: byte, short, int, and long Real numbers: float and double Characters: char Appendix A: Introduction to Java

ASCII Encoding For example, character 'O' is 79 (row value 70 + col value 9 = 79). O 9 70 Characters can be stored in a computer memory using the ASCII encoding. The ASCII codes range from 0 to 127. The character 'A' is represented as 65, for example. The ASCII values from 0 to 32 are called nonprintable control characters. For example, ASCII code 04 eot stands for End of Transmission. We can use this character to signal the end of transmission of data when sending data over a communication line.

Variable declaration Format: <data type> <variable_name>; If more than one variable has the same data type: <data type> <name1>, <name2>..;

Assignment statement <variable name> = <expression>; Example: x =2*5+6-1;

Variable names It must be a legal identifier. It must not be a keyword, a boolean literal (true or false), or the reserved word null. It must be unique within its scope.

Variable name (cont.) Legal identifier:be composed of letters, numbers, _ and $. Identifiers may only begin with a letter, _, or $. Keyword: http://java.sun.com/docs/books/tutorial/java/ nutsandbolts/_keywords.html Java styles: Variable names begin with a lowercase letter Class names begin with an uppercase letter

Review question Which of the following is not a valid Java identifier? a. my Value b. $_AAA1 c. width d. m_x Appendix A: Introduction to Java

Review question Which of the following is not a valid Java identifier? a. my Value b. $_AAA1 c. width d. m_x Appendix A: Introduction to Java

Review question Which of the following is a correct variable declaration statement? a. int x - float y; b. int x: float y; c. int x,y; d. Long int x; Appendix A: Introduction to Java

Review question Which of the following is a correct variable declaration statement? a. int x - float y; b. int x: float y; c. int x,y; d. Long int x; Appendix A: Introduction to Java

Constant and variables Value it contains doesn’t change final int MONTHS_IN_YEAR = 12; Variables: Value it contains may vary double loanAmount; loanAmount =0; loanAmount = 1000.99;

Integer division and type casting Integer/integer = integer, 7/2 = 3 Integer/double = double, 7/2.0 = 3.5 Double/integer = double, 7.0/2 = 3.5 Type casting: a process that converts a value of one data type to another data type. Implicit casting Explicit casting

Type casting (cont.) Implicit casting: Operand is converted from a lower to a higher precision Higher precision: a data type with a larger range of values Double has a higher precision than float Int has a higher precision than short Operand: can be a constant, variable, method call or another arithmetic expression

Type casting (cont.) Explicit casting (<data type>) <expression> Example: float result; result = (float) ((3+5)/6); and result = ((float) (5+3))/6;

Type Compatibility and Conversion Widening conversion: operations involving mixed-type operands, the numeric type of the smaller range is converted to the numeric type of the larger range In an assignment operation, a numeric type of smaller range can be assigned to a numeric type of larger range Appendix A: Introduction to Java

Control Statements: Simple Choice Statement if (<boolean expression>) <block>; else if (<boolean expression>) single statement; else

Boolean expression Boolean expression: is a conditional expression that is evaluated to either true or false. Conditional expression: is a three part expression: <exp.> <relational operators> <exp.> Boolean expressions can be combined by boolean operators

Relational Operators

&& means AND || means OR ! means NOT Boolean operators && means AND || means OR ! means NOT

Pre-review question How many times the method readData() will be called in the following code segnment? int i; i = 0;   while ( i <= 4 ) { readData(); i = i + 1; } // end while 5 Appendix A: Introduction to Java

Pre-review question .          can be used to traverse a two- dimensional array. a. A do while statement. b. A for statement. c. Two nested for statements. d. Three nested for statements. Appendix A: Introduction to Java

Pre-review question .          can be used to traverse a two- dimensional array. a. A do while statement. b. A for statement. c. Two nested for statements. d. Three nested for statements. Appendix A: Introduction to Java

The While Loop while(<boolean expression>){ // Repeat multiple statements. statement 1 statement 2 statement 3 ... }

The Do-While Loop do { // Repeat multiple statements. statement 1 ... } while(<boolean expression); Note that the statements in the body of the loop are always executed at least one. Note the final semicolon, which is required.

The For-Loop Outline Commonly used with increment // Repeat multiple statements. for(initialization; condition; post-body update){ // Statements to be repeated. statement 1 statement 2 statement 3 ... } Commonly used with increment and decrement operators.

Increment and Decrement Used as a shorthand for add-one-to and subtract-one-from: value = value+1; value += 1; value++; Prefix and postfix forms: ++value; --value; value--;

Attributes (Data Member) Declaration <modifiers> <data type> <name> ; Modifiers Data Type Name private String ownerName ; Note: There’s only one modifier in this example.

Method Declaration <modifier> <return type> <method name> ( <parameters> ){ <statements> } Modifier Return Type Method Name Parameter public void setOwnerName ( String name ) { ownerName = name; } Statements

Constructor A constructor is a special method that is executed when a new instance of the class is created. public <class name> ( <parameters> ){ <statements> } Modifier Class Name Parameter public Bicycle ( ) { ownerName = “Unassigned”; } Statements

Arguments and Parameters An argument is a value we pass to a method. A parameter is a placeholder in the called method to hold the value of the passed argument. class Sample { public static void main(String[] arg) { Account acct = new Account(); . . . acct.add(400); } class Account { . . . public void add(double amt) { balance = balance + amt; } argument

Arguments and Parameters An argument is a value we pass to a method. A parameter is a placeholder in the called method to hold the value of the passed argument. class Sample { public static void main(String[] arg) { Account acct = new Account(); . . . acct.add(400); } class Account { . . . public void add(double amt) { balance = balance + amt; } parameter

Referencing and Creating Objects You can declare reference variables that reference objects of specified types Two reference variables can reference the same object The new operator creates an instance of a class A constructor executes when a new object is created Appendix A: Introduction to Java

Methods Programmers use methods to define a group of statements that perform a particular operation The modifier static indicates a static or class method A method that is not static is an instance method All method arguments are call-by-value If the argument is a primitive type, its value is passed to the method The method can’t modify the argument value and have the modification remain after return from the method Appendix A: Introduction to Java

Methods (continued) If the argument is of a class type, the value of the reference variable is passed, not the value of the object itself Reference variables point to the object and any modification to the object will remain after return from the method Appendix A: Introduction to Java

Review question Consider the following Java statements: int x = 9; double y = 5.3; result = calculateValue( x, y );   Which of the following statements is false? a. A method is called with its name and arguments inside parentheses. b. x and y are parameters. c. Copies of x and y are passed to the method calculateValue(). d. x and y are arguments Appendix A: Introduction to Java

Review question Consider the following Java statements: int x = 9; double y = 5.3; result = calculateValue( x, y );   Which of the following statements is false? a. A method is called with its name and arguments inside parentheses. b. x and y are parameters. c. Copies of x and y are passed to the method calculateValue(). d. x and y are arguments Appendix A: Introduction to Java

The Class Math Provides a collection of methods that are useful for performing common mathematical operations Appendix A: Introduction to Java

Escape Sequences An escape sequence is a sequence of two characters beginning with the character \ Represents characters or symbols that have a special meaning in Java Appendix A: Introduction to Java

The String Class String class defines a data type that is used to store a sequence of characters You cannot modify a String object If you attempt to do so, Java will create a new object that contains the modified character sequence Appendix A: Introduction to Java

Comparing Objects You can’t use the relational operators or equality operators to compare the values stored in strings or other objects Appendix A: Introduction to Java

Examples We can do this because String objects are immutable. By making String objects immutable, we can treat it much like a primitive data type for efficient processing. If we use the new operator to create a String object, a separate object is created as the top diagram illustrates. If we use a simple assignment as in the bottom diagram, then all literal constants refer to the same object. We can do this because String objects are immutable.

The StringBuffer Class Stores character sequences Unlike a String object, the contents of a StringBuffer object can be changed

Pre-review question 7 Consider the Java segment: String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1 ); int count = tok.countTokens();   What is the value of count ? 7 Appendix A: Introduction to Java

Pre-review question Consider the Java segment: String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1, delimArg ); For the String line1 to have 4 tokens, delimArg should be: a. String delimArg = "+="; b. String delimArg = "123" c. String delimArg = "c+"; d. String delimArg = " ";

Pre-review question Consider the Java segment: String line1 = new String( "c = 1 + 2 + 3" ) ; StringTokenizer tok = new StringTokenizer( line1, delimArg ); For the String line1 to have 4 tokens, delimArg should be: a. String delimArg = "+="; b. String delimArg = "123" c. String delimArg = "c+"; d. String delimArg = " ";

StringTokenizer Class We often need to process individual pieces, or tokens, in a string Appendix A: Introduction to Java

Wrapper Classes for Primitive Types Sometimes we need to process primitive-type data as objects Java provides a set of classes called wrapper classes whose objects contain primitive-type values: Float, Double, Integer, Boolean, Character, etc. Appendix A: Introduction to Java

Defining Your Own Classes Unified Modeling Language is often used to represent a class Standard means of documenting class relationships widely used in industry Appendix A: Introduction to Java

Defining Your Own Classes (continued) The modifier private sets the visibility of each variable or constant to private visibility These data fields can be accessed only within the class definition Only class members with public visibility can be accessed outside of the class Constructors initialize the data fields within a class Appendix A: Introduction to Java

Arrays In Java, an array is also an object The elements are indexes and are referenced using a subscripted variable of the form arrayname[subscript] Appendix A: Introduction to Java

Review question A programmer must do the following before using an array: a. declare then reference the array. b. create then declare the array. c. create then reference the array. d. declare then create the array. Appendix A: Introduction to Java

Review question A programmer must do the following before using an array: a. declare then reference the array. b. create then declare the array. c. create then reference the array. d. declare then create the array. Appendix A: Introduction to Java

Input/Output using Class JOptionPane (continued) Appendix A: Introduction to Java

Converting Numeric Strings to Numbers A dialog window always returns a reference to a string Therefore, a conversion is required Appendix A: Introduction to Java

Input/Output using Streams An input stream is a sequence of characters representing program data An output stream is a sequence of characters representing program output The console keyboard stream is System.in or Scanner The console window is associated with System.out.print(ln) or Formatter Appendix A: Introduction to Java