Lecture 02 - Java Basics - Part I - ll.pdf
Document Details
Uploaded by PreeminentGravity
Full Transcript
Basics of programming with Java Part: 1 and 2 Chapter 1-4 CCSIT | Computer Science Topics Outline Programming 01 Languages Programs, Programming Languages, Interpreters & Comp...
Basics of programming with Java Part: 1 and 2 Chapter 1-4 CCSIT | Computer Science Topics Outline Programming 01 Languages Programs, Programming Languages, Interpreters & Compilers 02 Java Why and How? Java Basics of 03- Programming 04 Selection Mathematical functions Characters and strings 2 1 Programming Languages Programs Computer programs, known as software, are instructions to the computer. You tell a computer what to do through programs. Without programs, a computer is an empty machine. Computers do not understand human languages, so you need to use computer languages to communicate with them. Programs are written using programming languages. 4 Programming Languages Machine Language: In Machine Language the instruction are in the form of 0,1 (Binary) or 1FFA (Hexadecimal). These instruction are directly understand by the computer and it’s varies from machine to machine (i.e. one machine instruction can’t be run on another machine. Assembly Language: Assembly languages is a symbolic language and easy to program instruction for a speciMc processor. Computer only understands machine language, which are strings of 1's and 0’s. As, machine language is too hard and complex for using in software development. So, the low-level assembly language is designed that represents various instructions in symbolic code and a more understandable form. High-Level Language: The high-level languages are English-like and easy to learn and program. For example, the following is a high-level language statement that computes the area of a circle with radius 5: area = 5 * 5 * 3.1415; 5 Translation from HLL – Machine or Interpreter 6 Popular High-Level Languages Language Description Ada Named for Ada Lovelace, who worked on mechanical general-purpose computers. The Ada language was developed for the Department of Defense and is used mainly in defense projects. BASIC Beginner’s All-purpose Symbolic Instruction Code. It was designed to be learned and used easily by beginners. C Developed at Bell Laboratories. C combines the power of an assembly language with the ease of use and portability of a high-level language. C++ C++ is an object-oriented language, based on C. C# Pronounced “C Sharp.” It is a hybrid of Java and C++ and was developed by Microsoft. COBOL COmmon Business Oriented Language. Used for business applications. FORTRAN FORmula TRANslation. Popular for scientific and mathematical applications. Java Developed by Sun Microsystems, now part of Oracle. It is widely used for developing platform- independent Internet applications. Pascal Named for Blaise Pascal, who pioneered calculating machines in the seventeenth century. It is a simple, structured, general-purpose language primarily for teaching programming. Python A simple general-purpose scripting language good for writing short programs. Visual Visual Basic was developed by Microsoft and it enables the programmers to rapidly develop Basic graphical user interfaces. 7 Java A general-purpose computer High Level Programming Language designed to produce programs that will run on any computer system. Java can be used to develop various types of applications including: Desktop applications Embedded systems Web application Mobile applications 8 Features of Java 9 Java Editions Java is a full-Xedged and powerful language that can be used in many ways. It comes in three editions: Java Micro Edition (Java ME) to develop applications for mobile devices, such as cell phones. Java Standard Edition (Java SE) to develop client-side applications. The applications can run standalone or as applets running from a Web browser. Java Enterprise Edition (Java EE) to develop server-side applications, such as Java servlets, JavaServer Pages (JSP), and JavaServer Faces (JSF). 10 JDK & IDEs Java Development Toolkit (JDK ): consists of a set of separate programs, each invoked from a command line, for developing and testing Java programs Instead you can use integrated development environment (IDE) such as: NetBeans, BlueJ,.. Editing, compiling, building, debugging, and online help are integrated in one graphical user interface. 11 How to compile and Run Java Program 12 Simple Java Program public class Welcome { public static void main(String[] args) { // Display message Welcome to Java! on the console System.out.println("Welcome to Java!"); } } Every Java program must have at least one class. Output: Each class has a name. By convention, class names start with Welcome to Java! an uppercase letter. The program is executed from the main method. A class may contain several methods. 13 Programming Style and Documentation Proper Indentation and Appropriate Comments Spacing Include a summary and your details at Indentation: Indent two spaces. the beginning of the program to Spacing: Use blank line to separate segments of the code. explain the program, its features, and also include your details. Naming Conventions Block Styles Choose meaningful and descriptive names. Class names: Capitalize the drst letter of each word in the name. For example, the class name ComputeExpression. 14 Programming Errors Syntax Errors Runtime Errors Logic Errors Grammatical Error and Causes the program to Produces incorrect result public class ShowLogicErrors { detect by the compiler abort public static void main(String[] args) { System.out.println((9 / 5) * 35 + 32); }} public class ShowSyntaxErrors { public static main(String[] args) { public class ShowRuntimeErrors { Catch Error: System.out.println("Welcome to Java); public static void main(String[] args) } { } System.out.println(1 / 0); } Catch Error: } Catch Error: 15 2 Elementary Programming Objectives Java Development Toolkit (JDK ): consists of a set of separate programs, each invoked from a command line, for developing and testing Java programs Instead you can use integrated development environment (IDE) such as: NetBeans, BlueJ,.. Editing, compiling, building, debugging, and online help are integrated in one graphical user interface. 17 Trace a Program Execution public class ComputeArea { public static void main(String[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); } } Write Output of the Program: _________________________________________________________________________ 18 Variable (Identider) An identider is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identider must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. An identider cannot be a reserved word. (See Appendix A, “Java Keywords,” for a list of reserved words). An identider cannot be true, false, or null. An identider can be of any length. 19 Variable (Identider) // Compute the first area radius = 1.0; area = radius * radius * 3.14159; System.out.println("The area is “ + area + " for radius "+radius); // Compute the second area radius = 2.0; area = radius * radius * 3.14159; System.out.println("The area is “ + area + " for radius "+radius); Write name of the variables: _____________ _________________ _______________ ________ 20 Variable Declaration Declaring Assignment Declare & Variables Statements Initialization int x; X = 10; Int X = 10; double radius; Radius = 3.49; Double Radius = 3.49; char a; a = ‘A’; Char a = ‘A’; 21 Name Constant Declaring a constant variables Must be initialize during declaration. Why? Syntax: final datatype CONSTANTNAME = VALUE; Examplefinal double PI = 3.14159; final int SIZE = 3; 22 Variable Naming Conventions Choose meaningful and descriptive names. Variables and method names: Use lowercase. If the name consists of several words, concatenate all in one. use lowercase for the drst word, and capitalize the drst letter of each subsequent word in the name. For example, the variables radius and area, and the method computeArea. 23 Variable Naming Conventions Class names: Capitalize the drst letter of each word in the name. For example, the class name ComputeArea. Constants: Capitalize all letters in constants, and use underscores to connect words. For example, the constant PI and MAX_VALUE 24 Reading Input from the Console (Keyboard) Create a Scanner object Scanner input = new Scanner(System.in); Use the method nextDouble() to obtain a double value. For example, System.out.print("Enter a double value: "); Scanner input = new Scanner(System.in); double d = input.nextDouble(); Java read the data as a string from the keyboard using the SCANNER object. We are using di`erent methods to read the data from the input string as 25 Output Statement (Display data on screen) System.out.print(“Java World!"); It display data on the Screen and control will still wait on the same line System.out.println(“Java World!"); It display data on the Screen and control will move to the next line 26 Java Data Types 27 Java – Data Types 28 Operators used in Java Also called Relational Operators 29 Augmented Assignment Operators 30 Type Casting Implicit casting double d = 3; (type widening) Explicit casting int i = (int)3.0; (type narrowing) int i = (int)3.9; (Fraction part is truncated) What is wrong? int x = 5 / 2.0; 31 3 Selections The boolean Type and Operators Sometimes we need to compare two values, to check whether the value is greater than or less than from the other. Java provides six comparison operators (also known as relational operators) that can be used to compare two values. The result of the comparison is a Boolean value: TRUE or FALSE. boolean b = (1 > 2); 33 Relational (Comparison) Operators Java Mathematics Name Example Result Operator Symbol (radius is 5) < < less than radius < 0 false greater than radius > 0 true >= ≥ greater than or equal to radius >= 0 true == = equal to radius == 0 false != ≠ not equal to radius != 0 true 34 One-way IF Statements It’s a conditional statement Used to control the execution of the statement(s). Condition is a Boolean Expression and is evaluated to either True or False 35 Short Quiz - 01 Write a program that prompts the user to enter an integer. If the number is a multiple of 5, print HiFive. If the number is divisible by 2, print HiEven. 36 Two-way if Statements ( IF – Else Statement) It’s a conditional statement Used to control the execution of the statement(s). Condition is a Boolean Expression and is evaluated to either True or False 37 Multiple Alternative if Statements 38 Multiple Alternative if Statements 39 Short Quiz - 02 Draw Flow-Chart for the following algorithm. 40 ELSE – Clause matching with IF The else clause matches the most recent if clause in the same block. 41 Short Quiz - 03 What will be output of the following code segment? Record Your Answer Here: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B"); 42 Short Quiz - 04 What will be output of the following code segment? Record Your Answer Here: if (radius >= 0); { area = radius*radius*PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); } If there’s error then what kind of error is that: 43 Logical Operators Logical Operators are used to combine the Boolean Expression. Operat Name Description Reference to or Gates ! NOT Logical negation NOT – Gate && AND Logical AND – Gate conjunction || OR Logical OR – Gate 44 switch Statements Conditional Statement. It provide another way to decide which statement to execute next. The switch statement evaluates an expression, then attempts to match the result to one of several possible cases. The match must be an exact match. Provide a better alternatives than a large Switch-Expression is not a Boolean series of IF-ELSE-IF stataement. Expression, so it’s answer is not in 45 True or False switch Statement Rules The switch-expression must be enclosed in parenthesis. Switch-Expression yield a value of char, byte, short, or int type. The Switch-Expression and cases must have same data-types. The case-Value are constant values and cannot contain variables. When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until either a 46 break statement or the end of the switch statement switch Statement Rules The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. The default case, which is optional, can be used to perform actions when none of the specided cases matches the switch-expression. 47 Short Quiz - 05 What will be output of the following code segment? public class Test { What will be the answer for: public static void main(String[] args){ int day = 5; String dayString; switch (day) { Day = 3, answer: case 1: dayString = "Monday"; break; case 2: dayString = "Tuesday"; break; _______________________ case 3: dayString = "Wednesday"; break; case 4: dayString = "Thursday"; break; Day = 7, answer: case 5: dayString = "Friday"; break; case 6: dayString = "Saturday"; break; _______________________ case 7: dayString = "Sunday"; break; default: dayString = "Invalid day"; break; Day = -1, answer: } System.out.println(dayString); ______________________ 48 }} Short Quiz - 06 What will be output of the following code segment? public class Test { What will be the answer for: public static void main(String[] args){ int day = 5; String dayString; String dayType; switch (day){ Day = 3, answer: case 1: case 2: _______________________ case 3: case 4: Day = 7, answer: case 5: dayType = "Weekday"; break; case 6: _______________________ case 7: dayType = "Weekend"; break; default: dayType= "Invalid daytype"; Day = -1, answer: } ______________________ System.out.println(dayString+" is a "+ dayType); }} 49 ?: Conditional Operator The conditional operator is a ternary operator. used to evaluate boolean expressions much like an if statement if (x > 0) y = 1 else y = - 1; y = (x > 0) ? 1 : -1; Synatx: 50 (boolean-expression) ? expression1 : expression2 Short Quiz - 07 What will be output of the following code segments, if num=11? if (num % 2 == 0) Record your answer here: System.out.println(num + “is even”); else System.out.println(num + “is odd”); System.out.println( Record your answer here: (num % 2 == 0)? num + “is even” : num + “is odd”); Record your opinion (which one is best): 51 Operator Precedence 1) var++, var-- 2) +, - (Unary plus and minus), ++var,--var 3) (type) Casting 4) ! (Not) 5) *, /, % (Multiplication, division, and remainder) 6) +, - (Binary addition and subtraction) 7) = (Relational operators) 8) ==, !=; (Equality) 9) ^ (Exclusive OR) 10) && (Conditional AND) Short-circuit AND 11) || (Conditional OR) Short-circuit OR 12) =, +=, -=, *=, /=, %= (Assignment operator) 52 Operator Associativity The expression in the parentheses is evaluated drst. (Parentheses can be nested, in which case the expression in the inner parentheses is executed drst.) When evaluating an expression without parentheses, the operators are applied according to the precedence rule and the associativity rule. If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left- associative 53 Operator Associativity When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation. All binary operators except assignment operators are left-associative. a – b + c – d is equivalent to ((a – b) + c) – d Assignment operators are right-associative. Therefore, the expression a = b += c = 5 is equivalent to a = (b += (c = 5)) 54 Operator Associativity Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows: 3 + 4 * 4 > 5 * (4 + 3) - 1 (1) inside parentheses first 3 + 4 * 4 > 5 * 7 – 1 (2) multiplication 3 + 16 > 5 * 7 – 1 (3) multiplication 3 + 16 > 35 – 1 (4) addition 19 > 35 – 1 (5) subtraction 19 > 34 (6) greater than false 55 4 Mathematical Functions, Characters & Strings Mathematical Functions In Java, mathematical functions are implemented as methods on the Math-Class. It is a part of the built-in java.lang package and you don’t need to import it. The Math-Class also provides constants for the mathematical values PI and E. The Math-Class have a number of Class methods: Trigonometric Methods Exponent Methods Rounding Methods min, max, abs, and random Methods 57 Trigonometric Methods The Trigonometric Methods of the Math-Class provides all functionality for the Trigonometry. Some of the Trigonometry functions are: sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a) Examples: Math.sin(0) returns 0.0 Math.sin(Math.PI / 6) returns 0.5 Math.sin(Math.PI / 2) returns 1.0 Math.cos(0) returns 1.0 Math.cos(Math.PI / 6) returns 0.866 Math.cos(Math.PI / 2) returns 0 58 Exponent Methods There are dve methods related to exponents in the Math-Class 1. exp(double a) Returns e raised to the power of a. Examples: 2. log(double a) Returns the natural logarithm Math.exp(1) returns 2.71 of a. Math.log(2.71) returns 1.0 3. log10(double a) Math.pow(2, 3) returns 8.0 Returns the 10-based logarithm of a. Math.pow(3, 2) returns 9.0 4. pow(double a, double b) Math.pow(3.5, 2.5) returns 22.91765 Returns a raised to the power of b. Math.sqrt(4) returns 2.0 5. sqrt(double a) Math.sqrt(10.5) returns 3.24 Returns the square root of a. 59 Rounding Methods The Math-Class contains dve Rounding Methods 1.double ceil(double x) Examples: x rounded up to its nearest integer. This Math.ceil(2.1) returns 3.0 integer is returned as a double value. Math.ceil(2.0) returns 2.0 Math.ceil(-2.0) returns –2.0 2.double floor(double x) Math.ceil(-2.1) returns -2.0 x is rounded down to its nearest integer. Math.floor(2.1) returns 2.0 This integer is returned as a double Math.floor(2.0) returns 2.0 value. Math.floor(-2.0) returns –2.0 Math.floor(-2.1) returns -3.0 3.double rint(double x) Math.rint(2.1) returns 2.0 x is rounded to its nearest integer. If x is Math.rint(2.0) returns 2.0 equally close to two integers, the even Math.rint(-2.0) returns –2.0 one is returned as a double. Math.rint(-2.1) returns -2.0 Math.rint(2.5) returns 2.0 4.int round(float x) Math.rint(-2.5) returns -2.0 Return (int)Math.Xoor(x+0.5). Math.round(2.6f) returns 3 Math.round(2.0) returns 2 5.long round(double x) Math.round(-2.0f) returns -2 Return (long)Math.Xoor(x+0.5). Math.round(-2.6) returns -360 min(), max(), abs() and random() max(a, b)and min(a, b) Examples: Returns the maximum or minimum of two Math.max(2, 3) returns 3 Math.max(2.5, 3) returns 3.0 parameters. Math.min(2.5, 3.6) returns 2.5 Math.abs(-2) returns 2 abs(a) Math.abs(-2.1) returns 2.1 Returns the absolute value of the parameter. random() Returns a random integer (int)(Math.random() * 10) between 0 and 9. Returns a random double value in the range [0.0, 50 + (int)(Math.random() * 50) Returns a random integer 1.0). between 50 and 99. 61 Character Data Type char letter = 'A'; (ASCII) char numChar = '4'; (ASCII) char letter = '\u0041'; (Unicode) [ 4 hexadecimal ] char numChar = '\u0034'; (Unicode) [ 4 hexadecimal ] The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character b. char ch = 'a'; 62 Unicode Format Java characters use Unicode, a 16-bit encoding scheme established by the Unicode Consortium to support the interchange, processing, and display of written texts in the world’s diverse languages. Unicode takes two bytes, preceded by \u, expressed in four hexadecimal numbers that run from '\u0000' to '\uFFFF'. So, Unicode can represent 65535 + 1 characters. Unicode \u03b1 \u03b2 \u03b3 for three Greek letters 63 ASCII Code for Commonly Used Characters Characters Code Value in Decimal Unicode Value '0' to '9' 48 to 57 \u0030 to \u0039 'A' to 'Z' 65 to 90 \u0041 to \u005A 'a' to 'z' 97 to 122 \u0061 to \u007A Escape Sequences for Special Characters 64 Casting between char and Numeric Types int i = 'a'; // Same as int i = (int)'a'; char c = 97; // Same as char c = (char)97; if (ch >= 'A' && ch = 'a' && ch = '0' && ch