Java_Unit_1
Java_Unit_1
UNIT – 1
Introduction to JAVA
OBJECT ORIENTED PROGRAMMING (OOP) :-
The major motivating factor in the invention of object oriented is to remove some of the
flaws encountered in the procedural oriented approach. Object oriented programming
treats data as a critical element in the program development and does not allow it to flow
freely around the system. It ties data more closely to the functions that operate on it, and
protects it from accidental modifications from outside functions.
Object oriented programming allows a decomposition of a problem into a number
entity called objects and then builds data and functions around these objects. The data of an
object can be accessed only by the functions associated with that object. However, functions
of one object can access the functions of other objects.
CONCEPTS OF OOP’S
The prime purpose of Java programming was to add object orientation to the C
programming language, which is in itself one of the most powerful programming
languages.
The core of the pure object-oriented programming is to create an object, in code, that
has certain properties and methods. While designing Java modules, we try to see whole
world in the form of objects. For example, a car is an object, which has certain properties
such as color, number of doors, and the like. It also has certain methods such as accelerate,
brake, and so on.
There are a few principle concepts that form the foundation of object-oriented
programming:
1. Object.
2. Classes.
3. Inheritance.
4. Data Abstraction.
5. Data Encapsulation.
6. Polymorphism.
7. Dynamic Binding.
8. Message Passing
Object Oriented Concepts using Java
Message
Dynamic Passing
Binding
OBJECT:
Any real world entity which can have some characteristics or which can perform
some work is called as Object. Object is the basic unit of object-oriented programming.
Objects are identified by its unique name. An object represents a particular instance of a
class. There can be more than one instance of a class. Each instance of a class can hold its
own relevant data.
For example consider we have a Class of Cars under which Santro Xing, Alto and Wagener
represents individual Objects. In this context each Car Object will have its own, Model, Year
of Manufacture, Color, Top Speed, Engine Power etc., which form Properties of the Car class
and the associated actions i.e., object functions like Start, Move, and Stop form the Methods
of Car Class.
No memory is allocated when a class is created. Memory is allocated only when an object is
created, i.e., when an instance of a class is created.
DATA ABSTRACTION:
Data abstraction refers to providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in program
without presenting the details.
Data abstraction is a programming (and design) technique that relies on the
separation of interface and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs, and DVD
players, BUT you do not know its internal details, that is, you do not know how it receives
signals over the air or through a cable, how it translates them, and finally displays them on
the screen.
Thus, we can say a television clearly separates its internal implementation from its
external interface and you can play with its interfaces like the power button, channel
changer, and volume control without having zero knowledge of its internals.
Object Oriented Concepts using Java
Example:
TV operation
It is encapsulated with cover and we can operate with remote and no need to
open TV and change the channel.
Here everything is in private except remote so that anyone can access not to operate and change the
things in TV.
INHERITANCE OR REUSABILITY
The mechanism that allows us to extend the definition of a class without making any
physical changes to the existing class is inheritance.
Inheritance lets you create new classes from existing class. Any new class that you create
from an existing class is called derived class; existing class is called base class.
The inheritance relationship enables a derived class to inherit features from its base
class. Furthermore, the derived class can add new features of its own. Therefore, rather than
create completely new classes from scratch, you can take advantage of inheritance and
reduce software complexity.
Object Oriented Concepts using Java
TYPES OF INHERITANCE
Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from
one base class.
Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from
multiple base classes. But java does not support multiple inheritance.
Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class
for other classes.
Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other
four types of inheritance.
Object Oriented Concepts using Java
POLYMORPHISM
"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an
object (or reference) to assume (be replaced by) or become many different forms of object.
Example: function overloading, function overriding, virtual functions.
Example1:
A Teacher behaves to student.
A Teacher behaves to his/her seniors.
Here teacher is an object but attitude is different in different situation.
Example2:
Below is a simple example of the above concept of polymorphism:
6 + 10
The above refers to integer addition.
The same + operator can also be used for floating point addition:
7.15 + 3.78
TYPES OF POLYMORPHISM
There are two types of polymorphism one is compile time polymorphism and the
other is run time polymorphism. Compile time polymorphism is functions and operators
overloading. Runtime time polymorphism is done using inheritance and virtual functions.
Here are some ways how we implement polymorphism in Object Oriented programming
languages.
Object Oriented Concepts using Java
Compile time polymorphism -> Function Overloading
Run time polymorphism -> Interface and abstract methods, Virtual member functions.
Method/Function overloading
METHOD/FUNCTION OVERLOADING
Using a single function name to perform different types of tasks is known as function
overloading. Using the concept of function overloading, design a family of functions with one
function name but with different argument lists. The function would perform different
operations depending on the argument list in the function call. The correct function to b e
invoked is determined by checking the number and type of the arguments but not on the
function type.
Run-time:
The appropriate member function could be selected while the programming is
running. This is known as run-time polymorphism. The run-time polymorphism is
implemented with inheritance.
Method/Function overriding
METHOD/FUNCTION OVERRIDING
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
In other words, if subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as method overriding.
DYNAMIC BINDING
Binding refers connecting the function call to a function definition/implementation.
Or It is a link between the function call and function definition.
Types of Binding
Static Binding.
Dynamic Binding.
STATIC BINDING:
By default, matching of function call with the correct function definition happens at
compile time. This is called static binding or early binding or compile-time binding. Static
binding is achieved using function overloading and operator overloading. Even though
Object Oriented Concepts using Java
there are two or more functions with same name, compiler uniquely identifies each function
depending on the parameters passed to those functions.
DYNAMIC BINDING:
Java provides facility to specify that the compiler should match function calls with
the correct definition at the run time; this is called dynamic binding or late binding or run-
time binding. Dynamic binding is achieved using virtual functions. Base class pointer points
to derived class object. And a function is declared virtual in base class, then the matching
function is identified at run-time using virtual table entry.
MESSAGE PASSING
Message passing nothing but sending and receiving of information by the objects
same as people exchange information. So this helps in building systems that simulate real
life. Following are the basic steps in message passing.
Creating classes that define objects and its behaviour.
Creating objects from class definitions
Establishing communication among objects
In OOPs, Message Passing involves specifying the name of objects, the name of the function,
and the information to be sent.
For example: student.mark (name). Here student is object, mark is message, and name is
information.
APPLICATIONS OF OOP:
Applications of OOP are beginning to gain importance in many areas. The most
important application is user interface design. Real business systems are more complex and
contain many attributes and methods, but OOP applications can simplify a complex
problem.
1. User interface design such as windows, menu.
2. Real Time Systems
3. Simulation and Modeling
4. Object oriented databases
5. AI and Expert System
6. Neural Networks and parallel programming
7. Decision support and office automation system
8. Computer animation
9. To design Compiler
10. To access relational data base
11. To develop administrative tools and system tools
12. To develop computer games
ABSTRACTION ENCAPSULATION
1. Abstraction solves the problem in the 1. Encapsulation solves the problem in the
design level. implementation level.
2. Abstraction is used for hiding the 2. Encapsulation means hiding the code
unwanted data and giving relevant data. and data into a single unit to protect the
data from outside world.
3. Abstraction lets you focus on what the 3. Encapsulation means hiding the
object does instead of how it does it internal details or mechanics of how an
object does something.
Introduction to Java
Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language.
History of Java
The history of Java is very interesting. Java was originally designed for interactive
television, but it was to advanced technology for the digital cable television industry at the
time.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries
like the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Object Oriented Concepts using Java
7) Why had they chose the name Java for Java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They
wanted something that reflected the essence of the technology: revolutionary, dynamic,
lively, cool, unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java
was so unique, most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It
is a kind of espresso bean. Java name was chosen by James Gosling while having a cup of
coffee nearby his office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been
many additional features added to the language. Now Java is being used in Windows
applications, Web applications, enterprise applications, mobile applications, cards, etc. Each
new version adds new features in Java.
Java Version History
Many java versions have been released till now. The current stable release of Java is Java SE
18.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (22 April 2022)
Object Oriented Concepts using Java
Features of Java
1. Compiled and Interpreted
2. Platform Independent and Portable
3. Object-Oriented
4. Robust and Secured
5. Distributed
6. Simple, Small and Familiar
7. Multithreaded & Interactive
8. High Performance
9. Dynamic & Extensible
10. Scalability and Performance
Here the MyFirstProgram.class generated on any machine(OS) can be run on any other
machine having same or different OS. This is why we call java is a platform independent
language.
Object Oriented Concepts using Java
As we know, java code written on one machine can be run on another machine. The
platform-independent feature of java in which its platform-independent bytecode can be
taken to any platform for execution makes java portable.
Object Oriented
We Know that is purely OOP Language that is all the Code of the java Language is Written
into the classes and Objects So For This feature java is Most Popular Language because it
also Supports Code Reusability, Maintainability etc. Java is not pure object oriented
language because it supports primitive data types (byte, int, float etc) which are not objects.
Distributed
Java is also called a distributed language. This means java programs running on one
machine can easily access the resources (files, java objects etc) of other machine on
internet/network. Java provides class libraries for high-level support of networking. We
can also say, same or different applications running on different JVM on different machines
can interact with each other for sharing data over the internet. RMI and EJB are mostly used
for distributed programming.
High Performance
Java architecture is defined in such a way that it reduces overhead during the
runtime and at some time java uses Just In Time (JIT) compiler where the compiler
compiles code on-demand basics where it only compiles those methods that are called
making applications to execute faster.
C vs C++ vs Java
The languages are based on each other but still, they are different in design and
philosophy. The following table describes the major differences between C, C++, and Java.
It will help you to select which language you have to learn.
Object Oriented Concepts using Java
S.N. Basis C C++ Java
The Java
The C++ language
The C language is programming
1 Origin is based on the C
based on BCPL. language is based on
language.
both C and C++.
It is an object- It is a pure object-
Programming It is a procedural oriented oriented
2
Pattern language. programming programming
language. language.
It also uses the
It uses the top-down It uses the bottom-
3 Approach bottom-up
approach. up approach.
approach.
It is a static It is also a static It is a dynamic
Dynamic or
4 programming programming programming
Static
language. language. language.
Code The code is executed The code is The code is executed
5
Execution directly. executed directly. by the JVM.
It is platform-
Platform It is platform It is platform
6 independent because
Dependency dependent. dependent.
of byte code.
Java uses both
It also uses a
It uses a compiler compiler and
compiler only to
only to translate the interpreter and it is
7 Translator translate the code
code into machine also known as an
into machine
language. interpreted
language.
language.
File It generates the .exe, It generates .exe It generates .class
8
Generation and .bak, files. file. file.
There There There
Number of
9 are 32 keywords in are 60 keywords in are 52 keywords in
Keyword
the C language. the C++ language. the Java language.
Source File The source file has a The source file has The source file has a
10
Extension .c extension. a .cpp extension. .java extension.
Java does not
Pointer It also supports support the pointer
11 It supports pointer.
Concept pointer. concept because of
security.
It also supports
Union and It supports union It does not support
union and
12 Structure and structure data union and structure
structure data
Datatype types. data types.
types.
It uses pre-
It uses pre-processor
processor It does not use
Pre-processor directives such as
13 directives such as directives but uses
Directives #include, #define,
#include, #define, packages.
etc.
#header, etc.
Object Oriented Concepts using Java
It does not support It supports both
Constructor/ It supports
14 constructor and constructor and
Destructor constructors only.
destructor. destructor.
It supports
Exception It does not support It also supports
15 exception
Handling exception handling. exception handling.
handling.
It uses the calloc(),
It uses new and
malloc(), free(), and It uses a garbage
Memory delete operator to
16 realloc() methods to collector to manage
Management manage the
manage the the memory.
memory.
memory.
Method and
It does not support Only method
operator
17 Overloading the overloading overloading can be
overloading can be
concept. achieved.
achieved.
goto It supports the goto It also supports the It does not support
18
Statement statement. goto statement. the goto statements.
It is used to develop
It is widely used to It is widely used web applications,
19 Used for develop drivers and for system mobile applications,
operating systems. programming. and windows
applications.
An array can
be declared
An array should be
without
declared with size. An array should be
20 Array Size declaring the
For example, int declared with size.
size. For
num[10].
example, int
num[].
The first reason is that the Object oriented programming language should only have
objects whereas java contains 8 primitive data types like char, boolean, byte, short,
int, long, float, double which are not objects. These primitive data types can be used
without the use of any object. (Eg. int x=10; System.out.print(x.toString());)
The second reason related to the static keyword. In pure object oriented language,
we should access everything by message passing (through objects). But java contains
static variables and methods which can be accessed directly without using objects.
That means, when we declare a class as 'static' then it can be referenced without the
use of an object.
The Virtual machine code is not machine specific. The machine specific code is generated
by Java interpreter by acting as an intermediary between the virtual machine and real
machines as shown above diagram.
Object Oriented Concepts using Java
Java Object Framework act as the intermediary between the user programs and the virtual
machine which in turn act as the intermediary between the operating system and the Java
Object Framework.
For compiling and running the program, we have to use following commands:
a) javac (Java compiler) In java, we can use any text editor for writing program and
then save that program with “.java” extension. Java compiler is a platform independent. Java
compiler convert the source code or program in bytecode and interpreter convert “.java”
file in “.class” file. Syntax: C:\javac filename.java If my filename is “abc.java” then the
syntax will be
C:\javac abc.java
b) java (Java Interpreter) As the Java compiler compiles the source code into the Java
bytecode. In the same way, the Java interpreter converts or translates the bytecode into the
machine-understandable format i.e. machine code, after that the machine code interacts
with the operating system. Java interpreter is a platform dependent.
Object Oriented Concepts using Java
C:\java ab
Overview of Java
Java is a general purpose, object oriented programming language
Stand-alone program
Stand-alone programs are simple programs
They written in java to carry out certain tasks on a standalone local computer
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is
currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in, javatpoint.com etc.
Object Oriented Concepts using Java
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
Documentation Section
It is used to improve the readability of the program. It consists of comments in Java
that include basic information such as the method’s usage or functionality to make it easier
for the programmer to understand it while reviewing or debugging the code. A Java
comment is not necessarily limited to a confined space, it can appear anywhere in the code.
The compiler ignores these comments during the time of execution and is solely meant for
improving the readability of the Java program.
There are three types of comments that Java supports
Single line Comment
Multi-line Comment
Documentation Comment
Let us look at an example to understand how we can use the above-mentioned comments in
a Java program.
// a single line comment is declared like this
/* a multi-line comment is declared like this
and can have multiple lines as a comment */
/** a documentation comment starts with a delimiter and ends with */
Object Oriented Concepts using Java
Package Statement
There is a provision in Java that allows you to declare your classes in a collection called
package. There can be only one package statement in a Java program and it has to be at the
beginning of the code before any class or interface declaration. This statement is optional, for
example, take a look at the statement below.
package student;
This statement declares that all the classes and interfaces defined in this source file are a part
of the student package. Only one package can be declared in the source file.
Import Statement
Many predefined classes are stored in packages in Java, an import statement is used
to refer to the classes stored in other packages. An import statement is always written after
the package statement but it has to be before any class declaration.
We can import a specific class or classes in an import statement. Take a look at the example
to understand how to import statement works in Java.
Interface Section
This section is used to specify an interface in Java. It is an optional section which is
mainly used to implement multiple inheritances in Java. An interface is a lot similar to a class
in Java but it contains only constants and method declarations.
An interface cannot be instantiated but it can be implemented by classes or extended by other
interfaces.
interface stack
{
void push(int item);
void pop();
}
Class Definition
A Java program may contain several class definitions, classes are an essential part of
any Java program. It defines the information about the user-defined classes in a program.
A class is a collection of variables and methods that operate on the fields. Every program in
Java will have at least one class with the main method.
Let’s analyse the above program line by line to understand how it works.
Comments
To improve the readability, we can use comments to define a specific note or
functionality of methods, etc for the programmer.
Braces
The curly brackets are used to group all the commands together. To make sure that
the commands belong to a class or a method.
String[] args
It is an array where each element is a string, which is named as args. If you run the
Java code through a console, you can pass the input parameter. The main() takes it as an
input.
System.out.println();
The statement is used to print the output on the screen where the system is a
predefined class, out is an object of the PrintWriter class. The method println prints the text
on the screen with a new line. All Java statements end with a semicolon.
Object Oriented Concepts using Java
When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do class,
object, methods, and instance variables mean.
Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behavior such as wagging their tail, barking, eating. An object is an
instance of a class.
Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
Methods − A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
Step2: The Java programs are store with the extension of mainclassname.java
Step4: For compiling programs always use javac filename.java in the command prompt
The Java compiler also recognizes and subsequently removes comments and whitespaces.
Example:
public class Hello
{
public static void main(String args[])
{
System.out.println(“Welcome in Java”); //print welcome in java
}
}
In above Example,
The source code contains tokens such as public, class, Hello, {, public, static, void,
main, (, String, [], args, {, System, out, println(, “welcome in Java”, }, }.
The resulting tokens· are compiled into Java bytecodes that is capable of being run
from within an interpreted java environment.
Token are useful for compiler to detect errors.
When tokens are not arranged in a particular sequence, the compiler generates an
error message.
Object Oriented Concepts using Java
Identifiers:
Identifiers are tokens that represent names.
These names can be assigned to variables, methods, and classes to uniquely identify
them to the compiler.
Identifiers are,
Sequence of Uppercase letters(A to Z)
Sequence of Lowercase letters (a to z)
Numbers (0 to 9)
Underscore (_)
Dollar Symbol ($)
Valid Invalid
$age #age (does not begin with any other symbol except _ $ )
Object Oriented Concepts using Java
Keywords or Reserved Words or Predefined words
Keywords are pre-defined, reserved words used in Java programming that have
special meanings to the compiler. In Java, we have 53 such reserved words, out of which 48
are in use and 2 are reserved but not in use and 3 are reserved literals.
For example:
int score;
Here, int is a keyword. It indicates that the variable score is of integer type (32-bit signed
two's complement integer).
You cannot use keywords like int, for, class, etc as variable name (or identifiers) as they are
part of the Java programming language syntax. Here is the complete list of all keywords in
Java programming.
Object Oriented Concepts using Java
Constants or Literals
Constants in java are fixed values those are not changed during the execution of
program java supports several types of Constants those are :
JAVA
CONSTANTS
Non-Numeric or
NUMERIC
CHARACTER
CONSTANTS CONSTANTS
SINGLE
INTEGER REAL/FLOAT STRING
CHARACTER
CONSTANTS CONSTANTS CONSTANTS CONSTANTS
Integer constants
An integer constant refers to a sequence of digits. It includes,
1. Decimal integer
2. Octal integer
3. Hexadecimal integer
1. Decimal Integer
It consists of a set of digits, 0 through 9, preceded by an optional minus sign.
Valid examples of integer constants are, 123, -321, 0 ,654321
Embedded spaces, commas & non-digit characters are not permitted b/w
digits.
Mantissa e exponent
Character constants
Single Character constants
A single character constant or simply character constant contains a single character
enclosed within a pair of single quote marks.
The characters may be alphabets, digits, special characters and blank spaces.
String constants
A string constant is a sequence of characters enclosed between double quotes. The
characters may be alphabets, digits, special characters and blank spaces.
EXAMPLE PROGRAM:
class Simple
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Object Oriented Concepts using Java
Declaring constant in Java
In Java, to declare any variable as constant, we use static and final modifiers. It is also
known as non-access modifiers. According to the Java naming convention the identifier
name must be in capital letters.
Where static and final are the non-access modifiers. The double is the data type and PRICE
is the identifier name in which the value 432.78 is assigned.
In the above statement, the static modifier causes the variable to be available without an
instance of its defining class being loaded and the final modifier makes the variable fixed.
Here a question arises that why we use both static and final modifiers to declare a
constant?
If we declare a variable as static, all the objects of the class (in which constant is defined)
will be able to access the variable and can be changed its value. To overcome this problem,
we use the final modifier with a static modifier.
When the variable defined as final, the multiple instances of the same constant value will
be created for every different object, which is not desirable.
When we use static and final modifiers together, the variable remains static and can be
initialized once. Therefore, to declare a variable as constant, we use both static and final
modifiers. It shares a common memory location for all objects of its containing class.
Object Oriented Concepts using Java
DATA TYPES:
Every variable in java has a data type.
Data types specify the size and type of values that can be stored.
Java language is rich in its data types.
Primitive types are also called as intrinsic or built-in types.
Derived data types are also known as reference types.
Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory.
.
Object Oriented Concepts using Java
byte
Byte data type is an 8-bit signed two's complement integer
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers, since
a byte is four times smaller than an integer.
Example: byte a = 100, byte b = -50
short
Short data type is a 16-bit signed two's complement integer
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer
Default value is 0.
Example: short s = 10000, short r = -20000
int
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648 (-2^31)
Maximum value is 2,147,483,647(inclusive) (2^31 -1)
Integer is generally used as the default data type for integral values unless there is a
concern about memory.
The default value is 0
Example: int a = 100000, int b = -200000
Object Oriented Concepts using Java
Example Program:
class Simple
{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Output:
10
10.0
long
Long data type is a 64-bit signed two's complement integer
Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
This type is used when a wider range than int is needed
Default value is 0L
Example: long a = 100000L, long b = -200000L
float
Float data type is a single-precision 32-bit IEEE 754 floating point
Float is mainly used to save memory in large arrays of floating point numbers
Default value is 0.0f
Float data type is never used for precise values such as currency
Example: float f1 = 234.5f
double
double data type is a double-precision 64-bit IEEE 754 floating point
This data type is generally used as the default data type for decimal values, generally
the default choice
Double data type should never be used for precise values such as currency
Default value is 0.0d
Example: double d1 = 123.4
boolean
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for simple flags that track true/false conditions
Default value is false
Example: boolean one = true
char
char data type is a single 16-bit Unicode character
Object Oriented Concepts using Java
Minimum value is '\u0000' (or 0)
Maximum value is '\uffff' (or 65,535 inclusive)
Char data type is used to store any character
Example: char letterA = 'A'
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in the memory.
Local Variables
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or block.
There is no default value for local variables, so local variables should be declared
and an initial value should be assigned before the first use.
Example
class Functionoverloading
{
public void add(int x, int y)
{
int sum; //local variables
sum=x+y;
System.out.println(sum);
}
Object Oriented Concepts using Java
public void add(double a, double b)
{
double total; //local variables
total=a+b;
System.out.println(total);
}
}
class Mainfunover
{
public static void main(String args[])
{
Functionoverloading obj = new Functionoverloading();
obj.add(10,20);
obj.add(10.40,10.30);
}
}
Output:
Instance Variables
Instance variables are declared in a class, but outside a method, constructor or any
block.
When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
Instance variables can be accessed directly by calling the variable name inside the
class.
import java.io.*;
public class Employee
{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal)
{
salary = empSal;
}
// this method prints the employee details.
public void printEmp()
{
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
Class/Static Variables
Class variables also known as static variables are declared with the static keyword
in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
Static variables are created when the program starts and destroyed when the
program stops.
Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
Static variables can be accessed by calling with the class
name ClassName.VariableName.
Example
/* Program with class variable that is available for all instances of a class. Use static
variable declaration. Observe the changes that occur in the object’s member variable
values.*/
Object Oriented Concepts using Java
class StaticDemo
{
static int count=0; //static variable declaration
public void increment()
{
count++;
}
public static void main(String args[])
{
StaticDemo obj1=new StaticDemo ();
StaticDemo obj2=new StaticDemo ();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Output:
Operators
An operator is a special symbol that tells the compiler to perform a specific
mathematical or logical operation on one or more operands where an operand can be an
expression. An operation is an action(s) performed on one or more operands that evaluates
mathematical expressions or change the data.
There are many types of operators in java, which are given below:
Object Oriented Concepts using Java
Unary Operator
Unary operators are the types that need only one operand to perform any operation
like increment, decrement, negation, etc.
Arithmetic Operators:
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as Java arithmetic operators.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
Example:
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}
}
Output: 21
Object Oriented Concepts using Java
Relational Operators are a bunch of binary operators used to check for relations between
two operands, including equality, greater than, less than, etc. They return a boolean result
after the comparison and are extensively used in looping statements as well as conditional if-
else statements and so on.
Example
public class Test
{
public static void main(String args[])
{
int a = 10,b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
}
}
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
Object Oriented Concepts using Java
Logical Operators:
These operators are used to perform logical “AND”, “OR” and “NOT” operation,
i.e. the function similar to AND gate and OR gate in digital electronics. They are used to
combine two or more conditions/constraints or to complement the evaluation of the
original condition under particular consideration.
Bitwise Operators:
Bitwise operators are used to performing the manipulation of individual bits of a
number. They can be used with any integral type (char, short, int, etc.).
= Assign 10+10 = 20
Syntax:
variable = Expression ? expression1 : expression2
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Output
Leap year
In the above example, we have used the ternary operator to check if the year is a leap year
or not.
Other operators
Besides these operators, there are other additional operators in Java.
Operator Description
Expressions
Expressions are a combination of variables, constants & operators arranged as per
the syntax of the language.
Java can handle any complex mathematical expressions.
Evaluation of expression:
Expressions are evaluated using an assignment statement of the form
Variable=expression;
Variable is any valid java variable name.
When the statement is encountered, the expression is evaluated first & the result then
replaces the previous value of the variable on the left-hand side.
Ex:
X=a*b-c;
Y=b/c*a;
Z=a-b/c + d;
The blank spaces around an operator are optional & it is added only to improve
readability.
The variables a, b, c, d must be defined before they are used in the expression.
Object Oriented Concepts using Java
Operator Precedence
Example:
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2); //expression
}
}
Output:
21
o if statement
o if-else statement
o Nested if-else statement
o if-else-if ladder
Syntax:
if(condition)
{
//code to be executed
}
Example:
public class IfExample
{
public static void main(String[] arg)
{
Object Oriented Concepts using Java
int age=20;
if(age>18)
{
System.out.print("Age is greater than 18");
}
}}
Output:
Age is greater than 18
Syntax:
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
}
}
Example:
public class Test
{
public static void main(String args[])
{
int x = 30;
int y = 10;
if( x == 30 )
{
if( y == 10 )
{
System.out.print("X = 30 and Y = 10");
}
}
}
}
Object Oriented Concepts using Java
if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}
Object Oriented Concepts using Java
Example:
public class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}
Output:
C grade
Object Oriented Concepts using Java
Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Object Oriented Concepts using Java
Example:
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number)
{
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output: 20
Iteration Statement:
Syntax:
for(initialization;condition;incr/decr)
{
//code to be executed
}
Object Oriented Concepts using Java
Example:
/* Program to accept a number and find whether the number is Prime or not.*/
import java.util.*;
class Prime
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no");
int n = sc.nextInt();
int i=1,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==2)
{
System.out.println(n+" is a PRIME no");
}
else
{
System.out.println(n+" is a NOT a prime no");
}
}
}
Output:
Object Oriented Concepts using Java
While Loop
The Java while loop is used to iterate a
part of the program several times. If the
number of iteration is not fixed, it is
recommended to use while loop.
Syntax:
while(condition)
{
//code to be executed
}
Example:
/* Program to list the factorial of the
numbers 1 to 10. To calculate the factorial
value, use while loop.*/
do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop. The Java do-while loop is executed at least once because
condition is checked after loop body.
Syntax:
do
{
//code to be executed
}while(condition);
Example:
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=8);
}
}
Output:
12 34 5678
Statements or loops perform a set of operations continually until the control variable
will not satisfy the condition.
But if we want to break the loops when condition will satisfy then Java give a
permission to jump from one statement to end of loop or beginning of loop as well
as jump out of a loop.
“break” keyword use for exiting from loop and “continue” keyword use for
continuing the loop.
Break statement is used to terminate from a loop while a test condition is true.
1. Break statement
2. Continue statement
Break Statement
The Java break is used to break loop or switch statement. It breaks the current flow of
the program at specified condition. In case of inner loop, it breaks only inner loop.
Syntax:
jump-statement;
break;
Example:
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
break;
}
System.out.println(i);
}
}
}
Output:
1234
Object Oriented Concepts using Java
Continue Statement
The Java continue statement is used to continue loop. It continues the current flow of
the program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.
Syntax:
jump-statement;
continue;
Example:
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++){
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}
Output:
1 2 3 4 6 7 8 9 10
Java Methods
A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability of code.
We write a method once and use it many times. We do not require to write code again and
again. It also provides the easy modification and readability of code, just by adding or
removing a chunk of code. The method is executed only when we call or invoke it.
Method Declaration :
In general, method declarations has six components:
1. Modifier: It defines the access type of the method i.e. from where it can be accessed in
your application. In Java, there 4 types of access specifiers.
public: It is accessible in all classes in your application.
protected: It is accessible within the class in which it is defined and in its subclass/es
private: It is accessible only within the class in which it is defined.
Object Oriented Concepts using Java
default: It is declared/defined without using any modifier. It is accessible within the
same class and package within which its class is defined.
2. The return type: The data type of the value returned by the method or void if does not
return a value.
3. Method Name: the rules for field names apply to method names as well, but the
convention is a little different.
4. Parameter list: Comma-separated list of the input parameters is defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
5. Exception list: The exceptions you expect by the method can throw, you can specify
these exception(s).
6. Method body: it is enclosed between braces. The code you need to be executed to
perform your intended operations.
1. Predefined Method: In Java, predefined methods are the method that is already defined
in the Java class libraries is known as predefined methods. It is also known as the standard
library method or built-in method. We can directly use these methods just by calling
them in the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc.
2. User-defined Method: The method written by the user or programmer is known as a
user-defined method. These methods are modified according to the requirement.
Object Oriented Concepts using Java
Types of User-defined methods
Static Method or Factory Methods
Instance Method
Abstract Method
1. Static Method
A method that has static keyword is known as static method. In other words, a
method that belongs to a class rather than an instance of a class is known as a static
method. We can also create a static method by using the keyword static before the method
name.
The main advantage of a static method is that we can call it without creating an
object. It can access static data members and also change the value of it. It is used to create
an instance method. It is invoked by using the class name. The best example of a static
method is the main() method.
2. Instance Method
The method of the class is known as an instance method. It is a non-static method
defined in the class. Before calling or invoking the instance method, it is necessary to create
an object of its class.
3. Abstract Method
The method that does not has method body is known as abstract method. In other
words, without an implementation is known as abstract method. It always declares in
the abstract class. It means the class itself must be abstract if it has abstract method. To
create an abstract method, we use the keyword abstract.
/* Program to add two integers and two float numbers. When no arguments are supplied,
give a default value to calculate the sum. Use function overloading.*/
class Functionoverloading
{
public void add(int x, int y)
{
int sum;
sum=x+y;
System.out.println(sum);
}
public void add(double a, double b)
{
double total;
total=a+b;
System.out.println(total);
}
}
class Mainfunover
{
public static void main(String args[])
{
Functionoverloading obj = new Functionoverloading();
obj.add(10,20);
obj.add(10.40,10.30);
}
}
Output:
Object Oriented Concepts using Java
2. Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition
of two numbers and second add method performs addition of three numbers.
/* Program to add two integers and two float numbers. When no arguments are supplied,
give a default value to calculate the sum. Use function overloading.*/
class Functionoverloading
{
public void add(int x, int y)
{
int sum;
sum=x+y;
System.out.println(sum);
}
public void add(int a, int b, int c)
{
int total;
total=a+b+c;
System.out.println(total);
}
}
class Mainfunover
{
public static void main(String args[])
{
Functionoverloading obj = new Functionoverloading();
obj.add(10,20);
obj.add(10,20,30);
}
}
Output:
30
60
The class Math contains methods for performing basic numeric operations such as
the elementary exponential, logarithm, square root, and trigonometric functions. Unlike
some of the numeric methods of class StrictMath, all implementations of the equivalent
functions of class Math are not defined to return the bit-for-bit the same results. This
relaxation permits better-performing implementations where strict reproducibility is not
required.
Object Oriented Concepts using Java
The java.lang.Math class provides us access to many of these functions. The table
below lists some of the more common among these.
// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));
Java array is an object, which contains elements of a similar data type. Additionally, the
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Advantages
o Code Optimization: It makes the code optimized; we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It does not grow
its size at runtime. To solve this problem, collection framework is used in Java, which
grows automatically.
Creation of arrays
To allocate space for an array element use below general form or syntax.
arrayName = new type[size];
Where arrayName is the name of the array and type is a valid java datatype
and size specifies the number of elements in the array.
Example: physics = new int[10];
Above statement will create an integer of an array with ten elements that can be
accessed by physics.
physics[0]
Structure of one dimensional array physics[1]
Note that array indexes begins with zero.
physics[2]
That means if you want to access 1st element of an array use zero as
physics[3]
an index.
To access 3rd element refer below example. physics[4]
physics[2] = 10; // it assigns value 10 to the third element of an array. physics[5]
java also allows an abbreviated syntax to declare an array. General physics[6]
form or syntax of is is as shown below.
physics[7]
physics[8]
physics[9]
Initialization of an Array
The final step is to put values into the array created. This process is known as
initialization.
Syntax:
arrayname[subscript] = value;
Example:
physics[0]=12;
physics[1]=15;
physics[2]=16;
physics[3]=18;
physics[4]=20;
physics[5]=23;
physics[6]=25;
physics[7]=27;
Object Oriented Concepts using Java
physics[8]=30;
physics[9]=35;
In The above example assigns the value as,
physics[0] 12
physics[1] 15
physics[2] 16
physics[3] 18
physics[4] 20
physics[5] 23
physics[6] 25
physics[7] 27
physics[8] 30
physics[9] 35
Example Program:
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output:
10
20
70
40
50
Object Oriented Concepts using Java
Example for Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Syntax:
DataType ArrayName[][];
ArrayName = new DataType[][];
(or)
DataType ArrayName[][] = new DataType[][];
Data_type:
This will decide the type of elements it will accept.
For example, If we want to store integer values then, the Data Type will be declared
as int, If we want to store Float values then, the Data Type will be float etc.
Array_Name:
This is the name you want to give it to array.
For example Car, students, age, marks, department, employees etc
Object Oriented Concepts using Java
Creating of Two Dimensional Array in java
int[][] a = new int[3][4];
Here, a is a two-dimensional array. The array can
hold maximum of 12 elements of type int.
Java uses zero-based indexing, that is, indexing
of arrays in Java starts with 0 and not 1.
Intialization of Array:
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
Example:
class MultidimensionalArray
{
public static void main(String[] args)
{
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
System.out.println("Length of row 1: " + a[0].length);
System.out.println("Length of row 2: " + a[1].length);
System.out.println("Length of row 3: " + a[2].length);
}
}
Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
Object Oriented Concepts using Java
One Marks Questions
1. What is object and class?
2. What do you mean by data abstraction and encapsulation?
3. What is inheritance? Mention types of inheritance.
4. What is binding? Mention different types of binding
5. Who and when java was developed?
6. What was the first name of java?
7. Expand JDK, JVM and JRE
8. Which is the latest version of java?
9. When & which company owns java?
10. Why java is called compiled and interpreted language?
11. What do you mean platform independent?
12. What do you mean by garbage collection in java?
13. Why is java is called secured?
14. Mention types of programs in java?
15. What is import statement? Give example
16. What is javac and java?
17. What are tokens? Mention types of java tokens?
18. What is identifier? Give Example
19. Mention any two valid and invalid identifiers
20. What is literal? Give example
21. What is variable? Mention types of variable
22. What is byte code in java?
23. Write any 5 keywords in java?
24. What is static and final modifiers in java?
25. What is reference data types in java?
26. What is instanceof and new operator in java?
27. What is one way branching?
28. What is two way branching?
29. What is method? Mention different types of user defined methods in java?
30. What is method overloading? Give example
31. Mention different types to implement method overloading in java?
32. Why Math class is used in java?
33. Math.floor() and Math.random() mention their use in java?
34. What is array? Mention types of array
35. Write syntax to create array in java?
Object Oriented Concepts using Java
Five Marks Questions
1. Write a short note on History of Java?
2. Why java is Platform independent? Justify your answer
3. Write a short note on JVM?
4. Is java pure object oriented language? Justify your answer
5. Explain public static void main (String [] args) method in java?
6. Write rules to declare identifiers or variable.
7. How to declare constants in java?
8. What is class or static variable? Explain with example
9. Write a short note on Operators in Java?
10. What is ternary operator? Explain with syntax and example?
11. Differentiate between while and do while loop?
12. Explain switch statement with syntax and example?
13. Explain break and continue statements in java?
14. What is method? Explain different types methods in java?
15. Write a short note on Math class and its methods in java?