Lecture Notes – Basics (Ch1-6)

Slides:



Advertisements
Similar presentations
 Base “primitive” types: TypeDescriptionSize intThe integer type, with range -2,147,483, ,147,483,647 4 bytes byteThe type describing a single.
Advertisements

Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Chapter 4  Fundamental Data Types 1 Chapter 4 Fundamental Data Types.
Datalogi A 3: 26/9. Java Concepts chapter 4 Fundamental Data Types int (long and short) double (and float) boolean char String.
Chapter 4 Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To.
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 4: Fundamental Data Types. To understand integer and floating-point numbers To recognize the limitations of the numeric types To become aware.
Chapter 4 Numeric types & arithmetic Strings: reading & writing.
Chapter 4 Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To recognize the limitations of the numeric types To.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 4 – Fundamental Data Types.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Four: Fundamental Data Types.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 3 – Fundamental Data Types.
Java Basics. Java High-level language  More readable for humans  Need to be translated to machine language for execution Compilers  CPU-independent.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 4 – Fundamental Data Types.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Four: Fundamental Data Types.
Fall 2006Slides adapted from Java Concepts companion slides1 Fundamental Data Types Advanced Programming ICOM 4015 Lecture 4 Reading: Java Concepts Chapter.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
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.
Chapter 2 Elementary Programming
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 4 Mathematical Functions, Characters,
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. int: integers, no fractional part: 1, -4, 0 double : floating-point.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Four: Fundamental Data Types.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/20) Java Basics Joel Adams and Jeremy Frens Calvin College.
Using Java Class Library
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 4 – Fundamental Data Types.
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
Variables and Types Java Part 3. Class Fields  Aka member variable, field variable, instance variable, class variable.  These are the descriptors of.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
A Sample Program public class Hello { public static void main(String[] args) { System.out.println( " Hello, world! " ); }
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Fundamentals 2 1. Programs and Data Most programs require the temporary storage of data. The data to be processed is stored in a temporary storage in.
Object Oriented Programming Lecture 2: BallWorld.
M105 - Week 2 Chapter 3 Numerical Data 1 Prepared by: M105 Team - AOU - SAB.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Crash course in the Java Programming Language
Elementary Programming
Chapter 3 Java Input/Output.
Java Programming: From Problem Analysis to Program Design, 4e
OUTPUT STATEMENTS GC 201.
Program Style Console Input and Output
IDENTIFIERS CSC 111.
מבוא למדעי המחשב, סמסטר א', תשע"א תרגול מס' 2
Chapter 4: Mathematical Functions, Characters, and Strings
Chapter 4 – Fundamental Data Types
Introduction to Java Programming
An Introduction to Java – Part I, language basics
Chapter 2: Basic Elements of Java
בתרגול הקודם אתר הקורס (הודעות, פרטי סגל הקורס, עבודות, פורום, מערכת הגשת תרגילים וכו') שימוש בחלון ה-command, פקודות בסיסות קוד Java: הידור (= קומפילציה)
Fundamentals 2.
Chapter 2: Java Fundamentals
Java Basics.
Chapter 3 Input/Output.
Principles of Computer Science I
4.3 Arithmetic Operators and Mathematical Functions
Introduction to Computer Science and Object-Oriented Programming
Ch 5 : Mathematical Functions, Characters, and Strings
Presentation transcript:

Lecture Notes – Basics (Ch1-6) Yonglei Tao

A Class as Viewed by Its Client public class Die { … public Die (int s) { } public int cast () { Public interface and private implementation Encapsulation

Class Definition 1 import java.util.Random; 2 3 /** 3 /** 4 This class models a die that, when cast, lands on a random 5 face. 6 */ 7 public class Die 8 { 9 private Random generator; 10 private int sides; 11 12 /** 13 Constructs a die with a given number of sides. 14 @param s the number of sides, e.g. 6 for a normal die 15 */ 16 public Die(int s) 17 { 18 sides = s; 19 generator = new Random(); 20 } 21

Class Definition (Cont.) 22 /** 23 Simulates a throw of the die 24 @return the face of the die 25 */ 26 public int cast() 27 { 28 return 1 + generator.nextInt(sides); 29 } 30 }

Class Definition (Cont.) 1 /** 2 This program simulates casting a die ten times. 3 */ 4 public class DieSimulator 5 { 6 public static void main(String[] args) 7 { 8 Die d = new Die(6); 9 final int TRIES = 10; 10 for (int i = 1; i <= TRIES; i++) 11 { 12 int n = d.cast(); 13 System.out.print(n + " "); 14 } 15 System.out.println(); 16 } 17 }

Primitive and Reference Variables int num1 = 10, num2; // primitive variables num2 = num1 + 2; Rectangle box1; // reference variable box1 = new Rectangle (5, 10, 20, 30); Rectangle box2 = box1; box2.translate (10, 20);

Constant Definition Declared in a method final double NICKEL_VALUE = 0.05; Declared in a class public static final double LITERS_PER_GALON = 3.785;

Primitive Types Type Description Size int The integer type, with range -2,147,483,648 . . . 2,147,483,647 4 bytes byte The type describing a single byte, with range -128 . . . 127 1 byte short The short integer type, with range -32768 . . . 32767 2 bytes long The long integer type, with range -9,223,372,036,854,775,808 . . . 9,223,372,036,854,775,807 8 bytes double The double-precision floating-point type, with a range of about ±10308 and about 15 significant decimal digits float The single-precision floating-point type, with a range of about ±1038 and about 7 significant decimal digits char The character type, representing code units in the Unicode encoding scheme boolean The type with the two truth values false and true 1 bit

Cast Convert an expression from one type to another int num = 125; double bal; bal = num + 50; num = (int) bal; num = (int) (bal * 100) byte b1 = 1, b2 = 2; byte b3 = (byte) (b1 + b2);

Mathematical Methods Static methods Function Returns square root Math.sqrt(x) square root Math.pow(x, y) power xy Math.exp(x) ex Math.log(x) natural log Math.sin(x), Math.cos(x), Math.tan(x) sine, cosine, tangent (x in radians) Math.round(x) closest integer to x Math.min(x, y), Math.max(x, y) minimum, maximum

Class String A sequence of Unicode characters String s = “Hello”; char ch = s.charAt (2); s = “Goodbye”; System.out.println ( s.length() ); if ( s.equals(“Hello”) ) … int pos = s.indexOf(“e”); System.out.println ( s.substring(pos, pos+2) );

String Concatenation “Hello, “ + name int n = 5; String s = “Section “ + n Date now = Date(); String s = “Hello, “ + now; String sub = s.substring(0, 5); String input = “7”; int num = Integer.parseInt ( input );

The if Statement if ( condition ) a single or compound statement else

Testing Simple test Test for floating point values int a = 5, b = 10; if ( a == b ) … Test for floating point values double r = Math.sqrt(2); double d = r * r - 2; if (d == 0) System.out.println(“result is 0"); else System.out.println(“result is not 0 but " + d); Output ? result is not 0 but 4.440892098500626E-16

How to Compare? if Math.abs(d) < 0.001 then

Testing Test for reference equality s2 == s3 Test for value equality String s1 = new String(“abc”): String s2 = new String(“abc”); String s3 = s2; Test for reference equality s2 == s3 s1 == s2 s1 == null Test for value equality s1.equals (s2) boolean equals (Object other)

De Morgan’s Law ! ( A && B ) is the same as !A || !B

while Loops year = 0; while (balance < targetBalance) { double interest = balance * rate / 100; balance = balance + interest; years++; }

for Loops for (int i = 0; i < n; i++) { double interest = balance * rate / 100; balance = balance + interest; }

Read Input Scanner in = new Scanner (System.in); System.out.print (“Your age: “); int age = in.nextInt (); nextBoolean() hasNextBoolean() nextByte() hasNextByte() nextDouble() hasNextDouble() nextFloat() hasNextFloat() nextLong() hasNextLong() nextShort() hasNextShort() next() useDelimiter(“;")

Read Character with Scanner Scanner in = new Scanner (new File(“input.txt”)); while ( in.hasNextLine() ) { String line = in.nextLine(); char[ ] list = line.toCharArray(); for (char ch: list) // a for-each loop // process ch } Or String line = in.nextLine(); for (int i=0; i<line.length(); i++) // process line.charAt(i)

Keyboard Output Other format specifiers and flags System.out.println(“Your age is: “ + age); System.out.printf(“Your age is: %d \n“, age); System.out.printf(“Pi is %7.3f \n“, Math.Pi); Other format specifiers and flags %s, %c %s^ convert to upper case %d- left justified %f, show commas to separate each group of 3 digits %f+ include a sign %d( show negative values in parentheses

Documentation Comments /** A driver program for Greeter.java. It also shows java documentation comments.   @author Yonglei Tao, GVSU */ public class GreeterTest { public static void main(String[] args) { Greeter worldGreeter = new Greeter("World"); String greeting = worldGreeter.sayHello(); System.out.println(greeting); }

Documentation Comments /** A class for producing simple greetings. */   public class Greeter { private String name; Constructs a Greeter object that can greet a person or entity. @param aName the name of the person or entity who should be addressed in the greetings. @throws Exception in case of ... public Greeter(String aName) { name = aName; } Greet with a "Hello" message. @return a message containing "Hello" and the name of the greeted person or entity. public String sayHello() { return "Hello, " + name + "!";