0% found this document useful (0 votes)
1 views67 pages

1.1 Java Unit1 Introduction

The document provides an overview of Object-Oriented Programming (OOP) with Java, detailing its history, features, and applications. It explains key concepts such as encapsulation, inheritance, polymorphism, and the advantages of OOP over procedural programming. Additionally, it outlines the Java programming environment, including tools and packages available for developers.

Uploaded by

Mridula Verma
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)
1 views67 pages

1.1 Java Unit1 Introduction

The document provides an overview of Object-Oriented Programming (OOP) with Java, detailing its history, features, and applications. It explains key concepts such as encapsulation, inheritance, polymorphism, and the advantages of OOP over procedural programming. Additionally, it outlines the Java programming environment, including tools and packages available for developers.

Uploaded by

Mridula Verma
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/ 67

Object Oriented Programming with Java

(BCS403)

by
Dr. Surendra Kr. Keshari
Associate Professor
KIET Group of Institutions
1
Introduction to JAVA
• Java is a programming language and a platform.
• Platform: Any hardware or software environment in which a program
runs, is known as a platform. Since Java has its own runtime environment
(JRE) and API, it is called platform.
• Java is a high level, robust, secured and object-oriented programming
language.
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 Version History
• There are many java versions that has been released. Current stable release of
• JDK Alpha and Beta (1995)
• JDK 1.0 (23rd Jan, 1996)
• JDK 1.1 (19th Feb, 1997)
• J2SE 1.2 (8th Dec, 1998)
• J2SE 1.3 (8th May, 2000)
• J2SE 1.4 (6th Feb, 2002)
• J2SE 5.0 (30th Sep, 2004)
• Java SE 6 (11th Dec, 2006)
• Java SE 7 (28th July, 2011)
• Java SE 8 (18th March, 2014)
• https://www.javatpoint.com/history-of-java
Where it is used?

• Desktop Applications such as acrobat reader, media player, antivirus


etc.
• Web Applications such as irctc.co.in, javatpoint.com etc.
• Enterprise Applications such as banking applications.
• Mobile
• Embedded System
• Smart Card
• Robotics
• Games etc.
Java !
The Java programming is claimed as

Simple Robust

Object-
Portable
Oriented

Secure
Java Architecture
Neutral

High
Dynamic
Performance
Platform
Multithreaded
Independent
Interpreted
Java Language Features
1) simple
2) object-oriented
3) robust
4) multithreaded
5) architecture-neutral
6) interpreted and high-performance
7) distributed
8) dynamic
9) secure
Java Language Features 1
1) simple – Java is designed to be easy for the professional programmer to
learn and use.
2) object-oriented – a clean, usable, pragmatic approach to objects, not
restricted by the need for compatibility with other languages.
3) robust – restricts the programmer to find the mistakes early, performs
compile-time (strong typing) and run-time (exception-handling) checks,
manages memory automatically.
Java Language Features 2
4) multithreaded – supports multi-threaded programming for writing
program that perform concurrent computations
5) architecture-neutral – Java Virtual Machine provides a platform-
independent environment for the execution of Java bytecode
6) interpreted and high-performance – Java programs are compiled into an
intermediate representation – bytecode:
a) can be later interpreted by any JVM
b) can be also translated into the native machine code for efficiency.
Java Language Features 3
7) distributed – Java handles TCP/IP protocols, accessing a resource
through its URL much like accessing a local file.
8) dynamic – substantial amounts of run-time type information to verify and
resolve access to objects at run-time.
9) secure – programs are confined to the Java execution environment and
cannot access other parts of the computer.
Garbage collection
➢Garbage collection is the mechanism that De allocate the memory of
an object when it is no longer referenced by a variable.
➢In c++, the memory of an object is released by use of delete
operator.
➢Java virtual machine determines when to free up the memory of an
object.
Programming languages
Program

Machine Level Assembly Level High Level


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

Assembler

Interpreter

Compiler
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.
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
Data Access Object uses local data and can be accessed in a control manner
the 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.


Object means a real word entity such as pen, chair,
table etc.
Object-Oriented Programming is a methodology or
paradigm to design a program using classes and
objects. It simplifies the software development and
maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Advantage of OOPs over Procedure-oriented
programming language
• OOPs makes development and maintenance easier where as in
Procedure-oriented programming language it is not easy to manage if
code grows as project size grows.
• OOPs provides data hiding whereas in Procedure-oriented
prgramming language a global data can be accessed from anywhere.
• OOPs provides ability to simulate real-world event much more
effectively. We can provide the solution of real word problem if we
are using the Object-Oriented Programming language.
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 Address
No. Marks
Cost Books[]
Borrower
Issue()
DOI 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 Add() Remove()
No. Text
Cost
Borrower Publisher
DOI Rack No.
Permission
Book Issue() Copy Type
Fine()
Return() Display()
Open() Close()
Close() Reference Open()
Copy()
Information hiding
Public
Title Author
Protected
Account No.
Private
Cost

Public
Issues() Returns()
Protected
Book 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) Add(Img, Doc) : Image + Document Paste an Image to a document
Add(Doc1, Doc2)
Add(Doc1, Doc2) : Document1 + Document2 Merge two documents
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


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
C/C++ versus Java exec ution
C

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
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
Packages in Java
API (Application Programming Interface) in Java SDK
–The API enables Java programmers to develop varieties of applets and
applications
–It contains following 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)


Java Program Explained
MyProgram is the name of the class:

class MyProgram {

main is the method with one parameter args and no results:

public static void main(String[] args) {

println is a method in the standard System class:

System.out.println(“First Java program.");


}
}
Classes and Objects
A class is the basic building block of Java programs.
A class encapsulates:
a)data (attributes) and
b)operations on this data (methods)
and permits to create objects as its instances.
Main Method
The main method must be present in every Java application:
1)public static void main(String[] args) where:
a) public means that the method can be called by any object
b) static means that the method is shared by all instances
c) void means that the method does not return any value
2)When the interpreter executes an application, it starts by calling its main
method which in turn invokes other methods in this or other classes.
3)The main method accepts a single argument – a string array, which holds
all command-line parameters.
Let us consider a simple program to find the square root of an
integer.

import java.lang.*; //Math class is defined in this package

class Calculator{ double i;


double x = Math.sqrt(i);
}

class Example{
public static void main(String args[]){ Calculator a = new Calculator();
a.i = 20;
System.out.println("Square root of "+a.i+" is "+a.x);
}
}
Let us examine each statement step-by-step.
Import
import java.lang.*;
Statements
class Calculator{ double i;
double x = Math.sqrt(i);
Declaration }
of class class Example{
public static void main(String args[]){ Calculator a = new
Calculator();
a.i = 20;
System.out.println("Square root of "+a.i+" is "+a.x);
Declaration of }
main class }
➢ Java program starts its execution from a method belongs to a class
only.

➢ The main() method is the starting point of the execution of the main thread.

➢ If there are multiple classes, then ambiguity is resolved by incorporating a


main() method into only one special class called main class.

➢ The name of the Java program should be named after this class so that Java
interpreter unanimously choose that class to start its execution.
Java main() method
➢ It is an access specifier, which allows the programmer to control the visibility of class members.
➢ public member may be accessed by code outside the class in which it is declared.

• main() must be declared as public, since it must be called by


code outside of its class when the program is started.
Java main() method
Note: By default a member is public.
Other access specifiers will be discussed later.
➢ The keyword static allows main() to be called without having to instantiate a particular instance of
the class.

• This is necessary since main() is called by Java interpreter before any objects are made.

Java main() method


Note: There are more information about static which will
be discussed shortly.
➢ void

• As per the Java programming language paradigm, each method


should return a value; if it does not return anything, then
the return type should be void.

• The keyword void simply tells the compiler that main()


does not return any value after its execution.

Java main() method


➢ main

• main is the name of a method in a class.

• This method is searched by JVM as a starting point for an


application with a particular signature only.

Java main() method


➢ String args[]

• Here, String is a class defied in java.lang API.

• args[] is an array to store objects of class String.

• Here, you could write anything, say String x[] instead of


String args[]. args[] is a common practice
that every programmer use. It is a customary.

• Java sees everything as String objects.


Java main() method
• It will help to read an input and then store into the array
args[] as String objects.
Statement 12 includes the following code
System.out.println("Square root of "+a.i+" is "+a.x);

➢ System is a final class from the java.lang package.

➢ out is a class variable of type PrintStream declared in the System class.

➢ println is a method of the PrintStream class.

➢ a.i and a.x represents the names of variables to be printed.

➢ + is a concatenation operator, it is used to concatenate the string values.


Consider the following lines to be printed as output
Debasis Samanta

This can be done using both println() and print()


functions
System.out.print(“Surendra”);
System.out.println(“Surendra”;
System.out.print(“\n”);
System.out.println(“Keshari”);
System.out.print(“Keshari”);

• The println(“…") method prints the string "..." and moves the cursor to a new line.
• The print("...") method instead prints just the string "...", but does not move the cursor to a
new line. Hence, subsequent printing instructions will print on the same line.

Note: The println() method can also be used without parameters, to position the cursor on the next
line.
Let us run this Java program

public class Echo{


public static void main(String args[]){
for(int i=0;i<args.length;i++){
System.out.print(args[i]+" ");
System.out.print("\n");
}
System.exit(0);
}
}
Let us run the same Java program with different input:

public class Echo{


public static void main(String args[]){
for(int i=0;i<args.length;i++){
System.out.print(args[i]+" ");
System.out.print("\n");
}
System.exit(0);
}
}
Let us run this Java program:

public class UserArgument{


public static void main(String args[]){
System.out.print("Hi ");
System.out.print(args[0]);
System.out.print(", How are you?");
}
}
Let us run this Java program:
import java.lang.*;

class Calculator{ double i;


double x = Math.sqrt(i);
}
class Example{
public static void main(String args[]){ Calculator a = new
Calculator();
a.i = Integer.parseInt(args[0]); System.out.println("Square
root of "+a.i+" is "+a.x);
}
}
Input to Java program with Scanner Class
Scanner is one of the predefined class which is
used for reading the data dynamically from the
keyboard.
import java.util.Scanner;

public class MaximumCalculator {


public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
// Calculating the maximum two numbers in Java System.out.println("Please enter two
numbers to find maximum of two"); int a = scnr.nextInt();
int b = scnr.nextInt(); if (a > b) {
System.out.printf("Between %d and %d, maximum is %d \n", a, b, a);
}
else {
System.out.printf("Between %d and %d, maximum number is %d \n", a, b, b);
}
}
}
Thank
You
67

You might also like