OBJECT ORIENTED PROGRAMMING WITH JAVA
Concept of Java Programming
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Additional resources
 Books
The Complete 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
Concept of Java Programming
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.
Why Java is named 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.
The Java programming is claimed as
Java !
Java
Simple
Secure
Portable
High
Performance
Multithreaded
Interpreted
Platform
Independent
Dynamic
Architecture
Neutral
Object-
Oriented
Robust
Current popularity
Language Score
Java has
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.
How is Java Unique?
Von Neumann architecture of computing
Programming languages
DEBASIS SAMANTA
CSE
IIT KHARAGPUR
Program
11010111
10100101
ADD X Y
MOV Z A
…
#include<…>
main(){
printf(“…”)
}
Assembler
Interpreter
Compiler
Machine Level Assembly Level High Level
Third generation programming languages
• 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.
High-level Programming Principles
Function-oriented programming
Object-oriented programming
FOP versus OOP
Function Oriented 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 Paradigm
Java programming paradigms
Java is 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
Encapsulation in Java
Encapsulation in Java is a process of wrapping
code and data together into a single unit, for
example, a capsule which is mixed of several
medicines.
Encapsulation: Example
Book Borrower
Title
Author
Accession No.
Cost
Borrower DOI
Issue()
Fine()
Return()
Open()
Close()
data
methods
Name
Roll No.
Address
Marks
Books[]
Search Books()
Request()
Renew()
Enroll()
Exit()
data
methods
Encapsulation: Example
Books Borrowers
Inheritance in Java
Inheritance in 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).
Inheritance: Example
Title
Author
Accession No.
Cost
Borrower DOI
Issue()
Fine()
Return()
Open()
Close()
Book
Text
Reference
DOP
Version
Department
Add()
Remove()
Publisher
Rack No.
Permission
Copy Type
Display()
Close()
Open()
Copy()
Information hiding
Public
Title
Author
Protected
Account No.
Private
Cost
Public
Issues()
Returns()
Protected
Resave()
Private
Open()
Close()
Book
Polymorphism
Image Document
print()
In object-oriented programming,
polymorphism refers to a
programming language's ability to
process objects depending on their
class.
Polymorphism: Example
Add(x, y) : 12 +34
Add(s1 + s2) : Debasis + Samanta
Add(Img, Doc) : Image + Document
Add(Doc1, Doc2) : Document1 + Document2
Add two numbers
Merge two strings
Paste an Image to a document
Merge two documents
x, y;
s1, s2;
Img,Doc,Doc1,Doc2
Add(x, y)
Add(s1, s2)
Add(Img, Doc)
Add(Doc1, Doc2)
print()
Java Programming Features
Features of Java programming
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
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?
OBJECT ORIENTED PROGRAMMING WITH JAVA
Java Programming Steps
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Your First Java Program
Program in C and 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
C versus Java
Aspects C 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
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 editing
Java program editing
Java program editing
Java program editing
Java program compilation
The Java 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 compilation
Java program compilation
Java program execution
To execute the Java program, type the command java (from the
command prompt).
– For example, the current program HelloWorldApp.class can be
executed as
java HelloWorldApp
Java program execution
Java program execution
C/C++ versus Java execution
C
JAVA
C++ versus Java
C++ versus Java
Areas of 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.
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) × √
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
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?
OBJECT ORIENTED PROGRAMMING WITH JAVA
Java Tools and Resources
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Java Programming Tools
Tools available for Java 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
Tools available for Java 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
Tools available for Java 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
Resource for Java programming
• 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/
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.
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)
Other third part tools 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)
Other third part tools 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)
Few more from Java 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.
Java Language Subset
A rich subset of the Java language
Built-in data types in 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.
The Java character set
•The Java language alphabet
•Uppercase letters ‘A’ to ‘Z’
•Lowercase letters ‘a’ to ‘z’
•Digits ‘0’ to ‘9’
•Java special characters:
, < > . _
( ) ; $ :
% [ ] # ?
' & { } "
^ ! * / |
-  ~ +
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!
Datatype declaration rule
Declaration and assignment statements
int a, b = 0;
a = 123;
b = 45;
int c = a + b;
System.out.print(“The sum is” + c);
Array in Java
Following are the three 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
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 ];
Define and allocate memory together
<type> <arrayName> [ ] = new <type> [<size>];
Example:
int x [ ] = new int [100];
Creating an array
Initialization of Array
<arrayName> [<subscript> ] = <value>;
Example:
x [5] = 100;
for (int i = 0; i < 100; i++)
x[i] = <value>;
Storing elements in array
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!
• Insertion
• Insertion at 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
• Declaration of an 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
Declare and Allocate
Example:
int myArray [ ] [ ];
myArray = new int [3] [4];
OR
int myArray [ ] [ ] = new int [3] [4];
Creating a 2D array
Initializing a 2D array : 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
 Creating a variable-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];
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();
}
}
}
Example program using an 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);
}
}
Questions to think…
• How to write recursive programs in Java?
• Which program? Application or applet?
Chapter1 Object Oriented Programming And Java.pdf

Chapter1 Object Oriented Programming And Java.pdf

  • 1.
    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
  • 3.
    Concept of JavaProgramming
  • 4.
    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.
  • 8.
    How is JavaUnique?
  • 9.
  • 10.
    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.
  • 12.
  • 13.
  • 14.
  • 15.
    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.
  • 16.
  • 17.
    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.
  • 19.
    Encapsulation: Example Book Borrower Title Author AccessionNo. Cost Borrower DOI Issue() Fine() Return() Open() Close() data methods Name Roll No. Address Marks Books[] Search Books() Request() Renew() Enroll() Exit() data methods
  • 20.
  • 21.
    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).
  • 22.
    Inheritance: Example Title Author Accession No. Cost BorrowerDOI Issue() Fine() Return() Open() Close() Book Text Reference DOP Version Department Add() Remove() Publisher Rack No. Permission Copy Type Display() Close() Open() Copy()
  • 23.
  • 24.
    Polymorphism Image Document print() In object-orientedprogramming, polymorphism refers to a programming language's ability to process objects depending on their class.
  • 25.
    Polymorphism: Example Add(x, y): 12 +34 Add(s1 + s2) : Debasis + Samanta Add(Img, Doc) : Image + Document Add(Doc1, Doc2) : Document1 + Document2 Add two numbers Merge two strings Paste an Image to a document Merge two documents x, y; s1, s2; Img,Doc,Doc1,Doc2 Add(x, y) Add(s1, s2) Add(Img, Doc) Add(Doc1, Doc2) print()
  • 26.
  • 27.
    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
  • 31.
  • 32.
    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
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
    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
  • 40.
  • 41.
  • 42.
    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
  • 43.
  • 44.
  • 45.
    C/C++ versus Javaexecution C JAVA
  • 46.
  • 47.
    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
  • 53.
  • 54.
    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.
  • 63.
  • 64.
    A rich subsetof the Java language
  • 65.
    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!
  • 68.
    Datatype declaration rule Declarationand assignment statements int a, b = 0; a = 123; b = 45; int c = a + b; System.out.print(“The sum is” + c);
  • 69.
  • 70.
    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?