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

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

Fall 2017 CISC124 10/1/2017

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

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

Week 6: Review. Java is Case Sensitive

Fall 2017 CISC124 9/16/2017

Fall 2017 CISC124 9/27/2017

Getting started with Java

USING LIBRARY CLASSES

Simple Java Reference

JAVA Ch. 4. Variables and Constants Lawrenceville Press

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

Programming with Java

Computational Expression

Introduction to Programming Using Java (98-388)

Full file at

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

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

Basic Operations jgrasp debugger Writing Programs & Checkstyle

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

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

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

Important Java terminology

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

Chapter 2 ELEMENTARY PROGRAMMING

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

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

Java Input/Output. 11 April 2013 OSU CSE 1

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

IT101. File Input and Output

WOSO Source Code (Java)

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

Lesson 3: Accepting User Input and Using Different Methods for Output

Using Java Classes Fall 2018 Margaret Reid-Miller

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

Mr. Monroe s Guide to Mastering Java Syntax

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

Streams and File I/O

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

Lecture 7. File Processing

CS 251 Intermediate Programming Java I/O Streams

Chapter 2 Elementary Programming

Performing input and output operations using a Byte Stream

Streams and File I/O

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

PROGRAMMING FUNDAMENTALS

3. Java - Language Constructs I

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Basics of Java Programming

COMP 110 Introduction to Programming. What did we discuss?

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

CT 229 Fundamentals of Java Syntax

Java Notes. 10th ICSE. Saravanan Ganesh

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

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

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Index COPYRIGHTED MATERIAL

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

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

.. Cal Poly CPE 101: Fundamentals of Computer Science I Alexander Dekhtyar..

Pace University. Fundamental Concepts of CS121 1

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

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

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

OBJECT ORIENTED PROGRAMMING IN JAVA

Computer Science 145 Midterm 1 Fall 2016

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

CSC Java Programming, Fall Java Data Types and Control Constructs

Visual C# Instructor s Manual Table of Contents

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Data Structures. 03 Streams & File I/O

Chapter 1 Introduction to java

Introduction to Java Applications; Input/Output and Operators

Course Outline. Introduction to java

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

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Chapter 2: Data and Expressions

Full file at

CEN 414 Java Programming

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

1. An operation in which an overall value is computed incrementally, often using a loop.

Values and Variables 1 / 30

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

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

CS313D: ADVANCED PROGRAMMING LANGUAGE

Data Types and the while Statement

Chapter 2. Elementary Programming

H212 Introduction to Software Systems Honors

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

What did we talk about last time? Examples switch statements

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

Introduction to Programming (Java) 4/12

Lecture Set 2: Starting Java

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

Simple Java Input/Output

Contents Chapter 1 Introduction to Programming and the Java Language

Transcription:

Fundamental Java Syntax Summary Sheet for CISC124, Fall 2015 Notes: Items in italics are things that you must supply, either a variable name, literal value, or expression. Java is Case - Sensitive! Variable Naming Rules 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 have not used "~". The "+" operator is "overloaded" in Java! We have not used 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 java.util and java.io packages for example: import java.util.*; // for Utilities 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 "*/". Javadoc 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. Methods using non-static attributes must also be non-static. 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 a String or 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 or newer: 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 or newer): 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 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 or newer): 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); input.close(); // end main method // end JavaScannerInput class Text File Input in Java You must have imported java.io.* and java.nio.* to use these classes. To create an input resource for a try-with-resources structure: BufferedReader reader = Files.newBufferedReader(file) To read from the file (reads one entire line from file, and removes leading or trailing white space): String inputline = reader.readline().trim(); To create the Path object: Path file = Paths.get(fileName); The String "filename" can contain just the filename (if the file is in the project folder) or a full path to the file.

Text File Output To create an output resource for a try-with-resources structure: BufferedWriter writer = Files.newBufferedWriter(file) To write to the file: writer.write(astring); Binary File Input To create an input resource: ObjectInputStream binfilein = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputFileString))) To read from the file (reads one int value): int variable_name = binfilein.readint(); Binary File Output To create an output resource: ObjectOutputStream binfileout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file.toFile())) Binary files can be used to read and store To write to the file (writes one int value): objects directly. Use the readobject() and writeobject() methods. readobject() returns binfileout.writeint(variable_name_or_value); an Object, so it must be cast back to its original type. Random Access File I/O To create a random file resource: FileChannel fc = (FileChannel.open(file, readopt)) fc contains methods to write or read any byte in the file, such as position(), read() and write(). To create readopt for read-only for example: StandardOpenOption readopt = StandardOpenOption.READ; Exceptions with File I/O There are "read" methods for every primitive type and for an Object. 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. 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 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); Some 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.isLetter(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