Programming by Java PDF
Document Details

Uploaded by MagnanimousNephrite7738
1995
Tags
Related
- CS0070 Object-Oriented Programming Module 1 PDF
- Object Oriented Programming (2nd Year 1st Sem) PDF
- CCS0023 OBJECT ORIENTED PROGRAMMING Past Paper PDF
- Introduction To Object Oriented Programming PDF
- Object-Oriented Programming Prelim Workbook PDF (2025)
- Unit-1 Introduction to Object Oriented Programming and Basic Concepts PDF
Summary
These slides provide an introduction to programming with Java, covering fundamental concepts such as data types, operators, program structure, and more. It includes examples of Java code and illustrates key principles of object-oriented programming.
Full Transcript
PROGRAMMING BY JAVA INTRODUCTION TO JAVA WHAT IS JAVA? JAVA IS A PROGRAMMING LANGUAGE AND COMPUTING PLATFORM FIRST RELEASED BY SUN MICROSYSTEMS IN 1995. PROBLEM SOLVING GETTING STARTED WITH JAVA PROGRAMMING CREATE, COMPILE AND RUNNING A JAVA APPLICATION...
PROGRAMMING BY JAVA INTRODUCTION TO JAVA WHAT IS JAVA? JAVA IS A PROGRAMMING LANGUAGE AND COMPUTING PLATFORM FIRST RELEASED BY SUN MICROSYSTEMS IN 1995. PROBLEM SOLVING GETTING STARTED WITH JAVA PROGRAMMING CREATE, COMPILE AND RUNNING A JAVA APPLICATION 2 CHARACTERISTICS OF JAVA JAVA IS SIMPLE JAVA IS OBJECT-ORIENTED JAVA IS DISTRIBUTED JAVA IS INTERPRETED JAVA IS ROBUST JAVA IS SECURE JAVA IS ARCHITECTURE-NEUTRAL JAVA IS PORTABLE JAVA’S PERFORMANCE JAVA IS MULTITHREADED JAVA IS DYNAMIC 3 Java is Simple: Java was designed to be easy to learn and use. Its syntax is straightforward, and it eliminates complex features like explicit pointers and operator overloading. Java is Object-Oriented: Java uses an object-oriented programming (OOP) paradigm, which promotes reusable and modular code by focusing on objects and their interactions. Java is Distributed: Java provides tools and libraries (e.g., RMI, CORBA) that make it easier to create distributed applications, where different parts of an application run on different systems in a network. Java is Interpreted: Java code is compiled into an intermediate form (bytecode) that is interpreted by the Java Virtual Machine (JVM) at runtime, making it platform-independent. Java is Robust: Java emphasizes early checking for errors and runtime exception handling. Features like garbage collection and memory management help prevent 4 issues like memory leaks. Java is Secure: Java includes built-in security features like the Java Security API, sandboxing, and bytecode verification to protect against unauthorized code execution. Java is Architecture-Neutral: Java bytecode is platform-independent, allowing Java applications to run on any device with a compatible JVM, regardless of hardware or operating system. Java is Portable: Because Java is architecture-neutral and its compiled bytecode can run on any system with a JVM, Java programs are highly portable across platforms. Java’s Performance: While Java is slower than low-level languages like C++, modern Just-In-Time (JIT) compilation and optimizations in the JVM ensure competitive performance. Java is Multithreaded: Java supports multithreading, allowing developers to write programs that can perform multiple tasks simultaneously, which is essential for modern applications. Java is Dynamic: Java can dynamically load new classes and resolve methods at runtime, making it adaptable to changing environments or extensions without recompilation. 5 GETTING STARTED WITH JAVA PROGRAMMING A simple java application Compiling programs Executing applications 6 A SIMPLE APPLICATION Example 1.1 //This application program prints welcome //To java! Package chapter1; Public class welcome { public static void main(string[] args) { system.Out.Println("welcome to java!"); } } 7 ANATOMY OF A JAVA PROGRAM Comments Reserved words Modifiers Statements Blocks Classes Methods The main method The exit method 8 COMMENTS In java, comments are preceded by two slashes (//) in a line, or enclosed between in one or multiple lines. When the compiler sees //, it ignores all text after // in the same line. When it sees and ignores any text between. 9 RESERVED WORDS Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. Other reserved words in example 1.1 are public, static, and void. Their use will be introduced later. 10 MODIFIERS Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. Examples of modifiers are public and static. Other modifiers are private, final, abstract, and protected. A public datum, method, or class can be accessed by other programs. A private datum or method cannot be accessed by other programs. 11 STATEMENTS A statement represents an action or a sequence of actions. The statement system.Out.Println(“Welcome to Java!"); In the program in example 1.1 is a statement to display the greeting "welcome to java!" Every statement in java ends with a semicolon (;). 12 BLOCKS A pair of braces in a program forms a block that groups components of a program. public class Test { Class block public static void main(String[] args) { System.out.println("Welcome to Java!"); Method block } } 13 CLASSES The class is the essential java construct. A class is a template or blueprint for objects. A java program is defined by using one or more classes. 14 METHODS What is system.Out.Println? It is a method: a collection of statements that performs a sequence of operations to display a message on the console. It can be used even without fully understanding the details of how it works. It is used by invoking a statement with a string argument. The string argument is enclosed within parentheses. In this case, the argument is "welcome to java!" You can call the same println method with a different argument to print a different message. 15 MAIN METHOD The main method provides the control of program flow. The java interpreter executes the application by invoking the main method. The main method looks like this: Public static void main(string[] args) { // statements; } 16 PRIMITIVE DATA TYPES AND OPERATIONS Introduce programming with an example Identifiers, variables, and constants Primitive data types Byte, short, int, long, float, double, char, boolean Expressions Operators, precedence, associativity, operand evaluation order: ++, --, *, /, %, +=, -=, *=, /=, %=, ^, &, |, +, -, Getting input from input dialog boxes Case studies (computing mortgage, and computing changes) Style and documentation guidelines 17 Syntax errors, runtime errors, and logic errors IDENTIFIERS An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($). An identifier must start with a letter, an underscore (_), or a dollar sign ($). it cannot start with a digit. An identifier cannot be a reserved word. (See appendix A, “java keywords,” for a list of reserved words). An identifier cannot be true, false, or null. An identifier can be of any length. 18 VARIABLES // 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); 19 DECLARING VARIABLES Int x; // declare x to be an // Integer variable; Double radius; // declare radius to // Be a double variable; Char a; // declare a to be a // Character variable; 20 NUMERICAL DATA TYPES (P.33) Byte 8 bits Short 16 bits Int 32 bits Long 64 bits Float 32 bits Double 64 bits 21 ASSIGNMENT STATEMENTS X = 1; // assign 1 to x; Radius = 1.0; // assign 1.0 to radius; A = 'A'; // assign 'A' to a; 22 CONSTANTS Final datatype CONSTANTNAME = VALUE; Final double PI = 3.14159; Final int size = 3; 23 OPERATORS +, -, *, /, And % 5/2 yields an integer 2. 5.0/2 yields a double value 2.5 5 % 2 yields 1 (the remainder of the division) 5.0 % 2 is not defined : modulo is defined only for integers. 24 NOTE Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. For example, System.Out.Println(1 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1); Displays 0.5000000000000001, not 0.5, and System.Out.Println(1.0 - 0.9); Displays 0.09999999999999998, not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a precise integer result. 25 EXAMPLE PROGRAM 1: ADDITION public class addition { public static void main(String[] args) { // declare variables int x, y, z; // Specify values of x and y x = 2; y = 3; z = x + y; System.out.println("x has a value of " + x); System.out.println("y has a value of " + y); System.out.println("The sum of x + y is " + z); System.exit(0); } } 26 EXAMPLE PROGRAM 2 : DIVISION public class division { public static void main ( String[] args) { //declare variables int x, y, z ; x = 12; y = 4; z = x / y ; System.out.println("x has a value of " + x); System.out.println("y has a value of " + y); System.out.println("x divided by y is " + z); System.exit(0); } } 27 COMPILING AND RUNNING A JAVA PROGRAM Java source code files (files with a.Java extension) are compiled into a format called bytecode (files with a.Class extension), which can then be executed by a java interpreter. Compiled java code can run on most computers because java interpreters and runtime environments, known as java virtual machines (vms), exist for most operating systems, including UNIX, the macintosh OS, and windows. Bytecode can also be converted directly into machine language instructions by a just-in-time compiler (JIT). 28 FOR EXAMPLE Create a file named say.. addition.Java using some editor say wordpad. From the command line type the following Javac addition.Java (java code compiled to a bytecode) A file called addition.Class(bytecode) is created, Now type Java addition (bytecode being executed by java interpreter) And you will get the results 29 ARITHMETIC EXPRESSIONS 3 4 x 10( y 5)(a b c ) 4 9x 9( ) 5 x x y is translated to (3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y) 30 SHORTCUT ASSIGNMENT OPERATORS Operator Example Equivalent += i+=8 i = i+8 -= f-=8.0 f = f-8.0 *= i*=8 i = i*8 /= i/=8 i = i/8 %= i%=8 i = i%8 31 INCREMENT AND DECREMENT OPERATORS suffix x++; // Same as x = x + 1; prefix ++x; // Same as x = x + 1; suffix x––; // Same as x = x - 1; prefix ––x; // Same as x = x - 1; 32 INCREMENT AND DECREMENT OPERATORS, CONT. int i=10; Equivalent to int newNum = 10*i++; int newNum = 10*i; i = i + 1; int i=10; Equivalent to int newNum = 10*(++i); i = i + 1; int newNum = 10*i; 33 INCREMENT AND DECREMENT OPERATORS, CONT. Using increment and decrement operators makes expressions short, But it also makes them complex and difficult to read. Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i. Its not a good programming practice. 34 public class assignment_operators { public static void main(String[] args) { // declare variables int x = 10; int y = 5; int z = 3; System.out.println("x = "+x+", y = "+y+", z = "+z); x++; // x = x+1; y += x; // y = y+x; z *= x; // z = z*x; System.out.println("Now x = "+x+", y = "+y+", z = "+z); x--; // x = x-1; y *= x; // y = y*x; z %= x; // z = z%x; System.out.println("And now x = "+x+", y = "+y+", z = "+z); System.exit(0); } } 35 public class circle_area { public static void main(String[] args) { // declare variables double radius, area; // assign radius of the circle radius = 3.00; area = radius * radius * 3.14159 ; System.out.println("The area of the circle of radius " + radius + " is " + area); System.exit(0); } } 36 public class circle_area_pi { public static void main(String[] args) { final double PI = 3.14159; // declare variables double radius, area; // assign radius of the circle radius = 3.00; area = radius * radius * PI ; System.out.println("The area of the circle of radius " + radius + " is " + area); System.exit(0); } } 37 ASSIGNMENT EXPRESSIONS AND ASSIGNMENT STATEMENTS Prior to java 2, all the expressions can be used as statements. Since java 2, only the following types of expressions can be statements: Variable op= expression; // where op is +, -, *, /, or % ++variable; Variable++; --Variable; Variable--; 38 NUMERIC TYPE CONVERSION Consider the following statements: Byte i = 100; Long k = i*3+4; Double d = i*3.1+k/2; Int x = k; //(wrong) Long k = x; //(fine,implicit casting) 39 TYPE CASTING Double Float Long Int Short Byte 40 TYPE CASTING, CONT. Implicit casting Double d = 3; (type widening) Explicit casting Int i = (int)3.0; (type narrowing) What is wrong? Int x = 5/2.0; 41 ANSWER Needs explicit type cast Int x = (int) 5/2.0; 42 CHARACTER DATA TYPE Char letter = 'A'; (ASCII) Char numchar = '4'; (ASCII) Char letter = '\u0041'; (unicode) Char numchar = '\u0034'; (unicode) Special characters Char tab = ‘\t’; 43 UNICODE FORMAT Description Escape Sequence Unicode Backspace \b \u0008 Tab \t \u0009 Linefeed \n \u000a Carriage return \r \u000d 44 APPENDIX B: ASCII CHARACTER SET ASCII Character Set is a subset of the Unicode from \u0000 to \u007f 45 ASCII CHARACTER SET, CONT. ASCII Character Set is a subset of the Unicode from \u0000 to \u007f 46 CASTING BETWEEN CHAR AND NUMERIC TYPES int i = 'a'; // Same as int i = (int) 'a'; char c = 97; // Same as char c = (char)97; 47 THE BOOLEAN TYPE AND OPERATORS Boolean lightson = true; Boolean lightson = false; Boolean b = (1 > 2); && (and) (1 < x) && (x < 100) || (Or) (lightson) || (isdaytime) ! (Not) !(isstopped) 48 COMPARISON OPERATORS Operator Name < less than greater than >= greater than or equal to == equal to != not equal to 49 BOOLEAN OPERATORS Operator Name ! not && and || or ^ exclusive or 50 TRUTH TABLE FOR OPERATOR ! Truth Table for Operator ! Operand !Operand true false false true 51 TRUTH TABLE FOR OPERATOR && Operand1 Operand2 Operand1 && Operand2 false false false false true false true false false true true true 52 TRUTH TABLE FOR OPERATOR || Operand1 Operand2 Operand1 || Operand2 false false false false true true true false true true true true 53 OPERATOR PRECEDENCE HOW TO EVALUATE 3 + 4 * 4 > 5 * (4 + 3) - ++I 54 OPERATOR PRECEDENCE VAR++, VAR-- +, - (UNARY PLUS AND MINUS), ++VAR,--VAR (TYPE) CASTING ! (NOT) *, /, % (MULTIPLICATION, DIVISION, AND MODULUS) +, - (BINARY ADDITION AND SUBTRACTION) = (COMPARISON) ==, !=; (EQUALITY) & (UNCONDITIONAL AND) ^ (EXCLUSIVE OR) | (UNCONDITIONAL OR) && (CONDITIONAL AND) SHORT-CIRCUIT AND || (CONDITIONAL OR) SHORT-CIRCUIT OR =, +=, -=, *=, /=, %= (ASSIGNMENT OPERATOR) 55 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)) 56 OPERAND EVALUATION ORDER The precedence and associativity rules specify the order of the operators, but do not specify the order in which the operands of a binary operator are evaluated. Operands are evaluated from left to right in java. The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated. 57 OPERAND EVALUATION ORDER, CONT. If no operands have side effects that change the value of a variable, the order of operand evaluation is irrelevant. Interesting cases arise when operands do have a side effect. For example, x becomes 1 in the following code, because a is evaluated to 0 before ++a is evaluated to 1. Int a = 0; Int x = a + (++a); But x becomes 2 in the following code, because ++a is evaluated to 1, then a is evaluated to 1. Int a = 0; 58 Int x = ++a + a; OPERATOR PRECEDENCE HOW TO EVALUATE 3 + 4 * 4 > 5 * (4 + 3) - ++I LETS PARENTHISIZE (3 + (4 * 4) ) > ( (5 * (4 + 3)) – (++I ) ) THIS IS EVALUATES TO 19 > (35 – (++I)) THIS EVALUATES TO TRUE IF THE VALUE OF I JUST BEFORE THIS EXPRESSION IS > 15 59 EXAMPLE 2.4 COMPUTING CHANGES This program lets the user enter the amount in decimal representing dollars and cents and output a report listing the monetary equivalent in single dollars, quarters, dimes, nickels, and pennies. Your program should report maximum number of dollars, then the maximum number of quarters, and so on, in this order. 60 PROGRAMMING STYLE AND DOCUMENTATION Appropriate Comments Naming Conventions Proper Indentation And Spacing Lines Block Styles 61 APPROPRIATE COMMENTS Include a summary at the beginning of the program to explain what the program does, its key features, its supporting data structures, and any unique techniques it uses. Include your name, class section, instruction, date, and a brief description at the beginning of the program. 62 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 first word, and capitalize the first letter of each subsequent word in radius and the name. For example, the variables area, and the method computearea. 63 NAMING CONVENTIONS, CONT. Class names: Capitalize the first letter of each word in the name. For example, the class name computearea. Constants: Capitalize all letters in constants. For example, the constant PI. 64 PROPER INDENTATION AND SPACING INDENTATION INDENT TWO SPACES. SPACING USE BLANK LINE TO SEPARATE SEGMENTS OF THE CODE. 65 BLOCK STYLES USE END-OF-LINE STYLE FOR BRACES. Next-line public class Test style { public static void main(String[] args) { System.out.println("Block Styles"); } } End-of-line style public class Test { public static void main(String[] args) { System.out.println("Block Styles"); } } 66 PROGRAMMING ERRORS SYNTAX ERRORS DETECTED BY THE COMPILER RUNTIME ERRORS CAUSES THE PROGRAM TO ABORT LOGIC ERRORS PRODUCES INCORRECT RESULT 67 COMPILATION ERRORS Public class showsyntaxerrors { public static void main(string[] args) { i = 30 System.Out.Println(i+4); } 68 RUNTIME ERRORS Public class showruntimeerrors { public static void main(string[] args) { int i = 1 / 0; } } 69 LOGIC ERRORS Public class showlogicerrors { // determine if a number is between 1 and 100 inclusively Public static void main(string[] args) { // prompt the user to enter a number String input = joptionpane.Showinputdialog(null, "please enter an integer:", "Showlogicerrors", joptionpane.Question_message); Int number = integer.Parseint(input); // Display the result System.Out.Println("the number is between 1 and 100, " + "inclusively? " + ((1 < number) && (number < 100))); System.Exit(0); 70 } }