View
57
Download
0
Category
Preview:
DESCRIPTION
Fundamentals of Core java
Citation preview
7/13/2019 Introduction to Java Fundamentals
1/98
1TCS Confidential
Introduction to Java(Genesis & Basics)
Java Programming
7/13/2019 Introduction to Java Fundamentals
2/98
2TCS Confidential
Genesis of Java
What is Java?
Java BuzzwordsJava API and JVM
Data Types in Java
Conditional Statements and Constructs
7/13/2019 Introduction to Java Fundamentals
3/98
3TCS Confidential
What is Java?
Java is a programming language
developed by Sun Microsystems in 1991
Its the current hot language
Its almost entirely object-oriented
It has a vast library of predefined objects
and operations
It is platform (OS/Hardware) independent
7/13/2019 Introduction to Java Fundamentals
4/98
4TCS Confidential
Pre-requisite For Java Execution
JDK 1.3 or above (Java Development
Toolkit)
Download the JDK version compatible with
your operating system (Windows, Unix,
Linux etc) fromhttp://java.sun.com
Execute Setup.exe File in your JDK kit for
installing Java Development/Executionenvironment in your machine.
7/13/2019 Introduction to Java Fundamentals
5/98
5TCS Confidential
Writing a Java Program
public class Suryodaya{
public static void main(String args[])
{System.out.println( Welcome to Suryodaya! );
}
}
Executing a Java program is a two step processCompilation (javac)
Execution (java)
7/13/2019 Introduction to Java Fundamentals
6/98
6TCS Confidential
How to Compile the Java Program?
Type the program using Notepad or DOSeditor and save it as Suryodaya.java.
Java being case sensitive, Suryodaya isdifferent from suryodaya Now type -
c:\jdk1.3>bin>javac Suryodaya.java
Suryodaya.class file is created on
successful compilation.
7/13/2019 Introduction to Java Fundamentals
7/98
7TCS Confidential
How to Run the Java Program?
Once the class file is created, type thefollowing command at the prompt to run theprogram:
c:\jdk1.3>bin>java Suryodaya
Setting the CLASSPATH
The output is:
c:\jdk1.3>bin>Welcome to Suryodaya!
7/13/2019 Introduction to Java Fundamentals
8/98
8TCS Confidential
The Java Buzzwords
Simple
Object-orientedPortable
SecureRobust
Multithreaded (will be discussed in later sessions)Interpreted (will be discussed in later sessions)
7/13/2019 Introduction to Java Fundamentals
9/98
9TCS Confidential
Simple
Javas syntax is similar to that of C++
Features that led to complexity and
ambiguity were removed (For Ex:)
Simple and easy to learn language
Java = C++ - Complexity & Ambiguity
+ Security & Portability
7/13/2019 Introduction to Java Fundamentals
10/98
10TCS Confidential
Object Oriented
OO Programming is a powerful paradigm -
complex programming problems can be
reduced to simple solutions (For Ex:)
Everything in Java (except the primitivedata types) is an object
7/13/2019 Introduction to Java Fundamentals
11/98
11TCS Confidential
Portable
Goal of Java: Write once, run anywhere,anytime, forever! How?
Javas Magic: The Bytecode & JVM Java Complier always converts a .java file
(High level language) into a Generic formatcommonly know as bytecode, .class file
JVM ,specific to OS (Windows, Unix, Linuxetc) then interprets this .class file andexecutes the bytecode
7/13/2019 Introduction to Java Fundamentals
12/98
12TCS Confidential
What is Java Virtual Machine (JVM)?
JVM is simply the interpreter and the
classes that are needed to run the Java
bytecode.
Byte codes are not compiled with the
knowledge of underlying hardware/OS, the
JVM is always machine specific and knows
how the underlying OS works.
7/13/2019 Introduction to Java Fundamentals
13/98
13TCS Confidential
Java Program Execution
JavaSourceCode
Java BytecodeCompiler
JavaBytecodes
Java
Bytecode
Moved
Bytecode Verifier
(Verif ies that the byte
codes are from Java
compiler or not)
Java Class
Library
Java Class
Library
Java Virtual MachineJava Virtual Machine
Java InterpreterJava Interpreter
Runtime System(Executable Code)
Runtime System(Executable Code)
Operating SystemOperating System
HardwareHardware
Class Loader
Rejected
Exceptions handled Rejected
2
1
3
4
5
6
7
8
9
Suryodaya.java
Suryodaya.class
7/13/2019 Introduction to Java Fundamentals
14/98
14TCS Confidential
Secure
Java was designed to be a safe language.
Its powerful security mechanism acts atfour different levels of system architecture:
Security by Complier Security by Class Loaders
Java Virtual Machine Using Java API
7/13/2019 Introduction to Java Fundamentals
15/98
15TCS Confidential
Robust
Strictly Typed Language (For Ex:)
Memory Management (For Ex:) Exceptional handling (For Ex:)
7/13/2019 Introduction to Java Fundamentals
16/98
16TCS Confidential
Robust ...
Example of Exception Handling:
try {
float i = a / b; // if b=0
}
catch(Exception e) {
System.out.println(Dividing by Zero is not allowed+e);
}finally { }
7/13/2019 Introduction to Java Fundamentals
17/98
17TCS Confidential
Java API
Java API orApplication Program Interfacecontains class libraries needed or called by
the application programs at run-time.Java APIs can be downloaded from
http://java.sun.comJava API For:
J2SE (Standard Edition)
J2EE (Enterprise Edition)
J2ME (Micro Edition)
7/13/2019 Introduction to Java Fundamentals
18/98
18TCS Confidential
Java API
J2SE (Standard Edition): Core Java
J2EE (Enterprise Edition): Advance Java
(Servlets, EJBs, JSPs etc)
J2ME (Micro Edition): PDA / MobileApplications Libraries etc..
7/13/2019 Introduction to Java Fundamentals
19/98
19TCS Confidential
Diagrammatic Representation JAVA
Platform
Java API
Java Applications
Java Virtual Machine
Hardware
JavaCode
NativeCode
Foundation
Classes
Network and
I/O Classes
Abstract Window
Toolkit (AWT)
7/13/2019 Introduction to Java Fundamentals
20/98
20TCS Confidential
Understanding Java Programming
Fundamentalspublic classSuryodaya {
public static void main(String args[])
{if(args.length > 0)
{
System.out.print(Welcome ::);for(int i=0; i
7/13/2019 Introduction to Java Fundamentals
21/98
21TCS Confidential
Understanding Java Programming
FundamentalsThe name of the program can be anything,but should begin with a letter and maycontain digits but no blanks.
The word public means that the contents of
the block are accessible from all otherclasses.
The word static means that the definedmethod is applied to the class itself ratherthan to the objects of the class.
7/13/2019 Introduction to Java Fundamentals
22/98
22TCS Confidential
Understanding Java Programming
FundamentalsThe word void means that the method main
has no return value.
The word main is the name of the method
being defined.
String args[] is a parameter to the method.
It is an array of objects of String type.
System.out.println tells the system to print
the message: Welcome::
7/13/2019 Introduction to Java Fundamentals
23/98
23TCS Confidential
Understanding Java Programming
Fundamentals The word println is the name of the
method that tells the system to positionthe cursor at the beginning of the next line
after the message is printed
7/13/2019 Introduction to Java Fundamentals
24/98
24TCS Confidential
Basics in Java (Self Reading)
Data Types, Variables, LiteralsSimple Data Types
Type Conversion and CastingAutomatic Type Promotion
Arrays
OperatorsArithmetic, Bitwise, Relational, Boolean,Assignment, ?
Operator Precedence and Associativity
Control Statements
Selection and Iteration
7/13/2019 Introduction to Java Fundamentals
25/98
25TCS Confidential
Data Types (Self Reading)
There are two data types in Java:
Primitive
Reference
Java defines eight primitive types of data:
byte, short, int, long, char, float, double,
boolean
Java defines 3 reference data types
arrays, classes, Interfaces
7/13/2019 Introduction to Java Fundamentals
26/98
26TCS Confidential
Primitive Data Types (Self Reading)
3.4e-38 to 3.4e+3832float
1.7e-38 to 1.7e+3864double
-128 to 1278Byte
+ 32,768 to - 32,76716short
-2,147,483,648 to +2,147,483,64732int
+ 9,223,372,036,854,775,80864long
RangeWidthName
7/13/2019 Introduction to Java Fundamentals
27/98
27TCS Confidential
Primitive Data Types (Self Reading)
true or false32boolean
0 to 65,53516char
RangeWidthName
7/13/2019 Introduction to Java Fundamentals
28/98
28TCS Confidential
Variables (Self Reading)
Variables can be defined as memory unitsinto which data is stored. There are two
basic parameters used to define a variable:Identifier or name
Type or categoryAssigning a value to a variable at the time
of declaration is optionalApart from this, variables have a scopewhich defines their lifetime and visibility.
7/13/2019 Introduction to Java Fundamentals
29/98
29TCS Confidential
Literals (Self Reading)
A literal is a simple value where what you
type is what you get. Numbers,
characters and Strings are all examples ofliterals.
Literals are constant data values.
Examples:
100 98.6 x This is a test ox98
7/13/2019 Introduction to Java Fundamentals
30/98
30TCS Confidential
The Scope and Lifetime of Variables
Two major scopes:Scope by Class
Scope by MethodScope by Block
Variables declared inside a scope are notvisible (that is, accessible) to the code that
is defined outside that scope
7/13/2019 Introduction to Java Fundamentals
31/98
31TCS Confidential
Example - Usual Scope and Lifetime
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
// x and y both known here
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); } }
7/13/2019 Introduction to Java Fundamentals
32/98
32TCS Confidential
Type Conversion And Casting
Type conversion is converting one data
type to another.
Conversion may be:
Automatic (Implicit)Casting (Explicit or Forced)
7/13/2019 Introduction to Java Fundamentals
33/98
33TCS Confidential
Automatic Type Conversion
An automatic type conversion will takeplace if the following two conditions are
met:The two types are compatible.
The destination type is larger than the sourcetype.
When these two conditions are met, a
widening conversion takes place (byte toshort, int, long).
7/13/2019 Introduction to Java Fundamentals
34/98
34TCS Confidential
Automatic Type Conversion
Examples of Automatic type conversions:
int a; byte b; a = b;
long l; int I; l = I;
double d; float f; d = f;
float f; int i; i = f;
7/13/2019 Introduction to Java Fundamentals
35/98
35TCS Confidential
Casting Incompatible Types
Explicit or forced type conversion.
General form: (target-type) value
target-type specifies the desired type toconvert the specified value to
Example:int a; byte b; b = (byte) a;
Usually a narrowing conversion requirestype cast.
7/13/2019 Introduction to Java Fundamentals
36/98
36TCS Confidential
What are Arrays?
An array is defined as a group of like typedvariables referred to by a common name.
Like variables, it is essential to specify thefollowing for declaring an array:
Data values (int , float)
Identifier for the array
Elements of an array cannot be accessedusing pointer arithmetic
7/13/2019 Introduction to Java Fundamentals
37/98
37TCS Confidential
How to Declare Arrays?
Example
float basicSalary[ ]; // Array declaration
basicSalary = new float[10]; // Refers to a
float array
// Allocating space
new operator automatically allocates the
array and initializes its elements to zero.
7/13/2019 Introduction to Java Fundamentals
38/98
38TCS Confidential
Assigning Values
NULL is assigned for an array of objects.Array elements cannot be accessed till their
values are inserted. Example: double nums[ ] = { 10.1, 11.2, 12.3,
13.4, 14.5 };Above syntax does 3 things at a time:
Declaration of array
Allocation of space
Initialization of array with 5 elements.
How to Declare Multi dimensional
7/13/2019 Introduction to Java Fundamentals
39/98
39TCS Confidential
How to Declare Multi-dimensional
Arrays?Multidimensional arrays are arrays of arrays.
Examples:
1.Assume that a two dimensional array of
two rows and three columns has to be
declared:
int multiTwo[ ] [ ] = new int[2][3];
2.Initializing a 2x3 integer array:
int [ ] [ ] a = { {77, 22, 44}, {11, 33, 88}};
7/13/2019 Introduction to Java Fundamentals
40/98
40TCS Confidential
Example - One-dimensional Array
classAverage {
public static void main(String args[ ]) {
doublenums[] ={10.1, 11.2, 12.3, 13.4, 14.5};double result = 0;
for (int j = 0; j < 5; j++)result = result + nums[j];
System.out.println(average is +result / 5); }}
7/13/2019 Introduction to Java Fundamentals
41/98
41TCS Confidential
Declaring Arrays
It is not essential in Java to allocate the samenumber of elements in each dimension:
Example: int multiTwo[ ][ ] = new int [3][ ];multiTwo[0] = new int[1];
multiTwo[1] = new int[2];multiTwo[2] = new int[3];
[0][0]
[1][0] [1][1]
[2][0] [2][1] [2][2]
One element in row 0
Two elements in row 1
Three elements in row 2
7/13/2019 Introduction to Java Fundamentals
42/98
42TCS Confidential
Example - Two-dimensional Array
class ShowArray{ int p;
public static void main(String args[]) {
int twoD[][] = new int[4][5];for (int j = 0; j < 4 ; j++) {
for (int k = 0; k < 5; k++) {twoD[j][k] = p++;
System.out.println(twoD[j][k] + );
}
}}
}
U d t di St i
7/13/2019 Introduction to Java Fundamentals
43/98
43TCS Confidential
Understanding Strings
String: String is not a simple data type likean array of characters but a complete
object on its own.Arrays of String can also be declared.
Example: class FirstString {public static void main (String args[ ] ) {
String str = My first string in Java;
System.out.println(str); }}
7/13/2019 Introduction to Java Fundamentals
44/98
44TCS Confidential
Operators in Java (Self Reading)
Type Description Symbol Usage
Arithmetic
Addition
subtractionmultiplication
division
modulusincrement
decrement
assignment
+
-
*
/
%
++
+= -= /=*= %=
int no = 3 + 2
int no = 3 - 2
int no = 3 * 2
int no = 3 / 2
int no = 3 % 2no++ or ++no
no += 4; same asno = no + 4; etc.
-- no-- or --no
O t i J (S lf R di )
7/13/2019 Introduction to Java Fundamentals
45/98
45TCS Confidential
Operators in Java ... (Self Reading)
Type Description Symbol Usage
bitwise
NOTa = 2Binary Rep: 10~a = 01 // Decimal 1
AND
~
&b = 3Binary Rep: 11a & b = 10 // Dec. 2
OR | a | b = 11 // Dec. 3Exclusive-OR ^ a ^ b = 01 // Dec. 1
Shift left / right >
byte a = 64, b;
b= (byte)(a 2; // 8int d = -8 >> 1; //-4
O t i J (S lf R di )
7/13/2019 Introduction to Java Fundamentals
46/98
46TCS Confidential
Operators in Java ... (Self Reading)
Type Description Symbol
Relational
Equal toNot equal toGreater than
Less thanGreater than or equal to
Less than or equal to
==!=>
=>= 1; c >Always shifts zerointo high order bits
Operators in Java (Self Reading)
7/13/2019 Introduction to Java Fundamentals
47/98
47TCS Confidential
Operators in Java ... (Self Reading)
The ? Operator
A special ternary operator that can replace
certain types of if-then-else statements:ratio = denom == 0 ? 0 : num / denom;
Difference between & and &&, | and ||
& and | are the logical AND and OR.
&& and || are the Short-circuit AND and OR.
Precedence of the Java Operators (Self
7/13/2019 Introduction to Java Fundamentals
48/98
48TCS Confidential
Precedence of the Java Operators (Self
Reading)( ) [ ]++ -- ~ !* / %+ ->> >>> >= <
7/13/2019 Introduction to Java Fundamentals
49/98
49TCS Confidential
Control Statements
A program does not always follow a simple
sequence. There are always chances of
having to choose from several alternativesor to repeat a certain set of steps. That is
where the various programming constructsthat a programming language provides
come to aid.
If Statement
7/13/2019 Introduction to Java Fundamentals
50/98
50TCS Confidential
If Statement
The if-elsestatements can be nested as shown below. It isnormally used when more than one condition needs to betested.
if (score > 100) { // Nested-if
if (score > 250)
System.out.println( Excellent score );
else system.out.println( Good score );} else system.out.println( Bad score ); if (score >250) // if-else-ifLadder
System.out.println(Excellent Score);
else if (score > 100)
System.out.println( Good Score );
else System.out.println(Bad Score);
Selection Constructs
7/13/2019 Introduction to Java Fundamentals
51/98
51TCS Confidential
Selection Constructs
Selection Statements:
if , if-else, and if-else-if
switch-case
if Statement
if(score > 100 ) {
System.out.println( Good Score );}
else{
System.out.println( Bad Score );}
switch Statement
7/13/2019 Introduction to Java Fundamentals
52/98
52TCS Confidential
switch Statement
Switch statement are used to reduce thecomplexity and compound conditions in if-else statements
A switch statement can be nested intoanother switch statement .
Switch statement defines its own blocks.Hence no conflicts arise betweenconstants in the inner blocks and those inthe outer blocks.
switch Statement
7/13/2019 Introduction to Java Fundamentals
53/98
53TCS Confidential
switch Statement
switch (score) {case 300:
System.out.println(Excellent Score);break;
case 200:
System.out.println(Good Score); break;
default: System.out.println(Bad Score);
}If there is no break statement after each
case then all cases are executed
Iteration Constructs
7/13/2019 Introduction to Java Fundamentals
54/98
54TCS Confidential
Iteration Constructs
Javas iteration statements are while, do-whileand for.
whileStatement
i = 0; found = false;
while (found == false && i < length)
{// where i is the array index
if (Array[i] == str) found = true;
i++;
}
Iteration Constructs ...
7/13/2019 Introduction to Java Fundamentals
55/98
55TCS Confidential
Iteration Constructs ...
do-whileStatementi=0; found = false;
do {
if (Array[i] == str) found = true;
i++;
} while (found == false && i < length);forStatement
// Execution over a range of integer values
for(i = 0 ; i < length ; i++){if (Array[i] == str) break;} // break to exit a loop
Summary
7/13/2019 Introduction to Java Fundamentals
56/98
56TCS Confidential
y
We discussed the following in this session:
Genesis of Java
Java Buzzwords
Java API and JVM
Basics in Java
Data Types, Variables, Literals, Arrays
Operators
Assignments (Mandatory to submit)
7/13/2019 Introduction to Java Fundamentals
57/98
57TCS Confidential
g ( y )
Exercise 1:
Write a Java program that initializes two arrays
with the following products and their prices, and a
method that will display the same.
Chips 10 Hangers 75
Apples 10 Pens 10Mangoes 12 Corn Flakes 19
Towels 125 Oats 22
Room Freshner 150 Tooth Paste 50
Assignments (Mandatory to submit)
7/13/2019 Introduction to Java Fundamentals
58/98
58TCS Confidential
g ( y )
Exercise 2:Write a program for the problem: An array of integersindicating the marks of students is given, You have
to calculate the percentile of the students accordingto the rule: The percentile of a student is the %of noof students having marks less then him.
For example: Suppose Student A,B,C,D,E,F secure12,60,80,71,30,45 respectively
Percentile of C = 5/5 *100 = 100 (out of 5 students 5 are havingmarks less then him)
7/13/2019 Introduction to Java Fundamentals
59/98
59TCS Confidential
Object-Oriented Programming in Java
Object-Oriented Programming in Java
7/13/2019 Introduction to Java Fundamentals
60/98
60TCS Confidential
j g g
The Three OOP Principles
Classes, Objects
Methods with ParametersConstructors
The Keywords: static, finalfinalize( ) Method
Overloading and Overriding Methods
The Three OOP Principles
7/13/2019 Introduction to Java Fundamentals
61/98
61TCS Confidential
p
EncapsulationIs the mechanism that binds together code and
data it manipulates, and keeps both safe fromthe outside interference and misuse
Inheritance
Is the process by which one object acquires theproperties of another object
PolymorphismIs a feature that allows one interface to be usedfor a general class of actions
Bank Module
7/13/2019 Introduction to Java Fundamentals
62/98
62TCS Confidential
Bank Module
Definition: Create a Bank applicationwhich supports all elementary functions
like deposit, withdraw, checking balance,interest calculation, transaction details
etc
Bank Module
7/13/2019 Introduction to Java Fundamentals
63/98
63TCS Confidential
Bank Module
Bank
Customers Accounts
Savings Account Current Account
Step_1 Identifying Physical Entities
7/13/2019 Introduction to Java Fundamentals
64/98
64TCS Confidential
Each Physical entity contains attributesthat defines its state at any point of time.
Identify the Physical Entities:
BankCustomer
Account (Savings / Current)
Step_2 : Defining Attributes
7/13/2019 Introduction to Java Fundamentals
65/98
65TCS Confidential
Account Entity:
Account ID
Account Type
Account Balance
Customer Entity:Customer ID
Customer NameCustomer Address
Bank Entity:Bank ID
Bank NameBranch Name
Address
Encapsulation
7/13/2019 Introduction to Java Fundamentals
66/98
66TCS Confidential
p
Data Encapsulation
Data Items
Methods
Car
What are Classes?
7/13/2019 Introduction to Java Fundamentals
67/98
67TCS Confidential
Classes are templates on which objectsmodel themselves. They contain data-itemsand the methods that are needed tomanipulate the former.
Classes are blue-prints that define the
variables and the methods common to allobjects of a certain type.
Class variables define the attributes of aclass and are called fields.Instancevariables define the attributes of an object.
What are Objects?
7/13/2019 Introduction to Java Fundamentals
68/98
68TCS Confidential
Objects are instance of classes.
Step_3 of Building the Account Class
(Encapsulation)
7/13/2019 Introduction to Java Fundamentals
69/98
69TCS Confidential
( p )
public class Account{
private int accountId,balance,custId;
Account (int accountId,int custId,int balance){
this.accountId = accountId;
this.custId = custId;
this.balance = balance;
}publicvoid printAccountDetails()
{ .} continue in next slide.
Step_3 of Building the Account Class
(Encapsulation)
7/13/2019 Introduction to Java Fundamentals
70/98
70TCS Confidential
public boolean isAccountActive()
{.}
public int depositAmount (int depAmount){.}
public int withdrawAmount (int debitAmount)
{.}
public int getMinBalanceReq()
{}
}
(Encapsulation)
Inheritance
7/13/2019 Introduction to Java Fundamentals
71/98
71TCS Confidential
A class once defined can be used by otherclasses whenever required. It does not need
to be redefined again and again.The derived class automatically inherits the
members of the parent class and adds to
them new methods and data members thus
increasing the functionality of the parent
class.
SuperClass SubClass
Inherits From Super
Step_4 of Building the SavingsAccount Class
(Inheritance)
7/13/2019 Introduction to Java Fundamentals
72/98
72TCS Confidential
class SavingsAccountextendsAccount
{
private String accType = SA;
SavingsAccount (int accountId, int custId, int balance)
{super(accountId, custId, balance) ;
}
continue in next slide.
Step_4 of Building the SavingsAccount Class
(Inheritance)
7/13/2019 Introduction to Java Fundamentals
73/98
73TCS Confidential
public int getMinBalanceReq()
{return 2000;
}}
(Inheritance)
Step_5 of Building the SavingsAccount Class
(Polymorphism)
7/13/2019 Introduction to Java Fundamentals
74/98
74TCS Confidential
class SavingsAccount extends Account
{
private String accType = SA;
SavingsAccount (int accountId, int custId, int balance)
{super(accountId, custId, balance) ;
}
continue in next slide.
Step_5 of Building the SavingsAccount Class
(Polymorphism)
7/13/2019 Introduction to Java Fundamentals
75/98
75TCS Confidential
public int getMinBalanceReq()
{..}
/*By default 30 days duration*/
public void getTransactionData()
{ .}
/*Duration will be passed in parameter*/
public void getTransactionData(int duration)
{ .}
}
(Polymorphism)
Creating Objects
7/13/2019 Introduction to Java Fundamentals
76/98
76TCS Confidential
Memory needs to be allocated for the object so thata reference can be returned to it and stored in thevariable sAcc in this case.
The new operator is used to dynamically allocatememory to the object
SavingsAccount sAcc;sAcc = new SavingsAccount (1,1,2500);
An alternate way is :
SavingsAccount sAcc = new SavingsAccount (1,1,2500 );
Methods With Parameters
7/13/2019 Introduction to Java Fundamentals
77/98
77TCS Confidential
Methods are capable of acceptingparameters that can be passed in the
following ways:By value: Normally all parameters (except
Objects) are passed by value onlyBy reference: When an object is passed
as a parameter, it is passed as a referenceto the method. In reality, the reference to
the object is passed by value.
public class TestArguments
{Example Of Pass By
7/13/2019 Introduction to Java Fundamentals
78/98
78TCS Confidential
{
class BalanceDetail {
int balance;
BalanceDetail(int bal) { ..}void printData() { }
}
public void passByValue(int bal){..... }
public void PassByReference(BalanceDetail balObj ){. } continue in next slide.
Value and
Pass By Reference
public static void main(String[] args)
7/13/2019 Introduction to Java Fundamentals
79/98
79TCS Confidential
{TestArguments Obj1 = new TestArguments();
BalanceDetail balObj = new BalanceDetail();Obj1.passByValue(10);
Obj1.PassByValue(10);Obj1.PassByReference(balObj);
}}
Constructors
7/13/2019 Introduction to Java Fundamentals
80/98
80TCS Confidential
Constructors initializes the values of objectat the time of creation.
A constructors is a special public methodwith no return type (not even void), with orwithout parameters, and with the samename as the class.
If a constructor is not explicitly defined in a
class, Java automatically defines a defaultconstructor
A Parameterized Constructor
7/13/2019 Introduction to Java Fundamentals
81/98
81TCS Confidential
class SavingsAccount extends Account{
private String accType = SA;
SavingsAccount (int accountId, int custId,
Int Balance)
{
super(accountId, custId, balance) ;
}
continue in next slide..
A Parameterized Constructor
7/13/2019 Introduction to Java Fundamentals
82/98
82TCS Confidential
public float interest(int time,int rateOfInt)
{return balance*time*rateOfInt*0.01;
}}
static methods and variables
7/13/2019 Introduction to Java Fundamentals
83/98
83TCS Confidential
At times one wants to define a class memberthat will be used independently of any object of
that class. A static method can be used by itselfwith the following restrictions:A static method can call only other static methods
They may access only static data
They cannot refer to the keywords this or superin any way
Variables declared as static do not occupymemory on a per-instance basis
final Keyword
7/13/2019 Introduction to Java Fundamentals
84/98
84TCS Confidential
A final variable is essentially a constant:final int File_Open = 2;
Value of a final variable cannot be modifiedafter its initialization
The finalize( ) Method
7/13/2019 Introduction to Java Fundamentals
85/98
85TCS Confidential
Sometimes an object will need to performsome action when it is destroyed.
Using the finalize( ) method, specificactions can be defined that can occur justbefore an object is reclaimed by the
garbage collector.protected void finalize( )
{ // finalize code here}
Overloading Methods
7/13/2019 Introduction to Java Fundamentals
86/98
86TCS Confidential
A set of methods, having the same namebut different set of parameters can be
defined in the same class.To external methods and data members it
would serve as one interface.
This phenomenon is termed as method
overloading.
Demo of OverLoading.javaclass OverLoading { // Overloading Methods
7/13/2019 Introduction to Java Fundamentals
87/98
87TCS Confidential
static void add( ){
System.out.println(No parameters passed");}
static void add( double pnum){System.out.println(Parameter = + pnum);}
static void add(int pnum1, int pnum2){ int result;
result = pnum1 + pnum2;
System.out.println(Integer sum = + result);}
static void add(float pnum1, float pnum2) {float result; result = pnum1 + pnum2;
System.out.println(Float sum = + result); }
OverLoading.java ...public static void main(String args[ ]) {
dd( ) // t
7/13/2019 Introduction to Java Fundamentals
88/98
88TCS Confidential
add( ); // no parameter.
add(20, 45); // 2 integerparameters.
add(30.5f, 40.5f); // 2 float parameters.add(45); // integer parameter is
} // elevated to type double.
}Output
No parameters passedInteger sum = 65Float sum = 71.0 Parameter = 45.0
In essence, method overloading is compile-time
polymorphism.
Method Overriding
I l hi h h th d i
7/13/2019 Introduction to Java Fundamentals
89/98
89TCS Confidential
In a class hierarchy, when a method in asubclass has the same name and
signature as a method in its superclass,then the method in the subclass is said tooverride the method in the superclass.
class SavingsAccount extends Account
Method Overriding ...
7/13/2019 Introduction to Java Fundamentals
90/98
90TCS Confidential
{
private String accType = SA;
SavingsAccount (int accountId, int custId, int balance)
{
super(accountId, custId, balance) ;
}
public int getMinBalanceReq() { return 2000; }
continue in next slide..
Method Overriding ...
bli i t ithd A t (i t d bitA t)
7/13/2019 Introduction to Java Fundamentals
91/98
91TCS Confidential
public int withdrawAmount (int debitAmount)//Method overridden by Child Class
//This method is already defined in parent class
{
if( (balance debitAmount) > getMinBalanceReq() )
balance = balance debitAmount;else
System.out.println(Minimum Balance Of +
getMinBalanceReq() + is required);} continue in next slide
Method Overriding ...
7/13/2019 Introduction to Java Fundamentals
92/98
92TCS Confidential
public void getTransactionData(int
duration) /*Duration will be passed inparameter*/
{ .}}
Assignments
Exercise 3:
7/13/2019 Introduction to Java Fundamentals
93/98
93TCS Confidential
Exercise 3:
[Aim: Using Command-line arguments & Input from
keyboard]
Write a JAVA program to generate n prime numbers
greater than a given value. Read n from the keyboard
and supply the threshold values as command-linearguments.
Assignments Exercise 4:
7/13/2019 Introduction to Java Fundamentals
94/98
94TCS Confidential
Define a class called Complex containing two class
variables real and imag of type double. Define
methods, readC() and displayC() for reading acomplex number from keyboard and displaying it on
screen.
Also define methods for arithmetic operations,
addC(), subC(), mulC(), and divC() (add, subtract,
multiply, divide). Write a program to read twocomplex numbers. Display the result of each
arithmetic operation on the two numbers
Instructions For Assignments
The given assignments are mandatory to
7/13/2019 Introduction to Java Fundamentals
95/98
95TCS Confidential
The given assignments are mandatory tosubmit
We request all college co-ordinators to ensurethat assignments from the college aresubmitted in a single .zip file by Wednesday,11/10/2006
Instructions For Assignments
Folder Structure in zip file:
7/13/2019 Introduction to Java Fundamentals
96/98
96TCS Confidential
Folder Structure in .zip file:College Name - Branch Name -
Students Roll No. - Programs
Email your assignments at suryodaya@tcs.com
with subject line as:Assignments: (Java) Session Date (dd/mm/yyyy).
Whats Next???
7/13/2019 Introduction to Java Fundamentals
97/98
97TCS Confidential
Object Oriented Programming II
Java Database Connectivity (JDBC)
7/13/2019 Introduction to Java Fundamentals
98/98
98TCS Confidential
Question & Answers
Recommended