Topic: Anatomy of Java Program

Slides:



Advertisements
Similar presentations
Chapter 1: Computer Systems
Advertisements

Programming with Java. Problem Solving The purpose of writing a program is to solve a problem The general steps in problem solving are: –Understand the.
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.
The Java Programming Language
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Outline Java program structure Basic program elements
Chapter 1 Introduction. © 2004 Pearson Addison-Wesley. All rights reserved1-2 Outline Computer Processing Hardware Components Networks The Java Programming.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Chapter 1 Introduction.
1 Character Strings and Variables Character Strings Variables, Initialization, and Assignment Reading for this class: L&L,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Prepared by Uzma Hashmi Instructor Information Uzma Hashmi Office: B# 7/ R# address: Group Addresses Post message:
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
© 2006 Pearson Education Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition.
Java: Chapter 1 Computer Systems Computer Programming II.
Java Language and SW Dev’t
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
© 2006 Pearson Education 1 Obj: cont 1.3 and 1.4, to become familiar with identifiers and to understand how programming languages work HW: p.51 #1.8 –
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Program Statements Primitive Data Types and Strings.
C Derived Languages C is the base upon which many build C++ conventions also influence others *SmallTalk is where most OOP comes Java and Javascript have.
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.
Chapter 2: Java Fundamentals
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
1 Problem Solving b The purpose of writing a program is to solve a problem b The general steps in problem solving are: Understand the problemUnderstand.
White Space Spaces, blank lines, and tabs are collectively called white space and are used to separate words and symbols in a program Extra white space.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Chapter 2: Data and Expressions String and String Concatenation Escape Sequences Variables Primitive Date Types Expressions Interactive Programs.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Data and Expressions. Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration.
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
CompSci 230 S Programming Techniques
Key Words / Reserved Words
Chapter 2 Variables.
Working with Java.
Chapter 4 Assignment Statement
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Lecture 2: Data Types, Variables, Operators, and Expressions
CS180 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Variables and Arithmetic Operators in JavaScript
1.3 Problem Solving The purpose of writing a program is to solve a problem The general steps in problem solving are: Understand the problem Dissect the.
Chapter 3 Assignment Statement
Java Programming: From Problem Analysis to Program Design, 4e
Starting JavaProgramming
Introduction to Java Programming
An overview of Java, Data types and variables
Chapter 2: Basic Elements of Java
Chapter 1: Computer Systems
Units with – James tedder
Units with – James tedder
elementary programming
Focus of the Course Object-Oriented Software Development
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Variables.
Instructor: Alexander Stoytchev
Java Programming Presented by Dr. K. SATISH KUMAR,
Presentation transcript:

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

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

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

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

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

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 */

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

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

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

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

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)

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

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

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 ("")

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); ^

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;

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

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.

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 = 0.1257; float populationChange = 0; float currentPopulation = 1000000; 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);

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

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

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

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

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

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

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

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

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

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)

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

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

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

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: " + 40 + " km per hour"); }

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

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: " + 24 + 45); System.out.println ("24 and 45 added: " + (24 + 45)); }

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;

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)

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

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

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));

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

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

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)

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

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

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

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();

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

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)

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

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

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

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.

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

THANK YOU