OOPS Through JAVA
Software
 Software is a collection of programs as a solution to
the real time problems.
 A Program is a set of instructions with syntax and
semantics.
 We write programs by using a programming
language.
Programming Languages
 Machine Language
 It contains 0’s and 1’s.
 Machine understandable form
 Difficult to write programs for human
 Assembly Language
 Microprocessor Language
 Contains pneumonics
 High Level Language
 Procedures and functions
 Object oriented programs are also high level.
 Ex: PASCAL, COBOL,FORTRAN, C, C++, JAVA
Programming Styles
 Three different programming styles.
 Top-down
 Bottom – Up
 Modules
 Top-down
 The main method appears at top of the program. The
compilation begins from top.
 Bottom-up
 The functions or classes will be defined first, followed by main
method.
 The compilation starts from the main, that is available at
bottom and goes to top.
Network, Types of Networks, Protocols
what is Java?
 Java is an Object Oriented Programming Language.
 In Java, we can write two types of programs.
 Console Applications
 These programs result will displays at command prompt.
 Applets / Web Programs
 The program result will displays in the web browser.
Relation between java and network
History of Java
 Java started out as a research project to manipulate consumer
electronic devices.
 Research began in 1991 as the Green Project at Sun
Microsystems, under the lead of James Gosling.
 Research efforts birthed a new language, OAK. ( A tree outside
the window of James Gosling’s office at Sun)
 It was developed as an embedded programming language,
which would enable embedded system application.
History of Java
 With the invention of www in 1993, The team developed
web applets to run on network of computers.
 The team developed a web browser called HotJava in
1994.
 Java is available as jdk from 1995 and it is an open source
s/w.
From the History of Java
Language was created with 5 main goals:
 It should be object oriented.
 A single representation of a program could be executed on
multiple operating systems. (i.e. write once, run anywhere)
 It should fully support network programming.
 It should execute code from remote sources securely.
 It should be easy to use.
James Gosling
Green Team
Java Logo
Versions of Java
Version Year Features Added
JDK 1.1 Feb19,1997
Inner classes JavaBeans, JDBC, RMI, Reflection,
AWT.
J2SE 1.2 Dec8, 1998
JIT compiler, Collections, IDL & CORBA, strictfp,
Java Plug-in.
J2SE 1.3
May8,
2000
HotSpot JVM, JavaSound, Java Naming and
Directory Interface, Java Platform Debugger
Architecture.
J2SE 1.4 Feb6, 2002
Preferences API, Logging API, assert, image I/O
API, security and cryptography extensions.
J2SE 5.0
Sep30,
2004
Generics, annotations, Autoboxing, Enumerations,
Varargs, Enhanced for each.
JAVA SE 6
Dec11,
2006
JDBC 4.0, JVM improvements, Improved web
services, Support for older Win9x versions dropped.
Java Platforms
There are three main platforms for Java:
 Java SE (Java Platform, Standard Edition) – runs on
desktops and laptops.
 Java ME (Java Platform, Micro Edition) – runs on
mobile devices such as cell phones.
 Java EE (Java Platform, Enterprise Edition) – runs on
servers.
Java Development Kit: (Jdk)
It contains JRE's along with the various development tools like
the Java source compilers, bundling and deployment tools,
debuggers, development libraries, etc.
Tools of jdk
• javac ( java compiler)
• java (java interpreter)
• appletviewer
• jdb (java debugger)
Java Terminology
 javadoc  creates html format documentation
for java source code.
 javap  java disassembler, that converts
bytecode into program description
 Java Virtual Machine: (JVM)
 It interprets the byte code into the machine code
depending upon the underlying OS and hardware
combination. It uses the class libraries, and other
supporting files provided in JRE
Java Terminology
 Java Runtime Environment:
A runtime environment which implements Java Virtual
Machine, and provides all class libraries and other facilities
necessary to execute Java programs. This is the software on
your computer that actually runs Java programs.
JRE = JVM + Java Packages Classes (like util, math,
lang, awt, swing etc) +runtime libraries.
Java Terminology
Object Oriented Programming Concepts
Objects
Classes
Data abstraction and
Encapsulation
Inheritance
Polymorphism
Dynamic Binding
A class is collection of objects of similar type or it is a template.
Ex: fruit mango;
 Objects are instances of the type class.
The wrapping up of data and functions into a single unit ( called
class) is known as encapsulation. Data encapsulation is the
most striking features of a class.
Abstraction refers to the act of representing essential features without
including
the background details or explanations
Inheritance is the process by which objects of one class acquire the properties
of another class. The concept of inheritance provides the reusability.
class object
Polymorphism:
It allows the single method to perform different actions based on
the parameters.
Dynamic Binding: When a method is called within a program, it
associated with the program at run time rather than at compile
time is called dynamic binding.
Object-Oriented Languages Types
1.Object-based programming language: It supports
Data encapsulation
Data hiding and access mechanisms
Automatic initialization and clear-up of objects
Operator overloading
Disadvantage : They do not support inheritance and dynamic binding
Ex: Ada
2.Object-oriented programming languages:
OOP = Object-based + inheritance + dynamic binding
Ex: C++, Java, Smalltalk, Object Pascal
Benefits of OOP
Through inheritance, we can eliminate redundant code and
extend the use of existing classes.
The principle of data hiding helps the programmer to build
secure programs.
It is easy to partition the work in a project based on objects.
Object oriented system easily upgraded from small to large
systems.
Software complexity can be easily managed.
Applications of oop
 Real-time systems
 Object-oriented databases
 Neural networks and parallel programming
 Decision support and office automation systems
 CAD/CAM systems
C++ Vs. Java
C++ Java
Supports operator
overloading
Doesn’t support operator
overloading
Template classes are available. No templates
C++ Vs. Java
C++ Java
Features of Java (Java Buzz Words)
 Simple
 Object Oriented
 Distributed
 Robust
 Secure
 System independence & Portable
 Compile, Interpreted and High Performance
 Multithreaded
 Dynamic
 Architecture-Neutral
Java Features
 Simple
 The design goal of java is simple.
 Pointers are eliminated in java.
 Improper handling of pointers leads to memory leaks and reliability
issues.
 Pointers may crash a program easily. For ex: when we add two
pointers the program crashes immediately.
 Pointers break security over internet.
 Rich pre-defined class libraries through packages
 Object Oriented
 Every thing (primitive types, arrays, void including static variable
and static methods ) will be represented as objects of class.
 Java follows all features of OOP language.
 All methods are associated with objects
 Distributed
 Java is designed for the distributed environment of the
Internet, because it handles TCP/IP protocols.
 Allows objects on two different computers to execute
procedures remotely by using package called Remote Method
Invocation (RMI)
 Robust
 Robust means strong.
 Inbuilt exception handling features.
 Memory management feature.
 Automatic garbage collection tracks objects usage over time
and deletes if the variable or an object is not used.
Java Features
Java Features
 Secure
 Security problems and virus threats can be eliminated or
minimized with java programs (firewalls) over internet.
 Access restrictions are forced (private, public)
 System independence
 Byte code is not machine dependent. It can run on any processor
and any operating system.
 Portability
 Same application runs on all platforms
 The sizes of the primitive data types are always the same
Java Features
 Compile, Interpreted and High Performance
 Java compiler generate byte-code, not native machine code
 The byte-codes are platform-independent
 Java byte code is translated to machine readable
instructions in runtime (Java Virtual Machine)
 Easy to translate directly into native machine code by using a
just-in-time compiler, which enhances the speed of execution.
 Multithreaded
 A thread is an individual process.
 JVM supports multithreaded programming.
 Need not wait for the application to finish one task before
beginning another one.
Java Features
 Dynamic
 Libraries can freely add new methods and instance
variables without any effect on their clients
 Interfaces promote flexibility and reusability in code by
specifying a set of methods an object can perform, but
leaves open how these methods should be implemented .
 Architecture-Neutral
 Goal of java designers is “write once; run anywhere, any
time, forever.”
Java Program Structure
Documentation Section
Package Statement
Import Statement
Interface Statements
Class Definition
Main method class
{
main method definition
}
Suggested
Optional
Essential
Optional
compulsory
Optional
Starting a Java Program (Sample)
import java.lang.System;
import java.lang.String; or use import java. lang.*;
class First
{
public static void main (String args [])
{
System.out.println (“Welcome to Java”);
}
}
Starting a Java Program (Sample) Explanation
First , decide and import the classes, which are required for the
program. Group of classes and interfaces with its methods are
contained in a package.
Java has several such packages in its library.
java library
Packages
Classes and interfaces
Methods
In java.lang.* , * means all the classes and interfaces of that
package are make available into our program.
 
System is a class which is present in java.lang package.
out is a static field present in system class which returns a
PrintStream object. As out is a static field it can call directly
with classname.
println() is a method which present in PrintStream class
which can call through the PrintStream object return by
static field out present in System class to print a line to
console.
Single Line comments:  Starts with // double slash symbol.
Multi Line comments: Stars with /* and ends with */
Java documentation comments: Starts with /** and end with
*/. These comments are used to provide description for
every feature in a java program.
Comments
Formatting the Output
n Next line
t Horizontal tab space
r Enter key
b Back space
f Form feed
 Displays 
” Displays”
’ Displays’
The Architecture of the Java Virtual Machine
Operating System
Interpreter
& JIT
W
Java
Sour
ce
Class
Loader
Byte
Code
Verifier
Java
Class
Librari
es
Java
Interp
reter
Just-in-
time
Compil
er
Run Time
System
Java
OS
Win
32 Solari
s
MAC
Other
s
Hardware
Java Execution Procedure
Binary form of a class file
 public class Hello
 {
 public static
 {
 System.out.println("Hello,
World!");
 }
 }

Keywords
abstract continue goto package synchronized
assert default if private this
boolean do implements protected throw
break double import public throws
byte else instanceOf return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
Data Types
Simple Type Derived Type User Defined
Type
Numeric Type Non-Numeric class Interface
Integer Float Char Boolean
float double
byte short int long
E.g: Array, String…
Single precision
Double precision
Data Types
 Java Is a Strongly Typed Language
 Every variable has a type, every expression has a type,
and every type is strictly defined.
 All assignments, whether explicit or via parameter
passing in method calls, are checked for type
compatibility.
 There are no automatic conversions of conflicting types
as in some languages.
 For example, in C/C++ you can assign a floating-point
value to an integer. In Java, you cannot.
Integer Data Types
 Java does not support unsigned, positive-only integers.
 All are signed, positive and negative values.
Byte Data Type
 The smallest integer type is byte.
 Variables of type byte are especially useful while working with a
stream of data from a network or file.
 Byte variables are declared by use of the byte keyword.
Ex: byte b, c;
Floating Point Types
 There are two kinds of floating-point types.
 All math functions, such as sin( ), cos( ), and sqrt( ), return
double values.
Boolean Data Type
 It can have only one of two possible values, true or false.
 This is the type, returned by all relational operators, such as a <
b.
Character Data Type
 char in Java is not the same as char in C or C++.
 Java uses Unicode to represent characters.
 Unicode defines a fully international character set that can represent
all of the characters found in all human languages.
 It is a unification of dozens of character sets, such as Latin, Greek,
Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more.
 Hence it requires 16 bits.
 The range of a char in java is 0 to 65,536.
 There are no negative chars.
Data Types
Name Width in bits Range
long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038
char 16 0 to 65,536.
public class IntDemo{
public static void main(String args[]){
System.out.println(" For an Integer ");
System.out.println("Size is : "+Integer.SIZE);
int i1 = Integer.MAX_VALUE;
int i2 = Integer.MIN_VALUE ;
System.out.println("Max value is : "+i1);
System.out.println("Min Value is : "+i2);
System.out.println(" For an Byte");
System.out.println("Size is : "+Byte.SIZE);
byte b1 = Byte.MAX_VALUE;
byte b2 = Byte.MIN_VALUE ;
System.out.println("Max value is : "+b1);
System.out.println("Min Value is : "+b2);
System.out.println(" For an Short");
System.out.println("Size is : "+Short.SIZE);
short s1 = Short.MAX_VALUE;
short s2 = Short.MIN_VALUE ;
System.out.println("Max value is : "+s1);
System.out.println("Min Value is : "+s2);
System.out.println(" For a Long");
System.out.println("Size is : "+Long.SIZE);
long l1 = Long.MAX_VALUE;
long l2 = Long.MIN_VALUE ;
System.out.println("Max value is : "+l1);
System.out.println("Min Value is : "+l2);
}
}
public class FloatDemo{
public static void main(String args[]){
System.out.println(" For an Float");
System.out.println("Size is : "+Float.SIZE);
float f1 = Float.MAX_VALUE;
float f2 = Float.MIN_VALUE ;
System.out.println("Max value is : "+f1);
System.out.println("Min Value is : "+f2);
System.out.println(" For an Double");
System.out.println("Size is : "+Double.SIZE);
double d1 = Double.MAX_VALUE;
double d2 = Double.MIN_VALUE ;
System.out.println("Max value is : "+d1);
System.out.println("Min Value is : "+d2);
}
}
public class CharDemo{
public static void main(String args[]){
System.out.println(" For a Char");
System.out.println("Size is : "+Character.SIZE);
int f1 = Character.MAX_VALUE;
long f2 = Character.MIN_VALUE ;
System.out.println("Max value is : "+f1);
System.out.println("Min Value is : "+f2);
}
}
Variables
 The variable is the basic unit of storage in a Java program.
 A variable is defined by the combination of an identifier, a type, and an
optional initializer.
Declaring a Variable
 In Java, all variables must be declared before they can be used.
type identifier [ = value][, identifier [= value] ...] ;
Types
 Instance Variable
 Class Variable
 Local Variable
 Parameters
Local variables :
• Local variables are declared in methods, constructors, or blocks.
Instance variables :
• Instance variables are declared in a class, but outside a method,
constructor or any block.
• Instance variables are created when an object is created with the use of
the key word 'new' and destroyed when the object is destroyed.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block
in the class.
• Instance variables have default values.
• Instance variables can be accessed directly by calling the variable name
inside the class.
• However within static methods and different class ( when instance
variables are given accessibility) that should be called using the fully
qualified name ObjectReference.VariableName
Class/Static variables :
• Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
• Static variables are stored in static memory.
• Static variables are created when the program starts and destroyed when
the program stops.
• Visibility is similar to instance variables.
• Default values are same as instance variables.
• Static variables can be accessed by calling with the class name
ClassName.VariableName
class Variables{
int i;
public int j
static long l=10;
public static float f;
char c;
boolean b;
void display(int a){
i=a;
System.out.println("i value in display: "+i);
}
public static void main(String args[]){
double d=0.0;
//public double d=0.0; invalid
Variables v1=new Variables();
Variables v2=new Variables();
Variables v3=new Variables();
v1.display(100);
v1.i=2;
v2.i=3;
v3.i=4;
System.out.println("i value is: "+v1.i);
System.out.println("i value is: "+v2.i);
System.out.println("i value is: "+v3.i);
System.out.println("i value is: "+v1.j);
v1.l=20;
v2.l=30;
v3.l=40;
System.out.println("l value is: "+v1.l);
System.out.println("l value is: "+v2.l);
System.out.println("l value is: "+v3.l);
System.out.println("f value is: "+f);
System.out.println("c value is: "+v1.c);
System.out.println("b value is: "+v1.b);
System.out.println("d value is: "+d);
}
}
class Variables{
int i;//instance variable
public int j ;//instance variable
static long l=10;//class variable
public static float f;//class variable
char c;//instance variable
boolean b;//instance variable
void display(int a){
i=a;
System.out.println("i value in display: "+i);
}
public static void main(String args[]){
double d=0.0;//local varible
//public double d=0.0; invalid
Variables v1=new Variables();
Variables v2=new Variables();
Variables v3=new Variables();
v1.display(100);
v1.i=2;
v2.i=3;
v3.i=4;
System.out.println("i value is: "+v1.i);
System.out.println("i value is: "+v2.i);
System.out.println("i value is: "+v3.i);
System.out.println("i value is: "+v1.j);
v1.l=20;
v2.l=30;
v3.l=40;
System.out.println("l value is: "+v1.l);
System.out.println("l value is: "+v2.l);
System.out.println("l value is: "+v3.l);
System.out.println("f value is: "+f);
System.out.println("c value is: "+v1.c);
System.out.println("b value is: "+v1.b);
System.out.println("d value is: "+d);
}
}
 Variables declared inside a scope are not accessible to code
outside.
 Scopes can be nested. The outer scope encloses the inner
scope.
 Variables declared in the outer scope are visible to the inner
scope.
 Variables declared in the inner scope are not visible to the
outside scope.
Operators
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment and decrement operators
 Conditional Operators
 Bitwise Operators
 Special Operators
Arithmetic Operators
Operator Result
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
Relational Operators
 The relational operators determine the relationship that
one operand has to the other.
 They determine equality and ordering.
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Logical Operators
Operator Result
&& Logical AND
| | Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
& //executes both left and right side operands
&& // Java will not bother to evaluate the right-hand
operand when the outcome of the expression can be
determined by the left operand alone.
class Test{
public static void main(String args[]){
int denom=0,num=20;
if (denom != 0 && num / denom > 10)
System.out.println("Hi");
}
}
Boolean Logical Operators(2)
Operator Result
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
Assignment Operator
Operator Result
+= Addition assignment
– = Subtraction
assignment
*= Multiplication
assignment
/= Division assignment
%= Modulus assignment
Increment / Decrement Operator
Operator Result
++ Pre / Post increment
-- Pre / Post Decrement
Example:
class IncDec{
public static void main(String args[]){
int a = 1;
int b = 2;
int c,d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class OpEquals{
public static void main(String args[]){
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
Bitwise Operators(1)
 bitwise operators can be applied to the integer types,
long, int, short, byte and char.
 These operators act upon the individual bits of their
operands.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
Bitwise Operators(2)
Operator Result
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
00101010 42
&00001111 15
--------------
00001010 10
00101010 42
^00001111 15
-------------
00100101 37
int a = 32;
a = a >> 2; 8
int a = 64;
a = a << 2; 256
11111000 –8
>>1
11111100 –4
11111111 11111111 11111111 11111111 –1
>>>24
00000000 00000000 00000000 11111111 255
Example:
public class RelationalOperatorsDemo
{
public static void main(String args[])
{
int x=10,y=5;
System.out.println(“x>y:”+(x>y));
System.out.println(“x<y:”+(x<y));
System.out.println(“x>=y:”+(x>=y));
System.out.println(“x<=y:”+(x<=y));
System.out.println(“x==y:”+(x==y));
System.out.println(“x!=y:”+(x!=y));
}
}
public class TernaryOperatorDemo
{
public static void main(String args[])
{
int x=10,y=12;
int z;
z= x > y ? x : y;
System.out.println(“Z=“+z);
}
Operator Precedence
Expressions
 An expression is a combination of constants (like 10),
operators ( like +), variables(section of memory) and
parentheses ( like “(” and “)” ) used to calculate a
value.
Ex1: x = 1;
Ex2: y = 100 + x;
Ex3: x = (32 - y) / (x + 5)
public class TernaryOperatorDemo
{
public static void main(String args[ ])
{
int x=10,y=12;
int z;
z= x > y ? x : y;
System.out.println(“Z=“+z);
}
Operator Precedence
Expressions
 An expression is a combination of constants (like 10),
operators ( like +), variables(section of memory) and
parentheses ( like “(” and “)” ) used to calculate a
value.
Ex1: x = 1;
Ex2: y = 100 + x;
Ex3: x = (32 - y) / (x + 5)
Control Statements
 Selection Statements: if & switch
 Iteration Statements: for, while and do-while
 Jump Statements: break, continue and return
Selection Statements
if (condition)
statement1;
else
statement2;
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
…
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The condition is any expression that returns a boolean value.
The expression must be of type byte, short, int, or char;
Each of the values specified in the case statements must be of a type
compatible with the expression.
Iteration Statements
while(condition)
{
// body of
loop
}
do
{
// body of loop
} while (condition);
for(initialization; condition; iteration)
{
// body
}
for – each loop
 This loop is specifically designed to handle the elements
of a collection. Collection represents a group of elements.
Example for for-each
 class demo
 {
 public static void main(String args[])
 {
 }
 }
 }
Jump Statements
break; //exit from the loop
continue; //bypass the followed instructions
return; //control returns to the caller
label:
- - - -
- - - -
break label; //it’s like goto
statement
break, continue and return statements
 break:
 Used inside of a loop to come out of it.
 Used inside switch block to come out of it.
 Used in nested blocks to go to the end of the block.
 Continue:
 Used inside the loop to repeat the next iteration of loop.
 When continue is executed, subsequent statements in the
loop are not executed and control goes back to the next
repetition of the loop.
 Return statement is used in a method to come out of it
to the calling method.
Example for continue
class continuedemo
{
public static void main(String args[])
{
;
}
}
}
Type Conversion and Casting
 Type conversion, typecasting, refers to different
ways of, implicitly or explicitly, changing an entity of one
data type into another.
 Types of Conversions:
1.Widening conversion
2.Narrowing conversion
Widening Conversion
The widening conversion is permitted in the following
cases:
 byte to short, int, long, float, or double
 short to int, long, float, or double
 char to int, long, float, or double
 int to long, float, or double
 long to float or double
 float to double
 When one type of data is assigned to another type of variable, an
automatic type conversion will take place if the following two
conditions are met:
 The two types are compatible.
 The destination type is larger than the source type.
 When these two conditions are met, a widening conversion takes
place.
Ex: char and boolean are not compatible with each other.
 In general, the narrowing primitive conversion can occur in
these cases:
short to byte or char
char to byte or short
int to byte, short, or char
long to byte, short, or char
float to byte, short, char, int, or long
double to byte, short, char, int, long, or float
 Narrowing conversion is used to cast the above incompatible types.
(target-type) value
Narrowing Conversion
Arrays
 An array is a group of homogeneous (same type of) elements
that are referred by a common name.
 In java, Arrays are created on dynamic memory by JVM.
 The operator new is used for dynamic memory allocation.
 One-Dimensional Arrays:
Syntax: type variablename[] = {elements list};
ex: int marks[] = {60,70,80,50};
Syntax : type varname[]=new type[size];
int month[] = new int[12];
Multidimensional Arrays
int twoD[][]=new int[4][5];
 If month is a reference to an array, month.length will gives
the length of the array.
Initialization:
char []c = {‘a’, ‘b’, ‘c’};
double d[][]= {
{1.0,2.0,3.0},
{4.0,5.0,6.0},
{7.0,8.0,9.0}
};
3-Dimensional Arrays
Jagged Arrays
X[0] [0] x[0] [1]
X[1] [0] x[1] [1] x[1] [2]