CSC 224 Java for Programmers Winter 2002 (2002/01/07 -- 2002/03/13) Monday/Wednesday 3:10 -- 4:40 pm Instructor: John Petlicki Office hours: Monday and.

Slides:



Advertisements
Similar presentations
Chapter 1: Computer Systems
Advertisements

Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
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.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
1 Java Basics. 2 Compiling A “compiler” is a program that translates from one language to another Typically from easy-to-read to fast-to-run e.g. from.
The Java Programming Language
Outline Java program structure Basic program elements
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.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
String Escape Sequences
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Software Solutions Lewis and Loftus Chapter 2 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Software Concepts -- Introduction.
Expressions, Data Conversion, and Input
Prepared by Uzma Hashmi Instructor Information Uzma Hashmi Office: B# 7/ R# address: Group Addresses Post message:
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
CSCI 1100/1202 January 16, Why do we need variables? To store intermediate results in a long computation. To store a value that is used more than.
Java Language and SW Dev’t
System development with Java Lecture 2. Rina Errors A program can have three types of errors: Syntax and semantic errors – called.
INTRODUCTION TO JAVA CHAPTER 1 1. WHAT IS JAVA ? Java is a programming language and computing platform first released by Sun Microsystems in The.
1 Computer Systems -- Introduction  Chapter 1 focuses on:  the structure of a Java application  basic program elements  preparing and executing a program.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
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.
Chapter 2: Java Fundamentals
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 1: Introduction Java Programming Language How the Java Virtual Machine Works (compiling, etc…) Update by: Dan Fleck Coming up: The Java Programming.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Lecture 2 Software Concepts Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Copyright Curt Hill Variables What are they? Why do we need them?
White Space Spaces, blank lines, and tabs are collectively called white space and are used to separate words and symbols in a program Extra white space.
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.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Java Software Solutions Lewis and Loftus Chapter 2 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Software Concepts -- Introduction.
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.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Data and Expressions. Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration.
Introduction to Java Programming by Laurie Murphy Revised 09/08/2016.
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.
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Working with Java.
Chapter 4 Assignment Statement
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Multiple variables can be created in one declaration
Chapter 3 Assignment Statement
Escape Sequences What if we wanted to print the quote character?
Introduction to Java Programming
An overview of Java, Data types and variables
The Building Blocks Classes: Java class library, over 1,800 classes:
Chapter 1: Computer Systems
Objects and Primitive Data
Units with – James tedder
Units with – James tedder
Focus of the Course Object-Oriented Software Development
Chap 2. Identifiers, Keywords, and Types
Chapter 2: Objects and Primitive Data
Chapter 2 Primitive Data Types and Operations
Instructor: Alexander Stoytchev
Presentation transcript:

CSC 224 Java for Programmers Winter 2002 (2002/01/ /03/13) Monday/Wednesday 3: :40 pm Instructor: John Petlicki Office hours: Monday and Wednesday 1:30 – 3:00 pm (CST Building) Home page:

Review of Resources CD-ROM of "Java Software Solutions" contains: Java(TM) 2 SDK, Standard Edition (for Microsoft Windows) Forte for Java Community Edition (for Microsoft Windows) Slides in PowerPoint 97 format Keyboard materials Example programs

Characteristics of Java Simple Object-oriented Strongly typed Interpreted Architecture neutral Garbage collected Multithreaded Robust Secure Portable

Simple Many programmers are already familiar with Java syntax (borrowed from C and C++). Difficult aspects of C++ are removed. No header files No pointer arithmetic (pointer Syntax) No structures or unions No operator overloading No virtual base classes Etc.

Object-oriented A technique of developing programs by creating entities that contain logically related data and methods that interface to the data

Strongly typed Every variable must have a declared type. Java has eight primitive types  4 types of integers  2 types of floating numbers  1 character type (for Unicode characters)  1 boolean type for truth values

Interpreted The Java source code is compiled into Java bytecode. The Java interpreter can execute Java bytecodes on any machine to which the interpreter has been ported.

Architecture neutral Java bytecode can be run on many different processors. Bytecode  is not dependent on the machine code of any particular computer.  is designed to be easily translated into the native machine code of any machine.

Garbage Collected The programmer does not have to explicitly return allocated memory to the system. Java performs automatic garbage collection when object references are lost.

Multithreaded A program can be designed as multithreaded in order to perform multiple tasks at the same time Can take advantage of multiprocessor systems

Robust Emphasis on early checking of possible problems. Dynamic run-time checking. Eliminate situations that are error-prone Pointer model eliminates possibility of overwriting memory and corrupting data

Secure Security features Java will not corrupt memory outside its own process space. Web browser can prevent Java applets from reading or writing local files And more

Portable The size of primitive data types and the behavior of arithmetic on them is specified and constant. The libraries have portable interfaces – the abstract Window class has implementations for UNIX, Windows and Macintosh.

A Java Program /* * Example HelloWorld.java * Prints the message "Hello, World!“ */ public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, world.”); }

Java programming steps Create a source code program with a text editor (HelloWorld.java) Compile the source code into Java bytecode (javac HelloWorld.java) Run the bytecode with a Java interpreter (java HelloWorld) Java interpreters translate bytecode instruction to machine code and then carry out the instruction. A compiler and interpreter are in the Java 2 SDK (Software Development Kit )

Installing JDK 1.3 For Microsoft Windows platform, run the executable j2sdk1_3 file on the CD For other platforms other than Microsoft Windows, obtain the SDK directly from Sun, at

Java Development Environments DOS command line interface basic with SDK 2. (javac, java) Forte -- heavyweight IDE forte_ce_2.exe on the CD ROM Bluej – lightweight IDE Download from And others

Installing Bluej (optional) Be sure the JDK is installed Download from Download the Bluej tutorial Follow the installation instructions

Java Basics Program structure Naming conventions Package Identifiers Reserved words Data types Type conversions Arithmetic operators and expressions Variable declaration and initialization Assignments

Packages Java provides mechanisms to organize large-scale programs in a logical and maintainable fashion. Class --- highly cohesive functionalities File --- one class or more closely related classes Package --- a collection of related classes or packages

Java Class Library The Java class library is organized into a number of packages: java.lang --- general java.awt --- GUI java.io --- I/O java.util --- utilities java.applet --- applet java.net --- networking

Example using import // Example Time // Prints a greeting message with // the current time. import java.util.*; public class Time { public static void main(String[] args) { System.out.println("Hello!”); System.out.println("The time is " + new Date()); }

Fully qualified class name public class Time1 { public static void main(String[] args) { System.out.println("Hello!"); System.out.println("The time is " + new java.util.Date()); }

Java Reserved Words abstract boolean break byte byvalue case cast catch char class const continue default do double else extends false final finally float for future generic goto if implements import inner instanceof int interface long native new null operator outer package private protected public rest return short static super switch synchronized this throw throws transient true try var void volatile while

Identifiers are the words a programmer creates in a program made up of letters, digits, underscore character (_), and the dollar sign cannot begin with a digit Java is case sensitive, therefore Total and total are different identifiers

White Space Spaces, blank lines, and tabs are collectively called white space White space is used to separate words and symbols in a program Extra white space is ignored A valid Java program can be formatted many different ways Programs should be formatted to enhance readability, using consistent indentation

Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total; int count, temp, result; Multiple variables can be created in one declaration

Variables A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149; b When a variable is referenced in a program, its current value is used

Data Types Type byte short int long float Double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value ,768 -2,147,483,648 < -9 x /- 3.4 x with 7 significant digits +/- 1.7 x with 15 significant digits Max Value ,767 2,147,483,647 > 9 x 10 18

Boolean Type boolean boolean constants: true false

Character Type char 16-bit Unicode character. ASCII is a subset of Unicode --- ISO-8859 (Latin-1) Examples of character constants: 'A' 'y' '8' '*' ' ' (space) '\n' (new line).

Escape Sequences \b backspace \f form feed \n new line (line feed) \r carriage return \t tab \" double quote \' single quote \\ backslash \uhhhh: hex-decimal code, e.g. \u000A \ddd: octal code, e.g. \040

Data Conversions Sometimes it is convenient to convert data from one type to another For example, we may want to treat an integer as a floating point value during a computation Conversions must be handled carefully to avoid losing information Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int ) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short )

Data Conversions In Java, data conversions can occur in three ways: assignment conversion arithmetic promotion casting Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening conversions can happen via assignment Arithmetic promotion happens automatically when operators in expressions convert their operands

Data Conversions Casting is the most powerful, and dangerous, technique for conversion Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total : result = (float) total / count;

Legal data conversion (No Information Loss)

String -- a class type Examples of string literals: "watermelon" "fig" "$%&*^%!!" "354" " " (space) "" (empty string) Constructor String name = new String(“John”); Concatenation operator + methods: (page 75) charAt(int i) length()

Arithmetic Operators and Expressions + addition - subtraction * multiplication / division % remainder precedence and association

Example Time2 import java.util.*; public class Time2 { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); System.out.println("The time is " + hour + ":" + minute + ":" + second); System.out.println("The time is " + hour / 10 + hour % 10 + ":" + minute / 10 + minute % 10 + ":" + second / 10 + second % 10); }

Variable declaration / initialization int x, y, z; long count; char a, b; boolean flag; float massInKilos; short timeInSeconds = 245; char ch1 = 'K', ch2 = '$'; boolean isNew = true; double maxVal = ;

Assignments total = quantity * unitPrice; count = count + 1; count += 1; count++;

Constants an identifier that is similar to a variable except that it holds one value for its entire existence The compiler will issue an error if you try to change a constant In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; Constants: give names to otherwise unclear literal values facilitate changes to the code prevent inadvertent errors

Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e 1432 a + b * c - d / e 3241 a / (b + c) - d % e 2341 a / (b * (c + (d - e))) 4123