You are on page 1of 38

CS8392-Object Oriented Programming in java UNIT : 1

INTRODUCTION TO OOPs AND JAVA FUNDAMENTALS


JAVA:
Java is an object-oriented, class-based, concurrent, secured and general-purpose computer-programming
language. It is a widely used robust technology.

What is Java?

Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is called a platform.

Application

According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of
them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Types of Java Applications

There are mainly 4 types of applications that can be created using Java programming:

1) Standalone Application

Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
CS8392-Object Oriented Programming in java UNIT : 1
2) Web Application

An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used
for creating enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile application. Currently, Android and
Java ME are used for creating mobile applications.

Java Platforms / Editions

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net,
java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top
of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

It is a micro platform that is dedicated to mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a lightweight user interface API.

OOPs (Object Oriented Programming)


CS8392-Object Oriented Programming in java UNIT : 1

• Object means a real word entity such as pen, chair, table etc.
• Object-Oriented Programming is a methodology or paradigm to design a program using classes
and objects.
• It simplifies the software development and maintenance by providing some concepts as follows:
o Object
o Class
o Encapsulation
o Inheritance
o Polymorphism
o Abstraction

OOPs Feature

Object
• The real world entities are modeled as an Object that has state and behavior.
• For example: chair, pen, table, keyboard, bike, Person, Bank account , Place etc.
• It is also known as user defined data type.
• Object can be defined as an instance of a class.
• An object contains an address and takes up some space in memory.
• Objects can communicate without knowing details of each other's data or code.
CS8392-Object Oriented Programming in java UNIT : 1
Examples of states and behaviors
Example 1:
Object: Car
State: Color, Brand, Weight, Model
Behavior: Start, Drive, Break, Accelerate, Slow Down, Gear change, stop
Example 2:
Object: House
State: Address, Area in Sq.ft
Behavior: Build, Open door, close door, Remodel

Class
• Collection of data members(states) and methods(behavior) is called class.
• It is a logical entity.
• A class can also be defined as a blueprint from which you can create an individual object.
• Class doesn’t store any space
• Example ... A Student entity is defined using
data members
Sno, Sname, branch, phoneNo, email etc
methods
getData(), putData(), calculateTotal() etc...

Inheritance

 Inheritance is a process of defining a new class based on an existing class by extending its common
data members and methods.
 The new class called the subclass can acquires all the data members and methods of parent class
called as the super class.
 Inheritance allows us to reuse of code code in base class need not be rewritten in the child class.
 The Parent class is called the Base class or Super class. The class that extends the base class is
called the Child class or Derived class or Sub class .
 Java supports single inheritance, multi level inheritance it does not support multiple inheritance
 For example, if we have a class Vehicle that has properties like Color, Price, etc, we can create 2 classes like
Bike and Car from it that have those 2 properties and additional properties that are specialized for them like a car
has numberOfWindows while a bike cannot. Same is applicable to methods.

Polymorphism
• Polymorphism means taking more than one form.
• When one task is performed by different ways it is known as polymorphism
• An operation may exhibit different behavior at different instances
10 + 20 =30
“Hello” + “ World” = “HelloWorld”
Here the operator + behaves differently with different data types.
• Example – Draw_shape() implemented differently by different people like draw a
Lline, Rectang1e,Circ1e etc.
• In java polymorphism is implemented by Method overloading and method overriding.
CS8392-Object Oriented Programming in java UNIT : 1

Abstraction
• Hiding internal details and showing functionality is known as abstraction.
• For example.’ phone call, we don't know the internal processing.
• For example, when you login to your bank account online,
 Enter your user_id and password and press login,
The input data sent to server, how it gets verified is all abstracted(hidden) from you.
• In java, we use abstract class and interface to achieve abstraction.

Encapsulation

• Binding (or wrapping) code and data together into a single unit is known as encapsulation.
• This encapsulation of data from direct access of the user helps to achieve data hiding.
• A java class is the example of encapsulation which combines data members and methods together.
• Data members can be accessed only by objects though methods encapsulated with that.

Message Passing

• In OOPs set of objects can communicate with each other.


CS8392-Object Oriented Programming in java UNIT : 1

Advantage of OOPs over Procedure-oriented programming language

Type Procedure Oriented Programming Object Oriented Programming

Divided Into In POP, program is divided into small parts In OOP, program is divided into parts called
called functions. objects.

Importance In POP, Importance is not given to data but to In OOP, Importance is given to the data rather than
functions as well as sequence of actions to be procedures or functions because it works as a real
done. world.

Approach POP follows Top Down approach. OOP follows Bottom Up approach.

Access POP does not have any access specifier. OOP has access specifiers named Public, Private,
Specifiers Protected, etc.

Data Moving In POP, Data can move freely from function to In OOP, objects can move and communicate with
function in the system. each other through member functions.

Expansion To add new data and function in POP is not so OOP provides an easy way to add new data and
easy. function.

Data Access In POP, Most function uses Global data for In OOP, data can not move easily from function to
sharing that can be accessed freely from function,it can be kept public or private so we can
function to function in the system. control the access of data.

Data Hiding POP does not have any proper way for hiding OOP provides Data Hiding so provides more
data so it is less secure. security.

Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form of
Function Overloading and Operator Overloading.

Examples Example of POP are : C, VB, FORTRAN, Example of OOP are C*+, JAVA, VB.NET,
Pascal. C#.NET.
CS8392-Object Oriented Programming in java UNIT : 1

FEATURES / CHARACTERISTICS OF JAVA

• The Objective of Java programming language creation was to make it portable, simple and
secure programming language.
• There are also some awesome features which plays important role in the popularity of this
language. They are as follows.
o Simple
o Object-Oriented
o Portable
o Platform independent
o Secured
o Robust
o Architecture neutral
o Dynamic
o Interpreted
o High Performance
o Multithreaded
o Distributed

1. Simple
• Java is easy to learn and its syntax is simple to understand.
• Java is simple than C++ because it has removed many confusing & rarely used features like
explicit pointers, operator overloading etc.
• No need to remove unreferenced objects because there is Automatic Garbage Collection in java.

2. Object-oriented
• Java is Object-oriented programming language. Everything in Java is an object.
• Object-oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior.
• Object-oriented programming(OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
• Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

3. Platform Independent
• A platform is the hardware or software environment in which a program runs.
• Java is platform independent because it is different from other languages like C, C++ etc. which
are compiled into platform specific machines while Java is a write once, run anywhere
language.
CS8392-Object Oriented Programming in java UNIT : 1

• There are two types of platforms software-based and hardware based.


• Java provides software-based platform that runs on the top of other hardware-based platforms.
• It has two components:
1. Runtime Environment
2. API(App1ication Programming Interface)
• Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc.
• Java code is compiled by the compiler and converted into byte code. This byte code is a
platform-independent code because it can be run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).

4. Secured

• Java is best known for its security & using Java, we can develop virus-free systems.
• Java is secured because:
o No explicit pointer
o Java Programs run inside virtual machine sandbox_

• Classloader:
o Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to
dynamically load Java classes into the Java Virtual Machine.
o It adds security by separating the package for the classes of the local file system from
those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
• Security Manager: It determines the resources that a class can access such as reading and
writing to the local disk.

These security are provided by java language. Some security can also be provided by application
developer through SSL, JAAS, cryptography etc.

5. Robust

• Robust means strong.


• Java is robust because:
o Strong memory management.
o Lack of pointers that avoids security problem.
o Automatic garbage collection.
o Exception handling and Type checking mechanism.
All these points makes java robust.

6. Architecture-neutral
• Java is architecture neutral because there is no implementation dependent features e.g. size of
primitive types is fixed.
• Eg.in C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32
and 64 bit architectures.
CS8392-Object Oriented Programming in java UNIT : 1

7. Portable

• Java is portable because it facilitates you to carry the java byte code to any platform.

8. High-performance

• Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++).
• Java is an interpreted language, so it is also a reason that why it is slower than compiled
language C, C++.

9. Distributed
• Java is distributed because it facilitates us to create distributed applications in java.
• Eg.RMI and EJB are used for creating distributed applications. We may access files by calling
the methods from any machine on the internet.

10. Multi-threaded

• A thread is like a separate program, executing concurrently.


• Difference between multitasking and multithreading.
• Advantage-It doesn't occupy memory for each thread. It shares a common memory area.
• Threads are important for multi-media, Web applications etc.
CS8392-Object Oriented Programming in java UNIT : 1

Difference between C++ and JAVA

There are many differences and similarities between C++ programming language and Java. A list
of top differences between C++ and Java are given below:
Comparison Index C++ Java

Platform-
C++ is platform-dependent. Java is platform-independent.
independent

Java is mainly used for application


C++ is mainly used for system
Mainly used for programming. It is widely used in window,
programming.
web-based, enterprise and mobile applications.

Goto C++ supports goto statement. Java doesn’t support goto statement.

Java doesn't support multiple inheritance


C++ supports multiple
Multiple inheritance through class. It can be achieved by interfaces
inheritance.
in java.

Operator C++ supports operator


Java doesn't support operator overloading.
Overloading overloading.

Java supports pointer internally. But you can't


C++ supports pointers. You can
Pointers write the pointer program in java. It means java
write pointer program in C++.
has restricted pointer support in java.

Compiler and
C++ uses compiler only. Java uses compiler and interpreter both.
Interpreter

Call by Value and C++ supports both call by value Java supports call by value only. There is no
Call by reference and call by reference. call by reference in java.

C++ supports structures and


Structure and Union Java doesn't support structures and unions.
unions.

C++ doesn't have built-in support


Thread Support for threads. It relies on third-party Java has built-in thread support.
libraries for thread support.

Documentation C++ doesn't support Java supports documentation comment (/**


comment documentation comment. */) to create documentation for java source
CS8392-Object Oriented Programming in java UNIT : 1

Java

Java is an object-oriented, class-based, concurrent, secured and general-purpose computer-


programming language. It is a widely used robust technology.
• Java is a programming language and a platform.
• Java is a high level, robust, secured and object-oriented programming language.

Platform:
• Any hardware or software environment in which a program runs, is known as a platform.
• Since Java has its own runtime environment (JRE) and API, it is called platform.

Example

class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");.
}
}
Where it is used
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in, javatpoint.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.

THE JAVA ENVIRONMENT


• The Java Environment includes large number of development tools and hundreds of
classes and methods.
• The JDK (Java Development Kit) is a software development environment with a
collection of tools that are used for developing and running java programs.
• and classes and methods are part of Java Standard Library(JSL) and is also known as
Application Program Interface(API)
• Tools include..
appletviewer for viewing applets
javac (java compiler)
java (Java Interpreter)
javap(Java disassemble)
javah (for C header files)
javadoc( for creating HTML documents)
jdb (java debugger)
CS8392-Object Oriented Programming in java UNIT : 1

o Java Run-time Environment (JRE) is the part of the (JDK) available on


devices to run java programs.
o The source Java code gets compiled and converted to Java byte code, to run this
byte code on any platform, you require JRE.
o It is a freely available software distribution which has
Java Class Library
• They are set of core class libraries that are required for the execution
of java program.
JVM. (Java virtual machine)
• JVM -A program that interprets the intermediate java byte code and
generates the desired output.
o The JRE loads classes, verify access to memory, and retrieves the
system resources.
o JRE acts as a layer on the top of the operating system.

JRE also consists of the following components:


• Deployment technologies,
 Development technologies :
Java plug-in : Enables the execution of a java applet on
browser Java web start : Enables remote development
of an application.
o User interface Toolkits for user interface like AWT, Swing Java 2D.
o Integration libraries like Java Database Connectivity (JDBC) and Java Naming and
Directory Interface (JNDI).
o Libraries such as Lang and util.
o Other base libraries like Java Management Extensions (JMX), Java Native Interface
(JNI) and Java for XML Processing (JAX-WS).

Difference between JVM, JRE and JDK

JVM
• JVM (Java Virtual Machine) is an abstract machine.
• It is a specification that provides runtime environment in which java bytecode can be
executed.
• JVM is responsible for executing the java program line by line hence it is also
known as interpreter.
• JVMs are available for many hardware and software platforms. JRE and JDK are
platform dependent because configuration of each OS differs.
• But, JVM is platform independent.
• The JVM performs following
CS8392-Object Oriented Programming in java UNIT : 1

main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
• JRE is an acronym for Java Runtime Environment.
• It is used to provide runtime environment. It is the implementation of JVM. It physically
exists. It contains set of libraries + other files that JVM uses at runtime.
• JVM’s implementation are also actively released by other companies besides Sun Micro
Systems.

JDK

• JDK is an acronym for Java Development Kit.


• It physically exists. It contains JRE + development tools.
CS8392-Object Oriented Programming in java UNIT : 1

JAVA PROGRAM STRUCTURE

o Java Program may contain many classes of which only one class defines the main
method.
o A Java Program may contain one or more sections.
Documentation Section
Package Statement
Import Statements
Interface Statements
Class Definitions
Class
{
Main Method Definition
}
Of the above Sections shown in the figure, the Main Method class is Essential part,
Documentation Section is a suggested part and all the other parts are optional.

Documentation Section:

o It Comprises a Set of comment lines giving the name of the program, the author and other
details.
o Comments help in Maintaining the Program.
o Java uses a Style of comment called documentation comment.
/* * ...... */
This type of comment helps is generating the documentation automatically.
Package Statement
o The first statement allowed in a Java file is a package statement.
o It declares the package name and informs the compiler that the classes defined in this
file belong to this package.
o Example : package student; It is an optional declaration.
Import Statements
o The statement instructs the interpreter to load a classes contained in a particular package.
o Example : import student.test; Where, student is the package and test is the class.
Interface Statements
o An interface is similar to classes which consist of group of method declaration.
o It is used when we want to implement the feature of Multiple Inheritance in Java It is an
optional declaration.
Class Definitions
o A Java Program can have any number of class declarations.
o The number of classes depends on the complexity of the program.
Main Method Class
o Every Java Stand alone program requires a main method as its starting point.
o A Simple Java Program will contain only the main method class.
o It creates objects of various classes and uses those objects for performing various
operations.
CS8392-Object Oriented Programming in java UNIT : 1

JAVA SOURCE FILE

Example :

class Simple
{
public static void main(String args[])
{
System.out.println("Hello java");
}
}

File Name: Simple.


java Compiler : javac Simple.java
Run : java Simple

Parameters used in first java program

• class keyword is used to declare a class in java.


• public keyword is an access modifier which represents visibility, it means it is visible to
all.
• static is a keyword, if we declare any method as static, it is known as static method.
The core advantage of static method is that there is no need to create object to invoke
the static method. The main method is executed by the JVM, so it doesn't require to
create object to invoke the main method. So it saves memory.
• void is the return type of the method, it means it doesn’t return any value.
• main represents the starting point of the program.
• String[] args is used for command line argument.
• System.out.println() is used as a print statement.

COMPILATION IN JAVA

• A compiler is a program that translates a source program written in some high-level


programming language (such as Java) into machine code for some computer
architecture (such as the Intel Pentium architecture)
• Java source code is compiled into bytecode when we use the javac compiler. The
bytecode gets saved on the disk with the file extension .class . When the program is to
be run, the bytecode is converted, using the just-in-time (JIT) compiler. The result is
machine code which is then fed to the memory and is executed.
• Java is a compiled programming language, but rather than compiling straight to
CS8392-Object Oriented Programming in java UNIT : 1

executable machine code, it compiles to an intermediate binary form called JVM


bytecode. The bytecode is platform independent, because it's targeted at Java Virtual
Machine. Then the JVM which is platform independent translates it into machine
code.

 javac Simple.java
 java Simple

Output
Hello World

DATA TYPES:
Java defines eight simple types of data: byte, short, int, long, char, float, double, and Boolean.
Integers this group includes byte, short, int, and long, which are for whole valued signed
numbers.
The width and ranges of these integer types vary widely, as shown in this table:
Name Width Range
long 64 —9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 —2,147,483,648 to 2,147,483,647
short 16 —32,768 to 32,767
byte 8 -128 to 127

• Floating-point numbers this group includes float and double, which represent numbers
with fractional precision.
here are two kinds of floating-point types, float and double, which represent single- and
double- precision numbers, respectively.
Their width and ranges are shown here:
Name Width in Bits Approximate Range
double 64 4.9e—324 to 1.8e+308
float 32 1.4e—045 to 3.4e+038
CS8392-Object Oriented Programming in java UNIT : 1

• Characters this group includes char, which represents symbols in a character set, like
letters and numbers.
• Boolean this group includes Boolean, which is a special type for representing true/false values.

VARIABLE
• A Variable is a named piece of memory that is used for storing data in java Program.
An object stores its state in variables. A variable is an identifier used for storing a
data value.
• A Variable may take different values at different times during the execution in the
program, unlike the constants.
• Rules followed for variable names ( consist of alphabets, digits, underscore and
dollar characters)
1. They must not begin with digits.
2. Uppercase and lowercase are not the same. Example: Total and total are two
variables which are distinct.
3. It should not be a keyword.
4. Whitespace is not allowed.
5. variable names can be of any length.

OPERATORS

o Operators are used in programs for manipulating data and variables.


o An operator performs a function on one, two, or three operands.
o An operator that requires one operand is called a unary operator. For example, ++ is a
unary operator that increments the value of its operand by 1.
o An operator that requires two operands is a binary operator. For example, = is a
binary operator that assigns the value from its right-hand operand to its left-hand
operand.
o A ternary operator is one that requires three operands. The Java programming
language has one ternary operator?:
o The various categories of operators are as follows:
• Arithmetic Operators
• Relational Operators
• Conditional Operators
• Shift and Logical Operators
• Assignment Operators
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators −
Assume integer variable A holds 10 and variable B holds 20, then −
CS8392-Object Oriented Programming in java UNIT : 1

Operator Description Example

+ (Addition) Adds values on either side of the operator. A + B will give 30

Subtracts right-hand operand from left-


- (Subtraction) A - B will give -10
hand operand.

Multiplies values on either side of the


* (Multiplication) A * B will give 200
operator.

Divides left-hand operand by right-hand


/ (Division) B / A will give 2
operand.

Divides left-hand operand by right-hand


% (Modulus) B % A will give 0
operand and returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19

The Relational Operators

Operator Description

Checks if the values of two operands are equal or not, if yes then
== (equal to)
condition becomes true.

Checks if the values of two operands are equal or not, if values are
!= (not equal to)
not equal then condition becomes true.

Checks if the value of left operand is greater than the value of right
> (greater than)
operand, if yes then condition becomes true.

Checks if the value of left operand is less than the value of right
< (less than)
operand, if yes then condition becomes true.

>= (greater than or equal Checks if the value of left operand is greater than or equal to the value
to) of right operand, if yes then condition becomes true.

Checks if the value of left operand is less than or equal to the value of
<= (less than or equal to)
right operand, if yes then condition becomes true.
CS8392-Object Oriented Programming in java UNIT : 1

The Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int, short,
char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13;
now in binary format they will be as follows −
a =00111100
b =00001101
a&b = 0 0 0 0 1 1 0 0
a|b =00111101
a^b = 0 0 1 1 0 0 0 1
~a = 1 1 0 0 0 0 1 1
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then −

Operator Description Example

& (bitwise Binary AND Operator copies a bit to the result (A & B) will give 12 which is
and) if it exists in both operands. 0000 1100

Binary OR Operator copies a bit if it exists in (A | B) will give 61 which is


| (bitwise or)
either operand. 0011 1101

^ (bitwise Binary XOR Operator copies the bit if it is set (A ^ B) will give 49 which is
XOR) in one operand but not both. 0011 0001

(~A ) will give -61 which is


~ (bitwise Binary Ones Complement Operator is unary 1100 0011 in 2's complement
compliment) and has the effect of 'flipping' bits. form due to a signed binary
number.

Binary Left Shift Operator. The left operands


A << 2 will give 240 which is
<< (left shift) value is moved left by the number of bits
1111 0000
specified by the right operand.

Binary Right Shift Operator. The left operands


A >> 2 will give 15 which is
>> (right shift) value is moved right by the number of bits
1111
specified by the right operand.
CS8392-Object Oriented Programming in java UNIT : 1

Shift right zero fill operator. The left operands


>>> (zero fill value is moved right by the number of bits A >>>2 will give 15 which is
right shift) specified by the right operand and shifted 0000 1111
values are filled up with zeros.

The Logical Operators

Assume Boolean variables A holds true and variable B holds false, then −

Operator Description Example

Called Logical AND operator. If both the operands are (A && B) is false
&& (logical and)
non-zero, then the condition becomes true.

Called Logical OR Operator. If any of the two operands (A || B) is true


|| (logical or)
are non-zero, then the condition becomes true.

Called Logical NOT Operator. Use to reverses the !(A && B) is true
! (logical not) logical state of its operand. If a condition is true then
Logical NOT operator will make false.
The Assignment Operators
Operator Description Example

Simple assignment operator. Assigns values from right C = A + B will assign


=
side operands to left side operand. value of A + B into C

Add AND assignment operator. It adds right operand to C += A is equivalent to


+=
the left operand and assign the result to left operand. C=C+A

Subtract AND assignment operator. It subtracts right


C -= A is equivalent to
-= operand from the left operand and assign the result to left
C=C– A
operand.

Multiply AND assignment operator. It multiplies right


C *= A is equivalent to
*= operand with the left operand and assign the result to left
C=C*A
operand.

/= Divide AND assignment operator. It divides left operand


C /= A is equivalent to C
with the right operand and assign the result to left
=C/A
operand.
CS8392-Object Oriented Programming in java UNIT : 1

Modulus AND assignment operator. It takes modulus C %= A is equivalent to


%=
using two operands and assign the result to left operand. C=C%A

C <<= 2 is same as C =
<<= Left shift AND assignment operator.
C << 2

C >>= 2 is same as C =
>>= Right shift AND assignment operator.
C >> 2

C &= 2 is same as C = C
&= Bitwise AND assignment operator.
&2

bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C


^=
^2

bitwise inclusive OR and assignment operator. C |= 2 is same as C = C |


|=
2

CLASSES AND OBJECTS IN JAVA

Object in Java:
• Object is the physical as well as logical entity whereas class is the logical entity only.
• An entity that has state and behavior is known as an object e.g. chair, bike, Banking
system, etc.
• An object has three characteristics:
o state: represents data (value) of an object.
o behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
o identity: Object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. But, it is used internally by the
JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.
• Object is an instance of a class. Class is a template or blueprint from which objects
are created. So object is the instance(result) of a class.
• Object Definitions:
o Object is a real world entity.
o Object is a run time entity.
o Object is an entity which has state and behavior.
o Object is an instance of a class.
CS8392-Object Oriented Programming in java UNIT : 1

Class in Java :
• A class is a group of objects which have common properties.
• It is a template or blueprint from which objects are created.
• It is a logical entity. It can't be physical.
• A class in Java can contain:
o Fields (Data Members)
o methods
o constructors(special method in name as that of your class)
o blocks
o nested class
and interface Syntax
to declare a class:
class <class name>
{ field;
method;
}
Types of Variables
There are three types of variables in java:
o local variable
o instance variable
o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called instance variable. It is
not declared as static.

It is called instance variable because its value is instance specific and is not shared among instances.

3) Static variable

A variable which is declared as static is called static variable. It cannot be local. You can create a single
copy of static variable and share among all the instances of the class. Memory allocation for static
variable happens only once when the class is loaded in the memory.
CS8392-Object Oriented Programming in java UNIT : 1

METHODS IN JAVA

o In java, a method is function


o It is used to expose behavior of an object(functionality).
o Advantage of Method
o Code Reusability
o Code Optimization
• A method can be called (invoked) at any point in a program simply by utilizing the
method’s name.
• A method as a subprogram that acts on data and often returns a value. Each method has its
own name.
• new keyword in Java
o The new keyword is used to allocate memory at run time. All objects get memory
in Heap memory area.
Example-1 Circle.java

class Circle
{
int r; //field or data member or instance variable

void calculateArea()
{
System.out.println("Radius : "+r);
System.out.println("Area : "+(3.14*r*r));
}

public static void main(String args[])


{
Circle s1 = new Circle ( ); //creating an object of Student
s1.r = 4; //accessing member through reference variable
s1. calculateArea ();
}
}

Example-2 StudentData.java

class StudentData
{
int id;
String studentname;
String collegename;
CS8392-Object Oriented Programming in java UNIT : 1

void setData()
{
id= 1;
studentname ="Kalam";
collegename ="AMS Engg College";
}
void putData()
{
System.out.println("ID "+id);
System.out.println("Name of the Student :"+studentname);
System.out.println("College Name :"+collegename);

}
public static void main(String args[])
{
StudentData s1 = new StudentData();
s1.setData();
s2.putData();

}
}

Example-3 : TestRectangle1.java

class Rectangle
{
int length;
int breath;

void getData( )
{
length=10;
breath=15;
}
void getData(int l,int b )
{
length=l;
breath=b;
}
void displayArea( )
{
System.out.println("\nLength :"+length);
System.out.println("Breath :"+breath);
System.out.println("Area :"+(length*breath));
}
}
CS8392-Object Oriented Programming in java UNIT : 1

class TestRectangle1
{
public static void main(String args[])
{
Rectangle r1=new Rectangle( );
Rectangle r2=new Rectangle( );
r1.getData();
r2.getData(10,12);
r1.displayArea();
r2.displayArea();
}
}

CONSTRUCTORs IN JAVA
• Java constructors are special methods that are called when an object is to be instantiated.
• The constructor initializes the newly created object.
• Here are the key differences between a constructor
and a method:
o A constructor doesn’t have a return type.
o Constructors are not considered members of a class.
o The purpose of constructor is to initialize the object of a class but the purpose
of a method is to perform a task .
o Constructor is invoked implicitly when an object is created but a method
has to be invoked explicitly.
o Constructors cannot be abstract final, static and synchronized while methods
can be
• Constructors can be divided into 2 types:
o Default Constructor.
o Parametrized Constructor.
o Copy Constructor
Default Constructor
• A default constructor is a 0 argument constructor which contains a no-argument call to the
super class constructor.
• To assign default values to the newly created objects.
• Compiler writes a default constructor in the code only if the program does not write any
constructor in the class.
Parameterized Constructors
• The parameterized constructors are the constructors having a specific number of
arguments to be passed.
• The purpose of a parameterized constructor is to assign user-wanted specific values to the
instance variables of different objects.
• A parameterized constructor is written explicitly by a programmer.
Copy Constructors
• The Copy constructors are the constructors objects are passed as parameter.
CS8392-Object Oriented Programming in java UNIT : 1

Example-4 : Rectangle.java

class Rectangle
{
int length;
int breadth;

Rectangle() //Default Constructor


{
length=10;
breadth=15;
}
Rectangle(int a,int b)
{
length=a;
breadth=b;
}
void displayData()
{
System.out.println("Length :"+length);
System.out.println("Breadth :"+breadth);
System.out.println("Area :"+(length*breadth));

}
public static void main(String args[])
{
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle(15,12);
r1.displayData();
r2.displayData();

}
CS8392-Object Oriented Programming in java UNIT : 1

Example-5 : TestCar.java

class Car
{
String name ;
String model;
Car( ) //Default Constructor
{
name ="Hyunndai";
model="il0";
}

Car(String n, String m) //Parameterized Constructor


{
name =n;
model=m;
}

Car(Car cc) //Copy Constructor


{
name =cc.name;
model=cc.model;
}
void display()
{
System.out.println("\n\nCar Name :"+name);
System.out.println("Car Model :"+model);
}
}
class TestCar
{
public static void main(String args[])
{
Car cl=new Car();
Car c2=new Car("Ford","Fiesta");
Car c3=new Car(c2);
cl.display();
c2.display();
c3.display();
}
}

Constructor Overloading
Overloaded constructors have the same name (name of the class) but different number of arguments.
Depending upon the number and type of arguments passed, specific constructor is called.
CS8392-Object Oriented Programming in java UNIT : 1

STATIC IN JAVA

• The static keyword in java is used for memory management .


• Java static keyword can be used with:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
STATIC VARIABLE

• The static variable gets memory only once in class area at the time of class loading.
• A single copy to be shared by all instances of the class
• A static variable can be accessed directly by the class name and doesn’t need any object
• The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees,college name of students
etc.
Example-6 : StudentData1.java
class StudentData1
{
int id;
String studentname;
static String collegename="AMS Eng College";

StudentData1(int i,String sn) //parametirized constructor


{
id= i;
studentname =sn;
}
void putData()
{
System.out.println("ID "+id);
System.out.println("Name of the Student :"+studentname);
System.out.println("College Name :"+collegename);
}
public static void main(String args[])
{
StudentData1 s1 = new StudentData1(1,"Kalam" );
StudentData1 s2 =new StudentData1(2, "Abul" );
StudentData1 s3 =new StudentData1(3, "Vinu" );
System.out.println(" Student Details ");
s1.putData();
s2.putData();
s3.putData();

}}
CS8392-Object Oriented Programming in java UNIT : 1

Example-7 : Counter.java

class Counter class Counter


{ {
int count=0;//will get memory when instance is static int count=0;//will get memory when
created // class loaded

Counter() Counter()
{ {
count++; count++;
System.out.println(count); System.out.println(count);
} }

public static void main(String args[]) public static void main(String args[])
{ {
Counter cl=new Counter(); Counter cl=new Counter();
Counter c2=new Counter(); Counter c2=new Counter();
Counter c3=new Counter(); Counter c3=new Counter();

} }
} }
Output: Output:
1 1
1 2
1 3
The variable count is initialized once for every static variable count is initialized only once for the
objectc1,c2,c3 of the class Counter class Counter shared by all objects
CS8392-Object Oriented Programming in java UNIT : 1

STATIC METHOD

• A static method belongs to the class rather than object of a class.


• A static method can be invoked without the need for creating an instance of a class.
• static method can access only static data member and can change the value of it.

Example-8 : Calculate.java

class Calculate
{

static int square(int x)


{
return x*x;
}
static int cube(int x)
{
return x*x*x;
}

public static void main(String args[])


{
int s,c;
s=Calculate.square(2); // Static method accessed directly using classname Calculate
System.out.println("Square :"+s);

c=Calculate.cube(3); // Static method accessed directly using classname Calculate


System.out.println("Cube :"+c);
}
}
class TestStaticMethod
{
int z=40;//non static
static void display()
{
System.out.println(z);
}
public static void main(String args[])
{
TestStaticMethod obj=new TestStaticMethod();
obj.display();
}
}
CS8392-Object Oriented Programming in java UNIT : 1

The main restrictions for the static method.


• The static method can not use non static data member or call non-static method directly.

In Example-5 : StudentData1.java (add the method changeCollege() and make the following
change in main function)
• collegename is static variable shared by all object to change value of the static variable
collegename we may use the following static method changeCollege() additionally in the
program
• //When we make changes in main method as follows college name of student 3 changes
• // A static method can be invoked with the name of the class

static void changeCollege()


{
collegename="AMS Polytechnic College";
}
public static void main(String args[])
{
StudentData1 s1 = new StudentData1 (1,"Kalam" );
StudentData1 s2 =new StudentData1 (2, "Abul" );
StudentData1 s3 =new StudentData1 (3, "Vinu" );
System.out.println(" Student Details ");
s1.putData();
s2.putData();
StudentData1.changeCollege();
s3.putData();

}
CS8392-Object Oriented Programming in java UNIT : 1

STATIC BLOCK
• It is used to initialize the static data member.It is executed before main method at the time
of class loading.
Example-9 : TestStaticBlock.java

class TestStaticBlock
{
void display()
{
System.out.println("Inside Display method");
}
static
{
System.out.println("Inside Static Block");
}
public static void main(String args[])
{
TestStaticBlock t1=new TestStaticBlock();
System.out.println("Inside Main Block Block");
t1.display();

} }
CS8392-Object Oriented Programming in java UNIT : 1

JAVA PACKAGE
• Packaging is Java’s way of grouping similar types of classes, interfaces and sub-packages.
• This grouping is done usually based on functionality.
• Package in java can be categorized in two form,
o built-in package
o User-defined package.
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math
operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and
support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
Advantage of Java Package
1. Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2. Java package provides access protection.
3. Java package removes naming collision.
Example Program
1. Create a folder mypack. d:\oops java\programs\Unit 1\mypack>
2. Create two classes Calcu1ator.java and ScientificCalculator.java and place them
in the folder mypack. d:\oops java\programs\Unit 1\mypack>
3. Compile all files and it generates *.class file.
4. Create a sub folder mysubpack under mypack folder.
d:\oops java\programs\Unit 1\mypack\mysubpack>
5. Create a class MathCalculator.java and place them
in the folder mysubpack. d:\oops java\programs\Unit 1\mypack\mysubpack>
6. Compile all files and it generates *.class file.
7. Now go to the working directory(d:\oops java\programs\Unit 1>) and use
above classes by import mypack.*; and import mypack.mysubpack.*;
Example-10 : Calculator.java
package mypack;
public class Calculator
{
public void sum(int a,int b)
{
System.out.println("Sum :"+(a+b));
}
}
CS8392-Object Oriented Programming in java UNIT : 1

Example-11 : ScientificCalculator.java
package mypack;
import java.lang.Math;

public class ScientificCalculator


{
public void squareroot(int n)
{
System.out.println("sqrt :"+ Math.sqrt(n));
}
}
Example-12 : MathCalculator.java
package mypack.mysubpack;
public class MathCalculator
{
public void sqaure(int x)
{
System.out.println("Square of "+x+" is :"+(x*x));
}
public void cube(int x)
{
System.out.println("Cube of "+x+" is :"+(x*x*x));
}
}
Example-13 : TestMypack.java
import mypack.*;
import mypack.mysubpack.*;
class TestMypack
{

public static void main(String args[])


{
Calculator cc=new Calculator();
cc.sum(2,3);

ScientificCalculator sc=new ScientificCalculator();


sc.squareroot(49);

MathCalculator mc=new MathCalculator();


mc.sqaure(2);
mc.cube(2);
}
}
CS8392-Object Oriented Programming in java UNIT : 1

ACCESS SPECIFIER IN JAVA

• An access modifier restricts the access of a class, constructor, data member


and method in another class. In java we have four access modifiers:
1. public -- visible to everyone
2. private -- Visible to class
3. default -- Visible to package
4. protected --Visible to package and all subclasses

Access Within Within Outside package Outside


Modifier class package and Subclass only package
public Y Y Y Y
private Y N N N
default Y Y N N
protected Y Y Y N

Private:

The private access modifier is specified using the keyword private.


• The methods or data members declared as private are accessible only within the
class in which they are declared.
• Any other class of same package will not be able to access these members.
• Classes or interface can not be declared as private.
In this example, we will create two classes A and B within same package p1. We will
declare a method in class A as private and try to access this method from class B and
see the result.
CS8392-Object Oriented Programming in java UNIT : 1

Example-14 : TestMypack.java

package p1;
class College
{
private void display()
{
System.out.println("AMS Engg College");
}
}
class TestCollege
{
public static void main(String args[])
{
College c1 = new College ();
c1.display();
}
}

Default:
.
• The data members, class or methods which are not declared using any access
modifiers i.e. having default access modifier are accessible only within the same
package.
• In this example, we will create two packages and the classes in the packages will
be having the default access modifiers and we will try to access a class from one
package from a class of second package.
CS8392-Object Oriented Programming in java UNIT : 1

Example-15 : A.java

package mypack;
class A
{
void msg()
{
System.out.println("Hello");
}
}

Example-16 : B.java

package p1;
import mypack.A;
class B
{
public static void main(String args[])
{
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
CS8392-Object Oriented Programming in java UNIT : 1

Protected:

• The protected access modifier is specified using the keyword protected.


• The methods or data members declared as protected are accessible within same
package or sub classes in different package.
• In this example, we will create two packages p1 and p2. Class Y in p1 is made
public, to access it in p2. The method display in class A is protected and class Z is
inherited from class Y and this protected method is then accessed by creating an
object of class B.

//save by Y.java
package p1;
public class Y
{
protected void msg()
{
System.out.println("Hello");
}
}

//save by Z.java
package p1;
import mypack.*;

class Z extends Y
{
public static void main(String args[])
{
Z obj = new Z();
obj.display();
}
}

Output:Hello

You might also like