OBJECT ORIENTED PROGRAMMINGWITH JAVA
Concept of Java Programming
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
2.
Additional resources
Books
TheComplete Reference Java 2 (10th Edition)
Hebert Schildt, Tata Mc Graw Hill
Object-Oriented Programming with C++ and Java
Debasis Samanta, Prentice Hall of India
Website
https://cse.iitkgp.ac.in/~dsamanta/java/index.htm
History of Java
•James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of Sun engineers called Green Team.
• Firstly, it was called "Greentalk" by James Gosling, and file extension was .gt.
• Java was originally designed for small, embedded systems in electronic appliances
like set-top boxes, but it was too advanced technology for the digital cable
television industry at the time.
• After that, it was called Oak and was developed as a part of the Green project. Java
team members initiated this project to develop a language for digital devices.
• Later, Java technology was incorporated by Netscape as it was suited for
networking.
5.
Why Java isnamed Java?
• Java was called Oak as it is a symbol of strength and chosen as a national tree of
many countries like U.S.A., France, Germany, Romania, etc.
• The team wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.
• In 1995, Oak was renamed as Java
• Java is an island of Indonesia where first coffee was produced (called java coffee).
• In 1995, Time magazine called Java one of the Ten Best Products of 1995.
• JDK (Java Development Kit) 1.0 released in January 23, 1996.
6.
The Java programmingis claimed as
Java !
Java
Simple
Secure
Portable
High
Performance
Multithreaded
Interpreted
Platform
Independent
Dynamic
Architecture
Neutral
Object-
Oriented
Robust
7.
Current popularity
Language Score
Javahas
worldwide
popularity
Parallel and
Distributed
development
Base for
Android
mobile
platform
Reliability,
speed and
performanc
e
Java offers
backward
compatibility
Platform
Independence
Java has consistently been more popular
than any other programming language.
Programming languages
DEBASIS SAMANTA
CSE
IITKHARAGPUR
Program
11010111
10100101
ADD X Y
MOV Z A
…
#include<…>
main(){
printf(“…”)
}
Assembler
Interpreter
Compiler
Machine Level Assembly Level High Level
11.
Third generation programminglanguages
• A third generation (programming) language (3GL) is a grouping of programming languages that introduced significant enhancements to second
generation languages, primarily intended to make the programming language more programmer-friendly.
• English words are used to denote variables, programming structures and commands, and Structured Programming is supported by most 3GLs.
• Commonly known 3GLs are FORTRAN, BASIC, Pascal, JAVA and the C-family (C, C+, C++, C#, Objective-C) of languages. Also known as a
high-level programming language.
FOP versus OOP
FunctionOriented Programming (FOP) Object Oriented Programming (OOP)
Program organization Program is divided into small parts called functions. Program is divided into parts called objects.
Importance Importance is not given to data but to functions Importance is given to the data rather than procedures
Approach FOP follows top down approach OOP follows bottom up approach
Access Specifiers Does not have any access specifier Has three access specifiers, namely Public, Private, Protected
Data Moving Data can move freely from function to function in the system Objects can move and communicate with each other
Maintainability To add new data and function is not so easy Provides an easy way to add new data and function
Data Access
Function uses global data for sharing that can be accessed freely from function to function in the
system.
Object uses local data and can be accessed in a control manner
Data Hiding No data hiding is possible, hence security is not possible Provides data hiding, hence secured programming is possible
Overloading Polymorphism is not possible Polymorphism is possible
Examples C, Visual Basic, FORTRAN, Pascal. C++, JAVA, VB.NET, C#.NET.
Java programming paradigms
Javais based on the concept of object-oriented programming. As the name suggests, at
the center of it all is an object. Objects contain both data and the functionality that
operates on that data. This is controlled by the following four paradigms
• Encapsulation
• Inheritance
• Information hiding
• Polymorphism
18.
Encapsulation in Java
Encapsulationin Java is a process of wrapping
code and data together into a single unit, for
example, a capsule which is mixed of several
medicines.
Inheritance in Java
Inheritancein Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object. It is an important
part of OOPs (Object-Oriented Programming system).
Features of Javaprogramming
I/O Handler
Java bean
Packages
Interfaces
Exception handling
Multithreading
Windows toolkit
Java multimedia
Java swing Networking
Java script
JSP
JDBC
Distributed
programming
Java
Core
Java
Applet
Java
Internet
28.
Questions to think…
•Can a software be developed in Java so that it runs in
any OS? Any machine?
• How a browser (e.g., Mozilla, Google Chrome, Safari,
etc.) works in your mobile/ Computer?
30.
OBJECT ORIENTED PROGRAMMINGWITH JAVA
Java Programming Steps
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Program in Cand Java
#include <stdio.h>
int main()
{
printf("Hello, World!");
return 0;
}
import java.lang.*;
class HelloWorldApp
{
public static void main(String args[]){
System.out.println("Hello, World!");
}
}
A program in C to display message A program in Java to display message
Note: Both the languages are case sensitive
33.
C versus Java
AspectsC Java
Paradigms Procedural Object-oriented
Platform
Dependency
Dependent Independent
Datatypes : union,
structure
Supported Not supported
Pre-processor
directives
Supported
(#include, #define)
Not supported
Header files Supported
Use packages
(import)
Storage class Supported Not supported
Aspects C Java
Inheritance No inheritance
Supported
(Simple
inheritance)
Pointers Supported No Pointers
Code translation Compiled Interpreted
Multi-threading
and Interfaces
Not supported Supported
Exception
Handling
No exception
handling
Supported
Database
Connectivity
Not supported Supported
34.
Java program editing
•Any text editor can be used to write Java programs. For example,
– In Windows
• Notepad, Edit, Wordpad, MS-Word, etc.
– In Unix
• vi, emacs, gedit etc.
• Save the program
– Save the program in a file with the name
HelloWorldApp.java
Java program compilation
TheJava compiler ( javac ) converts a Java program into Java byte code
– Open a DOS shell (in Windows) or Terminal (in Unix)
– Move to the directory where your Java program has been saved
– Enter the following command to compile:
javac HelloWorldApp.java
Java program execution
Toexecute the Java program, type the command java (from the
command prompt).
– For example, the current program HelloWorldApp.class can be
executed as
java HelloWorldApp
C++ versus Java
Areasof applications
– C++ is best suitable for developing large software.
• Library management system, Employee management system,
Passenger reservation system, etc.
– Java is best suitable for developing communication/ Internet
application software.
• Network protocols, Internet programs, web page, web browser, etc.
48.
C++ versus Java: Programming features
Features in C++ in Java
Data abstraction and encapsulation √ √
Polymorphism √ √
Binding
Static √ √
Dynamic √ √
Inheritance
Single Inheritance √ √
Multiple Inheritance √ ×
Operator overloading √ ×
Template classes √ ×
Global variables √ ×
Header files √ ×
Pointers √ ×
Interface and packages × √
API (Application Programming Interface) × √
49.
C++ versus Java: Programming environments
C++ source
code
C++
Complier
C++ object
code
Java source
code
Java BYTE
code
Java
compiler
Java
interprter
WIN32
Java
interprter
Solaris
Java
interprter
Macintosh
Intel Pentium Sun Solaris Apple Macintosh
JVM
C++ provides platform dependent programming Java provides platform independent programming
50.
Questions to think…
•How a Java program can include two or more classes and
then compile them?
• How a browser can run a Java program?
52.
OBJECT ORIENTED PROGRAMMINGWITH JAVA
Java Tools and Resources
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Tools available forJava programming
• Java Software Developer’s Kit (SDK) : JavaTM 2 SDK
– SDK from JavaSoft, a division of Sun Microsystems Inc.
– Contains the basic tools and libraries necessary for creating, testing,
documenting and executing Java programs.
• JavaTM 2 SDK, Standard Edition
https://java.sun.com/j2se/1.4.2/docs/index.html
– Official site for JavaTM 2 SDK, Standard Edition
55.
Tools available forJava programming
There are seven main programs in SDK
javac – the Java Compiler
java – the Java Interpreter
javadoc – generates documentation in HTML
appletviewer – the Java Interpreter to execute Java applets
jdb – the Java Debugger to find and fix bugs in Java programs
javap – the Java Disassembler to displays the accessible functions and data
in a compiled class; it also displays the meaning of byte codes
javah – to create interface between Java and C routines
56.
Tools available forJava programming
• Additional few sources
Javatpoint website : Another official site for JavaTM 2 SDK, Standard
Edition, help, tutorial, etc.
https://www.javatpoint.com/java-tutorial
Free Java Download : Download Java for your desktop computer now
https://www.java.com/en/download/index.jsp
57.
Resource for Javaprogramming
• There are many resources for learning Java
The JavaTM2 Tutorials
• The Java tutorials are practical guides for programmers who want to use the Java
programming language to create applications.
https://java.sun.com/docs/books/tutorial/index.html
Sun Developer Network
• Sun Microsystem's official website listing down all the API documentation, latest Java
Technologies, books and other resources.
https://java.sun.com/reference/docs/
58.
Packages in Java
API(Application Programming Interface) in Java SDK
– The API enables Java programmers to develop varieties of applets and
applications
– It contains nine packages
• java.applet – for applet programming
• java.awt – the Abstract Windowing Toolkit for designing GUI like Button, Checkbox,
Choice, Menu, Pannel, etc.
• java.io – file input/output handling
• java.lang – provides useful classes like to handle Object, Thread, Exception, String,
System, Math, Float, Integer, etc.
59.
Packages in Java
•java.lang – provides useful classes like to handle Object, Thread, Exception, String,
System, Math, Float, Integer etc.
• java.net – classes for network programming; supports TCP/IP networking protocols
• java.util – it contains miscellaneous classes like Vector, Stack, List, Date, Dictionary,
Hash etc.
• javax.swing – for designing graphical user interface (GUI)
• java.sql – for database connectivity (JDBC)
60.
Other third parttools for Java programming
Java IDE (Integrated Development Environment)
– Number of IDEs are available to support the productivity of software development
• Sun’s Java Workshop from Sun’s JavaSoft (recently powered with Visual Java)
• Mojo from Penumbra Software (best visual environment for creating Java
applets)
• Jumba from Aimtech and IBM (graphical applet builder)
• Semantic Café from Semantics (a de-facto standard for Java development on
Windows systems)
61.
Other third parttools for Java programming
Web browser
– Java environment requires Java-enabled web browser to supports Java
applets
– Few (free) popular Java-enabled web browsers:
• HotJava from JavaSoft web site (http://java.sun.com)
• Netscape Navigator from Netscape home page (http://home.nescape.com)
• Internet Explorer from Microsoft’s web page (http://www.microsoft.com)
62.
Few more fromJava professionals
Net Beans - https://netbeans.org/downloads/
− This is one of the most commonly used IDEs for Java and some major languages.
NotePad++ - https://notepad-plus-plus.org/download/v7.5.8.html
− This is a very advanced and handy NotePad,
it has several built-in tools and functions for making programming easy.
Built-in data typesin Java
Type Size
boolean 1 bit
byte 8 bits
char 16 bits
short 16 bits
Type Size
int 32 bits
long 64 bits
float 32 bits
double 64 bits
In Java, every variable has a type declared in the source code. There are two
kinds of types: reference types and primitive types. Reference types are
references to objects. Primitive types directly contain values.
66.
The Java characterset
•The Java language alphabet
•Uppercase letters ‘A’ to ‘Z’
•Lowercase letters ‘a’ to ‘z’
•Digits ‘0’ to ‘9’
•Java special characters:
, < > . _
( ) ; $ :
% [ ] # ?
' & { } "
^ ! * / |
- ~ +
67.
Identifiers in Java
•Identifiers
• Names given to various program elements (variables, constants, class, methods,
etc.)
• May consist of letters, digits and the underscore (‘_’) character, with no space
between.
• Blank and comma are not allowed.
• First character must be an alphabet or underscore.
• An identifier can be arbitrary long.
• Identifier should not be a reserved word.
• Java programming language is case sensitive.
• area, AREA and Area are all different!
Following are thethree tasks to manipulate an array in Java
• Declaration of an array.
• Allocate memory for it.
• Loading the values into array.
An array is a finite, ordered and collection of homogeneous
data elements.
0 1 2 3 4 n-1
n-2
marks
marks.length = n
Array in Java
71.
Declaration of array
<type><arrayName>[ ];
Example:
int x[ ];
<type>[ ] <arrayName>;
Example:
int [ ] x;
Creating an array
Allocate memory for an array
<arrayName> = new <type> [<size>];
Example:
x = new int [100 ];
72.
Define and allocatememory together
<type> <arrayName> [ ] = new <type> [<size>];
Example:
int x [ ] = new int [100];
Creating an array
73.
Initialization of Array
<arrayName>[<subscript> ] = <value>;
Example:
x [5] = 100;
for (int i = 0; i < 100; i++)
x[i] = <value>;
Storing elements in array
74.
Initialization of array:An alternative way
<type> <arrayName> [ ] = { <list of values> };
Example:
int x [ ] = {12, 3, 9, 15};
Storing elements in array
Here, declaration, allocation of memory and array initialization all are at one go!
75.
• Insertion
• Insertionat any location
• Insertion at front
• Insertion at end
• Insertion is sorted order
• Deletion
• Deletion a particular element
• Deletion an element at a particular location
• Deletion the element at front
• Deletion the element at end
• Searching and Traversal
• Finding the smallest and largest element
• Printing all element or some specific element
• Sorting
• In ascending order, descending order, lexicographical order etc.
Processing elements in an array
76.
• Declaration ofan array
Examples
int numbers[ ];
float averageScores[ ];
int [ ] rollNo;
float [ ] marks;
• Memory allocation for an array
Examples
numbers = new int [5];
averageScores = new float [20];
rollNo = new int [49];
marks = new float [54];
• Initialization of an array
Examples
int numbers[] = {5, 4, 2, 1, 3};
float marks[] = {2.5, 3.4, 4.5};
What is the size of the array marks?
n = marks.length;
How to define a two dimensional array?
Array in Java: A quick visit
77.
Declare and Allocate
Example:
intmyArray [ ] [ ];
myArray = new int [3] [4];
OR
int myArray [ ] [ ] = new int [3] [4];
Creating a 2D array
78.
Initializing a 2Darray : An example
int myArray [2] [3] = {1, 2, 3, 4, 5, 6};
OR
int myArray [ ] [ ] = { {1, 2, 3}, {4, 5, 6} };
1
6
5
4
3
2
Loading a 2D array
79.
Creating avariable-sized 2D array
<type><2DarrayName>[][] = new <type> [<rowSize>][];
for (int i = 0; i < <rowSize>; i++)
<2DarrayName>[i] = new <type> [<colSizei>];
x[0]
x[1]
x[2]
Variable sized 2D array
Another way: Example
int x [ ] [ ] = new int [3][ ];
x[0] = new int [2];
x[1] = new int [4];
x[2] = new int [3];
80.
3D arrays :An example
class a3DArray {
public static void main(String args[]) {
int my3DArray [ ][ ][ ] = new int [3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
my3DArray[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(my3DArray[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
81.
Example program usingan array
class TestArray{
public static void main(String args[]){
int a[] = new int[5]; //Declaration and instantiation
a = {10, 20, 30, 40, 50}; //Initialization
//Traversing array
for(int i=0;i<a.length;i++){ //length is the property of array
System.out.println(a[i]);
}
// Average calculation
float sum = 0; avg;
for(i=0;i<a.length;i++) //Calculating the sum of the numbers
sum += a[i];
avg = sum/a.length;
System.out.println(“Avergae = “ + avg);
}
}
82.
Questions to think…
•How to write recursive programs in Java?
• Which program? Application or applet?