Chapter 2: Java Fundamentals cont’d

Slides:



Advertisements
Similar presentations
Chapter 8: Arrays.
Advertisements

CSci 1130 Intro to Programming in Java
COMP 14 Introduction to Programming
Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
Computer Programming w/ Eng. Applications
 Base “primitive” types: TypeDescriptionSize intThe integer type, with range -2,147,483, ,147,483,647 4 bytes byteThe type describing a single.
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Self Check 1.Which are the most commonly used number types in Java? 2.Suppose x is a double. When does the cast (long) x yield a different result from.
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Chapter 2 Elementary Programming
Chapter 2 JAVA FUNDAMENTALS CONT’D
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Introduction to C Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Chapter 2 - Introduction to Java Applications
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Primitive Data Types byte, short, int, long float, double char boolean Are all primitive data types. Primitive data types always start with a small letter.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 5a: Input and.
Chapter 2 - Introduction to Java Applications
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.
Chapter 2: Introduction to C++.
Introduction to C Programming
JOptionPane class. Dialog Boxes A dialog box is a small graphical window that displays a message to the user or requests input. A variety of dialog boxes.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Input, Output, and Processing
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.
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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 2 - Introduction to Java Applications Outline 2.1Introduction 2.2A Simple Program: Printing a.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Data Types and Statements MIT 12043: Fundamentals of Programming Lesson 02 S. Sabraz Nawaz Fundamentals of Programming by
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Java Fundamentals Part Integer Division Division can be tricky. In a Java program, what is the value of 1/2? You might think the answer is.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
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.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING String and Scanner Objects.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
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.
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.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
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.
2.5 Another Java Application: Adding Integers
Multiple variables can be created in one declaration
Chapter 2 Edited by JJ Shepherd
Chapter 2 - Introduction to Java Applications
elementary programming
In this class, we will cover:
Chapter 2: Java Fundamentals cont’d
Just Enough Java 17-May-19.
Chapter 2 Primitive Data Types and Operations
JOptionPane class.
Chapter 2: Java Fundamentals cont’d
Presentation transcript:

Chapter 2: Java Fundamentals cont’d

Outline 2.1 The Parts of a Java Program 2.2 The print and println Methods, and the Java Standard Class Library 2.3 Variables and Literals 2.4 Primitive Data Types 2.5 Arithmetic Operators 2.6 Combined Assignment Operators 2.7 Conversion Between Primitive Types 2.8 Creating Named Constants with final 2.9 The String Class 2.10 Scope 2.11 Comments 2.12 Programming Style 2.13 Reading Keyboard Input 2.14 Dialog Boxes 2.15 Common Errors to Avoid

The % operator Returns the remainder of the division Examples;

Exercise Write the following in a Java file: double amount = 137/5; System.out.println(“Amount is : “ + amount ); amount = 137.0/5;

Integer Division Dividing an integer by an integer gives an integer  the remainder is ignored Examples: 5/4 is 1 17/3 is 5

Operator Precedence What is the result of: Polynomial = 1+2*3+ 6/2 -2; Is it ? (1+2)*3 + 6/(2-2) 1+(2*3) +(6/2)-2 (1+2)*3 + (6/2)-2

Precedence Rules Always evaluate * , / and % before + and – Always negate before any calculations *, / and % have same precedence + and – have same precedence If equal precedence then evaluate from left to right except for negations where we evaluate from right to left

Precedence examples Polynomial = 1+2*3+ 6/2 – 2; Polynomial has the value of 1+6+3-2=8 Polynomial = –1 + 5 – 2; // 2 Polynomial = –(–3) + –(–5); //8

Grouping with parentheses You can use parentheses to force the evaluation of a formula Examples: x * ( y + z*z ) instead of x*y + z*z x * ( y * ( z + 165 ) + 85 ) – 65 Average = (a +b +c ) /3;

The Math class value = Math.pow( x,y); // now value holds x to the power of y value = Math.sqrt( x); //now value holds the square root of x

Combined Assignment Operators += x += 1; x = x + 1; –= x –= 1; x = x – 1; *= x *= 1; x = x * 1; /= x /= 1; x = x / 1; %= x %= 1; x = x % 1;

Operator Precedence What is the result of: Polynomial = 1+2*3+ 6/2 -2; Is it ? (1+2)*3 + 6/(2-2) 1+(2*3) +(6/2)-2 (1+2)*3 + (6/2)-2

Precedence Rules Always evaluate * , / and % before + and – Always negate before any calculations *, / and % have same precedence + and – have same precedence If equal precedence then evaluate from left to right except for negations where we evaluate from right to left

Precedence examples Polynomial = 1+2*3+ 6/2 – 2; Polynomial has the value of 1+6+3-2=8 Polynomial = –1 + 5 – 2; // 2 Polynomial = –(–3) + –(–5); //8

Grouping with parentheses You can use parentheses to force the evaluation of a formula Examples: x * ( y + z*z ) instead of x*y + z*z x * ( y * ( z + 165 ) + 85 ) – 65 Average = (a +b +c ) /3;

The Math class value = Math.pow( x,y); // now value holds x to the power of y value = Math.sqrt( x); //now value holds the square root of x

Combined Assignment Operators += x += 1; x = x + 1; –= x –= 1; x = x – 1; *= x *= 1; x = x * 1; /= x /= 1; x = x / 1; %= x %= 1; x = x % 1;

2.7 Conversion between Primitive Data Types Before a value is stored in a variable, Java checks the Data Type of the value and the variable If the data types are compatible then Java performs the conversion automatically  No Error If the data types are not compatible then Java issues an error.

2.7 Conversion between Primitive Data Types A widening conversion is the conversion of a small value to a larger one A narrowing conversion is the conversion of a large value to a smaller one double largest float long int short byte smallest

Widening conversion Example 1: Example 2: double x; int y = 10; x = y; int x; short y =2; x= y;

Narrowing Conversion We have to perform casting i.e. the name of the smaller data type is put in parentheses in front of the value Example: int number; double pi = 3.14; number = (int) pi;

Cast operator Used to convert from one primitive data type to another Must be used for narrowing conversions

Example: int pies = 10, people = 4; double piesPerPerson; piesPerPerson = pies /people; piesPerPerson =(double) pies/people; piesPerPerson =pies/(double) people; piesPerPerson=(double)(pies/people); (double)(10/4) = (double)(2) = 2.0 because it is an integer division 10/4 = 2 because it is an integer division 10.0/4 = 2.5 because one of the numbers is a double 10/4.0 = 2.5 because people is double

Mixed Integer Operations The result of an arithmetic operation that involves only byte, short, or int variables is always an int even if both variables are of data type short or byte Example: short x =5, y =7; short z = x+y; // this statement gives an error short z = (short) ( x+y ); //correct

Mixed Integer Operations If one of the operator’s operands is a double then the result of the operation is a double If one of the operator’s operands is a float then the result of the operation is a float If one of the operator’s operands is a long then the result of the operation is a long

Creating named constants with final A named constant is a variable whose value is read-only and cannot be changed To create a named constant add the word final to declaration An initialization value is required when declaring a constant Example: final double INTEREST_RATE = 0.069;

More about named constants When naming a constant, the variable name should be written in all uppercase characters. Math.PI is a constant that holds the value of pi ( i.e. 3.14159 …) Math.PI is already declared and initialized so it ready to use. Example: double area = Math.PI * radius * radius ;

The String class A String literal is any text enclosed in quotations A String is the DataType of a variable that can store String literals Example of a String variable: String name = “CS 0007”; System.out.println( name );

The String class To determine how many letters are stored in a String variable (name) use name.length(); Example: String mycourse = “CS 0007”; int number = mycourse.length();

String methods charAt(index) index is an integer and specifies the character position in the String This method returns the character at the specified position Example: char letter; String myText = “This is my Text”; letter = myText.charAt(8);

T h i s m y e x t String methods myText.length returns 15 because there are 15 characters T h i s m y e x t 1 2 3 4 5 6 7 8 9 10 11 12 13 14 myText.charAt(8) returns m because m is the letter at position 8

String methods toLowerCase() This method returns a new String that has all of the characters of the original String but in lowercase Example: String bigName = “I am BIG!!”; String smallName = bigName.toLowerCase(); // now smallName holds “i am big!!”

String methods toUpperCase() Same as toLowerCase() but it converts all the characters to uppercase Example: String smallName = “I am Big!!”; String bigName = smallName.toUpperCase(); // now bigName holds “I AM BIG!!”

Example: String message = "Java is Great Fun!"; String upper = message.toUpperCase(); String lower = message.toLowerCase(); char letter = message.charAt(2); int stringSize = message.length(); System.out.println(message); System.out.println(upper); System.out.println(lower); System.out.println(letter); System.out.println(stringSize);

Scope The variable scope is the part of the program that has access to it public class Scope { public static void main(String[] args) System.out.println(value); // ERROR! int value = 100; }

Scope public class Scope { public static void main(String[] args){ int number = 100; System.out.println(number); int number = 200; //ERROR }

Comments Java provides three methods for commenting code. // Single line comment. Anything after the // on the line will be ignored by the compiler. /* … */ Block comment. Everything beginning with /* and ending with the first */ will be ignored by the compiler. This comment type cannot be nested. /** … */ Javadoc comment. This is a special version of the previous block comment that allows comments to be documented by the javadoc utility program. Everything beginning with the /** and ending with the first */ will be ignored by the compiler. This comment type cannot be nested.

Programming Style Although Java has a strict syntax, whitespace characters are ignored by the compiler. The Java whitespace characters are: space tab newline carriage return form feed

Programming Style public class Compact {public static void main(String[] args){int shares=220; double averagePrice=14.67; System.out.println("There were "+shares+" shares sold at $"+averagePrice+ " per share.");}} Compiles !!!

Indentation Programs should use proper indentation. Each block of code should be indented a few spaces from its surrounding block. Two to four spaces are sufficient

Programming Style /** This example is much more readable than Compact.java. */ public class Readable { public static void main(String[] args) int shares = 220; double averagePrice = 14.67; System.out.println("There were " + shares + " shares sold at $" + averagePrice + " per share."); }

Dialog Boxes A dialog box is a small graphical window that displays a message to the user or requests input. A variety of dialog boxes can be displayed using the JOptionPane class. Two of the dialog boxes are: Message Dialog - a dialog box that displays a message. Input Dialog - a dialog box that prompts the user for input.

Using the import Statement The JOptionPane class is not automatically available to your Java programs. The following statement must be before the program’s class header: import javax.swing.JOptionPane; This statement tells the compiler where to find the JOptionPane class. 

Dialog Boxes The JOptionPane class provides static methods to display each type of dialog box.

Message Dialogs JOptionPane.showMessageDialog method is used to display a message dialog. JOptionPane.showMessageDialog(null, "Hello World"); The second argument is the message that is to be displayed.

Input Dialogs An input dialog is a quick and simple way to ask the user to enter data. The dialog displays a text field, an Ok button and a Cancel button. If Ok is pressed, the dialog returns the user’s input. If Cancel is pressed, the dialog returns null.

Input Dialogs String name; name = JOptionPane.showInputDialog( "Enter your name."); The argument passed to the method is the message to display. If the user clicks on the OK button, name references the string entered by the user. If the user clicks on the Cancel button, name references null.

NamesDialog.java import javax.swing.JOptionPane; public class NamesDialog { public static void main(String[] args) String firstName; // The user's first name String middleName; // The user's middle name String lastName; // The user's last name // Get the user's first name firstName = JOptionPane.showInputDialog("What is " + "your first name? ");

NamesDialog.java // Get the user's middle name. middleName = JOptionPane.showInputDialog( "What is " + "your middle name? "); // Get the user's last name. lastName = JOptionPane.showInputDialog("What is " + "your last name? ");

Example // Display a greeting JOptionPane.showMessageDialog(null, "Hello " + firstName + " " +middleName + " " + lastName); System.exit(0); }

The System.exit() Method A program that uses JOptionPane does not automatically stop executing when the end of the main method is reached. Java generates a thread, which is a process running in the computer, when a JOptionPane is created. If the System.exit method is not called, this thread continues to execute.

The System.exit() Method The System.exit method requires an integer argument. System.exit(0); This argument is an exit code that is passed back to the operating system. This code is usually ignored, however, it can be used outside the program: to indicate whether the program ended successfully or as the result of a failure. The value 0 traditionally indicates that the program ended successfully.

Converting a String to a Number The JOptionPane’s showInputDialog method always returns the user's input as a String String containing a number, such as “127.89, can be converted to a numeric data type.

The Parse Methods Parse methods convert strings to numeric data types They are: Byte.parseByte Integer.parseInt Short.parseShort Long.parseLong Float.parseFloat Double.parseDouble

The Parse Methods- Examples byte bVar = Byte.parseByte("1"); int iVar = Integer.parseInt("2599"); short sVar = Short.parseShort("10"); long lVar = Long.parseLong("15908"); float fVar = Float.parseFloat("12.3"); double dVar = Double.parseDouble("7945.6");

PayrollDialog.java import javax.swing.JOptionPane; public class PayrollDialog { public static void main(String[] args) String inputString; // For reading input String name; // The user's name int hours; // The number of hours worked double payRate; // The user's hourly pay rate double grossPay; // The user's gross pay

PayrollDialog.java // Get the user's name. name = JOptionPane.showInputDialog("What is " + "your name? "); // Get the hours worked. inputString = JOptionPane.showInputDialog( "How many hours” + “ did you work this week? "); // Convert the input to an int. hours = Integer.parseInt(inputString);

PayrollDialog.java // Get the hourly pay rate. inputString = JOptionPane.showInputDialog("What is” + " your hourly pay rate? "); // Convert the input to a double. payRate = Double.parseDouble(inputString); // Calculate the gross pay. grossPay = hours * payRate;

PayrollDialog.java // Display the results. JOptionPane.showMessageDialog(null, "Hello " + name + ". Your gross pay is $" + grossPay); // End the program. System.exit(0); }