Download presentation
Presentation is loading. Please wait.
1
Introduction to Java Lecture One
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 1
2
Book’s Name The complete reference of java 2 (J2SE 6 Edition)
Author : Herbert Schieldt 2. Programming in Java2 Author : E. Balagurusamy Web Source: Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 2
3
History of Java Java is a general purpose object oriented programming language. Developed by Sun Microsystems. (James Gostling) Initially called “Oak” but was renamed as “Java” in 1995. Initial motivation is to develop a platform independent language to create software to be embedded in various consumer electronics devices. Become the language of internet. (portability and security). Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 3
4
Features of Java Simple, Small and Familiar Compiled and Interpreted
Object Oriented Platform Independent and portable Robust and Secure Distributed / Network Oriented Multithreaded and Interactive High Performance Dynamic 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 4
5
Simple, Small and Familiar
Similar to C/C++ in syntax But eliminates several complexities of No operator overloading No direct pointer manipulation or pointer arithmetic No multiple inheritance No malloc() and free() – handles memory automatically 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 5
6
Compiled and Interpreted
Java works in two stage Java compiler translate the source code into byte code. Java interpreter converts the byte code into machine level representation. Byte Code: -A highly optimized set of instructions to be executed by tehe java runtime system, known as java virtual machine (JVM). -Not executable code. Java Virtual Machine (JVM): Need to be implemented for each platform. Although the details vary from machine to machine, all JVM understand the same byte code. 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 6
7
Java Virtual Machine Java compiler produces an intermediate code known as byte code for a machine, known as JVM. It exists only inside the computer memory. Machine code is generated by the java interpreter by acting as an intermediary between the virtual machine and real machine. Java Program Java Compiler Virtual Machine Bytecode Java Interpreter Machine Code 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 7
8
Object Oriented Fundamentally based on OOP Classes and Objects
Efficient re-use of packages such that the programmer only cares about the interface and not the implementation The object model in java is simple and easy to extend. 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 8
9
Platform Independent and Portable
“Write-Once Run-Anywhere” Changes in system resources will not force any change in the program. The Java Virtual Machine (JVM) hides the complexity of working on a particular platform Convert byte code into machine level representation. 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 9
10
Robust and Secure Designed with the intention of being secure
No pointer arithmetic or memory management! Strict compile time and run time checking of data type. Exception handling It verify all memory access Ensure that no viruses are communicated with an applet. 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 10
11
Distributed and Network Oriented
Java grew up in the days of the Internet Inherently network friendly Original release of Java came with Networking libraries Newer releases contain even more for handling distributed applications RMI, Transactions 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 11
12
Multithreaded and Interactive
Handles multiple tasks simultaneously. Java runtime system contains tools to support multiprocess synchronization and construct smoothly running interactive systems. 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 12
13
High Performance Java performance is slower than C
Provisions are added to reduce overhead at runtime. Incorporation of multithreading enhance the overall execution speed. Just-in-Time (JIT) can compile the byte code into machine code. Can sometimes be even faster than compiled C code! 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 13
14
Dynamic Capable of dynamically linking a new class libraries, methods and objects. Java can use efficient functions available in C/C++. Installing new version of library automatically updates all programs 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 14
15
Language of Internet Programming
Java Applets Security Portability Applets: Special java program that can transmitted over the network and automatically executed by a java-compatible web browser. 2. Security: Java compatible web browser can download java applets without fear of viral infection and malicious agent. 3. Portable: Java applets can be dynamically downloaded to all the various types of platforms connected to the internet 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 15
16
Why portable and Secure?
. The output of java compiler is not executable code. Once JVM exists for a platform, any java program can run on it. The execution of byte code by the JVM makes java programs portable. Java program is confined within the java execution environment and cannot access the other part of the computer. 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 16
17
Basics of Java Environments
Java programs normally undergo five phases Edit Programmer writes program (and stores program on disk) Compile Compiler creates bytecodes from program Load Class loader stores bytecodes in memory Verify Verifier ensures bytecodes do not violate security requirements Execute Interpreter translates bytecodes into machine language 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 17
18
Phase 1 Editor Phase 2 Compiler Phase 3 Class Loader Bytecode Verifier
Primary Memory . Disk Editor Compiler Class Loader Program is created in an editor and stored on disk in a file ending with .java. Compiler creates bytecodes and stores them on disk in a file ending with .class. Class loader reads .class files containing bytecodes from disk and puts those bytecodes in memory. Phase 1 Phase 2 Phase 3 Bytecode Verifier Bytecode verifier confirms that all bytecodes are valid and do not violate Java’s security restrictions. Phase 4 Interpreter Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes. Phase 5 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 18
19
Java Environment Development tools-part of java development kit (JDK).
Classes and methods-part of Java Standard Library (JSL), also known as Application Programming Interface (API). JDK: Appletviewer ( for viewing applets) Javac (Compiler) Java (Interpreter) Javap (Java disassembler) Javah (for C header files) Javadoc ( for creating HTML description) Jdb (Java Debugger) 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 19
20
Java Environment 2. Application Package Interface (API)
Contains hundreds of classes and methods grouped into several functional packages: Language Support Package Utility Packages Input/Output Packages Networking Packages AWT Package Applet Package 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 20
21
The Evolution of Java 1. Java Java 1.1 (Add new library, redefine applet handling and reconfigured many features.) 3. Java 2 (Second generation). Version no:1.2 (Internal version number of java library). Also known as J2SE [ Java 2 Platform Standard Edition]. - Add swing, the collection framework, enhanced JVM etc. 4. J2SE J2SE J2SE J2SE 1.6 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 21
22
Versions of Java Three versions of the Java 2 Platform, targetted at different uses Java 2 Micro Edition (J2ME) Very small Java environment for smart cards, pages, phones, and set-top boxes Subset of the standard Java libraries aimed at limited size and processing power Java 2 Standard Edition (J2SE) The basic platform J2SE can be used to develop client-side standalone applications or applets. Java 2 Enterprise Edition (J2EE) For business applications, web services, mission-critical systems Transaction processing, databases, distribution, replication 05/07/ Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 22
23
Chapter One of the text book. Software Used for the Course:
Java 2 (Version 6) NetBean IDE J creature Sun.java.com Mosarratj Jahan, Dept. of CSE, DU Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 23
24
Concept of Object oriented Programming & Writing First Java Program
Lecture Two Concept of Object oriented Programming & Writing First Java Program Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
25
Programming languages
Three types of programming languages Machine languages Strings of numbers giving machine specific instructions Assembly languages English-like abbreviations representing elementary computer operations (translated via assemblers) Example: LOAD BASEPAY ADD OVERPAY STORE GROSSPAY High-level languages Codes similar to everyday English Use mathematical notations (translated via compilers) Example: grossPay = basePay + overTimePay Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
26
Structured Programming
Disciplined approach to writing programs Clear, easy to test and debug and easy to modify Structured programming is hard and takes time to master Can handle the program complexity up to a certain size. Recent Trend: Object-oriented Programming Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
27
Procedure Oriented Programming
The problem is viewed as a sequence of actions and a number of functions are written to solve these actions. Large problem is divided into smaller programs known as modular programming. Main program Function-1 Function-2 Function-3 Function-4 Function-5 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
28
Procedure Oriented Programming
Data move openly around the system from function to function. Employs top-down approach in program design. Global Data Global Data Function-3 Function-1 Function-2 Local Data Local Data Local Data Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
29
Object –Oriented Programming
Emphasis is on data rather than procedure. Programs are divided into objects. Data Data Functions Functions Object A Object B Functions Object C Data Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
30
Object –Oriented Programming
Objects can communicate with each other through functions. New data and functions can be easily added whenever necessary. Follow bottom up approach in program design. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
31
Basic Concepts of OOP Objects and classes Data Encapsulation
Inheritance Polymorphism Dynamic Binding Message Communication Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
32
Objects and Classes Program objects should be chosen such that they match closely with the real-world objects. Any programming problem is analyzed in terms of objects and the nature of communication between them. Objects contain data and code to manipulate that data. A class is a data type and an object is a variable of that data type. Class define the data and code that should be included in each object of that class. It is a user defined type Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
33
Data Encapsulation Inheritance
The wrapping of data and methods into a single unit is known as encapsulation. This ensures data hiding. The methods of an object provides interface between the data of the object and the program. Inheritance Inheritance is the process by which objects of one class can acquire the properties of objects of another class. It provides the idea of reusability. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
34
Polymorphism Dynamic Binding
Polymorphism means the ability to take more than one form. A general class of operations may be accessed in the same manner even though specific actions associated with each operation may differ. Dynamic Binding The code associated with a procedure call is not known until the time of the call at runtime. It is associated with polymorphism and inheritance. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
35
Message Communication
Objects communicate with each other by sending and receiving messages. Message passing involves specifying the object name, the name of the method and the information to be sent. Example : Employee . salary (name); Message Sending Object Method () Receiving Object Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
36
Advantages of OOP Through inheritance, we can eliminate redundant code and extend the use of existing classes. Inheritance leads to saving of time and higher productivity. The principle of data hiding produces more secure program. It is possible to map objects in the problem domain to those objects in program. It is easy to partition the work in a project based on object. System can easily be upgraded from small to large system. Software complexity can easily handled. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
37
Java Program Java Source Code Java Compiler Application Type
Applet Type Java Enabled Browser Java Interpreter Output Output Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
38
First Java Program-Example 1
/*This is a simple java program*/ class Example { public static void main (String args[]) System.out.println (“This is a simple Java program”); } Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
39
Simple Java Program-Some important points
public: Access specifier. main() must be made public, since it must be called by code defined outside it’s class. Static: It is required because main() is called without creating an object of it’s class String args[]: An array of objects of type String class. Each object of type string contains a character string. It is used to manipulate command line argument. Java is case sensitive. System predefined class that refers to system. out It is static data member of System class println() It is a member of out object Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
40
JRE and JDK JRE: J2SE Runtime Environment JDK: J2SE Development Kit
provides libraries, Java virtual machine, other components necessary for you to run applets and applications JDK: J2SE Development Kit includes JRE command-line development tools such as compilers and debuggers Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
41
Implementing a Java Program
Creating a java program Compiling a java program Running the program Creating a Java Program: All java source file has an extension .java. If a program contains multiple classes, the file name must be the class name of the class containing the main method. This class must be the only public class. [Rule: File name should match the name of the public class of a source code.] Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
42
Implementing a Java Program
Compiling a Java Program: To compile a java program, execute the java compiler javac, specifying the name of the source file on the command line. C:\> javac Example.java When java source code is compiled, each individual class is put into it’s own output file named after the class and using the .class extension. Each file with .class extension contains the bytecode corresponding to that class Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
43
Implementing a Java Program
To run the program, interpreter java is used the name of the class that contains the main function. c:\> java Example Actually it searches for Example. class file. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
44
Second Java Program, Constants, Data Types and Variables
Lecture Three Second Java Program, Constants, Data Types and Variables 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 44 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 44
45
First Java Program-Example 1
/*This is a simple java program*/ class Example { public static void main (String args[]) System.out.println (“This is a simple Java program”); } Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 45 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
46
Simple Java Program-Some important points
public: Access specifier. main() must be made public, since it must be called by code defined outside it’s class. Static: It is required because main() is called without creating an object of it’s class String args[]: An array of objects of type String class. Each object of type string contains a character string. It is used to manipulate command line argument. Java is case sensitive. System predefined class that refers to system. out It is static data member of System class println() It is a member of out object Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 46 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
47
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
Second Java Program class add_num { public int add(int a, int b) return a+b; } public class test { public static void main(String args[]) int a, b; a=100; b=23; add_num ob = new add_num(); System.out.println(“The addition: “+ ob.add_num(a,b)); } 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 47 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
48
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
Points to be Noted Java source code can contain multiple classes, the name of the source code must be the name of the only public class of the code. Usually public class contains the main() method, that is the starting point of program execution. Object of a class is created using new operator. Method of a class is accessed through an object of that class. + in System.out.println() method concatenate two strings. 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 48 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
49
Java is a Strongly typed Language
Every variable and expression has a strongly defined type. All assignments are checked for type compatibility. Java compiler checks all expressions and parameters to ensure that the types are compatible. 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 49 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
50
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
The Primitive Types There are exactly eight primitive data types in Java Four of them represent whole valued signed numbers: byte, short, int, long Two of them represent floating point numbers: float, double One of them represents characters: char And one of them represents boolean values: boolean 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 50 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
51
Numeric Primitive Types
The difference between the various numeric primitive types is their size, and therefore the values they can store: Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 with 7 significant digits +/- 1.7 x with 15 significant digits Max Value 127 32,767 2,147,483,647 > 9 x 1018 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 51 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
52
Character Primitive Type
It uses unicode to represent character. The char type is unsigned 16 bit values ranging from 0 to ASCII still ranges from 0 to 127. Example: class test { public static void main (String args[]) { char ch1, ch2; ch1=88; ch2=‘Y’; System.out.println (“ch1 and ch2: “ + ch1+” “+ch2); } Output: ch1 and ch2: X Y 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 52 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
53
Character Primitive Type
Example: class test { public static void main (String args[]) char ch1; ch1= ‘X’; Sytem.out.println (“ch contains “+ch1); ch1++; System.out.println (“ch1 is now “ + ch1); } Output: ch1 contains X Ch1 is now Y 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 53 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
54
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
Booleans Size is 1 bit – two value: true and false. This type is returned by all relational operators. Example: boolean b; b= true; System.out.println(“b is “+b); System.out.println(“10>9 is “ +(10>9)); Output: b is true 10>9 is true 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 54 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
55
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
Literals Integer Literals 1. base 10 – 1,2,43 etc. 2. base 8 – octal values are denoted in java by a leading 0. 3. base 16 – hexadecimal values are denoted by leading 0x or 0X. Any whole number is by default integer (32 bits). To specify a long literal, the number should appended with an upper- or lowercase L. 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 55 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
56
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
Literals Floating point Literals 1. Standard Notation – , , 2.0 etc. 2. Scientific Notation – 6.022E23, 2e+100. Floating point literals are by default of type double. To specify a float literal, we must append an F or f to the constant. Boolean Literals Two values – true and false. True is not equal 1 and false is not equal to 0. They can be assigned to variable declared as boolean. 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 56 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
57
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
Literals Character Literals: A literal character is represented inside a pair of single quotes. Escape sequence Unicode Representation Description \’ \” \\ \r \n \f \t \b \ddd \uxxxx \u0027 \u0022 \u005c \u000d \u000a \u000b \u0009 \u0008 Single quote Double quote Backslash Carriage Return New line Form feed Tab Backspace Octal Character Hexadecimal Unicode character 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 57 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
58
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
Literals String Literals A sequence of characters between a pair of double quotes. In java string must begin and end on the same line. 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 58 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
59
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
Variables Variable is a name for a location in memory. Declaring a variable: type identifier [=value][,identifier [=value]….]; The initialization expression must result in a value of the same or compatible type as that specified for the variable. When a variable is not initialized, the value of that variable is undefined. 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 59 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
60
Scope and Lifetime of a variable
A block begins with an opening curly brace and ends by a closing curly brace. A block determines scope, that defines which objects are visible to other parts of your program. Variables declared within a block localize themselves. In case of nested block, the outer block encloses the inner block. The variables declared in the outer block is visible to the inner block but the reverse is not true. A variable will not hold it’s value once it has gone out of it’s scope. In an inner block, it is not possible to declare a variable of the same name as in outer block. 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 60 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
61
Scope and Lifetime of a variable
Example: public static void main( String args[]) { int x =10; if ( x == 10) int y =20; System.out.println(“x and y: “ +x +” “+y); x= y * 2; } y= 100; //Error System.out.println (“x is “+x); 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 61 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
62
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
Chapter Three -Book of Herbert Schieldt Read about keyword, identifier, character set yourself. 8/2/2018 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 62 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
63
Type Conversion and Casting and Introduction to Class
Lecture Four Type Conversion and Casting and Introduction to Class Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
64
Automatic Type Conversion
When one type of data is assigned to another type of variable, an automatic type conversion will take place if: 1. Two types are compatible. 2. The destination type is larger than the source type. It is known as widening conversion. The numeric types, including integer and floating point types are compatible. Numeric types are not compatible with char or boolean. Char and boolean are not compatible with each other. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
65
Automatic Type Conversion
short’s variable = byte’s variable int’s variable = byte’s variable byte’s variable = int’s variable float’s variable = int’s variable int’s variable = float’s variable double’s variable = float’s variable float’s variable = double’s variable char’s variable = any other variable int’s variable = char’s variable short’s variable = char’s variable boolean variable = any other variable Any other variable = boolean variable ok ok Error ok Error ok Error Error ok Error Error Error Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
66
Casting Type Problem: assigning int value to a byte type variable.
This type of conversion is known as narrowing conversion. A cast is simply an explicit type conversion : (target_type) value Example: int a; byte b; …. b = (byte) a; Contains the remainder of an integer division by byte’s range. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
67
Casting Type class test { public static void main(String args[])
byte b; int i = 257; double d = ; b=(byte)i; System.out.println (“Conversion of int to byte: ” + i +” “+ b); i = (int)d; System.out.println(“Conversion of double to int: “ +d+” “+i); b=(byte)d; System.out.println(“Conversion of double to byte: “ +d+” “+b); } Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
68
Casting Type Output: Conversion of int to byte: 257 1
Conversion of double to int: Conversion of double to byte: Note: When assigning a fractional number’s to a whole number’s variable, fractional part is truncated. If the value of the whole number part is too large to fit into the target integer type, then that value will be reduced modulo the targest type’s range. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
69
Automatic Type Promotion in Expression
Takes place in expression. Rules: 1. All byte and short values are promoted to int. 2. If one operand is long, the whole expression is promoted to long. 3.If one operand is float, the entire expression is promoted to float. 4. If one operand is double, the entire expression is promoted to double. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
70
Automatic Type Promotion-Example
byte b =42; char c=‘a’; short s=1024; int i=50000; float f=5.67f; double d=.1234; double result = (f * b) + (i / c) – (d * s); (f * b) is promoted to float. (i / c) is promoted to int. (d *s ) is promoted to double. float + int – double = float – double = double Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
71
Automatic Type Conversion-Example
byte a =40, b= 50, c =100; int d = a * b /c; 2. byte b =50; b = b * 2; //Error 3. byte b =50; b = (cast) b * 2; Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
72
An Example of Object Oriented Programming
Colored points on the screen What data goes into making one? Coordinates Color What should a point be able to do? Move itself Report its position Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
73
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
74
Java Terminology Each point is an object Each includes three fields
Each has three methods Each is an instance of the same class Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
75
Object-Oriented Style
Solve problems using objects: little bundles of data that know how to do things to themselves Not the computer knows how to move the point, but rather the point knows how to move itself Object-oriented languages make this way of thinking and programming easier Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
76
void move (int newXCoord, int newYCoord) { xCoord = newXCoord;
class Point { int xCoord; int yCoord; Point() { xCoord = 0; yCoord = 0; } int currentX() { return xCoord; int currentY() { return yCoord; void move (int newXCoord, int newYCoord) { xCoord = newXCoord; yCoord = newYCoord; Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
77
The General Form of a Class
A class is defined by specifying the data and the code that operate on the data. The general form: class classname{ type instance-variable1; type instance-variable2; ………… type methodname1( parameter-list) { // body of the method } type methodname2( parameter-list) //body of the method …………………… Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
78
Class and Object A class defines a new data type. This new data type is used to create objects of that type. A class is a template for an object and an object is an instance of a class. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
79
Creating Objects Obtaining objects of a class is two steps process:
1. Declare a variable of the class type. 2. Acquire an actual, physical copy of the object and assign it to that variable. To allocate a physical memory new() is used. It dynamically allocates memory for an object and returns a reference to it. In Java, all class objects must be dynamically allocated. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
80
A Simple Example class Box { class BoxDemo double width; {
double height; double depth; } class BoxDemo { public static void main( String args[]) Box mybox, mybox1; mybox = new Box(); mybox1 = new Box(); mybox.width=10; mybox.height = 20; mybox. depth = 15; mybox1.width = 10; mybox1.height = 25; mybox1.depth=5; } Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
81
A Simple Example- Some points
Members are linked to an object using dot (.) operator. Each object contains its own copy of each instance variables defined by the class. The java compiler automatically puts each class into it’s own .class file. - For this example, two .class files: 1. Box.class 2. BoxDemo.class Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
82
A Simple Example- Some points
new() is used to dynamically allocate memory for an object. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
83
A Closer Look at New Box mybox; mybox = new Box(); Box b1 = new Box();
Box b2 = b1; null mybox Width Height mybox Depth Call to the default constructor defined by the compiler. It initializes the instance variables to 0. b1 Width Height b2 Depth Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
84
References An reference variable holds the memory address.
It is similar to the pointer. Key difference- cannot manipulate as pointer– It point any arbitrary memory location or it cannot be manipulate like an integer. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
85
The null Reference An object reference variable that does not currently point to an object is called a null reference The reserved word null can be used to explicitly set a null reference: name = null; An object reference variable declared at the class level (an instance variable) is automatically initialized to null The programmer must carefully ensure that an object reference variable refers to a valid object before it is used Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
86
Instance variables Default initialization
If the variable is within a method, Java does NOT initialize it. If the variable is within a class, Java initializes it as follows: Numeric instance variables initialized to 0 Logical instance variables initialized to false Object instance variables initialized to null Each instance variable is defined without specifying an initial value. Therefore, whenever a new ColoredRectangle object is to be constructed, Java first initializes the new instance variables to default values. By default, numeric instance variables are initialized to 0, boolean instance variables are initialized to false, and reference-type instance variables are initialized to null. Thus, every time a new ColoredRectangle object is to undergo construction, new width, height, x, y, window, and color instance variables are created and default initialized for the new object. The numeric attributes width, height, x, and y are initialized to zero and the class-type attributes window and color are initialized to null. The instance variable definitions specify each of the variable to be private. This modifier indicates that direct access to the instance variables is limited to the class itself. Thus, class ColoredRectangle practices information hiding by encapsulating its attributes. Defining instance variables to be private is a standard practice. When attributes are private, other classes are forced to use the class’s interface methods to manipulate its attributes. Those interface methods normally are programmed to ensure that the requested manipulations are valid. Because the initial definition of class ColoredRectangle does not provide any methods to give access to the attributes, once a ColoredRectangle is constructed it is immutable. In Section , we introduce several ColoredRectangle methods for accessing and modifying the attributes of a ColoredRectangle object. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
87
-Book of Herbert Schieldt
Chapter Three and Six -Book of Herbert Schieldt Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
88
Import Statement & Taking Input
Lecture Five Import Statement & Taking Input Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
89
Import Statement A java package is a collection of related classes.
In order to access the available classes in the package, the program must specify the complete dot seperated package path. The general format: import package-level1.[package-level2.]classname|* Two form of import statement: 1. import.package.class; 2. import package.*; Example: import java.util.Scanner; import java.util.*; Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
90
Example java.lang in automatically imported with every java program.
import java.util.Random; class random { public static void main(String args[]) Random r = new Random(); int i; float v; for(i=0;i<5;i++) v=r.nextFloat(); System.out.println(v); } Output: java.lang in automatically imported with every java program. System.out.println() belongs to java.lang. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
91
Predefined Stream Stream:
-A stream is an abstraction that either produces or consumes information. -It is linked to a physical device by a java I/O system. -The hide the details of the physical device to which they are connected. System: -System is a predefined class included in the package java.lang. (Imported automatically by all java programs). -It includes three predefined stream variables: 1. in 2. out err Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
92
The Predefined Streams
System.out: refers to the standard output stream. It is an object of type PrintStream. System.in: refers to the standard input stream. It is an object of type InputStream. System.err: refers to the standard error stream. It is an object of type PrintStream. Note: they are defined as public and static. InputStream: This class in included in the package java.io. It has some subclasses the handle the differences between various devices. Includes some methods that the subclasses will implement. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
93
Scanner Class Scanner class is used to read input from the keyboard, a file, a string or any source that implements the Readable or ReadByteChannel. Scanner can be created for a string, an InputStream, or any object that implements Readable or ReadByteChannel interface. Scanner class is under the package of java.util Added in J2SE 5. Readable Interface: It is added by J2SE. It is included in Java.lang. It defines one method: int read(CharBuffer buf) throws IOException It reads characters into buf. It returns the number of characters read or -1 if an EOF is encountered. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
94
Taking Input from the Keyboard
First, Scanner class is connected to System.in which is an object of type InputStream. Then, it uses it’s internal functions to read from System.in Example: Scanner test = new Scanner(System.in); Calls the constructor Scanner(InputStream) Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
95
Take an input from the keyboard-1
import java.util.*; public static void main(String[] args) { int value; System.out.print(“Enter an Integer number:"); Scanner tmp = new Scanner(System.in); if(tmp.hasNextInt()) { value=tmp.nextInt(); System.out.println(“You have entered: ”+value); } else System.out.println(“Not an Integer”); Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
96
Taking Input from the KeyBoard-2
import java.util.*; class input { public static void main(String args[]) Scanner tmp = new Scanner(System.in); float i; while(tmp.hasNextFloat()) i=tmp.nextFloat(); System.out.println("The Number: ",i); } Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
97
Scanning Basics A Scanner reads tokens from the underlying source.
A token is a portion of input that is delineated by a set of delimiters, which is by default whitespace. A token is read by matching it with a particular regular expression. Scanner follow the procedure below: 1. Determine if a specific type of input is available by calling one of the hasNextX methods. 2. If input is available, read it by calling one of nextX method. 3. Repeat the process until the input is exhausted. Note: if nextX() method does not find a matching token, it throws a NoSuchElementException. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
98
Important Methods of Scanner Class
public Scanner(InputStream in) // Scanner(): convenience constructor for an InputStream object boolean hasNext() //Return true if another token of any type is available to be read. boolean hasNextBoolean() //Return true if a boolean value is available to read. boolean hasNextByte() //Return true if a byte value is available to read. boolean hasNextShort() //Return true if a byte value is available to read. boolean hasNextInt() //Return true if a int value is available to read. boolean hasNextLong() //Return true if a long value is available to read. boolean hasNextFloat() //Return true if a float value is available to read. boolean hasNextDouble() //Return true if a double value is available to read. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
99
Important Methods of Scanner Class
int nextInt() // return next token as int value. short nextShort() // return next token as short value. byte nextByte() // return next token as byte value. long nextLong() // return next token as long value. double nextDouble() // return next token as double value float nextFloat() // return next token as float value String next() //return next token of any type from the input source String nextLine() // return the next line of input as a string Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
100
Taking Input from the File
The following lines read data from a file: FileReader fin = new FileReader(“c:\\f_input.txt”); Scanner test = new Scanner(fin); FileReader: - belongs to java.io package. -It creates an object that can read the content of a file. Calls the constructor Scanner (Readable from) -Creates a Scanner that uses the Readable Object Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
101
Taking Input from the File
import java.io.*; import java.util.*; class file_input { public static void main(String args[]) throws IOException double i; String str; FileReader fin = new FileReader("c:\\f_input.txt"); Scanner test = new Scanner(fin); while(test.hasNext()) if(test.hasNextDouble()) i=test.nextDouble(); System.out.println("The number is:" + i); } else str = test.next(); System.out.println(str); fin.close(); Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
102
Taking Input from a File
Suppose the file contains the following data: done Output: The number is: 2.0 The number is: 3.4 The number is: 5.0 The number is: 6.0 The number is: 7.4 The number is: 9.1 The number is: 10.5 done Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
103
Writing Data into a File
import java.io.*; class test { public static void main (String args[]) FileWriter fout = new FileWriter(“c:\\test1.txt”); fout.write(“ done”); fout.close(); } Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
104
Chapter 18—Scanner Class [Page 543-534]
Chapter 9- Importing Packages [Page ] Chapter 16- Math Library [Page ] Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
105
Homework (Math Library)
Suppose you are given the following double a=56.34, b= , c= ; Calculate the following value: Print a random number. Find the absolute value of the variable c Find the square root of a Find the maximum value between a and b Calculate the value ab Round the number a Calculate the value of √(a2+b2) Find the floor, ceil and round value of b and c Find the radian value of a. Find the sin value of a where a represents the degree Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
106
Array in Java Lecture Six
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
107
One-Dimensional Array
Creating an array is a two steps process: 1. type var_name[]; 2. var_name = new type [size]; Example: int month_days []; month_days = new int [12]; - first line declares month_days as an array variable, no array actually exists. - Actual, physical array of integers, is allocated using new and assign it to month_days. -The elements of array are automatically initialized to 0. int month_days [] = new int[12]; Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
108
One-Dimensional Array
Once array is created, a specific element in the array can be accessed by specifying it’s index within square brackets. Example: month_days[0]=31; month_days[1]=28; Arrays can be initialized when they are declared. Example: int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
109
Features of Java to Manipulate Array
All arrays are dynamically allocated. Size of the array can be specified at the runtime. Index type is integer and the index range must be 0 to n-1, where n is the number of elements. Java runtime system will check to be sure that all array indexes are in the correct range. Incorrect reference will generate ArrayIndexOutofBoundsException. Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
110
Example import java.util.Scanner; class array_avg {
public static void main(String args[]) int i,sum=0; float avg; int a[] = new int[5]; Scanner test=new Scanner(System.in); System.out.println("Enter the input:"); for(i=0;i<5;i++) if(test.hasNextInt()) a[i]=test.nextInt(); sum=sum+a[i]; } avg=sum/5; System.out.println("The average value is: " + avg); Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
111
Array in Java int a[]; int b[] = null; int c[] = new int[5];
int d[] = { 1, 2, 3, 4, 5 }; a = c; d = c; null a - b null c can only reference char arrays v can only reference int arrays c 1 2 3 4 5 d Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
112
Multi-Dimensional Arrays
A two-dimensional array can be declared as int twoD [] [] = new int[4][5]; Represents column [0][0] [0][1] [0][2] [0][3] [0][4] [1][0] [1][1] [1][2] [1][3] [1][4] [2][0] [2][1] [2][2] [2][3] [2][4] [3][0] [3][1] [3][2] [3][3] [3][4] Represents row Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
113
Example int i,j; Scanner test=new Scanner(System.in);
int tmp[][] = new int[3][3]; int i,j; Scanner test=new Scanner(System.in); for(i=0;i<3;i++) for(j=0;j<3;j++) { System.out.print("Enter Input:"); if(test.hasNextInt()) tmp[i][j]=test.nextInt(); } System.out.print(tmp[i][j] + " "); System.out.println(); Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
114
Multi-dimensional Array
int twoD [][] = new int[4][]; twoD[0] = new int[5]; twoD[1] = new int[4]; twoD[2] = new int[3]; int m [][]={{1,2},{2,3}}; Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
115
Example Output: 1 2 3 4 5 int a[][]=new int[3][]; a[0]=new int[1];
int i,j,k=0; for(i=0;i<3;i++) for(j=0;j<i+1;j++) { a[i][j]=k; k++; } System.out.print(a[i][j]+” “); System.out.println(); Output: 1 2 3 4 5 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
116
Alternative Array Declaration Syntax
Type [] var_name; Example: int [] a = new int[3]; int [] num1, num2, num3; same as int num1[], num2[], num3[]; Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
117
Array as an Object An array is implemented as an object.
It has a special attribute: length instance variable. Example: int a1[] = new int[10]; int a2[] = {3, 5, 7, 9, 11, 13, 15, 17}; int a3[] = {4, 3, 2, 1}; System.out.println(“length of a1 is: ”+a1.length); System.out.println(“length of a2 is: ”+a2.length); System.out.println(“length of a3 is: ”+a3.length); Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
118
Decision Making, Branching and Looping
Lecture Seven Decision Making, Branching and Looping 04/08/08 Md.Samsuzzaman, lecturer ,Dept of CCE,PSTU 118 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
119
Decision Making and Branching
When a program breaks the sequential flow and jumps to another part of the code, it is known as branching. When branching is done on a condition it is known as conditional branching. Three decision making statements: 1. if statement 2. switch statement 3. conditional operator statement 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 119 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
120
The if Statement The if statement has the following syntax:
The condition must be a boolean expression. It must evaluate to either true or false. if is a Java reserved word if (condition) statement; Statement x; If the condition is true, the statement is executed. If it is false, the statement is skipped. 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 120 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
121
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
The if-else Statement An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; Statement x; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 121 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
122
Nested if….Else Statements
The if..else statement can be contained in another if or else statement. if (test condition1) { if (test condition2) statement-1; else statement-2; } statement-3; statement-x; 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 122 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
123
Nested if….Else Statements
An else clause is matched to the last unmatched if (no matter what the indentation implies!) Example: if(female) if(bal>5000) bon = 0.05 * bal; else bon = 0.02 * bal; bal = bal + bon; Braces can be used to specify the if statement to which an else clause belongs 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 123 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
124
Multiway Selection: Else if
Sometime you want to select one option from several alternatives if (conditon1) statement1; else if (condition2) statement2; else if (condition3) statement3; else statement4; conditon1 evaluated conditon2 conditon3 statement1 statement2 statement3 statement4 true false 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 124 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
125
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
Else if example double numberGrade = 83.6; char letterGrade; if (numberGrade >= 89.5) { letterGrade = ‘A’; } else if (numberGrade >= 79.5) { letterGrade = ‘B’; } else if (numberGrade >= 69.5) { letterGrade = ‘C’; } else if (numberGrade >= 59.5) { letterGrade = ‘D’; } else { letterGrade = ‘F’; } System.out.println(“My Grade is ” + numberGrade + “, ” + letterGrade); Output: My Grade is 83.6, B 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 125 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
126
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
The switch Statement The switch statement provides another means 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 expression of a switch statement must result in an integral type, meaning an int or a char Each case contains a value and a list of statements The flow of control transfers to statement associated with the first value that matches 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 126 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
127
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
The switch Statement The general syntax of a switch statement is: switch (expression) { case value1: statement-list1 case value2: statement-list2 case value3: statement-list3 } switch and case are reserved words If expression matches value2, control jumps from here 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 127 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
128
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
The switch Statement Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this can be appropriate, but usually we want to execute only the statements associated with one case 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 128 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
129
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 129 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
130
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
Switch example char letter = 'b'; switch (letter) { case 'a': System.out.println("A"); break; case 'b': System.out.println("B"); case 'c': System.out.println("C"); case 'd': System.out.println("D"); default: System.out.println(”?"); } B char letter = 'b'; switch (letter) { case 'a': System.out.println("A"); case 'b': System.out.println("B"); case 'c': System.out.println("C"); break; case 'd': System.out.println("D"); default: System.out.println(”?"); } B C 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 130 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
131
The Conditional Operator
Java has a conditional operator that evaluates a boolean condition that determines which of two other expressions is evaluated The result of the chosen expression is the result of the entire conditional operator Its syntax is: condition ? expression1 : expression2 If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 131 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
132
The Conditional Operator
The conditional operator is similar to an if-else statement, except that it forms an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); if (num1 > num2) larger = num1; else larger = num2; The conditional operator is ternary because it requires three operands 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 132 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
133
The Conditional Operator
Another example: System.out.println ("Your change is " + count + ((count == 1) ? "Dime" : "Dimes")); If count equals 1, then "Dime" is printed If count is anything other than 1, then "Dimes" is printed 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 133 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
134
Repetition Statements
Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: the while loop the do loop the for loop The programmer should choose the right kind of loop for the situation 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 134 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
135
The while Statement The while statement has the following syntax:
while (condition) statement; while is a reserved word If the condition is true, the statement is executed. Then the condition is evaluated again. The statement is executed repeatedly until the condition becomes false. 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 135 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
136
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
Logic of a while Loop condition evaluated false statement true Note that if the condition of a while statement is false initially, the statement is never executed. Therefore, the body of a while loop will execute zero or more times 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 136 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
137
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
while Loop Example final int LIMIT = 5; int count = 1; while (count <= LIMIT) { System.out.println(count); count += 1; } Output: 1 2 3 4 5 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 137 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
138
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
Infinite Loops The body of a while loop eventually must make the condition false If not, it is an infinite loop 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 138 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
139
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop Each time through the outer loop, the inner loop goes through its full set of iterations 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 139 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
140
The do Statement The do statement has the following syntax: do and do{
while are reserved words do{ statement; } while (condition); The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 140 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
141
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
do-while Example final int LIMIT = 5; int count = 1; do { System.out.println(count); count += 1; } while (count <= LIMIT); Output: 1 2 3 4 5 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 141 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
142
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
Comparing while and do statement true condition evaluated false while loop true condition evaluated statement false do loop 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 142 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
143
condition becomes false
The for Statement The for statement has the following syntax: The initialization is executed once before the loop begins The statement is executed until the condition becomes false Reserved word for (initialization; condition; increment) statement; The increment portion is executed at the end of each iteration The condition-statement-increment cycle is executed repeatedly 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 143 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
144
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while (condition) { statement; increment; } 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 144 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
145
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
Logic of a for loop initialization condition evaluated false statement true increment 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 145 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
146
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
The for Statement Like a while loop, the condition of a for statement is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times It is well suited for executing a loop a specific number of times that can be determined in advance 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 146 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
147
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
for Example final int LIMIT = 5; for (int count = 1; count <= LIMIT; count++) { System.out.println(count); } Output: 1 2 3 4 5 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 147 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
148
Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU
The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed Both semi-colons are always required in the for loop header 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 148 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
149
Choosing a Loop Structure
When you can’t determine how many times you want to execute the loop body, use a while statement or a do statement If it might be zero or more times, use a while statement If it will be at least once, use a do statement If you can determine how many times you want to execute the loop body, use a for statement 04/08/08 Md.Samsuzzaman,lecturer ,Dept of CCE,PSTU 149 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
150
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Lecture Eight Java Operators 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 150 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
151
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Operators in Java Classified into four groups: Arithmetic Operator Bitwise Operator Relational Operator Logical Operator 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 151 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
152
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Arithmetic Operators Addition Subtraction Multiplication * Division / Remainder % Increment Addition Assignment = Subtraction Assignment = Multiplication Assignment *= Division Assignment /= Modulus Assignment %= Decrement 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 152 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
153
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Arithmetic Operators If either or both operands associated with an arithmetic operator are floating point, the result is a floating point. % operator applies both to floating-point type and integer types. Example: class modulus { public static void main (String args []) int x = 42; double y = 42.3; System.out.println(“x mod 10 =“ + x%10); System.out.println(“y mod 10 = “ + y%10); } Output: x mod 10 =2 y mod 10 = 2.3 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 153 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
154
Increment and Decrement
The increment and decrement operators are arithmetic and operate on one operand The increment operator (++) adds one to its operand The decrement operator (--) subtracts one from its operand The statement count++; is functionally equivalent to count = count + 1; 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 154 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
155
Increment and Decrement
The increment and decrement operators can be applied in prefix form (before the operand) or postfix form (after the operand) When used alone in a statement, the prefix and postfix forms are functionally equivalent. That is, count++; is equivalent to ++count; 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 155 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
156
Increment and Decrement
When used in a larger expression, the prefix and postfix forms have different effects In both cases the variable is incremented (decremented) But the value used in the larger expression depends on the form used. If count currently contains 45, then the statement total = count++; assigns 45 to total and 46 to count If count currently contains 45, then the statement total = ++count; assigns the value 46 to both total and count 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 156 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
157
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Assignment Operators The right hand side of an assignment operator can be a complex expression The entire right-hand expression is evaluated first, then the result is combined with the original variable 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 157 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
158
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Assignment Operators There are many assignment operators, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 158 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
159
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Bitwise Operator ~ Bitwise unary NOT & Bitwise AND | Bitwise OR ^ Bitwise XOR >> Shift Right >>> Shift Right zero fill << Shift left & = Bitwise AND Assignment |= Bitwise OR Assignment ^= Bitwise XOR Assignment >>= Shift Right Assignment >>>= Shift Right zero fill Assignment <<= Shift Left Assignment 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 159 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
160
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Bitwise Operator Applied to integer type – long, int, short, byte and char. A B A | B A & B A^ B ~A 1 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 160 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
161
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
The Left Shift byte a=8, b=24; int c; c=a<<2; << 2 = =32 Java’s automatic type conversion produces unexpected result when shifting byte and short values. Example: byte a = 64, b; int i; i = a<<2; b= (byte) (a<<2); i = 256 b = 0 Each left shift double the value which is equivalent to multiplying by 2. 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 161 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
162
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
The Right Shift byte a=8, b=24; int c ; c=a>>2; >> 2= =2 Use sign extension. Each time we shift a value to the right, it divides that value by two and discards any remainder. The Unsigned Right Shift int c; c=a>>> >>> 1= =4 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 162 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
163
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Relational operators > greater than >= greater than or equal to < less than <= less than or equal to = = equal to != not equal to The outcome of these operations is a boolean value. = = , != can be applied to any type in java. Only numeric types are compared using ordering operator. 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 163 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
164
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Relational Operator int done; …… if(!done) … // Valid in C /C++ but not in java if(done)…. if (done == 0)…. if(done!=0) …… //Valid in Java 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 164 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
165
Boolean Logical Operator
& Logical AND | Logical OR ^ Logical XOR || Short-circuit OR && Short-circuit AND ! Logical unary NOT &= AND Assignment |= OR Assignment ^ = XOR Assignment = = Equal to != Not equal to ?: Ternary if-then-else 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 165 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
166
Boolean Logical Operator
The logical boolean operators &, | and ^ operates in the same way that they operate on the bits of integer. a b a & b a | b a ^ b !a true True false ture 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 166 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
167
Short Circuit Logical Operators
|| Short circuit logical OR && Short circuit logical AND If the left operand is sufficient to determine the result, the right operand is not evaluated if (demon !=0 && num / demon >10) This type of processing must be used carefully 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 167 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
168
The Conditional Operator
The conditional operator is similar to an if-else statement, except that it forms an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater that num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger The conditional operator is ternary because it requires three operands 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 168 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
169
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Operator Precedence Highest ( ) [] ~ ! * / % >> >>> << > >= < <= = = != & ^ | && || ?: = op= Lowest 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 169 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
170
Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU
Chapter Four of your text book. 8/2/2018 Md.Samsuzzaman,Lecturer,Dept of CCE,PSTU 170 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
171
Introduction to Class with Example
Lecture Nine Introduction to Class with Example Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
172
Creating a Car class What properties does a car have in the real world? Color Position (x,y) Fuel in tank We will implement these properties in our Car class class Car { private Color color; private int xpos; private int ypos; private int fuel; //... } 8/2/2018 Md.Samsuzzaman 172 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
173
Car’s instance variables
class Car { private Color color; private int xpos; private int ypos; private int fuel; //... } + … Car - color - fuel - xpos - ypos 8/2/2018 Md.Samsuzzaman 173 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
174
Instance variables Numeric instance variables initialized to 0
Default initialization If the variable is within a method, Java does NOT initialize it If the variable is within a class, Java initializes it as follows: Numeric instance variables initialized to 0 Logical instance variables initialized to false Object instance variables initialized to null + … Car - color = null - fuel = 0 - xpos = 0 - ypos = 0 Each instance variable is defined without specifying an initial value. Therefore, whenever a new ColoredRectangle object is to be constructed, Java first initializes the new instance variables to default values. By default, numeric instance variables are initialized to 0, boolean instance variables are initialized to false, and reference-type instance variables are initialized to null. Thus, every time a new ColoredRectangle object is to undergo construction, new width, height, x, y, window, and color instance variables are created and default initialized for the new object. The numeric attributes width, height, x, and y are initialized to zero and the class-type attributes window and color are initialized to null. The instance variable definitions specify each of the variable to be private. This modifier indicates that direct access to the instance variables is limited to the class itself. Thus, class ColoredRectangle practices information hiding by encapsulating its attributes. Defining instance variables to be private is a standard practice. When attributes are private, other classes are forced to use the class’s interface methods to manipulate its attributes. Those interface methods normally are programmed to ensure that the requested manipulations are valid. Because the initial definition of class ColoredRectangle does not provide any methods to give access to the attributes, once a ColoredRectangle is constructed it is immutable. In Section , we introduce several ColoredRectangle methods for accessing and modifying the attributes of a ColoredRectangle object. 8/2/2018 Md.Samsuzzaman 174 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 174
175
Car behaviors or methods
What can a car do? And what can you do to a car? Move it Change it’s x and y positions Change it’s color Fill it up with fuel For our computer simulation, what else do we want the Car class to do? Create a new Car Change Car’s condition Each of these behaviors will be written as a method 8/2/2018 Md.Samsuzzaman 175 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
176
Creating a new car It sets the instance variables to initial values
To create a new Car, we call: Car car = new Car(); Notice this looks like a method You are calling a special method called a constructor A constructor is used to create (or construct) an object It sets the instance variables to initial values The constructor: Car() { fuel = 1000; color = Color.BLUE; } 8/2/2018 Md.Samsuzzaman 176 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
177
EXACT same name as class
Constructors Car() { fuel = 1000; color = Color.BLUE; } No return type! EXACT same name as class 8/2/2018 Md.Samsuzzaman 177 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
178
Our Car class so far class Car { private Color color = Color.BLUE;
private int xpos; private int ypos; private int fuel; Car() { fuel = 1000; color = Color.BLUE; } class Car { private Color color = Color.BLUE; private int xpos; private int ypos; private int fuel = 1000; Car() { } 8/2/2018 Md.Samsuzzaman 178 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
179
Our Car class so far class Car { private Color color = Color.BLUE;
private int xpos = 0; private int ypos = 0; private int fuel = 1000; Car() { } Called the default constructor The default constructor has no parameters If you don’t include one, Java will SOMETIMES put one there automatically + Car() + … Car - color = Color.BLUE - fuel = 1000 - xpos = 0 - ypos = 0 8/2/2018 Md.Samsuzzaman 179 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
180
Another constructor Another constructor:
Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } This constructor takes in four parameters The instance variables in the object are set to those parameters This is called a specific constructor An constructor you provide that takes in parameters is called a specific constructor 8/2/2018 Md.Samsuzzaman 180 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
181
Our Car class so far class Car { private Color color = Color.BLUE;
private int xpos = 0; private int ypos = 0; private int fuel = 1000; Car() { } Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; + Car() + Car (Color, int, int, int) + … Car - color = Color.BLUE - fuel = 1000 - xpos = 0 - ypos = 0 8/2/2018 Md.Samsuzzaman 181 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
182
Using our Car class Now we can use both our constructors:
Car c1 = new Car(); Car c2 = new Car (Color.BLACK, 1, 2, 500); c1 c2 + Car() + Car (Color, int, int, int) + … Car - color = Color.BLUE - fuel = 1000 - xpos = 0 - ypos = 0 + Car() + Car (Color, int, int, int) + … Car - color = Color.BLACK - fuel = 500 - xpos = 1 - ypos = 2 8/2/2018 Md.Samsuzzaman 182 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
183
So what does private mean?
Consider the following code class CarSimulation { public static void main (String[] args) { Car c = new Car(); System.out.println (c.fuel); } Recall that fuel is a private instance variable in the Car class Private means that code outside the class CANNOT access the variable For either reading or writing Java will not compile the above code If fuel were public, the above code would work Note that it’s a different class! 8/2/2018 Md.Samsuzzaman 183 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
184
So how do we get the fuel of a Car?
Via accessor methods in the Car class: public int getFuel() { return fuel; } public Color getColor() { return color; As these methods are within the Car class, they can read the private instance variables As the methods are public, anybody can call them public int getYPos() { return ypos; } public int getXPos() { return xpos; 8/2/2018 Md.Samsuzzaman 184 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
185
So how do we set the fuel of a Car?
Via mutator methods in the Car class: public void setFuel (int f) { fuel = f; } public void setColor (Color c) { color = c; As these methods are within the Car class, they can read the private instance variables As the methods are public, anybody can call them public void setXPos (int x) { xpos = x; } public void setYPos (int y) { ypos = y; 8/2/2018 Md.Samsuzzaman 185 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
186
Why use all this? Used with private variables
These methods are called a get/set pair Used with private variables Our Car so far: + Car() + Car (Color, int, int, int) + void setXPos (int x) + void setYPos (int y) + void setPos (int x, int y) + void setColor (Color c) + void setFuel (int f) + int getFuel() + int getXPos() + int getYPos() + Color getColor() + … Car - color = Color.BLUE - fuel = 1000 - xpos = 0 - ypos = 0 8/2/2018 Md.Samsuzzaman 186 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
187
Back to our specific constructor
class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; Car (Color c, int x, int y, int f) { color = c; xpos = x; ypos = y; fuel = f; } class Car { private Color color = Color.BLUE; private int xpos = 0; private int ypos = 0; private int fuel = 1000; Car (Color c, int x, int y, int f) { setColor (c); setXPos (x); setYPos (y); setFuel (f); } 8/2/2018 Md.Samsuzzaman 187 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
188
Back to our specific constructor
Using the mutator methods (i.e. the ‘set’ methods) is the preferred way to modify instance variables in a constructor 8/2/2018 Md.Samsuzzaman 188 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
189
So what’s left to add to our Car class?
What else we should add: A mutator that sets both the x and y positions at the same time A means to “use” the Car’s fuel Let’s do the first: public void setPos (int x, int y) { setXPos (x); setYPos (y); } Notice that it calls the mutator methods 8/2/2018 Md.Samsuzzaman 189 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
190
Using the Car’s fuel For each pixel it moves, it uses one unit of fuel
Whenever the Car moves, it should burn some of the fuel For each pixel it moves, it uses one unit of fuel We could make this more realistic, but this is simpler public void setXPos (int x) { xpos = x; } public void setYPos (int y) { ypos = y; public void setXPos (int x) { fuel -= Math.abs(getXPos()-x); xpos = x; } public void setYPos (int y) { fuel -= Math.abs(getYPos()-y); ypos = y; 8/2/2018 Md.Samsuzzaman 190 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
191
Using the Car’s fuel Notice that to access the instance variables, the accessor methods are used Math.abs() gets the absolute value of the passed parameter public void setPos (int x, int y) { setXPos(x); setYPos(y); } 8/2/2018 Md.Samsuzzaman 191 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
192
The main() method public static void bar () {
Consider a class with many methods: public class WhereToStart { public static void foo (int x) { // ... } public static void bar () { public static void main (String[] args) { Where does Java start executing the program? Always at the beginning of the main() method! 8/2/2018 Md.Samsuzzaman 192 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
193
Running a class without a main() method
Consider the Car class It had no main() method! Create another class named “CarSimulation” where main function and Car class is declared. 8/2/2018 Md.Samsuzzaman 193 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
194
String Handling in Java
Lecture 16 String Handling in Java Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
195
String in Java String is a sequence of characters.
Java implements strings as objects of type String. It belongs to java.lang. Once a String object is created, it is not possible to change the characters that comprise the string. When a modifiable string is needed, java provides two options: 1.java.lang.StringBuffer 2.java.lang.StringBuilder 8/2/2018 Md.Samsuzzaman 195 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
196
The String Constructor
String()- Example: String s = new String(); String (char chars[]) Example: char chars[] = {‘a’, ‘b’, ’c’}; String s=new String (chars); String( char chars[], int startIndex, int numChars); char chars[] = {‘a’, ‘b’, ’c’, ‘d’, ‘e’, ‘f’}; String s = new String (chars, 2, 3); 8/2/2018 Md.Samsuzzaman 196 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
197
The String Constructor
4. String (String str); Example: char c[] = {‘j’, ‘a’, ‘v’, ‘a’}; String s1 = new String (c); String s2 = new String (s1); System.out.println (s1); System.out.println(s2); 5. String ( byte asciiChars []); String ( byte asciiChars [], int startIndex, int numChars); 8/2/2018 Md.Samsuzzaman 197 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
198
The String Constructor
Example: byte ascii [] = {65, 66, 67, 68, 69, 70}; String s1 = new String (ascii); System.out.println ( s1); String s2 = new String ( ascii, 2, 3); Output: ABCDEF CDE 8/2/2018 Md.Samsuzzaman 198 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
199
char st [ ] = {‘a’, ‘b’, ‘c’}; String a = new String (st);
String Length: int length(); Example: char st [ ] = {‘a’, ‘b’, ‘c’}; String a = new String (st); System.out.println ( a.length()); Creating String from String Literals: String s1 = “abcd”; String object is created for every string literals. System.out.println (“abc” . length()); 8/2/2018 Md.Samsuzzaman 199 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
200
String Concatenation Java allows only + operator to be applied on string, which concatenates of two strings. Example: String age = “9”; String s = “He is “ + age + “ years old.”; System.out.println (s); The compiler will convert an operand to it’s string equivalent whenever the other operand of the + is an instance of String. int age = 9; 8/2/2018 Md.Samsuzzaman 200 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
201
Data Conversion using valueOf()
It converts data from its internal format into a human-readable format. Static overloaded method within String for built-in types and for type Object. static String valueOf (double num) static String valueOf( Object ob) During concatenation operation, it is automatically called. All of the simple types are converted into their String representation. For any object valueOf() automatically calls the object’s toString() method. 8/2/2018 Md.Samsuzzaman 201 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
202
toString() Method It is defined by Object.
Every class implements toString() because every class is subclass of Object. General form: String toString() It returns a String object that appropriately describe any object. Example: class tt { int a; tt() { a=100;} public String toString() return “a= “+a; } Output: a= 100 class test { public static void main (String args[]) tt b = new tt(); System.out.println(b); } 8/2/2018 Md.Samsuzzaman 202 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
203
Character Extraction charAt (): char ch;
ch = “abc”.charAt(1); ch<-’b’ getChars(int sourceStart, int sourceEnd, char target [], int targetStart) sourceStart- the beginning of the substring sourceEnd- one past the end of the desired substring target – destination array of characters targetStart – index at which the substring will be copied. 8/2/2018 Md.Samsuzzaman 203 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
204
Character Extraction Example: String s = “abcdefghijklmnop”;
int start =10, end = 14; char st [] = new char [end-start]; s.getChars (start, end, st, 0); System.out.println (st); st->klmn 8/2/2018 Md.Samsuzzaman 204 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
205
String Comparison equals () boolean equals( String str)
-str is the String object being compared with the invoking String object. -Case sensitive. 2. equalsIgnoreCase () boolean equalsIgnoreCase( String str) -Not case sensitive. 8/2/2018 Md.Samsuzzaman 205 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
206
String Comparison Example: String s1 = “Hello”; String s2 = “HELLO”;
System.out.println ( s1 + “ equals “ +s2 + s1.equals(s2)); System.out.println ( s1 + “ equals “ +s2 + s1.equalsIgnoreCase(s2)); Output: Hello equals HELLO false Hello equals HELLO true 8/2/2018 Md.Samsuzzaman 206 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
207
String Comparison 3. Boolean regionMatches ( int startIndex, String str2, int str2Index, int numchars) - compare a specifice region inside a string with another specific region in another string. - startIndex- specifies the beginning index of the invoking object str2Index- specifies the beginning index of the object str2 numchars – specifies the number of characters to be compared. 4. StartsWith () and endsWith () Example: “Football”. endsWith ( “ball”); returns true “Football”. startsWith (“wood”); returns false 8/2/2018 Md.Samsuzzaman 207 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
208
String Comparison 5. int compareTo (String str)
- less than 0: if invoking string is less than str greater than 0: if invoking string is greater than str 0: if equal - case sensitive. 8/2/2018 Md.Samsuzzaman 208 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
209
equals () versus == hello equals hello false
equals () method compares the characters within a String object. The == operator compares two object references to see whether they refer to the same object. Example: String s1 = “hello”; String s2 = new String(s1); System.out.println(s1 + “ equals “+s2 + “ ”+ s1.equals(s2)); System.out.println(s1 + “ equals “+s2 + “ ”+ (s1==s2)); Output: hello equals hello true hello equals hello false 8/2/2018 Md.Samsuzzaman 209 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
210
Chapter 15 of The Complete Reference Java.
8/2/2018 Md.Samsuzzaman 210 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
211
String Handling in Java and Object Class
Lecture 17 String Handling in Java and Object Class Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
212
Searching Strings indexOf() – searches for the first occurrence of a character or substring lastIndexOf() – searches for the last occurrence of a character or substring indexOf (int ch, int startIndex); lastIndexOf (int ch, intstartIndex); All the methods return the index at which the character or the substring is found or return -1 on failure. 8/2/2018 Md.Samsuzzaman 212 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
213
Searching String Example: String s = “ This is a Java Program”;
s.indexOf( ‘J’); s.indexOf( “Program”); s.indexOf( ‘a’, 9); 8/2/2018 Md.Samsuzzaman 213 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
214
Modifying a String substring(): -1. String substring( int startIndex);
2. String substring( int startIndex, int endIndex); concat(): String concat(String str); replace(): String replace( char original, char replacement); trim(): String trim() -Example: String s=“ Hello “.trim(); 8/2/2018 Md.Samsuzzaman 214 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
215
StringBuffer StringBuffer Constructors
It represents growable and writeable character sequences. StringBuffer Constructors StringBuffer () – Reserves space for 16 characters. StringBuffer ( int size) StringBuffer (String str)– String argument is used to set the initial content and also reserves space 16 more characters. 8/2/2018 Md.Samsuzzaman 215 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
216
Useful Methods length () and capacity(): Example:
StringBuffer st = new StringBuffer (“Hello”); System.out.println(“length: “+st.length()); //length: 5 System.out.println(“capacity: “+st.capacity()); //capacity: 21 charAt () and setCharAt(): char charAt( int position); void setCharAt( int postion, char ch); getChars() void getChars( int sourceStart, int sourceEnd, char target [], int targetStart) 8/2/2018 Md.Samsuzzaman 216 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
217
Useful Methods insert(): -It is an overloaded functions.
-It calls String.valueOf() to obtain the string representation of the value it is called with. - StringBuffer insert( int index, String str) reverse (): StringBuffer reverse() Example: StringBuffer st = new StringBuffer(“ I Java!”); System.out.println(st.insert(2, “like ”)); //I like Java! System.out.println(st.reverse()); //!avaJ ekil I 8/2/2018 Md.Samsuzzaman 217 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
218
Useful Methods delete() and deleteCharAt()
StringBuffer delete( int startIndex, int endIndex); StringBuffer deleteCharAt( int pos); Replace () StringBuffer replace(int startIndex, int endIndex, String str) Example: StringBuffer st = new StringBuffer(“This is a test.”); System.out.println(st.replace(5,7, “was”); //This was a test. System.out.println(st.delete(4, 8)); //This a test System.out.println(st.deleteCharAt(0)); // his a test 8/2/2018 Md.Samsuzzaman 218 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
219
Useful Methods append (): -It is an overloaded functions.
-It calls String.valueOf() to obtain the string representation of the value it is called with. - StringBuffer append(String str) 8/2/2018 Md.Samsuzzaman 219 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
220
Object A special class defined by java.
All other classes are subclasses of Object. A reference variable of type Object can refer to an object of any other class. Important Methods defined by Object: Object clone() – creates an object that is same as the object being cloned. Boolean equals (Object ob) – Determines whether one object is equal to another. String toString () – Returns a string that describes the object. - Automatically called when an object is output using println(). 8/2/2018 Md.Samsuzzaman 220 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
221
Example Output: temp@10b62c9 class temp { int a; public temp() a=10; }
class tst public static void main(String args[]) temp ob = new temp(); System.out.println(ob.toString()); System.out.println(ob); 8/2/2018 Md.Samsuzzaman 221 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
222
Example Output: This Object contains an integer number. 8/2/2018
class temp { int a; public temp() a=10; } String toString() String t =“This Object contains an integer number”; return t; class tst public static void main(String args[]) temp ob = new temp(); System.out.println(ob.toString()); System.out.println(ob); Output: This Object contains an integer number. 8/2/2018 Md.Samsuzzaman 222 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
223
Lecture 18 Package Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
224
Packages Provides a mechanism for grouping a variety of classes and / or interfaces together. Grouping is based on functionality. Benefits: The classes contained in the packages of other programs can be reused. In packages, classes can be unique compared with classes in other packages. Packages provides a way to hide classes. 8/2/2018 SOBUZ 224 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
225
Packages Two types of packages: 1. Java API packages 2. User defined packages Java API Packages: A large number of classes grouped into different packages based on functionality. Examples: 1. java.lang 2. java.util 3. java.io 4. java.awt 5.java.net 6.java. applet etc. 8/2/2018 SOBUZ 225 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
226
Package Java Package containing awt package awt Color
Package containing classes Graphics Image 8/2/2018 SOBUZ 226 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
227
Accessing Classes in a Package
Fully Qualified class name: Example:java.awt.Color import packagename.classname; Example: import java.awt.Color; or import packagename.*; Example: import java.awt.*; Import statement must appear at the top of the file, before any class declaration. 8/2/2018 SOBUZ 227 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
228
Creating Your Own Package
Declare the package at the beginning of a file using the form package packagename; 2. Define the class that is to be put in the package and declare it public. Create a subdirectory under the directory where the main source files are stored. Store the listing as classname.java in the subdirectory created. Compile the file. This creates .class file in the subdirectory. Example: package firstPackage; Public class FirstClass { //Body of the class } 8/2/2018 SOBUZ 228 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
229
Example1-Package package p1; public class ClassA {
public void displayA( ) System.out.println(“Class A”); } import p1.*; Class testclass { public static void main(String str[]) ClassA obA=new ClassA(); obA.displayA(); } Source file – ClassA.java Subdirectory-p1 ClassA.Java and ClassA.class->p1 Source file-testclass.java testclass.java and testclass.class->in a directory of which p1 is subdirectory. 8/2/2018 SOBUZ 229 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
230
Creating Packages Consider the following declaration:
package firstPackage.secondPackage; This package is stored in subdirectory named firstPackage.secondPackage. A java package can contain more than one class definitions that can be declared as public. Only one of the classes may be declared public and that class name with .java extension is the source file name. 8/2/2018 SOBUZ 230 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
231
Example2-Package package p2; public class ClassB {
protected int m =10; public void displayB() System.out.println(“Class B”); System.out.println(“m= “+m); } import p1.*; import p2.*; class PackageTest2 { public static void main(String str[]) ClassA obA=new ClassA(); Classb obB=new ClassB(); obA.displayA(); obB.displayB(); } 8/2/2018 SOBUZ 231 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
232
Example 3- Package import p2.ClassB; class ClassC extends ClassB {
int n=20; void displayC() System.out.println(“Class C”); System.out.println(“m= “+m); System.out.println(“n= “+n); } class PackageTest3 { public static void main(String args[]) ClassC obC = new ClassC(); obC.displayB(); obC.displayC(); } 8/2/2018 SOBUZ 232 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
233
Package Correct Code: import p1.*; import p2.*; p1.Student student1;
package p1; public class Teacher {………….} public class Student {……………..} package p2; public class Courses {………..} {………………..} import p1.*; import p2.*; Student student1; //Error Correct Code: import p1.*; import p2.*; p1.Student student1; p2.Student student2; 8/2/2018 SOBUZ 233 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
234
Default Package If a source file does not begin with the package statement, the classes contained in the source file reside in the default package The java compiler automatically looks in the default package to find classes. 8/2/2018 SOBUZ 234 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
235
Finding Packages Two ways:
1.By default, java runtime system uses current directory as starting point and search all the subdirectories for the package. 2.Specify a directory path using CLASSPATH environmental variable. 8/2/2018 SOBUZ 235 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
236
CLASSPATH Environment Variable
The compiler and runtime interpreter know how to find standard packages such as java.lang and java.util The CLASSPATH environment variable is used to direct the compiler and interpreter to where programmer defined imported packages can be found The CLASSPATH environment variable is an ordered list of directories and files 8/2/2018 SOBUZ 236 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
237
CLASSPATH Environment Variable
To set the CLASSPATH variable we use the following command: set CLASSPATH=c:\ Java compiler and interpreter searches the user defined packages from the above directory. To clear the previous setting we use: set CLASSPATH= 8/2/2018 SOBUZ 237 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
238
Example1-Package[Using CLASSPATH]
package p1; public class ClassA { public void displayA( ) System.out.println(“Class A”); } import p1.ClassA; Class PackageTest1 { public static void main(String str[]) ClassA obA=new ClassA(); obA.displayA(); }} Source file – c:\p1\ClassA.java Compile-javac c:\p1\ClassA.java Class file in –c:\p1\ClassA.class Source file-c:\java\jdk1.6.0_06\bin\PackageTest1.java Compile-javac PackageTest1.java Copy –PackageTest1.class -> c:\ Execute-java PackageTest1 8/2/2018 SOBUZ 238 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
239
Example2-Package[Using CLASSPATH]
package p2; public class ClassB { protected int m =10; public void displayB() System.out.println(“Class B”); System.out.println(“m= “+m); } import p1.*; import p2.*; class PackageTest2 { public static void main(String str[]) ClassA obA=new ClassA(); Classb obB=new ClassB(); obA.displayA(); obB.displayB();} } Source file-c:\java\jdk1.6.0_06\bin\PackageTest2.java Compile-javac PackageTest2.java Copy –PackageTest2.class -> c:\ Execute-java PackageTest2 Source file – c:\p2\ClassB.java Compile-c:\p2\ClassB.java Class file in –c:\p2\ClassB.class 8/2/2018 SOBUZ 239 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
240
Example 3- Package[Using CLASSPATH]
import p2.ClassB; class ClassC extends ClassB { int n=20; void displayC() System.out.println(“Class C”); System.out.println(“m= “+m); System.out.println(“n= “+n); } class PackageTest3 { public static void main(String args[]) ClassC obC = new ClassC(); obC.displayB(); obC.displayC(); } Source file-c:\java\jdk1.6.0_06\bin\PackageTest3.java Compile-javac PackageTest3.java Copy –PackageTest3.class -> c:\ Execute-java PackageTest3 Source file – c:\ClassC.java Compile-c:\ClassC.java Class file in –c:\ClassC.class 8/2/2018 SOBUZ 240 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
241
Adding a Class to a Package
Every java source file can contain only class declared as public. The name of the source file should be same as the name of the public class with .java extension. package p1; public ClassA{ ……………} Source file : ClassA.java Subdirectory: p1 package p1; public ClassB{…………} Source file: ClassB.java Subdirectory:p1 8/2/2018 SOBUZ 241 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
242
Adding a Class to a Package
Decide the name of the package. Create the subdirectory with this name under the directory where the main source file is located. Create classes to be placed in the package in separate source files and declare the package statement package packagename; 4. Compile each source file. When completed the package will contain .class files of the source files. 8/2/2018 SOBUZ 242 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
243
public/package/private scope
Scope is concerned with the visibility of program elements such as classes and members Class members (methods or instance fields) can be defined with public, package (default), private or protected scope A class has two levels of visibility: -public scope means it is visible outside its containing package - default scope means it is visible only inside the package. (package scope/ friendly scope) 8/2/2018 SOBUZ 243 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 243
244
public/package/private scope
A class member with public scope means it is visible anywhere its class is visible A class member with private scope means it is visible only within its encapsulating class A class/class member with package scope means it is visible only inside its containing package A class member with protected scope means it is visible every where except the non-subclasses in other package. 8/2/2018 SOBUZ 244 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 244
245
Example 1 package my_package; class A // package scope {
// A’s public & private members } public class B // public scope // B’s public and private members 8/2/2018 SOBUZ 245 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 245
246
Example-2 package my_package; class D {
// D’s public & private members // Class D ‘knows’ about classes A and B private B b; // OK – class B has public scope private A a; // OK – class A has package scope } 8/2/2018 SOBUZ 246 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 246
247
Example-3 package another_package; import my_package.*; class C {
// C’s public & private members // class C ‘knows’ about class B private B b; // OK – class B has public scope } 8/2/2018 SOBUZ 247 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 247
248
Example 4 package my_package; class A {
int get() { return data; } // package scope public A(int d) { data=d;} // public scope private int data; // private scope } class B void f() A a=new A(d); // OK A has package scope int d=a.get(); // OK – get() has package scope int d1=a.data; // Error! – data is private 8/2/2018 SOBUZ 248 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU 248
249
Levels of Access Control
public protected friendly (default) private same class Yes Subclass in the same package No Other class in the same package Subclass in other packages Non-subclass in other package 8/2/2018 SOBUZ 249 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
250
Interface Similar to a class.
Consists of only abstract methods and final variables. Any number of classes can implement an interface. One class can implement any number of interfaces. To implement an interface a class must define each of the method declared in the interface. Each class can also add new features. Interface disconnect the definition of a method or set of methods from the inheritance hierarchy. 8/2/2018 Md.samsuzzaman 250 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
251
Defining an Interface Example: General form of an interface:
interface callback{ void callback (int param); } General form of an interface: access interface name { ret-type method1(parameter list); ret-type method2(parameter list); type final var1 = value; type final static val2 = value; } 8/2/2018 Md.samsuzzaman 251 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
252
Defining an Interface Access is either public or default.
Variables declared inside an interface are implicitly final and static. Variables must be initialized with a constant value. All methods and variables are implicitly public if the interface, itself, is declared as public. 8/2/2018 Md.samsuzzaman 252 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
253
Implementing Interfaces
The General Form: access class classname [extends superclass][implements interface[,interface]] { } The methods that implement an interface must be declared public. The type signature of the implementing method must match exactly the type signature specified in the interface definition. 8/2/2018 Md.samsuzzaman 253 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
254
Accessing Implementations through Interface Reference
Interface reference is required to access the implementation. Any instance of the class that implements the interface can be referred to by such a variable. When a method is called through one of the reference, the correct version will be called based on the actual instance of the interface being referred to. The method to be executed is looked up dynamically at run time. 8/2/2018 Md.samsuzzaman 254 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
255
Example-1 interface call { void callback(int param); }
class client implements call public void callback(int p) System.out.println("callback called with "+p); public class testIface public static void main(String args[]) call c = new client(); c.callback(423); 8/2/2018 Md.samsuzzaman 255 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
256
Example-2 public class testIface {
interface call { void callback(int param); } class client implements call public void callback(int p) System.out.println("callback is called with "+p); class anotherclient implements call System.out.println("p squred is "+(p*p)); public class testIface { public static void main(String args[]) call c = new client(); c.callback(42); c=new anotherclient(); c.callback(10); } 8/2/2018 Md.samsuzzaman 256 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
257
Partial Implementation
If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract. Example: abstract class temp implements call{ int a, b; void show() { //body of the method } Any class that inherits temp must implement callback() or declared abstract itself. 8/2/2018 Md.samsuzzaman 257 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
258
Extending Interfaces interface Item extends ItemConstant {
One interface can inherit another by using the keyword extends. The new sub interface will inherit all the member of the super interface. Any class that will implement the interface that inherits another interface, it must provide implementations of all methods defined within the interface inheritance chain. General form: interface name2 extends name1 { //body of name2 } Example: interface ItemConstant int code =1001; String name =“Pen”; interface Item extends ItemConstant { void display(); } An interface cannot extends a class. 8/2/2018 Md.samsuzzaman 258 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
259
Multiple Inheritance Using Interface
Java supports multiple inheritance through the use of interface. Care should be taken to avoid some conflicts. 8/2/2018 Md.samsuzzaman 259 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
260
Example-3 interface test1 { int val=10; void display(); }
class test3 implements test1, test2 { public void display() System.out.println(“In test3”); System.out.println(test1.val); System.out.println(test2.val); } 8/2/2018 Md.samsuzzaman 260 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
261
Example-4 interface test1 { int val=10; void display(); }
interface test3 extends test1, test2 int val=50; class test4 implements test3 { int val=57; public void display() System.out.println(test1.val); System.out.println(test2.val); System.out.println(test3.val); System.out.println(val); } public class Iface_test public static void main(String args[]) test4 ob = new test4(); ob.display(); 8/2/2018 Md.samsuzzaman 261 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
262
Example-5 interface test1 { class test3 extends test2 int val=33; {
void display(); } class test2 implements test1 static int val=34; void display() System.out.println(test1.val); System.out.println(val); class test3 extends test2 { int val=35; void show() System.out.println(test1.val); System.out.println(test2.val); System.out.println(val); } class test4 public static void main(String args[]) test3 ob = new test3(); ob.show(); 8/2/2018 Md.samsuzzaman 262 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
263
Exception Handling Lecture 21
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
264
Exception Handling-Fundamentals
An exception is an abnormal condition that arises in a code sequence at run time A Java exception is an object that describes an exceptional condition that has occurred in a piece of code When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error An exception can be caught to handle it or pass it on Exceptions can be generated by the Java run-time system, or they can be manually generated by your code 8/2/2018 Md.Samsuzzaman 264 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
265
Exception Handling Performing action in response to exception Examples
Exit program (abort) Deal with exception and continue Print error message Request new data Retry action 8/2/2018 Md.Samsuzzaman 265 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
266
Representing Exceptions
8/2/2018 Md.Samsuzzaman 266 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
267
Representing Exceptions
Java Exception class hierarchy ClassNotFoundException CloneNotSupportedException Exception IOException ArithmeticException AWTException NullPointerException RuntimeException Object Throwable IndexOutOfBoundsException … NoSuchElementException LinkageError … VirtualMachoneError Error AWTError Checked … Unchecked 8/2/2018 Md.Samsuzzaman 267 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
268
Exception Handling in Java
Java exception handling is managed by via five keywords: try, catch, throw, throws, and finally Program statements to monitor are contained within a try block If an exception occurs within the try block, it is thrown Code within catch block catch the exception and handle it 8/2/2018 Md.Samsuzzaman 268 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
269
Example Output: Division by zero. After catch statement. 8/2/2018
Md.Samsuzzaman 269 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
270
try and catch statement
The scope of a catch clause is restricted to those statements specified by the immediately preceding try statement. A catch statement cannot catch an exception thrown by another try statement. The statements that are protected by the try must be surrounded by curly braces. 8/2/2018 Md.Samsuzzaman 270 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
271
Multiple Catch Clauses
If more than one can occur, then we use multiple catch clauses When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed After one catch statement executes, the others are bypassed 8/2/2018 Md.Samsuzzaman 271 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
272
Example 8/2/2018 Md.Samsuzzaman 272
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
273
Caution Exception subclass must come before any of of their superclasses A catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. So, the subclass would never be reached if it come after its superclass For example, ArithmeticException is a subclass of Exception Moreover, unreachable code in Java generates error 8/2/2018 Md.Samsuzzaman 273 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
274
Example 8/2/2018 Md.Samsuzzaman 274
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
275
Nested try Statements A try statement can be inside the block of another try Each time a try statement is entered, the context of that exception is pushed on the stack If an inner try statement does not have a catch, then the next try statement’s catch handlers are inspected for a match If a method call within a try block has try block within it, then then it is still nested try 8/2/2018 Md.Samsuzzaman 275 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
276
Example 8/2/2018 Md.Samsuzzaman 276
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
277
throw It is possible for your program to to throw an exception explicitly throw ThrowableInstance Here, ThrowableInstance must be an object of type Throwable or a subclass Throwable There are two ways to obtain a Throwable objects: Using a parameter into a catch clause Creating one with the new operator 8/2/2018 Md.Samsuzzaman 277 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
278
Example -throw Statements
Output: Caught inside demoproc. Recaught: java.lang.NullPointerException: demo 8/2/2018 Md.Samsuzzaman 278 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
279
throws { // body of method }
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception type method-name parameter-list) throws exception-list { // body of method } It is not applicable for Error or RuntimeException, or any of their subclasses 8/2/2018 Md.Samsuzzaman 279 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
280
Example: incorrect program
8/2/2018 Md.Samsuzzaman 280 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
281
Example: corrected version
Output: Inside throwOne. Caught java.lang.IllegalAccessException: demo 8/2/2018 Md.Samsuzzaman 281 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
282
Finally Statement finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. finally block will be executed whether or not an exception is thrown. Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. Each try clause requires at least one catch or finally clause. 8/2/2018 Md.Samsuzzaman 282 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
283
Example 8/2/2018 Md.Samsuzzaman 283
Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
284
Output inside procA procA's finally Exception caught inside procB
procB's finally inside procC procC's finally 8/2/2018 Md.Samsuzzaman 284 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
285
Uncaught Exceptions class exc0{ public static void main(String args[])
int d=0; int a=42/d; } A new exception object is constructed and then thrown. This exception is caught by the default handler provided by the java runtime system. The default handler displays a string describing the exception, prints the stack trace from the point at which the exception occurred and terminates the program. Output: java.lang.ArithmeticException: / by zero at exc0.main(exc0.java:4) 8/2/2018 Md.Samsuzzaman 285 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
286
Displaying a Description of an Exception
Throwable overrides the toString() method (defined by Object) so that it returns a string containing a description of the exception. Example: catch(ArithmeticException e) { System.out.println(“Exception: “+e); } Output: Exception: java.lang.ArithmeticException: / by zero 8/2/2018 Md.Samsuzzaman 286 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
287
User Defined Exception
Define a subclass of the Exception class. The new subclass inherits all the methods of Exception and can override them. class MyException extends Exception{ private int a; MyException(int i) { a = i;} public String toString (){ return “MyException[“ + a+”]”;} } 8/2/2018 Md.Samsuzzaman 287 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
288
Continuation of the Example
class test{ static void compute (int a) throws Myexception{ if(a>10) throw new MyException(a); System.out.println(“Normal Exit”); } public static void main(String args[]){ try{ compute(1); compute(20); }catch(MyException e){ System.out.println(“Caught “ +e); 8/2/2018 Md.Samsuzzaman 288 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
289
Example-2 class InvalidRadiusException extends Exception {
private double r; public InvalidRadiusException(double radius){ r = radius; } public void printError(){ System.out.println("Radius [" + r + "] is not valid"); 8/2/2018 Md.Samsuzzaman 289 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
290
Continuation of Example-2
class Circle { double x, y, r; public Circle (double centreX, double centreY, double radius ) throws InvalidRadiusException { if (r <= 0 ) { throw new InvalidRadiusException(radius); } else { x = centreX ; y = centreY; r = radius; 8/2/2018 Md.Samsuzzaman 290 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
291
Continuation of Example-2
class CircleTest { public static void main(String[] args){ try{ Circle c1 = new Circle(10, 10, -1); System.out.println("Circle created"); } catch(InvalidRadiusException e) { e.printError(); 8/2/2018 Md.Samsuzzaman 291 Md. Samsuzzaman ,Lecturer Faculty of CSE, PSTU
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.