0% found this document useful (0 votes)
5 views

Chapter 1

Uploaded by

ankitdb04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chapter 1

Uploaded by

ankitdb04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

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.


Java !
The Java programming is claimed as

Simple Robust

Object-
Portable
Oriented

Secure
Java Architecture
Neutral

High
Dynamic
Performance
Platform
Multithreaded
Independent
Interpreted
Current popularity
Java has Platform
Language Score worldwide Independence
popularity

Java offers
Parallel and
Distributed
backward
development compatibility

Base for Reliability,


Android speed and
mobile Java has consistently been more popular performanc
platform than any other programming language. e
How is Java Unique?
Von Neumann architecture of computing
Programming languages
Program

Machine Level Assembly Level High Level


ADD X Y #include<…>
11010111 main(){
MOV Z A printf(“…”)
10100101
… }

Assembler

Interpreter

Compiler

DEBASIS SAMANTA
CSE
IIT KHARAGPUR
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

Function uses global data for sharing that can be accessed freely from function to function in the
Data Access Object uses local data and can be accessed in a control manner
system.

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

Title Name
data data
Author Roll No.
Accession No. Address
Cost Marks
Borrower DOI Books[]

Issue() Search Books()


Fine() Request()
Book Return() Borrower
Renew()
Open() Enroll()
methods methods
Close() Exit()
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
DOP
Version
Title Department
Author
Accession No. Add()
Cost Text Remove()
Borrower DOI
Publisher
Issue() Rack No.
Fine() Permission
Book Return() Copy Type
Open()
Close() Display()
Close()
Reference Open()
Copy()
Information hiding
Public
Title
Author
Protected
Account No.
Private
Cost

Public
Issues()
Book Returns()
Protected
Resave()
Private
Open()
Close()
Polymorphism

In object-oriented programming,
Image Document
polymorphism refers to a
programming language's ability to
process objects depending on their
class.

print()
Polymorphism: Example

print()
x, y;
s1, s2; Add(x, y) : 12 +34 Add two numbers
Img,Doc,Doc1,Doc2
Add(s1 + s2) : Debasis + Samanta Merge two strings
Add(x, y)
Add(s1, s2) Add(Img, Doc) : Image + Document Paste an Image to a document
Add(Img, Doc)
Add(Doc1, Doc2) Add(Doc1, Doc2) : Document1 + Document2 Merge two documents
Java Programming Features
Features of Java programming
Interfaces Multithreading Java multimedia Java script

I/O Handler JSP

Java Java Java JDBC


Java bean
Core Applet Internet
Distributed
Packages programming

Exception handling Windows toolkit Java swing Networking


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?
Your First Java Program
Program in C and Java

A program in C to display message A program in Java to display message

#include <stdio.h> import java.lang.*;

class HelloWorldApp
int main()
{
{
public static void main(String args[]){
printf("Hello, World!");
System.out.println("Hello, World!");
return 0;
}
}
}

Note: Both the languages are case sensitive


C versus Java
Aspects C Java Aspects C Java
Paradigms Procedural Object-oriented Supported
Inheritance No inheritance (Simple
Platform inheritance)
Dependent Independent
Dependency
Pointers Supported No Pointers
Datatypes : union,
Supported Not supported Code translation Compiled Interpreted
structure
Pre-processor Supported Multi-threading
Not supported Not supported Supported
directives (#include, #define) and Interfaces
Use packages Exception No exception
Header files Supported Supported
(import) Handling handling
Database
Storage class Supported Not supported Not supported Supported
Connectivity
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 √ √
Static √ √
Binding
Dynamic √ √
Single Inheritance √ √
Inheritance
Multiple Inheritance √ ×
Operator overloading √ ×
Template classes √ ×
Global variables √ ×
Header files √ ×
Pointers √ ×
Interface and packages × √
API (Application Programming Interface) × √
C++ versus Java : Programming environments
Java source
code

Java
compiler

Java BYTE
code JVM

C++
Complier Java Java Java
interprter interprter interprter
C++ source C++ object WIN32 Solaris Macintosh
code code

Intel Pentium Sun Solaris Apple Macintosh

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?


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

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.

Type Size Type Size


boolean 1 bit int 32 bits

byte 8 bits long 64 bits

char 16 bits float 32 bits

short 16 bits double 64 bits


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
Array in Java
0 1 2 3 4 n-2 n-1

marks

marks.length = n

An array is a finite, ordered and collection of homogeneous


data elements.

Following are the three tasks to manipulate an array in Java


• Declaration of an array.
• Allocate memory for it.
• Loading the values into array.
Creating an array
Declaration of array Allocate memory for an array
<type> <arrayName>[ ]; <arrayName> = new <type> [<size>];
Example:
Example:
int x[ ];
x = new int [100 ];
<type>[ ] <arrayName>;
Example:
int [ ] x;
Creating an array
Define and allocate memory together
<type> <arrayName> [ ] = new <type> [<size>];

Example:
int x [ ] = new int [100];
Storing elements in 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};

Here, declaration, allocation of memory and array initialization all are at one go!
Processing elements in an array
• 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.
Array in Java: A quick visit
• Declaration of an array • Initialization of an array
Examples Examples
int numbers[ ];
int numbers[] = {5, 4, 2, 1, 3};
float averageScores[ ];
int [ ] rollNo; float marks[] = {2.5, 3.4, 4.5};
float [ ] marks;

What is the size of the array marks?


• Memory allocation for an array
Examples n = marks.length;
numbers = new int [5];
averageScores = new float [20];
rollNo = new int [49];
marks = new float [54];
How to define a two dimensional array?
Creating a 2D array
Declare and Allocate
Example:

int myArray [ ] [ ];
myArray = new int [3] [4];
OR
int myArray [ ] [ ] = new int [3] [4];
Loading a 2D array
Initializing a 2D array : An example
1 2 3

4 5 6

int myArray [2] [3] = {1, 2, 3, 4, 5, 6};

OR
int myArray [ ] [ ] = { {1, 2, 3}, {4, 5, 6} };
Variable sized 2D array
x[0]

x[1]

x[2]

Creating a variable-sized 2D array Another way: Example


<type><2DarrayName>[][] = new <type> [<rowSize>][]; int x [ ] [ ] = new int [3][ ];
for (int i = 0; i < <rowSize>; i++) x[0] = new int [2];
x[1] = new int [4];
<2DarrayName>[i] = new <type> [<colSizei>]; 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?

You might also like