Introduction to Java Applications

Slides:



Advertisements
Similar presentations
CSci 1130 Intro to Programming in Java
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter2: Introduction to Java Applications 1.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CMT Programming Software Applications
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 2 - Introduction to Java Applications
Introduction to C Programming
String Escape Sequences
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
Java Applications & Program Design
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
 2005 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
 2005 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
1 2 2 Introduction to Java Applications Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Intro and Review Welcome to Java. Introduction Java application programming Use tools from the JDK to compile and run programs. Videos at
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Introduction to C Programming Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
Week 1 Algorithmization and Programming Languages.
 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.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
Java™ How to Program, 10/e Late Objects Version © Copyright by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
REEM ALMOTIRI Information Technology Department Majmaah University.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
© by Pearson Education, Inc. All Rights Reserved.
Introduction to Java Applications
Chapter 6 JavaScript: Introduction to Scripting
Chapter 1: Introduction to computers and C++ Programming
Chapter 2 Introduction to C++ Programming
Chapter 2 - Introduction to C Programming
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 2 Introduction to Java Applications
Chapter 2 Introduction to Java Applications
Introduction to Scripting
Chapter 2 - Introduction to C Programming
Fundamentals of Java Programs, Input/Output, Variables, and Arithmetic
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Introduction to C++ Programming
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Expressions and Assignment
Introduction to Java Applications
Chapter 2 - Introduction to C Programming
Java How to Program, 11/e Questions?
Introduction to C Programming
Presentation transcript:

Introduction to Java Applications

Topics First Program in JAVA: Printing a Line of Text Modifying our First Java Program Escape Sequences Displaying Text with printf Data types in JAVA Another Application: Adding Integers Programs Memory Concepts Arithmetic Decision Making: Equality and Relational Operators Precedence and Associativity of Operators Exercises Questions

First Program in JAVA : Printing a Line of Text

First Program in JAVA : Printing a Line of Text Comments: // Program Name: Welcome.java // This Program prints line of text // indicates that the line is a comment. Used to document programs and improve their readability. Compiler ignores comments. So they do not cause the computer to perform any action when the program is run. A comment that begins with // is an end-of-line comment—it terminates at the end of the line on which it appears. Traditional comment, can be spread over several lines as in /* This is a traditional comment. It can be split over multiple lines */ This type of comment begins with /* and ends with */. All text between the delimiters is ignored by the compiler.

First Program in JAVA : Printing a Line of Text Class declaration: public class Welcome Every Java program consists of at least one class that you define. class keyword introduces a class declaration and is immediately followed by the class name. Welcome is a java identifier that specifies the name of the class to be defined. Keywords are reserved for use by Java and are always spelled with all lowercase letters. By convention, class names begin with a capital letter and capitalize the first letter of each word they include for example: AdditionTwoNos Opening brace: Every class definition in Java begins with an opening brace { and ends with a matching closing brace }, appearing in the last line in the above program.

First Program in JAVA : Printing a Line of Text Method defining: public static void main(String[] args) - is the starting point of every Java application. All parameters are declared inside a pair of parentheses. Defines a method named main. Conceptually, this is similar to the main() function in C. A Java application can have any number of classes but only one of them must include a main method to initiate the execution. otherwise, the JVM will not execute the application. Methods perform tasks and can return information when they complete their tasks. This line contains a number of keywords - public, static and void public The keyword public is an access specifier that declares the main method as unprotected and therefore making it accessible to all other classes static Which declares this method as one that belongs to entire class and not a part of any objects of the class. The main must always be declared as static since the interpreter uses this method before any objects are created. More about the static variables and methods will be discussed later. void Void is an modifier that states the main method does not return any value.

First Program in JAVA : Printing a Line of Text Body of the method declaration: Enclosed in left and right braces. All methods in java should be enclosed with open brace { and ending brace }. Statement: System.out.println("Welcome to Java Programming!"); Instructs the computer to perform an action to print the string of characters contained between the double quotation marks.. System.out: Standard output object. Allows Java applications to display strings in the command window from which the Java application executes. System.out.println : Displays (or prints) a line of text in the command window. The string in the parentheses the argument to the method. Positions the output cursor at the beginning of the next line in the command window. The statements in java should end with semicolon (;).

First Program in JAVA : Printing a Line of Text Compiling and Executing Your First Java Application : Open a command window and change to the directory where the program is stored. Many operating systems use the command cd to change directories. To compile the program, type javac Welcome.java If the program contains no syntax errors, preceding command creates a.class file (known as the class file) containing the platform-independent Java bytecodes that represent the application. When we use the java command to execute the application on a given platform, these bytecodes will be translated by the JVM into instructions that are understood by the underlying operating system. The figure as shown

First Program in JAVA : Printing a Line of Text javac is the command which complies the java file. If program has the errors it displays the errors with lines numbers and error description. If there are no errors it will display the prompt.

First Program in JAVA : Printing a Line of Text Compiling and Executing Your First Java Application : To execute the program, type java Welcome. Launches the JVM, which loads the .class file for class Welcome. Note that the .class file-name extension is omitted from the preceding command; otherwise, the JVM will not execute the program. The JVM calls method main to execute the program. Output: java with the class file name which executes the program displays the result.

Modifying Our First Java Program Class Welcome1, uses two statements to produce the same output as that shown in above program.. System.out’s method print displays a string. Unlike println, print does not position the output cursor at the beginning of the next line in the command window. The next character the program displays will appear immediately after the last character that print displays.

Modifying Our First Java Program Prints Welcome to and leaves cursor on same line Prints Java Programming! starting where the cursor was positioned previously, then outputs a new lines character

Modifying Our First Java Program Output:

Escape Sequences The effect of these characters are felt at the time execution but not at the time of compilation. The backslash (\) is called an escape character. Indicates a “special character” Backslash is combined with the next character to form an escape sequence. Some common escape sequences are listed. They are:

Escape Sequences Program using “\n” Each \n moves the output cursor to the next line. Where output continues

Escape Sequences Output:

Displaying Text with printf Feature added in Java SE 5.0 System.out.printf f means “formatted” displays formatted data Multiple method arguments are placed in a comma-separated list. Java allows large statements to be split over many lines. Cannot split a statement in the middle of an identifier or string. Method printf’s first argument is a format string May consist of fixed text and format specifiers. Fixed text is output as it would be by print or println. Each format specifier is a placeholder for a value and specifies the type of data to output. Format specifiers begin with a percent sign (%) and are followed by a character that represents the data type. Format specifier %s is a placeholder for a string.

Displaying Text with printf Each %s is a placeholder for a String that comes later in the argument Statements can be split over multiple lines. Output:

Data types in JAVA Primitive Data Types Size in Bytes Size in Bits int Although complex data values are represented using objects, Java defines a set of primitive types to represent simple data. Java provides eight primitive data types, they are boolean char, byte, short, int, long float, double Primitive Data Types Size in Bytes Size in Bits int 4 32 long 8 64 float double char 2 16 boolean (boolean in Java) 1

Data types in JAVA A data type is defined by a set of values called the domain and a set of operations. The following table shows the data domains and common operations for all eight of Java’s primitive types: Type Domain Common operations The arithmetic operators: byte 8-bit integers in the range –128 to 127 + add * multiply - subtract / divide short 16-bit integers in the range –32768 to 32767 % remainder 32-bit integers in the range –2146483648 to 2146483647 The relational operators: int = = equal to != not equal 64-bit integers in the range –9223372036754775808 to 9223372036754775807 < less than <= less or equal long > greater than >= greater or equal 32-bit floating-point numbers in the range ± 1.4 x 10-45 to ± 3.4028235 x 10-38 float The arithmetic operators except % 64-bit floating-point numbers in the range ± 4.39 x 10-322 to ± 1.7976931348623157 x 10308 The relational operators double 16-bit characters encoded using Unicode The relational operators char The logical operators: boolean the values true and false && add || or ! not

Another Application: Adding Integers Imports class scanner for use in this program Creates Scanner object for reading data from the user

Another Application: Adding Integers Varaibles that are declared but not initalized

Another Application: Adding Integers Reads an int value from the user

Another Application: Adding Integers Reads another int value from the user

Another Application: Adding Integers Sums the values of num1 and num2

Another Application: Adding Integers Output:

Another Application: Adding Integers Import Declaration : Helps the compiler locate a class that is used in this program. Rich set of predefined classes that you can reuse rather than “reinventing the wheel.” Classes are grouped into packages—named groups of related classes—and are collectively referred to as the Java class library, or the Java Application Programming Interface (Java API). You use import declarations to identify the predefined classes used in a Java program. Scanner class : For input we use methods of the class java.util.Scanner. Scanner is not part of the fundamental Java Language but is part of a package, java.util, that you can include in your program. A Package is a collection of classes which may be used in your program. Think of a package as a tool box and the classes within it as tools. Different programs need different tools and include different packages.

Another Application: Adding Integers Scanner statement : Scanner input = new Scanner(System.in); Specifies the name (input) and type (Scanner) of a variable that is used in this program. The equals sign (=) in a declaration indicates that the variable should be initialized (i.e., prepared for use in the program) with the result of the expression to the right of the equals sign. The new keyword creates an object. Standard input object, System.in, enables applications to read bytes of information typed by the user. Scanner object translates these bytes into types that can be used in a program.

Another Application: Adding Integers Getting Input from a Scanner :

Another Application: Adding Integers Variable : A location in the computer’s memory where a value can be stored for use later in a program. Must be declared with a name and a type before they can be used. A variable’s name enables the program to access the value of the variable in memory. The name can be any valid identifier. A variable’s type specifies what kind of information is stored at that location in memory. Variable declaration statements : int num1; // first number to add int num2; // second number to add int sum; // sum of num1 and num2 Declare that variables number1, number2 and sum hold data of type int They can hold integer. Range of values for an int is –2,147,483,648 to +2,147,483,647. Actual int values may not contain commas. Several variables of the same type may be declared in one declaration with the variable names separated by commas..

Another Application: Adding Integers Prompt : Output statement that directs the user to take a specific action. System is a class. Part of package java.lang. Class System is not imported with an import declaration at the beginning of the program. Scanner method nextInt num1 = input.nextInt(); // read first number from user Obtains an integer from the user at the keyboard. Program waits for the user to type the number and press the Enter key to submit the number to the program. The result of the call to method nextInt is placed in variable num1 by using the assignment operator, =. “num1 gets the value of input.nextInt().” Operator = is called a binary operator—it has two operands. Everything to the right of the assignment operator, =, is always evaluated before the assignment is performed.

Another Application: Adding Integers Arithmetic : sum = num1 + num2; Assignment statement that calculates the sum of the variables num1 and num2 then assigns the result to variable sum by using the assignment operator, =. “sum gets the value of num1 + num2.” In general, calculations are performed in assignment statements. Portions of statements that contain calculations are called expressions. An expression is any portion of a statement that has a value associated with it. Integer formatted output : System.out.printf("Sum is %d\n", sum); // display sum Format specifier %d is a placeholder for an int value The letter d stands for “decimal integer.”

Programs Output: Output: Write a java application to display the subtraction two given numbers? Output: Write a java application to read the radius of the circle from user and display area and circumference of the circle? (area: =𝝅 𝒓 𝟐 and circumference =𝟐𝝅r) 𝝅 = 3.14 Output: Write a java application to read the radius of the circle from user and display area and circumference of the circle? (area: =𝝅 𝒓 𝟐 and circumference =𝟐𝝅r) 𝝅 = 3.14

Programs Write a java application to swap two numbers and display the swapped numbers? Output:

Memory Concepts num1 45 num2 72 num1 45 num2 72 sum 117 Variables : Every variable has a name, a type, a size (in bytes) and a value. When a new value is placed into a variable, the new value replaces the previous value (if any) The previous value is lost. num1 45 num2 72 Memory locations after storing values for num1 and num2 num1 45 num2 72 sum 117 Memory locations after storing sum of num1 and num2

Arithmetic Arithmetic operators are summarized in given Fig The asterisk (*) indicates multiplication The percent sign (%) is the remainder operator The arithmetic operators are binary operators because they each operate on two operands. Integer division yields an integer quotient. Any fractional part in integer division is simply discarded (i.e., truncated)—no rounding occurs. The remainder operator, %, yields the remainder after division. .

Arithmetic Arithmetic expressions in Java must be written in straight-line form to facilitate entering programs into the computer. Expressions such as “a divided by b” must be written as a / b, so that all constants, variables and operators appear in a straight line. Parentheses are used to group terms in expressions in the same manner as in algebraic expressions. If an expression contains nested parentheses, the expression in the innermost set of parentheses is evaluated first.

Arithmetic Rules of operator precedence: Multiplication, division and remainder operations are applied first. If an expression contains several such operations, they are applied from left to right. Multiplication, division and remainder operators have the same level of precedence. Addition and subtraction operations are applied next. If an expression contains several such operations, the operators are applied from left to right. Addition and subtraction operators have the same level of precedence. When we say that operators are applied from left to right, we are referring to their associativity. Some operators associate from right to left.

Arithmetic

Arithmetic Write a java application to display the average of three numbers? Output:

Decision Making: Equality and Relational Operators Condition: An expression that can be true or false. Equality operators (== and !=) Relational operators (>, <, >= and <=) Both equality operators have the same level of precedence, which is lower than that of the relational operators. The equality operators associate from left to right. The relational operators all have the same level of precedence and also associate from left to right.

Decision Making: Equality and Relational Operators

Decision Making: Equality and Relational Operators

Decision Making: Equality and Relational Operators Output:

Precedence and Associativity of Operators All these operators , with the exception of the assignment operator, =, associate from left to right . Addition is left associate so an expression like x + y + z is evaluated as if had been various as ( x + y ) + z. The assignment operator = association is right to left so an expression like x = y = 0 is evaluated as if it had been written as x = ( y = 0), which first assigns the value 0 to variable y, then assigns the result of that assignment 0 to x. The figure as shown

Exercises Questions Assuming x = 2 and y = 3, what does each of the following statements display? System.out.printf(“x = %d\n”, x) System.out.printf(“value of %d + %d = %d”, x, y, (x + y * x )); Assuming that float variable p = 5 and q = 7, what does each of the following statements display? System.out.printf( "p = %f\n", p ); System.out.printf( "%f = %f\n", ( p + q ), ( p + q ) ); Answers: 1.1 x = 2 1.2 2 + 3 = 8 2.1 p = 5.000000 2.2 12.000000 = 12.000000

Programs Write an application that reads an integer and determines and prints whether it’s even or odd. [Hint: use the remainder operator. An even number is multiple of 2. Any multiple of 2 leaves remainder of 0 when divided by 2.] Write an application that ask the user to enter two integers, and prints their sum, product, difference and division. Output:

?