940 likes | 951 Views
This lesson provides an overview of Java programming language, covering topics such as packages, comments, classes, data types, expressions, statements, and I/O facilities.
E N D
Lesson 2The Java Prog LanAUBG ICoSCIS TeamAssoc. Prof. Stoyan Bonev March, 23 - 24, 2013 SWU, Blagoevgrad
Time Schedule March 23, Saturday - March 24, Sunday • 10:00 – 10:45 09:00 – 09:45 • 11:00 – 11:45 10:00 – 10:45 • 12:00 – 12:45 11:00 – 11:45 Lunch Break (45’) Lunch Break (45’) • 13:30 – 14:15 12:30 – 13:15 • 14:30 – 15:15 13:30 – 14:15 • 15:30 – 16:15 14:30 – 15:15
Lesson Contents • Overview of Java Programming Language • Anatomy of a Java program • Sample source text • Packages • Comments • Names – identifiers, reserved words, modifiers • Classes – data fields, methods (statements, blocks of statements ) • Components of a Java program • Data – by category • Data – by type • Expressions (incl. operands & operators) • Statements • Routines (member functions - methods) • I/O facilities • Data collections – arrays • Demo programs - examples
The Basics of a Java Program Java program: collection of classes. Classes capsulated as packages – named or unnamed Package: collection of related classes Class: collection of data items and methods Method: designed to accomplish a specific task There is a main method public static void main()in every Java program. The main method provides the control of program flow. The JVM executes application by invoking the main method 4
The package Logical entity describes user defined or API predefined package Really located as one file or as many files Syntax to mark package start: package <name>; Always first line in the source code May be omitted: program without explicit package name Reference to predefined package: import <package name>; import java.lang.*; This statement makes the methods in the library package java.lang available to the class following it. java.lang is just 1 package in the Java library or API. Primitive data types and the class String: Part of the Java language. They Don’t need to be imported Java Programming: From Problem Analysis to Program Design, 4e 5
Anatomy of a Java program: Sample source text Sample Run: Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 6
Comments Three types of comments in Java. Line comment: A line comment is preceded by two slashes (//) in a line. Paragraph comment: A paragraph comment is enclosed between /* and */ in one or multiple lines. javadoc comment: javadoc comments begin with /** and end with */. Used for documenting classes, data, methods. They can be extracted into HTML file using JDK's javadoc command. Assoc. Prof. Stoyan Bonev
Names - Identifiers • Names of entities (like variables, named constants, methods, classes, objects etc.) • 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. • An identifier can be of any length. • Java is case sensitive – ion, Ion, IOn, ION Java Programming: From Problem Analysis to Program Design, 3e
Naming Conventions • Choose meaningful and descriptive names. • Class names: • Capitalize the first letter of each word in the name. For example, the class name ComputeArea. • Named Constants: • Capitalize all letters in constants, and use underscores to connect words. For example, PI and MAX_VALUE • 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 the name. For example, the variables radius and area, and the method computeArea. Java Programming: From Problem Analysis to Program Design, 3e
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, class, void. are reserved words. 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. Java Programming: From Problem Analysis to Program Design, 3e
Data classified by Type Data Types Classified: 8 Primitive Data Types boolean, byte, short, int, long, float, double, char Abstract/Reference Data Types (classes, objects) String, Object, Frame, Person, Animal, … Array types (also reference types) Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 11
Primitive Data Types – 3 subgroups • Integral, which is a data type that deals with integers (or numbers without a decimal part) and characters • char – Unicode – 2 bytes/char, to present symbolic data • byte, short, int, long, to present numeric data fixed point • Floating-point, a data type that deals with decimal numbers • float: precision = 6 or 7 decimal places, Single (4 bytes) • double: precision = 15 decimal places, Double (8 bytes) • Boolean, a data type that deals with logical values: true, false • Memory allocated to boolean data type is 1 bit Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 12
Values and Memory Allocation for Integral Data Types Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 13
Primitive Data Types Classified by Category as: Literals Named Constants Variables Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 14
Literals (Constants) Integer literals, integer constants, or integers: 23 -67 +447 0177 0x1a Floating-point literals, floating-point constants, floating-point numbers: 12.34 +25.60 -3.15 5. .166 3.14e-2 2.78e+3 5.23e4 Character literals, character constants, or characters: 'a' '5' '+' '\n' Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 15
Named Constants Named constant Cannot be changed during program execution Declared by using the reserved word final Initialized when it is declared Example: final double CENTIMETERS_PER_INCH = 2.54; final int NO_OF_STUDENTS = 20; final charBLANK = ' '; final doublePAY_RATE = 15.75; Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 16
Variables Variable (name, value, data type, size) Content may change during program execution Must be declared before it can be used May not be automatically initialized If new value is assigned, old one is destroyed Value can only be changed by an assignment statement or an input (read) statement Example: double amountDue; int counter; char ch; int num1, num2; Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 17
Declaring and Initializing Variables int first; OR int first = 13; first = 13; char ch; OR char ch = ‘E’; ch = ‘E’; double value; OR double value = 35.68; value = 35.68; ------------------------------------------------------------- Java Programming: From Problem Analysis to Program Design, 3e 18
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. char letter = 'A'; (ASCII) char letter = '\u0041'; (Unicode) char numChar = '4'; char numChar = '\u0034'; Unicode \u03b1 \u03b2 \u03b3 for three Greek letters Java Programming: From Problem Analysis to Program Design, 3e 19
(Non-)Pointers in Java • In Java, all primitive variables are value variables. (Real, actual) • it is impossible to have a pointer to any variable of one of the primitive data types • All object variables are actually reference variables (pointers, memory addresses) to objects. • it is impossible to have anything but references to objects. You can never have a plain object variable Java Programming: From Problem Analysis to Program Design, 3e
Expressions - operands • Operands • Literals • Named Constants • Variables – regular(scalar) or indexed • Method call • Sub expression like ( … ) Java Programming: From Problem Analysis to Program Design, 3e
Arithmetic Operators and Operator Precedence 1. * / % (same precedence) 2. + - (same precedence) Operators in 1 have a higher precedence than operators in 2 When operators have the same level of precedence, operations are performed from left to right Unary operator: operator that has one operand Binary operator:operator that has two operands Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 22
Mixed Arithmetic Expressions Operands of different types Examples 2 + 3.5 6 / 4 + 3.9 Integer operands yield an integer result; floating-point numbers yield floating-point results If both types of operands are present, the result is a floating-point number Precedence rules are followed Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 23
Type Conversion (Casting) Used to avoid implicit type coercion Syntax (dataTypeName)expression Expression evaluated first, then type converted to dataTypeName Examples (int)(7.9 + 6.7) => 14 (int)(7.9) + (int)(6.7) => 13 Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 24
Conversion Rules When performing a binary operation involving two operands of different types, Java automatically converts the operand based on the following rules: 1. If one of the operands is double, the other is converted into double. 2. Otherwise, if one of the operands is float, the other is converted into float. 3. Otherwise, if one of the operands is long, the other is converted into long. 4. Otherwise, both operands are converted into int. Java Programming: From Problem Analysis to Program Design, 3e
Type Casting Implicit casting double d = 3; (type widening permitted) 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; Java Programming: From Problem Analysis to Program Design, 3e
Comparison Operators Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to Logical Operators Operator Name ! not && and || or ^ exclusive or Conditional Operator y = (x > 0) ? 1 : -1; Java Programming: From Problem Analysis to Program Design, 3e
The class String Used to manipulate strings String Sequence of zero or more characters Enclosed in double quotation marks Null or empty strings have no characters Numeric strings consist of integers or decimal numbers Length is the number of characters in a string Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 28
Strings and the Operator + Operator + can be used to concatenate two strings or a string and a numeric value or character Example "The sum = " + 12 + 26 -After this statement executes, the string assigned to str is: "The sum = 1226"; Consider the following statement: "The sum = " + (12 + 26) In this statement, because of the parentheses, you first evaluate num1 + num2 Because num1 and num2 are both int variables, num1 + num2 = 12 + 26 = 38 After this statement executes, the string assigned to str is: "The sum = 38"; Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 29
Types of statements Declaration/definition statements Executable statements Every statement in Java ends with a semicolon (;). Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 30
Blocks A pair of braces in a program forms a block that groups components of a program. • Use end-of-line style for braces. Java Programming: From Problem Analysis to Program Design, 3e
Executable Statements Assignment stmts To implement linear algorithms Selection/Decision stmts To implement branch algorithmsif, if-else, if-else if, switch Repetition/Iteration stmts To implement loop algorithms for, while, do-while, for(version foreach) Input/Output Other break, continue Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 32
Assignment Statements x = 1; // Assign 1 to x; radius = 1.0; // Assign 1.0 to radius; a = 'A'; // Assign 'A' to a; variable = variable * (expression); is equivalent to variable *= expression; Similarly, variable = variable + (expression); is equivalent to variable += expression; Java Programming: From Problem Analysis to Program Design, 3e
One-way if Statements if (radius >= 0) { area = radius * radius * PI; System.out.println("The area" + " for the circle of radius " + radius + " is " + area); } if (boolean-expression) { statement(s); } Java Programming: From Problem Analysis to Program Design, 3e
Java Programming: From Problem Analysis to Program Design, 3e
if...else Example if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area for the “ + “circle of radius " + radius + " is " + area); } else { System.out.println("Negative input"); } Java Programming: From Problem Analysis to Program Design, 3e
Switch-case switch ( N ) { // (Assume N is an integer variable.) case 1: System.out.println("The number is 1."); break; case 2: case 4: case 8: System.out.println("The number is 2, 4, or 8."); System.out.println("(That's a power of 2!)"); break; case 3: case 6: case 9: System.out.println("The number is 3, 6, or 9."); System.out.println("(That's a multiple of 3!)"); break; case 5: System.out.println("The number is 5."); break; default: System.out.println("The number is 7 or is outside range 1 to 9."); } Java Programming: From Problem Analysis to Program Design, 3e
Java Programming: From Problem Analysis to Program Design, 3e
Introducing while Loops int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; } Java Programming: From Problem Analysis to Program Design, 3e
Java Programming: From Problem Analysis to Program Design, 3e
Java Programming: From Problem Analysis to Program Design, 3e
For-loop For (int i=1, j=10; i < j; i++, j-=2) System.out.println("i="+i+" j="+j); i=1 j=10 i=2 j=8 i=3 j=6 for (int i = 0; i < 4; i++){ for( char letter = 'A'; letter <= 'A' + i; letter++) System.out.print(letter); System.out.println(); } A AB ABC ABCD Java Programming: From Problem Analysis to Program Design, 3e
Enhanced for Loop (for-each loop) JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList: for (double value: myList) System.out.println(value); In general, the syntax is for (elementType value: arrayRefVar) { // Process the value } You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array. Java Programming: From Problem Analysis to Program Design, 3e
Console Input (Read) statement Standard input stream object: System.in Input numeric data to program Separate by blanks, lines, or tabs To read data: Create an input stream object of the classScanner (import java.util.*; or import java.util.Scanner;) Use the methods such as next(), nextLine(), nextInt(), nextFloat(),nextDouble() Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 44
Input (Read) statement staticScanner console = new Scanner(System.in); Java program: static Scanner cin = new Scanner(System.in); int feet; int inches; Suppose the input is: 23 7 Feet = cin.nextInt(); //Line 1 Inches = cin.nextInt(); //Line 2 How to read a single character: char ch; ch = console.next().charAt(0); Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 45
Reading Input from the Console • 1. Create a Scanner object • Scanner cin = new Scanner(System.in); • 2. Use the methods next(), nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain to a string, byte, short, int, long, float, double, or boolean value. For example, • System.out.print("Enter a double value: "); • Scanner cin = new Scanner(System.in); • double d = cin.nextDouble(); Java Programming: From Problem Analysis to Program Design, 3e
Java Programming: From Problem Analysis to Program Design, 3e
Output (Write/Print/Display) statement Standard output object: System.out Methods print println Syntax System.out.print(stringExp); System.out.println(stringExp); System.out.println(); Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 48
Input/Output using Dialog Boxes Java Programming: From Problem Analysis to Program Design, 3e Java Programming: From Problem Analysis to Program Design, 4e 49 49
JOptionPane Input Two ways of obtaining input. • Using the Scanner class (console input) needs import java.util.Scanner; • Using JOptionPane input dialogs needs import javax.swing.JOptionPane; Java Programming: From Problem Analysis to Program Design, 3e