CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Fall 2014.

Slides:



Advertisements
Similar presentations
Chapter 2: Java Fundamentals cont’d
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
Chapter 2 - Introduction to Java Applications
Chapter 2: Using Data.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
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.
Introduction to Computers and Programming Lecture 3: Variables and Input Professor: Evan Korth New York University.
Outline Java program structure Basic program elements
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.
Chapter 2 - Introduction to Java Applications
Fundamental data types Horstmann Chapter 4. Constants Variables change, constants don't final = ; final double PI = ; … areaOfCircle = radius *
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.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Source Code: Chapters 1 and 2
Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.
The Java Programming Language
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.
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
Chapter 2 Elementary Programming
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
CIT 590 Intro to Programming First lecture on Java.
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.
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.
 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.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
A variable is a storage location for some type of value. days 102 taxrate 7.75 int days = 102; double taxrate = 7.75; char grade = ‘A’; boolean done.
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.
Ihsan Ayyub Qazi Introduction to Computer Programming Recitation 3 Ihsan Ayyub Qazi.
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING String and Scanner Objects.
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
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.
IAS 1313: OBJECT ORIENTED PROGRAMMING Week 3: Data Type, Control Structure and Array Prepared by: Mrs Sivabalan1.
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
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.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
INTERMEDIATE PROGRAMMING USING JAVA
Crash course in the Java Programming Language
Elementary Programming
Chapter 2 Elementary Programming
Message, Input, Confirm, and Specialized Dialogs
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
IDENTIFIERS CSC 111.
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Chapter 2 - Introduction to Java Applications
Message, Input, and Confirm Dialogs
The System.exit() Method
Dr. Sampath Jayarathna Cal Poly Pomona
Chapter 2: Java Fundamentals cont’d
JOptionPane class.
Chapter 2: Java Fundamentals cont’d
Presentation transcript:

CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Fall 2014

Chapter 2 Presentation Outline Compiling and running our first Java program Using Notepad and command lines Using Netbeans Exploring Netbeans main features Start our Java Journey Reserved Keywords Identifiers Naming Convention Literals Variables and primitive data types Data type sizes Casting variables

Chapter 2 Presentation Outline (continued) The Java API Math Class String Class Variable Scope Program Style Ways of input data into your program Converting/Parsing data

Computing how much you will earn in a week of work $25 per hour40 hours a week How to compute the weekly income in this specific case?

Our First Java Code public class Payroll { public static void main(String[] args) { int hours = 40; double grossPay, payRate = 25.0; grossPay = hours * payRate; System.out.println(“Your gross pay is S” + grossPay); } See Payroll.java

Our First Java Code Remember, we need to compile our code to be able to run it!

Manually Compiling a Java code Compiling the java code: javac Filename Example: Payroll.java will be “translated to” Payroll.class (bytecode) Payroll.class will be the one to be sent to the JVM

Running the java class Running the java code: java Filename Example: java Payroll

Exploring NetBeans Creating the same java program in the IDE Explaining the source code that it generates for you Placing a print command Placing two variables Understanding how the IDE helps you to find errors Debugging your code Executing the code

First Program in Netbeans

Java Identifiers Identifiers are the names of the variables, methods, classes, packages, and interfaces Identifier Rules:  Must be composed of :  letters  numbers  underscore _  dollar sign $  Identifiers may only begin with :  a letter  the underscore  dollar sign

Examples of Identifiers Valid Identifiers: MyVariable myvariable MYVARIABLE x i _myvariable $myvariable _9pins andros ανδρος Oreilly Invalid Identifiers: My Variable 9pins a+c testing1-2-3 O'Reilly OReilly_&_Associates

The Java keywords abstractcontinuefornewswitch assertdefaultgotopackagesynchronized booleandoifprivatethis breakdoubleimplementsprotectedthrow byteelseimportpublicthrows caseenuminstanceofreturntransient catchextendsintshorttry charfinalinterfacestaticvoid classfinallylongstrictfp ** volatile const * floatnativesuperwhile

Naming Convention Class names always start with upper case letters and the rest in lower case: Example:public class Bicycle Method names always start with lower case letters Example: private void evaluate() Variable names always start with lower case: Example:int number = 10;

Naming Convention (continuation) Names that contain two or more words, we capitalize the initial of the words as follows: For classes:public class RacingBikes For methods:private void calculateAnnualTax() For variables:int numberOfKeys = 10;

Java Literals Literals are constant values in a program. Literals represent numerical (integer or floating-point), character, boolean or string values. Integer literals: Floating-point literals: Character literals: '(' 'R' 'r' '{‘ Boolean literals: true false String literals: "language" "0.2" "r" ""

Data types Handling more efficiently the computer resources (memory, hard-disk, etc.) Working/Manipulating different data types Why should we care about data types?

There is always a limit of how much memory a laptop has. It depends on its configuration.

Handling more efficiently the computer resources Booleans Integers floats Strings Doubles Chars Objects

Primitive data types byte: The byte data type is an 8-bit signed integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). short: The short data type is a 16-bit signed integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). int: The int data type is a 32-bit signed integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). long: The long data type is a 64-bit signed. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).

Variables and primitive data types float: The float data type is a single-precision 32-bit IEEE 754 floating point. double: The double data type is a double-precision 64-bit IEEE 754 floating point. boolean:The boolean data type has only two possible values: true and false. char:The char data type is a single 16-bit Unicode character

Variables and data types int weekDays = 7; So how do we tell our program to pick up the right box size???

Handling more efficiently the computer resources I though that I was going to do a Kitchen advertisement…

Data Transfer over the internet Another problem in having all variables defined as double: Your program will be bigger in size and the bigger your program is the more it takes to be downloaded/transferred over the internet

Be careful when handling variables of different types Small types can fit on bigger types Example: int a = 10; double b; b = a; Big types do not fit in small variables Example: double b = 10.5; int a; a = b; However, sometimes we can make it fit! We can use casting to fit one big value into a small variable Example: double b = 10.9; int a; a = (int) b;

An alternative ending for Cinderella story… Now that I am using the Java casting feature, her shoes fit like a glove…

There are lots of more information about variables in the textbook! Please take a look!

Java APIs Show JAVA API documentation on the internet

An Example of Using the API Let’s make a Java code that computes the length of a hypotenuse (side “c”) of a right angle triangle, based on the triangle sides “a” and “b” What is the equation to compute c?

Java Math Class In Google, search for Java API Math: Let’s understand what the documentation is telling us about the methods input arguments and returning values

The Program Source Code import java.lang.*; public class HypotenuseCalculator { public static void main(String[] args) { double a = 3; double b = 4; double c; c = Math.sqrt( Math.pow(a,2) + Math.pow(b,2)); System.out.println(c); } } See HypotenuseCalculator.java

The String Class // A simple program demonstrating String objects. public class StringDemo { public static void main(String[] args) { String greeting = "Good morning "; String name = "Herman"; System.out.println(greeting + name); } }

// This program demonstrates a few of the String methods. public class StringMethods { public static void main(String[] args) { 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); } } See StringMethods.java

Scope public class Scope { public static void main(String[] args) { int x; // known to all code withing the main x = 10; if (x == 10) { int y = 20; // known only to this IF block System.out.println("The value of x is: " + x + " the value of y is: " + y); } System.out.println("The value of x is: " + x ); System.out.println("The value of y is: " + y ); } } See Scope.java

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.");}} 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."); }

Ways of entering data into your program How did we enter the sides of the triangle in our Pythagoras program?

import java.lang.*; public class PythagoreanTheorem { public static void main(String[] args) { double a = 3; double b = 4; double c; c = Math.sqrt(Math.pow(a,2)+Math.pow(b,2)); System.out.println(c); } } That’s what we call “hard-coded” values Is there any other way to input data?

Let’s play Family Feud Game

What are the most common ways of entering data into a program?

Hard-coded inputs import java.lang.*; public class PythagoreanTheorem { public static void main(String[] args) { double a = 3; double b = 4; double c; c = Math.sqrt(Math.pow(a,2)+Math.pow(b,2)); System.out.println(c); } } Good or bad? Math.PI

The main(String[] args) public static void main(String[] args) { double a = Double.parseDouble(args[0]); double b = Double.parseDouble(args[1]); double c = Math.sqrt(Math.pow(a,2) + Math.pow(b,2)); System.out.println("Value of c: " + c); } What does “args” stand for? But what arguments???

The main(String[] args) Arguments from the command line

Setting up args[ ] in Netbeans

The Scanner Class To read input from the keyboard we can use the Scanner class. The Scanner class is defined in java.util, so we will use the following statement at the top of our programs: import java.util.Scanner;

The Scanner Class Scanner objects work with System.in To create a Scanner object: Scanner keyboard = new Scanner(System.in); Google for “Java Scanner Documentation” See example: Payroll2.javaPayroll2.java

Getting data from a text file Your program must process this data This data is saved in a text file There are 1000 lines to process It is inefficient to type them in the command line!

Getting data from a text file BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt")); String line = null; while ((line = reader.readLine()) != null) { // do whatever you need with the data here } fr = new FileReader("data.txt"); Scanner fromFile = new Scanner(fr); String line; while(fromFile.hasNextLine()) { line = fromFile.nextLine(); String[] dataListInStringFormat = line.split(","); for (String dataItem : dataListInStringFormat) { sum += Double.parseDouble(dataItem.trim()); }

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. The JOptionPane class provides methods to display each type of dialog box.

The JOptionPane Class

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.

Converting a String to a Number The JOptionPane’s showInputDialog method always returns the user's input as a String Names are Strings, so we are ok here Numbers are not Strings! Is it a problem?

This is John! You can chat and interact with this person This is John’s picture! You cannot chat with it! Even though they look the same, they are two different things! You cannot interact with John’s picture as you would with the actual John!

Converting a String to a Number Similarly, a String representing a number is NOT the same as a number! You cannot do math operations on a “picture” of a number You MUST convert the String representation to an actual number!

The Parse Methods // Store 1 in bVar. byte bVar = Byte.parseByte("1"); // Store 2599 in iVar. int iVar = Integer.parseInt("2599"); // Store 10 in sVar. short sVar = Short.parseShort("10"); // Store in lVar. long lVar = Long.parseLong("15908"); // Store 12.3 in fVar. float fVar = Float.parseFloat("12.3"); // Store in dVar. double dVar = Double.parseDouble("7945.6"); See example: PayrollDialog.java

Any Questions? 81

Homework / lab work Lab 01 Homework 01