Introduction to Java. CS 3: Computer Programming in Java

Similar documents
Introduction to Java

Chapter 2: Elements of Java

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

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

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

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

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

Chapter 3. Input and output. 3.1 The System class

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

Basics of Java Programming Input and the Scanner class

Comp 248 Introduction to Programming

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

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

Using Files as Input/Output in Java 5.0 Applications

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

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

Chapter 2 Elementary Programming

Pemrograman Dasar. Basic Elements Of Java

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

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

Chapter 2 Introduction to Java programming

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Variables, Constants, and Data Types

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

CS 106 Introduction to Computer Science I

Lecture 5: Java Fundamentals III

Lab 5: Bank Account. Defining objects & classes

Object-Oriented Programming in Java

AP Computer Science Static Methods, Strings, User Input

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

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Building Java Programs

Interactive Applications (CLI) and Math

Java Basics: Data Types, Variables, and Loops

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

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

Java Crash Course Part I

Moving from CS 61A Scheme to CS 61B Java

Java CPD (I) Frans Coenen Department of Computer Science

CS 106 Introduction to Computer Science I

Java Programming Fundamentals

Programming and Data Structures with Java and JUnit. Rick Mercer

Building Java Programs

Install Java Development Kit (JDK) 1.8

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Some Scanner Class Methods

Topic 11 Scanner object, conditional execution

Introduction to Java Lecture Notes. Ryan Dougherty

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

Sample CSE8A midterm Multiple Choice (circle one)

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

Introduction to Programming

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Week 1: Review of Java Programming Basics

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

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

AP Computer Science Java Subset

Programming Fundamentals I CS 110, Central Washington University. November 2015

6.1. Example: A Tip Calculator 6-1

Example of a Java program

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

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

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

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

Java Interview Questions and Answers

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

java Features Version April 19, 2013 by Thorsten Kracht

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

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

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

Building Java Programs

Programmierpraktikum

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

Reading Input From A File

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

VB.NET Programming Fundamentals

Basic Programming and PC Skills: Basic Programming and PC Skills:

Introduction to Python

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Programming Languages CIS 443

Object Oriented Software Design

Exercise 1: Python Language Basics

AP Computer Science Java Mr. Clausen Program 9A, 9B

13 File Output and Input

Introduction to Python

(Eng. Hayam Reda Seireg) Sheet Java

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

Overview. java.math.biginteger, java.math.bigdecimal. Definition: objects are everything but primitives The eight primitive data type in Java

An Overview of Java. overview-1

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Informatica e Sistemi in Tempo Reale

Explain the relationship between a class and an object. Which is general and which is specific?

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

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

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

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

Chapter 8. Living with Java. 8.1 Standard Output

Transcription:

Introduction to Java CS 3: Computer Programming in Java

Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods

Primitive Data Types Rules for programmer created identifiers Examples of valid and invalid programmer created identifiers Multiple declarations Java strings

Rules for Programmer Created Identifiers Program will need to create memory or storage locations for storing the program data and method names as well as choose names for classes and packages The job of the programmer is to create these identifiers

Rules for Programmer Created Identifiers The rules for the programmer created identifiers in Java are as follows: Identifiers must only contain alphabets, underscore ( _ ),digits (0 to 9 ), and a $ sign An identifier must begin with an alphabet, underscore or $ It cannot begin with a digit An identifier cannot contain blank spaces A horrid practice used by Windows filing system An identifier cannot be a Java reserved word

Examples of Valid Identifiers A a1 student_name stdntnm _asystemname _anthrsysnm $class _public

Examples of Invalid Identifiers Sum+var 2names The + sign is illegal; violates the first rule The first character is invalid; violates the second rule Stdnt Nmbr int Contains whitespace in between the phrases; violates the third rule Reserved word; violates the fourth rule

More About Identifiers It is important to use meaningful identifiers Another Java coding practice is to start the name of classes with upper case letter If the name of the class contains more than one word, then first letter of each word is capitalized

More About Identifiers (2) The names of methods begin with lower case letter, but if method name contains more than one word then first letter of each word after the first word is capitalized Names of program and class variables may be in upper or lower case, but it is a good programming practice to use all lower case names for Java primitive data types and first letter of each word capitalized for the instances of Java classes or objects int myint = 10; float mydecimal = 10.0006; Leaving out data type in Java for a local or class variable name in which data will be stored will cause a compile error

Types of Primitive Data Types Integral byte char short int long Boolean Can only have values true and false Floating Point float double

Java Primitive Sizes and Values Type Size (bytes) Minimum Value Maximum Value char 2 Uses Unicode characters; language dependent byte 1-128 127 short 2-32768 32767 int 4-2147483648 2147483647 long 8-9223372036854775808 9223372036854775807 float 4 +/-1.4E-45 +/-3.4028235E+38 double 8 +/-4.9E-324 +/-1.7976931348623157E+308 boolean 1 false true

Multiple Declarations Java allows one to use the comma operator and declare multiple variables of same data type on one line For example the following declarations are legal: int val1,val2,val3; int val4=22, val5=-10, val6; However, understand that a compile error will result if any attempt is made to use val1, val2, val3, and val6 prior to their initialization

Java Strings Strings in Java are objects of class java.lang.string This means that String class is located in the java.lang package Also, this package is automatically imported in all Java programs Java String class is designed in such a manner that two or more String objects and Strings and primitive Java data can be concatenated, simply by using the plus (+) sign

Java String Concatenation Example For example, the following String concatenation is a legal Java construct: String Big_String = John + + H +. + + Smith is + 20+ years old and has a gpa = + 3.9+ and he does well in + true + / + false+ type examinations. ; System.out.println (Big_String); The above code snippet will print the following on the DOS console: John H. Smith is 20 years old and has a gpa = 3.9 and he does well in true/false type examinations.

Java String Concatenation Example (2) Notice that using the property of overloaded operator plus (+) for String class, Java is able to concatenate characters (such as space, alphabets, and punctuation marks), integers (20 in above case), floating-point numbers (3.9), and boolean literals (true and false) all into one string It is however, required that on right hand side of String concatenation expression, at least one of the data must be of String type

Invalid Java String Concatenation Example For example, expression given below is not a valid String concatenation expression and will cause compile error: String Not_A_String = H + 25 + L ; be concatenated are of type String! // Compile error. None of the expressions to Therefore, one must remember the following String concatenation rule: At least one of the expressions to be concatenated must be of String type

Create a Main Class with Helper Functions Some Programming projects are simple enough to be solved by a single main method which uses built-in Java Classes and their predefined methods However, most robust applications will need to be modularized, both within the Main class and within the user defined Classes that will be needed to implement them

Simple Java Application: Example #1 The following is an example of a simple application which solves a simple problem of reading a name and an age from the user, and displaying the number of months the person has lived The first version solves the problem using only the main method //************************************************ // InCalcOut1.java Author: Edwin Ambrosio // Program calculates how many months old you are after // prompting you for your name and age. // Demonstrates the use of the Scanner class methods with // primitive data types and simple arithmetic operations //************************************************ import java.util.scanner; public class InCalcOut1 { //----------------------------------------------------------------- // Reads a character string from the user and prints it. //----------------------------------------------------------------- public static void main (String[] args) { String name; int age; double months; Scanner scan = new Scanner(System.in); System.out.println("Enter your name:"); name = scan.nextline(); System.out.println("Enter your age: "); age = scan.nextint(); months = age * (double)360 / 30; System.out.println ("You are " months + " months old."); } }

Simple Java Application: Example #2 Although this approach will solve simple programs, we want to divide the program into modules which become methods that perform simple tasks to support the overall goals of the application When these methods are placed in the Main class to assist the main method, they are called Helper Methods The following listing shows a better version of the previous application, using helper methods //************************************************ // InCalcOut2.java Author: Edwin Ambrosio // Program calculates how many months old you are after // prompting you for your name and age. // Demonstrates the use of the Helper methods in the Main // class of InCalcOut1.java //************************************************ import java.util.scanner; import java.text.decimalformat; public class InCalcOut2 { //----------------------------------------------------------------- // Reads a name and age and calculates the number of // months from the age, then display the results. //----------------------------------------------------------------- public static void main (String[] args) { String name; int age; double months; name = getname(); age = getage();

Simple Java Application: Example #2 (2) months = age * (double)365 / 30; // Round the output to three decimal places DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println (name + " you are " + fmt.format(months) + " months } old."); //----------------------------------------------------------------- // Reads a character string from the user and returns it to main - //---------------------------------------------------------------- public static String getname() { } String name; Scanner scan = new Scanner(System.in); System.out.println("Enter your name:"); name = scan.nextline(); return name;

Simple Java Application: Example #2 (3) //----------------------------------------------------------------- // Reads an int from the user and returns it to main //----------------------------------------------------------------- } public static int getage() { int age; Scanner scan = new Scanner(System.in); System.out.println("Enter your age:"); age = scan.nextint(); return age; }

Why Method 2? In this second application, we have used helper methods getname(), and getage() to assist perform the duties of obtaining data from the user We expect this type of design/structure in all the programs that you write for this course Do not try to get by with writing a large main method to solve the problem

Built-In Class Methods All methods are either Class Methods or Instance Methods Class methods are defined within a Class using the static modifier in its description This allows the method to be called by using the Class name as the qualifier: Classname.methodname

Built-In Class Method Example In Java there is no operator to perform the exponent operation, so, we must call the pow method from the Math Class The code to square the variable radius and put its value into the variable rsquared (assuming all variables are type double) would be rsquared = Math.pow(radius, 2); When main calls getname() and getavg(), these calls are to Class methods, but do not need to be qualified because the calls occur within the Class definition

Instance Methods Do not have the static modifier in their definition, and must be called by using a Class object reference as the qualifier Are intended to manipulate the data contained in the particular instance/object that called it All the remaining calls to methods in the above examples are calls to Instance Methods

Instance Methods Example The call: name = scan.nextline(); calls the nextline() method of the Scanner Class for the instance object scan The call: System.out.println("Enter your name:"); calls the println() method of the System Class for the instance object out.

Summary Identifiers Choose names for classes and packages Rules Identifiers must only contain alphabets, underscore ( _ ),digits (0 to 9 ), and a $ sign An identifier must begin with an alphabet, underscore or $ An identifier cannot contain blank spaces An identifier cannot be a Java reserved word Primitive Data Types Integral Boolean Floating point

Summary (2) Java strings Strings in Java are objects of class java.lang.string On the right hand side of String concatenation expression, at least one of the data must be of String type Creating a Main class with helper functions Most robust applications will need to be modularized, both within the Main class and within the user defined Classes that will be needed to implement them Built-in methods and instance methods Class methods are defined within a Class using the static modifier in its description Instance methods do not have the static modifier in their definition, and must be called by using a Class object reference as the qualifier