Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.



Similar documents
Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Introduction to Java

Chapter 2: Elements of Java

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Install Java Development Kit (JDK) 1.8

6.1. Example: A Tip Calculator 6-1

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Variables, Constants, and Data Types

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Introduction to Java. CS 3: Computer Programming in Java

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Comp 248 Introduction to Programming

Some Scanner Class Methods

Pemrograman Dasar. Basic Elements Of Java

Chapter 2 Elementary Programming

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Moving from CS 61A Scheme to CS 61B Java

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Java Basics: Data Types, Variables, and Loops

Object-Oriented Programming in Java

Chapter 3. Input and output. 3.1 The System class

Programming and Data Structures with Java and JUnit. Rick Mercer

Java Interview Questions and Answers

CS 106 Introduction to Computer Science I

Building Java Programs

Lecture 5: Java Fundamentals III

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Chapter 2 Introduction to Java programming

Java Programming Fundamentals

An Overview of Java. overview-1

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

AP Computer Science Java Subset

Lecture 1 Introduction to Java

Part I. Multiple Choice Questions (2 points each):

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

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

Crash Course in Java

Programming in Java Course Technology, a part of Cengage Learning.

Topic 11 Scanner object, conditional execution

Building Java Programs

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Informatica e Sistemi in Tempo Reale

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

J a v a Quiz (Unit 3, Test 0 Practice)

1001ICT Introduction To Programming Lecture Notes

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

CS 111 Classes I 1. Software Organization View to this point:

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Object Oriented Software Design

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Basics of Java Programming Input and the Scanner class

Computer Programming I

VB.NET Programming Fundamentals

Java CPD (I) Frans Coenen Department of Computer Science

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chapter 1 Fundamentals of Java Programming

Habanero Extreme Scale Software Research Project

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

C++ Language Tutorial

13 File Output and Input

Programming in Java. What is in This Chapter? Chapter 1

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Java programming for C/C++ developers

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Week 1: Review of Java Programming Basics

Using Files as Input/Output in Java 5.0 Applications

Building Java Programs

Course Title: Software Development

Java Crash Course Part I

Sample CSE8A midterm Multiple Choice (circle one)

Programming Languages CIS 443

Introduction to Java Lecture Notes. Ryan Dougherty

java Features Version April 19, 2013 by Thorsten Kracht

Object Oriented Software Design

Chapter 1 Java Program Design and Development

Sources: On the Web: Slides will be available on:

Fundamentals of Java Programming

Chapter 2 Basics of Scanning and Conventional Programming in Java

Introduction to Programming

CS106A, Stanford Handout #38. Strings and Chars

CS 106 Introduction to Computer Science I

Chapter 5 Names, Bindings, Type Checking, and Scopes

PL / SQL Basics. Chapter 3

Chapter 8. Living with Java. 8.1 Standard Output

Simple Java Applications

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

D06 PROGRAMMING with JAVA

Transcription:

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java an object-oriented programming language Introduced by James Golsling in 1995 (at Sun ). supports development of full fledged applications and browser-run applets includes support for concurrency and security C++-like syntax, but no pointers, thus safer code supported by powerful vendor: Oracle Java Application Standalone programs - run using a Java Virtual Machine interpreter Widely used for Networking Database applications Multi-tiered architectures Important features of Java Portability - Java code compiles into platform independent byte-code, which is interpreted on each platform by a java-virtual -machine. Automatic garbage collection (no memory allocation/leakage worries) No pointer arithmetic (safer code) Multiple inheritance supported only for interfaces Rigorous support for exception (error) handling Supports method execution across a network via Remote Method Invocation Comes with an extensive library of predefined classes (Java API) - 1 -

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 2 of 11 Object-Oriented Development It is popular because of issues of productivity and overall speed of development. Key idea focus modeling and implementation on the individuals of the problem domain rather then system functions, build system description around the objects, because domain objects usually comprise the most stable part of the system (usually don t change much even if system requirements change dramatically). Class: a general description of objects of similar kind. Includes data and methods that operate on that data Example: a banking application operates on accounts Class: Account Data (properties): Owner, Number, Open Date, Transactions Methods (behaviors): Compute Balance Key OO concepts: 1. Objects and Classes problem domain entities classified according to their properties 2. Encapsulation and Information Hiding package an object s data attributes and behavior together restrict access to data 3. Specialization (a.k.a. inheritance) detect commonalities between classes create class hierarchy to inherit common properties without repeating them Example: Checking account, Savings account classes are subclasses of Account. Inherit properties of Account, Class: Checking Account Data (properties): All those of Account class + Service Fee Methods (behaviors): All those of Account class + Deposit, Withdraw 4. Communication with messages to invoke an object send it a message, let the object itself handle it 5. Polymorphism often same operation exists in many classes, example: Print each class implements it differently, but uses the same name for it Compared to structured development, OO provides additional flexibility, potential for reuse and robustness in face of changes. Click to see an illustration. From Java source code to execution - 2 -

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 3 of 11 Java application is a collection of classes. Here s the simplest example with one class containing just a single method called main. Create a Java source file called HelloWorldApp.java. The name of the file must match the name of the class. Java is case sensitive, e.g. main is different from Main, Hello is different from hello /* HelloWorldApp.java * Prints Hello, World! */ public class HelloWorldApp { public static void main(string[] args) { // print Hello World! System.out.println("Hello, World! Welcome to Bentley."); In compiled languages: Source Code Processor- Specific Compiler Binary File Runtime System In Java: Source Code Hello.java Compiler javac.exe Bytecode Hello.class Java Virtual Machine (JVM) interprets byte-code Java Virtual Machine Processor- Specific Interpreter java.exe Runtime System - 3 -

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 4 of 11 LEXICAL ELEMENTS: Words and symbols that make up a language, including comments, keywords, identifiers, punctuation, literals, and operators. Example: /* This is an example of a simple Java program that prints the value stored to the variable x */ public class DeclareVar{ public static void main(string[] args){ int x; x = 5; // declare variable x // store the value 5 to x System.out.println("x = " + x); // print the value of x // end of main method // end of class DeclareVar Comments: // for a single line, till the end of line /* Start a multiple line comment with the slash and asterisk End it with an asterisk and a slash */ Punctuation: a ; is used to indicate the end of a statement. Variable - is a named location to store data It can hold only one type of data All program variables must be declared before using them. A variable declaration associates a name with a storage location in memory and specifies the type of data it will store: e.g. int, float, double, char, String x 5 Identifiers: names for elements in a program, including classes, methods, and variables May consist of letters, digits, the underscore(_) and $ (reserved for system identifiers) Must not start with a digit Can t be a keyword: word that has a meaning in the language, such as if, boolean, or class. Can t include spaces, punctuation symbols Are case sensitive: x is not the same as X! By convention: class names start with an uppercase letter, variables and methods start with the lowercase. - 4 -

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 5 of 11 DATA TYPES: Each variable has a name and a type. Type refers to the values that can be stored in a variable. Java has primitive and class types. 1. Primitive: built into Java, define non-decomposable values. (1) Numeric: byte 8 bits = 1 byte -128 to 127 short 16 bits -32768 to 32767 int 32 bits -2 31 to 2 31-1 Default for integer literal long 64 bits specify by adding an l or L: 23L float 32 bits specify by adding f or F: 37.23F double 64 bits default for floating point literal ex. of floating point types: 3.12342, 2.18e-25 (= 2.18 x 10-25 ) (2) char: stores a single character, digit, or symbol. Always surrounded by single quotes, such as a or 9. Stored in 2-bytes (as opposed to many other languages allows for many alphabets) Each character is stored as its code number in Unicode. (3) boolean: true or false. All variables must be declared either before or when they are first used: ASSIGNMENT OPERATOR = Used to set, or assign a variable is to store a given value in the location denoted by the variable name. Not the same as equality in algebra, It means - Store the value of the expression on the right side to the variable on the left side. Examples: Can have any expression on the right hand side of = Restriction: the type of the variable must be compatible with the type of the expression on the right hand side. // declare integer variable and store value to it int x; x = 3; //declare new integer and store value of x to it int y = x; // evaluated right to left: // set value stored to x = value stored to y = 4 x = y = 4; - 5 -

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 6 of 11 // declare two doubles and store values to them double u, v; u = 2.32; v = x; //declare two integers and store value to one of them int a = 2, b; // declare a character variable and store a value to it char letter = a ; //declare two boolean variables and store values to them boolean done = false; boolean start = true; 2. Classes : all other data types (i.e., non-primitives) are defined as class types. String: stored as object of class String. Always enclosed in double quotes. // declare a string variable and store a value to it String prompt = enter your name ; OPERATORS Arithmetic Operators: only operate on numerical data. +, -, *, /, %, ( ) (1) integer division: results from dividing one int by another. Returns whole number quotient, ignoring remainder (truncates). 21 / 4 =? 7 / 2 =? (2) %: modulus, or remainder. 21 % 4 =? 8 % 2 =? /* Illustration of % operator */ public class Remainder{ public static void main(string[] args){ int x = 7; int y = 3; int z = (x/y)*y + x%y System.out.println("z = " + z); // print value of z // end of main method // end of class Remainder - 6 -

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 7 of 11 Order of precedence (elements in the same row have the same precedence): () +(unary) (unary) * / % + - = (assignment) Unary operators take one operand. Example: -3 + 5 // unary operator is ( ) before the three; the (+) is a binary operator here Read from left to right when evaluating an expression. Example: int x = 4, y = 5, z = 3, answer; answer = y - x * z; answer = (y - x) * z; answer = y / x + z; answer = y / (x + z); answer = x - y % z + y; answer = (x - y) % (z + y); Java automatically converts from int to double when the data types are mixed: double x = 4; x = 3.4 * 2; //4 is converted to a double //2 treated as a double Rule for implicit conversion: any numeric value can be assigned to a numeric value of any type that supports a larger range of values. ints are converted to doubles in mixed-type expression. doubles are not converted to ints in mixed-type expression. Explicit type casting: double x = 4.3; // int y = (int)x; // truncates and stores 4 in y int z = (int)'a'; // explicitly converts char to an int - 7 -

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 8 of 11 Relational Operators: also called Comparison Operators. Used with operands: <operand> operator <operand> Use them for making decisions: true or false for outcome. Include: > < >= <= ==!=! is a not operator, so!= means not equal = is an assignment operator, while == is a comparison operator) x = 3; // assigns 3 to x y = x + 1; // increment x by 1 and store to y // compare x and y x == y; // evaluates to true or false // Demo of comparison operators and boolean type public class Comparison { public static void main(string [] args) { int grade = 87; System.out.println( grade>50 ); // set a = boolean that condition evaluates to boolean a = (grade == 100); System.out.println("Student earned 100% is " + a); Examples: boolean state; int i = 5; int j = 9; state = (i > j); state = (i == j); state = (i 3) <= j; state = (i!= j); - 8 -

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 9 of 11 OUTPUT Print: use print and println methods. println moves the cursor to the beginning of the next line after completing the print. Examples: System.out.print(x); //print the value of x System.out.println(x); //print the value of x followed by a //new line System.out.println( The result is + result); System.out.println( The sum of 2 + 3 is + 2 + 3); // prints The sum of 2 + 3 is 23 System.out.println( The sum of 2 + 3 is + (2 + 3)); // prints The sum of 2 + 3 is 5 Special characters: \n //newline \t //tab \b //backspace \ //double quote \\ //backslash Example: /* */ This is a printing demo. Shows special characters within a string public class PrintJava { public static void main(string [] args) { System.out.println("This\nwill start a new line"); System.out.println(3+"\n"+ 4 + "\non different lines"); System.out.println("first column\tsecond column"); System.out.println("with \"double quotes around it\""); System.out.println("directory c:\\cs603\\homework"); - 9 -

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 10 of 11 INPUT Using Scanner class: Use Scanner class to read from keyboard. Scanner a class for text input processing from keyboard, file, or string. To read input from the keyboard: a. Need to include the following line above the class definition import java.util.scanner; This statement tells Java to Make the Scanner class available to the program Find the Scanner class in a library of classes (i.e., Java package) named java.util b. Need to create an object of Scanner class inside the main method as follows: Scanner kb = new Scanner (System.in); Once a Scanner object has been created, a program can then use that object to read user input from the keyboard using methods of the Scanner class These methods are type-specific kb.nextint(); - returns an integer entered by the user. Skips all white space (space, tab, end-of-line characters) that appear before the integer. kb.nextdouble(); - double kb.nextboolean(); kb.next(); - returns the String value consisting of characters up to, but not including the next white space (or end of line). Essentially, reads one word, where word is a sequence of non-white space characters. kb.nextline(); - returns the String value consisting of characters up to, but not including the end of the current line. Unlike the other methods, does not skip the end-of-line character, instead treats it as the end of the line. int x = kb.nextint(); double y = kb.nextdouble(); String word = kb.next(); String line = kb.nextline(); Subtle point: The method nextline of the class Scanner reads the remainder of a line of text starting wherever the last keyboard reading left off. This can cause problems when combining it with different methods for reading from the keyboard such as nextint - 10 -

Handout 1 CS603 Object-Oriented Programming Fall 15 Page 11 of 11 Example: Given the code, Scanner keyboard = new Scanner(System.in); int n = keyboard.nextint(); String s1 = keyboard.nextline(); String s2 = keyboard.nextline(); and user input, 2 Heads are better than 1 head. what are the values of n, s1, and s2? Answer: n will be set to 2, s1 will be equal to "", and s2 will be equal to "Heads are better than" Explanation: \n below denotes the invisible end of line character. Here s what the user input looks like 2\nHeads are better than\n1 head.\n If the following results were desired instead n equal to 2, s1 equal to "heads are better than", and s2 equal to "1 head" then an extra invocation of nextline() would be needed to get rid of the end of line character '\n'. Scanner keyboard = new Scanner(System.in); int n = keyboard.nextint(); keyboard.nextline(); // to get rid of \n after number String s1 = keyboard.nextline(); String s2 = keyboard.nextline(); This only happens when the program needs to read a new line with nextline() after using any other Scanner reading methods (next(), nextint(), nextdouble(), etc..) - 11 -