Unit 1
Unit 1
OBJECT ORIENTED
PROGRAMMING WITH JAVA
By
UNIT – 1 Syllabus
• UNIT-I: Introduction: Program Structure in Java: Introduction, Writing Simple Java
Programs, Elements or Tokens in Java Programs, Java Statements, Command Line
Arguments, User Input to Programs, Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators :Introduction, Data Types in Java, Declaration of
Variables, Data Types, Type Casting, Scope of Variable Identifier, Literal Constants,
Symbolic Constants, Formatted Output with printf() Method, Static Variables and
Methods, Attribute Final, Introduction to Operators, Precedence and Associativity of
Operators, Assignment Operator ( = ), Basic Arithmetic Operators, Increment (++) and
Decrement (--) Operators, Ternary Operator, Relational Operators, Boolean Logical
Operators, Bitwise Logical Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else
Expressions, Ternary Operator?:, Switch Statement, Iteration Statements, while
Expression, do–while Loop, for Loop, Nested for Loop, For–Each for Loop, Break
Statement, Continue Statement.
JAVA Programming BSNV R Murthy 2
Aditya College of Engineering & Technology
Introduction
• Since the invention of the Computer, many programming approaches have been
tried. Such as modular programming, top-down programming, bottom-up
programming and structured programming.
• A programming language specifies the words and symbols that we can use to
write a program
• A programming language employs a set of rules that dictate how the words and
symbols can be put together to form valid program statements
• The Java programming language was created by Sun Microsystems, Inc.
• It was introduced in 1995 and it's popularity has grown quickly since.
Introduction
• Like C, C++ etc. Java is another computer language but with a difference.
• Java’s designers have borrowed the best features of many existing language such
as C and C++ and added a few new features to form a simple language.
• One of the important reason for java’s success is the amazing functionality it adds
to the WWW.
• Java has two lives, one as a stand-alone computer language for general purpose
programming and the other as a supporting language for Internet programming.
• The general purpose programs are known as applications and the programs
written for internet are known as applets.
Introduction
In Java, there are three types of programs as follows:
• Stand- aline application programs : These programs are made and run on users
computers
• Applet programs : These programs are meant to run in a web page on the
Internet.
• Java Servlets : These programs run in computers that provide web services. They
are also often called server isde programs or servlets.
OOPs Concepts
Procedural vs OOPs
POP OOPs
POP stands for Procedure Oriented OOP stands for Object Oriented
Programming Programming
Problem is divided into small things called Programs are divided into things called as
as functions objects
Emphasis is on functions i.e., doing things Emphasis is on data rather than procedures
Approach : Top down Approach : Bottom up
Debugging is very difficult Debugging is very easy
No such features are supported Abstraction, Inheritance, Encapsulation &
polymorphism are its key features
Examples: C, Basic, FORTRAN etc.. Examples: Java, C++, VB.NET, C# etc..
Security: Less secure Security: More
JAVA Programming BSNV R Murthy 7
Aditya College of Engineering & Technology
Advantages of OOPs
• Easy to understand
• Code reuse
• Improved software-development productivity ( Faster in time and Lower in
cost of development )
• Improved software maintainability.
• Encapsulation
• Data security
• Addresses real world problems
• Polymorphism
• Extensibility
JAVA Programming BSNV R Murthy 8
Aditya College of Engineering & Technology
Applications of OOPs
• Real-time systems
• Simulation and modeling
• Object-oriented databases
• Hypertext, hypermedia and Expert Text
• AI and expert systems
• Neural networks and parallel programming
• Decision support systems
• CAD/CAM/CIM systems.
Object
• An object is a basic unit of Object-Oriented Programming that
represents real-life entities.
• Every object has an identity, attributes, behavior and state.
• Examples: car, pen, table, apple, rose, student, account, keyboard,
chair etc..
• Similar objects are grouped and categorized.
• Each object has responsibility to react for a particular type of
functionality.
JAVA Programming BSNV R Murthy 11
Aditya College of Engineering & Technology
Class
• A class is a user-defined blueprint or prototype from which objects
are created.
• It represents the set of properties or methods that are common to all
objects of one type.
• Using classes, you can create multiple objects with the same behavior
instead of writing their code multiple times.
• This includes classes for objects occurring more than once in your
code.
Class
Examples
Class: Fruit ; Object: Apple, Banana,
Mango
Object Class
Class is a blueprint or template from
Object is an instance of a class.
which objects are created.
Object is a real world entity such as
pen, laptop, mobile, bed, keyboard, Class is a group of similar objects.
mouse, chair etc.
Object is a physical entity. Class is a logical entity.
Object allocates memory when it is Class doesn't allocated memory when
created. it is created
Object is created through new
Class is declared using class keyword
keyword
Class Syntax
Class has attributes i.e., variables and methods which are operations
performed on attributes.
Abstraction
• Data Abstraction is the property by virtue of which only the essential
details are displayed to the user. The trivial or non-essential units are
not displayed to the user.
• Data Abstraction may also be defined as the process of identifying
only the required characteristics of an object, ignoring the irrelevant
details.
• The properties and behaviors of an object differentiate it from other
objects of similar type and also help in classifying/grouping the
object.
Abstraction
Ex: A car is viewed as a car rather than its
individual components.
• When you drive your car you do not have to be
concerned with the exact internal working of your
car.
• What you are concerned with is interacting with
your car via its interfaces like steering wheel, brake
pedal, accelerator pedal etc.
Encapsulation
• Technically, in encapsulation, the variables or the data in a class is
hidden from any other class and can be accessed only through any
member function of the class in which they are declared.
• In encapsulation, the data in a class is hidden from other classes,
which is similar to what data-hiding does. So, the terms
“encapsulation” and “data-hiding” are used interchangeably.
Encapsulation
• Encapsulation is a concept that binds together the data of an object,
and functions that manipulate the data in to a single unit or single
component.
• Encapsulation provides more security to the data with data hiding,
from outside interference and misuse.
Encapsulation
Encapsulation
Inheritance
• Inheritance is an important pillar of OOP (Object Oriented
Programming).
• Most important aspect of oops is code reusability.
• Inheritance is the process of forming a new class from an existing
class.
The existing class called as base class, new class is
formed called as derived class.
Inheritance
Inheritance
Polymorphism
• The ability to use an operator or function in different ways is called
polymorphism
• Poly refers to many.
• A single function or an operator, functioning in many ways different
upon the usage is called polymorphism.
• Ex:
Method Overloading
Method Overriding
Operator Overloading
Polymorphism
Polymorphism
Dynamic binding
Message Passing
• Message passing is the vital activity for executing an object oriented program.
Message Passing
Introduction to JAVA
• Java is a general-purpose object oriented programming language.
History of JAVA
• In 1990, James Gosling and his team was given the task of creating
programs to control consumer electronics.
• They used C++ as its model, stripping away all the difficult features of
C++, and named "Oak ".
• "By the time Sun Micro systems discovered that the name "Oak" was
already claimed and they changed the name to " Java" .
Applications of JAVA
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Scientific applications
• Database connections
• Enterprise applications
• No pointers
• No operator overloading
• No multiple inheritance
• Just-in-time compilers
• Java API is part of JRE and these libraries are dynamically linked at runtime
while executing on the target platform.
• Java classes carry run-time type information, that uses to dynamically linking
of objects at run time.
Features of JAVA
• Many Java features are inherited from the earlier languages:
B, C, C++
Program Structure
A Java Program source file having extension of .java,
consists of a collection of classes.
Here: public is access specifier. This class is accessible to any outside code. Otherwise the class is
accessible to only same package classes.
class is a keyword of java language which is used to declare the class.
The class body starts with the left brace { and ends with the right closing brace }. // are comments
which are neglected by the compiler.
A class body may comprise statements for declaration of variables. constants, expressions, and
methods.
{
System.out.println(“This is a simple Java program”);
}
}
• Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
• For example:
1. /*It is an example of
2. multiline comment*/
• Documentation Comment: It starts with the delimiter (/**) and ends with */.
• For example:
JAVA STATEMENTS
A statement specifies an action in a Java program.
Declaration statement
Expression statement
JAVA STATEMENTS
Declaration statement
string str;
JAVA STATEMENTS
Expression statement
An expression with a semicolon at the end is called an expression statement.
Ex. //Increment and decrement expressions
num++; num--;
++num; --num;
//Assignment expressions
num = 100; num *= 10;
//Method invocation expressions
System.out.println("This is a statement");
someMethod(param1, param2);
JAVA STATEMENTS
Flow Control statement
By default, all statements in a Java program are executed in the order they
appear in the program. Sometimes you may want to execute a set of
statements repeatedly for a number of times or as long as a particular
condition is true.
All of these are possible in Java using flow control statements. The if
statement, while loop statement and for loop statement are examples of
control flow statements.
Command line arguments are parameters that are passed to the application
program at the time of execution.
The first argument is stored at args[0] The second argument is stored at args[1]
and so on…
Declaration of Variables
Examples:
double price = 28.5;
char ch = "C":
String name - "John";
illustrates the declaration and output of some data types
PrintOut.java
The object “scaninput” invokes the method nextInt() which reads the value
typed by the user.
Example 1: Arithmetic.java
Example2 :Kinput.java
Escape.java
Programming Style
There are no set patterns of good style and bad style
TYPE CASTING
Converting one data type to another data type is called as Type Casting.
There are two types of type casting.
They are,
i. Implicit Type casting
Implicit type casting is done automatically by a compiler when we assign a
value to the variable.
Example: int a=10;
double b;
b=a;
Here a is integer and d is double variables. Integer value is automatically converted
into double by the compiler
JAVA Programming BSNV R Murthy 92
Aditya College of Engineering & Technology
TYPE CASTING
II. Explicit Type casting
The explicit type casting is carried out by the following code:
type variable = (new_type) variable;
It is illustrated by the following code lines:
double D = 6.865;
int A = (int) D;
In such a conversion, there is loss of data
TYPE CASTING
II. Explicit Type casting
The explicit type casting is carried out by the following code:
type variable = (new_type) variable;
It is illustrated by the following code lines:
double D = 6.865;
int A = (int) D;
In such a conversion, there is loss of data
Example: TypeCast.java
i. Literal Constants
The char literals are enclosed in single quotes (‘ ’). The examples ‘A’ and ‘B’.
These may also be written as \u0041 and \u0042
ii. Symbolic Constants
A Symbolic constant is a variable whose value does not change throughout
the program. Some of the examples include Pi, NORTH, EAST etc.
Illustrates the use of symbolic constant
Example: SymbolicConst.java
Static Variables:
The static variables are class variables.
Only one copy of such variables is kept in the memory and all the objects share
that copy.
The static variables are accessed through class reference, whereas the instance
variables are accessed through class object reference.
Example: EmpCount.java
Static Method:
Static Method:
The static methods are similar to class methods and can be invoked without any
reference of object of class.
However, class reference (name of class) is needed, as in the following example
The method like sqrt() is declared as static method in Math class and is called
Math.sqrt(5); // Finds square root of 5
The static method is called using the method name that is preceded by the class
name; in this case. Math and period ().
Example:StaticMethods.java
ATTRIBUTE FINAL
Final Variable: The value of a variable declared final cannot be changed in the
program. It makes the variable a constant.
A few examples of declarations are as follows:
final double PI = 3.14159; // The value of PI cannot be changed in its scope
final int M = 900; // The value of M cannot be changed in its scope.
Final Method: The attribute final may be used for methods as well as for classes.
These are basically connected with inheritance of classes.
When final keyword is used with Java method, it becomes the final method.
A final method cannot be overridden in a sub-class.
Final Class: A Java class with final modifier is called final class A final class cannot
be sub-classed or inherited.
JAVA Programming Example:Final.java BSNV R Murthy 101
Aditya College of Engineering & Technology
FLOW OF CONTROL
CONTROL STATEMENTS: (FLOW OF CONTROL) - A Control statement is a statement
used to control the flow of execution in a Java Program.
If Statement
Syntax:
if(condition)
//code to be executed
}
JAVA Programming BSNV R Murthy 103
Aditya College of Engineering & Technology
If else Statement
• Syntax:
Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else- if
ladder statement.
The switch statement works with byte, short, int, long, enum types, String and some wrapper
types like Byte, Short, Int, and Long.
• Points to Remember:
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only. The case value must be literal or constant. It
doesn't allow variables.
Switch Statement
Syntax:
switch(expression)
{
case value1: //code to be executed;
break; //optional
case value2: //code to be executed;
break; //optional
…
…
default: //code to be executed if all cases are not matched;
}
JAVA Programming BSNV R Murthy 108
Aditya College of Engineering & Technology
Switch Statement
Ternary Operator
Ternary Operator
Example:
public class Ternary
{
public static void main (String args[])
{
int a=10;
int b = (a< 20) ? 100 : 200;
System.out.println("b= "+b);
}
}
LOOP STATEMENTS
• for loop
• While loop
• Do-while loop
• A simple for loop is the same as C/C++ We can initialize the variable check
condition and increment/decrement value. It consists of four parts:
• Initialization:
• It is the initial condition which is executed once when the loop starts. Here, we
can initialize the variable, or we can use an already initialized variable. It is an
optional condition.
• Condition:
• It is the second condition which is executed each time to test the condition of
the loop. It continues execution until the condition is false. It must return
Boolean value either true or false. It is an optional condition.
• Statement: The statement of the loop is executed each time until the second
condition is false.
• Increment/Decrement: It increments or decrements the variable value. It is
JAVA Programming BSNV R Murthy 113
an optional condition.
Aditya College of Engineering & Technology
• If we have a for loop inside the another loop, it is known as nested for loop.
• The inner loop executes completely whenever outer loop executes.
The for-each loop is used to traverse array or collection in java. It is easier to use
than simple for loop because we don't need to increment value and use
subscript notation.
It works on elements basis not index. It returns element one by one in the
defined variable.
Syntax:
//Java For-each loop example which prints the elements of the array
public class ForEach
{
public static void main(String[] args)
{
int arr[]={12,23,44,56,78}; //Declaring an array
//Printing array using for-each loop
for(int i:arr)
{
System.out.println(i);
}
}
}
JAVA Programming BSNV R Murthy 117
Aditya College of Engineering & Technology
class Main
{
public static void main(String[] args)
{
// an array of numbers
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum=0; // iterating through each element of the array
for (int number: numbers)
{
sum += number;
}
System.out.println("Sum = " + sum);
}
JAVA Programming BSNV R Murthy 118
}
Aditya College of Engineering & Technology
The while loop loops through a block of code as long as a specified condition is true.
The do/while loop is a variant of the while loop.
This loop will execute the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
}
}
JAVA Programming BSNV R Murthy 121
Aditya College of Engineering & Technology
Break STATEMENTS
break statement: -The break statement skips from the loop or block in which it is defined.
The control then automatically goes to the first statement after the loop or block.
The general format is break;
Break STATEMENTS
Continue STATEMENTS
The continue statement is used for continuing next iteration of loop statements. –
When it occurs in the loop, it does not terminate but it skips the statements after
it.
It is useful when we want to continue the program without executing any part of
the program.
Continue STATEMENTS
class Test
{
public static void main(String[] args) {
for (int i = 1; i <= 10; ++i)
{
i=1 2 3 4 9 10
if (i > 4 && i < 9)
{
continue;
}
System.out.println(i);
}
}
}
JAVA Programming BSNV R Murthy 126
ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY
Thank You