You are on page 1of 60

Object Oriented Programming using Java

Education, Training and Assessment
We enable you to leverage knowledge anytime,
anywhere!

2

Copyright Guideline
© 2013 Infosys Limited, Bangalore, India. All Rights Reserved.

Infosys believes the information in this document is accurate as of its publication date; such
information is subject to change without notice. Infosys acknowledges the proprietary rights of
other companies to the trademarks, product names and such other intellectual property rights
mentioned in this document. Except as expressly permitted, neither this documentation nor
any part of it may be reproduced, stored in a retrieval system, or transmitted in any form or by
any means, electronic, mechanical, printing, photocopying, recording or otherwise, without the
prior permission of Infosys Limited and/ or any named intellectual property rights holders
under this document.

Copyright © 2013-2014, Infosys Limited

Confidential

3

Confidential Information
 This Document is confidential to Infosys Limited. This document contains information and data that
Infosys considers confidential and proprietary (“Confidential Information”).
 Confidential Information includes, but is not limited to, the following:
 Corporate and Infrastructure information about Infosys
 Infosys’ project management and quality processes
 Project experiences provided included as illustrative case studies
 Any disclosure of Confidential Information to, or use of it by a third party, will be damaging to Infosys.
 Ownership of all Infosys Confidential Information, no matter in what media it resides, remains with
Infosys.
 Confidential information in this document shall not be disclosed, duplicated or used – in whole or in part –
for any purpose other than reading without specific written permission of an authorized representative of
Infosys.
 This document also contains third party confidential and proprietary information. Such third party
information has been included by Infosys after receiving due written permissions and authorizations from
the party/ies. Such third party confidential and proprietary information shall not be disclosed, duplicated
or used – in whole or in part – for any purpose other than reading without specific written permission of
an authorized representative of Infosys.

3
Copyright © 2013-2014,
Infosys Limited

Confidential

0-OOP Course Name: OO programming using Java Document Number: OOP-01 Version Number: V4. Infosys Limited Confidential .4 Course Information Course Code: CCFP4.0 Copyright © 2013-2014.

5 Why these courses – OOP using Java? Object oriented programming is used to build complex and large software systems Problem Solving skills Acquaints you with OOP  features  Choose most appropriate  Data  structure and Algorithm Implementation of OOP  features using Java Basic vocabulary of  Programming Unit Testing Techniques Object oriented thought process Code Tuning Techniques Object Oriented programming skills are essential for creation of robust software using languages  like Java  and C# Copyright © 2013-2014. Infosys Limited Confidential .

Infosys Limited Confidential .6 Topics covered in OOP using Java course • Programming Fundamentals • Data Structures • Software Development Lifecycle Overview • Object Oriented Concepts • Object Oriented Fundamentals • Relationships • Polymorphism – Static and Dynamic • Packages • Code Optimization Techniques and Best Practices • Unit Testing Copyright © 2013-2014.

Programming Fundamentals .

Infosys Limited Confidential .8 Programming Fundamentals • Problem Solving Skills • Identifiers • Variables • Data types • Declaration of variables • Operators • Control Structures Copyright © 2013-2014.

9 Skills for Software Engineers Coding Software Testing Knowledge of tools Logical and analytical  thinking Problem Solving Skills Technical Skills Copyright © 2013-2014. Infosys Limited Communication Teamwork Soft Skills Confidential .

10 What is a Problem? A problem is a puzzle that requires logical thought or mathematics to solve it Source: Collins COBUILD Advanced Learner’s  English Dictionary Problem Types Social Legal  Scientific Computational Business Copyright © 2013-2014. Infosys Limited Confidential .

11 Computational Problem Solving • Computers can be effectively used to solve many complex problems in all domains. However we will primarily focus on solving business problems • Using computers to solve complex problems require computational thinking (way in which one can use computers to solve problems) – Computational thinking requires problem solving techniques that programmers use to analyze problems and design solutions Copyright © 2013-2014. Infosys Limited Confidential .

Infosys Limited Sub-problems Confidential .12 Solving complex business problem – Approach Top-down Analysis Problem Online Ticket Booking Login Travel Booking 90 Making Payment Register Travel Options Credit Card Login Validation Passenger Details Net banking Bottom-up Synthesis Copyright © 2013-2014.

These are some fundamental problems  encountered in real world problems  Copyright © 2013-2014.13 Solving complex business problem – Approach Consider building the Travel Options module Source Destination Date of travel Type of travel Input What logic might be  involved here? Train details Seat availability Processing Output Searching on input criteria.. Infosys Limited Confidential . Sorting on number of trains and time etc.

14 Frequently encountered problems Problems  Counting include Searching Sorting Decision Optimization Copyright © 2013-2014. Infosys Limited Confidential .

Steps Top-down Analysis Bottom-up Synthesis • The problem is broken down into smaller sub problems • Each sub problem solution is built as a unit or module • Each sub problem is successively refined till we recognize the solution • Modules are successively put together to make the entire solution Guided Activity: Introduction to Problems .Assignment 1 Copyright © 2013-2014.15 Analysis and Synthesis . Infosys Limited Confidential .

Infosys Limited Obviously. some  LOGIC is at work! Solution Process to solve  problem Confidential Output .16 Problem solving requires identification and understanding of: How does the process generate the  output from the inputs provided?  Problem data Constraints Input Copyright © 2013-2014.

17

Logic

Logic is a method of reasoning that involves a series of
statements, each of which must be true, if the
statement before it is true.
Source : Collins COBUILD Advanced Learner’s  English Dictionary

• Logic requires thinking in a step by step manner about how a problem can be
solved
• Logic is a mental model required to solve a problem
• The logic is represented as an ALGORITHM

Copyright © 2013-2014, Infosys Limited

Confidential

18

Algorithms - Definition
Demo: Algorithms – Assignment 2

Algorithm is a finite set of steps to accomplish a task /
solve a problem. The steps must be executed in some
definite sequence to achieve the expected result.

Algorithm

=

Computation

Finite steps

Must be executed 
(computable) 

Copyright © 2013-2014, Infosys Limited

Confidential

+

Control
Definite sequence 

19

Algorithm- Representation
Flowcharts

Pseudo-code

• Diagrammatic representation

• English like representation using
programming constructs

• Good for smaller problems

• Good for larger problems

We will focus more on writing pseudo‐code in this course

Demo : Algorithm and its Representation – Assignment 3

Copyright © 2013-2014, Infosys Limited

Confidential

etc. Python etc. simple English to write pseudo-code • Uses keywords and structured phrases like begin. Copyright © 2013-2014. else.20 Pseudo-code • Is a way to represent the step by step operations to find a solution to the given problem • Uses a structured. limited natural language vocabulary to develop logic • Avoids the need to consider machine/language specific details • Simplifies the process of program writing Pseudo-code Guidelines • Use clear. then. end. for. • Machine/language syntax details are avoided. However it is easy to translate to a high level programming language like Java. C. if. Infosys Limited Confidential .

21 Pseudo-code – Building blocks Building Blocks are Sequential Selectional Iterational are are Copyright © 2013-2014. Infosys Limited Recursion if while do if else do while else if ladder for Confidential .

Item_Price Copyright © 2013-2014. Infosys Limited Confidential . Item_Name.22 Pseudo-code : Variables • Container for data in memory • Meaningful names must be given to identify data in a problem – Examples : Item_Code.

 “Item Price:”.  Item_Price Copyright © 2013-2014.23 Pseudo-code : Operations Operation Description Examples Assignment Used to assign a Operation variable or constant or the result of an expression to a variable Item_Code = Item_Code_Temp Item_Code = 1001 Item_Code = Item_Code + 1 Input Operation Used to input a variable from user input Item_Name. Item_Price.  Item_Code. “Item Name:”.  Item_Name.  Supplier_Code Output Operation Used to output values to user display “Hello World” display “Item Code:”. Infosys Limited Confidential .

24 Pseudo-code . Infosys Limited Confidential .Best Practices • Each instruction in the pseudo-code can be numbered for easy reference • Use indent to clearly communicate structure of the pseudo-code • Provide a meaningful name for the pseudo-code • Selectional control structures – if and if-else statements should end with end-if • Iterational control structures – for statements should end with end-for – while statements should end with end-while • Conditional expressions – Two or more conditional expressions can be combined using ‘and’ or ‘or’ Copyright © 2013-2014.

  end‐for Copyright © 2013-2014 Infosys Limited Confidential .   input N 2.   for Counter = 1 to N do 3. Mark3 4.         Average = Sum / 3 6.      input Mark1.        end‐if 11. Mark2.         if (Average >= 65) then 7. Sum = Mark1 + Mark2 + Mark3 5.         else 9.25 Pseudo-code conventions Pseudo code to compute average marks scored by trainees in 3 modules Meaningful name Line numbers Indents for easy reading AVERAGE‐MARKS 1.            display “Student Failed” 10.            display “Student Passed” 8.

26 Pseudo-code testing .Dry Run • Pseudo-code cannot be executed on a real computer • Dry run simulates the computer executing each instruction one by one and recording the values of the variables in a table called as the Trace Table • Used for checking correctness of logic Copyright © 2013-2014 Infosys Limited Confidential .

Variable name n Demo : Pseudo-code Testing – Assignment 4 Copyright © 2013-2014 Infosys Limited Confidential .27 Pseudo-code testing – Trace Table • Each column corresponds to a variable used in the pseudo-code • Each row corresponds to the value of a variable which is affected by the line in the pseudo-code Line number Variable name 1 ………….

28 Algorithm properties Properties Input Has zero or more inputs that are provided to it initially or dynamically Output Has one or more outputs. Knuth Pearson Edition Copyright © 2013-2014 Infosys Limited Confidential . quantities that have a specified relation to inputs are Finiteness Must terminate after a finite number of steps Definiteness Action in each step to be carried out must be rigorously and unambiguously specified Effectiveness Operations to be primitive verifiable using pencil and paper and Reference : The Art of Computer Programming Fundamental Algorithms Third Edition Donald E.

29 Algorithm properties assignments Demo : Algorithm properties– Assignment 5 Guided Activity: Algorithm properties .Assignment 6 Copyright © 2013-2014 Infosys Limited Confidential .

we need: – Logic – High level programming language • Programming Fundamentals – Identifiers We will be using Java as the high level programming language in this course – Variables – Data types – Operators etc Copyright © 2013-2014. Infosys Limited Confidential . to solve the problem using a program.30 Programming Constructs in Java Guided Activity: Programming constructs in Java .Assignment 7 • Given a real world problem.

31 Identifiers – Guided Activity • Are names given to anything that you want to identify in a program • Helps to refer to that item from any place in the program • Can start with an underscore (_) or dollar sign ($) • Identifiers cannot match any of Java's reserved words • Are case-sensitive and have no maximum length Identify the identifiers  needed to solve the problem  discussed as part of previous  guided activity? billId customerId billAmount Copyright © 2013-2014. Infosys Limited Confidential .

Infosys Limited Confidential .32 Variables – Guided Activity • An identifier for the data in the program • Holds the data in your program • Is a location (or set of locations) in memory where a value can be stored • A quantity that can change during program execution What type of data will be Can we consider the  stored in these member identifiers identified earlier  variables ? as variables required to solve  How many bytes will it the problem discussed? occupy in memory??? Yes!!! Copyright © 2013-2014.

Infosys Limited Confidential .33 Data Types (1 of 3) • Data types determine the following: – Type of data stored – Number of bytes it occupies in memory – Range of data Copyright © 2013-2014.

Data types (2 of 3) Data Types Non-Primitive Primitive types array integer type byte short char long Copyright © 2013-2014. Infosys Limited floating type int class boolean float Confidential double interface .

0f false • The char data type in Java is 2 bytes because it uses UNICODE character set to support internationalization • UNICODE is a character set which covers all known scripts and languages in the world Guided Activity: Programming constructs in Java .0d required for char data type in ‘\u0000’ (UNICODE  Java? equivalent of null) Logical boolean 1 byte Floating Type 0. of bytes  occupied Default Value Integer Type byte 1 byte 0 short 2 bytes 0 int 4 bytes 0 long 8 bytes 0L float 4 bytes double 8 bytes Textual char 2 bytes Why is it that two bytes are 0. Infosys Limited Confidential .35 Data Types (3 of 3) Category Data Type No .Assignment 8 Copyright © 2013-2014.

36 Declaration of variables – Guided Activity We have identified the data types for the variables. float billAmount. Infosys Limited Confidential . how can we declare those variables? Example: int billId. How can we initialize these variables to values mentioned in the problem and write a simple program? We must understand different types of operators and how to write a simple program Copyright © 2013-2014. int customerId.

Infosys Limited Confidential .37 Operators (1 of 7) • Used to perform specific operations on one or more operands (or variables) and provide a result Assignment Operator Arithmetic Operators Relational Operators Logical Operators Prefix and Postfix Operators Copyright © 2013-2014.

customerId=101. Example: billId=1001.38 Operators (2 of 7) • Assignment Operator: – Used to assign a value or a variable or the result of an expression to a variable – Syntax: Variable = Variable or Value or Expression. You will encounter examples of a variable being initialized with another variable or expression as you solve the upcoming guided activities. Infosys Limited Confidential . billAmount=199. Copyright © 2013-2014. Note: This is an example where a variable is initialized with a value.99f.

39 Operators (3 of 7) • Arithmetic Operators – Used for performing arithmetic operations Operators + * / % Description Additive operator (also used for String concatenation) Subtraction operator Multiplication operator Division operator Modulus operator Can % operator be applied on floating point data? Yes!!! % can be applied to floating-point data type also in Java Copyright © 2013-2014. Infosys Limited Confidential .

40 Operators (4 of 7) • Relational Operators – Relational operators (also known as Comparison operators) – Used in conditional statements to compare values and take action depending on the result Operators == < > <= >= != Copyright © 2013-2014. Infosys Limited Description Equal to Less than Greater than Less than or equal to Greater than or equal to Not equal to Confidential .

41 Operators (5 of 7) • Logical Operators – Logical operators are based on boolean algebra – Result will always be true or false Operator && Copyright © 2013-2014. Infosys Limited Meaning Short Circuit-AND || Short Circuit-OR ! Unary NOT Confidential .

Infosys Limited Postfix operator Confidential . ++val. it is postfix Example: val=1.42 Operators (6 of 7) Prefix and post fix operators • Operators ++ and -. it is prefix and if the operator is used after the operand. Prefix operator Copyright © 2013-2014. val--.are called as increment and decrement operators • These operators increment or decrement the variable’s value by 1 • They are also called as unary operators because they have only one operand to operate • If the operator is used before the operand.

Copyright © 2013-2014. Value of result will be 6 and val will also be 6. Infosys Limited Confidential . – Post fix operator makes the assignment and then increments/decrements the value Example: int val=5. int result. result = val++. Value of result will be 5 and val will be 6.43 Operators (7 of 7) • Difference between prefix and postfix operators – Prefix operator first increments / decrements and then makes the assignment Example: int val=5. result = ++val. int result.

Assignment 10 Copyright © 2013-2014. Infosys Limited Confidential .Assignment 9-B • Identifiers • Local Variables • Data types • Operators • Compilation and Execution of a Java program Note: More on compilation and execution of a Java program will be discussed later Guided Activity: Programming constructs in Java .44 A simple program Demo: Programming constructs in Java -Working in Eclipse Assignment 9-A Demo: Programming constructs in Java .

different set of statements will be executed Iteration • Certain statements will be executed repeatedly Copyright © 2013-2014.Assignment 11 • A control structure refers to the way in which the programmer specifies the order of executing the statements • The following approaches can be chosen depending on the problem statement: Sequential • All the statements will be executed in the same order as it is written Selection • Based on some conditions.45 Control Structures Guided Activity: Programming constructs in Java . Infosys Limited Confidential .

46 Selection Control Structures Selection Control Statements if switch if-else else if ladder Nested if Copyright © 2013-2014. Infosys Limited Confidential .

47 Selection Control Structure statements (1 of 2) • if-else statement . } else { Statement set‐2. } Next Statement. if (condition‐1)  { Statement set‐1. Infosys Limited if (condition) { Statement set‐1. } Next Statement. } ……………………………… ……………………………… else  { Statement set‐x. } else if (condition‐2)  { Statement set‐2.  Confidential .Syntax: • ‘else-if’ ladder statement – Syntax: Copyright © 2013-2014.

Confidential .48 Selection Control Structure statements (2 of 2) • Nested if statement . } } ……………. } Next Statement.. else{ Statement set‐n.. Infosys Limited if (condition‐1)  { if (condition‐2) { …. if(condition‐n){ Statement set‐1. } else{ Statement set‐2.Syntax: Copyright © 2013-2014. } } else  { Statement set‐x.

Infosys Limited Confidential . …………… case integer or character constant‐n :  Statement(s). default                                                  :  Statement(s).Selection Control Structures ‘switch’ statement 49 • The ‘switch’ statement is a selection control structure that helps to select a choice from a set of available choices • It is very similar to ‘if’ statement. } Demo: Programming constructs in Java .Assignment 13 Copyright © 2013-2014. break. But ‘switch’ statement cannot replace ‘if’ statement in all the situations • Syntax: switch(integer variable or integer expression or character variable) { case integer or character constant‐1 :  Statement(s). break. break.Assignment 12 Guided Activity: Programming constructs in Java .

while Confidential for  .50 Iterational Control Structures • Iteration (repetitive) control structures are used to repeat certain statements for a specified number of times • The statements are executed as long as the condition is true • These kind of control structures are also called as loop control structures Iteration Control  Statements while Copyright © 2013-2014. Infosys Limited do..

• for loop statement – Syntax: for (Initialization.51 Iterational Control Structure statements • While loop statement . Termination‐Condition.Assignment 14 Copyright © 2013-2014. } while (condition). Next Statement. • Do-while loop statement – Syntax: do { Set of statement(s). } Next Statement. Increment‐Step){ Set of statement(s). } Next Statement.Syntax: while (condition) { Set of statements. Infosys Limited Confidential . Demo: Programming constructs in Java .

24 Quitting the iteration control structure Different ways of  quitting from the  loops break Copyright © 2013-2014. Infosys Limited continue Confidential exit .

Infosys Limited Confidential . – the loop terminates immediately and the execution resumes with the next statement following the loop • If used in a nested loop.53 break statement Demo: Programming constructs in Java . quits only the loop from where it is called Copyright © 2013-2014.Assignment 15 • Forces the termination of a loop • When encountered in a loop.

‘continue’ makes the execution of the increment portion of the statement and then evaluates the conditional part • In case of while and do-while loops. Infosys Limited Confidential .Assignment 16 • ‘continue’ statement forces the next iteration of the loop to take place and skips the code between ‘continue’ statement and the end of the loop • In case of for loop. ‘continue’ makes the conditional statement to be executed Copyright © 2013-2014.54 continue statement Demo: Programming constructs in Java .

18 Copyright © 2013-2014.Assignment 17.55 Comparison of break and continue statements break statement continue statement Used to quit a loop or switch Used to continue the loop Can be used only within loops or switch Can be used only within the loops Guided Activity: Programming constructs in Java. Infosys Limited Confidential .

Infosys Limited Confidential .56 Type Conversion • A variable of one type can receive the value of another type • Type Conversion can be of two types: • Widening Conversion int i = 10. i = l. int i. long l. l = i. Why? • Narrowing Conversion long l = 109000l. In this case there is a compilation error. The error arises due to assignment of a long data to an int variable Copyright © 2013-2014.

Note: In narrowing conversion typecasting should be done explicitly else it will result in compile time error Demo: Programming constructs in Java . int i. i = (int) l. Infosys Limited Confidential . we have to explicitly specify the type cast operator – This prevents accidental loss of data long l = 109000l.Assignment 20 Copyright © 2013-2014.57 Type Casting • Whenever a larger type is converted to a smaller type.Assignment 19 Guided Activity: Programming constructs in Java .

Infosys Limited Confidential .58 Programming constructs in Java – we have learnt • Identifiers • Variables • Data types • Declaration of variables • Operators • Control Structures • Type conversion and casting Copyright © 2013-2014.

coursera.udacity. Infosys Limited Confidential .org/#course/algs4partI – https://www.59 Self Study • Data structures and Algorithms – https://www.udacity.com/course/viewer#!/c-cs215/l-48747095/m-48691607 – https://www.com/course/cs101 Copyright © 2013-2014.org/#course/algs4partII – https://www.coursera.org/#course/algo • Intro to Computer Science – https://www.coursera.org/#course/cs101 – https://www.coursera.

mechanical. Except as expressly permitted. stored in a retrieval system. Infosys acknowledges the proprietary rights of other companies to the trademarks. such information is subject to change without notice. photocopying. Infosys believes the information in this document is accurate as of its publication date. neither this documentation nor any part of it may be reproduced. product names and such other intellectual property rights mentioned in this document. All Rights Reserved. or transmitted in any form or by any means. India. Bangalore. recording or otherwise.Thank You © 2013 Infosys Limited. . without the prior permission of Infosys Limited and/ or any named intellectual property rights holders under this document. printing. electronic.