Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Java M1

The document discusses object-oriented programming using Java. It provides an overview of Java, including that it is a platform-independent, general-purpose programming language. It discusses object-oriented programming and the two programming paradigms - procedure-oriented and object-oriented. Object-oriented programming organizes a program around objects and their attributes and behaviors, while procedure-oriented programming focuses on functions and actions. The document also lists some characteristics of procedure-oriented programming.

Uploaded by

gowrishhm.mp4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java M1

The document discusses object-oriented programming using Java. It provides an overview of Java, including that it is a platform-independent, general-purpose programming language. It discusses object-oriented programming and the two programming paradigms - procedure-oriented and object-oriented. Object-oriented programming organizes a program around objects and their attributes and behaviors, while procedure-oriented programming focuses on functions and actions. The document also lists some characteristics of procedure-oriented programming.

Uploaded by

gowrishhm.mp4
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Object Oriented Programming using JAVA

Chethan Raj C
Assistant Professor & HoD,
Dept of CSE
MODULE-01
 An Overview of Java
 Object-Oriented Programming (Two Paradigms, Abstraction, The Three OOP Principles).
 Using Blocks of Code
 Lexical Issues (Whitespace, Identifiers, Literals, Comments, Separators, The Java Keywords).
 Data Types
 Variables and Arrays
 The Primitive Types (Integers, Floating-Point Types, Characters, Booleans)
 Type Conversion and Casting— Refer class notes
 Automatic Type Promotion in Expressions-- Refer class notes
 Arrays
 Introducing Type Inference with Local Variables.
 Operators
 Operator Precedence
 Using Parentheses.
 Control Statements Refer class notes
 Java‘s Selection Statements (if, The Traditional switch) Refer class notes
 Iteration Statements (while, do-while, for, The For-Each Version of the for Loop, Local Variable Type Inference in a for Loop,
Nested Loops) Refer class notes
 Jump Statements (Using break, Using continue, return). Refer class notes

Chethan Raj C, HoD, Dept of CSE Page 1


Object Oriented Programming using JAVA
Introduction to Programming
Language
Language is medium which is used for communication. Ex: English, Kannada, Hindi, etc.

Programming
It is a Set of instruction / Group of instruction.

Programming Language
A Language which is used to communicate between user and system. Ex: C, C++, Java, Python etc.

Types of Programming Language


1. Low Level Programming Language
2. Middle Level Programming Language
3. High Level Programming Language

Low Level Programming Language


Language which is not understandable by humans but it is understandable by machine/system. Ex: Binary code (0, 1).

High Level Programming Language


A language which is written in simple English which is understandable by users. Ex: Java, c, c++, etc..
Low level language High level programming
Low level programming language isa machine friendly High level programming language is user-friendly language.
language.
Low level programming language ishigh memory High level programming language isless memory
efficiency. efficiency.
Debugging is difficult. Debugging is easy.
No need of translator. It needs translator.
Platform
It is combination of hardware and software components.
Example: windows, Linux, Unix, Mac etc.
Types of platform Programming Language
1. Platform dependent programming Language
2. Platform independent programming Language
Platform dependent Programming Language
Chethan Raj C, HoD, Dept of CSE Page 2
Object Oriented Programming using JAVA
Application which create in one platform we cannot run it in other platform.
Example: C & C++ etc..

Platform independent Programming Language


Application which create in one platform and we can running any other platform.
Example: Python, Java, etc..

An Overview of Java
Java is a general-purpose and object-oriented programming language developed for the distributed environment and software development
for consumer electronic devices such as TVs, VCRs, toasters, etc.
Java Programming Language is a platform-independent language, which means there is no limitation to any particular hardware or
operating system. It provides users the facility to ‗write once, run anywhere‘(WORA). Many operating systems such as Sun Solaris,
RedHat, Windows, etc., support Java.

Java is a concurrent, class-based, and object-oriented language. It is freely accessible, and we can run it on all the platforms or the operating
systems. Java is simple and easy to learn.
Ex: Java Hello World Example
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("HelloWorld!");
}
}

Object-Oriented Programming: JAVA PROGRAMMING


Everywhere you look in the real world you see objects—people, animals, plants, cars, planes, buildings, computers and so on. Humans
think in terms of objects. Telephones, houses, traffic lights, microwave ovens and water coolers are just a few more objects. Computer
programs, such as the Java programs are sometimes divided into objects of two categories: animate and inanimate. Animate objects are
―alive i.e they move around and do things. Inanimate objects, on the other hand, do not move on their own .Objects of both types,
however, have some things in common. All the objects have attributes-properites (e.g., size, shape, color and weight), and they all exhibit
behaviors (e.g., a ball rolls, bounces, inflates and deflates; a baby cries, sleep crawls, walks and blinks; a car accelerates, brakes and turns; a
clothes absorbs water). Humans learn about existing objects by studying their attributes and observing their behaviors. Different objects can
have similar attributes and can exhibit similar behaviors. Comparisons can be made, for example, between babies and adults and between

Chethan Raj C, HoD, Dept of CSE Page 3


Object Oriented Programming using JAVA
humans and chimpanzees. Object-oriented design provides a natural and intuitive way to view the software design process—namely,
modeling objects by their attributes and behaviors just as we describe real-world objects. OOD also models communication between
objects. Just as people send messages to one another (e.g., a sergeant commands a soldier to stand at attention), objects also communicate
via messages. A bank account object may receive a message to decrease its balance by a certain amount because the customer has
withdrawn that amount of money.

Two Paradigms
In General all computer programs consist of two elements: code and data. Furthermore, a program can be conceptually organized around
its code or around its data. That is, some programs are written around ―what is happening and others are written around ―who is being
affected. These are the two paradigms that govern how a program is constructed. The first way is called the process-oriented model. This
approach characterizes a program as a series of linear steps (that is, code). The process-oriented model can be thought of as code acting on
data. Procedural languages such as C employ this model. Problems with this approach appear as programs grow larger and more complex
and to manage program is increasing in complexity. The second approach, called object-oriented programming, where Object-oriented
programming(OOP) organizes a program around its data (that is, objects) and a set of well-defined interfaces to that data. An object-
oriented program can be characterized as data controlling access to code as by switching the controlling entity to data, you can achieve
several organizational benefits.

Procedure oriented Programming (POP): In this approach, the problem is always considered as a sequence of tasks to be done. A
number of functions are written to accomplish these tasks. Here primary focus on ―Functions‖ and little attention on data. There are many
high level languages like COBOL, FORTRAN, PASCAL, C used for conventional programming commonly known as POP. POP basically
consists of writing a list of instructions for the computer to follow, and organizing these instructions into groups known as functions.

Normally a flowchart is used to organize these actions and represent the flow of control logically sequential flow from one to another. In a
multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function
may have its own local data. Global data are more vulnerable to an in advent change by a function. In a large program it is very difficult to
identify what data is used by which function. In case we need to revise an external data structure, we should also revise all the functions
that access the data.
Drawback: It does not model real world problems very well, because functions are action oriented and do not really corresponding to the
elements of the problem.
Chethan Raj C, HoD, Dept of CSE Page 4
Object Oriented Programming using JAVA

Characteristics of POP:
1. Emphasis is on doing actions.
2. Large programs are divided into smaller programs known as functions.
3. Most of the functions shared global data.
4. Data move openly around the program from function to function.
5. Functions transform data from one form to another.
6. Employs top-down approach in program design.

Object Oriented Programming (OOP):


OOP allows us to decompose a problem into a number of entities called objects and then builds data and methods around these entities.
OOP is an approach that provides a way of modularizing programs by creating portioned memory area for both data and methods that can
used as templates for creating copies of such modules on demand. That is ,an object a considered to be a partitioned area of computer
memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be
used in a variety of different programs without modifications.

Characteristics of OOP:
1. Emphasis on data .
2. Programs are divided into what are known as methods.
3. Data structures are designed such that they characterize the objects.
4. Methods that operate on the data of an object are tied together .
5. Data is hidden.
6. Objects can communicate with each other through methods.
7. Code Reusability.
8. Follows bottom-up approach in program design.

Chethan Raj C, HoD, Dept of CSE Page 5


Object Oriented Programming using JAVA

History of JAVA
 Java is started by company called as Sun microsystem.
 Java currently owned company called as Oracle.
 Java is invented by person called as James Gosling.
The first name of Java was Green talk but the name was not so popular so renamed as oak in the year 1991 but the name was already
registered by some other company later it is renamed as Java in the year 1994-95 and coffee mug is the sign of symbol for JAVA.

• Java was introduce in the year 1994


• JDK 1.0 is introduce in 1996
• Currently we have JDK 21 which is lunched in September 2023

Introduction to Java
Java is an object oriented language, complete java language is built on classes and object. Java is also known as a strong Object-oriented
programming language(oops). OOPS is a programming approach which provides solution to problems with the help of algorithms based on
real world. It uses real world approach to solve a problem. So object oriented technique offers better and easy way to write program then
procedural programming model such as C, ALGOL, PASCAL. Object oriented languages has 2 building blocks i) class -> template of an
object ii) object -> a real world or an instance of a class In Java everything is encapsulated under classes. Class is the core part of the Java
language. Object-Oriented Programming is a strategy or a style of developing applications or developing software. It is a methodology.
Other methodologies are also there like Structured Programming, Procedural Programming, Modular Programming. or Aspect-Oriented
programming. But nowadays, one of the well-known and famous styles is Object Orientation. Nowadays, all the latest programming
languages support object orientation and this object orientation is more related to the designing of software and this deals with internal
design but not external that is visible designing. So, it is nowhere related to the users of the software, it is related to the programmers who
are working on developing software.

Chethan Raj C, HoD, Dept of CSE Page 6


Object Oriented Programming using JAVA
With the help of object orientation, the application development or the programming becomes more and more systematic and user can
follow the procedures of engineering to develop software. Like other engineering, how any product is developed, in the same way, a
software product is developed by adopting object orientation. Consider the other engineering branches like a civil engineer is constructing a
building then firstly user will make a plan and then make a design. While making a design, they may be having many options but they will
select one of the designs and finalize it. Then once it is finalized as a blueprint on paper then they will start constructing. In the same way,
an electronic engineer, when user is manufacturing any device, will come up with some design that is the circuit design of that device on
paper. Once it is finalized then he will start manufacturing the device. So, on paper user make blueprints but recently users are not using
paper nowadays. Users have many computer editing tools for developing software and a team of programmers can work over a single
software and the work can be distributed easily and the work can be reused between the programmers very easily.
So, Object Orientation all depends on how user see the system or how user understand the system. Looking at the system and user
perspective is more important. So, if user understand the system perfectly and if user perspective is very clear then user can develop a better
system. Not just Object-Oriented Programming, there are other programming styles also available like Procedural Programming, Modular
Programming. or Structure Programming, or Aspect Programming but Object-Oriented Programming is a well known and successful
pattern for software development, and most of the latest languages that are used for application development, they are object-oriented.

Abstraction
Abstraction is the process of hiding the internal and secured details and showing just the functionality. Abstraction can be achieved through
abstract class or interface in Java. Hiding internal details and showing required functionality is known as abstraction.
For example: In phone call, user don't know the internal processing. In java, user use abstract class and interface to achieve abstraction.
Hiding the Implementations from the User which are not necessary, and showing the necessary details to the user i.e., method names,
parameters, returns types. Abstraction is achieved by using interfaces, interfaces will have only method declarations, it suggests what
method does but doesn‗t suggest how it is implemented. So that the implementation is done by somebody else and interfaces are used other
developers
1. Abstract classes offer default functionality for the subclasses.
2. Provides a template for future specific classes
3. Helps user to define a common interface for its subclasses
4. Abstract class allows code reusability.

The Java's smallest unit of abstraction is class. Because of the interplay between the classes and packages, Java addresses the following four
categories of visibility for class members :
1. Subclasses in same package
2. Non-subclasses in same package
3. Subclasses in different packages
4. Classes that are neither in same package nor in subclasses.

Chethan Raj C, HoD, Dept of CSE Page 7


Object Oriented Programming using JAVA
Features of Java/Java Buzzwords
Features of a language are nothing but the set of services or facilities provided by the language vendors to the industry programmers. Some
important features of java are;

Fig: Java Program Features


1. Simple
1 Java was designed to be easy for professional programmer to learn and use effectively.
2 It‘s simple and easy to learn if user knows the basic concepts of Object Oriented Programming(OOP).
3 C++ programmer can move to JAVA with very little effort to learn.
4 In Java, there is small number of clearly defined ways to accomplish a given task.
5 As Java inherits the C/C++ syntax and many of the object-oriented features of C++, its easy to learn.

It is simple because of the following factors also:


Java was developed by taking the best points from other programming languages, primarily C and C++.
1. It is free from pointer i.e handled by the Java environment automatically rather than by the programmer, due to this execution time
of application is improved. [Whenever user write a Java program without pointers then internally it is converted into the equivalent
pointer program].
2. It has Rich set of API (application protocol interface).
3. It has Garbage Collector which is always used to collect un-Referenced (unused) Memory location for improving performance of a
Java program.
4. It contains user friendly syntax for developing any applications.

Chethan Raj C, HoD, Dept of CSE Page 8


Object Oriented Programming using JAVA
2. Object oriented
Java is object oriented language.
 Almost ―Everything is an Object‖ paradigm. All program code and data reside within objects and classes.
 The object model in Java is simple and easy to extend.
 Java comes with an extensive set of classes, arranged in packages that can be used in our programs through inheritance.

3. Secure
Java goes to the great security issues by putting in place multilevel system of security.
First at the compile time pointers and memory allocation are removed even though the java compiler produces only correct java code
there is still the possibility of the code being tempered with between compilation and runtime. java guards against this by using bytecode
Verifier to check the bytecode for language compliance when the code fist enters the interpreter before it gets the chance to run. It also
specifies following things that the code does not do any of the following.
 Forge pointers
 Violate access restrictions
 Incorrectly access classes
 Overflow or underflow operand stack
 Use incorrect parameters of bytecode instructions
 Use illegal data conversions
Second at run time the java interpreter further ensures that classes loaded do not access the file system except in the manner permitted
by the client Or the user.
Sun Microsystems adds another dimension to the security of java. They are currently working on public key encryption system to allow
java applications to be stored and transmitted over the internet in a secure encrypted form.

4. Compiled, Interpreted and High Performance programming Language.


Usually a computer language is either compiled or Interpreted. Java combines both this approach and makes it a two-stage system.
• Compiled: Java enables creation of a cross platform programs by compiling into an intermediate representation called Java Bytecode.
• Interpreted: Bytecode is then interpreted, which generates machine code that can be directly executed by the machine that provides a
Java Virtual machine.
When java code is compiled by the compiler outputs the java bytecode which is an executable for the Java virtual machine(JVM). The
bytecode is then run through a java interpreter on any given platform that has the interpreter parted to it. The interpreter converts the code
to the target hardware and executes it.
Note: In this architecture same application is distributed in multiple server system.

Chethan Raj C, HoD, Dept of CSE Page 9


Object Oriented Programming using JAVA
Since the bytecode produced by the Java compiler from the corresponding source code is very close to machine code, it can be interpreted
very efficiently on any platform. In cases where even greater performance is necessary than the interpreter can provide, just-in-time
compilation can be employed whereby the code is compiled at run-time to native code before execution.
It have high performance because of following reasons;
• This language uses Bytecode which is faster than ordinary pointer code so Performance of this language is high.
• Garbage collector, collect the unused memory space and improve the performance of the application.
• It has no pointers so that using this language user can develop an application very easily.
• It support multithreading, because of this time consuming process can be reduced to executing the program.

The Java language supports many high-performance feature such as multithreading, just-in-time compiling, and native code usage.

Java has employed multithreading to help overcome the performance problems suffered by interpreted code as compared to native code.
Since an executing program hardly ever uses CPU cycles 100 % of the time, Java uses the idle time to perform the necessary garbage
cleanup and general system maintenance that renders traditional interpreters slow in executing applications. [Note: Multithreading is the
ability of an application to execute more than one task (thread) at the same time e.g. a word processor can be carrying out spell check in one
document and printing a second document at the same time.

5. Platform Independent
A program or technology is said to be platform independent if and only if which can run on all available operating systems with respect to
its development and compilation. (Platform represents O.S).
Platform independent: Java programs use the Java virtual machine as abstraction and do not access the operating system directly. This
makes Java programs highly portable. A Java program (which is standard-compliant and follows certain rules) can run unmodified on all
supported platforms, e.g., Windows or Linux.

6. Architectural Neutral
A Language or Technology is said to be Architectural neutral means, which can run on any available processors in the real world without
considering their development and compilation with other specifications and requirements as ―write once; run anywhere, any time,
forever.‖(WORA).

Chethan Raj C, HoD, Dept of CSE Page 10


Object Oriented Programming using JAVA
Changes and upgrades in operating systems, processors and system resources doesn‘t affect the any changes in Java Programs.

The languages like C, CPP are treated as architectural dependent.

7. Portable
If any language supports platform independent and architectural neutral feature known as portable. The languages like C, CPP, Pascal are
treated as non-portable language. It is a portable language.
•Java Provides a way to download programs dynamically to all the various types of platforms connected to the Internet.
•It helps in generating Portable executable code.

8. Multithreaded
Java was designed to meet the real world requirement by creating interactive networked programs.
Java programs can do many things simultaneously.To accomplish this java support multithreaded programming which allows user to write
programs that does many things and tasks simultaneously.

A flow of control is known as a thread i.e single line of execution in program. When any Language executes multiple thread at a time that
language is known as multithreaded. Java‘s easy-to-use approach to multithreading allows to work on specific behaviour of the program,
not the multitasking subsystem.

9. Distributed
Java is designed for the environment of internet because it handles TCP\IP protocol and be able to access files on the internet as easily,as
writing to a local file system.
Java also allows objects on two different computers to execute procedures remotely. java has recently revised this interfaces in a package
called Remote Method Invocation(RMI).

Chethan Raj C, HoD, Dept of CSE Page 11


Object Oriented Programming using JAVA
This feature brings an unparallel level of abstraction to client server programming.
• Java is designed for distributed environment of the Internet. Its used for creating applications on networks.
• Java applications can access remote objects on Internet as easily as they can do in local system.
• Java enables multiple programmers at multiple remote locations to collaborate and work together on a single project.

10. Networked
It is mainly designed for web based applications, J2EE is used for developing network based applications.

11. Robust
Java is a robust language. It provides many safeguards to ensure reliable code. The ability to create robust programs was given a high
priority in the design of Java. Java is a strictly typed language; it checks the code at compile time. However, it also checks user code at run
time. In fact, many hard-to-track-down bugs that often turn up in hard-to-reproduce run-time situations are simply impossible to create in
Java.
There are two reasons for program failure
1. memory management mistakes
2. mishandled exceptional conditions
Java manages memory automatically by using garbage collector. Exception conditions are handled in java by providing object
exception handling. In the well written java program all runtime errors can and should be managed by the program.
Note: Robust simply means strong. It is robust or strong Programming Language because of its capability to handle Run-time Error,
automatic garbage collection, the lack of pointer concept, Exception Handling. All these points makes java robust Language.

12. Dynamic

Chethan Raj C, HoD, Dept of CSE Page 12


Object Oriented Programming using JAVA
By connecting to the internet a user immediately has access to thousands of programs and other computers. During the execution of a
program java can dynamically load classes that it requires either from the local hard drive from another computer on the local area network
or from a computer somewhere on the internet.
 Java is capable of linking in new class libraries, methods, and objects.
 It can also link native methods (the functions written in other languages such as C and C++).
It supports Dynamic memory allocation due to this memory wastage is reduce and improve performance of the application. The process of
allocating the memory space to the input of the program at a run-time is known as dynamic memory allocation, To programming to allocate
memory space by dynamically user use an operator called 'new' 'new' operator is known as dynamic memory allocation operator.

13. Secure
It is a more secure language compared to other language; In this language, all code is covered in byte code after compilation which is not
readable by human.

The Three OOP Principles


Object-oriented programming refers to the practice of defining classes and objects to organize code, and is used in most programming
languages today. There are three major pillars on which object-oriented programming relies: encapsulation, inheritance, and polymorphism.

Encapsulation:
The most adopted and popular programming language approach, structured programming approach, failed to show the desired results in
terms of bug-free, easy-to-maintain, and reusable programs.

The programming approach, Object-Oriented approach (OOP), offers a new and powerful way to cope with this complexity. The approach
of OOP is based on various concepts that help achieve its goal to overcome the drawbacks of structured programming approaches.

Encapsulation is one of the most powerful and fundamental concepts of Object-Oriented Programming. Encapsulation, in general, is the
action of enclosing or binding the data and member function. In OOP, it is a way of combining both data and functions that operate on that
data, into a single unit.

In other words, we can define it as Encapsulation is the wrapping up of data and functions (methods that operate on the data) into a single
unit (called class).

Note:
There is a prohibition for direct access to the data. Functions (that combine with the data) are the only way to access data. These functions are
the member functions or methods in Java. It basically creates a shield due to which the code or data cannot be accessed outside the shield.

Chethan Raj C, HoD, Dept of CSE Page 13


Object Oriented Programming using JAVA
If you want to read data items in an object, you call the member function in the object. It will read the data item from the function and return
the value to you. You can‘t access the data directly using the object. The data is hidden, so it is kept protected and safe from accidental
alteration.

Inheritance: Inheritance is a process of acquiring the properties, functionalities and behaviors defined in one class (Base class) into to
another class (Derived class). In java extends keyword is used for inheritance concept. Inheritance provides and achieves the reusability of
code from one class to another class.
• Is-A Relationship
• Has-A Relationship.
One of the advantages of an Object-Oriented programming language is code reuse. There are two ways user can do code reuse either by the
implementation of inheritance (IS-A relationship), or object composition (HAS-A relationship). Although the compiler and Java virtual
machine (JVM) confirms the use of inheritance, user can also get at the functionality of inheritance when user use composition.

Advantages:
1. The main purpose of the inheritance is code extensibility whenever user are extending automatically the code is reused.
2. In inheritance one class giving the properties and behavior and another class is taking the properties and behavior.
3. Inheritance is also known as is-a relationship means two classes are belongs to the same hierarchy
4. By using extends keyword user are achieving inheritance concept.
5. In the inheritance the person who is giving the properties is called parent the person who is taking the properties is called child.
6. To reduce length of the code and redundancy of the code the concept of inheritance is introduced.

Polymorphism
Polymorphism in Java is the task that performs a single action in different ways. So, languages that do not support polymorphism are not
‗Object-Oriented Languages‘, but ‗Object-Based Languages‘. Ada, for instance, is one such language. Since Java supports polymorphism,
it is an Object-Oriented Language.
Polymorphism occurs when there is inheritance, i.e., many classes are related. Inheritance is a powerful feature in Java. Java Inheritance
lets one class acquire the properties and attributes of another class. Polymorphism in Java allows us to use these inherited properties to
perform different tasks. Thus, allowing us to achieve the same action in many different ways. ―Poly‖ means numerous, and ―Morphs‖
means forms. So, polymorphism means innumerable forms. Polymorphism, therefore, is one of the most significant features of Object-
Oriented Programming.

User can perform Polymorphism in Java via two different methods:


1. Method Overloading
2. Method Overriding

Chethan Raj C, HoD, Dept of CSE Page 14


Object Oriented Programming using JAVA
Method Overloading in Java
Method overloading is the process that can create multiple methods of the same name in the same class, and all the methods work in
different ways. Method overloading occurs when there is more than one method of the same name in the class.
What is Method Overriding in Java?
Method overriding is the process when the subclass or a child class has the same method as declared in the parent class.
Polymorphism in Java can be classified into two types, i.e:
1. Static/Compile-Time Polymorphism
2. Dynamic/Runtime Polymorphism

Compile-Time Polymorphism in Java


Compile Time Polymorphism In Java is also known as Static Polymorphism. Furthermore, the call to the method is resolved at compile-
time. Compile-Time polymorphism is achieved through Method Overloading. This type of polymorphism can also be achieved through
Operator Overloading. However, Java does not support Operator Overloading.

Method Overloading is when a class has multiple methods with the same name, but the number, types, and order of parameters and the
return type of the methods are different. Java allows the user freedom to use the same name for various functions as long as it can
distinguish between them by the type and number of parameters
Runtime polymorphism in Java is also popularly known as Dynamic Binding or Dynamic Method Dispatch. In this process, the call to an
overridden method is resolved dynamically at runtime rather than at compile-time. You can achieve Runtime polymorphism via Method
Overriding.
Method Overriding is done when a child or a subclass has a method with the same name, parameters, and return type as the parent or the
superclass; then that function overrides the function in the superclass. In simpler terms, if the subclass provides its definition to a method
already present in the superclass; then that function in the base class is said to be overridden. Also, it should be noted that runtime
polymorphism can only be achieved through functions and not data members.

Overriding is done by using a reference variable of the superclass. The method to be called is determined based on the object which is being
referred to by the reference variable. This is also known as Upcasting.
Upcasting takes place when the Parent class‘s reference variable refers to the object of the child class.

Structure and execution flow of Java Program:


Once developer received the requirement developer/user team start working on it and write a java program which is also known as
source code and save the file as(filename. java) to check any bugs or mistakes or errors developers is going to give the compiler for a
compilation purpose.

Chethan Raj C, HoD, Dept of CSE Page 15


Object Oriented Programming using JAVA
Java Program Structure
A Java program may contain many classes of which only one class defines a main method. Classes contain data members and methods that
operate on the data members of the class Method may contain data type declaration and executable statement. To write a Java program user
first define classes and then put them together. A java program may contain one or more section
Documentation Section
The documentation section comprises a set of comment lines giving the name of the program the author and other details, which the
programmer would like to refer to at a later stage. Comments must explain why and what of classes and hoe of algorithms. This would
greatly help in maintaining the program. In addition to the two styles of comments discussed earlier. Java also uses a third style of comment
/**…..*/ Known as documentation comment. This form of comment is used for generating documentation automatically.
Package: Packages in Java are groups of similar types of collection of classes, interface and sub packages. It is a way of grouping a variety
of classes or interfaces collectively. The grouping is usually done according to functionality. The Java packages act as containers for Java
classes.
There is also a term named sub-packages. Package inside the package is called the sub-package. It should be created to categorize the
package further.
Package Statement: The first statement allowed in a Java file is a Package statement. This statement declare a Package name and informs
the compiler that the classes defined here belong to this package. The package statement is optional. Example
package p1;

1. Documentation Section
2. Package Statement
3. Import Statement
4. Interface Statement
5. Class Definition
6. Main Method Class
{
main Method Definition
}

Import Statement: After a package statement (but before any class definition)may be a number of import statement. This is similar to the
#include statement in C
Example: import java.util.Date;
This statement instructs the interpreter to load the Date class contained in the package util.
The benefits of organizing classes:

Chethan Raj C, HoD, Dept of CSE Page 16


Object Oriented Programming using JAVA
1. The classes contained in the packages of another program can be easily reused.
2. Packages also allow programmers to separate design from coding.
3. In packages, classes can be declared uniquely compared with classes in other packages.
4. Java Packages provide a way to ‗hide‘ classes thus preventing other programs or packages from accessing classes that are meant for
internal use only.
5. Packages provide access protection.
6. Java package removes naming collision.
For most applications, programmers need to use different sets of classes, one for the internal representation of program‘s data and other for
the external presentation purposes. User may build own classes for handling the program data and use existing class libraries for designing
class libraries for designing the user interface.
Interface Statement: An interface is like a class but includes a group of method declaration. This is also optional section and is used only
when wish to implement the multiple inheritance feature in the program. Interface is a new concept in Java.
Interface: An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide
the behaviour published by that interface. This section defines a simple interface and explains the necessary changes for any class that
implements it.

Compiler
Compiler is a system software and it checks any bugs is there in the program, if it find any bugs then compiler throw the compilation
error to the user and user should debug and sent the code back to the compiler to compile it for error free in a given source program,
this process will be repeated until it correct it, once compiler didn't found any mistake then the compiler is going to convert source
code into byte code and saved file name as (filename.class).

Byte code
Byte code is an intermediate code which is not understandable by machine nor by human beings and byte code a platform independent
which means byte code can be run in any operating system like windows, Linux, Mac, etc. with the help of JVM.

JVM (Java virtual Machine)


Java virtual Machine reads the byte code line by line and convert it to machine understandable language with the help of JIT(Speed
up the process of Interpretation) and interpreter. JVM is a platform dependent which means JVM used for windows is not same for
any other operating system.

JDK: It is a collection of essential resources and software which is used for development of java application.
JRE (Java runtime environment): It will provide the environment for execution of Java program.
JVM (Java virtual Machine): It is used to convert bytecode into machine code with the help of JIT and interpreter.

Chethan Raj C, HoD, Dept of CSE Page 17


Object Oriented Programming using JAVA
Interpreter: It is a translator which is used to convert bytecode into machine code in Java.

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.
o When the end of main is reached the program terminates and the control transferred back to the Operating system.
main() method is the starting execution block of a java program or any java program to start their execution from main method. If any class
contain main() method known as main class.
Syntax of main() method:public static void main(String args[])
{
.......
.......
}

Public: This is the access modifier of main method. It has to be public so that java runtime can execute this method. Remember that if user
can make any method non-public then it‘s not allowed to be executed by any program, there are some access restrictions applied. So it
means that main method has to be public

public is a keyword in a java language whenever if it is preceded by main() method the scope is available anywhere in the java environment
i.e main() method can be executed from anywhere. main() method must be accessed by every java programmer and hence whose access
specifier must be public.

Static: When java runtime starts, there is no object of the class present. That‘s why main method has to be static, so that JVM can load the
class into memory and call the main method. If main method won‘t be static, JVM would not be able to call it because of there is no object
of the class is present.

Chethan Raj C, HoD, Dept of CSE Page 18


Object Oriented Programming using JAVA
In java static keyword is preceded to any class properties for that memory is allocated only once in the program. Static method are executed
only once in the program. The main() method of java executes only once throughout the java program execution and hence it declare must
be static.

void: void is a special datatype also known as no return type, whenever it is preceded by main() method that will be never return any value
to the operating system. main() method of java is not returning any value and hence its return type must be void.

String args[] String args[] is a String array used to hold command line arguments in the form of String values. User can change the order of
modifiers i.e Instead of String[] args. Java main method accepts a single argument of type String array. This is also called as java command
line arguments. The example of using java command line arguments.
Ex: public class Test
{
public static void main(String[] args)
{
for(String s : args)
{
System.out.println(s);
}
}
}

Chethan Raj C, HoD, Dept of CSE Page 19


Object Oriented Programming using JAVA
JDK (Java Development Kit)

How to create a main method


Syntax:
public static void main(String[] args) // String[] args or String [] args
{
Statements;
}

Printing Statement
1. System.out.println(data);
2. System.out.print(data);

println(): Print the data and cursor will be shifted into the next line.
print(): Print the data and cursor will be staying in the same line.

Using Blocks of Code


A code block is a grouping of two or more statements. This is done by enclosing the statements between opening and closing curly braces.
Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can.

A code block is a section of code enclosed in curly braces {}. Code blocks are used to group one or more statements. Code blocks can be
nested, meaning you can have code blocks inside of other code blocks.
The example below is a code block that contains a single statement:
{

Chethan Raj C, HoD, Dept of CSE Page 20


Object Oriented Programming using JAVA
int x = 10;
}
A code block enclosing a single statements
The code block in the code above contains a single statement, int x = 10;.

Code blocks usually contain multiple statements. The example below is a code block that contain multiple statements:
{
int x = 10;
int y = 20;
System.out.println(x + y);
}
A code block enclosing multiple statements
In the code example above, the code block is the section of code between the opening curly brace { and the closing curly brace }. In the
above code block is used to group the int x = 10;, int y = 20;, and System.out.println(x + y); statements. When the code block is executed,
the statements are run from top to bottom.

The static code block


Static code blocks are a special type of code block that are used to initialize variables. Static code blocks are marked with the
statickeyword. The initialization code is run only once when the class is first loaded.

The following is an example of a static code block:


1. public class MyClass
2. {
3. static int x;
4. static
5. {
6. // This code is run only once
7. // when the class is first loaded.
8. x = 10;
9. }
10. public static void main(String[] args)
11. {
12. System.out.print("x -> " + x);
13. }

Chethan Raj C, HoD, Dept of CSE Page 21


Object Oriented Programming using JAVA
14. }

Above Java program demonstrating static code blocks

Logic
• Line 1: We declare a class named MyClass.
• Line 3: We declare a static variable x of type integer. The static keyword is used to mark a variable as a static variable.
• Line 4: We declare a static code block. Here, the x variable is initialized to 10.
• Line 10: The main() method is declared.
• Line 10: The println() statement is used to print the value of x to the console.
When the above code is compiled and run, it will produce the following output:

x -> 10
The output of the static block code example
As you can see from the output, the value of x is 10. This is because the static code block is executed only once when the class is first
loaded.

The main() code block


Every Java program has at least one code block, which is the code block that contains the main() method.
class Main
{
public static void main(String[] args)
{
// this is the main code block
// it contains the program's entry point
int x = 10;
int y = 20;
System.out.println(x + y);
}
}

A code block example in Java


We create a class named Main, which contains the main() method.
We have a code block inside of the main() method.

Chethan Raj C, HoD, Dept of CSE Page 22


Object Oriented Programming using JAVA
We declare a variable x and initialize it with the value 10.
We declare a variable y and initialize it with the value 20.
We print the sum of x and y.
When the program is run, the code in the main() code block is executed. The output of the code would be 30.

Creating methods
Code blocks can also be used to create methods in Java. A method is a self-contained section of code that performs a specific task. When
you create a method, you give it a name and specify the code block that contains the statements that the method will execute.
Code example
public static void printSum(int x, int y)
{
// this is the method's code block
// it contains the statements that the method will execute
System.out.println(x + y);
}

A method in Java
• The printSum() method has a code block that contains a single statement.
• This statement prints out the sum of the variables x and y.

Calling a method
You can call a method from another method, or from the main() method. When you call a method, the code in the method's code block is
executed.
class Main
{
public static void printSum(int x, int y)
{
// this is the method's code block
// it contains the statements that the method will execute
System.out.println(x + y);
}
public static void main(String[] args)
{
// this is the main method

Chethan Raj C, HoD, Dept of CSE Page 23


Object Oriented Programming using JAVA
int x = 10;
int y = 20;
// call the printSum() method
printSum(x, y);
}
}
A Java code example demonstrating calling a method.
• We create a class named Main, which contains the main() method.
• We create the printSum() method. This method has two parameters, x and y.
• We have a code block inside of the printSum() method. This code block contains a single statement that prints out the sum of x and y.
• We create the main() method, which is the entry point for our program.
• The main() method calls the printSum() method. When the printSum() method is called, the code in its code block is executed and the sum
of x and y is printed out.

Nested code clocks


You can also nest code blocks inside of other code blocks. Nested code blocks are often used to group related statements.
class Main
{
public static void main(String[] args)
{
// this is the main method
int x = 10;
int y = 20;
// this code block is nested inside the main method
{
// print out the sum of x and y
System.out.println(x + y);
// print out the difference of x and y
System.out.println(x - y);
}
}
}
A Java code demonstrate nested code blocks

Chethan Raj C, HoD, Dept of CSE Page 24


Object Oriented Programming using JAVA
Logic
• Line 8–14: There is a code block nested inside the main() method. This code block contains two statements.
• Line 10: The statement prints out the sum of x and y .
• Line 13: The statement prints out the difference of x and y.

Lexical Issues (Whitespace, Identifiers, Literals, Comments, Separators, The Java Keywords).
Java programs are the collection of whitespace, identifiers, literals, comments and separators. Lexical issues are very common in
programming, which is used to analysis, operate and implement the program in a sequential order.

Computer languages, like human languages, have a lexical structure. A source code of a Java program consists of tokens. Tokens are
atomic code elements. In Java we have comments, identifiers, literals, operators, separators, and keywords.

Java programs are composed of characters from the Unicode character set.The atomic elements of Java programs is a collection of
whitespace, identifiers, literals, comments, operators, separators, and keywords.

Whitespace
Java is a free-form language. This means that you do not need to follow any special indentation rules. For instance, the Example program
could have been written all on one line or in any other strange way users like typing it, as long as there was at least one whitespace
character between each token that was not already delineated by an operator or separator. In Java, whitespace is a space, tab, or newline.
For example, there is no format to be followed to write a Java program. A program can be written even in a single line or any number of
lines can be used, whatever the user wishes. By default, single whitespace is required between each character.

White space in Java is used to separate tokens in the source file. It is also used to improve readability of the source code.

int i = 0;

White spaces are required in some places. For example between the int keyword and the variable name. In other places, white spaces are
forbidden. They cannot be present in variable identifiers or language keywords.

int a=1;
int b = 2;
int c = 3;

Chethan Raj C, HoD, Dept of CSE Page 25


Object Oriented Programming using JAVA
The amount of space put between tokens is irrelevant for the Java compiler. The white space should be used consistently in Java source
code.

Identifiers
A name given to all the components of Java is known as identifiers An identifier is referred as any descriptive sequence of uppercase,
lowercase letters, underscore or a dollar sign character. Identifiers are used for specifying the class name, method name and variable name.
Since Java is case-sensitive language any letter of a word will be different from another word (VALUE is a different identifier than Value,
The dollar-sign character is not intended for general use.). Some examples of valid identifiers are AvgTEmp, Count, a4, $test, a_b and
invalid identifiers are 2Count, high-temp, Not/ok.
These are valid Java identifiers.
 String name23;
 int _col;
 short car_age;

These are not valid Java identifiers.


 String 23name;
 int %col;
 short car age;

Example:
class Test
{
public static void main(String[] args)
{
}
}
Test, main are identifiers
Rules of identifiers

Chethan Raj C, HoD, Dept of CSE Page 26


Object Oriented Programming using JAVA
• It's not start with the numbers.
• Special characters are not allowed other than $ and _ as identifiers.
• We cannot use keywords has identifiers
• Space or not allowed in identifiers.
Identifiers are names for variables, methods, classes, or parameters. Identifiers can have alphanumerical characters, underscores and dollar
signs ($). It is an error to begin a variable name with a number. White space in names is not permitted.

Identifiers are case sensitive. This means that Name, name, or NAME refer to three different variables. Identifiers also cannot match
language keywords.

There are also conventions related to naming of identifiers. The names should be descriptive. We should not use cryptic names to
identifiers. If the name consists of multiple words, each subsequent word is capitalized.

The following program demonstrates that the variable names are case sensitive. Event though the language permits this, it is not a
recommended practice to do.

public class CaseSensitiveIdentifiers


{
public static void main(String[] args)
{
String name = "GC";
String Name = "CKP";
System.out.println(name);
System.out.println(Name);
}
}

Name and name are two different identifiers. In Visual Basic, this would not be possible. In this language, variable names are not case
sensitive.

$ javac CaseSensitiveIdentifiers.java
$ java CaseSensitiveIdentifiers

Chethan Raj C, HoD, Dept of CSE Page 27


Object Oriented Programming using JAVA

Output: GC
CKP

Literals
The data or constant value written by a programmer in the program is known as literals.
Programming needs to be optimized for efficiency, faster outputs, and memory. Variables are key in programming that stores data at a
particular memory location. While executing a Java program, it stores values in containers called variables, a basic storage unit. To enhance
the program‘s readability, one needs to follow particular conventions while naming variables and assigning values. A source code
representing a fixed value is called ‗literal‘.
Literals in Java are defined directly in the code without any kind of computation. Any primitive type variables are assigned using literals.
Java has a generic, class-based, reflective, imperative, multi-paradigm, and is an object-oriented programming language.
Literals in java is represented only for primitive data types like boolean, string, character, or numeric data. The literals in java are a form of
data type covering the fixed values temporarily assigned fixed values as well.
A constant value in Java is created by using a literal representation of it. For example, here are some literals:

Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a character constant, and the last is a string. A
literal can be used anywhere a value of its type is allowed.

A literal is a textual representation of a particular value of a type. Literal types include boolean, integer, floating point, string, null, or
character. Technically, a literal will be assigned a value at compile time, while a variable will be assigned at runtime.

int age = 29;


String nationality = "INDIAN";Here we assign two literals to variables. Number 29 and string "INDIAN" are literals.
Java programming languages has different data types, viz. primitive data types, and non-primitive data types. Primitive data types include
int, byte, short, float, boolean, double, and char, whereas non-primitive data types include arrays, string, and classes.

Chethan Raj C, HoD, Dept of CSE Page 28


Object Oriented Programming using JAVA
The primitive literals in java int, byte, short, float, boolean, double, and char represent certain signed integer values. Such as byte data type
is an 8-bit signed, the short data type is a 16-bit signed, the int data type is 32-bit signed, the long data type is a 64-bit type, the float is 32-
bit signed, double is 64-bit, boolean has only two possible values i.e. either true or false and lastly, char is 16-bit unicode character.

The various types of literals in Java are particularly helpful for implementation in the code since it eliminates the need to add labels and
declare constants on the same line.

Types of literals
1. Integral Literals
2. Floating-point Literals
3. Char Literals
4. String Literals
5. Boolean Literals
6. Null Literals

Integral Literals in Java:


class Int_Lit
{
public static void main(String[] args)
{
int a = 101; // decimal-form literal
int b = 0100; // octal-form literal
int c = 0xFace; // Hexa-decimal form literal
int d = 0b1111; // Binary literal
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}

floating-point literal in Java:


class Float_Lit
{

Chethan Raj C, HoD, Dept of CSE Page 29


Object Oriented Programming using JAVA
public static void main(String[] args)
{
float a = 101.230f; // decimal-form literal
float b = 0123.222f; // It also serves the purpose of a decimal literal
float c = 0x123.222; // Hexa-decimal form (error)
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}

Character Literals
class Char_Lit
{
public static void main(String[] args)
{
char ch = 'a'; // single character literal within a single quote
char b = 0789; // It is an Integer literal with an octal form
char c = '\u0061'; // Unicode representation
System.out.println(ch);
System.out.println(b);
System.out.println(c);
System.out.println("\" is a symbol"); // Escape character literal
}
}

String Literals
String s = ―Hello‖;
class StringLiterals
{
public static void main(String[] args)
{
String myString = "I am a string literal";
System.out.println("String Literals? \n" + myString);

Chethan Raj C, HoD, Dept of CSE Page 30


Object Oriented Programming using JAVA
System.out.println("String length is? ");
//String method length() get length in characters
System.out.println("I am " + myString.length() + " characters long");
}
}

Boolean Literals
boolean b = true;
boolean d = false
Ex: class JavaBooleanLiterals
{
public static void main(String[] args)
{
boolean isTrue = true;
boolean isFalse =false;
System.out.println("The boolean value of isTrue: " + isTrue);
System.out.println("The boolean value of isFalse: " + isFalse);
}
}

Comments
As mentioned, there are three types of comments defined by Java like Single-line, multiline and another type is called a documentation
comment. This type of comment is used to produce an HTML file that documents your program. The documentation comment begins with
a /** and ends with a */.
Separators
In Java, there are a few characters that are used as separators. The most commonly used separator in Java is the semicolon. As you have
seen, it is used to terminate statements. The separators are shown in the following table:

Chethan Raj C, HoD, Dept of CSE Page 31


Object Oriented Programming using JAVA

The Java Keywords


Keywords are the words which are having inbuilt predefined meaning and this meaning cant be modify since it is reserved words and it can
not be used as identifiers.
There are 50 keywords currently defined in the Java language. These keywords, combined with the syntax of the operators and separators,
form the foundation of the Java language. These keywords cannot be used as identifiers. Thus, they cannot be used as names for a variable,
class, or method.
The keywords const and goto are reserved hence its not used as variable declaration. The current specification for Java defines only the
keywords shown in Table.
In addition to the keywords, Java reserves the following: true, false, and null. These are values defined by Java. You may not use these
words for the names of variables, classes, and so on.

Chethan Raj C, HoD, Dept of CSE Page 32


Object Oriented Programming using JAVA

Tokens
It is a smallest unit/part in the all the programming language
1. Keywords
2. Identifiers
3. Literal or values
Keywords
• Keywords is a predefine word which is understandable by a compiler and which having a fixed meaning.
• It is also called as reserve words.
• In Java we have 50 + keywords Example: class, public, static, void, etc...
Rules
• Keywords should be written in lower case.

Chethan Raj C, HoD, Dept of CSE Page 33


Object Oriented Programming using JAVA
Data Types
Java is a statically typed programming language. This means that when you create a variable, you must also specify its data type, which is
the type of information it stores. This is in contrast to dynamically typed languages, such as PHP. With dynamically typed languages, you
don‘t have to specify the data type of a variable.

However, knowing the data types and using them appropriately allows developers to optimize their code because each data type has
specific resource requirements. Also, if you specify one data type and try to store a different type, such as by mistake, you won‘t be able to
compile the code. Thus, with statically typed languages, you can detect errors even before any testing.

Java has two data types: primitive and reference (also known as non-primitive). In this tutorial, you will use variables to store and use
information in a Java program to learn about some of the commonly used data types in Java. This is not an exhaustive overview of all data
types, but this guide will help you become familiar with what options are available to you in Java.

• It is used to specify or indicate which type of data to be stored in the variable.


• For different data we are creating a different type of container.

The data-types are the most important basis of any programming language. It is the most important concept for every beginner. The data
type is essential to represent the type, nature and set of operations for the value which it stores.
Java data types are the most basic and initial thing you should know before moving towards other concepts of Java. These are very useful in
every aspect of Java, either to create a simple program or to develop any application or software.

Data Type in Java


In computer science, a data type is an attribute of data that tells the compiler or interpreter how the programmer aims to use the data. A data
type restricts the values that expression, such as a variable or a function that take. It defines how the values of that data type are stored in
memory and what operations can be performed on the data.

Data types incorporate storage categories like integers, floating-point values, strings, characters, etc.
For example, if a variable is of ―int‖ data type, then it can hold only integer values.

There are majorly two types of languages:


The first is statically typed language in which the data type of each variable has to be defined during the compile time. That is, we have to
declare the type of the variable before we can use it.
Once we declare a variable of a specific data type, then we cannot change its data type again. However, they can be converted to other types
by using explicit type casting in Java, except boolean. Some statically typed languages are C, C++, C#, Java, and Scala.

Chethan Raj C, HoD, Dept of CSE Page 34


Object Oriented Programming using JAVA
For example, if we write int num = 5;
Then it means the variable num is of integer type and holds a numerical value and its type will always be the same.

The other is dynamically typed language. In this type of language, the data types can change with respect to time and the variables are
checked during run-time. Some dynamically typed languages are Ruby, Python, Erlang, Perl, VB, and PHP.

In Java, data types play an important role in defining the kind of information that can be stored and manipulated. Data type is defined as the
type of value that variable can occupies in a program.

Data types are important factor in all computer programming languages. The task of a programmer is to develop a program by assigning the
valid types of data to the right variables. Data types represent the type, nature, and set of operations for the value which they store. There
are two data types of categories in Java: Primitive and Non-Primitive.

Data types in Java specify how memory stores the values of the variable. Each variable has a data type that decides the value the variable
will hold. Moreover, Primitive Data Types are also used with functions to define their return type.

Data Types in Java


Data types are the basis of programming languages. Data types in Java are divided into 2 categories:
1. Primitive Data Types
2. Non-Primitive Data Types

Primitive Types
Java primitive types are the simplest and most basic data types in Java. It represents raw values such as numbers and characters. The
primitive data types are the building blocks of the program and the primitive data cannot be manipulate and data cannot be further divided.
The most frequently used primitive data types are int (integers), boolean (boolean values), and char (characters), float (floating point).

Chethan Raj C, HoD, Dept of CSE Page 35


Object Oriented Programming using JAVA

Boolean type – Boolean


A boolean data type can store either True or False. They can be used to check whether two values are equal or not (basically in conditional
statements to return True or False). Typically, programmers use it as a flag variable to track true or false conditions.

The default boolean value is False. Moreover, the boolean type‘s size depends on the Java Virtual Machine. Therefore, it fluctuates on
different platforms.

Example-
class BooleanDataTypes
{
public static void main(String args[])
{
boolean var1 = true;
if (var1 == true) //checks if the value is true or false
{
System.out.println("Boolean value is True");
}
else
{

Chethan Raj C, HoD, Dept of CSE Page 36


Object Oriented Programming using JAVA
System.out.println("Boolean value is False");
}
}
}

Character type – char


The char data type stores a single character. It stores lowercase and uppercase characters, which must be enclosed in single quotes. The char
data type in Java supports Unicode characters and provides provision to multiple languages like English, French, German, etc. It takes
memory space of 16 bits or 2 bytes. The values stored range between 0 to 65536.

Example:- class CharDataType


{
public static void main(String[] args)
{
char var1 = 'A';
char var2 = 'd';
System.out.println(var1);
System.out.println(var2);
}
}

Integer type
An integer type stores an integer number with no fractional or decimal places. Java has four integer types – byte, short, int, and long.

Byte
The byte is the smallest data type among all the integer data types. It is an 8-bit signed two‘s complement integer. It stores whole numbers
ranging from -128 to 127.
Syntax: byte byteVariable;

Short
Short is a 16-bit signed two‘s complement integer. It stores whole numbers with values ranging from -32768 to 32767. Its default value is 0.
Syntax: short shortVariable;

Int

Chethan Raj C, HoD, Dept of CSE Page 37


Object Oriented Programming using JAVA
Int is a 32-bit signed two‘s complement integer that stores integral values ranging from 2147483648 (-2^31) to 2147483647 (2^31 -1). Its
default value is 0.
Syntax: int intVariable;

Long
long is a 64-bit signed two‘s complement integer that stores values ranging from -9223372036854775808(-2^63) to
9223372036854775807(2^63 -1). It is used when we need a range of values more than those provided by int. Its default value is 0L. This
data type ends with ‗L‘ or ‗l‘.
Syntax: long longVariable;

Example:
class IntegerDataTypes
{
public static void main(String args[])
{
int a = 10;
short s = 2;
byte b = 6;
long l = 125362133223l;
System.out.println("The integer variable is " + a + '\n');
System.out.println("The short variable is " + s + '\n');
System.out.println("The byte variable is " + b + '\n');
System.out.println("The long variable is " + l);

}
}

Float type
Floating-point is used for expressions involving fractional precision. floating-point data type that stores the values, including their decimal
precision. It is not used for precise data such as currency or research data. It has two types: float and double.

A Float value: is a single-precision 32-bit or 4 bytes IEEE 754 floating-point can have a 7-digit decimal precision ends with an ‗f‘ or ‗F‘
default value = 0.0f stores fractional numbers ranging from 3.4e-038 to 3.4e+038
Syntax: float floatVariable;

Chethan Raj C, HoD, Dept of CSE Page 38


Object Oriented Programming using JAVA

Double
The double data type is similar to float. The difference between the two is that is double twice the float in the case of decimal precision. It is
used for decimal values just like float and should not be used for precise values.

A double value: is a double-precision 64-bit or 8 bytes IEEE 754 floating-point can have a 15-digit decimal precision default value = 0.0d
stores fractional numbers ranging from 1.7e-308 to 1.7e+308
Syntax: double doubleVariable;

Example:
class FloatDataTypes
{
public static void main(String args[])
{
float f = 65.20298f;
double d = 876.765d;
System.out.println("The float variable is " + f);
System.out.println("The double variable is " + d);
}
}

Primitive Data Types Table – Default Value, Size, and Range


Data Type Default Value Default size Range
byte 0 1 byte or 8 bits -128 to 127
short 0 2 bytes or 16 bits -32,768 to 32,767
int 0 4 bytes or 32 bits 2,147,483,648 to 2,147,483,647
long 0 8 bytes or 64 bits 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 0.0f 4 bytes or 32 bits 1.4e-045 to 3.4e+038
double 0.0d 8 bytes or 64 bits 4.9e-324 to 1.8e+308
char ‗\u0000‘ 2 bytes or 16 bits 0 to 65536
boolean FALSE 1 byte or 2 bytes 0 or 1

Non-Primitive Data Types

Chethan Raj C, HoD, Dept of CSE Page 39


Object Oriented Programming using JAVA
Non-primitive data types or reference data types refer to instances or objects. They cannot store the value of a variable directly in memory.
They store a memory address of the variable. Unlike primitive data types, non-primitive data types are user-defined data type. Programmers
create them and can be assigned with null. All non-primitive data types are of equal size and the data can be easily manipulate and
subdivided.
Ex: Arrays, Strings, Class, Interface, Enumerated.

Array
Array is non primitive data type that holds elements of the same type. Array is an object in Java, and the array name (used for declaration)
is a reference value that carries the base address of the continuous location of elements of an array.

Example:
int Array_Name = new int[7];
array_reference_variable

String
The String data type stores a sequence or array of characters. A string is a non-primitive data type, but it is predefined in Java. String literals
are enclosed in double quotes.
class Cs
{
public static void main(String[] args)
{
// create strings
String S1 = "Java String Data type";
// print strings
System.out.println(S1);
}
}

Class
A class is a user-defined data type from which objects are created. It describes the set of properties or methods common to all objects of the
same type. It contains fields and methods that represent the behaviour of an object. A class gets invoked by the creation of the respective
object.
Class acts as a blueprint and a template.
Example: code=class

Chethan Raj C, HoD, Dept of CSE Page 40


Object Oriented Programming using JAVA
Interface
An interface is declared like a class. The key difference is that the interface contains abstract methods by default; they have nobody.

Example:
interface printable
{
void print();
}
class A1 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A1 obj = new A1();
obj.print();
}
}

Enum
An enum, similar to a class, has attributes and methods. However, unlike classes, enum constants are public, static, and final (unchangeable
– cannot be overridden). Developers cannot use an enum to create objects, and it cannot extend other classes. But, the enum can implement
interfaces.

Java enum, also called Java enumeration type, is a type whose fields consist of a fixed set of constants. The purpose of an enum is to
enforce compile-time type safety. The enum keyword is one of the reserved keywords in Java. The enums are a special type of class that
always extends java.lang.Enum.

Syntax: enum (name of user defined datatype)


{
Values of user defined datatype
}

Chethan Raj C, HoD, Dept of CSE Page 41


Object Oriented Programming using JAVA

Ex: enum Branch


{
CSE,ISE,ECE,PS;
}

Logically, each enum is an instance of enum type itself.


//declaration of an enum
enum Level
{
LOW,
MEDIUM,
HIGH
}

In Java, we define enums inside and outside of a class. In Java, an enum is defined as a class type, so we do not need to instantiate the enum
using new; it will contain the same capabilities as other classes.

In the below example, we are defining the enum datatype inside the class as follows: We are creating the class name as enum_class as
follows:
class enum_class
{
enum Level
{
LOWER,
MEDIUM,
HIGHER
}
public static void main(String[] args)
{
Level mv = Level.MEDIUM;
System.out.println (mv);
}
}

Chethan Raj C, HoD, Dept of CSE Page 42


Object Oriented Programming using JAVA

Defining the enum datatype outside of the class as follows. We are creating the class name as enum_class as follows.
enum Color
{
GREEN,
BLACK,
BLUE;
}
class enum_class
{
public static void main(String[] args)
{
Color col = Color.BLUE;
System.out.println (col);
}
}

Variable
Variable is a name given to memory location i.e to store the specific format of data in the system. It's a container or block of memory
which is used to store the data. It is defined as the name given or assigned to allocate the data inside the computer memory.

Characteristics of variable
• Variable is a named block of memory
• By using a name user can store the data and can fetch the data
• User cannot store multiple values in single variable name.

Variable declaration
Syntax : datatype variablename ;
Ex: int a;

Variable initialization
Syntax : variablename=value/data ;
Ex: a=20;

Chethan Raj C, HoD, Dept of CSE Page 43


Object Oriented Programming using JAVA
Variable declaration and initialization
Syntax : datatype variablename=value/data ;
Ex: int a=20;

Permissible Variable Names


lastDayOfMonth = 20
firstYear = 1952
name = "E"

Impermissible Variable Names


last day of month = 20
1day = 1952
beware! = 1910
1920 = 1

Variable is a name given to a memory location The Variable is a block of memory that is typically used to store information. All the
variables must be declared before use in the Java code. During the program execution, the value stored in the variable can be changed.
Variables are just the name of the reserved memory location, and all the operations done on the variables will definitely effects that
memory location.
There are three types of variables in java: local, instance and static. There are two types of data types in java: primitive and non-primitive.
int data=50;//Here data is variable

Types of Variables
Java Programming language defines three types of variables.
1.Instance variables
2.Static Variables
3.Local Variables

Chethan Raj C, HoD, Dept of CSE Page 44


Object Oriented Programming using JAVA
Local variable: These variables are declared and used within a specific method, constructor, or block of code. They are only accessible
within the scope in which they are defined. Local variables must be initialized before they can be used.

Instance variable: These variables are declared within a class but outside any method, constructor, or block of code. They are associated
with individual instances (objects) of the class. Each instance of the class has its own copy of the instance variables. Instance variables are
initialized to their default values if not explicitly assigned.

Static variable: These variables are declared with the static keyword within a class but outside any method, constructor, or block of code.
They are associated with the class itself rather than with instances of the class. Static variables are shared among all instances of the class,
and changes to the variable will be reflected in all instances. Static variables are initialized to their default values if not explicitly assigned.

Ex: class Demo


{
int a = 50; // member variable
public static void main(String[] args)
{
int a = 10; // local Variable
{
int b = 20; // local Variable
}
}

Ex: class Cse


{
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
public static void main(String args[])
{
int data=50; //instance variable

Chethan Raj C, HoD, Dept of CSE Page 45


Object Oriented Programming using JAVA
}
}//end of class

Local Variables in Java:


 Local Variables are declared inside the method of the class. The scope of the local variable is limited to the method, which means
user cannot change the value of the local variable outside the method and cannot even access it outside the method. The
initialization of the local variable is mandatory.
 Scope of Local Variable: Within the block in which it is declared.
 The lifetime of Local Variable: Until the control leaves the block in which it is declared.
Ex: class LocalVariableExample
{
public void EmployeeAge ()
{
// local variable age
int age = 30;
age = age + 5;
System.out.println ("Employee age is : " + age);
}
public static void main (String args[])
{
LocalVariableExample obj = new LocalVariableExample ();
obj.EmployeeAge ();
}
}
Output: Employee age is : 35
In the above code, age is the Local Variable to the method EmployeeAge(). If user declare age outside the method, it will give a
compilation error.

Instance Variables in Java:


 The instance variable is also known as a non-static variable. It is always declared in a class but outside the method, block, or
constructor. The instance variable is created when an object of the class is created and destroyed when the object is destroyed.
Instance Variables can only be accessed by creating the objects of the class. The initialization of the instance variable is not
required, it takes the default value as 0.
 Scope of Instance Variable: Throughout the class except in static methods.

Chethan Raj C, HoD, Dept of CSE Page 46


Object Oriented Programming using JAVA
 The lifetime of Instance Variable: Until the object is available in the memory.

Ex: class Marks


{
// These variables are instance variables.
// These variables are in a class
// and are not inside any function
int engMarks;
int mathsMarks;
int phyMarks;
}
class InstanceVariableExample
{
public static void main (String args[])
{
//Object
Marks obj1 = new Marks ();
obj1.engMarks = 50;
obj1.mathsMarks = 80;
obj1.phyMarks = 90;
// displaying marks for object
System.out.println ("Marks for first object:");
System.out.println (obj1.engMarks);
System.out.println (obj1.mathsMarks);
System.out.println (obj1.phyMarks);
}
}
Output: 50
80
90

Static Variables in Java:


 The static variable is also known as the Class Variable. Static variables are created at the start of program execution and destroyed
automatically when execution ends. These variables are declared similarly to instance variables, the difference is that static variables

Chethan Raj C, HoD, Dept of CSE Page 47


Object Oriented Programming using JAVA
are declared using the static keyword within a class outside any method constructor or block. Initialization of Static Variable is not
mandatory, it‘s default value is 0. If user access the static variable without the class name, the Compiler will automatically append
the class name.
 To access static variables, user need not create an object of that class, user can simply access the variable as
class_name.variable_name;
 Scope of Static Variable: Throughout the class.
 The lifetime of Static Variable: Until the end of the program.

Ex:class Employee
{
// static variable salary
public static double salary;
public static String name = "H";
}
class StaticVariableExample
{
public static void main (String[]args)
{
// accessing static variable without object
Employee.salary = 75000;
System.out.println (Employee.name + "'s average salary:" + Employee.salary);
}
}
Output: H average salary:75000.0

Primitive variable
A variable which is created by using primitive data type.

Non Primitive Variable


A variable which is used to store address/reference of object . It is created by using non primitive datatype.
className is non primitive data type.

Ex: class Demo


{

Chethan Raj C, HoD, Dept of CSE Page 48


Object Oriented Programming using JAVA

}
Demo d1;
class Student
{

}
Student s1;
class Employee
{

}
Employee e1;
•In java user can create any number of non-primitive data type.

Reinitialization
The process of modifying existing data inside the variable is known as reinitialization.

Ex: class Demo


{
public static void main(String[] args)
{
int a = 20 ;
a=30;
a=40;
System.out.println(a);
}
}

Ex: class Demo


{
public static void main(String[] args)
{
int a = 20 ;

Chethan Raj C, HoD, Dept of CSE Page 49


Object Oriented Programming using JAVA
System.out.print(a);
a=a+10;
System.out.println(a);
}
}

Reading Different Variable Types from User


In the text-based user interfaces the user's input is always read as a string, since the user writes their input as text. Reading strings from the
user has become familiar by using the nextLine-command of the Scanner class method.

import java.util.Scanner;
class Program
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Write text and enter ");
String text = scanner.nextLine();
System.out.println("You wrote " + text);
}
}
Write text and enter
text
You wrote text

Other input types, such as integers, doubles, and booleans are also read as text. However, they need to be converted to the target variable's
type with the help of syntax provided by Java.

Reading Integers
The Integer.valueOf command converts a string to an integer. It takes the string containing the value to be converted as a parameter.
String valueAsString = "42";
int value = Integer.valueOf(valueAsString);
System.out.println(value);
Output: 42

Chethan Raj C, HoD, Dept of CSE Page 50


Object Oriented Programming using JAVA
When using a Scanner object, the reading of the value is usually inserted directly into the type conversion:

import java.util.Scanner;
class Program
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Write a value ");
int value = Integer.valueOf(scanner.nextLine());
System.out.println("You wrote " + value);
}
}
Sample output
Write a value
42
You wrote 42

Introducing Type Inference with Local Variables: Local Variable Type Inference
Java 10 introduced a noticeable feature: the Local variable type inference. This allows us to declare local variables without specifying the
type using the varkeyword, the compiler automatically infers its type. This reduces the complex boilerplate declarations and makes the code
look clean.
However, we cannot declare variables everywhere with the var keyword. There are some restrictions, which are given below.
1. Class level
When we say ‗local‘ variable type inference, we can use it strictly in a method's local context. We cannot declare a variable inside a class
(static or instance) using the varkeyword. The compiler throws a compilation error if trying to declare it inside a class.
class Example
{
int rollNumber;
var name; // Compiler Error! - Cannot resolve symbol 'var'
}

Chethan Raj C, HoD, Dept of CSE Page 51


Object Oriented Programming using JAVA
2. Null Assignment
You must assign a non-null value to the variable during the declaration so that the compiler can infer its type. Assigning a null reference to
a variable makes the compiler difficulty to infer its type. Hence, the null assignment is not allowed during the declaration.
public static void main(String[] args)
{
var name = null; // Compiler Error! - Cannot infer type: variable initializer is 'null'
}
However, you can assign the null after the first initialization.
public static void main(String[] args)
{
var name = "hello";
name = null; // Valid now!
}
3. Compound Initialization
Java allows us to initialize multiple variables of the same type in a single statement separated by a comma. int length = 10, breadth = 20,
height = 30; However, this is not allowed when you use thevar.
public static void main(String[] args)
{
var length = 10, breadth = 20, height = 30; // Compiler Error! 'var' is not allowed in a compound declaration
}
4. Array Initialization
Array initialization is not allowed without specifying its type during the initialization.
public static void main(String[] args)
{
var a = { 1, 2, 3 }; // Compiler Error! Array initializer is not allowed here

Chethan Raj C, HoD, Dept of CSE Page 52


Object Oriented Programming using JAVA
var[] b = { 1, 2, 3 }; // Compiler Error! Unexpected token.
var[] c = new int[] { 1, 2, 3 }; // Compiler Error! Unexpected token.
var d = new int[] { 1, 2, 3 }; // Valid!
}
for loop allows us to initialize multiple variables. Java 10 allows us to use the var on for loops. However, the compound declaration is not
allowed here too.
for (var i = 0; i < 10; i++)
{ // Valid! Single var declaration is allowed
System.out.println(i);
}
for (var i = 0, j = 10 ; i < 10; i++, j--)
{ // Compiler error! 'var' is not allowed in a compound declaration
System.out.println(i + j);
}
Local Variable Type Inference is one of the most evident change to language available from Java 10 onwards. It allows to define a variable
using var and without specifying the type of it. The compiler infers the type of the variable using the value provided. This type inference is
restricted to local variables.

Old way of declaring local variable.


String name = "Welcome to JAVA Program";
New Way of declaring local variable.
var name = "Welcome to JAVA Program";
Now compiler infers the type of name variable as String by inspecting the value provided.
1. No type inference in case of member variable, method parameters, return values.
2. Local variable should be initialized at time of declaration otherwise compiler will not be infer and will throw error.

Chethan Raj C, HoD, Dept of CSE Page 53


Object Oriented Programming using JAVA
3. Local variable inference is available inside initialization block of loop statements.
4. No runtime overhead. As compiler infers the type based on value provided, there is no performance loss.
5. No dynamic type change. Once type of local variable is inferred it cannot be changed.
6. Complex boilerplate code can be reduced using local variable type inference.
import java.util.List;
class Test
{
public static void main(String[] args)
{
var names = List.of("G", "C", "C", "K",‖P‖);
for (var name : names)
{
System.out.println(name);
}
System.out.println("");
for (var i = 0; i < names.size(); i++)
{
System.out.println(names.get(i));
}
}
}

Arrays
Arrays in Java store multiple values of the same type in a single variable. They are objects that can hold a fixed number of elements, and
each element has an index used to access it. Arrays enable developers to manipulate data efficiently and perform operations like sorting,
searching, insertion, and deletion quickly and easily.
• In Java array is a predefined class.
• It is a multiple block of memory which is used to store the multiple data.

The array is a referenced data type used to create fixed numbers of multiple variables of the same type to store multiple values of the same
type in continuous memory locations with a single variable name.

Chethan Raj C, HoD, Dept of CSE Page 54


Object Oriented Programming using JAVA
Definition: An array is a collection of similar types of data. It is a container that holds data (values) of one single type. In Java, arrays are a
fundamental construct that allows user to store and access a large number of values conveniently.
An array is a derived data type of collection of similar data types and are referred by a common name. Array is a container object that hold
values of homogenous type. It is also known as static data structure because size of an array must be specified at the time of its declaration.
Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. The array
index ranges from 0 to n−1; therefore, in an array of size 10, the first element is stored at index 0 and the last or the 10th element at index 9.

Note: Like other data types array is not a keyword rather it is a concept. It creates continuous memory locations using other primitive or
reference types.
Array Limitation: Its size is fixed, which means user cannot increase or decrease its size after its creation.

Features of Array
1. Arrays are objects
2. They can even hold the reference variables of other objects
3. They are created during runtime
4. They are dynamic, created on the heap
5. The Array length is fixed.
An array can be either primitive or reference type. It allocates memory in heap area. Index of array starts from zero to size-1.

Advantages of array:-
1) Length of the code will be decreased
2) User can access the element present in the any location.
3) Readability of the code will be increased

Note: 1) Array is a final class inheritance is not possible.


2) Arrays are used to store the multiple numbers of elements of single type.
3) The length of the array is established at the time of array creation. After creation the length is fixed.
4) The items presented in the array are classed elements. Those elements can be accessed by index values. The index is begins from (0).

Two types of Arrays:


1. Single Dimensional Array
2. Multi-Dimensional Array
Single Dimensional Arrays, means user are storing multiple values in one dimensional that is either horizontally or vertically.

Chethan Raj C, HoD, Dept of CSE Page 55


Object Oriented Programming using JAVA
Declaration: <Accessibility Modifiers><Non Accessibility Modifiers><data type> [ ]< array Variable name>;
Here
1. Accessibility modifiers can be public, private, or protected.
2. The non-accessibility modifier can be static.
3. The data type can be any primitive data type or class type
4. Array name must be any java valid identifier
5. The array must be represented using []
Syntax : datatype[ ] identifier; or datatype identifier[ ];

Ex: public static int[] intArr; //Here, int is primitive data type
public static Employee[] empArr; //Employee is a class type or user can say reference type.

Rules for declaring Arrays in Java:


User place the pair of square brackets [] after the variable name, before the variable name, after the data type but not before the data type.

Example :public int[ ] arr; or int[ ] arr; // valid


public char [ ]arr; // valid
public short arr[ ]; // valid
public [ ] int arr; //invalid
int[ ][ ] arr; // two dimensional array.

Initialization of Array
new operator is used to initialize an array.
Example : int[ ] arr = new int[10]; //10 is the size of array.
or
int[ ] arr = {10,20,30,40,50};

Declaration & instantiation & initialization :-


approach 1:- int a[]={10,20,30,40};
approach 2:- int[] a=new int[100];
a[0]=10;
a[1]=20;
a[2]=30;
a[4]=40;

Chethan Raj C, HoD, Dept of CSE Page 56


Object Oriented Programming using JAVA
Accessing array element
The array index starts from 0. To access nth element of an array.
Syntax : arrayname[n-1];

Example : To access 4th element of a given array


int[ ] arr = {10,20,30,40};
System.out.println("Element at 4th place" + arr[3]);
The above code will print the 4th element of array arr on console.

Ex:-printing the array elements


class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
}
}

Ex:-printing the array elements by using for loop


class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
for (int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}

Chethan Raj C, HoD, Dept of CSE Page 57


Object Oriented Programming using JAVA

Ex:-printing the array elements by using enhanced for loop called: for-each loop
class Test
{
public static void main(String[] args)
{
int[] a={10,20,30,40};
for (int a1:a)
{
System.out.println(a1);
}
}
}

Ex: class Test


{
public static void main(String[] args)
{
int[] a=new int[4];// allocates memory for 4 elements
a[0]=10;
a[1]=100;
a[2]=1000;
a[3]=10000;
int p=a.length;
System.out.println("Array length="+p);
System.out.println("Array Elements are");
for (int i=0;i<p;i++)
{
System.out.println(a[i]);
}
}
}

Ex: public class MyClass

Chethan Raj C, HoD, Dept of CSE Page 58


Object Oriented Programming using JAVA
{
public static void main(String[] args)
{
String[] student = {"SCK", "CKP", "CKF", "GCK"};
for (int i = 0; i < student.length; i++)
{
System.out.println(student[i]);
}
}
}
Output: SCK
CKP
CKF
GCK

Characteristics of array
• The size of arrays fixed
• Array is homogeneous data collection
• Arrays index based, the index number is always start from zero
• Duplicates are allowed in arrays
• By using array name, index no we can store the data we can fetch the data

Uses of Arrays in Java


There are various uses of java array, such as:
1. They allow us to store multiple elements of the same type in a single array. This is useful when we need to store large amounts of
data and process them efficiently.
2. Arrays are also used for sorting, searching, accessing, and manipulating data.
3. Also, arrays provide various advantages such as memory efficiency, better performance, and faster execution time.
4. Arrays can solve complex problems such as calculating the sum or finding maximum or minimum values in an array.
5. They can also be used to implement multi-dimensional arrays, which are useful for representing matrices and graphs.
6. Arrays have applications in computer programming, engineering, mathematics etc.

Advantages of Array in Java


Here are the advantages of array:

Chethan Raj C, HoD, Dept of CSE Page 59


Object Oriented Programming using JAVA
1. Easy to use: Arrays are easy to use and require less coding than traditional data structures. This makes arrays a great choice for rapid
development.
2. High performance: Arrays provide fast and efficient access to elements as compared to other data structures such as linked lists,
trees etc.
3. Flexible size: The size of arrays can be changed easily at runtime, making them a very flexible type of data structure.
4. Memory efficient: Arrays are memory efficient as they can store multiple values in the same location. This reduces the amount of
RAM required to store data and improves overall performance.
5. Random Access: Arrays support random access, meaning elements can be accessed directly using their index. This makes arrays an
ideal choice for applications requiring fast data access.

Disadvantages of Array in Java


Here are the disadvantages of array:
1. Fixed-size: An array is a fixed-size data structure that can store only a predetermined number of elements. If you need to
dynamically add or remove elements, arrays aren't the best choice - other data structures like Array List are better suited for this
purpose.
2. Lack of flexibility: Arrays don't provide many features like sorting or searching, which you could use to make the data more
accessible. The elements in an array should be accessed using indexes, and arrays are not flexible enough to easily add or remove
elements.
3. Overhead: Arrays in Java can have certain overhead associated with them. This includes the time to look up a particular item, add or
delete items, and rearrange arrays if needed.

How to create array


1. By using new keyword
2. By using literals

By using new keyword Syntax:


data type[ ] arrayName= new data type[size] ;
Ex: int [ ] arr = new int [4];

How to store Data


Syntax: arrayName[index] = data/value ;
Ex: arr [0]=10;

How to Fetch Data

Chethan Raj C, HoD, Dept of CSE Page 60


Object Oriented Programming using JAVA
Syntax: arrayName[index]
Ex: arr [0]; / /10

Ex: Here is a complete, executable java code demonstrating the declaration, instantiation, and initialization of an array in java.
class ArrayExample
{
public static void main(String[] args)
{
// Declare an array variable
int[] numbers;

// Instantiate the array


numbers = new int[5];

// Initialize the array elements


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Print the array elements


for (int i = 0; i < numbers.length; i++)
{
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Ex: public static void printArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}

Chethan Raj C, HoD, Dept of CSE Page 61


Object Oriented Programming using JAVA
System.out.println();
}
public static void main(String[] args)
{
int[] myArray = {1, 2, 3, 4, 5};
printArray(myArray);
}

User can create an array of non-primitive data types in java, just the same way as you create an array for primitive data types. Consider the
following example for better understanding.
class Coding
{
private int id;
private String name;
public Coding(int id, String name) //Constructor i.e parametrized constructor
{
this.id = id;
this.name = name;
}

public int getId()


{
return id;
}

public String getName()


{
return name;
}
}

Coding[] Array = new Coding[5];

By Using Literals

Chethan Raj C, HoD, Dept of CSE Page 62


Object Oriented Programming using JAVA
Syntax: data type[ ] arrayName={value1, value2, value3…….}
Ex: int[ ] arr={10,20,30,40};

There are two different ways of creating array literals.


1. Initialization of array elements at the time of creating array object.
2. Using anonymous arrays

Method 1: Initialization of array elements at the time of creating array object. It is the most commonly used syntax and can only be used
when declaring a variable of array type.
Syntax: int[] factors= { 1, 2, 3, 4, 6, 12, 24 };

Implementation:
The above statement creates an array of int data types containing 7 elements. Here, we:
• Created an array object without using new keyword.
• Didn‘t specify the type of the array.
• Didn‘t explicitly specify the length of the array object.

Ex:// Java Program to Illustrate Array Literals by Initialization of array elements at the time of creating array object
import java.io.*;
class Cs
{
public static void main(String[] args)
{
// Initializing array elements at the time of
// creating an array object
int[] factors = { 1, 2, 3, 4, 6, 12, 24 };
// Iterating using for each loop
for (int i : factors)
// Print the elements
System.out.print(i + " ");
}
}
Output 1 2 3 4 6 12 24

Chethan Raj C, HoD, Dept of CSE Page 63


Object Oriented Programming using JAVA
Note: There is a flaw in this method as this array literal syntax works only when you assign the array object to a variable. If you need to do
something with an array value such as pass it to a method but are going to use the array only once. In this case, we can avoid assigning it to
a variable, but this syntax won‘t allow us to do so.

Method 2: We have another syntax that allows us to use anonymous arrays. Anonymous arrays are arrays that are not assigned to any
variables and hence, they don‘t have names).

Syntax: double volume = computeVolume(new int[] { 3, 4, 5 });

Implementation:
The above statement call a method computeVolume with an anonymous array. Here, we:
• Didn‘t store the array in any variable.
• Used new keyword for creating an array object.
• Explicitly specified the type of array.

Example
// Java Program to Illustrate Array Literals Using anonymous arrays
// Importing required classes
import java.io.*;
class Is
{
public static double computeVolume(int[] dimensions)
{
int l = dimensions[0];
int b = dimensions[1];
int h = dimensions[2];
// returning the volume
return (l * b * h);
}
public static void main(String[] args)
{
// Passing an array object directly to a method
// without storing it in a variable
double volume= computeVolume(new int[] { 3, 4, 5 });

Chethan Raj C, HoD, Dept of CSE Page 64


Object Oriented Programming using JAVA

// Print and display the volume


System.out.print(volume);
}
}
Output 60.

Operators:
Java operators are the predefined symbols that are used to perform specific task or operations on variables or operands. It also helps to
manipulate the values of the operands. .
Ex:10+20

Operands:
The data are value between the operators is known as operands.

Expression:
The combination of operator and operand is known as expression.
Types of Operators
1. Arithmetic operators
2. Assignment operators
3. Comparison/Relational operators
4. Logical operators
5. Ternary operators
6. Unary operators
7. Bit wise operator
8. Shift operator

1. Arithmetic operators
It is a operator which is used to perform Arithmetic operations.
Symbols:[+,-,*,/,%]
Ex: classDemo2
{
public static void main(String[]args)
{

Chethan Raj C, HoD, Dept of CSE Page 65


Object Oriented Programming using JAVA
System.out.println(10+20);
System.out.println(20-2);
System.out.println(5*6);
System.out.println(6/2);
System.out.println(5%3);
}
}

2. Assignment operators
It is a shortened operators used to modify the existing data in variable.
Symbols:[=,+=,-=,*=,/=,%=]
Ex:
int a=20;
a += 10;//a=a+10
a - = 15;//a=a-15
a * = 12;//a=a*12
a/=14;//a=a/14
a%=11;//a=a%11

3. Comparison or Relational operators:


This operator is used to compare the two operands. Ex:[== ,!=,>,<,>=,<=]
• The return type of this operator is Boolean.
Condition: Expression which returns the Boolean value.

4. Logical operators:
The operator which is used to compare the two condition, the return type of this operator is also Boolean. Ex :[&&,||,!]
a) &&[and]
This operator is used to compare the two condition if both the condition are true then it will return Boolean true otherwise it will return
false.

Truth Table

Condition ReturnValue

Chethan Raj C, HoD, Dept of CSE Page 66


Object Oriented Programming using JAVA
True&&False False

False&&True False
False&&False False

True&&True True

If both conditions are satisfied then only it will return True otherwise False

b)|| [or]
This operator is used to compare the two condition if both the condition are false then it will return Boolean false otherwise it will return
true
Truth Table
Condition Return Value
True||False True

False||True True

False||False False

True||True True

If one conditions are satisfied then only it will return True otherwise False
classDemo2
{
public static void main(String[]args)
{
inta=10,b=20,c=10;
System.out.println(true&&false);
System.out.println(true||false);
System.out.println(a>b&&a==c);
System.out.println(b<c || a!=b) ;
System.out.println(a!=c||b==c);
}
}
Chethan Raj C, HoD, Dept of CSE Page 67
Object Oriented Programming using JAVA
c) ![not]
This operator is used to reverse the Boolean output.
Ex:
System.out.println(!true);//false
System.out.println(!false);//true

Unary operator
The operator which will have only one operands is known as unary operator.
Types of unary operator
1. Increment
2. Decrement

Chethan Raj C, HoD, Dept of CSE Page 68


Object Oriented Programming using JAVA

6. Ternary operators
A operator which will have a three operands is known as ternary operator

Syntax:Condition?Op2:Op3;
•The return type of this operator is depended upon the data type of operands.

Operator Precedence
In real life when we solve an expression containing multiple operators we follow some rules. For example in an expression 2+3*4, we do
the multiplication first before addition because the multiplication operator has higher precedence than addition operator. The same applies
in java as well.
In java, operator precedence is a rule that tells us the precedence of different operators. Operators with higher precedence are evaluated
before operators with lower precedence. For example in expression a+b*c, the operator * will be evaluated before + operator, because
operator * has higher precedence than + operator.
Table bellow shows the precedence of operators in decreasing order, the operators appearing first in table have higher precedence than
operators appearing later. Operators appearing in same row of table have equal precedence. When operators of equal precedence appears in
the same expression, a rule governs the evaluation order which says that all binary operators except for the assignment operator are
Object Oriented Programming using JAVA
evaluated from left to right while assignment operator is evaluated from right to left. For example in expression 2+3-4, 2 and 3 is added first
then 4 is subtracted from it. Consider a and b as two operands for the examples given in below table.

Java operator precedence table

Operators Precedence Example

Postfix expr++ expr-- a++ , a--

Unary ++expr --expr +expr -expr ~ ! ++a , --a , !a

Multiplicative */% a*b , a/b , a%b

Additive +- a+b , a-b

Shift << >> >>> a<<2 , a>>1

Relational < > <= >= instanceof a<2 , a>1

Equality == != a==b , a!=b

Bitwise AND & a&b

Bitwise exclusive OR ^ a^b

Bitwise inclusive OR | a|b

Logical AND && a&&b

Logical OR || a||b

Ternary ?: a = a>2 ? a : b

Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= a=b, a+=b, a/=b, a>>=2


Object Oriented Programming using JAVA
Which operator has highest precedence in java
The postfix operator(eg. a++, a--) has the highest precedence in java.

Which operator has lowest precedence in java


Assignment operator and it's different forms has the lowest precedence in java.

A programmer should remember below rules while evaluating an expression in java.


• The operands of operators are evaluated from left to right. For example in expression ++a + b--, the operand ++a is evaluated first then b--
is evaluated.
• Every operand of an operator (except the conditional operators &&, ||, and ? :) are evaluated completely before any part of the operation
itself is performed. For example in expression ++a + b--, the addition operation will take place only after ++a and b-- is evaluated.
• The left-hand operand of a binary operator are evaluated completely before any part of the right-hand operand is evaluated.
• Order of evaluation given by parenthesis () get's preference over operator precedence.
• The prefix version of ++ or -- evaluates/uses the incremented value in an expression while postfix version of ++ or -- evaluates the current
value, then increases/decreases the operand value.
• All binary operators are evaluated from left to right except assignment operator.

Using Parenthesis
What changes the precedence of the operators in Java : Parentheses "()" are used to alter the order of evaluation. For example in an
expression a+b*c, if you want the addition operation to take place first, then rewrite the expression as (a+b)*c.

Java Program of Operator Precedence


class OperatorPrecedence {
public static void main (String[] args)
{
int result = 0;
result = 5 + 2 * 3 - 1;
System.out.println("5 + 2 * 3 - 1 = " +result);

result = 5 + 4 / 2 + 6;
System.out.println("5 + 4 / 2 + 6 = " +result);

result = 3 + 6 / 2 * 3 - 1 + 2;
System.out.println("3 + 6 / 2 * 3 - 1 + 2 = " +result);

result = 6 / 2 * 3 * 2 / 3;
Object Oriented Programming using JAVA
System.out.println("6 / 2 * 3 * 2 / 3 = " +result);

int x = 2;
result = x++ + x++ * --x / x++ - --x + 3 >> 1 | 2;
System.out.println("result = " +result);
}
}
Consider the expression x++ + x++ * --x / x++ - --x + 3 >> 1 | 2 is evaluated step by step.

operands are evaluated first, left to right


2 + 3 * 3 / 3 - 3 + 3 >> 1 | 2

* and / have higher preference than other, * evaluated first as it comes in left
2 + 9 / 3 - 3 + 3 >> 1 | 2

/ have higher preference than others


2 + 3 - 3 + 3 >> 1 | 2

+ and - have higher preference than others


5 >> 1 | 2

>> have higher preference than |


2|2

Output
2

1. Nested parentheses in an expression are evaluated from the innermost parentheses to the outermost parenthesis.
2. If evaluation of the left-hand operand of a binary operator does not complete properly, no part of the right-hand operand will be
evaluated.
3. Arguments in a method are evaluated from left to right.

Characteristics of operators
1. Every operator will return data or value.
2. Presidency
3. Associativity
Object Oriented Programming using JAVA
1. Every operator will returns some data or value
Ex:10+20->30
50*2->100

2. Precedence[Priority]
When the expression having more than one operator then precedence comes into picture.
Ex:10+2*3

3. Associativity
• Direction of order of execution.
• When you have the same priority then associativity comes into picture.
Ex:10+20+30
20+10-5
5–2+5

Module 01 Questions

1. Describe the two paradigm of object oriented java programming language.


2. Explain the three OOP principles with an example.
3. Define data type. Classify the java data type and explain primitive data type with an example
4. Explain type Casting with an example of java Program (Widening and Narrowing).
5. Explain type Conversion with an example of java Program.
6. Define operators. List the different operators supported by java. Explain logical and bitwise operators with an example.
7. Define control statement and list the different control statement supported by java. Explain for each looping construct with an
example.
8. Explain the local variable type inference in for loop with an example.
9. With example explain the return, break and continue statement in java.
10. With an example explain the ternary operator. Write a java program to fine the largest of three numbers using ternary operator
11. Explain the following a) literals b)Identifiers
12. Define array and how are arrays declared and initialized in java with an example.
13. Explain automatic type promotion in expression with rules and example program.
14. Explain the process of compiling and execution of java applications with an example.
15. Define variables. List the different type of variables supported by java with an example.
Object Oriented Programming using JAVA

You might also like