CSC 243 - Java Programming, Spring, 2010 Week 2: Java Data Types, Control Constructs, and their C++ counterparts.

Slides:



Advertisements
Similar presentations
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.
Advertisements

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.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Shlomo Hershkop1 Introduction to java Class 1 Fall 2003 Shlomo Hershkop.
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 Java intro Part 3. 2 Arrays in Java Store fixed number of values of a given type Arrays are objects –have attributes –must be constructed Array declaration:
Lecture 3 Java Basics Lecture3.ppt.
Some basic I/O.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
March 2005Java Programming1. March 2005Java Programming2 Why Java? Platform independence Object Oriented design Run-time checks (fewer bugs) Exception.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
LESSON 2 CREATING A JAVA APPLICATION JAVA PROGRAMMING Compiled By: Edwin O. Okech [Tutor, Amoud University]
DAT602 Database Application Development Lecture 5 JAVA Review.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
CSC204 – Programming I Lecture 4 August 28, 2002.
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 4.
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
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
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.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Chapter 2: Java Fundamentals
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
1 Programming Java Java Basics. 2 Java Program Java Application Program Application Program written in general programming language Applet Program running.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSC 298 Streams and files.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
CSC Java Programming, Fall, 2008 Week 3: Objects, Classes, Strings, Text I/O, September 11.
Java Part I By Wen Fei, HAO. Program Structure public class ClassName { public static void main(String[] args) { program statements } user defined methods.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 9.
CSC Java Programming, Fall, 2008 August 28, 2008, class 2 Tuesday, September 2 uses Monday’s schedule!
CompSci 100E JB1.1 Java Basics (ala Goodrich & Tamassia)  Everything is in a class  A minimal program: public class Hello { public static void main(String[]
Object Oriented Programming Lecture 2: BallWorld.
Java Programming Language Lecture27- An Introduction.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Objects, Classes, Program Constructs
Introduction to Programming in Java
Starting JavaProgramming
null, true, and false are also reserved.
Introduction to Java Programming
An Introduction to Java – Part I, language basics
An overview of Java, Data types and variables
Chap 1 Chap 2 Chap 3 Chap 5 Surprise Me
Java Programming Language
CSC Java Programming, Spring, 2012
Problem 1 Given n, calculate 2n
Presentation transcript:

CSC Java Programming, Spring, 2010 Week 2: Java Data Types, Control Constructs, and their C++ counterparts

Summary of Java built-in types Primitive type variables are not class objects byte is 8-bit signed, -128 through 127 (page 32 in text) short is 16-bit signed, through int is 32-bit signed, long is 64-bit signed float is 32-bit type and double is 64-bit type boolean is 1-bit true or false, char is UNICODE Some class types are built into the language java.lang.String a class built into the language Wrapper classes in java.lang wrap native types as classes. Examples are Integer, Float, Long, Double.

Summary of Java control constructs boolean (true or false) is the basis for control flow /export/home/faculty/parson/JavaLang/week1/bool for, while and do-while loops, just like C++ if.. else if.. else selection, just like C++ switch statement (text p. 86) also like C++ break exits the innermost loop or switch continue goes to the top of innermost loop There are no stand-alone functions! A method always exists inside a class. A non-static method uses a class object. A static method uses only class-static data.

Java Methods A method is equivalent to a C++ member function. In Java all methods resides in classes. A static method does not require an object. int intvar = java.lang.Integer.parseInt(“2”); System.out.println(“integer: “ + intvar); Statics method use static class variables. A regular method needs an object reference. Integer intObject = new Integer(“3”); System.out.println(“integer: “ + intObject.intValue());

Java storage of class and object data Only one copy of a static data element exists for its class. Both static methods and non- static methods (object methods) can use it. static java.lang.String oneStringPerClass = new String(); There is one copy of each non-static data element in each object. Only non-static methods can use it. String oneStringPerObject = new String(“my value”);

Java access to class and object methods and data Public methods and data can be used by any code that imports the class. Protected methods and data can be used only by the defining class and derived classes. Private methods and data can be used only by the defining class. If there is no explicit access restriction, then package methods and data can be used by any class in the package.

First example Java program CountArgString counts distinct, non- overlapping occurrences of a string in a file /export/home/faculty/parson/JavaLang/countargs Make sure you “cp –pr ~parson/JavaLang ~/JavaLang” to get JavaLang into your home directory Make sure CLASSPATH include your $HOME/JavaLang makefile drives execution of compile and test steps gmake build to compile Java files gmake test to run test cases gmake clean to clean up test output and compiled files

Boolean example code /export/home/faculty/parson/JavaLang/bool Make sure you have a copy of this. cp –pr ~parson/JavaLang/bool ~/JavaLang/bool Program verifies valid command line args. 1. Program reads command line into an array of floats, raising an Exception if any of the command line arguments is not a float. 2. Verify that array is in ascending order using &&. 3. Verify that array is in ascending order using ||.

Booleans Boolean variables and constants boolean isSortedAnd = true, isOutOfOrderOr = false ; Boolean expressions isOutOfOrderOr || ! isLessThanOrEqual(numbers[i], numbers[i+1]) Condition control constructs use booleans if (isSortedAnd != ! isOutOfOrderOr) { Conditional expressions use booleans System.exit(isSortedAnd ? 0 : 1);

Class java.lang.System System.in is equivalent to C++ cin. import java.util.Scanner ; Scanner inputScanner = new Scanner(System.in); System.out and System.err are equivalent to C++ cout and cerr. System.out.println("sort result = " + isSortedAnd); System.exit(0) causes the process to exit with status of 0, meaning there is no error. A non-0 exits status signifies an error.

Creating Java Arrays Arrays are constructed using new (like C++). “float [] numbers ;” creates a null array reference. float [] numbers = new float [ INTEGER_SIZE ] ; Java implicitly initializes an array of numbers with 0. Booleans gets false, chars get ‘\0000’. float [] numbers = {1.9F, 2.9F, 3.4F, 3.5F} ; Myclass [] myobject = new Myclass[ INTEGER_SIZE ] ; Java initializes an array of object references with null. Java objects and arrays created using “new” need not be “deleted.” JAVA HAS GARBAGE COLLECTION!

Using Java Arrays “String [] args” is the parameter for Java main. public static void main(String args[]) { main is needed for running a class from the UNIX command line. Expression “numbers.length” gives the number of elements in the array. if (args.length == 0) { float [] numbers = new float [ args.length ] A subscript access and element of an array numbers[i] = Float.parseFloat(args[i]);

Helper class java.util.Arrays Utility methods for manipulating arrays. public static int[] copyOf(int[] original, int newLength); » First available in Java 1.6, not 1.5 on Mac OSX. public static void fill(int[] a, int val); public static void sort(int[] a); public static int binarySearch(int[] a, int key); public static T[] copyOf(T[] original, int newLength); public static void sort(T[] a, Comparator c) ;Comparator Comparator int compare(T o1, T o2) returns -1 or 0 or 1 for o1 o2 respectively.T

Multidimensional Arrays int [][] matrix ; // an array of arrays, null int [][] matrix = new int[4][3]; // 4 rows of 3 int [][] matrix = { // See Figure 6.11, p. 204 {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; matrix[0][0] is the initial element of the initial row matrix[3][2] is the last element of the last sub-array (last column of the last row)

“Ragged Arrays” int [][] triangle = { // p. 205 {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} }; int [][] triangle = new int [5][]; for (int i = 0 ; i < triangle.length ; i++) { triangle[i] = new int [triangle.length – i]; } triangle[1].length gives the length of the second sub-array triangle[1], which == 4.

Handling an exception from a library method Read on-line doc on java.lang.Float.parseFloat try { numbers[i] = Float.parseFloat(args[i]); } catch (NumberFormatException nfexp) { System.err.println("format error on " + args[i] + ": " + nfexp.getMessage()); isSortedAnd = false ; isOutOfOrderOr = true ; // Initialize array element to a default value. numbers[i] = 0.0F ; }

Notes on the makefile If you run a test that you intend to fail – System.exit(NON-0) – then put a “-” in front of that command invocation in the makefile. -java $(PACKAGE).$(BASENAME) fred Also, since your error messages are sent to System.err, you need to redirect System.err to a file to capture its output to use with diff. >> $(BASENAME).out 2>&1 >> $(BASENAME).out 2>$(BASENAME).err

Programming practices Always handle exceptions! We may handle some by explicitly ignoring them. Always use { curly braces } for control blocks. Use coding standards that we discuss in class. Write Javadoc documentation. Use both healthy and degenerate tests. » Ignoring these rules will cost you points.