OOP-Java_Unit-1-1
OOP-Java_Unit-1-1
PROGRAMMING
THROUGH JAVA
Prepared by GSK
R22 II CSE I SEM
Unit-1
Object oriented thinking and
1
Java Basics
TEXT BOOKS:
1. Java the complete reference, 7th edition, Herbert
schildt, TMH.
Prepared by GSK
2. Understanding OOP with Java, updated edition,
T. Budd, Pearson education.
• REFERENCE BOOKS:
1. An Introduction to programming and OO design
using Java, J.Nino and F.A. Hosch, John wiley
& sons.
2. 2. An Introduction to OOP, third edition, T.
Budd, Pearson education. 2
Prepared by GSK
CHAPTER-1
OBJECT-ORIENTED THINKING &
JAVA BASICS
3
WHAT IS JAVA
Prepared by GSK
4
WHO DEVELOPED JAVA?
James Gosling , Mike Sheridan, and Patrick
Naughton initiated the Java language project in
June 1991.
Prepared by GSK
5
HISTORY OF JAVA
The Java team members (also known as Green
Team), initiated a project to develop a language
for digital devices such as set-top boxes,
televisions, etc. However, it was best suited for
Prepared by GSK
internet programming. Later, Java technology was
incorporated by Netscape.
Firstly, it was called "Greentalk" by James
Gosling, and the file extension was .gt
After that, it was called Oak and was developed as
a part of the Green project.
Initially developed by James Gosling at Sun
Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995. 6
WHY JAVA WAS NAMED AS "OAK"?
Prepared by GSK
In 1995, Oak was renamed as "Java" because it
was already a trademark by Oak Technologies.
7
WHY JAVA PROGRAMMING NAMED "JAVA"?
Prepared by GSK
having a cup of coffee nearby his office
Notice that Java is just a name, not an acronym.
8
WHEN IT WAS RELEASED?
Prepared by GSK
Prepared by GSK
portable, simple and secure programming
language.
Apart from this, there are also some excellent
features which play an important role in the
popularity of this language.
The features of Java are also known as Java
buzzwords. 10
Prepared by GSK
11
SIMPLE
Java is very easy to learn, and its syntax is simple, clean
and easy to understand. According to Sun Microsystem,
Java language is a simple programming language
Prepared by GSK
because:
Java syntax is based on C++ (so easier for programmers
to learn it after C++).
Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator
overloading, etc.
There is no need to remove unreferenced objects because
12
there is an Automatic Garbage Collection in Java.
OBJECT-ORIENTED
Prepared by GSK
Object-oriented means we organize our
software as a combination of different types
of objects that incorporate both data and
behavior.
13
OBJECT-ORIENTED CONT..
Object
Prepared by GSK
1.
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
14
PLATFORM INDEPENDENT
Prepared by GSK
languages like C, C++, etc. which are
compiled into platform specific
machines while Java is a write
once, run anywhere language.
No explicit pointer
Prepared by GSK
16
ROBUST
The English meaning of Robust is strong. Java is
robust because:
It uses strong memory management.
Prepared by GSK
There is a lack of pointers that avoids security
problems.
Java provides automatic garbage collection which
runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application
anymore.
There are exception handling and the type checking
17
mechanism in Java. All these points make Java robust
ARCHITECTURE-NEUTRAL
Prepared by GSK
the size of primitive types is fixed.
Prepared by GSK
It doesn't require any additional implementation.
19
HIGH-PERFORMANCE
Prepared by GSK
because Java byte code is "close" to native code.
It is still a little bit slower than a compiled
language (e.g., C, C++).
Modern Java has seen significant improvements in
performance due to optimizations in the JVM. The
Just-In-Time (JIT) compiler and other
enhancements have made it faster. 20
DISTRIBUTED
Prepared by GSK
RMI and EJB are used for creating distributed
applications.
Prepared by GSK
We can write Java programs that deal with many
tasks at once by defining multiple threads.
The main advantage of multi-threading is that it
doesn't occupy memory for each thread.
It shares a common memory area.
Threads are important for multi-media, Web
22
applications, etc.
DYNAMIC
Prepared by GSK
23
DISADVANTAGES
Memory Consumption:
Java program consumes more memory than C/C++
since it runs on top of Java virtual machine.
Prepared by GSK
Slow:
Java is slower than C/C++ because the additional
work of interpreter to convert the code into
machine language
Not Freeware:
Oracle charge a fee for the commercial license of
Java 11 and above 24
APPLICATIONS
Desktop Applications such as acrobat reader, media
player, antivirus, etc.
Prepared by GSK
Web Applications such as irctc.co.in, javatpoint.com,
etc.
Enterprise Applications such as banking applications.
Mobile
Embedded System
Robotics
25
Games, etc.
FIRST JAVA PROGRAM
class HelloWorld
{
public static void main(String args[ ])
Prepared by GSK
{
System.out.println("welcome to java Programming");
} Save the file with class_Name.java
Ex: HelloWorld.java
} Open the CMD & Set the location
Compile:
Syntax: javac Filename.java
Ex: javac HelloWorld.java
Execute: 26
Syntax: java Filename
Ex: java HelloWorld
class keyword is used to declare a class in Java.
Prepared by GSK
static is a keyword. If we declare any method as
static, it is known as the static method. The core
advantage of the static method is that there is no
need to create an object to invoke the static
method. The main() method is executed by the
JVM, so it doesn't require creating an object to
invoke the main() method. So, it saves memory. 27
void is the return type of the method. It means it
doesn't return any value.
Prepared by GSK
String[ ] args or String args[] is used for command
line argument.
Prepared by GSK
provides access to system-level resources, including
standard input, output.
29
JAVA PLATFORMS / EDITIONS
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform.
Prepared by GSK
Prepared by GSK
3) Java ME (Java Micro Edition)
It is a micro platform which is mainly used to develop
mobile applications.
4) JavaFX
JavaFX is a software platform used for creating and
delivering rich client applications that can run across a
wide variety of devices. 31
32
JAVA JVM, JDK AND JRE
Prepared by GSK
code.
Prepared by GSK
Stack : Local variables and partial results are
store here. Each thread has a private JVM stack
created when the thread is created.
Prepared by GSK
Native Method Interface : Native method interface gives an
interface between java code and native code during
execution.
Prepared by GSK
Machine, and other components to run
applications written in the Java programming
language. JRE does not contain tools and utilities
such as compilers or debuggers for developing
applications.
37
JDK : The JDK also called Java Development Kit is
a superset of the JRE, and contains everything that
is in the JRE, plus tools such as the compilers and
debuggers necessary for developing applications.
Prepared by GSK
38
Prepared by GSK
39
Prepared by GSK
have stored our information, we name that address.
The naming of an address is known as variable.
Variable is the name of memory location.
Prepared by GSK
Access modifiers can be given for instance variables.
Instance variables are created when an object is
created with the use of the keyword 'new' and
destroyed when the object is destroyed
Instance variables have default values. For
numbers, the default value is 0, for Booleans it is
43
false, and for object references it is null
STATIC/CLASS VARIABLES IN JAVA
Prepared by GSK
Static variables are initialized only once.
Prepared by GSK
In Java, it means that it will be constant for all
the instances created for that class.
static variable need not be called from object.
It is called by classname.static_variable_name
Note: A static variable can never be defined
inside a method i.e it can never be a local
45
variable.
LOCAL VARIABLES IN JAVA
Local variables are declared in method, constructor
or block.
Local variables are initialized when method, constructor
Prepared by GSK
or block start and will be destroyed once its end.
Local variable reside in stack. Access modifiers are not
used for local variable.
Local variables are visible only within the declared
method, constructor, or block.
There is no default value for local variables, so local
variables should be declared and an initial value
should be assigned before the first use. 46
Example program: Types of the variables
Prepared by GSK
void method()
{
int n=90; //local variable
}
public static void main(String args[])
{
Statement(s);
} 47
} //end of class
Prepared by GSK
48
Prepared by GSK
49
Prepared by GSK
50
Data Type
(=)
Assignment
51
Prepared by GSK
52
Prepared by GSK
53
Prepared by GSK
54
Prepared by GSK
55
JAVA ARRAYS
Normally, an array is a collection of similar type of
elements which has contiguous memory location.
We can store only a fixed set of elements in a Java
array.
Array in Java is index-based, the first element of the
array is stored at the 0th index, 2nd element is stored
on 1st index and so on.
56
TYPES OF ARRAY IN JAVA
Multidimensional Array
Prepared by GSK
Single Dimensional Array in Java:
Syntax to Declare an Array in Java
dataType arr[ ];
57
SET ARRAY ELEMENTS
Prepared by GSK
It is useful when we want to store static data
into the array.
arr[1] = 105 Here, we are assigning a value to
array’s 1 index. It is useful when we want to
store dynamic data into the array.
58
Prepared by GSK
59
Prepared by GSK
60
MULTI-DIMENSIONAL ARRAY
Prepared by GSK
dimensional array, which can have only one row
index.
It represent data into tabular form in which data
is stored into row and columns.
Multi-Dimensional Array Declaration
datatype[ ][ ] arrayName;
61
Example:
Two dimensional array:
int[ ][ ] twoD_arr = new int[10][20];
Prepared by GSK
int[ ][ ][ ] threeD_arr = new int[10][20][30];
62
class TwoDimensional
{
public static void main(String args[])
{
int[ ][ ] a={{10,20},{30,40}}; //declaration and initialization
Prepared by GSK
are");
System.out.println(a[0][0]);
System.out.println(a[0][1]);
System.out.println(a[1][0]);
System.out.println(a[1][1]); Output:
}
}
63
FOR-EACH LOOP
Prepared by GSK
decrement operator.
For-each loop syntax
Following is the syntax to declare for-each loop in
the Java.
64
Output:
20
21
22
23
24
Prepared by GSK
In this example, we are traversing array elements using
the for-each loop.
For-each loop terminates automatically when no
element is left in the array object.
65
TYPE CONVERSION
Java provides various datatypes to store various
data values.
boolean − Stores 1-bit value representing true or,
Prepared by GSK
false.
byte − Stores twos compliment integer up to 8 bits.
Prepared by GSK
In this case the casting/conversion is done
automatically therefore, it is known as implicit type
casting.
In this case both datatypes should be compatible with
each other.
67
public class WideningExample
{
public static void main(String args[])
{
int i=20;
Prepared by GSK
float f=i; // Implicit Type Conversion
System.out.println(f);
}
}
Output:
20.0
68
NARROWING
Narrowing − Converting a higher datatype to a
lower datatype is known as narrowing.
In this case the casting/conversion is not done
automatically, you need to convert explicitly using
Prepared by GSK
the cast operator “( )” explicitly.
Therefore, it is known as explicit type casting.
69
public class NarrowingTypeCasting
{
public static void main(String []args)
{
double a = 30.256;
Prepared by GSK
int b = (int)a; // Explicit Type Conversion
System.out.println(b);
}
}
Output:
30
70
OBJECT ORIENTED PROGRAMMING
CONCEPTS
Prepared by GSK
71
ABSTRACTION
Prepared by GSK
only the necessary information to the user.
Prepared by GSK
both safe from outside interference and misuse.
74
Prepared by GSK
75
Prepared by GSK
76
Prepared by GSK
77
Example:
Inheritance: Real-Time example
Prepared by GSK
78
POLYMORPHISM
Prepared by GSK
This concept is achieved through method
overriding or method overloading, allowing an
object to respond to different types of input or
behave in different ways.
79
Prepared by GSK
80
Prepared by GSK
81
Note: Java doesn’t support operator overloading except +
What are Classes and Objects?
Classes and objects are the two main aspects of object-
oriented programming.
Look at the following illustration to see the difference
Prepared by GSK
between class and objects:
82
Prepared by GSK
So, a class is a template for objects, and an
object is an instance of a class.
Prepared by GSK
A class defines new data type. Once defined
this new type can be used to create object of
that type.
Object is an instance of class. You may also
call it as physical existence of a logical
template class.
84
JAVA CLASS C ONTD..
Prepared by GSK
methods that operate on that data.
Prepared by GSK
Properties refer to the fields declared with in class and
behavior represents to the methods available in the class.
In real world, we can understand object as a cell phone
that has its properties like: name, cost, color etc and
behavior like calling, chatting etc.
So we can say that object is a real world entity. Some real
world objects are: ball, fan, car etc. 86
Prepared by GSK
87
EXAMPLE: OBJECT CREATION
Prepared by GSK
Student std = new Student();
Prepared by GSK
89
METHODS IN JAVA
Prepared by GSK
Method describes behavior of an object.
A method is a collection of statements that are
grouped together to perform an operation.
For example, if we have a class Human, then
this class should have methods like eating(),
walking(), talking() etc, which describes the
behavior of the object. 90
METHODS IN JAVA CONTD..
Prepared by GSK
We do not require to write code again and again.
91
METHOD HEADER
Prepared by GSK
Method Signature: Every method has a method signature. It is a part of
the method declaration. It includes the method name and parameter list.
92
NAMING A METHOD
Prepared by GSK
In the multi-word method name, the first letter of
each word must be in uppercase except the first
word. For example:
Prepared by GSK
return-type refers to the type of value returned
by the method.
methodName is a valid meaningful name that
represent name of a method.
parameter-list represents list of parameters
accepted by this method.
94
Method may have an optional return statement
that is used to return value to the caller function.
WHAT ARE THE TYPES OF METHODS IN
JAVA?
Prepared by GSK
Predefined
User-defined
95
PREDEFINED METHODS
Prepared by GSK
define.
Prepared by GSK
Output:
The Square root is 5.0
97
USER-DEFINED METHODS
Custom methods defined by the user are known as
user-defined methods. (Ex: subNumbers)
Prepared by GSK
98
Output: Out come is: 35
PARAMETER PASSING TECHNIQUES
Parameter passing is the mechanism of transferring
data between methods.
Prepared by GSK
There is only call by value in java, not call by
reference.
If we pass value(s) while calling a method, it is
known as call by value.
The changes being done in the called method
(ex : sum) , is not affected in the calling method
(ex: main( )). 99
Output:before change 50 after change 50
Output:
public class Swap
In called method x= 20
{
In called method y= 10
public static void swap(int x, int y)
After Swapping x = 10
{
After Swapping y = 20
int temp = x;
x = y;
y = temp;
Prepared by GSK
System.out.println(“In called method= " + x);
System.out.println(" In called method = " + y);
}
public static void main(String[] args)
{
int x = 10;
int y = 20;
swap(x, y);
System.out.println(" After Swapping = " + x);
System.out.println(“After Swapping= " + y);
}
} 100
Prepared by GSK
A method in java that calls itself is called recursive method.
It makes the code compact but complex to understand.
Syntax:
returntype methodname(parmeter_list )
{
//code to be executed
methodname(); //calling same method
} 101
Prepared by GSK
Working of Recursion
102
JAVA RECURSION EXAMPLE 1: INFINITE TIMES
class RecursionExample1
{
static void p()
Prepared by GSK
{
System.out.println("hello");
p( );
}
Prepared by GSK
{ hello 3
count++; hello 4
hello 5
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args)
{
p();
}
104
}
Java Program to find Factorial of a number using Recursion
class Factorial
{
Prepared by GSK
return n * factorial(n-1); // recursive call
else
return 1;
}
Prepared by GSK
106