SlideShare a Scribd company logo
CS3391-OBJECT ORIENTED PROGRAMMING
UNIT I INTRODUCTION TO OOP AND JAVA
Overview of OOP – Object-oriented programming paradigms – Features of Object Oriented
Programming – Java Buzzwords – Overview of Java – Data Types, Variables and Arrays –
Operators – Control Statements – Programming Structures in Java – Defining classes in
Java – Constructors Methods -Access specifiers – Static members- Java Doc comments.
TEXT BOOKS:
1. Herbert Schildt, “Java: The Complete Reference”, 11 th Edition, McGraw Hill
Education, New Delhi, 2019
2. Herbert Schildt, “Introducing JavaFX 8 Programming”, 1 st Edition, McGraw Hill
Education, New Delhi, 2015
Overview of OOP -Basic concepts of object-oriented programming
paradigm
OBJECT ORIENTED PROGRAMMING (OOP):
• Object-oriented programming Systems (OOPs) is a programming paradigm based on the concept
of ―objects that contain
• Data and methods, instead of just functions and procedures.
• Purpose Of Oops-increase the flexibility and maintainability of programs. (code optimization & no
redundant code)
• Object-oriented programming brings together data and its behavior (methods) into a single entity
(object).
• Simula is the first object-oriented programming language.
• Many of the most widely used programming languages (such as C++, Java, Python etc.)
are multiparadigms.
Features of object-oriented programming
• The basic concepts of OOP are as follows:
 Object
 Classes
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction
 Dynamic binding
 Message Passing
object oriented programming unit one ppt
Overview of java
• Java is an object-oriented programming language was
originally developed by Sun Microsystems which was
initiated by James Gosling and released in early 1990 .
• James Gosling, often called as the father of Java
• In initial stage java was called as 'Oak. ‘
• Later it was renamed as “java” in 1995.
HISTORY OF
JAVA
HISTORY OF
JAVA
object oriented programming unit one ppt
CLASS
• Class is a user-defined blueprint or prototype
from which objects are created.
• For Example: Student is a class , particular
student named Ravi is an object of a class.
• Syntax:
• Example:
Class class_name
{………
}
Class Student
{………..
}
OBJECT
• Object is the basic run time entity
• It is the instances of class
• It is a combination of data and its methods(functions)
• Example: Student
• Syntax for creating objects:
• The object of a class can be created by using the new keyword
• Example:
class_name object_name = new class_name();
Student s=new Student();
object oriented programming unit one ppt
INHERITANCE
• Inheritance is a process by which object of one class acquires
the properties of objects of another class.
• New classes are created from the existing classes.
• The new class created is called “derived class” or “child
class” and the existing class is known as the “base class” or
“parent class”.
• The derived class now is said to be inherited from the base
class.
• Old class- Base Class(Super Class)
• New class-Derived Class(Sub Class)
object oriented programming unit one ppt
POLYMORPHISM
• Polymorphism, A Greek Term, means the ability to do more
than one form.
• The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.
• Another Example:
 If you are in classroom-student
 If you are in market-customer
 If you are in home that time-son,daughter,parent
Abstraction
• Abstraction refers to the act of representing essential features
without including the background details or explanations.
• i.e., Abstraction means hiding lower-level details and exposing
only the essential and relevant details to the users.
• For Example: - Consider an ATM Machine; All are performing
operations on the ATM machine like cash withdrawal, money
transfer, retrieve mini-statement…etc. but we can't know
internal details about ATM.
Encapsulation
• Wrapping of data and method together into a single unit is
known as Encapsulation.
Dynamic Binding
• Dynamic binding in C++ is a practice of connecting the
function calls with the function definitions at run time.
Message passing
• An object–oriented program comprises a set
of objects that communicate with each other.
• Message passing involves specifying the name of the object, the
name of the method (message) and the information to be sent.
• Example:
• Where,
• Employee – object name
• getName – method name
• (message) name - information
Employee.getName(name);
Java Buzzwords
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
object oriented programming unit one ppt
 Simple:
• Java is Easy to write and more readable and eye catching.
• Most of the concepts are drawn from C++ thus making
Java learning simpler.
 Secure:
• Java provides a secure means of creating Internet
applications and to access web applications.
• Java enables the construction of secured, virus-free.
 Object Oriented:
• Java programming is pure object-oriented programming
language. Like C++, Java provides most of the object
oriented features.
 Robust:
• Java encourages error-free programming by being
strictly typed and performing run-time checks.
Platform Independent:
• Unlike C, C++, when Java program is compiled, it is not
compiled into platform-specific machine code, rather it is
converted into platform independent code called bytecode.
• The Java bytecodes are not specific to any processor. They can
be executed in any computer without any error.
• Because of the bytecode, Java is called as Platform
Independent.
object oriented programming unit one ppt
Portable:
• Java bytecode can be distributed over the
web and interpreted by Java Virtual Machine
(JVM)
• Java programs can run on any platform
(Linux, Window, Mac)
• Java programs can be transferred over world
wide web.
Architecture Neutral:
• Java is not tied to a specific machine or operating system
architecture.
• Machine Independent i.e. Java is independent of hardware.
• Bytecode instructions are designed to be both easy to
interpret on any machine and easily translated into native
machine code.
Dynamic and Extensible:
• Java is a more dynamic language than C or C++. It
was developed to adapt to an evolving environment.
• Java programs carry with them substantial amounts
of run-time information that are used to verify and
resolve accesses to objects at run time.
 Interpreted:
• Java supports cross-platform code through the use of Java
bytecode.
• The Java interpreter can execute Java Bytecodes directly on any
machine to which the interpreter has been ported.
 High Performance:
• Bytecodes are highly optimized.
• JVM can execute the bytecodes much faster.
• With the use of Just-In-Time (JIT) compiler, it enables high
performance.
 Multithreaded:
• Java provides integrated support for multithreaded programming.
• Using multithreading capability, we can write programs that can
do many tasks simultaneously.
• The benefits of multithreading are better responsiveness and real-
time behavior.
 Distributed:
• Java is designed for the distributed environment for the Internet
because it handles TCP/IP protocols.
• Java programs can be transmit and run over internet.
JAVA SOURCE FILE - STRUCTURE – COMPILATION
 The java source file:
• A Java source file is a plain text file containing Java source
code and having .java extension.
 Java Program Structure:
• Java program may contain many classes of which only one
class defines the main method.
object oriented programming unit one ppt
object oriented programming unit one ppt
Main Method Class :
• Every Java Standalone program requires a main method as its
starting point.
• A Simple Java Program will contain only the main method class.
 Syntax for writing main:
public static void main(String arg[])
Compiling and running a java program in command prompt
 Step 1:
• Set the path of the compiler as follows (type this in command prompt):
• Set path=”C:ProgramFilesJavajdk1.6.0_20bin”;
 Step 2:
• To create a Java program, ensure that the name of the class in the file is
the same as the name of the file.
 Step 3:
• Save the file with the extension .java (Example: HelloWorld.java)
 Step 4: To compile the java program use the command javac as follows:
javac HelloWorld.java
 Step 5:
• To run java program use the command java as follows:
java HelloWorld
Example 1: A First Java Program:
public class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Save: HelloWorld.java
Compile: javac HelloWorld.java
Run: java HelloWorld
Output: Hello World
A Java Program for getting input from user: Scanner object
import java.util.Scanner; // Import the Scanner class
class userinput
{
public static void main(String[] args)
{
int x, y, sum;
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Type a number:");
x = myObj.nextInt(); // Read user input
System.out.println("Type another number:"); OUTPUT:
y = myObj.nextInt(); // Read user input Type a number:10
sum = x + y; Type another number:5
System.out.println("Sum is: " + sum); // Output user input Sum is: 15
}
}
Using BufferReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args)
throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Reading data using readLine
String name = reader.readLine();
// Printing the read line
System.out.println(name); OUTPUT:
} CSE
} CSE
JAVA – DATA TYPES
• Data type is used to allocate sufficient
memory space for the data.
• Data types specify the different sizes and
values that can be stored in the variable.
• Every variable in java must be declared with a
data type.
Data types in Java are of two types:
Primitive data types (Intrinsic or built-in types ) :-
The primitive data types include boolean, char, byte,
short, int, long, float and double.
Non-primitive data types (Derived or Reference
Types): The non-primitive data types include Classes,
Interfaces, Strings and Arrays.
Primitive Types:
• Primitive data types are those whose
variables allow us to store only one value and
do not allow storing multiple values of same
type.
There are eight primitive types in Java:
 Integer Types:
1. int
2. short
3. long
4. byte
 Floating-point Types:
5. float
6. double
 Others:
7. char
8. Boolean
Integer Types:
• The integer types are form numbers without
fractional parts.
• Negative values are allowed. Java provides
the four integer types shown below:
object oriented programming unit one ppt
Floating-point Types:
• The floating-point types denote numbers with
fractional parts.
Char:
• Char data type is used to store any character.
• Example: char letterA ='A'
Boolean:
• boolean data type represents one bit of information.
• There are only two possible values: true and false.
• This data type is used for simple flags that track true/false conditions.
• Default value is false.
• Example: boolean one = true
Variables
• Variables are containers(memory) for storing data values.
Declaring (Creating) Variables:
Syntax:
• Where type is one of Java's types (such as int or String)
• Variable_name is the name of the variable (such as x or name).
• The equal sign is used to assign values to the variable.
Data _type variable_name=value;
Example
• Create a variable called name of data type String and assign it the value
"John“
public class Main
{
public static void main(String[] args) {
String name = "John";
System.out.println(name); output:
} John
}
• Example
Create a variable called myNum of data_type int and assign it
the value 15
public class Main
{
public static void main(String[] args)
{
int myNum = 15;
System.out.println(myNum); output:
} 15
}
• Declare a variable without assigning the value, and assign
the value later.
public class Main {
public static void main(String[] args) {
int myNum;
myNum = 15;
System.out.println(myNum);
} output:
} 15
• Change the valueof myNum from 15 to 20:
public class Main {
public static void main(String[] args) {
int myNum = 15;
myNum = 20; // myNum is now 20
System.out.println(myNum);
}
}
Output:
20
Final Variables
• Use the final keyword (if we declare the variable as "final" or "constant", which means
unchangeable and read-only):
public class Main {
public static void main(String[] args)
{
final int myNum = 15;
myNum = 20; // will generate an error
System.out.println(myNum);
}
} output:
• Main.java:4: error: cannot assign a value to final variable myNum
myNum = 20;
^
1 error
Java Arrays
• An array is a collection of similar type of elements which
has contiguous memory location.
• Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
• 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.
• To declare an array, define the variable type with square
brackets:
• To create an array of integers,
String cars[];
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int mynum[]={10,20,30,40};
• Advantage of Array:
• • Code Optimization: It makes the code
optimized; we can retrieve or sort the data
easily.
• • Random access: We can get any data
located at any index position.
• Disadvantage of Array:
• Size Limit: We can store only fixed size of
elements in the array. It doesn't grow its size
at runtime.
Change an Array Element
• To change the value of a specific element,
refer to the index number:
• Example
• String[] cars = {“Toyota", "BMW", "Ford",
“Innova"};
Cars[0]=“Kia_Carrons”;
public class Main
{
public static void main(String[] args)
{
String[] cars = {“Toyota", "BMW", "Ford", “Innova"};
cars[0] = “Kia_Carrons";
System.out.println(cars[0]);
output:
} Kia_Carrons
}
Array Length
• To find out how many elements an array has, use
the length property
public class Main
{
public static void main(String[] args)
{
String[] cars = {“Toyota", "BMW", "Ford", “innova"};
System.out.println(cars.length);
}
}
Output:
4
Types of Array:
There are two types of array.
1. One-Dimensional Arrays
2. Multidimensional Arrays
One-Dimensional Array:
• A one-dimensional array is an array in which
the elements are stored in one variable name
by using only one subscript.
• Example:
• String[] cars = {“Toyota",
"BMW", "Ford", “Innova"};
public class Main
{
public static void main(String[] args)
{
String[] cars = {“Toyota", "BMW", "Ford", “Innova"};
cars[0] = “Kia_Carrons";
System.out.println(cars[0]);
output:
} Kia_Carrons
}
Multidimensional Arrays
• A multidimensional array is an array of arrays.
• Multidimensional arrays are useful when you
want to store data as a tabular form, like a
table with rows and columns.
• To create a two-dimensional array, add each
array within its own set of curly braces:
• Example
• myNumbers is now an array with two arrays
as its elements.
int [ ] [ ] myNumbers={ {1,2,3,4}, {5,6,7} };
Example
public class Main
{
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]);
}
}
Output:
7
Java Operators
• Operators are used to manipulate primitive
data types.
• Operators are used to perform operations on
variables and values.
• Java operators can be classified as unary,
binary, or ternary—meaning taking one, two,
or three arguments, respectively.
Java Unary Operator
• The Java unary operators require only one
operand.
• Unary operators are used to perform various
operations .
• i.e.:
incrementing/decrementing a value by one
class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++); //10(11)
System.out.println(++x); //12
System.out.println(x--); //12(11)
System.out.println(--x); //10
}
}
Different categories of operator:
1. Assignment operator
2. Arithmetic operator
3. Relational operator
4. Logical operator
5. Bitwise operator
6. Conditional operator
object oriented programming unit one ppt
Java Assignment Operator
• The java assignment operator statement has
the following syntax:
<variable> = <expression>
Java Assignment Operator Example
class assignmentop{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4; //a=a+4 (a=10+4)
b-=4; //b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Java Arithmetic Operators
• Java arithmetic operators are used to perform
addition, subtraction, multiplication, and
division.
• They act as basic mathematical operations.
object oriented programming unit one ppt
Java Arithmetic Operator Example:
class arithmeticop
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}
}
Relational Operators
• Relational operators in Java are used to
compare 2 or more objects.
• Java provides six relational operators: Assume
variable A holds 10 and variable B holds 20,
then:
object oriented programming unit one ppt
public class RelationalOperatorsDemo {
public RelationalOperatorsDemo()
{
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 static void main(String args[])
{
RelationalOperatorsDemo d1=new RelationalOperatorsDemo();
}
}
Logical Operators
• Logical operators return a true or false value based on the
state of the Variables.
• Given that x and y represent boolean expressions, the
boolean logical operators are defined in the Table below.
public class LogicalOperatorsDemo
{
void LogicalOperatorsDemo()
{
boolean x = true;
boolean y = false;
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 : " + (!x));
}
public static void main(String args[])
{
LogicalOperatorsDemo d1=new LogicalOperatorsDemo();
d1.LogicalOperatorsDemo();
}
}
Bitwise Operators
• Java provides Bit wise operators to
manipulate the contents of variables at the
bit level.
Conditional Operators
• The Conditional operator is the only ternary (operator takes
three arguments) operator in Java.
• The operator evaluates the first argument and, if true,
evaluates the second argument.
• If the first argument evaluates to false, then the third
argument is evaluated.
• The conditional operator is the expression equivalent of the
if-else statement.
public class TernaryOperatorsDemo {
public TernaryOperatorsDemo()
{ int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : " + z);
}
public static void main(String args[])
{
TernaryOperatorsDemo d1=new TernaryOperatorsDemo();
}
}
object oriented programming unit one ppt
object oriented programming unit one ppt
object oriented programming unit one ppt
CONTROL-FLOW STATEMENTS
• Java Control statements control the order of execution
in a java program, based on data values and conditional
logic.
• There are three main categories of control flow
statements;
• Selection statements: if, if-else and switch.
• Loop statements: while, do-while and for.
• Transfer statements: break, continue, return, try-catch-
finally and assert.
Selection statements (Decision Making Statement)
• There are two types of decision making
statements in Java. They are:
• if statements
• if-else statements
• nested if statements
• switch statements
if Statement:
• An if statement consists of a Boolean
expression followed by one or more
statements.
• Block of statement is executed when the
condition is true otherwise no statement will
be executed.
Syntax:
if(<conditional expression>)
{
< Statement Action>
}
object oriented programming unit one ppt
public class IfStatementDemo {
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
System.out.println("b > a");
}
}
Output:
$java IfStatementDemo
b > a
if-else Statement:
• The if/else statement is an extension of the if statement.
• if statement fails, the statements in the else block are executed.
• Syntax:
• The if-else statement has the following syntax:
if(<conditional expression>)
{
< Statement Action1>
}
else
{
< Statement Action2>
}
object oriented programming unit one ppt
Example:
public class IfElseStatementDemo {
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b) {
System.out.println("a > b");
}
else {
System.out.println("b > a"); Output: b > a
}
}
}
Nested if Statement:
• Nested if-else statements, is that using one if
or else if statement inside another if or else if
statement(s).
Syntax:
if(condition1)
{
if(condition2)
{
//Executes this block if condition is True
}
else
{
//Executes this block if condition is false
}
}
else
{
//Executes this block if condition is false
}
object oriented programming unit one ppt
Example-nested-if statement:
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i ==10)
{
if (i < 15)
{
System.out.println("i is smaller than 15");
}
else
{
System.out.println("i is greater than 15");
}
}
else
{
System.out.println("i is greater than 15");
}
}
}
Output:
i is smaller than 15
Switch Statement:
• The switch case statement, also called a case statement is a
multi-way branch with several choices.
• A switch is easier to implement than a series of if/else
statements.
• A switch statement allows a variable to be tested for equality
against a list of values.
• Each value is called a case, and the variable being switched
on is checked for each case.
Syntax:
switch (<expression>)
{
case label1: <statement1>
case label2: <statement2>
…
case labeln: <statementn>
default: <statement>
}
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Looping Statements (Iteration Statements)
• While Statement :
• The while statement is a looping control
statement that executes a block of code while
a condition is true.
• It is entry controlled loop.
object oriented programming unit one ppt
object oriented programming unit one ppt
Example:
public class WhileLoopDemo {
public static void main(String[] args) { int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++); } } }
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
do-while Loop Statement
• do while loop checks the condition after executing the
statements atleast once.
• Therefore it is called as Exit Controlled Loop.
• The do-while loop is similar to the while loop, except that the
test is performed at the end of the loop instead of at the
beginning.
object oriented programming unit one ppt
object oriented programming unit one ppt
• public class DoWhileLoopDemo {
• public static void main(String[] args)
• {
• int count = 1;
• System.out.println("Printing Numbers from 1 to 10");
• do {
• System.out.println(count++);
• } while (count <= 10);
• }
• }
For Loops
• The for loop is a looping construct which can
execute a set of instructions a specified number of
times.
• It‘s a counter controlled loop. A for statement
consumes the initialization, condition and
increment/decrement in one line.
• It is the entry controlled loop.
object oriented programming unit one ppt
Example
public class ForLoopDemo {
public static void main(String[] args)
{
System.out.println("Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++)
{
System.out.println(count);
}
}
}
Transfer Statements / Loop Control Statements/ Jump
Statements)
• 1. break statement
• 2. continue statement
Using break Statement:
• The break keyword is used to stop the entire loop.
• The break keyword must be used inside any loop or
a switch statement.
• The break keyword will stop the execution of the
innermost loop and start executing the next line of
code after the block.
object oriented programming unit one ppt
Using continue Statement:
• The continue keyword can be used in any of
the loop control structures.
• It causes the loop to immediately jump to
the next iteration of the loop.
object oriented programming unit one ppt
Defining Classes in java
• In object-oriented programming, a class is a basic
building block.
• It can be defined as template that describes the
data and behaviour associated with the class
instantiation.
• A class can also be called a logical template to
create the objects that share common properties
and methods.
• For example, an Employee class may contain
all the employee details in the form of
variables and methods.
• If the class is instantiated i.e. if an object of
the class is created (say e1), we can access all
the methods or properties of the class.
• Java provides a reserved keyword class to
define a class.
• The keyword must be followed by the class
name.
• Inside the class, we declare methods and
variables.
• In general, class declaration includes the
following in the order as it appears:
• Modifiers: A class can be public or has default access.
• Class keyword: The class keyword is used to create a class.
• Class name: The name must begin with an initial letter
(capitalized by convention).
• Superclass (if any): The name of the class's parent
(superclass), if any, preceded by the keyword extends. A class
can only extend (subclass) one parent.
• Body: The class body surrounded by braces, { }.
object oriented programming unit one ppt
Example 1
object oriented programming unit one ppt
object oriented programming unit one ppt
Constructor
• Constructor is a special type of method that
is used to initialize the object.
• Constructor is invoked at the time of object
creation.
• At the time of calling constructor, memory for
the object is allocated in the memory.
• Every time an object is created using the
new() keyword, at least one constructor is
called.
• if there is no constructor available in the
class. It calls a default constructor
• In such case, Java compiler provides a default
constructor by default.
object oriented programming unit one ppt
object oriented programming unit one ppt
Rules for creating Java constructor
• There are three rules defined for the
constructor.
The Constructor name must be the same as
its class name
A Constructor must have no return type
A Java constructor cannot be static, final,
Types of Java constructors
• There are two types of constructors in Java:
Default constructor (no-arg constructor)
Parameterized constructor
Java Default Constructor
object oriented programming unit one ppt
Java Parameterized Constructor
• A constructor which has a specific number of
parameters is called a parameterized
constructor.
object oriented programming unit one ppt
object oriented programming unit one ppt
Constructor Overloading in Java
• Constructor overloading in Java is a technique of having
more than one constructor with different parameter lists.
• They are arranged in a way that each constructor performs
a different task.
object oriented programming unit one ppt
object oriented programming unit one ppt
METHODS
• A Java method is a collection of statements
that are grouped together to perform an
operation.
• The syntax shown above includes:
•  modifier: It defines the access type of the method
and it is optional to use.
•  returnType: Method may return a value.
•  Method_name: This is the method name. The
method signature consists of the method name and the
parameter list.
•  Parameter List: The list of parameters, it is the type,
order, and number of parameters of a method. These
are optional, method may contain zero parameters.
•  Method body: The method body defines what the
method does with statements.
object oriented programming unit one ppt
class method
{
void display() //Method declaration
{
System.out.print(“Hello World”);
}
public static void main(String args[])//main function
{
method m1=new method();
m1.display();
}
Output:
Hello World
object oriented programming unit one ppt
ACCESS SPECIFIERS
• Access specifiers are used to specify the
visibility and accessibility of a class
constructors, member variables and methods.
• One of four different access modifiers:
1. Public
2. Private
3. Protected
4. Default (package)
1. Public (anything declared as public can be accessed from anywhere):
• A variable or method declared/defined with
the public modifier can be accessed
anywhere in the program through its class
objects, through its subclass objects and
through the objects of classes of other
packages also.
2. Private (anything declared as private can’t be seen outside of the class):
• The instance variable or instance methods
declared/initialized as private can be accessed
only by its class.
• Even its subclass is not able to access the private
members.
3. Protected (anything declared as protected can be accessed by classes in the same package and subclasses in the other packages):
• The protected access specifier makes the instance variables
and instance methods visible to all the classes, subclasses of
that package and subclasses of other packages.
4. Default (can be accessed only by the classes in the same package):
• The default access modifier is friendly.
• This is similar to public modifier except only
the classes belonging to a particular package
knows the variables and methods.
object oriented programming unit one ppt
IN TOOLS PACKAGE
Simple.java
package tools;
public class Simple
{
public int marks = 6;
}
IN SAME PACKAGE
B.java
public class B
{
int marks = 10;
}
import tools.Simple;
class Test
{
public static void main(String
args[])
{
Simple obj = new Simple();
System.out.println(obj.marks);
B obj1 = new B();
System.out.println(obj1.marks);
}
• Output:
6
10
Static Members
• The static keyword in Java is mainly used for
memory management.
• The static keyword in Java is used to share the
same variable or method of a given class.
• The users can apply static keywords with
variables, methods, blocks, and nested classes
object oriented programming unit one ppt
object oriented programming unit one ppt
object oriented programming unit one ppt
object oriented programming unit one ppt
object oriented programming unit one ppt
import java.io.*;
class staticdemo
{
int a=10,b=20,c=30; //non static variable
static int count; //static variable
static void SMdemo() //static method
{
count=100;
}
static // static block creation
{
System.out.println("java program for static");
}
static class innerclass //static class creation
{
static int count2=200;
}
staticdemo() //constructor creation
{
count=count+1;
}
}
class Test1
{
public static void main(String args[])
{
staticdemo.SMdemo(); //static method calling
staticdemo st1=new staticdemo();
staticdemo st2=new staticdemo();
System.out.println("non-static variable"+st1.a); // non-static variable calling
System.out.println("object count" +staticdemo.count); //static variable calling
System.out.println("Static class called"+staticdemo.innerclass.count2); // static class calling
}
}
java program for static
non-static variable10
object count102
Static class called200
JavaDoc Comments
• Javadoc is a tool which comes with JDK and it is used for
generating Java code documentation in HTML format
from Java source code which has required
documentation in a predefined format.
Format:
• A Javadoc comment precedes similar to a multi-line comment except that
it begins with a forward slash followed by two asterisks (/**) and ends
with a */
• Each /** . . . */ documentation comment contains free-form text
followed by tags.
• A tag starts with an @, such as @author or @param.
• The first sentence of the free-form text should be a summary statement.
• The javadoc utility automatically generates summary pages that extract
these sentences.
• In the free-form text, you can use HTML modifiers such as <h1>...</h1>
for heading, <p>...</p> .
object oriented programming unit one ppt
object oriented programming unit one ppt
object oriented programming unit one ppt
object oriented programming unit one ppt
object oriented programming unit one ppt
Ad

More Related Content

Similar to object oriented programming unit one ppt (20)

1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
jyoti_lakhani
 
Untitled presentation about object oriented.pptx
Untitled presentation about object oriented.pptxUntitled presentation about object oriented.pptx
Untitled presentation about object oriented.pptx
janetvidyaanancys
 
Java Programming Fundamentals: Complete Guide for Beginners
Java Programming Fundamentals: Complete Guide for BeginnersJava Programming Fundamentals: Complete Guide for Beginners
Java Programming Fundamentals: Complete Guide for Beginners
Taranath Jaishy
 
U1 JAVA.pptx
U1 JAVA.pptxU1 JAVA.pptx
U1 JAVA.pptx
madan r
 
Jaga codinghshshshshehwuwiwijsjssnndnsjd
Jaga codinghshshshshehwuwiwijsjssnndnsjdJaga codinghshshshshehwuwiwijsjssnndnsjd
Jaga codinghshshshshehwuwiwijsjssnndnsjd
rajputtejaswa12
 
JAVA PROGRAMING NOTE FOR BEGINNERS 20242
JAVA PROGRAMING NOTE FOR BEGINNERS 20242JAVA PROGRAMING NOTE FOR BEGINNERS 20242
JAVA PROGRAMING NOTE FOR BEGINNERS 20242
boatengsolo963
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
prat0ham
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
VijalJain3
 
ppt_on_java.pptx
ppt_on_java.pptxppt_on_java.pptx
ppt_on_java.pptx
MAYANKKUMAR492040
 
PJ_M01_C01_PPT_Introduction to Object Oriented Programming Using Java.pdf
PJ_M01_C01_PPT_Introduction to Object Oriented Programming Using Java.pdfPJ_M01_C01_PPT_Introduction to Object Oriented Programming Using Java.pdf
PJ_M01_C01_PPT_Introduction to Object Oriented Programming Using Java.pdf
projectfora2
 
Introduction to Java Programming.pdf
Introduction to Java Programming.pdfIntroduction to Java Programming.pdf
Introduction to Java Programming.pdf
AdiseshaK
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
Object Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for studentsObject Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
Partnered Health
 
Share Unit 1- Basic concept of object-oriented-programming.ppt
Share Unit 1- Basic concept of object-oriented-programming.pptShare Unit 1- Basic concept of object-oriented-programming.ppt
Share Unit 1- Basic concept of object-oriented-programming.ppt
hannahrroselin95
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Prof. Dr. K. Adisesha
 
j-chap1-Basics.ppt
j-chap1-Basics.pptj-chap1-Basics.ppt
j-chap1-Basics.ppt
SmitaBorkar9
 
java slides
java slidesjava slides
java slides
RizwanTariq18
 
ITFT - Java Coding
ITFT - Java CodingITFT - Java Coding
ITFT - Java Coding
Blossom Sood
 
Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentation
dhananajay95
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
jyoti_lakhani
 
Untitled presentation about object oriented.pptx
Untitled presentation about object oriented.pptxUntitled presentation about object oriented.pptx
Untitled presentation about object oriented.pptx
janetvidyaanancys
 
Java Programming Fundamentals: Complete Guide for Beginners
Java Programming Fundamentals: Complete Guide for BeginnersJava Programming Fundamentals: Complete Guide for Beginners
Java Programming Fundamentals: Complete Guide for Beginners
Taranath Jaishy
 
U1 JAVA.pptx
U1 JAVA.pptxU1 JAVA.pptx
U1 JAVA.pptx
madan r
 
Jaga codinghshshshshehwuwiwijsjssnndnsjd
Jaga codinghshshshshehwuwiwijsjssnndnsjdJaga codinghshshshshehwuwiwijsjssnndnsjd
Jaga codinghshshshshehwuwiwijsjssnndnsjd
rajputtejaswa12
 
JAVA PROGRAMING NOTE FOR BEGINNERS 20242
JAVA PROGRAMING NOTE FOR BEGINNERS 20242JAVA PROGRAMING NOTE FOR BEGINNERS 20242
JAVA PROGRAMING NOTE FOR BEGINNERS 20242
boatengsolo963
 
Unit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rdUnit 1 Core Java for Compter Science 3rd
Unit 1 Core Java for Compter Science 3rd
prat0ham
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
VijalJain3
 
PJ_M01_C01_PPT_Introduction to Object Oriented Programming Using Java.pdf
PJ_M01_C01_PPT_Introduction to Object Oriented Programming Using Java.pdfPJ_M01_C01_PPT_Introduction to Object Oriented Programming Using Java.pdf
PJ_M01_C01_PPT_Introduction to Object Oriented Programming Using Java.pdf
projectfora2
 
Introduction to Java Programming.pdf
Introduction to Java Programming.pdfIntroduction to Java Programming.pdf
Introduction to Java Programming.pdf
AdiseshaK
 
Object Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for studentsObject Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
Partnered Health
 
Share Unit 1- Basic concept of object-oriented-programming.ppt
Share Unit 1- Basic concept of object-oriented-programming.pptShare Unit 1- Basic concept of object-oriented-programming.ppt
Share Unit 1- Basic concept of object-oriented-programming.ppt
hannahrroselin95
 
j-chap1-Basics.ppt
j-chap1-Basics.pptj-chap1-Basics.ppt
j-chap1-Basics.ppt
SmitaBorkar9
 
ITFT - Java Coding
ITFT - Java CodingITFT - Java Coding
ITFT - Java Coding
Blossom Sood
 
Advance java prasentation
Advance java prasentationAdvance java prasentation
Advance java prasentation
dhananajay95
 

Recently uploaded (20)

How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
Ancient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian HistoryAncient Stone Sculptures of India: As a Source of Indian History
Ancient Stone Sculptures of India: As a Source of Indian History
Virag Sontakke
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
Ad

object oriented programming unit one ppt

  • 1. CS3391-OBJECT ORIENTED PROGRAMMING UNIT I INTRODUCTION TO OOP AND JAVA Overview of OOP – Object-oriented programming paradigms – Features of Object Oriented Programming – Java Buzzwords – Overview of Java – Data Types, Variables and Arrays – Operators – Control Statements – Programming Structures in Java – Defining classes in Java – Constructors Methods -Access specifiers – Static members- Java Doc comments. TEXT BOOKS: 1. Herbert Schildt, “Java: The Complete Reference”, 11 th Edition, McGraw Hill Education, New Delhi, 2019 2. Herbert Schildt, “Introducing JavaFX 8 Programming”, 1 st Edition, McGraw Hill Education, New Delhi, 2015
  • 2. Overview of OOP -Basic concepts of object-oriented programming paradigm OBJECT ORIENTED PROGRAMMING (OOP): • Object-oriented programming Systems (OOPs) is a programming paradigm based on the concept of ―objects that contain • Data and methods, instead of just functions and procedures. • Purpose Of Oops-increase the flexibility and maintainability of programs. (code optimization & no redundant code) • Object-oriented programming brings together data and its behavior (methods) into a single entity (object). • Simula is the first object-oriented programming language. • Many of the most widely used programming languages (such as C++, Java, Python etc.) are multiparadigms.
  • 3. Features of object-oriented programming • The basic concepts of OOP are as follows:  Object  Classes  Encapsulation  Inheritance  Polymorphism  Abstraction  Dynamic binding  Message Passing
  • 5. Overview of java • Java is an object-oriented programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in early 1990 . • James Gosling, often called as the father of Java • In initial stage java was called as 'Oak. ‘ • Later it was renamed as “java” in 1995.
  • 9. CLASS • Class is a user-defined blueprint or prototype from which objects are created. • For Example: Student is a class , particular student named Ravi is an object of a class. • Syntax: • Example: Class class_name {……… } Class Student {……….. }
  • 10. OBJECT • Object is the basic run time entity • It is the instances of class • It is a combination of data and its methods(functions) • Example: Student
  • 11. • Syntax for creating objects: • The object of a class can be created by using the new keyword • Example: class_name object_name = new class_name(); Student s=new Student();
  • 13. INHERITANCE • Inheritance is a process by which object of one class acquires the properties of objects of another class. • New classes are created from the existing classes. • The new class created is called “derived class” or “child class” and the existing class is known as the “base class” or “parent class”. • The derived class now is said to be inherited from the base class.
  • 14. • Old class- Base Class(Super Class) • New class-Derived Class(Sub Class)
  • 16. POLYMORPHISM • Polymorphism, A Greek Term, means the ability to do more than one form. • The word "poly" means many and "morphs" means forms. So polymorphism means many forms.
  • 17. • Another Example:  If you are in classroom-student  If you are in market-customer  If you are in home that time-son,daughter,parent
  • 18. Abstraction • Abstraction refers to the act of representing essential features without including the background details or explanations. • i.e., Abstraction means hiding lower-level details and exposing only the essential and relevant details to the users. • For Example: - Consider an ATM Machine; All are performing operations on the ATM machine like cash withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal details about ATM.
  • 19. Encapsulation • Wrapping of data and method together into a single unit is known as Encapsulation.
  • 20. Dynamic Binding • Dynamic binding in C++ is a practice of connecting the function calls with the function definitions at run time.
  • 21. Message passing • An object–oriented program comprises a set of objects that communicate with each other.
  • 22. • Message passing involves specifying the name of the object, the name of the method (message) and the information to be sent. • Example: • Where, • Employee – object name • getName – method name • (message) name - information Employee.getName(name);
  • 23. Java Buzzwords • Simple • Secure • Portable • Object-oriented • Robust • Multithreaded • Architecture-neutral • Interpreted • High performance • Distributed • Dynamic
  • 25.  Simple: • Java is Easy to write and more readable and eye catching. • Most of the concepts are drawn from C++ thus making Java learning simpler.  Secure: • Java provides a secure means of creating Internet applications and to access web applications. • Java enables the construction of secured, virus-free.
  • 26.  Object Oriented: • Java programming is pure object-oriented programming language. Like C++, Java provides most of the object oriented features.  Robust: • Java encourages error-free programming by being strictly typed and performing run-time checks.
  • 27. Platform Independent: • Unlike C, C++, when Java program is compiled, it is not compiled into platform-specific machine code, rather it is converted into platform independent code called bytecode. • The Java bytecodes are not specific to any processor. They can be executed in any computer without any error. • Because of the bytecode, Java is called as Platform Independent.
  • 29. Portable: • Java bytecode can be distributed over the web and interpreted by Java Virtual Machine (JVM) • Java programs can run on any platform (Linux, Window, Mac) • Java programs can be transferred over world wide web.
  • 30. Architecture Neutral: • Java is not tied to a specific machine or operating system architecture. • Machine Independent i.e. Java is independent of hardware. • Bytecode instructions are designed to be both easy to interpret on any machine and easily translated into native machine code.
  • 31. Dynamic and Extensible: • Java is a more dynamic language than C or C++. It was developed to adapt to an evolving environment. • Java programs carry with them substantial amounts of run-time information that are used to verify and resolve accesses to objects at run time.
  • 32.  Interpreted: • Java supports cross-platform code through the use of Java bytecode. • The Java interpreter can execute Java Bytecodes directly on any machine to which the interpreter has been ported.  High Performance: • Bytecodes are highly optimized. • JVM can execute the bytecodes much faster. • With the use of Just-In-Time (JIT) compiler, it enables high performance.
  • 33.  Multithreaded: • Java provides integrated support for multithreaded programming. • Using multithreading capability, we can write programs that can do many tasks simultaneously. • The benefits of multithreading are better responsiveness and real- time behavior.  Distributed: • Java is designed for the distributed environment for the Internet because it handles TCP/IP protocols. • Java programs can be transmit and run over internet.
  • 34. JAVA SOURCE FILE - STRUCTURE – COMPILATION  The java source file: • A Java source file is a plain text file containing Java source code and having .java extension.  Java Program Structure: • Java program may contain many classes of which only one class defines the main method.
  • 37. Main Method Class : • Every Java Standalone program requires a main method as its starting point. • A Simple Java Program will contain only the main method class.  Syntax for writing main: public static void main(String arg[])
  • 38. Compiling and running a java program in command prompt  Step 1: • Set the path of the compiler as follows (type this in command prompt): • Set path=”C:ProgramFilesJavajdk1.6.0_20bin”;  Step 2: • To create a Java program, ensure that the name of the class in the file is the same as the name of the file.  Step 3: • Save the file with the extension .java (Example: HelloWorld.java)  Step 4: To compile the java program use the command javac as follows: javac HelloWorld.java  Step 5: • To run java program use the command java as follows: java HelloWorld
  • 39. Example 1: A First Java Program: public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World"); } } Save: HelloWorld.java Compile: javac HelloWorld.java Run: java HelloWorld Output: Hello World
  • 40. A Java Program for getting input from user: Scanner object import java.util.Scanner; // Import the Scanner class class userinput { public static void main(String[] args) { int x, y, sum; Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Type a number:"); x = myObj.nextInt(); // Read user input System.out.println("Type another number:"); OUTPUT: y = myObj.nextInt(); // Read user input Type a number:10 sum = x + y; Type another number:5 System.out.println("Sum is: " + sum); // Output user input Sum is: 15 } }
  • 41. Using BufferReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test { public static void main(String[] args) throws IOException { // Enter data using BufferReader BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // Reading data using readLine String name = reader.readLine(); // Printing the read line System.out.println(name); OUTPUT: } CSE } CSE
  • 42. JAVA – DATA TYPES • Data type is used to allocate sufficient memory space for the data. • Data types specify the different sizes and values that can be stored in the variable. • Every variable in java must be declared with a data type.
  • 43. Data types in Java are of two types: Primitive data types (Intrinsic or built-in types ) :- The primitive data types include boolean, char, byte, short, int, long, float and double. Non-primitive data types (Derived or Reference Types): The non-primitive data types include Classes, Interfaces, Strings and Arrays.
  • 44. Primitive Types: • Primitive data types are those whose variables allow us to store only one value and do not allow storing multiple values of same type.
  • 45. There are eight primitive types in Java:  Integer Types: 1. int 2. short 3. long 4. byte  Floating-point Types: 5. float 6. double  Others: 7. char 8. Boolean
  • 46. Integer Types: • The integer types are form numbers without fractional parts. • Negative values are allowed. Java provides the four integer types shown below:
  • 48. Floating-point Types: • The floating-point types denote numbers with fractional parts.
  • 49. Char: • Char data type is used to store any character. • Example: char letterA ='A' Boolean: • boolean data type represents one bit of information. • There are only two possible values: true and false. • This data type is used for simple flags that track true/false conditions. • Default value is false. • Example: boolean one = true
  • 50. Variables • Variables are containers(memory) for storing data values. Declaring (Creating) Variables: Syntax: • Where type is one of Java's types (such as int or String) • Variable_name is the name of the variable (such as x or name). • The equal sign is used to assign values to the variable. Data _type variable_name=value;
  • 51. Example • Create a variable called name of data type String and assign it the value "John“ public class Main { public static void main(String[] args) { String name = "John"; System.out.println(name); output: } John }
  • 52. • Example Create a variable called myNum of data_type int and assign it the value 15 public class Main { public static void main(String[] args) { int myNum = 15; System.out.println(myNum); output: } 15 }
  • 53. • Declare a variable without assigning the value, and assign the value later. public class Main { public static void main(String[] args) { int myNum; myNum = 15; System.out.println(myNum); } output: } 15
  • 54. • Change the valueof myNum from 15 to 20: public class Main { public static void main(String[] args) { int myNum = 15; myNum = 20; // myNum is now 20 System.out.println(myNum); } } Output: 20
  • 55. Final Variables • Use the final keyword (if we declare the variable as "final" or "constant", which means unchangeable and read-only): public class Main { public static void main(String[] args) { final int myNum = 15; myNum = 20; // will generate an error System.out.println(myNum); } } output: • Main.java:4: error: cannot assign a value to final variable myNum myNum = 20; ^ 1 error
  • 56. Java Arrays • An array is a collection of similar type of elements which has contiguous memory location. • Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. • 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.
  • 57. • To declare an array, define the variable type with square brackets: • To create an array of integers, String cars[]; String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; int mynum[]={10,20,30,40};
  • 58. • Advantage of Array: • • Code Optimization: It makes the code optimized; we can retrieve or sort the data easily. • • Random access: We can get any data located at any index position.
  • 59. • Disadvantage of Array: • Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime.
  • 60. Change an Array Element • To change the value of a specific element, refer to the index number: • Example • String[] cars = {“Toyota", "BMW", "Ford", “Innova"}; Cars[0]=“Kia_Carrons”;
  • 61. public class Main { public static void main(String[] args) { String[] cars = {“Toyota", "BMW", "Ford", “Innova"}; cars[0] = “Kia_Carrons"; System.out.println(cars[0]); output: } Kia_Carrons }
  • 62. Array Length • To find out how many elements an array has, use the length property public class Main { public static void main(String[] args) { String[] cars = {“Toyota", "BMW", "Ford", “innova"}; System.out.println(cars.length); } } Output: 4
  • 63. Types of Array: There are two types of array. 1. One-Dimensional Arrays 2. Multidimensional Arrays
  • 64. One-Dimensional Array: • A one-dimensional array is an array in which the elements are stored in one variable name by using only one subscript. • Example: • String[] cars = {“Toyota", "BMW", "Ford", “Innova"};
  • 65. public class Main { public static void main(String[] args) { String[] cars = {“Toyota", "BMW", "Ford", “Innova"}; cars[0] = “Kia_Carrons"; System.out.println(cars[0]); output: } Kia_Carrons }
  • 66. Multidimensional Arrays • A multidimensional array is an array of arrays. • Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows and columns. • To create a two-dimensional array, add each array within its own set of curly braces:
  • 67. • Example • myNumbers is now an array with two arrays as its elements. int [ ] [ ] myNumbers={ {1,2,3,4}, {5,6,7} };
  • 68. Example public class Main { public static void main(String[] args) { int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; System.out.println(myNumbers[1][2]); } } Output: 7
  • 69. Java Operators • Operators are used to manipulate primitive data types. • Operators are used to perform operations on variables and values. • Java operators can be classified as unary, binary, or ternary—meaning taking one, two, or three arguments, respectively.
  • 70. Java Unary Operator • The Java unary operators require only one operand. • Unary operators are used to perform various operations . • i.e.: incrementing/decrementing a value by one
  • 71. class OperatorExample { public static void main(String args[]) { int x=10; System.out.println(x++); //10(11) System.out.println(++x); //12 System.out.println(x--); //12(11) System.out.println(--x); //10 } }
  • 72. Different categories of operator: 1. Assignment operator 2. Arithmetic operator 3. Relational operator 4. Logical operator 5. Bitwise operator 6. Conditional operator
  • 74. Java Assignment Operator • The java assignment operator statement has the following syntax: <variable> = <expression>
  • 75. Java Assignment Operator Example class assignmentop{ public static void main(String args[]) { int a=10; int b=20; a+=4; //a=a+4 (a=10+4) b-=4; //b=b-4 (b=20-4) System.out.println(a); System.out.println(b); } }
  • 76. Java Arithmetic Operators • Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. • They act as basic mathematical operations.
  • 78. Java Arithmetic Operator Example: class arithmeticop { public static void main(String args[]) { System.out.println(10*10/5+3-1*4/2); } }
  • 79. Relational Operators • Relational operators in Java are used to compare 2 or more objects. • Java provides six relational operators: Assume variable A holds 10 and variable B holds 20, then:
  • 81. public class RelationalOperatorsDemo { public RelationalOperatorsDemo() { 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 static void main(String args[]) { RelationalOperatorsDemo d1=new RelationalOperatorsDemo(); } }
  • 82. Logical Operators • Logical operators return a true or false value based on the state of the Variables. • Given that x and y represent boolean expressions, the boolean logical operators are defined in the Table below.
  • 83. public class LogicalOperatorsDemo { void LogicalOperatorsDemo() { boolean x = true; boolean y = false; 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 : " + (!x)); } public static void main(String args[]) { LogicalOperatorsDemo d1=new LogicalOperatorsDemo(); d1.LogicalOperatorsDemo(); } }
  • 84. Bitwise Operators • Java provides Bit wise operators to manipulate the contents of variables at the bit level.
  • 85. Conditional Operators • The Conditional operator is the only ternary (operator takes three arguments) operator in Java. • The operator evaluates the first argument and, if true, evaluates the second argument. • If the first argument evaluates to false, then the third argument is evaluated. • The conditional operator is the expression equivalent of the if-else statement.
  • 86. public class TernaryOperatorsDemo { public TernaryOperatorsDemo() { int x = 10, y = 12, z = 0; z = x > y ? x : y; System.out.println("z : " + z); } public static void main(String args[]) { TernaryOperatorsDemo d1=new TernaryOperatorsDemo(); } }
  • 90. CONTROL-FLOW STATEMENTS • Java Control statements control the order of execution in a java program, based on data values and conditional logic. • There are three main categories of control flow statements; • Selection statements: if, if-else and switch. • Loop statements: while, do-while and for. • Transfer statements: break, continue, return, try-catch- finally and assert.
  • 91. Selection statements (Decision Making Statement) • There are two types of decision making statements in Java. They are: • if statements • if-else statements • nested if statements • switch statements
  • 92. if Statement: • An if statement consists of a Boolean expression followed by one or more statements. • Block of statement is executed when the condition is true otherwise no statement will be executed.
  • 95. public class IfStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); } } Output: $java IfStatementDemo b > a
  • 96. if-else Statement: • The if/else statement is an extension of the if statement. • if statement fails, the statements in the else block are executed. • Syntax: • The if-else statement has the following syntax: if(<conditional expression>) { < Statement Action1> } else { < Statement Action2> }
  • 98. Example: public class IfElseStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a > b"); } else { System.out.println("b > a"); Output: b > a } } }
  • 99. Nested if Statement: • Nested if-else statements, is that using one if or else if statement inside another if or else if statement(s).
  • 100. Syntax: if(condition1) { if(condition2) { //Executes this block if condition is True } else { //Executes this block if condition is false } } else { //Executes this block if condition is false }
  • 102. Example-nested-if statement: class NestedIfDemo { public static void main(String args[]) { int i = 10; if (i ==10) { if (i < 15) { System.out.println("i is smaller than 15"); } else { System.out.println("i is greater than 15");
  • 103. } } else { System.out.println("i is greater than 15"); } } } Output: i is smaller than 15
  • 104. Switch Statement: • The switch case statement, also called a case statement is a multi-way branch with several choices. • A switch is easier to implement than a series of if/else statements. • A switch statement allows a variable to be tested for equality against a list of values. • Each value is called a case, and the variable being switched on is checked for each case.
  • 105. Syntax: switch (<expression>) { case label1: <statement1> case label2: <statement2> … case labeln: <statementn> default: <statement> }
  • 106. public class SwitchExample { public static void main(String[] args) { int number=20; switch(number){ case 10: System.out.println("10");break; case 20: System.out.println("20");break; case 30: System.out.println("30");break; default:System.out.println("Not in 10, 20 or 30"); } } }
  • 107. Looping Statements (Iteration Statements) • While Statement : • The while statement is a looping control statement that executes a block of code while a condition is true. • It is entry controlled loop.
  • 110. Example: public class WhileLoopDemo { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); while (count <= 10) { System.out.println(count++); } } } Output Printing Numbers from 1 to 10 1 2 3 4 5 6 7 8 9 10
  • 111. do-while Loop Statement • do while loop checks the condition after executing the statements atleast once. • Therefore it is called as Exit Controlled Loop. • The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the beginning.
  • 114. • public class DoWhileLoopDemo { • public static void main(String[] args) • { • int count = 1; • System.out.println("Printing Numbers from 1 to 10"); • do { • System.out.println(count++); • } while (count <= 10); • } • }
  • 115. For Loops • The for loop is a looping construct which can execute a set of instructions a specified number of times. • It‘s a counter controlled loop. A for statement consumes the initialization, condition and increment/decrement in one line. • It is the entry controlled loop.
  • 117. Example public class ForLoopDemo { public static void main(String[] args) { System.out.println("Printing Numbers from 1 to 10"); for (int count = 1; count <= 10; count++) { System.out.println(count); } } }
  • 118. Transfer Statements / Loop Control Statements/ Jump Statements) • 1. break statement • 2. continue statement
  • 119. Using break Statement: • The break keyword is used to stop the entire loop. • The break keyword must be used inside any loop or a switch statement. • The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.
  • 121. Using continue Statement: • The continue keyword can be used in any of the loop control structures. • It causes the loop to immediately jump to the next iteration of the loop.
  • 123. Defining Classes in java • In object-oriented programming, a class is a basic building block. • It can be defined as template that describes the data and behaviour associated with the class instantiation. • A class can also be called a logical template to create the objects that share common properties and methods.
  • 124. • For example, an Employee class may contain all the employee details in the form of variables and methods. • If the class is instantiated i.e. if an object of the class is created (say e1), we can access all the methods or properties of the class.
  • 125. • Java provides a reserved keyword class to define a class. • The keyword must be followed by the class name. • Inside the class, we declare methods and variables.
  • 126. • In general, class declaration includes the following in the order as it appears: • Modifiers: A class can be public or has default access. • Class keyword: The class keyword is used to create a class. • Class name: The name must begin with an initial letter (capitalized by convention). • Superclass (if any): The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. • Body: The class body surrounded by braces, { }.
  • 131. Constructor • Constructor is a special type of method that is used to initialize the object. • Constructor is invoked at the time of object creation. • At the time of calling constructor, memory for the object is allocated in the memory.
  • 132. • Every time an object is created using the new() keyword, at least one constructor is called. • if there is no constructor available in the class. It calls a default constructor • In such case, Java compiler provides a default constructor by default.
  • 135. Rules for creating Java constructor • There are three rules defined for the constructor. The Constructor name must be the same as its class name A Constructor must have no return type A Java constructor cannot be static, final,
  • 136. Types of Java constructors • There are two types of constructors in Java: Default constructor (no-arg constructor) Parameterized constructor
  • 139. Java Parameterized Constructor • A constructor which has a specific number of parameters is called a parameterized constructor.
  • 142. Constructor Overloading in Java • Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. • They are arranged in a way that each constructor performs a different task.
  • 145. METHODS • A Java method is a collection of statements that are grouped together to perform an operation.
  • 146. • The syntax shown above includes: •  modifier: It defines the access type of the method and it is optional to use. •  returnType: Method may return a value. •  Method_name: This is the method name. The method signature consists of the method name and the parameter list. •  Parameter List: The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters. •  Method body: The method body defines what the method does with statements.
  • 148. class method { void display() //Method declaration { System.out.print(“Hello World”); } public static void main(String args[])//main function { method m1=new method(); m1.display(); } Output: Hello World
  • 150. ACCESS SPECIFIERS • Access specifiers are used to specify the visibility and accessibility of a class constructors, member variables and methods. • One of four different access modifiers: 1. Public 2. Private 3. Protected 4. Default (package)
  • 151. 1. Public (anything declared as public can be accessed from anywhere): • A variable or method declared/defined with the public modifier can be accessed anywhere in the program through its class objects, through its subclass objects and through the objects of classes of other packages also.
  • 152. 2. Private (anything declared as private can’t be seen outside of the class): • The instance variable or instance methods declared/initialized as private can be accessed only by its class. • Even its subclass is not able to access the private members.
  • 153. 3. Protected (anything declared as protected can be accessed by classes in the same package and subclasses in the other packages): • The protected access specifier makes the instance variables and instance methods visible to all the classes, subclasses of that package and subclasses of other packages.
  • 154. 4. Default (can be accessed only by the classes in the same package): • The default access modifier is friendly. • This is similar to public modifier except only the classes belonging to a particular package knows the variables and methods.
  • 156. IN TOOLS PACKAGE Simple.java package tools; public class Simple { public int marks = 6; }
  • 157. IN SAME PACKAGE B.java public class B { int marks = 10; } import tools.Simple; class Test { public static void main(String args[]) { Simple obj = new Simple(); System.out.println(obj.marks); B obj1 = new B(); System.out.println(obj1.marks); }
  • 159. Static Members • The static keyword in Java is mainly used for memory management. • The static keyword in Java is used to share the same variable or method of a given class. • The users can apply static keywords with variables, methods, blocks, and nested classes
  • 165. import java.io.*; class staticdemo { int a=10,b=20,c=30; //non static variable static int count; //static variable static void SMdemo() //static method { count=100; } static // static block creation { System.out.println("java program for static"); } static class innerclass //static class creation { static int count2=200; }
  • 166. staticdemo() //constructor creation { count=count+1; } } class Test1 { public static void main(String args[]) { staticdemo.SMdemo(); //static method calling staticdemo st1=new staticdemo(); staticdemo st2=new staticdemo(); System.out.println("non-static variable"+st1.a); // non-static variable calling System.out.println("object count" +staticdemo.count); //static variable calling System.out.println("Static class called"+staticdemo.innerclass.count2); // static class calling } }
  • 167. java program for static non-static variable10 object count102 Static class called200
  • 168. JavaDoc Comments • Javadoc is a tool which comes with JDK and it is used for generating Java code documentation in HTML format from Java source code which has required documentation in a predefined format.
  • 169. Format: • A Javadoc comment precedes similar to a multi-line comment except that it begins with a forward slash followed by two asterisks (/**) and ends with a */ • Each /** . . . */ documentation comment contains free-form text followed by tags. • A tag starts with an @, such as @author or @param. • The first sentence of the free-form text should be a summary statement. • The javadoc utility automatically generates summary pages that extract these sentences. • In the free-form text, you can use HTML modifiers such as <h1>...</h1> for heading, <p>...</p> .
  翻译: