Download presentation
Presentation is loading. Please wait.
1
CS206: OBJECT ORIENTED DESIGN AND PROGRAMMING
B.Tech. CSE Semester IV Viswajyothi College of Engineering and Technology
2
Course Objectives 1. To introduce basic concepts of object oriented design techniques. 2. To give a thorough understanding of Java language. 3. To provide basic exposure to the basics of multithreading, database connectivity etc. 4. To impart the techniques of creating GUI based applications.
3
Expected Outcomes 1. Apply object oriented principles in software design process. 2. Develop Java programs for real applications using java constructs and libraries. 3. Understand and apply various object oriented features like inheritance, data abstraction, encapsulation and polymorphism to solve various computing problems using Java language. 4. Implement Exception Handling in java. 5. Use graphical user interface and Event Handling in java. 6. Develop and deploy Applet in java.
4
Syllabus of Module 1 Object oriented concepts, Object oriented systems development life cycle. Unified Modeling Language, UML class diagram, Usecase diagram. Java Overview: Java virtual machine, data types, operators, control statements. Introduction to Java programming.
5
Procedure-Oriented Programming
Conventional programming using high level language such as COBOL, FORTRAN and C is commonly known as Procedure-oriented programming. Procedure-oriented programming basically consists of writing a list of instructions for the computer to follow and organizing these instructions into groups known as functions. The primary focus is on functions.
6
Structure of procedure-oriented programming
7
Drawback: More importance to functions and very little attention to data that are being used by the functions. In multi-function program many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. In large program it is very difficult to identify what data is used by which function.
8
Object-Oriented Programming
OOP treats data as a critical element in the program development and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it, and protects it from accidental modification from outside functions. OOP allows decomposition of a problem into a number of entities called objects.
9
Organization of data & function in OOP
10
Features of OOP Emphasis is on data rather than procedure or function.
Programs are divided into what are known as objects. Data is hidden and cannot be accessed by external functions. Objects may communicate with each other through functions. New data and functions can be easily added whenever necessary.
11
Object Oriented Concepts
Objects Class Data Abstraction Data Encapsulation Inheritance Polymorphism Dynamic binding Message Passing The three pillars of object-oriented development: Encapsulation, Inheritance, and Polymorphism.
12
Objects Objects are the basic run-time entities in an object oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program must handle. Program objects should be chosen such that they match closely with the real-world objects. Objects take up space in the memory. Each object is said to be an instance of its class.
13
Object is composed of attributes that defines the properties of object and functions that display the behaviour . Each instance of the class has its own value for each attribute but shares the same attribute names and operations with other instances of the class. Representation of objects
14
Classes Classes are user-defined data types and behave like the built-in types of a programming language. Objects are variable of type class. Once a class has been defined we can create any number of objects belonging to that class. A class is thus a collection of objects of similar type. Syntax used to create an object is no different than the syntax used to create an integer object in C. Suppose fruit is a class defined. fruit f1; //Here fruit is Class and f1 is an object of fruit Class.
15
Encapsulation The wrapping up of data and functions into a single unit is known as Encapsulation. The data is not accessible to the outside world and only those functions which are wrapped in the class can access it. This insulation of the data from direct access by the program is called data hiding or information hiding.
16
Inheritance: Inheritance is the process by which objects of one class acquire the properties of objects of another class. The principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived. Parent class is called base/superclass. Derived class is called subclass/derived class. In OOP the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it.
17
Eg:
18
Data Abstraction Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and functions to operate on these attributes. Since the classes use the concept of data abstraction, they are known as Abstract Data Types. Abstract classes have no instances but define common behaviors that can be inherited by more specific classes.
19
Polymorphism means the ability to take more than one form.
Different behaviours is exhibited in different instances. The behaviour depends upon the types of data used in the operation. Example: Operation of addition. For two numbers the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. The process of making an operator to exhibit different behaviours in different instances is known as operator overloading. Using a single function name to perform different types of tasks is known as function overloading.
20
Dynamic Binding The process of determining at run time which function to invoke is termed as dynamic binding. The code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.
21
Message Communication:
An object-oriented program consist of a set of objects that communicate with each other. Message passing involves specifying the name of the object, the name of the function (message) and the information to be sent. Eg: emp.salary(emp_name); Here emp is the object, salary is the message and emp_name is the information
22
Advantages of OOP Redundant code is eliminated and existing classes can be extended by the principle of inheritance. The principle data hiding helps the programmer to build secure programs. It is possible to have multiple objects to coexist without any interference. Object-oriented systems can be easily upgraded from small to large systems.
23
Software development process
Software development process consists of analysis, design, implementation, testing, and refinement. It transforms user’s needs into a software solution that satisfies their needs. One need to spend more time in gathering requirements, developing a requirement model and an analysis model, then turning them into the design model. The software development process can be divided into smaller, interacting sub processes.
24
Each subprocess must have the following
A description in terms of how it works Specification of the input required for the process Specification of the output to be produced Generally software development can be seen as a series of transformations, where the output of one transformation becomes the input of the subsequent transformation.
26
Transformation1(Analysis):
Translates the user’s needs into system requirements and responsibilities. The way the system is used can provide insight into the user’s requirements. For example: in library management system, identify who are the users and what are their requirements.
27
Transformation 2 (Design):
Begins with a problem statement and ends with a detailed design that can be transformed into a operational system. This transformation includes the bulk of the software development activity, including the definition of how to build the software, its development, and its testing. It also includes design descriptions, the programs and the testing material.
28
Transformation 3(Implementation):
Refines the detailed design into the system deployment that will satisfy the user’s needs. With inputs from system design, the system is first developed in small programs called units, which are integrated in the next phase. Finally the software product is embedded within its operational environment.
29
An example of the software development process is the waterfall approach.
It starts with deciding what has to be done. Once the requirements have been determined, decision is made as to how to accomplish them. This is followed by a step in which we implement or code it The result is then tested to see if it has satisfied the user’s requirements. Finally the product is made available for use by others.
30
Building high quality software
The ultimate goal of building high-quality software is user satisfaction The software process transforms the users' needs via the application domain to a software solution that satisfies those needs. High-quality products must meet users' needs and expectations. Furthermore, the products should attain this with minimal or no defects, the focus being on improving products (or services) prior to delivery rather than correcting them after delivery.
31
There are four quality measures for system evaluation: correspondence, correctness, verification, and validation. Correspondence measures how well the delivered system matches the needs of the operational environment, as described in the original requirements statement. Validation is the task of predicting correspondence. True correspondence cannot be determined until the system is in place. Correctness measures the consistency of the product requirements with respect to the design specification. Verification is the exercise of determining correctness.
33
Object-Oriented Systems Development: A use case driven approach
Object-oriented software development views problems as a system of cooperative objects. It uses an incremental development. The object oriented software development life cycle(SDLC) consists of three macro processes: Object-oriented analysis Object-oriented design Object-oriented implementation
35
The use case model can be employed throughout most activities of software development.
Furthermore, by following the lifecycle model of Jacobson , Ericsson, one can produce designs that are traceable across requirements, analysis, design, implementation, and testing.
37
Object oriented systems development includes these activities:
Object-oriented analysis- Use case driven Object oriented design Prototyping Component-based development Incremental testing
38
Object oriented Analysis- Use case Driven
The object oriented analysis phase of system development is concerned with determining the system requirements and identifying classes and their relationship to other classes in the problem domain. To understand the system requirements, we need to identify the users or the actors. Who are the actors and how do they use the system? Ivar Jacobson came up with the concept of use case to describe the user- computer system interaction. The object-oriented community has adopted use cases to a remarkable degree.
39
This intersection among object’s roles to achieve a given goal is called collaboration.
A use case is a typical interaction between a user and system that captures user’s goals and needs. The use case model represents the user’s view of the system or user’s needs. This process of developing use cases, like other object-oriented activities, is iterative—once the use-case model is better understood and developed classes are to be identified and their relationships have to be created.
40
Object-Oriented Design
The goal of object-oriented design (OOD) is to design the classes identified during the analysis phase and the user interface. During this phase, additional objects and classes that supports implementation of the requirements are defined. Object-oriented development is highly incremental; build the object model based on objects and their relationships, then iterate and refine the model: Design and refine classes. Design and refine attributes. Design and refine methods. Design and refine structures. Design and refine associations.
41
Following are the guidelines to use in the object-oriented design:
Reuse, rather than build, a new class. Know the existing classes. Design a large number of simple classes, rather than a small number of complex classes. Design methods. Critique what have been proposed. If possible, go back and refine the classes.
42
There are four categories for prototyping
Essentially, prototype is a version of a software product developed in the early stages of the product’s life cycle for specific, experimental purposes. A prototype enables you understand how easy or difficult it will be to implement some of the features of the system. It also can give users a chance to comment on the usability and usefulness of the user interface design. There are four categories for prototyping Horizontal Vertical Analysis Domain
43
In practice, prototypes are a hybrid between horizontal and vertical.
A horizontal prototype is a simulation of the interface i.e. it has the entire user interface that will be in the full-featured system but contains no functionality. Advantage very quick to implement provides a good overall feel of the system allows users to evaluate the interface on the basis of their normal, expected perception of the system. A vertical prototype is a subset of the system features with complete functionality. few implemented functions can be tested in great depth. In practice, prototypes are a hybrid between horizontal and vertical.
44
An analysis prototype is an aid for exploring the problem domain.
This class of prototype is used to inform the user and demonstrate the proof of a concept. The final product will use the concepts exposed by the prototype, not its code. A domain prototype is an aid for the incremental development of the ultimate software solution. It often is used as a tool for the staged delivery of subsystems to the users or other members of the development team. It demonstrates the feasibility of the implementation and eventually will evolve into a deliverable product.
45
Two basic ideas underlie component based development.
Component-based development (CBD) is an industrialized approach to the software development process. A CBD developer can assemble components to construct a complete software system. Two basic ideas underlie component based development. First, the application development can be improved significantly if applications can be assembled quickly from prefabricated software components. Second, an increasingly large collection of interpretable software components could be made available to developers in both general and specialist catalogs.
46
Incremental Testing The developers hand over applications to a quality assurance (QA) group for testing only after development was completed. Since the QA group wasn't included in the initial plan, it had no clear picture of the system characteristics until it came time to test. This caused unnecessary delay in the deployment of applications and would result in wasting a lot of money. Incremental testing is a way of integration testing in which first you test each module of the software individually then continue testing by adding another module to it and so on.
47
Unified Modeling Language(UML)
Modeling is building a model for a software system prior to its construction. It is used to describe a system at a high level of abstraction that includes user requirements and specifications. UML is a industry-standard graphical language for specifying, visualizing, constructing, and documenting the artifacts of software systems The UML uses mostly graphical notations to express the OO analysis and design of software projects. Simplifies the complex process of software design.
48
Why UML for Modeling? Use graphical notation to communicate more clearly than natural language (imprecise) and code(too detailed). Help acquire an overall view of a system. UML is not dependent on any one language or technology. Encourage the use of object oriented concepts. Integrate best practices and methodologies and support higher –level development concepts
49
Types of UML Diagrams Use Case Diagram Class Diagram Sequence Diagram Collaboration Diagram State Diagram
50
Use Case Diagram Depicts the functionality of the system.
Used for describing a set of user scenarios and is mainly used for capturing user requirements. Use cases represent specific flows of events in the system. A use-case diagram is a graph of actors, a set of use cases enclosed by a system boundary, communication/associations between the actors and the use cases, and generalization among the use cases.
51
Use Case Diagram (core components)
Actors: A role that a user plays with respect to the system. i.e. they are the entities that interact with the system. An actor may be people, computer hardware, other systems, etc. Use case: A set of scenarios that describes an interaction between a user and a system. It is shown as an ellipse. System boundary: rectangle diagram representing the boundary between the actors and the system. The use cases of the system are placed inside the system shape, while the actor who interact with the system are put outside the system.
52
Relationships shown in an use-case diagram
Association/communication: communication between an actor and a use case; Represented by a solid line. Generalization: Generalization of an actor means that one actor can inherit the role of an other actor. The descendant inherits all the use cases of the ancestor. The descendant have one or more use cases that are specific to that role.
53
Extend: a dotted line labeled <<extend>> with an arrow toward the base case. The extending use case may add behavior to the base use case. The base class declares “extension points”. <<extend>> The extending use case is dependent on the extended (base) use case. In the below diagram the “Calculate Bonus” use case doesn’t make much sense without the “Deposit Funds” use case. The extending use case is usually optional and can be triggered conditionally. In the diagram the extending use case is triggered only for deposits over 10,000 or when the age is over 55. The extended (base) use case must be meaningful on its own. This means it should be independent and must not rely on the behavior of the extending use case.
55
Include Relationship Between Two Use Cases
Include relationship show that the behaviour of the included use case is part of the including (base) use case. The main reason for this is to reuse the common actions across multiple use cases. In some situations this is done to simplify complex behaviors. Few things to consider when using the <<include>> relationship. The base use case is incomplete without the included use case. The included use case is mandatory and not optional.
57
Eg: Use case Diagram for a hospital management system
58
Pay Bill is a parent use case and Bill Insurance is the child use case
Pay Bill is a parent use case and Bill Insurance is the child use case. (generalization) Both Make Appointment and Request Medication include Check Patient Record as a subtask.(include) The extension point is written inside the base case Pay bill; the extending class Defer payment adds the behavior of this extension point. (extend)
59
Class diagram A class diagram is a collection of static modeling elements, such as classes and their relationships, connected as a graph. Class diagram do not show temporal information. Also known as object modeling. The main task of class diagram/object modeling is to Graphically show what each object will do in the problem domain. Describe its structure such as class hierarchy. Describe the relationship between objects.
60
Attribute and operations compartments may be suppressed.
Class representation Each class is represented by a rectangle subdivided into three compartments separated by horizontal lines. Class Name Attributes Operations Attribute and operations compartments may be suppressed. Modifiers are used to indicate visibility of attributes and operations. ‘+’ is used to denote Public visibility (everyone) ‘#’ is used to denote Protected visibility (friends and derived) ‘-’ is used to denote Private visibility (no one)
61
Eg: Class structure Account_Name - Customer_Name - Balance
+addFunds( ) +withDraw( ) +transfer( ) Name Attributes Operations
62
OO Relationships There are two kinds of Relationships Generalization (parent-child relationship) Association Associations can be further classified as Aggregation Composition
63
Generalization Generalization expresses a parent/child relationship among related classes. It is displayed as a directed line with a closed hollow arrowhead at the superclass end
64
Association A binary association is drawn as a solid path connecting two classes or both ends may be connected to the same class. It represents relationship between instances of classes. Eg: Student enrolls in a course Courses have students Courses have exams Association Role : The end of an association, where it connects to a class, is called the association role. The role is part of association and not part of class. Each association has two or more roles to which it is connected.
65
University Person teacher employer student Association supports navigation which is represented by directed arrows In the above figure association is navigable in only one direction, from Bank Account to Person and not the reverse. Bank Account Person
66
It specifies the range of allowable associated classes.
Qualifier: It is association attribute. Eg: A person may be associated to a bank object. An attribute of this association is the account#. Here account# is the qualifier of this association. It is represented as a small rectangle attached at the end of association path. It is part of association and not part of class. Multiplicity: It specifies the range of allowable associated classes. It is represented as a text string comprising a period-separated sequence of integer intervals, where an interval represents a range of integers in the format lower bound...upper bound
67
OR Association: Indicates a situation where one of several potential associations may be instantiated at one time for any single object. Shown as a dashed line connecting two or more associations.
68
Association class: It is an association that has class properties.
It is shown as a class symbol attached by a dashed line to an association path.
69
Aggregation An Aggregation notation between two classes is suitable whenever an instance of class A holds a collection of instances of class B. Sub parts can exist independently without the base component. Eg: Apples and Milk class can exist even in the absence of Bag class.
70
Composition Composition should be used to express a relationship where the behavior of Part instances is undefined without being related to an instance of the Whole. And, conversely, the behavior of the Whole is ill-defined or incomplete if one or more of the Part instances are undefined.
73
Eg: Class Diagram for order processing
Name class Order Multiplicity: mandatory Attributes -dateReceived -isPrepaid * Customer 1 -number :String -name -price : Money -address +dispatch() Association Operations +creditRating() : String() +close() 1 Generalization Corporate Customer Personal Customer -contactName -creditCard# -creditRating Multiplicity: Many value -creditLimit +remind() +billForMonth(Integer) Multiplicity: optional 0..1 * Employee * OrderLine -quantity: Integer * 1 Product -price: Money -isSatisfied: Boolean
74
Eg: Class diagram for library management system
75
Eg: Class diagram for ATM System
76
Syllabus Introduction to Java Genesis of Java Features of Java
Data Types Variables Arrays Operators Control Statements Selection Statements Iteration Statements Jump Statements
77
Java’s History Design objectives for the language
Originally developed by James Gosling at Sun Microsystems (which is now a part of Oracle Corporation) Originally called Oak Released in 1995 Aimed at producing an operating environment for networked devices and embedded systems. Design objectives for the language Simple, secure, object-oriented, architecture-neutral and portable, distributed and dynamic.
78
Java Applications and Applets
Java can be used to create two types of programs An application is a program that runs on your computer, under the operating system of that computer. An applet is an application designed to be transmitted over the Internet and executed by a Java-compatible Web browser. An applet is a program that can react to user input and dynamically change
79
Java Programming Language Platforms
A Java platform is a particular environment in which Java programming language applications run. All Java platforms consist of a Java Compiler , Java Virtual Machine (JVM) and an application programming interface (API). An API is a collection of software components that we can use to create other software components or applications. The API is a library of available java classes, packages and interfaces.
80
Java Programming Language Platforms
Java Platform, Standard Edition (J2SE) or Java SE Java SE's API provides the core functionality of the Java programming language. J2SE can be used to develop standalone applications or applets. Java Platform, Enterprise Edition (J2EE) or Java EE The Java EE platform provides an API and runtime environment for developing and running large-scale applications. Java platform Micro Edition (J2ME) or Java ME J2ME can be used to develop applications for mobile devices. JavaFX JavaFX is a platform for creating rich internet applications
81
The Compilation Process for Non-Java Programs
source code (programming language instructions) Programmers write this. Compilers compile source code into object code. object code (binary instructions) Computers run this.
82
The Compilation Process for Java Programs
Java source code Java compilers compile source code into bytecode. bytecode When a Java program is run, the JVM translates bytecode to object code. object code Computers run this.
83
Java Virtual Machine (JVM)
Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). It is a platform-independent execution environment that converts Java bytecode into machine language and executes it. As a Java program’s bytecode runs, the bytecode is translated into object code by the computer's bytecode interpreter program. Called Java Virtual Machine.
84
Comparison of JRE and JDK
The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications. JDK : The JDK also called Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.
85
Characteristics and Features of Java
Java inherits the C/C++ syntax and many of the object-oriented features of C++ . So JAVA is easier for programmers to learn it after C++. Removed many confusing and rarely-used features Eg: explicit pointers, operator overloading No need to remove unreferenced objects because there is Automatic Garbage Collection in java Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic
86
Characteristics and Features of Java
Every time a user compiles the Java program, the Java compiler creates a class file with Bytecode, which is tested by the JVM at the time of program execution for viruses and other malicious files. No explicit pointer so memory blocks cannot be accessed. Exception enables Java to capture a series of errors that helps developers to get rid of risk of crashing the system. Java’s access-control functionality on variables and methods within the objects provide secure program by preventing access to the critical objects from the untrusted code. Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic
87
Characteristics and Features of Java
Basic concepts of OOPs are: Object Class Inheritance Polymorphism Abstraction Encapsulation Java supports Object Oriented concepts. All program code and data reside within objects and classes. The object model in Java is simple and easy to extend. Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic
88
Characteristics and Features of Java
Robustness means strong and reliable. Java is reliable because of the following reasons Uses strong memory management i.e. lack of pointers hence avoids security problem There is automatic garbage collection There is exception handling mechanism There is type checking mechanism. Java is a strictly typed language. It checks the code at compile time as well as at run time Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic
89
Characteristics and Features of Java
Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic Java compiler translates source code into bytecode instructions. The bytecode is machine-independent and can run on any machine that has a Java interpreter(JVM). Java interpreter(JVM) generates machine code that can be directly executed by the machine.
90
Characteristics and Features of Java
Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic Java code is compiled by the compiler and converted into bytecode. This bytecode is platform independent because it can be run on multiple platforms with a Java Virtual Machine (JVM). i.e. Write Once and Run Anywhere(WORA).
91
Characteristics and Features of Java
Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic Because Java is architecture neutral, Java programs are portable. They can be run on any platform without being recompiled.
92
Characteristics and Features of Java
Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic A thread is like a separate program, executing concurrently. Allows you to write programs that do many things simultaneously.
93
Characteristics and Features of Java
Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic The execution speed of Java programs improved significantly due to the introduction of Just-In Time Compilation (JIT) They can be run on any platform without being recompiled.
94
Characteristics and Features of Java
Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic Distributed computing involves several computers working together on a network. We can create distributed applications in java. RMI and EJB are used for creating distributed applications. Java handles TCP/IP protocols. Networking capability is inherently integrated into Java, writing network programs is like sending and receiving data to and from a file.
95
Characteristics and Features of Java
Java Is Simple Java Is Secure Java Is Object-Oriented Java Is Robust Java Is Compiled and Interpreted Java Is Architecture-Neutral or Platform Independent Java Is Portable Java Is Multithreaded High Performance Java Is Distributed Java Is Dynamic Java programs carry with them substantial amount of run time information that is used to verify and resolve accesses to object at runtime. Java is capable of dynamically linking in new class libraries, methods, and objects.
96
A Simple Java Program – Hello.java
/* Hello World, first application, only output. */ import java.io.*; class Hello { public static void main (String args []) System.out.println(“Hello World\n”); } //end main }//end class To compile: javac Hello.java To run: java Hello Note : - Set Environment variables – To run java programs anywhere Set path to JDK bin directory set path=C:\Program Files\Java\jdk1.8.0_31\bin
97
A closer look /* Hello World, first application, only output. */
import java.io.*; class Hello { public static void main (String args []) System.out.println(“Hello World”); } //end main }//end class Multi line comment Similar to #include<stdio.h> Access to all the classes defined in java.io Keyword class to declare a new class Name of the class Main method Excecution statement Single line comment
98
Notice: Java is CASE SENSITIVE!!
File name has to be the same as class name in file. Need to import necessary class definitions All statements in Java end with a semicolon. Whitespace is ignored by compiler In Java, all code must reside inside a class.
99
public static void main (String args [])
All Java applications begin execution by calling main( ) main( ) must be declared as public, since it must be called by code outside of its class when the program is started. The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. This is necessary since main( ) is called by the Java interpreter before any objects are made. The keyword void simply tells the compiler that main( ) does not return a value. String args[ ] declares a parameter named args, which is an array of instances of the class String Objects of type String store character strings In this case, args receives any command-line arguments present when the program is executed.
100
System.out.println(“Hello World”);
This line outputs the string “Hello World” followed by a new line on the screen. System is a predefined class that provides access to the system out is the output stream that is connected to the console println( ) displays the string which is passed to it
101
Another Example: class Example2 {
public static void main(String args[]) int num; // this declares a variable called num num = 100; // this assigns num the value 100 System.out.println("This is num: " + num); num = num * 2; System.out.println("The value of num * 2 is "); System.out.println(num); }
102
Data Types Data type specify size and type of value that can be stored. Data types are classified as: Integer type Floating point type Character type Boolean type
103
Data Types : Integer Type
Java supports 4 types of integers Type Size Minimum value Maximum value byte 1 byte -128 127 short 2 byte -32768 32767 int 4 byte long 8 byte
104
Data Types : Floating point Type
Java supports 2 kinds of floating point storage Floating point numbers are treated as double-precision quantities. To force them to be in single-precision mode, f or F is appended to numbers. Floating-point data types support a special value known as Not-a- number (NaN). NaN is used to represent the result of operations such a divided zero by zero, where an actual number is not present. Type Size Minimum value Maximum value Float 4 byte 1.4e-045 3.4e+038 double 8 byte 4.9e-324 1.8e+308
105
// FLOATING TYPE EG: Compute the area of a circle
// FLOATING TYPE EG: Compute the area of a circle. class Area { public static void main(String args[]) double pi, r, a; r = 10.8; // radius of circle pi = ; // pi, approximately a = pi * r * r; // compute area System.out.println("Area of circle is " + a); }
106
Data Types : Character Type
Size Minimum value Maximum value Char 2 byte 65535 Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. Thus, in Java char is a 16-bit type. ASCII character set occupies the first 127 values in the Unicode character set. There are no negative chars. Even though chars are not integers, in many cases you can operate on them as if they were integers. This allows you to add two characters together, or to increment the value of a character variable.
107
CHARACTER TYPE EG class CharDemo {
public static void main(String args[]) char ch1, ch2; ch1 = 88; // code for X ch2 = 'Y'; System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2); }
108
class CharDemo2 { public static void main(String args[]) char ch1; ch1 = 'X'; System.out.println("ch1 contains " + ch1); // increment ch1, the next character in the unicode sequence ch1++; System.out.println("ch1 is now " + ch1); }
109
Data Types : Boolean Type
boolean type is used for logical values. It can have only one of two possible values, true or false. This is the type returned by all relational operators
110
Data Types : Boolean Type
class BoolTest { public static void main(String args[]) boolean b; b = false; System.out.println("b is " + b); b = true; if(b) System.out.println("This is executed."); System.out.println("This is not executed."); System.out.println("10 > 9 is " + (10 > 9)); }
111
Keywords There are 49 reserved keywords currently defined in the Java language. In addition to the keywords, Java reserves the following: true, false, and null. We may not use these words for the names of variables, classes, and so on.
112
Variables Basic unit of storage in a Java program.
It is defined by the combination of an identifier, a type, and an optional initializer. Variable declaration Syntax : type identifier [ = value][, identifier [= value] ...] ; Dynamic Initialization Variables are initialized dynamically(at run time)
113
Variables : Scope and Life time
Java allows variables to be declared within any block. A block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope. Within a block, variables can be declared at any point, but are valid only after they are declared. Two major scopes are those defined by a class and those defined by a method. The scope defined by a method begins with its opening curly brace. If a method has parameters, they too are included within the method’s scope.
114
Variables : Scope and Life time
Scopes can be nested. The objects declared in the outer scope will be visible to code within the inner scope. The reverse is not true. We cannot declare a variable to have the same name as one in an outer scope.
115
Example: class Scope { public static void main(String args[])
int x; // known to all code within main x = 10; if(x == 10) { // start new scope int y = 20; // known only to this block System.out.println("x and y: " + x + " " + y); x = y * 2; } y = 100; // Error! y not known here. x is still known here. System.out.println("x is " + x);
116
Variables : Scope and Life time
// This program will not compile class ScopeErr { public static void main(String args[]) int bar = 1; { // creates a new scope int bar = 2; // Compile-time error }
117
Operators Operators can be divided into four groups: Arithmetic
Bitwise Relational Logical Assignment
118
Operators : Arithmetic Operators
Result + Addition - Subtraction(Also Unary Minus) * Multiplications / Division % Modulus ++ Increment -- Decrement += Addition Assignment -= Subtraction ‘’ *= Multiplication ,, /= Division ,, %= Modulus ,,
119
Operators : Arithmetic Operators
Used in arithmetic expressions. The operands of the arithmetic operators must be of a numeric type or char types (since the char type in Java is a subset of int) Arithmetic operators are classified as: Basic Arithmetic Operators Modulus Operators Arithmetic Assignment Operators Increment and Decrement Operators
120
Arithmetic Operators : Basic Arithmetic
Basic arithmetic operators are Addition : + Subtraction : - Multiplication : * Division : / When the division operator is applied to an integer type, there will be no fractional component attached to the result.
121
Arithmetic Operators : Modulus Operator(%)
Returns the remainder of a division operation. It can be applied to floating-point types as well as integer types. Example: int x = 42; double y = 42.25; 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.25
122
Arithmetic Operators : Arithmetic Compound Assignment Operators
Arithmetic operator is combined with assignment operator. += , -=, *=, /=, %= Any statement of the form var = var op expression; can be rewritten as var op=expression; Benefits : Save a bit of typing time. They are implemented more efficiently by the Java run-time system than their equivalent long forms.
123
Arithmetic Operators : Increment and Decrement Operators
++, -- Example : x = x + 1; can be rewritten as: x++; x = x - 1; can be rewritten as: x--; These operators are appear in postfix form : Example: x = 42; y = x++; //output of y : 42 prefix form : y = ++x; //output of y : 43
124
Operators : Bitwise Operators
Result ~ Bitwise Unary NOT & Bitwise AND | Bitwise OR ^ Bitwise Exclusive OR >> Shift Right >>> Shift Right Zero Fill << Shift Left &= Bitwise AND Assignment |= Bitwise OR Assignment ^= Bitwise Excusive OR Assignment >>= Shift right Assignment >>>= Shift right zero fill Assignment <<= Shift left Assignment
125
Operators : Bitwise Operators
These operators act upon the individual bits of their operands. Bitwise operators can be classified as: Bitwise Logical Operators Left Shift Operator Right Shift Operator Unsigned Right Shift Operator Bitwise Assignment Operators
126
1 Binary Number Representation in Java left most bit byte b=42;
2^1+2^3+2^5 2+8+32=42 left most bit 0 means number is positive 1 means number is negative 2^ ^ ^ ^ ^ ^ ^ ^0 1
127
Negative Number Representation in Java
Java uses 2’s complement encoding a. inverting 1 to 0 and vice versa b. add 1 to the result Eg: - byte b=-42; 42 is represented as Inver 1s and zeros = Add 1 to the result 1 Result=
128
To Decode a Negative Number
Invert all 1s and 0s Add 1 to the result Eg:- -42= Inver all 1s and zeros= Add Result=
129
Bitwise Operators : Bitwise Logical Operators
A|B A&B A^B ~A 1 int a = 3; int b = 6; int c = a | b; int d = a & b; int e = a ^ b; int f = (~a & b) | (a & ~b); System.out.println(" c : "+c+" d : "+d+" e : "+e+" f : "+f); Output: ?
130
Bitwise Operators : Left Shift Operators
The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times. Syntax: value << num For each shift left, the high-order bit is shifted out and a zero is brought in on the right. Byte and short values are promoted to int when an expression is evaluated. Furthermore, the result of such an expression is also an int.
131
Example of left shift operator: byte a = 64,b; int i;
i = a << 2; b = (byte) (a << 2); System.out.println("Original value of a: " + a); System.out.println("i and b: " + i + " " + b); Output: Original value of a: 64 i and b: 256 0
132
Bitwise Operators : Right Shift Operators
The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. Syntax : value >> num Example : int a = 32; a = a >> 2; // a now contains 8 When a number is shifting right, the top (leftmost) bits exposed by the right shift are filled in with the previous contents of the top bit. This is called sign extension and serves to preserve the sign of negative numbers when you shift them right. Example : –8 >> 1 is –4 –8 >>1 –4
133
Bitwise Operators : Unsigned Right Shift Operators
Unsigned shift-right operator, >>>, always shifts zeros into the high-order bit. Example : int a=-1; a=a>>>24; System.out.println(a); –1 >>>24
134
Bitwise Operators : Bitwise Assignment Operator
All of the binary bitwise operators have a shorthand form Example : a = a >> 4; equivalent to a >>= 4; a = a | b; equivalent to a |= b;
135
Operators : Boolean Logical Operator
Result & Logical AND | Logical OR ^ Logical XOR (exclusive OR) ! Logical unary NOT || Short-circuit OR && Short-circuit AND &= AND assignment |= OR assignment ^= XOR assignment == Equal to != Not equal to ?: Ternary if-then-else Operate only on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value.
136
Boolean Logical Operator : Basic Boolean Logical Operator
The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they operate on the bits of an integer. The logical ! operator inverts the Boolean state: !true == false and !false == true. A B A|B A&B A^B !A False True
137
Boolean Logical Operator : Short circuit Operator
The & and | operators, when used as logical operators, always evaluate both sides. The && and || operators "short-circuit", meaning they don't evaluate the right hand side if it isn't necessary. Example : if (denom != 0 && num / denom > 10) Example : situation in which && and || can not be used if(c==1 & e++ < 100) d = 100; Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not
138
Boolean Assignment Operators
&= |= ^= Boolean Comparison Operators == != Boolean Ternary Operator ? : Syntax : expression1 ? expression2 : expression3 expression2 and expression3 are required to return the same type, which can’t be void. Example : int a=2,b=3,c=4,d; d=a>b?a:b; System.out.println(d); //output : 3
139
Operators : Relational Operator
The relational operators determine the relationship that one operand has to the other. The outcome of these operations is a boolean value i.e. true or false. Operator Result == Equal to != Not equal to > Greater than < Less than >= Greater than or equal to <= Less than or equal to
140
Operators : Assignment Operator
Syntax : var = expression; Variable must be compactable with expression It allows you to create a chain of assignments. Example : int x, y, z; x = y = z = 100; // set x, y, and z to 100
141
Operators Precedence . DOT OPERATOR Precedence 1 () [] 2 ++ -- ~ ! 3 *
/ % 4 + - 5 >> >>> << 6 > >= < <= 7 == != 8 & 9 ^ 10 | 11 && 12 || 13 ?: 14 =
142
Tutorial 2: Q1: Write a java program to do operations addition, subtraction, multiplication and division on any two numbers specified. Q2 a: Predict Output of the following code segment: int a=2,b=1,c=1,d; d=a | 4 + c >> b & 7; System.out.println(d); Q2 b: int xa=2; int ya=xa++; int za=xa; System.out.println("xa : "+(++xa)+" ya: "+ya+" za : "+za);
143
Type Conversion and Casting
Assign a value of one type to a variable of another type is called type conversion. Type conversion is classified as : Automatic Type Conversion Explicit Type Conversion
144
Type Conversion Rules :
An automatic type conversion will take place if the following two conditions are met: The two types are compatible. The destination type is larger than the source type. Example : Integer and floating-point types are compatible with each other int type is always large enough to hold all valid byte values Type Conversion Rules : All byte and short values are promoted to int If one operand is long then the whole expression is promoted to long If one operand is float then the whole expression is promoted to float If one operand is double then the whole expression is promoted to double
145
Example : byte b = 50; b = b * 2; // Error! Cannot assign an int to a byte! To handle this situation rewrite the above code as : byte b = 50; OR byte b = 50; b = (byte)(b * 2); int c; c = b * 2; Q) byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; System.out.println((f * b) + (i / c) - (d * s)); What is the type of data displayed by the println()? Why?
146
Explicit Type Conversion
To create a conversion between two incompatible types, we must use a cast. Syntax: (target-type) value target-type specifies the desired type to convert the specified value narrowing conversion : Explicitly making the value narrower so that it will fit into the target type Ex: Assign an int value to a byte variable int a; byte b; // ... b = (byte) a;
147
Truncation : the fractional component is lost
Ex : floating-point value is assigned to an integer type If the size of the whole number component is too large to fit into the target integer type, then that value will be reduced to modulo the target type’s range. Q) byte b,c; int i = 257,j; double d = ; b = (byte) i; c = (byte) d; j = (int) d; What is the value of b, c and j after executing above java codes?
148
Control Statements Control statements are used to alter the execution of statements based on certain conditions. Java’s program control statements can be put into the following categories: Selection statements/Branching Statements Iteration/Looping statements Jump statements
149
Selection Statement Selection statements allows to control the flow of program’s execution based upon conditions known only during run time. Java supports two selection statements: if nested if if-else-if ladder switch nested switch
150
Selection Statement : if
It can be used to route program execution through two different paths. Syntax : if (condition) statement1; else statement2; Each statement may be a single statement or a compound statement enclosed in curly braces. The condition is any expression that returns a boolean value. The else clause is optional.
151
Selection Statement : nested if
A nested if is an if statement that is the target of another if or else. Example : if(i == 10) { if(j < 20) a = b; if(k > 100) c = d; else a = c; } else a = d;
152
Selection Statement : if-else-if ladder
Syntax : if(condition) statement; else if(condition) ... else
153
Selection Statement : switch
Multiway branch statement. Used in menu driven programming. Syntax : switch (expression) { case value1: // statement sequence break; case value2: ... case valueN: default: // default stmt sequence }
154
The expression must be of type byte, short, int, or char.
Each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed. If we omit the break, execution will continue on into the next case.
155
Selection Statement : nested switch
A switch statement inside another switch Example : switch(count) { case 1: switch(target) // nested switch case 0: System.out.println("target is zero"); break; case 1: // no conflicts with outer switch System.out.println("target is one"); } case 2: // ...
156
Important features of the switch statements :
The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression. No two case constants in the same switch can have identical values. A switch statement is usually more efficient than a set of nested ifs and is faster when lot of cases are to be considered. Write a java program to print integers 1,2,3,4 and 5 in words using switch
157
Iteration Statement A loop repeatedly executes the same set of instructions until a termination condition is met. Java’s iteration statements(loops) are while do-while for
158
Iteration Statement : while (entry-controlled loop)
Syntax : while(condition) { // body of loop } The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. The body of the while can be empty. Write a program to print 10 to 0 using while loop. Write a program to find the mid point between i and j
159
Iteration Statement : do-while (exit-control loop)
Syntax: do { // body of loop } while (condition); do-while loop always executes its body at least once class DoWhile { public static void main(String args[]) { int n = 10; do { System.out.println( n); n--; } while(n > 0); }
160
Iteration Statement : for
Syntax : for(initialization; condition; iteration) { // body } It is possible to declare the variable inside the initialization portion of the for. When we declare a variable inside a for loop, the scope of that variable ends when the for statement does. It is possible to include more than one statement in the initialization and iteration portions of the for loop. Write a program to find the factorial of a number.
161
for Loop Variations: The condition controlling the for can be any Boolean expression. Example : boolean done = false; for(int i=1; !done; i++) { } Either the initialization or the iteration expression or both may be absent We can create an infinite loop by leaving all three parts of the for empty.
162
one loop may be inside another
Nested Loops: one loop may be inside another class Nested { public static void main(String args[]) { for(i=0; i<3; i++) for(j=i; j<3; j++) System.out.println("i : "+i+"\tj : "+j); System.out.println(" "); //output }
163
Jump Statement Transfer control to another part of the program.
Java supports three jump statements: break continue return
164
Jump Statement : break break statement has three uses.
It terminates a statement sequence in a switch statement It can be used to exit a loop When used inside a set of nested loops, the break statement will only break out of the innermost loop It can be used as a “civilized” form of goto. Syntax : break label; label is the name of a label that identifies a block of code When executing a break statement, control is transferred out of the named block of code. The labeled block of code must enclose the break statement, but it does not need to be the immediately enclosing block.
165
{ public static void main(String args[]) { boolean t = true; first:
class Break { public static void main(String args[]) { boolean t = true; first: { second: { third: { System.out.println("Before the break."); if(t) break second; // break out of second block System.out.println("This won't execute"); } System.out.println("This is after second block."); //output: Before the break. This is after second block.
166
Jump Statement : continue
Continue running the loop, but stop processing the remainder of the code in its body for this particular iteration. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. Q) Write a program to print all even numbers between 0 and 20 using for loop and continue statement
167
continue may specify a label to describe which enclosing loop to continue
class ContinueLabel { public static void main(String args[]) { outer: for(int i=0;i<4;i++) for(int j=0;j<4;j++) if(j==2) continue outer; System.out.println("i : "+i+" j : "+j); }
168
Jump Statement : return
Used to explicitly return from a method. Program control to transfer back to the caller of the method. Immediately terminates the method in which it is executed class Return { public static void main(String args[]) boolean t = true; System.out.println("Before the return."); if(t) return; // return to caller System.out.println("This won't execute."); }
169
Reading Input from user
A Java program can obtain input from the console through the keyboard. The Java system variable System.in represents the keyboard. The Java programming language provides a collection of methods stored in the Scanner class that perform read operations. The Java program must first import the containing class using import java.util.Scanner; Then a Scanner object is constructed using the following statement: Scanner in = new Scanner(System.in); Different methods that can be invoked using scanner object are: in.nextByte(), in.nextShort(), in.nextInt(), in.nextLong(), in.nextFloat(), in.nextDouble(), in.nextLine()
170
Sample program import java.util.Scanner; Import java.io.*; class Sampleapp { public static void main(String[] args) { int num; float fnum; String str; Scanner in = new Scanner(System.in); System.out.println("Enter a string: "); str = in.nextLine(); //read i/p string System.out.println("Input String is: "+str); System.out.println("Enter an integer: "); num = in.nextInt(); //read i/p integer no System.out.println("Input Integer is: "+num); System.out.println("Enter a float number: "); fnum = in.nextFloat(); //read i/p float number System.out.println("Input Float number is: "+fnum); }
171
Assignment 1(Date of submission :27/2/17)
Set 1(Roll 1-20) Design a use case diagram for a Hospital management system. Write a program to display Armstrong numbers in an interval in java. Set 2 (Roll:21-40) Design a class diagram for a Railway reservation system. Write a program to display prime numbers in an interval in java. Set 3 (Roll:41-59) Design a class diagram for Course registration system. Write a menu driven program to implement a calculator in java.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.