Fundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!

Similar documents
Fundamental Java Syntax Summary Sheet for CISC124, Fall Java is Case - Sensitive!

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

5/24/2006. Last Time. Announcements. Today. Method Overloading. Method Overloading - Cont. Method Overloading - Cont. (Midterm Exam!

Fall 2017 CISC124 10/1/2017

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Computational Expression

Streams and File I/O

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Programming with Java

Week 6: Review. Java is Case Sensitive

Lecture 7. File Processing

Simple Java Reference

Fall 2017 CISC124 9/16/2017

A variable is a name for a location in memory A variable must be declared

Streams and File I/O

Getting started with Java

Chapter 2 ELEMENTARY PROGRAMMING

File IO. Binary Files. Reading and Writing Binary Files. Writing Objects to files. Reading Objects from files. Unit 20 1

Full file at

Simple Java Input/Output

Data Structures. 03 Streams & File I/O

Fall 2017 CISC124 9/27/2017

File I/O Array Basics For-each loop

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Using Java Classes Fall 2018 Margaret Reid-Miller

CS 251 Intermediate Programming Java I/O Streams

Chapter 2 Elementary Programming

Important Java terminology

Computer Science 145 Midterm 1 Fall 2016

Introduction to Programming Using Java (98-388)

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Reading Input from Text File

USING LIBRARY CLASSES

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Section 2.2 Your First Program in Java: Printing a Line of Text

We now start exploring some key elements of the Java programming language and ways of performing I/O

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

c) And last but not least, there are javadoc comments. See Weiss.

IT101. File Input and Output

CEN 414 Java Programming

CMPSCI 187: Programming With Data Structures. Lecture #24: Files and a Case Study David Mix Barrington 2 November 2012

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

Chapter 11: Exceptions and Advanced File I/O

Chapter 12: Exceptions and Advanced File I/O

WOSO Source Code (Java)

Chapter 2: Data and Expressions

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

PROGRAMMING FUNDAMENTALS

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Lecture Set 2: Starting Java

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

Mr. Monroe s Guide to Mastering Java Syntax

Primitive Data Types: Intro

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Fundamentals of Programming Data Types & Methods

Introduction to Java Unit 1. Using BlueJ to Write Programs

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

AP Computer Science Unit 1. Writing Programs Using BlueJ

Input. Scanner keyboard = new Scanner(System.in); String name;

AP Computer Science Unit 1. Programs

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

Lecture Set 2: Starting Java

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Chapter 17 Binary I/O. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Chapter 2. Elementary Programming

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Input-Output and Exception Handling

3. Java - Language Constructs I

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 2: Data and Expressions

OBJECT ORIENTED PROGRAMMING IN JAVA

Pace University. Fundamental Concepts of CS121 1

Basics of Java Programming

COMP 110 Introduction to Programming. What did we discuss?

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

HST 952. Computing for Biomedical Scientists Lecture 8

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Chapter 1 Introduction to java

CS Programming I: File Input / Output

C17a: Exception and Text File I/O

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java Notes. 10th ICSE. Saravanan Ganesh

CS Programming I: File Input / Output

Lab5. Wooseok Kim

Object-Oriented Programming in Java

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Full download all chapters instantly please go to Solutions Manual, Test Bank site: testbanklive.com

Transcription:

Fundamental Java Syntax Summary Sheet for CISC101, Spring 2006 Notes: Items in italics are things that you must supply, either a variable name, literal value, or expression. Variable Naming Rules Java is Case - Sensitive! Start with a letter, letters and numbers only and the underscore character, no spaces, any length. Operator Precedence Table (Items at the top execute first, followed by those below. All items in the same section have the same precedence.) "Javaspeak" would be "Method invocation", rather than "Function call"! It is recommended that you stick with the postfix operators only. We will not use "~". The "+" operator is "overloaded" in Java! We will not use these "shift" operators either. Use "&&" and " " instead of "&" and " ".

Primitive Types char // '\u0000' to '\uffff' The most often used types are "int", "double" byte // -128 to 127 and "boolean". short // -32768 to 32767 int // -2147483648 to 2147483647 long // -9223372036854775808 to 9223372036854775807 float // ±1.4 x 10-38 to ±3.4 x 10 38 to 7 significant digits double // ±4.9 x 10-308 to ±1.7 x 10 308 to 15 significant digits boolean // true or false In Java, you must declare any variable (primitive type or Object) before you can use it. Basic Program Structure Without the use of any external packages: public class Classname { Saved in a text file called "Classname.java". public static void main (String[] args) { // Your code goes here // end main method // end class Importing the javax.swing and java.io packages for example: import javax.swing.*; // for GUI screen Input/Output import java.io.*; // for File Input/Output public class Classname { These two packages are part of all standard Java distributions. public static void main (String[] args) { // Your code goes here - this code can also use any Object in the javax.swing // package // end main method // end class No packages, but with the declaration of another method: public class Classname { public static return_type method_name (parameter_list) { // Your method code goes here // end method declaration public static void main (String[] args) { // Your code goes here // main can invoke the other method // end main method // end class "return_type" is any primitive or defined Object type, or "void". "method_name" must follow variable naming rules. "parameter_list" consists of none, one, or more parameters, separated by commas, where a parameter consists of a type declaration followed by a valid variable name. For example, a parameter list consisting of two int values would be like "int a, int b".

Comments In-Line comments start with "//". Block comments start with "/*" and end with "*/". Program Structure Blocks of code, including class definitions and method code are contained within sets of "{" and "". Statements are terminated with a ";". Methods & Class Attributes The syntax for method declaration is shown above. If a method has a return type other than "void", it must have at least one "return" statement within the method: return variable_value_or_expression; The type of variable_value_or_expression must match the return type declared in the method declaration. Methods can be declared in any order in a class. Variables called class attributes can be declared at the same level as methods. Class attributes are known inside every method in a class. All structural code must be contained within a method. Conditional Statements "if" statements, without statement blocks: if (expression_that_evaluates_to_a_boolean_value) // a single statement that executes if the expression is true else // the "else" part is optional // a single statement that executes if the expression is false with statement blocks: if (expression_that_evaluates_to_a_boolean_value) { // multiple statements that execute if the expression is true else { // the "else" part is optional // multiple statements that execute if the expression is false // end if an if-else-if "chain" with statement blocks: if (expression1) { // if expression1 is true else if (expression2) { // if expression2 is true else if (expression3) { // if expression3 is true else { // if none of the above are true // end if-else-if You can have as many "else if" statements as you like. Java also has a switch statement that performs a very similar function:

The "switch" statement: switch (expression) { case value1: // statements if expression equals value1 case value2: // statements if expression equals value2 case value3: // statements if expression equals value3 case value4: // statements if expression equals value4 default: // if none of the above match expression and all the values must be of an integer type: byte, short, int, long or char. You can have as many case statements as you like and the default: part is optional. // end switch Repetition Structures or "Loops" Example of a "while" loop: // this loop computes 1 + 2 + 3 +... + N int i = 1; while (i <= N) { sum = sum + i; i = i + 1; // end while Example of a "do-while" loop: // same calculation as at left int i = 1; do { sum = sum + i; i = i + 1; while (i <= N); // end do-while Example of a "for" loop: // same calculation as above int i; for (i = 1; i <= N; i++) { sum = sum + i; // end for or: for (int i = 1; i <= N; i++) sum = sum + i; or using the for each loop in Java 5.0 : double[] data = {...; for (double e : data) {... //e is an element in data Screen Output/Input Text Screen Output: System.out.print(whatever_you_want_to_print); or: System.out.println(whatever_you_want_to_print); // adds a CR/LF to the end of the output

Formatted output (in Java 5.0 ): System.out.printf(format_String, variable_name); format_string contains a placeholder, like %8.2f, (for double s), along with other characters. These placeholders determine the width of the space reserved to output the value, the number of digits to display after the decimal. The final letter determines the way the value is displayed. Use something like %8d for int types. See the Java 5.0 API for more detailed information. Output Format Control Strings: \n Adds a Line Feed character \t Adds a Tab character \r Adds a Carriage Return character \\ Adds the "\" character \' Adds the "'" character \" Adds the """ character \u#### Adds the specified Unicode character These sequences can be embedded in any String literal. "####" is a hex value between 0000 and ffff. Console input using the Scanner class (in Java 5.0 ): import java.util.scanner; public class JavaScannerInput { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Please provide a number: "); double anum = input.nextdouble(); System.out.printf("Formatted output: %8.2f\n", anum); // end main method // end JavaScannerInput class Text File Input in Java 5.0 You must have imported java.io.* and java.util.* to use these classes. To create an input stream: Scanner streamname = new Scanner(new FileReader(fileName)); To read from the file (reads one entire line from file, and removes leading or trailing white space): String inputline = streamname.nextline(); Other Scanner class methods; nextint() // reads an int "filename" can contain just the filename (if the file is in the same folder as your program) or a full path to the file. nextdouble() // reads a double hasnextline() // returns true if not at the // end of the file To close any text or binary input or output stream: streamname.close();

Text File Output To create an output stream: PrintWriter streamname = new PrintWriter(new FileOutputStream(fileName)); To write to the file: streamname.print(data); // no end of line character streamname.println(data); // appends end of line character Binary File Input To create an input stream: ObjectInputStream streamname = new ObjectInputStream(new FileInputStream(fileName)); To read from the file (reads one int value): int variable_name = streamname.readint(); Binary File Output To create an output stream: There are "read" methods for every primitive type. To read String's use the "readutf()" method. To write String's use the "writeutf()" method. You must read binary values in exactly the same order in which they were written. You cannot edit binary files with a text editor. ObjectOutputStream streamname = new ObjectOutputStream (new FileOutputStream (filename)); To write to the file (writes one int value): streamname.writeint(variable_name_or_value); Random Access File I/O Use: RandomAccessFile randfile = new RandomAccessFile(fileName, rw ); randfile contains methods to write or read any byte in the file, such as seek(), readbyte() and writebyte(). Other methods write or read primitive type values. They have the same names as the methods for binary file operations. Exceptions with File I/O For many read and write operations, you will need to be prepared to catch exceptions such as FileNotFoundException and the general IOException. You can use the EOFException to detect the end of a binary file when reading. Catching Exceptions Binary files can be used to read and store objects directly. Use the readobject() and writeobject() methods. readobject() returns an Object, so it must be cast back to its original type. try { // code that might generate an exception catch (Exception e) { // code that does something useful! // end try catch block This code catches all exceptions. You can catch specific exceptions using something like: catch (NumberFormatException e) Many catch blocks can be used.

String Declaration String String_variable_name = some_string_literal; // Initialization is optional or String String_variable_name = new String(some_String_literal); String Methods. Used as in: stringname.methodname(parameter(s)) length() // returns the length of the string as an int equals(otherstring) // returns true if otherstring matches the String equalsignorecase(otherstring) // returns true if otherstring matches the String, // ignoring upper/lower case compareto(otherstring) // returns a negative int if otherstring > String, a // positive int if otherstring < String, 0 if they match tolowercase() // returns the String all in lower case touppercase() // returns the String all in upper case trim() // returns the String without leading and/or trailing spaces charat(position) // returns the char at the specified position substring(start) // returns the right part of the String, starting from // position start substring(start, endplusone) // returns the String starting from position start and // ending at position endplusone - 1 indexof(searchstring) // returns the position of the first occurrence of // searchstring in the String indexof(searchstring, start) // returns the position of the first occurrence of // searchstring in the String searching from position start replace(oldchar, newchar) // returns a String that has all occurrences of // oldchar replaced with newchar format(format_string, values) // returns a formatted string from the numeric values // supplied, works just like printf (Java 5.0 only) A Few Wrapper Class Methods. Integer.parseInt(strInt) // returns strint (a String representation of an int) as an // actual int Double.valueOf(strDouble).doubleValue() // returns strdouble (a String representation of // a double) as an actual double Double.parseDouble(strDouble) // Available in newer Java versions Character.isDigit(charVal) // returns true if charval lies between 0 and 9 Character.isLeter(charVal) Character.isUpperCase(charVal) Character.isLowerCase(charVal) Character.toUpperCase(charVal) Character.toLowerCase(charVal) // returns true if charval is a letter A Few Math Class Methods. Math.PI Math.abs(aNumber) Math.pow(aNumber, exponent) Math.round(aFloat) Math.round(aDouble) // π expressed as a double // returns the absolute value of anumber as a double // returns a double of anumber raised to exponent // returns nearest int to afloat // returns nearest long to adouble Arrays int[] myarray = new int[10]; // myarray.length returns 10 int[][] ddarray = new int[20][5]; // ddarray.length returns 20, ddarray[0].length // returns 5