Introduction to Java · Goal of Java: “Write once, run anywhere, anytime, forever!” How?...
Transcript of Introduction to Java · Goal of Java: “Write once, run anywhere, anytime, forever!” How?...
1TCS Confidential
Introduction to Java(Genesis & Basics)
Java Programming
2TCS Confidential
Genesis of Java
What is Java? Java BuzzwordsJava API and JVMData Types in JavaConditional Statements and Constructs
3TCS Confidential
What is Java?Java is a programming language developed by Sun Microsystems in 1991It’s the current “hot” languageIt’s almost entirely object-orientedIt has a vast library of predefined objects and operationsIt is platform (OS/Hardware) independent
4TCS Confidential
Pre-requisite For Java ExecutionJDK 1.3 or above (Java Development Toolkit)Download the JDK version compatible with your operating system (Windows, Unix, Linux etc…) from http://java.sun.comExecute “Setup.exe” File in your JDK kit for installing Java Development/Execution environment in your machine.
5TCS Confidential
Writing a Java Programpublic 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)
6TCS Confidential
How to Compile the Java Program?Type the program using Notepad or DOS editor and save it as “Suryodaya.java”. Java being case sensitive, “Suryodaya” is different from “suryodaya” Now type -c:\jdk1.3>bin> javac Suryodaya.javaSuryodaya.class file is created on successful compilation.
7TCS Confidential
How to Run the Java Program?
Once the class file is created, type the following command at the prompt to run the program:
c:\jdk1.3>bin>java SuryodayaSetting the CLASSPATHThe output is:
c:\jdk1.3>bin>Welcome to Suryodaya!
8TCS Confidential
The Java BuzzwordsSimple Object-orientedPortableSecure Robust Multithreaded (will be discussed in later sessions)Interpreted (will be discussed in later sessions)
9TCS Confidential
Simple
Java’s 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”
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 primitive data types) is an object
11TCS Confidential
PortableGoal of Java: “Write once, run anywhere,
anytime, forever!” How?Java’s Magic: The Bytecode & JVMJava Complier always converts a .java file
(High level language) into a Generic format commonly know as bytecode, .class fileJVM ,specific to OS (Windows, Unix, Linux
etc…) then interprets this .class file and executes the bytecode
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.
13TCS Confidential
Java Program Execution
Java Source Code
Java Bytecode Compiler
JavaBytecodes
Java BytecodeMoved
Bytecode Verifier (Verifies that the byte codes are from Java
compiler or not)
Java ClassLibrary
Java ClassLibrary
Java Virtual MachineJava Virtual MachineJava InterpreterJava Interpreter
Runtime System(Executable Code)Runtime System
(Executable Code)
Operating SystemOperating System
HardwareHardware
Class Loader
Rejected
Exceptions handled Rejected
2
1
3
4
56
7
8
9
Suryodaya.java
Suryodaya.class
14TCS Confidential
Secure
Java was designed to be a safe language. Its powerful security mechanism acts at four different levels of system architecture:
» Security by Complier» Security by Class Loaders» Java Virtual Machine» Using Java API
15TCS Confidential
Robust
Strictly Typed Language (For Ex:)Memory Management (For Ex:)Exceptional handling (For Ex:)
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 { }
17TCS Confidential
Java APIJava API or Application Program Interface contains 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)
18TCS Confidential
Java API
J2SE (Standard Edition): Core Java
J2EE (Enterprise Edition): Advance Java (Servlets, EJBs, JSPs etc…)
J2ME (Micro Edition): PDA / Mobile Applications Libraries etc..
19TCS Confidential
Diagrammatic Representation JAVA Platform
Java API
Java Applications
Java Virtual Machine
Hardware
Java Code
NativeCode
Foundation Classes
Network and I/O Classes
Abstract Window Toolkit (AWT)
20TCS Confidential
Understanding Java Programming Fundamentals
public class Suryodaya {public static void main(String args[])
{if(args.length > 0){
System.out.print(“Welcome ::”);for(int i=0; i<args.length; i++)
System.out.print(args(i));}
}}
21TCS Confidential
Understanding Java Programming Fundamentals
The name of the program can be anything, but should begin with a letter and may contain digits but no blanks.The word public means that the contents of the block are accessible from all other classes.The word static means that the defined method is applied to the class itself rather than to the objects of the class.
22TCS Confidential
Understanding Java Programming Fundamentals
The word void means that the method mainhas 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::”
23TCS Confidential
Understanding Java Programming Fundamentals
The word println is the name of the method that tells the system to position the cursor at the beginning of the next line after the message is printed
24TCS Confidential
Basics in Java (Self Reading)Data Types, Variables, Literals Simple Data Types
Type Conversion and CastingAutomatic Type Promotion
ArraysOperators
Arithmetic, Bitwise, Relational, Boolean, Assignment, ?Operator Precedence and Associativity
Control StatementsSelection and Iteration
25TCS Confidential
Data Types (Self Reading)There are two data types in Java:
PrimitiveReference
Java defines eight primitive types of data: byte, short, int, long, char, float, double,
booleanJava defines 3 reference data typesarrays, classes, Interfaces
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,80864longRangeWidthName
27TCS Confidential
Primitive Data Types (Self Reading)
true or false32boolean
0 to 65,53516charRangeWidthName
28TCS Confidential
Variables (Self Reading)Variables can be defined as memory units into which data is stored. There are two basic parameters used to define a variable:
Identifier or nameType or category
Assigning a value to a variable at the time of declaration is optionalApart from this, variables have a scope which defines their lifetime and visibility.
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 of literals.Literals are constant data values.Examples:
100 98.6 ‘x’ “This is a test” ox98
30TCS Confidential
The Scope and Lifetime of Variables
Two major scopes:Scope by ClassScope by MethodScope by Block
Variables declared inside a scope are not visible (that is, accessible) to the code that is defined outside that scope
31TCS Confidential
Example - Usual Scope and Lifetimeclass Scope{
public static void main(String args[]) {int x; // known to all code within mainx = 10;
if (x ==10) { // start new scopeint y =20; // known only to this block
// x and y both known hereSystem.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); } }
32TCS Confidential
Type Conversion And CastingType conversion is converting one data type to another. Conversion may be:
Automatic (Implicit)Casting (Explicit or Forced)
33TCS Confidential
Automatic Type ConversionAn 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.
When these two conditions are met, a widening conversion takes place (byte to short, int, long).
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;
35TCS Confidential
Casting Incompatible TypesExplicit or forced type conversion.General form: (target-type) valuetarget-type specifies the desired type to convert the specified value toExample:
int a; byte b; b = (byte) a;Usually a narrowing conversion requires type cast.
36TCS Confidential
What are Arrays?An array is defined as a group of like typed variables referred to by a common name.Like variables, it is essential to specify the following for declaring an array:
Data values (int , float)Identifier for the array
Elements of an array cannot be accessed using pointer arithmetic
37TCS Confidential
How to Declare Arrays?Example
float basicSalary[ ]; // Array declarationbasicSalary = new float[10]; // Refers to a float array
// Allocating spacenew operator automatically allocates the array and initializes its elements to zero.
38TCS Confidential
Assigning ValuesNULL 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.
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}};
40TCS Confidential
Example - One-dimensional Arrayclass Average {public static void main(String args[ ]) {double nums[] ={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); }
}
41TCS Confidential
Declaring ArraysIt is not essential in Java to allocate the same number 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
42TCS Confidential
Example - Two-dimensional Arrayclass 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] + “ “);
}}}
}
43TCS Confidential
Understanding StringsString: String is not a simple data type like an 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); }}
44TCS Confidential
Operators in Java (Self Reading)
Type Description Symbol Usage
Arithmetic
Additionsubtractionmultiplicationdivisionmodulusincrementdecrement assignment
+
-*/%++
+= -= /= *= %=
int no = 3 + 2
int no = 3 - 2int no = 3 * 2int no = 3 / 2 int no = 3 % 2no++ or ++no
no += 4; same as no = no + 4; etc.
-- no-- or --no
45TCS Confidential
Operators in Java ... (Self Reading)Type Description Symbol Usage
bitwise
NOTa = 2Binary Rep: 10~a = 01 // Decimal 1
AND
~
&b = 3Binary Rep: 11 a & 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); //0int i = a << 2; // 256int c = 35 >> 2; // 8int d = -8 >> 1; //-4
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
==!=><>=<=
Bitwise Assignments
~= &= |= ^= <<= >>=
int a=1, b=2, c=3; a |= 4; b >>= 1; c <<= 1; a ^= c;(answers: a =3 b=1 c=6)
Unsigned Right Shift >>>Always shifts zero
into high order bits
47TCS Confidential
Operators in Java ... (Self Reading)The ? OperatorA 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.
48TCS Confidential
Precedence of the Java Operators (Self Reading)
( ) [ ]++ -- ~ !* / %+ ->> >>> <<> >= < <=== !=&^|&&||?:= op=
Highest
Lowest
49TCS Confidential
Control StatementsA program does not always follow a simple sequence. There are always chances of having to choose from several alternatives or to repeat a certain set of steps. That is where the various programming constructs that a programming language provides come to aid.
50TCS Confidential
If StatementThe if-else statements can be nested as shown below. It is normally used when more than one condition needs to be tested.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-if LadderSystem.out.println(“Excellent Score”);
else if (score > 100)System.out.println(“Good Score”);
else System.out.println(“Bad Score”);
51TCS Confidential
Selection ConstructsSelection Statements:
if , if-else, and if-else-ifswitch-case
if Statementif (score > 100 ) {
System.out.println(“Good Score”);}else {
System.out.println(“Bad Score”);}
52TCS Confidential
switch StatementSwitch statement are used to reduce the complexity and compound conditions in if-else statementsA switch statement can be nested into another switch statement .Switch statement defines its own blocks. Hence no conflicts arise between constants in the inner blocks and those in the outer blocks.
53TCS Confidential
switch Statementswitch (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
54TCS Confidential
Iteration ConstructsJava’s iteration statements are while, do-whileand for.while Statementi = 0; found = false;while (found == false && i < length) {
// where i is the array indexif (Array[i] == str) found = true; i++;
}
55TCS Confidential
Iteration Constructs ...do-while Statementi=0; found = false;do {
if (Array[i] == str) found = true;i++;
} while (found == false && i < length);for Statement // Execution over a range of integer valuesfor(i = 0 ; i < length ; i++){if (Array[i] == str) break;} // break to exit a loop
56TCS Confidential
Summary
We discussed the following in this session:Genesis of Java
Java BuzzwordsJava API and JVM
Basics in JavaData Types, Variables, Literals, ArraysOperators
57TCS Confidential
Assignments (Mandatory to submit)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 75Apples 10 Pens 10Mangoes 12 Corn Flakes 19Towels 125 Oats 22Room Freshner 150 Tooth Paste 50
58TCS Confidential
Assignments (Mandatory to submit)Exercise 2:Write a program for the problem: An array of integers indicating the marks of students is given, You have to calculate the percentile of the students according to the rule: The percentile of a student is the %of no of students having marks less then him.
For example: Suppose Student A,B,C,D,E,F secure 12,60,80,71,30,45 respectively
Percentile of C = 5/5 *100 = 100 (out of 5 students 5 are having marks less then him)
59TCS Confidential
Object-Oriented Programming in Java
60TCS Confidential
Object-Oriented Programming in Java
The Three OOP PrinciplesClasses, ObjectsMethods with ParametersConstructorsThe Keywords: static, finalfinalize( ) MethodOverloading and Overriding Methods
61TCS Confidential
The Three OOP PrinciplesEncapsulationIs the mechanism that binds together code and data it manipulates, and keeps both safe from the outside interference and misuseInheritanceIs the process by which one object acquires the properties of another objectPolymorphismIs a feature that allows one interface to be used for a general class of actions
62TCS Confidential
Bank Module
Definition: Create a Bank application which supports all elementary functions like deposit, withdraw, checking balance, interest calculation, transaction details etc…
63TCS Confidential
Bank Module
Bank
Customers Accounts
Savings Account Current Account
64TCS Confidential
Step_1 Identifying Physical Entities
Each Physical entity contains attributes that defines its state at any point of time.
Identify the Physical Entities:BankCustomerAccount (Savings / Current)
65TCS Confidential
Step_2 : Defining Attributes
Account Entity:Account IDAccount TypeAccount Balance
Customer Entity:Customer IDCustomer NameCustomer Address
Bank Entity:Bank IDBank NameBranch NameAddress
66TCS Confidential
Encapsulation
Data Encapsulation
Data Items
Methods
Car
67TCS Confidential
What are Classes?Classes are templates on which objects model themselves. They contain data-items and the methods that are needed to manipulate the former. Classes are blue-prints that define the variables and the methods common to all objects of a certain type.Class variables define the attributes of a class and are called fields.Instance variables define the attributes of an object.
68TCS Confidential
What are Objects?
Objects are instance of classes.
69TCS Confidential
Step_3 of Building the Account Class (Encapsulation)
public class Account {
private int accountId,balance,custId;Account (int accountId,int custId,int balance){
this.accountId = accountId;this.custId = custId;this.balance = balance;
}public void printAccountDetails()
{ ….} continue in next slide….
70TCS Confidential
public boolean isAccountActive(){….}
public int depositAmount (int depAmount){….}public int withdrawAmount (int debitAmount){….}public int getMinBalanceReq(){…}
}
Step_3 of Building the Account Class (Encapsulation)
71TCS Confidential
InheritanceA class once defined can be used by other classes 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 SubClassInherits From Super
72TCS Confidential
Step_4 of Building the SavingsAccount Class (Inheritance)
class SavingsAccount extends Account{
private String accType = “SA”;
SavingsAccount (int accountId, int custId, int balance){
super(accountId, custId, balance) ;}
continue in next slide….
73TCS Confidential
public int getMinBalanceReq(){
return 2000;}
}
Step_4 of Building the SavingsAccount Class (Inheritance)
74TCS Confidential
Step_5 of Building the SavingsAccount Class (Polymorphism)
class SavingsAccount extends Account{
private String accType = “SA”;
SavingsAccount (int accountId, int custId, int balance){
super(accountId, custId, balance) ;}
continue in next slide….
75TCS Confidential
public int getMinBalanceReq(){…..}
/*By default 30 days duration*/public void getTransactionData() { ….}
/*Duration will be passed in parameter*/public void getTransactionData(int duration) { ….}
}
Step_5 of Building the SavingsAccount Class (Polymorphism)
76TCS Confidential
Creating ObjectsMemory needs to be allocated for the object so that a reference can be returned to it and stored in the variable sAcc in this case.The new operator is used to dynamically allocate memory to the object
SavingsAccount sAcc;sAcc = new SavingsAccount (1,1,2500);
An alternate way is :SavingsAccount sAcc = new SavingsAccount (1,1,2500 );
77TCS Confidential
Methods With ParametersMethods are capable of accepting parameters 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 reference to the method. In reality, the reference to the object is passed by value.
78TCS Confidential
public class TestArguments {
class BalanceDetail { int balance; BalanceDetail(int bal) { ..} void printData() { …}
} public void passByValue(int bal) {..... }
public void PassByReference(BalanceDetail balObj ){…. } continue in next slide…….
Example Of Pass By
Value and
Pass By Reference
79TCS Confidential
public static void main(String[] args){
TestArguments Obj1 = new TestArguments(); BalanceDetail balObj = new BalanceDetail(); Obj1.passByValue(10); Obj1.PassByValue(10); Obj1.PassByReference(balObj);
}}
80TCS Confidential
Constructors
Constructors initializes the values of object at the time of creation. A constructors is a special public method with no return type (not even void), with or without parameters, and with the same name as the class. If a constructor is not explicitly defined in a class, Java automatically defines a default constructor
81TCS Confidential
A Parameterized Constructorclass SavingsAccount extends Account{private String accType = “SA”;
SavingsAccount (int accountId, int custId, Int Balance)
{super(accountId, custId, balance) ;
}continue in next slide…..
82TCS Confidential
public float interest(int time,int rateOfInt){
return balance*time*rateOfInt*0.01;}
}
A Parameterized Constructor
83TCS Confidential
static methods and variables
At times one wants to define a class member that will be used independently of any object of that class. A static method can be used by itself with the following restrictions:
A static method can call only other static methodsThey may access only static dataThey cannot refer to the keywords this or super in any way
Variables declared as static do not occupy memory on a per-instance basis
84TCS Confidential
final KeywordA final variable is essentially a constant:
final int File_Open = 2;Value of a final variable cannot be modified after its initialization
85TCS Confidential
The finalize( ) MethodSometimes an object will need to perform some action when it is destroyed. Using the finalize( ) method, specific actions can be defined that can occur just before an object is reclaimed by the garbage collector.
protected void finalize( ){ // finalize code here }
86TCS Confidential
Overloading MethodsA set of methods, having the same name but 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.
87TCS Confidential
Demo of OverLoading.javaclass OverLoading { // Overloading Methods
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); }
88TCS Confidential
OverLoading.java ...public static void main(String args[ ]) {
add( ); // no parameter.add(20, 45); // 2 integer parameters.add(30.5f, 40.5f); // 2 float parameters.add(45); // integer parameter is
} // elevated to type double.} OutputNo parameters passed Integer sum = 65 Float sum = 71.0 Parameter = 45.0In essence, method overloading is compile-time polymorphism.
89TCS Confidential
Method OverridingIn a class hierarchy, when a method in a subclass has the same name and signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.
90TCS Confidential
class SavingsAccount extends Account{
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 ...
91TCS Confidential
Method Overriding ...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……
92TCS Confidential
Method Overriding ...
public void getTransactionData(int duration) /*Duration will be passed in parameter*/
{ ….}}
93TCS Confidential
AssignmentsExercise 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-line arguments.
94TCS Confidential
AssignmentsExercise 4:Define a class called “Complex” containing two class variables real and imag of type double. Define methods, readC() and displayC() for reading a complex 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 two complex numbers. Display the result of each arithmetic operation on the two numbers
95TCS Confidential
Instructions For Assignments
The given assignments are mandatory to submit
We request all college co-ordinators to ensure that assignments from the college are submitted in a single .zip file by Wednesday, 11/10/2006
96TCS Confidential
Instructions For Assignments
Folder Structure in .zip file:College Name - Branch Name -Student’s Roll No. - Programs
Email your assignments at [email protected] subject line as:“Assignments: (Java) – Session Date (dd/mm/yyyy).”
97TCS Confidential
What’s Next???
Object Oriented Programming –II Java Database Connectivity (JDBC)
98TCS Confidential
Question & Answers