Presentation is loading. Please wait.

Presentation is loading. Please wait.

 First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Similar presentations


Presentation on theme: " First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA."— Presentation transcript:

1

2  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  Programs

3

4  // 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. Comments:

5  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 Class declaration: 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.

6  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 Method defining: publicThe keyword public is an access specifier that declares the main method as unprotected and therefore making it accessible to all other classes staticWhich 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. voidVoid is an modifier that states the main method does not return any value.

7  Enclosed in left and right braces. All methods in java should be enclosed with open brace { and ending brace }. Body of the method declaration:  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 (;). Statement:

8  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 Compiling and Executing Your First Java Application :

9 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.

10  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. Compiling and Executing Your First Java Application : Output: java with the class file name which executes the program displays the result.

11  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.

12 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

13 Output:

14  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:

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

16 Output:

17  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.

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

19  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 TypesSize in BytesSize in Bits int432 long864 float432 double864 char216 boolean (boolean in Java)18

20 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 short int long float double char boolean 8-bit integers in the range –128 to bit integers in the range –32768 to bit integers in the range – to bit integers in the range – to bit floating-point numbers in the range ± 1.4 x to ± x bit floating-point numbers in the range ± 4.39 x to ± x bit characters encoded using Unicode the values true and false The arithmetic operators: + - * / % add subtract remainder divide multiply = == = < != <= >= equal to less than greater or equal less or equal not equal > greater than The arithmetic operators except % The relational operators: The relational operators The logical operators: && add || or ! not DomainCommon operations byte

21 Imports class scanner for use in this program Creates Scanner object for reading data from the user

22 Varaibles that are declared but not initalized

23 Reads an int value from the user

24 Reads another int value from the user

25 Sums the values of num1 and num2

26 Output:

27 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.

28 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.

29 Getting Input from a Scanner :

30 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..

31 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.

32 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.”

33  Write a java application to display the subtraction two given numbers? Output:

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

35 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. Memory locations after storing values for num1 and num2 Memory locations after storing sum of num1 and num2

36  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..

37  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.

38 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.

39

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

41 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.

42

43

44 Output:

45  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

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

47 1.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.] Output: 2.Write an application that ask the user to enter two integers, and prints their sum, product, difference and division.

48


Download ppt " First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA."

Similar presentations


Ads by Google