Declaring Variables You must first declare a variable before you can use it! Declaring involves: – Establishing the variable’s spot in memory – Specifying.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Declaring Variables You must first declare a variable before you can use it! Declaring involves: – Establishing the variable’s spot in memory – Specifying.
CMT Programming Software Applications
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Basic Elements of C++ Chapter 2.
L EC. 02: D ATA T YPES AND O PERATORS (1/2) Fall Java Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
SOFTWARE TECHNOLOGY - I CONSTANTS VARIABLES DATA TYPES.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
Chapter 2: Java Fundamentals
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.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
 Character set is a set of valid characters that a language can recognise.  A character represents any letter, digit or any other sign  Java uses the.
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
COMP 110: Spring Announcements Lab 1 due Wednesday at Noon Assignment 1 available on website Online drop date is today.
Computer Programming with Java Chapter 2 Primitive Types, Assignment, and Expressions.
Java – Variables and Constants By: Dan Lunney. Declaring Variables All variables must be declared before they can be used A declaration takes the form:
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
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.
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 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
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.
1.  Algorithm: 1. Read in the radius 2. Compute the area using the following formula: area = radius x radius x PI 3. Display the area 2.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter Topics The Basics of a C++ Program Data Types
Java Variables and Types
Elementary Programming
Yanal Alahmad Java Workshop Yanal Alahmad
Basic Elements of C++.
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Basic Elements of C++ Chapter 2.
IDENTIFIERS CSC 111.
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2: Basic Elements of Java
Chapter 2: Java Fundamentals
elementary programming
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

Declaring Variables You must first declare a variable before you can use it! Declaring involves: – Establishing the variable’s spot in memory – Specifying what kind of data it will contain (its type) – Give it a name (its identifier) – Optionally give it an initial value Note: A program may declare as many variables as it needs Example of Java declarations: – Statement to: Declare an integer variable: int grade; – Statement to: Declare an integer variable with a value: int count = 5; – Statement to: Declare two integer variables: int grade, count = 5; Questions: What are the identifiers, initial value, and type in the above examples? Definition: A variable is a place in memory that can hold a value Important Note: Equal does NOT mean equal, it means assign

Primitive Variable types (not objects) There are many data types in Java There is a reserved word for each Examples: Integers, Fractions, String, boolean, and character Integer variables – byte i = 100; (a byte variable holds values from -128 to 127) – int x = 32768; (an int variable holds values to billions) – long total = ; (a long variable holds up to quintillians) Fraction variables – float percentage; (float variables are accurate to six digits) – double distance; (double variables are accurate to fifteen digits) Boolean variables: boolean isBig = true; or boolean isBig = false; String variables are a sequences of letters – String name = “bill”; (Enclose your strings with double quotes) Character variable: char c = ‘3’; // A single letter Definition: A type specifies a kind of data Question: Why all the types? Answer: Different variable types are stored differently in memory

Reference Data Types (objects) String (The most used non-primitive data type) Definition: A string is a sequence of characters Examples – A String literal: "abcdef" – Declare/initialize a string: String s = new String("abcdef"); – Convenient way: String s = "abcdef“; Reference variables contain methods and properties – s.length(); // returns the length of the string – s.charAt(0); // returns the first character of the string – s.toUpperCase(); // returns withall letters as upper case – s.substring(3,8); // returns substring from position 3 to (not including) 8 Important Note: Character positions count from zero, not from one

Literals Definition: A literal is a constant that we do not have to declare. Examples: – String literal: “abcdef” – Integer literal: -10 – Fraction literal: – Character literal: ‘t’ – Boolean literal: true

Expressions and Casting Expression: – A sequence of operations and operators – Example: x + y / 3 + (4 + z)/a Java is fussy about expressions with different types of data Casting Example: – z becomes 0: int x = 5, y = 8; float z = x/y; – z becomes 0.625: int x=5, y=8; float z = (float)x/y Definition: To cast means to access a variable as if it were a different type

Widening and Narrowing It is legal to store a primitive (non-object) variable type of a smaller range to one of a wider range (widening) – Example: ling x = 3; int y = 2; x = y; – Example: double z = 3; int y = 2; z = y; Attempting to store a primitive variable of a wider range into one of a smaller range causes a compile error (narrowing) – Example: long x = 3; int y = 2; y = x; – Example: double z = 3; int y = 2; y = z; – One must cast to eliminate the error: y = (int)z;

Identifier names Rules – All identifiers start with an alphabetic letter or underscore – Subsequent letters of an identifier can be alphabetic letters, underscores, or numeric digits (No Spaces) – Identifiers cannot be a Java reserved word Conventions followed by most programmers – Keep the identifiers relatively short – Identifiers should be easy to remember – Naming conventions Variables: start lower case, and first letter of subequent words should be upper case (ex: salesTotal) Classes: First letter of every word upper clase (ex: MilesPerGal) Symbolic constants: public final int MAX = 100; Definition: An identifier is the name we give to a variable Note: the final modifier means that the variable cannot be altered.

Programming conventions It is important to keep your programs readable Most programmers will – Indent blocks of instructions by several spaces – Add comments to the top with name, date, programmer name, source file name, purpose, modification purpose and date – Add comments to the top of each method to include its purpose and for automatic documentation generation Example: /** main method calculate miles per gallon args command line arguments (unused) */ public static void main(String[] args) { String data = “I’m indented”; System.out.println(data); }

Concatenation Definition: concatenation is gluing strings together. – String s = “abc” + “def” puts “abcdef” in s – Numbers and Strings are different yields 77 “33” + “44” yields “3344” “33” / “44” generates an error – String s = “abc ” + 33 puts “abc 33” in s because Java makes the 33 into a string and then does concatenation – What does the following print? x = 32.95; System.out.println(“you earned $” + x + “dollars”); Note: Assign means do what is on the right of the equal sign and store in the variable on the left

Escape Sequences ( or Characters) Definition: An escape sequence is two letters starting with a backslash (\) that has special meaning to Java Purpose: To represent characters that are not able to easily be displayed in a program Examples: – System.out.println(“don’t worry\tbe happy”); – System.out.println(“first line\nsecond line”); – System.out.println(“He said, \”hi\””); – System.out.println(“\fclear screen or new page”);

Numbering systems Binary: each digit is 2 times the previous Octal: each digit is 8 times the previous Decimal: each digit is 10 times the previous Hexadecimal: each digit is 16 times the previous Problems: – Convert 110 to decimal if it is binary, octal, or hexadecimal. – Convert: If FCA is a hexadecimal number, convert it to binary

Scope and Life Scope: – Where in a program can a variable can be accessed – A variable’s scope is from its declaration to the end of the block Life: – When memory for a variable is assigned for that variable – Variables live within the block where they are declared. Programming conventions: – limit scope as much as possible – This convention will result in less errors and make programs easier to maintain Example {// Outer block // Next instruction fails System.out.println(outer); int outer = 1; { // inner block int inner = 2; // The next is OK System.out.println (outer+inner); } // End of outer block // Next instruction fails System.out.println(inner); // Next instruction is OK. System.out.println(outer); }// End of outer block Block: the instructions within braces { }

Formatting Output import java.text.NumberFormat; import java.text.DecimalFormat; public class FormatTest { public static void main(String[] args) { System.out.print("Input args: " + args[0] + "/"); System.out.println(args[1]); System.out.println(); // Skip a line System.out.println("input args:" + args[0] + "/" + args[1] + "\n"); double v0 = Double.parseDouble(args[0]), v1 = Double.parseDouble(args[1]); System.out.printf("%-7s = %8.2f/%5.2f\n\n", "Printf", v0, v1); NumberFormat currency = NumberFormat.getCurrencyInstance(); System.out.println( "Currency: " + currency.format(v0) + "/" + currency.format(v1) + "\n"); DecimalFormat dec = new DecimalFormat("###0.0##"); DecimalFormat pct = new DecimalFormat("0.##%"); System.out.println( "Decimal: " + dec.format(v0) + "/" + pct.format(v1)); } }// End of FormatTest class

Formatting Strings for Output public class FormatExample { public static void main(String[] args) { String str = String.format("Cost: $%7.2f\n",35.23); str += String.format("Cost: $%-7.2f\n",35.23); str += String.format("Cost: $%.2f\n",35.23); str += String.format("Integer: $%4d\n",100); str += String.format("Left Justified:%-10s\n","Dan"); str += String.format("Right Justified:%10s\n","Dan"); str += String.format("All %.2f %d %-10s\n", 35.23, 100, "Dan"); JOptionPane.showMessageDialog(null, str); } }

Input from Keyboard // Import the correct package Import java.util.Scanner // Instantiate a an object from the Scanner class Scanner sc = new Scanner(System.in); // Input the appropriate kind of data int intData = sc.nextInt(); Long longData = sc.nextLong(); Double doubleData = sc.nextDouble(); String stringData = sc.nextLine(); From command line – Not for GUI point and click systems

Inputting Data: More GUI Friendly On the class web-site there is a java class called IO – Download by right clicking on the hyperlink – Store it in your lab folder so it can be used – Compile the.java file to make it useable We can use methods in this class to do input Examples: – int data = IO.readInt(“Enter a grade: ”); – String str = IO.readString(“Enter your name: ”); – double value = IO.readDouble(“Enter sales total:” );

Putting it all together import javax.swing.*; public class Average { public static final int NUM = 3; public static void main(String[] args) { int x = IO.readInt(“enter first: ”); int y = IO.readInt(“enter second: ”); int z = IO.readInt(“enter third: ”); double average = ((double)x + y + z)/NUM; JOptionPane.showMessageDialog (null, “The average is “ + average); } // End of main() method } // End of Average class

What prints? int x = 3; int y = x + 4; x = x + 2; x = x/2; int z = x + 2; String s = " abc " ; System.out.println(s+x + y + z); Remember: instructions execute one by one, in order

Review What is a data type? What is its purpose? Give some examples? What does it mean to cast? What is precision? Give some examples? What is the difference between a variable and an identifier? What is a symbolic constant? Why are they desirable? Can you declare a double and int in the same statement? Why or why not? How would you describe hexadecimal to someone without a clue? What is the difference between the scope and life of a variable? How are {} used in Java? How is ; used in Java? How is [] used? What does static mean? How about public and private? What is an escape sequence? What is concatenation? What are the programming conventions for naming variables, for indenting, and for commenting?