Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Types, Variables and Operators Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2013.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
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.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
Shlomo Hershkop1 Introduction to java Class 1 Fall 2003 Shlomo Hershkop.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 Primitive Data.
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.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
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.
COMP 14: I/O and Boolean Expressions May 24, 2000 Nick Vallidis.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
1 Course Lectures Available on line:
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
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 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
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.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA TYPES AND OPERATIONS.
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.
CPS120: Introduction to Computer Science Operations Lecture 9.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
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.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 3.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Operators.
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.
Programming Principles Operators and Expressions.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
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.
CompSci 230 S Programming Techniques
Chapter 2 Basic Computation
Lecture 3 Java Operators.
Introduction to Computer Science / Procedural – 67130
Lecture 2: Data Types, Variables, Operators, and Expressions
2.5 Another Java Application: Adding Integers
Primitive Data, Variables, Loops (Maybe)
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Basic Computation
Introduction to Programming in Java
Introduction to C++ Programming
Fundamentals 2.
Expressions and Assignment
Chapter 2 Programming Basics.
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Primitive Types and Expressions
Just Enough Java 17-May-19.
Introduction to C Programming
Presentation transcript:

Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011

Reference Variables Rommel AB Palomino - UDC Spring 20112

Reference Variables vs. Primitive Variables Two types of variables in Java:  Primitive Variables  Reference Variables Primitive Variables  variables with primitive data types.  stores data in the actual memory location of where the variable is

Reference Variables vs. Primitive Variables Reference Variables  variables that stores the address in the memory location  points to another memory location where the actual data is  When you declare a variable of a certain class, you are actually declaring a reference variable to the object with that certain class.

Example Suppose we have two variables with data types int and String. int num = 10; String name = "Hello"

Example The picture shown below is the actual memory of your computer, wherein you have the address of the memory cells, the variable name and the data they hold.

Operators Different types of operators:  arithmetic operators  relational operators  logical operators  conditional operators These operators follow a certain kind of precedence so that the compiler will know which operator to evaluate first in case multiple operators are used in one statement.

Arithmetic Operators

Arithmetic Operators: Sample Program 1 //a few numbers 2 int i = 37; 3 int j = 42; 4 double x = ; 5 double y = 7.22; 6 System.out.println("Variable values..."); 7 System.out.println(" i = " + i); 8 System.out.println(" j = " + j); 9 System.out.println(" x = " + x); 10 System.out.println(" y = " + y); 11//Adding numbers 12System.out.println("Adding..."); 13 System.out.println(" i + j = " + (i + j)); 14 System.out.println(" x + y = " + (x + y));

Arithmetic Operators: Sample Program 15 //subtracting numbers 16 System.out.println("Subtracting..."); 17 System.out.println(" i - j = " + (i – j)); 18 System.out.println(" x - y = " + (x – y)); 19 //multiplying numbers 20 System.out.println("Multiplying..."); 21 System.out.println(" i * j = " + (i * j)); 22 System.out.println(" x * y = " + (x * y));

Arithmetic Operators: Sample Program 15 //dividing numbers 16 System.out.println("Dividing..."); 17 System.out.println(" i / j = " + (i / j)); 18 System.out.println(" x / y = " + (x / y));

Arithmetic Operators: Sample Program 29 //computing the remainder 30 System.out.println("Computing the remainder..."); 31 System.out.println(" i % j = " + (i % j)); 32 System.out.println(" x % y = " + (x % y)); 33 //mixing types 34 System.out.println("Mixing types..."); 35 System.out.println(" j + y = " + (j + y)); 36 System.out.println(" i * x = " + (i * x));

Arithmetic Operators: Sample Program Output Variable values... i = 37 j = 42 x = y = 7.22 Adding... i + j = 79 x + y = Subtracting... i - j = -5 x - y = Multiplying... i * j = 1554 x * y = Dividing... i / j = 0 x / y = Computing the remainder... i % j = 37 x % y = Mixing types... j + y = i * x =

Arithmetic Operators Note:  When an integer and a floating-point number are used as operands to a single arithmetic operation, the result is a floating point. Integer + floating point = floating point  The integer is implicitly converted to a floating- point number before the operation takes place.

Increment and Decrement Operators unary increment operator (++) unary decrement operator ( - - ) Increment and decrement operators increase and decrease a value stored in a number variable by 1.

Increment and Decrement Operators (cont’d) Rommel AB Palomino - UDC Spring Increment the value of count by 1 count=count + 1;  count++; Decrement the value of count by 1 count=count - 1;  count--;

Increment and Decrement Operators (cont’d)

The increment and decrement operators can be placed before or after an operand. When used before an operand, it causes the variable first to be incremented or decremented by 1, and then the new value is used in the expression in which it appears.

Increment and Decrement Operators (cont’d) For example: int i = 10 int j = 3; int k = 0; k = ++j + i; //will result to k = 4+10 = 14

Increment and Decrement Operators (cont’d) When the increment and decrement operators are placed after the operand, the old value of the variable will be used in the expression where it appears. Then, it will be either incremented or decremented by 1.

Increment and Decrement Operators (cont’d) Rommel AB Palomino - UDC Spring For example: int i = 10; int j = 3; int k = 0; k = j++ + i; //will result to k = 3+10 = 13

Increment and Decrement Operators: Coding Guidelines Always keep expressions containing increment and decrement operators simple and easy to understand.

Relational Operators Relational operators compare two values and determines the relationship between those values. The output of evaluation are the boolean values true or false.

Relational Operators (cont’d) Rommel AB Palomino - UDC Spring

Relational Operators: Sample Program 1//a few numbers 2int i = 37; 3int j = 42; 4int k = 42; 5System.out.println("Variable values..."); 6System.out.println(" i = " +i); 7System.out.println(" j = " +j); 8System.out.println(" k = " +k); 9//greater than 10System.out.println("Greater than..."); 11System.out.println(" i > j = “ + ( i > j ) ); //false 12System.out.println(" j > i = “ + ( j > i ) ); //true 13System.out.println(" k > j = "+ ( k > j ) ); //false

Relational Operators: Sample Program 16 //greater than or equal to 17 System.out.println("Greater than or equal to..."); 18 System.out.println(" i >= j = "+ ( i >= j ) );//false 19 System.out.println(" j >= i = "+ ( j >= i ) );//true 20 System.out.println(" k >= j = "+( k >=j ) );//true 17 //less than 18 System.out.println("Less than..."); 19 System.out.println(" i < j = "+ ( i < j ) );//true 20 System.out.println(" j < i = "+ ( j < i ) );//false 21 System.out.println(" k < j = "+( k < j ) );//false

Relational Operators: Sample Program 27//less than or equal to 28System.out.println("Less than or equal to..."); 29 System.out.println(" i <= j = “ + ( i <= j ) );//true 30System.out.println(" j <= i = “ + ( j <= i ) );//false 31System.out.println(" k <= j = “ + ( k <= j ) );//true 32//equal to 33System.out.println("Equal to..."); 34System.out.println(" i == j = " + ( i == j ) );//false 35System.out.println(" k == j = " + ( k == j ) );//true

Relational Operators: Sample Program 27//not equal to 28System.out.println("Not equal to..."); 29System.out.println(" i != j = " + ( i! = j ) );//true 30System.out.println(" k != j = " + ( k! = j ) );//false

Relational Operators: Sample Program Output Variable values... i = 37 j = 42 k = 42 Greater than... i > j = false j > i = true k > j = false Greater than or equal to... i >= j = false j >= i = true k >= j = true Less than... i < j = true j < i = false k < j = false Less than or equal to... i <= j = true j <= i = false k <= j = true Equal to... i == j = false k == j = true Not equal to... i != j = true k != j = false

Logical Operators Logical operators have one or two boolean operands that yield a boolean result. There are six logical operators:  && (logical AND)  & (boolean logical AND)  || (logical OR)  | (boolean logical inclusive OR)  ^ (boolean logical exclusive OR)  ! (logical NOT)

Logical Operators The basic expression for a logical operation is: x1 op x2 where, x1, x2 can be boolean expressions, variables or constants op - is either &&, &, ||, | or ^ operator. The truth tables that will be shown next, summarize the result of each operation for all possible combinations of x1 and x2.

&&(boolean logical), &(logical) : AND Here is the truth table for && and &,

&&, & :AND (con’t) The basic difference between && and & operators :  && supports short-circuit evaluations (or partial evaluations), while & doesn't. Given an expression: exp1 && exp2  && will evaluate the expression exp1, and immediately return a false value if exp1 is false.  If exp1 is false, the operator never evaluates exp2 because the result of the operator will be false regardless of the value of exp2.  In contrast, the & operator always evaluates both exp1 and exp2 before returning an answer.

1int i = 0; 2 int j = 10; 3 boolean test= false; 4//demonstrate && 5 test = (i > 10) && (j++ > 9); 6 System.out.println(i); 7 System.out.println(j); 8 System.out.println(test); 9//demonstrate & 10 test = (i > 10) & (j++ > 9); 11 System.out.println(i); 12 System.out.println(j); 13 System.out.println(test); && and &: AND (cont’d)

The output of the program is, 0 10 false 0 11 false Note, that the j++ on the line containing the && operator is not evaluated since the first expression (i>10) is already equal to false.

|| (boolean logical) and | (logical) : inclusive OR Here is the truth table for || and |,

|| and |: inclusive OR The basic difference between || and I operators :  || supports short-circuit evaluations (or partial evaluations), while | doesn't. Given an expression: exp1 || exp2  || will evaluate the expression exp1, and immediately return a true value is exp1 is true  If exp1 is true, the operator never evaluates exp2 because the result of the operator will be true regardless of the value of exp2.  In contrast, the | operator always evaluates both exp1 and exp2 before returning an answer.

1 int i = 0; 2 int j = 10; 3 boolean test= false; 4 //demonstrate || 5 test = (i 9); 6 System.out.println(i); 7 System.out.println(j); 8 System.out.println(test); 9 //demonstrate | 10 test = (i 9); 11 System.out.println(i); 12 System.out.println(j); 13 System.out.println(test); || and | : inclusive OR: Sample Program

The output of the program is, 0 10 true 0 11 true Note that the j++ on line 5 is not evaluated since the first expression (i<10) is already equal to true.

Logical Operators: ^ (boolean logical exclusive OR) Here is the truth table for ^, The result of an exclusive OR operation is TRUE, if and only if one operand is true and the other is false. Note that both operands must always be evaluated in order to calculate the result of an exclusive OR.

^ (boolean logical exclusive OR) 1 boolean val1 = true; 2 boolean val2 = true; 3 System.out.println(val1 ^ val2); 4 val1 = false; val2 = true; 5 System.out.println(val1 ^ val2); 6 val1 = false; val2 = false; 7 System.out.println(val1 ^ val2); 8 val1 = true; val2 = false; 9 System.out.println(val1 ^ val2);

^ (boolean logical exclusive OR) The output of the program is, false true false true

! ( logical NOT) The logical NOT takes in one argument, wherein that argument can be an expression, variable or constant. Here is the truth table for ! :

! ( logical NOT) 1boolean val1 = true; 2 boolean val2 = false; 3 System.out.println( !val1 ); 4 System.out.println( !val2 ); Output : false true

Logical Operators: Conditional Operator (?:,) The conditional operator ?:  is a ternary operator. This means that it takes in three arguments that together form a conditional expression.

Conditional Operator (?:) (cont’d) Rommel AB Palomino - UDC Spring The structure of an expression using a conditional operator is exp1 ? exp2 : exp3 Where, -exp1 is a boolean expression whose result must either be true or false. -exp2 is the value returned, If exp1 is true. -exp3 is returned, If exp1 is false.

Conditional Operator (?:) (cont’d) 1 String status = ""; 2 int grade = 80; 3 //get status of the student 4 status = ( grade > = 60 ) ? “ Passed “ : “ Fail "; 5 //print status 6 System.out.println( status );  Output: Passed

Conditional Operator (?:) Flowchart

Operator Precedence

Given a complicated expression, 6 % 2 * / We can re-write the expression and place some parenthesis base on operator precedence: ( ( 6%2) * 5 ) + ( 4/2 ) + 88 – 10 ;

Operator Precedence: Coding Guidelines To avoid confusion in evaluating mathematical operations, keep your expressions simple and use parentheses.

Getting input from keyboard Rommel AB Palomino - UDC Spring

Getting Input from the Keyboard Two methods of getting input:  BufferedReader class  JOptionPane class (graphical user interface)

Using BufferedReader Class BufferedReader class  Found in the java.io package  Used to get input

Steps to get Input  1. Add this at the top of your code: import java.io.*;  2. Add this statement: BufferedReader dataIn = new BufferedReader( new InputStreamReader( System.in) );

Steps to get Input  3. Declare a temporary String variable to get the input, and invoke the readLine ( ) method to get input from the keyboard. You have to type it inside a try-catch block. try{ String temp = dataIn.readLine(); }catch( IOException e ){ System.out.println(“Error in getting input”); }

Sample Program 1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 import java.io.IOException; 4 public class GetInputFromKeyboard { 5 public static void main( String[] args ){ 6 BufferedReader dataIn = new BufferedReader(new 7 InputStreamReader( System.in) ); 8 String name = ""; 9System.out.print("Please Enter Your Name:"); 10 try{ 11name = dataIn.readLine(); 12 }catch( IOException e ){ 13 System.out.println("Error!"); 14 } 15System.out.println("Hello " + name +"!"); 16 } 17}

Sample Program The lines: import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; indicate that we want to use the classes BufferedReader, InputStreamReader and IOException which are inside the java.io package. These statements can also be written as: import java.io.*;

Sample Program The Java Application Programming Interface (API) contains hundreds of predefined classes that you can use in your programs. These classes are organized into what we call packages. Packages contain classes that have related purpose.

Sample Program The statement: public class GetInputFromKeyboard { class named GetInputFromKeyboard, The next statement declares the main method: public static void main( String[] args ){

Sample Program The statement: BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) ); declares a variable named dataIn, with the class BufferedReader.  Don't worry about what the syntax means for now. We will cover more about classes and declaring classes later in the course.

Sample Program The statement: String name = ""; declares a String variable with identifier name. The next statement: System.out.print("Please Enter Your Name:"); outputs a String on the screen asking for the user's name

Sample Program try{ name = dataIn.readLine(); }catch( IOException e ){ System.out.println("Error!"); } The given block defines a try-catch block. This assures that the possible exceptions that could occur in the statement name = dataIn.readLine(); will be catched.  We will cover more about exception handling in the latter part of this course.

Sample Program Now going back to the statement,: name = dataIn.readLine(); dataIn.readLine() gets input from the user and will return a String value: This value will then be saved to our name variable, which we will use in our final statement to greet the user: System.out.println("Hello " + name + "!");

Using JoptionPane Class Another way to get input from the user is by using the JOptionPane class which is found in the javax.swing package. JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something.

Sample Program 1 import javax.swing.JOptionPane; 2 public class GetInputFromKeyboard { 3 public static void main( String[] args ){ 4 String name = ""; 5 name = JoptionPane.showInputDialog(“Please enter your name"); 6 String msg = "Hello " + name + "!"; 7 JOptionPane.showMessageDialog(null, msg); 8 } 9 }

Sample Program Output

Sample Program The statement: import javax.swing.JOptionPane; indicates that we want to import the class JOptionPane from the javax.swing package. This can also written as, import javax.swing.*;

Sample Program The statement: name = JoptionPane.showInputDialog(“Please enter your name"); creates a JOptionPane input dialog, which will display a dialog with a message, a textfield and an OK button as shown in the figure. This returns a String which we will save in the name variable.

Sample Program The statement, String msg = "Hello " + name + "!"; creates the welcome message, which we will store in the msg variable.

Sample Program The statement, JOptionPane.showMessageDialog(null, msg); displays a dialog which contains a message and an OK button.

Summary Java Comments (C++-Style Comments, C-Style Comments, Special Javadoc Comments) Java statements, blocks, identifiers, keywords Java Literals (integer, floating point, boolean, character, String) Primitive data types( boolean, char, byte, short, int, long, float, double)

Summary Variables (declare, initialize, output) System.out.println() vs. System.out.print() Reference Variables vs. Primitive Variables Operators (Arithmetic operators, Increment and Decrement operators, Relational operators, Logical operators, Conditional Operator (?:), Operator Precedence)

Questions? Rommel AB Palomino - UDC Spring

For Next Class Rommel AB Palomino - UDC Spring