Unit 1

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

OBJECT ORIENTED PROGRAMMING WITH

JAVA

Ranajit Senko
Assistant Professor
Department of CSE
GITAM Institute of Technology (GIT)
Visakhapatnam – 530045

1
Topics to be Covered

Java Programming Fundamentals


OOPS Through Java
 JDK & JVM
Data Types and Operators
Program Control Structures

2
ABOUT JAVA LANGUAGE:

 Java is a High Level, Object Oriented Programming language developed by “SUN MICRO SYSTEMS” in 1995.

The origin of Java is OAK by JAMES GOSLING” in 1991.

 Java is designed for the development of Software for the Consumer Electronic Devices. The main features of

JAVA Language is that it is a Platform Independent Language. Java is called “The Internet Version of C”. The

first application program of JAVA was written was “HOT JAVA”.

 In 1994, a team of Java developers wrote Web Runner, a clone of the internet browser Mosaic. It was based

on the Java programming language. The name ‘Web Runner’ was a tribute to the Blade Runner movie. It was

renamed Hot Java and was officially announced in May the same year at the Sun World conference.

3
Advantages of Java Programming Language:

 Object Oriented − In Java, everything is an Object. Java can be


easily extended since it is based on the Object model.

 Platform Independent − Unlike many other programming


languages including C and C++, when Java is compiled, it is not
compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the
web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.

 Secure − With Java's secure feature it enables to develop


virus-free, tamper-free systems. Authentication techniques
are based on public-key encryption.

4
Advantages of Java Programming Language:

Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the
compiled code executable on many processors, with the presence of Java runtime system.

Portable − Being architecture-neutral and having no implementation dependent aspects of the specification
makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX
subset.

Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error
checking and runtime checking.

Multithreaded − With Java's multithreaded feature it is possible to write programs that can perform many
tasks simultaneously. This design feature allows the developers to construct interactive applications that can
run smoothly.

5
Advantages of Java Programming Language:

 High Performance − With the use of Just-In-Time compilers, Java enables high performance.

 Distributed − Java is designed for the distributed environment of the internet.

 Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry extensive amount of run-time information that can be
used to verify and resolve accesses to objects on run-time.

 Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an incremental
and light-weight process.

 Simple – Java designed simple and user friendly.

6
Java Development Kit – JDK

 The Java Development Kit (JDK) is a software development environment used for developing Java applications
and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a compiler (javac), an
archiver (jar), a documentation generator (javadoc) and other tools needed in Java development.

 The Java Development Kit (JDK) is one of three core technology packages used in Java programming, along with
the JVM (Java Virtual Machine) 

• javac - The Java Compiler


• javaprof - Java profiler
• javadoc - documentation generator ,
• javah - creates C header files
• javap - to print the Java byte codes ,
• jdb- The Java Debugger
• apple viewer -Tool to run the applets

7
Java Virtual Machine

By All Language compilers translate source code into machine code for a
specific computer.

Java compiler also does the same. The Java compiler produces an intermediate
code also known as “Byte Code” for a machine. The machine is called “Java
Virtual Machine (JVM). This exists only inside the computer memory. Byte code
is a form of instruction set designed for efficient execution by a software
interpreter.
8
Unlike human-readable source code, byte codes (normally numeric addresses)
encode the result of compiler parsing and performing semantic analysis of
things like type, scope, and nesting depths of program objects.

Whenever you write java command on the command prompt to run the java
class, (runtime Instance) an instance of JVM is created.

The JVM performs the following main tasks: Loads code, Verifies code, Executes
code, Provides runtime environment.
JVM ARCHITECTURE

 Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the classloader. There are three built-in classloaders in Java.

 Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader.
It loads the rt.jar file which contains all class files of Java Standard Edition like.
• java.lang package classes, java.net package classes, java.util package classes, java.io package
classes, java.sql package classes etc.

 Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System
classloader. It loads the jar files located inside.
•  $JAVA_HOME/jre/lib/ext directory.

9
JVM ARCHITECTURE
 System/Application ClassLoader: This is the child classloader of Extension classloader. It loads
the classfiles from classpath. By default, classpath is set to current directory. You can change
the classpath using "-cp" or "-classpath" switch. It is also known as Application class loader.

 2)Class(Method) Area - Class(Method) Area stores per-class structures such as the runtime
constant pool, field and method data, the code for methods.

 3) Heap - It is the runtime data area in which objects are allocated.

 4) Stack - Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return. Each thread has a private JVM stack, created at the same time
as thread. A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.

10
JVM ARCHITECTURE

 5) Program Counter Register - PC (program counter) register contains the address of the Java virtual machine instruction currently
being executed.

 6) Native Method Stack - It contains all the native methods used in the application.

 7) Execution Engine -
A virtual processor
Interpreter: Read bytecode stream then execute the instructions.
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have
Similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here,
the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.

 8) Java Native Interface


• Java Native Interface (JNI) is a framework which provides an interface to communicate with another application written in another
language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or interact with OS libraries.
11
WHAT IS JVM – JAVA VIRTUAL MACHINE ?

 JVM (Java Virtual Machine) is an abstract machine.

 It is called a virtual machine because it doesn't physically exist.

 It is a specification that provides a runtime environment in which Java bytecode can be executed.

 It can also run those programs which are written in other languages and compiled to Java bytecode.

 JVMs are available for many hardware and software platforms.

 JVM, JRE, and JDK are platform dependent because the configuration of each OS is different from each other.

 However, Java is platform independent.

 There are three notions of the JVM: specification, implementation, and instance.

12
Java Byte Code

13
Differences Between Byte code and Machine Code

Sl.No Byte Code Machine Code


1  Byte Code consisting of binary, hexadecimal, macro instructions like (new, add,  Machine code consisting of binary
swap, etc) and it is not directly understandable by the CPU. It is designed for instructions that are directly
efficient execution by software such as a virtual machine. intermediate-level understandable by the CPU.

2  Byte code is considered as the intermediate-level code  Machine Code is considered as the low-
level code.
3  Byte code is a non-runnable code generated after compilation of source code and  Machine code is a set of instructions in
it relies on an interpreter to get executed machine language or in binary format
and it is directly executed by CPU.
4  Byte code is executed by the virtual machine than the Central Processing Unit.  Machine code is not executed by a
virtual machine it is directly executed by
CPU.
5  Byte code is less specific towards machine than the machine code  Machine code is more specific towards
machine than the byte code.
6  It is platform-independent as it is dependent on the virtual machine and the system  It is not platform independent because
having a virtual machine can be executed irrespective of the platform. the object code of one platform can not
be run on the same Operating System.
7  All the source code need not be converted into byte code for execution by CPU.  All the source code must be converted
Some source code written by any specific high-level language is converted into into machine code before it is executed
byte code then byte code to object code for execution by CPU. by the CPU.

14
Simple Java Program

 The keyword public static void main is the


means by which you create a main method
within the Java application.

 It's the core method of the program and calls


all others.

 It can't return values and accepts parameters


for complex command-line processing.

Main Method in Java


15
Java Libraries

 A Java library is just a collection of classes that have been written by somebody else already. You download
those classes and tell your computer about them, and then you can use those classes in your code.

 If one installs Java Development Kit (JDK), in the directory above where you find the libs you will probably find
a src.jar file. This can be unpacked either with the jar.exe utility, or with a standard zip-style tool, and contains
the Java sources to the standard class.

 Libraries are places of information ... More than books.

 Libraries are places of information, offering people free access to the information that are found elsewhere.

 Example:
 java. util is a package and part of Java class library: A package is a namespace that organizes a set of related
classes and interfaces. The Java platform provides an enormous class library (a set of packages) suitable for use
in your own applications.

16
 LITERALS, IDENTIFIERS, WHITESPACES, COMMENTS, OPERATORS, SEPARATORS, KEYWORDS:

 Java programs are a collection of White spaces, identifiers, Comments, Literals, Operators, Separators and Keywords.
Java is a free form language i.e., you do not need to follow any special indentation rules.

 In Java, Whitespace is a Space, tab (or) a new line.

 Identifiers are used for class names, Method names and variable names. An Identifier may be any descriptive
sequence of Upper and lower case letters, numbers, Under score ( _ ) and a dollar Sign ( $ ) characters.
Example: Avgtemp Count A4 $test7 this_is_ok

 A constant value in Java is created by using a Literal representation of it.


Example: 100 – This specifies an Integer Literal value. 98.6 – Specifies floating point value.
‘X’ – Specifies character constant. “This is Suraj” – Specifies a string type.
17
Separators
 In Java, there are a few characters that are used as separators.
 The most commonly used separator in Java is the Semi-colon (;).
 The various other separators are Parenthesis ( ), Braces { }, Brackets [ ], Semi-colon ; , Comma, , Period.
Keywords
 In Java language there are 49 reserved keywords currently used.
 The keywords cannot be used as names for the variable, class (or) method.
 abstract const finally int public this
 boolean continue float interface return throw
 break default for long short throws
 byte do goto native static transient
 case double if new strictfp try
 catch else implements package super void
 char extends import private switch volatile
 class final instanceof protected synchronized while
18
Java Literals:
 Literals in Java are a sequence of characters, that represents constant values to be stored in
variables.

 Java allows following kinds of literals –


1. integer literals
2. Floating literals
3. Boolean literals
4. Character literals
5. String literals
6. Backslash literals

19
COMMENT STATEMENTS IN JAVA
 In Java there are three types of Comment Statements.
1. Single line Comment.
2. Multi line Comment.
3. Documentation Comment.

 The single line comments begin with double slash ( // ).

 For longer comments, we can create long Multi line comments by starting with a /* and ending with
*/.

 The documentation comment is used to produce an HTML file that documents your program. The
documentation comment with /** a and ends with a **/.
20
OOPS Concept in Java
Encapsulation:
• The wrapping up of data and methods into a single unit (class ) is known as “Encapsulation”.
• Data Encapsulation is the most striking feature of a class.
• The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it.
• There functions provide the Interface between the objects data and the program.

Inheritance:
• Inheritance is one of the concepts in Oops.
• Inheritance is the process by which objects of one class acquire the properties of objects of another class.
• It supports the concept of hierarchical classification.
• The concepts of Inheritance provides the idea of reusability. i.e., we can add additional feature to an existing class without modifying it.

Polymorphism:
• Polymorphism is one of the important concepts in OOPS.
• Polymorphism means “the ability to take more than one form”.
• An operation can exhibit different behaviors in different instances.
• Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface.
• Polymorphism is extensively used in implementing Inheritance.
21
Encapsulation

Types of Inheritance
22
Data Type in a Programming Language

 A data type in a programming language is a set of data


with values having predefined characteristics.
The PREDEFINED CHARACHARACTERISTICS are the
characteristics you define and are stored in a field
catalog.

 Java data types are of two types


 Primitive data types
 Reference data types

 Reference (Non-Primitive) data types are constructed


from primitive data types. These are classes, arrays,
strings and interfaces.

23
Declaration and Initialization of a Variable
 In Java, Variable is the basic unit of storage. It is defined as the combination of an Identifier. In Java, all
variables must be declared before they can be used. A variable can be used to store a value of any data type.
The general form of declaration of a variable is:

Type variable 1, variable 2, …,variable n;


Variables are separated by Comma’s ( , ).
A declaration statement must end with a semi-colon (;).
Example: int count;
float x, y, z;
 A variable must be given a value after it has been declared but before it is used in an expression.
The general form of Initializing a variable is:
Type variable- name=value;
Example: int m=5, n=10;
double total = 57.87;
The process of giving initial values to variable is known as the “Initialization”.
The one’s that are not initialized are automatically set to zero (0).
24
Automatic Type-Conversion and Type-Casting
 If the two types are compatible, then Java will perform the
conversion automatically. This is known as “Automatic Type
Conversion”.

 Automatic Type Conversion is possible only if the following


conditions are satisfied.

 If the two types are compatible.

 The destination type is larger than the Source type.


Example: The int type is always large enough to hold all valid byte

values, so no explicit cast statement is required.

 Suppose if the two types are incompatible, you must use a “cast”,
which performs an explicit conversion between incompatible types.

25
Type-Casting and Example of Type-Casting
 The process of converting one data type to another is called
“Casting”.

 We must cast the value to be stored by preceding it with the


type name in parenthesis ().

 The syntax is: Type Variable 1 = (type) Variable 2;

 Example: int m = 50;


byte n = (byte ) m;
long count = (long) m;

 Casting is often necessary when a method returns a type


different than the one we required. Casting into a small type
may result in a loss of data. Casting a floating point value to an
integer will result in a loss of the fractional part.

26
Types of Operators:
 Java supports a rich set of operators. An operator is a symbol that tells the
computer to perform certain Mathematical (or) Logical Manipulations.

 Java divides the operators into the following groups:


 Arithmetic operators
 Relational Operators (or) Comparison operators
 Assignment operators
 Logical operators
 Bitwise operators
 Increment (or) Decrement Operators also called Unary Operators.
 Special Operators.

27
 Arithmetic (Mathematical) Operators
Operator Name Description Example
+ Addition Adds together two x+y  Java Comparison Operators
values
Operato Name Exampl
- Subtraction Subtracts one value x-y r e
from another
== Equal to x == y
* Multiplication Multiplies two values x*y
!= Not equal x != y
/ Division Divides one value by
another x/y > Greater than x>y

% x%y < Less than x<y


Modulus Returns the division
remainder >= Greater than or equal to x >= y
<= Less than or equal to x <= y
 Java Logical Operator
Operator Name Description Example
&&  Logical and Returns true if both statements are true x < 5 &&  x < 10
||  Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x <
10)
28
BIT WISE OPERATOR Table Lists The Bitwise Operators - Example
Description
& (bitwise and) Binary AND Operator copies a bit to the result if it exists in both (A & B) will give 12 which is 0000 1100
operands.

 BITWISE OPERATOR
| (bitwise or) Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101  Java defines several
bitwise operators, which
^ (bitwise XOR)
Binary XOR Operator copies the bit if it is set in one operand but
(A ^ B) will give 49 which is 0011 0001 can be applied to the
not both.
integer types, long, int,
short, char, and byte.
Binary Ones Complement Operator is unary and has the effect of (~A ) will give -61 which is 1100 0011 in 2's
~ (bitwise compliment) 'flipping' bits. complement form due to a signed binary
number.  Bitwise operators are
used for testing the bits
<< (left shift) Binary Left Shift Operator. The left operands value is moved left A << 2 will give 240 which is 1111 0000 (or) shifting them to the
by the number of bits specified by the right operand.
left (or) right.

Binary Right Shift Operator. The left operands value is moved  These Operators may not
>> (right shift) A >> 2 will give 15 which is 1111
right by the number of bits specified by the right operand. be applicable to float (or)
double.
 Java defines several
Shift right zero fill operator. The left operands value is moved
>>> (zero fill right shift) right by the number of bits specified by the right operand and bitwise operators, which
A >>>2 will give 15 which is 0000 1111
shifted values are filled up with zeros. can be applied to the
integer types, long, int,
short, char, and byte.29
Examples of Bitwise Operator

 Bitwise operator works on bits and


Special Operator
performs the bit-by-bit operation.  The special Operators are instance of operator and Member selection
 Assume if a = 60 and b = 13; operator (or) Dot operator (.).
 Now in binary format they will be as
follows −   Instance of Operator: This operator determines whether the object
 a = 0011 1100 belongs to a particular class (or) not.
 b = 0000 1101 Example : Person instance of student;
• ------------------------
 It is true if the object “person” belongs to the class “student”;
 a&b = 0000 1100
otherwise it is false.
 a|b = 0011 1101
 a^b = 0011 0001  Dot Operator: The Dot Operator (.) is used to access the instance
 ~a = 1100 0011 variables and methods of class objects.
 Example: person age //Reference to the variable age.
It is also used to access classes and sub-packages from a
package.
30
SELECTION STATEMENTS OF JAVA

 Java supports the following selection


statements. If Statement:
• 1.If Statement.
 The if statement is a powerful decision making
• 2.Switch Statement statement and is used to control the flow of execution
• 3.Conditional Operation Statement. of statements.

 This statement allows you to control the flow of  The syntax is –


program execution based upon conditions, only If(Condition)
during run time.
 The if statement may be implemented in different
 These statements are also called “Control (or) forms.
Decision Making” statements They are:
1. Simple if statement.
2. If …else statement.
3. Nested if …else statement.
4. Else if ladder.

31
If Statement:

If…Else Statement:
 The syntax (or) general form of a simple if  This statement is an extension of the simple if statement. The syntax
statement is. is:
 If(Condition)  If(condition)
• { {
• True-Block statement;
statement-block;
}
• } else
• Statement x; {
 Here, the statement – Block may be a single False – Block statement;
statement (or) a group of statements. }
 If the condition is true, the statement – block will Statement – x;
be executed.
 If the condition is true, then the true – statement Block is executed.
 Otherwise, the statement – Block will be skipped Other wise, the False - statement Block is executed.
and the Execution will jump to statement – X.  In both these cases, the control is transferred sub-sequently to the
statement –x.
 In either case , either True –Block (or) False – Block will be executed
but not the both.
32
Nested If Statement Else if Ladder:

When a series of decisions are involved, we use more than one if…else statement
is Nested form.  The way of putting if’s together when multipath decisions are involved. A
multiple decision is a chain of if’s in which the statement is associated.
If(Condition 1)
{  The syntax of else if ladder is:
if(Condition 2) If(Condition 1)
{ statement 1;
Statement 1; else if(Condition 2)
} statement 2;
else else if(Condition N)
{ statement-n;
Statement 2; else
} default statement;
} Statement-x;
else
{  This construction is known as the else if ladder. The condition are evaluated
Statement 3; from top to down ward. As soon as the true condition is found. The statement
} associated with it is executed and the control is transferred to the statement –
Statement -X ; x;
 When all conditions become false, then the final else containing the default
Hence, if the condition 1 false, the statement 3 is executed. Other wise, continue statement will be executed.
to perform the condition 2.
If condition 2 is False, the statement 1 will be executed. Other wise the
statement 2 will be executed and then the control will be transferred to the
statement-x.
33
Switch Statement: Conditional Operator
 The switch statement tests the value of a given variable (or) condition
against a list of case values and when a match is found, a block of  This operator is a combination of ? And : And takes three
statement associated with that case is executed..
operators. This operator is known as Conditional Operator.
 The syntax of switch statement is:
The general form is:
• Switch(Expression) Conditional Expression1?Expression 2:Expression 3;
• {
• case value-1;
• Block-1;
– break;
• case value-2;
• Block-2;
• break;
• case value-N;
• Block-N;
• break;
• default:
• default-block;
• break;
• }

34
Iteration Statements in Java:
While Loop: The Do-While Loop:
 Java provides three loop (or) Iterative statements.  The Do-while loop always executes its body at
least once because its condition expression is
 They are: at the bottom of the loop.
 1. While Loop: While loop is Java’s most fundamental looping
statement. It repeats a statement (or) Block while its controlling  Initialization;
expression is true. Do
{
 Initialization; body of the loop;
• While(Condition) }while(Condition);
• {
• Body of loop;  Each iteration of the Do-while loop executes
• } the “body of the loop” and then evaluates the
conditional expression.
 The conditions can be any boolean expression. The “Body of Loop” will If the condition is true, the loop will repeats.
be executed as long as the conditional expression is “True”. When the Otherwise the loop terminates.
condition becomes false, control passes to the next line of the code
immediately following the loop. The while is an “Entry Control Loop”
This loop is also called as the ExitControlLoop.
statement.

35
For Loop:
 The For loop is another “Entry Control loop”.
Break Statement :
 In Java, the break statement has 3 uses.
 The general form of the for loop is. 1.It terminates a statement sequence in a switch statement.
 For(Initialization; Condition; Increment/Decrement) 2.It can be used to exit a loop.
{ 3.It can be used as a civilized form of a go to statement.
Body of the loop;
 The syntax is
}  break;

Continue Statement:
The Java continue statement stops one iteration in a loop and
JUMP STATEMENTS: continues to the next iteration.
 Jump statements in Java, transfer the control to another part of your
program.
This statement lets you skip particular iterations without stopping a
 Java supports 3 Jump statements. They are:
loop entirely. ...
• 1.Break

 That's where the continue statement comes in.
2.Continue
• 3. Return
The Java continue statement is used to skip the current iteration of a
loop in Java
36
Example on Continue Statement:
ContinueExample.java
//
Java Program to demonstrate the use of continue statement  
//inside the for loop.  
public class ContinueExample {  
public static void main(String[] args) {  
    //for loop  
    for(int i=1;i<=10;i++){  
        if(i==5){  
            //using continue statement  
            continue;//it will skip the rest statement  
        }  
        System.out.println(i);  
    }  
}  
}  

37
Return Statement:

 A return statement causes the Sample Program on Return Statement:


program control to transfer back to import java.util.*;  
the caller of a method.   public class ReturnExample4 {  
       List display()  
    {  
 Every method in Java is declared          List list=new ArrayList();  
         list.add("Java");  
with a return type and it is          list.add("C++");  
mandatory for all java methods.          list.add("Python");  
        return list;  
    }  
 A return type may be a primitive     public static void main(String[] args) {  
    ReturnExample4 e =new ReturnExample4();  
type like int, float, double, a     System.out.println(e.display());  
reference type or void type(returns }  
nothing). }

Output:
[Java, C++, Python]
38
Scope and Lifetime of a Variable

Variable Scope Lifetime


 The scope of a variable refers to the areas or Instance variable Throughout the class Until the object is
except in static available in the
the sections of the program in which the methods memory
variable can be accessed, and the lifetime of a Class variable Throughout the class Until the end of the
variable indicates how long the variable stays program
alive in the memory. Local variable Within the block in Until the control
which it is declared leaves the block in
which it is declared
 The scope of a variable is the part of a
program where the variable is known.
Parameters and variables defined inside a
function are not visible from outside. Hence,
they have a local scope. ... The lifetime of a
variable is the period throughout which the
variable exits in the memory of your Java
program.

39
THANK YOU

40

You might also like