Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topic: Anatomy of Java Program

Similar presentations


Presentation on theme: "Topic: Anatomy of Java Program"— Presentation transcript:

1 Topic: Anatomy of Java Program
Course : JAVA PROGRAMMING Paper Code: ETCS-307 Faculty : Dr. Prabhjot Kaur Reader, Dept. of IT MSIT Topic: Anatomy of Java Program 1

2 Java Program Structure
In the Java programming language: A program is made up of one or more classes A class contains one or more methods A method contains program statements These terms will be explored in detail throughout the course A Java application always contains a method called main

3 MSIT.java public class Msit { // // Prints a Welcome note. public static void main (String[] args) System.out.println (“Welcome in the Java Class"); }

4 Java Program Structure
// comments about the class public class MyProgram { } class header class body Comments can be placed almost anywhere

5 Java Program Structure
// comments about the class public class MyProgram { } // comments about the method public static void main (String[] args) { } method header method body

6 Comments Comments in a program are called inline documentation
They should be included to explain the purpose of the program and describe processing steps They do not affect how a program works Java comments can take three forms: // this comment runs to the end of the line /* this comment runs to the terminating symbol, even across line breaks */ /** this is a javadoc comment */

7 Identifiers Identifiers are the words a programmer uses in a program
An identifier can be made up of letters, digits, the underscore character ( _ ), and the dollar sign Identifiers cannot begin with a digit Java is case sensitive - Total, total, and TOTAL are different identifiers By convention, programmers use different case styles for different types of identifiers, such as title case for class names - Msit upper case for constants - MAXIMUM

8 Reserved Words The Java reserved words: abstract assert boolean break
byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while

9 White Space Spaces, blank lines, and tabs are called white space
White space is used to separate words and symbols in a program Extra white space is ignored A valid Java program can be formatted many ways Programs should be formatted to enhance readability, using consistent indentation

10 Syntax and Semantics The syntax rules of a language define how we can put together symbols, reserved words, and identifiers to make a valid program The semantics of a program statement define what that statement means (its purpose or role in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do

11 Errors A program can have three types of errors
The compiler will find syntax errors and other basic problems (compile-time errors) If compile-time errors exist, an executable version of the program is not created A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time errors) A program may run, but produce incorrect results, perhaps using an incorrect formula (logical errors)

12 Escape Sequences For Formatting
Description \t Horizontal tab \r Carriage return \n New line \” Double quote \\ Backslash

13 Example Formatting Codes
Name of the online example: FormattingExample.java public class FormattingExample { public static void main (String [] args) System.out.print(“one\ttwo\n"); System.out.println("hello\rworld"); System.out.println("\"Geek\" talk slash (\\) com"); }

14 Some Built-In Types Of Variables In Java
Description byte 8 bit signed integer short 16 but signed integer int 32 bit signed integer long 64 bit signed integer float 32 bit signed real number double 64 bit signed real number char 16 bit Unicode character (ASCII and beyond) boolean 1 bit true or false value String A sequence of characters between double quotes ("")

15 Initializing Variables
Always initialize your variables prior to using them! Do this whether it is syntactically required or not. Example how not to approach: public class OutputExample1 { public static void main (String [] args) int num; System.out.print(num); } OutputExample1.java:7: error: variable num might not have been initialized System.out.print(num); ^

16 Java Constants Constants have a name like variables and store a certain type of information but unlike variables they CANNOT change. Format: final <constant type> <CONSTANT NAME> = <value>; Example: final int SIZE = 100;

17 Why Use Constants? They make your program easier to read and understand populationChange = ( – ) * currentPopulation; Vs. final float BIRTH_RATE = 17.58; final float MORTALITY_RATE = ; int currentPopulation = ; populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation;

18 Why Use Constants? It can make your program easier to maintain (update with changes). If the constant is referred to several times throughout the program, changing the value of the constant once will change it throughout the program.

19 Why Use Constants? One change in the initialization of the constant changes all references to that constant. final float BIRTH_RATE = 0.5; final float MORTALITY_RATE = ; float populationChange = 0; float currentPopulation = ; populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation; if (populationChange > 0) System.out.println("Increase“) System.out.println("Birth rate:“+ BIRTH_RATE + " Mortality rate:“ + MORTALITY_RATE, " + Population change:“ + populationChange); else if (populationChange < 0) System.out.println("Decrease“); System.out.println("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+ MORTALITY_RATE +"Population change:“+populationChange); else System.out.print("No change“); System.out.print("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+ MORTALITY_RATE+ "Population change:“+populationChange);

20 Common Java Operators / Operator Precedence
Precedence level Operator Description Associativity 1 expression++ expression-- Post-increment Post-decrement Right to left 2 ++expression --expression + - ! ~ (type) Pre-increment Pre-decrement Unary plus Unary minus Logical negation Bitwise complement Cast

21 Common Java Operators / Operator Precedence
Precedence level Operator Description Associativity 3 * / % Multiplication Division Remainder/modulus Left to right 4 + - Addition or String concatenation Subtraction 5 << >> Left bitwise shift Right bitwise shift

22 Common Java Operators / Operator Precedence
Precedence level Operator Description Associativity 6 < <= > >= Less than Less than, equal to Greater than Greater than, equal to Left to right 7 = = != Equal to Not equal to 8 & Bitwise AND 9 ^ Bitwise exclusive OR

23 Common Java Operators / Operator Precedence
Precedence level Operator Description Associativity 10 | Bitwise OR Left to right 11 && Logical AND 12 || Logical OR

24 Common Java Operators / Operator Precedence
Precedence level Operator Description Associativity 13 = += -= *= /= %= &= ^= |= <<= >>= Assignment Add, assignment Subtract, assignment Multiply, assignment Division, assignment Remainder, assignment Bitwise AND, assignment Bitwise XOR, assignment Bitwise OR, assignment Left shift, assignment Right shift, assignment Right to left

25 Post/Pre Operators (2) The name of the online example is: Order2.java
public class Order2 { public static void main (String [] args) int num1; int num2; num1 = 5; num2 = ++num1 * num1++; System.out.println("num1=" + num1); System.out.println("num2=" + num2); }

26 Scope of Variables { int x=0; } Block1 { …. int n=5; … Block2 } { ….
int m=10; } Block3 32

27 Classification of java Statements
Expression Statement Control Statement Labelled Statement Synchronization Statement Guarding Statement Selection Statement Iteration Jump do for If-else switch break continue return while if

28 Character Strings A string of characters can be represented as a string literal by putting double quotes around the text: Examples: "This is a string literal." "123 Main Street" "X" Every character string is an object in Java, defined by the String class Every string literal represents a String object

29 System.out.println ("Whatever you are, be a good one.");
The println Method In the Lincoln program, we invoked the println method to print a character string The System.out object represents a destination (the monitor screen) to which we can send output System.out.println ("Whatever you are, be a good one."); method name object information provided to the method (parameters)

30 The print Method The System.out object provides another service as well The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line

31 Countdown.java public class Countdown { // // Prints two lines of output representing a rocket countdown. public static void main (String[] args) System.out.print ("Three... "); System.out.print ("Two... "); System.out.print ("One... "); System.out.print ("Zero... "); System.out.println ("Liftoff!"); // appears on first output line System.out.println (“Ohh, we have a problem."); }

32 String Concatenation The string concatenation operator (+) is used to append one string to the end of another "Peanut butter " + "and jelly" It can also be used to append a number to a string A string literal cannot be broken across two lines in a program

33 Facts.java public class Facts { public static void main (String[] args) // Strings can be concatenated into one long string System.out.println ("We present the following facts for your " + "extracurricular edification:"); System.out.println (); // A string can contain numeric digits System.out.println ("Letters in the Hawaiian alphabet: 12"); // A numeric value can be concatenated to a string System.out.println ("Dialing code for Delhi: " + 011); System.out.println (“MSIT college stared in the Year "+ 2001); System.out.println ("Speed of car: " " km per hour"); }

34 String Concatenation The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, it adds them The + operator is evaluated left to right, but parentheses can be used to force the order

35 Addition.java public class Addition { // // Concatenates and adds two numbers and prints the results. public static void main (String[] args) System.out.println ("24 and 45 concatenated: " ); System.out.println ("24 and 45 added: " + ( )); }

36 Accessing Pre-Created Java Libraries
It’s accomplished by placing an ‘import’ of the appropriate library at the top of your program. Syntax: import <Full library name>; Example: import java.util.Scanner;

37 Getting Text Input You can use the pre-written methods (functions) in the Scanner class. General structure: import java.util.Scanner; public static void main (String [] args) { Scanner <name of scanner> = new Scanner (System.in); <variable> = <name of scanner> .<method> (); } Creating a scanner object (something that can scan user input) Using the capability of the scanner object (actually getting user input)

38 Getting Text Input The name of the online example: MyInput.java
import java.util.Scanner; public class MyInput { public static void main (String [] args) String str1; int num1; Scanner in = new Scanner (System.in); System.out.print ("Type in an integer: "); num1 = in.nextInt (); System.out.print ("Type in a line: "); str1 = in.nextLine (); System.out.println ("num1:" +num1 +"\t str1:" + str1); }

39 Useful Methods Of Class Scanner
nextInt () nextLong () nextFloat () nextDouble () nextLine ();

40 Reading A Single Character
Text menu driven programs may require this capability. Example: GAME OPTIONS (a)dd a new player (l)oad a saved game (s)ave game (q)uit game There’s different ways of handling this problem but one approach is to extract the first character from the string. Partial example: String s = "boo“; System.out.println(s.charAt(0));

41 Reading A Single Character
MyInputChar.java import java.util.Scanner; public class MyInputChar { public static void main (String [] args) final int FIRST = 0; String selection; Scanner in = new Scanner (System.in); System.out.println("GAME OPTIONS"); System.out.println("(a)dd a new player"); System.out.println("(l)oad a saved game"); System.out.println("(s)ave game"); System.out.println("(q)uit game"); System.out.print("Enter your selection: "); selection = in.nextLine (); System.out.println ("Selection: " + selection.charAt(FIRST)); }

42 Decision Making In Java
Java decision making constructs if if, else if, else-if switch

43 Decision Making: If Format: Example:
if (Boolean Expression) Body Example: if (x != y) System.out.println("X and Y are not equal"); if ((x > 0) && (y > 0)) { System.out.println("X and Y are positive"); } Indenting the body of the branch is an important stylistic requirement of Java but unlike Python it is not enforced by the syntax of the language. What distinguishes the body is either: A semi colon (single statement branch) Braces (a body that consists of multiple statements)

44 Decision Making: If, Else
Format: if (Boolean expression) Body of if else Body of else Example: if (x < 0) System.out.println("X is negative"); System.out.println("X is non-negative");

45 Example Program: If-Else
Name of the online example: BranchingExample1.java import java.util.Scanner; public class BranchingExample1 { public static void main (String [] args) Scanner in = new Scanner(System.in); final int WINNING_NUMBER = ; int playerNumber = -1; System.out.print("Enter ticket number: "); playerNumber = in.nextInt(); if (playerNumber == WINNING_NUMBER) System.out.println("You're a winner!"); else System.out.println("Try again."); }

46 If, Else-If Format: if (Boolean expression) Body of if
else if (Boolean expression) Body of first else-if : : : Body of last else-if else Body of else

47 If, Else-If Name of the online example: BranchingExample.java
import java.util.Scanner; public class BranchingExample2 { public static void main (String [] args) Scanner in = new Scanner(System.in); int gpa = -1; System.out.print("Enter letter grade: "); gpa = in.nextInt();

48 If, Else-If if (gpa == 4) System.out.println("A"); else if (gpa == 3)
System.out.println("B"); else if (gpa == 2) System.out.println("C"); else if (gpa == 1) System.out.println("D"); else if (gpa == 0) System.out.println("F"); else System.out.println("Invalid letter grade"); }

49 Alternative To Multiple Else-If’s: Switch
Format (character-based switch): switch (character variable name) { case '<character value>': Body break; : default: } 1 The type of variable in the brackets can be a byte, char, short, int or long Important! The break is mandatory to separate Boolean expressions (must be used in all but the last)

50 Alternative To Multiple Else-If’s: Switch
Format (integer based switch): switch (integer variable name) { case <integer value>: Body break; : default: } 1 The type of variable in the brackets can be a byte, char, short, int or long

51 While Loops Format: Example: while (Boolean expression) Body
int i = 1; while (i <= 4) { // Call function createNewPlayer(); i = i + 1; }

52 For Loops Format: Example:
for (initialization; Boolean expression; update control) Body Example: for (i = 1; i <= 4; i++) { // Call function createNewPlayer(); i = i + 1; }

53 Post-Test Loop: Do-While
Recall: Post-test loops evaluate the Boolean expression after the body of the loop has executed. This means that post test loops will execute one or more times. Pre-test loops generally execute zero or more times.

54 Do-While Loops Format: Example: do Body while (Boolean expression);
char ch = 'A'; { System.out.println(ch); ch++; } while (ch <= 'K');

55 THANK YOU


Download ppt "Topic: Anatomy of Java Program"

Similar presentations


Ads by Google