0% found this document useful (0 votes)
5 views

Java Unit-I Notes

Uploaded by

Bhumika Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java Unit-I Notes

Uploaded by

Bhumika Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

CS405PC: JAVA PROGRAMMING

B.TECH II Year II Sem.


L T P C
3 1 0 4
Course Objectives:
 To introduce the object oriented programming concepts.
 To understand object oriented programming concepts, and apply them in solving problems.
 To introduce the principles of inheritance and polymorphism; and demonstrate how they
relate to the design of abstract classes
 To introduce the implementation of packages and interfaces
 To introduce the concepts of exception handling and multithreading.
 To introduce the design of Graphical User Interface using applets and swing controls.
Course Outcomes:
 Able to solve real world problems using OOP techniques.
 Able to understand the use of abstract classes.
 Able to solve problems using java collection framework and I/o classes.
 Able to develop multithreaded applications with synchronization.
 Able to develop applets for web applications.
 Able to design GUI based applications
UNIT - I
Object-Oriented Thinking- A way of viewing world – Agents and Communities, messages and
methods, Responsibilities, Classes and Instances, Class Hierarchies- Inheritance, Method
binding, Overriding and Exceptions, Summary of Object-Oriented concepts. Java buzzwords, An
Overview of Java, Data types, Variables and Arrays, operators, expressions, control statements,
Introducing classes, Methods and Classes, String handling.
Inheritance– Inheritance concept, Inheritance basics, Member access, Constructors, Creating
Multilevel hierarchy, super uses, using final with inheritance, Polymorphism-ad hoc
polymorphism, pure polymorphism, method overriding, abstract classes, Object class, forms of
inheritance- specialization, specification, construction, extension, limitation, combination,
benefits of inheritance, costs of inheritance.
UNIT - II
Packages- Defining a Package, CLASSPATH, Access protection, importing packages.
Interfaces- defining an interface, implementing interfaces, Nested interfaces, applying
interfaces, variables in interfaces and extending interfaces.
Stream based I/O (java.io) – The Stream classes-Byte streams and Character streams, Reading
console Input and Writing Console Output, File class, Reading and writing Files, Random access
file operations, The Console class, Serialization, Enumerations, auto boxing, generics.
UNIT - III
Exception handling - Fundamentals of exception handling, Exception types, Termination or
resumptive models, Uncaught exceptions, using try and catch, multiple catch clauses, nested try
statements, throw, throws and finally, built- in exceptions, creating own exception sub classes.
Multithreading- Differences between thread-based multitasking and process-based
multitasking, Java thread model, creating threads, thread priorities, synchronizing threads,
inter thread communication.
UNIT - IV
The Collections Framework (java.util)- Collections overview, Collection Interfaces, The
Collection classes- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque.
Accessing a Collection via an Iterator, Using an Iterator, The For-Each alternative, Map
Interfaces and Classes, Comparators, Collection algorithms, Arrays, The Legacy Classes and
Interfaces- Dictionary, Hashtable ,Properties, Stack, Vector
More Utility classes, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner
UNIT - V
GUI Programming with Swing – Introduction, limitations of AWT, MVC architecture,
components, containers. Understanding Layout Managers, Flow Layout, Border Layout, Grid
Layout, Card Layout, Grid Bag Layout.
Event Handling- The Delegation event model- Events, Event sources, Event Listeners, Event
classes, Handling mouse and keyboard events, Adapter classes, Inner classes, Anonymous Inner
classes.
A Simple Swing Application, Applets – Applets and HTML, Security Issues, Applets and
Applications, passing parameters to applets. Creating a Swing Applet, Painting in Swing, A Paint
example, Exploring Swing Controls- JLabel and Image Icon, JText Field, The Swing Buttons-
JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed Pane, JScroll Pane, JList, JCombo
Box, Swing Menus, Dialogs.
TEXT BOOKS:
1. Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education (India)
Pvt. Ltd.
2. Understanding Object-Oriented Programming with Java, updated edition, T. Budd,
Pearson Education.
REFERENCE BOOKS:
1. An Introduction to programming and OO design using Java, J. Nino and F.A.
Hosch, John Wiley & sons
2. Introduction to Java programming, Y. Daniel Liang, Pearson Education.
3. Object Oriented Programming through Java, P. Radha Krishna, University Press.
4. Programming in Java, S. Malhotra, S. Chudhary, 2nd edition, Oxford Univ. Press.
5. Java Programming and Object-oriented Application Development, R. A. Johnson, Cengage
Learning.
UNIT-I
OBJECT ORIENTED THINKING
 When computers were first invented, programming was done manually by toggling in a binary
machine instructions by use of front panel.
 As programs began to grow, high level languages were introduced that gives the programmer more
tools to handle complexity.
 The first widespread high level language is FORTRAN. Which gave birth to structured
programming in 1960’s. The Main problem with the high level language was they have no specific
structure and programs becomes larger, the problem of complexity also increases.
 So C became the popular structured oriented language to solve all the above problems.
 However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s a new way
of programming was invented and it was OOP. OOP is a programming methodology that helps to
organize complex programs through the use of inheritance, encapsulation & polymorphism.
A WAY OF VIEWING WORLD
 A way of viewing the world is an idea to illustrate the object-oriented programming concept with
an example of a real-world situation.
 Eg: Raju wished to send some flowers to his friend for his birthday & he was living some miles
away. He went to local florist and said the kind of flowers. He want to send to his friend’s address.
And florist assured those flowers will be sent automatically.
AGENTS AND COMMUNITIES
 An object-oriented program is structured as a community of interacting agents, called objects.
Where each object provides a service (data and methods) that is used by other members of the
community.
 Consider an eg, raju and ravi are good friends who live in two different cities far from each other. If
Raju wants to send flowers to ravi, he can request his local florist ‘hari’ to send flowers to ravi by
giving all the information along with the address.
 Hari works as an agent (or object) who performs the task of satisfying raju’s request. Hari then
performs a set of operations or methods to satisfy the request which is actually hidden from ravi,
Hari forwards a message to ravi’s local florist. Then local florist asks a delivery person to deliver
those flowers to ravi. The objects or agents helping raju in solving the problem of sending flowers
to his friend ravi can be shown in figure.
RESPONSIBILITIES
 A fundamental concept in OOP is to describe behavior in terms of responsibilities. A Request to
perform an action denotes the desired result. An object can use any technique that helps in
obtaining the desired result and this process will not have any interference from other object. The
abstraction level will be increased when a problem is evaluated in terms of responsibilities. The
objects will thus become independent from each other which will help in solving complex
problems. An Object has a collection of responsibilities related with it which is termed as ‘protocol’
 The Operation of a traditional program depends on how it acts on data structures. Where as an
OOP operates by requesting data structure to perform a service.
MESSAGES & METHODS
In object-oriented programming, every action is initiated by passing a message to an agent (object),
which is responsible for the action. The receiver is the object to whom the message was sent. In
response to the message, the receiver performs some method to carry out the request. Every message
may include any additional information as arguments.
CLASSES & INSTANCES
 In object-oriented programming, all objects are instances of a class. The method invoked by an
object in response to a message is decided by the class. All the objects of a class use the same
method in response to a similar message.
 All objects are said to be the instances of a class.
 For e.g., If ‘flower’ is a class then Rose is its instance
CLASS HIERARCHIES (INHERITANCE)
A graphical representation is often used to illustrate the relationships among the classes (objects) of a
community. This graphical representation shows classes listed in a hierarchical tree-like structure. In
this more abstract class listed near the top of the tree, and more specific classes in the middle of the
tree, and the individuals listed near the bottom.
In object-oriented programming, classes can be organized into a hierarchical inheritance
structure. A child class inherits properties from the parent class that higher in the tree.

Object Oriented Thinking

Let ‘Hari’ be a florist, but florist more specific form of shot keeper. Additionally, a shop keeper is a
human and a human is definitely a mammal. But a mammal is an animal & animal is material object.
METHOD BINDING
When the method is super class have same name that of the method in sub class, then the subclass
method overridden the super-class method. The program will find out a class to which the reference is
actually pointing and that class method will be binded.
Example
class parent
{
void print()
{
System.out.println(“From Parent”);
}
}
class child extends parent
{
void print()
{
System.out.println(“From Child”);
}
}
class Bind
{
Public static void main(String arg[])
{
child ob=new child();
ob.print();
}
}
Output: From Child
The child’s object ‘ob’ will point to child class print() method thus that method will be binded.
OVERRIDING
When the name and type of the method in a subclass is same as that of a method in its super class.
Then it is said that the method present in subclass overrides the method present in super class. Calling
an overridden method from a subclass will always point to the type of that method as defined by the
subclass, where as the type of method defined by super class is hidden.
E.g. (above ’method binding’ example)
EXCEPTIONS
Exception is a error condition that occurs in the program execution. There is an object called
‘Exception’ object that holds error information. This information includes the type and state of the
program when the error occurred.
E.g. Stack overflow, Memory error etc
SUMMARY OF OOP CONCEPTS
 Everything is an object.
 Computation is performed by objects communicating with each other, requesting that other objects
perform actions. Objects communicate by sending & receiving messages. A message is a request for
an action bundled with whatever arguments may be necessary to complete the task.
 Each object has its own memory, which consists of other objects.
 Every Object is an instance of class. A class simply represents a grouping of similar objects, such as
integers or lists.
 The class is the repository for behavior associated with an object. That is all objects that are
instances of same class can perform the same actions.
 Classes are organized into a singly rooted tree structure, called inheritance hierarchy.
OOP CONCEPTS
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every
program is follows the concept of object. In other words, OOP is a way of writing programs based on
the object concept.
The object-oriented programming paradigm has the following core concepts.
 Class
 Object
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction
Class
Class is a blue print which is containing only list of variables and methods and no memory is allocated
for them. A class is a group of objects that has common properties.
Object
 Any entity that has state and behavior is known as an object.
 For example a chair, pen, table, keyboard, bike, etc. It can be physical or logical.An Object can be
defined as an instance of a class.
 Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Encapsulation
 Encapsulation is the process of combining data and code into a single unit.
 In OOP, every object is associated with its data and code.
 In programming, data is defined as variables and code is defined as methods.
 The java programming language uses the class concept to implement encapsulation.
Inheritance
 Inheritance is the process of acquiring properties and behaviors from one object to another
object or one class to another class.
 In inheritance, we derive a new class from the existing class. Here, the new class acquires the
properties and behaviors from the existing class.
 In the inheritance concept, the class which provides properties is called as parent class and the
class which recieves the properties is called as child class.

Person
name,
designation
learn(),
walk(),
eat()

Programmer Dancer Singer


name, name, name,
designation designation designation
learn(), learn(), learn(),
walk(), walk(), walk(),
eat(), eat(), eat(),
coding() dancing() singing()

Polymorphism
 Polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviors.
 The java uses method overloading and method overriding to implement polymorphism.
 Method overloading - multiple methods with same name but different parameters.
 Method overriding - multiple methods with same name and same parameters.

Abstraction
 Abstraction is hiding the internal details and showing only esential functionality.
 In the abstraction concept, we do not show the actual implemention to the end user, instead we
provide only esential things.
 For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system
works? etc.
JAVA BUZZWORDS(JAVA FEATURES)
 Java is the most popular object-oriented programming language.
 Java has many advanced features, a list of key features is known as Java Buzz Words.
The Following list of Buzz Words
 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Architecture-neutral (or) Platform Independent
 Multi-threaded
 Interpreted
 High performance
 Distributed
 Dynamic
Simple
 Java programming language is very simple and easy to learn, understand, and code.
 Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++.
 In a java programming language, many complicated features like pointers, operator overloading,
structures, unions, etc. have been removed.
 One of the most useful features is the garbage collector it makes java more simple.
Secure
 Java is said to be more secure programming language because it does not have pointers concept.
 java provides a feature "applet" which can be embedded into a web application.
 The applet in java does not allow access to other parts of the computer, which keeps away from
harmful programs like viruses and unauthorized access.
Portable
 Portability is one of the core features of java .
 If a program yields the same result on every machine, then that program is called portable.
 Java programs are portable
 This is the result of java System independence nature.
Object-oriented
 Java is an object oriented programming language.
 This means java programs use objects and classes.
Robust
 Robust means strong.
 Java programs are strong and they don’t crash easily like a C or C++ programs
There are two reasons
 Java has got excellent inbuilt exception handling features. An exception is an error that occurs at
runtime. If an exception occurs, the program terminates suddenly giving rise to problems like loss
of data. Overcoming such problem is called exception handling.
 Most of the C and C++ programs crash in the middle because of not allocating sufficient memory or
forgetting the memory to be freed in a program. Such problems will not occur in java because the
user need not allocate or deallocate the memory in java. Everything will be taken care of by JVM
only.
Architecture-neutral (or) Platform Independent
 Java has invented to archive "write once; run anywhere, anytime, forever".
 The java provides JVM (Java Virtual Machine) to archive architectural-neutral or platform-
independent.
 The JVM allows the java program created using one operating system can be executed on any other
operating system.
Multi-threaded
 Java supports multi-threading programming.
 Which allows us to write programs that do multiple operations simultaneously.
Interpreted
 Java programs are compiled to generate byte code.
 This byte code can be downloaded and interpreted by the interpreter in JVM.
 If we take any other language, only an interpreter or a compiler is used to execute the program.
 But in java, we use both compiler and interpreter for the execution.
High performance
 The problem with interpreter inside the JVM is that it is slow.
 Because of Java programs used to run slow.
 To overcome this problem along with the interpreter.
 Java soft people have introduced JIT (Just in Time ) compiler, to enhance the speed of execution.
 So now in JVM, both interpreter and JIT compiler work together to run the program.
Distributed
 Information is distributed on various computers on a network.
 Using Java, we can write programs, which capture information and distribute it to the client.
 This is possible because Java can handle the protocols like TCP/IP and UDP.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running system
and it has a dynamic memory allocation and deallocation (objects and garbage collector).
OVERVIEW OF JAVA
 Java is a object oriented programming language.
 Java was created based on C and C++.
 Java uses C syntax and many of the object-oriented features are taken from C++.
 Before Java was invented there were other languages like COBOL, FORTRAN, C, C++, Small Talk, etc.
 These languages had few disadvantages which were corrected in Java.
 Java also innovated many new features to solve the fundamental problems which the previous
languages could not solve.
 Java was developed by James Gosling, Patrick Naughton, Chris warth, Ed Frank and Mike Sheridon
at Sun Microsystems in the year 1991.
 This language was initially called as “OAK” but was renamed as “Java” in 1995.
 The primary motivation behind developing java was the need for creating a platform independent
Language (Architecture Neutral), that can be used to create a software which can be embedded in
various electronic devices such as remote controls, micro ovens etc.
 The problem with C, C++ and most other languages is that, they are designed to compile on specific
targeted CPU (i.e. they are platform dependent), but java is platform Independent which can run on
a variety of CPU’s under different environments.
 The secondary factor that motivated the development of java is to develop the applications that can
run on Internet. Using java we can develop the applications which can run on internet i.e. Applet. So
java is a platform Independent Language used for developing programs which are platform
Independent and can run on internet.
STRUCTURE OF JAVA PROGRAM
Structure of a Java program contains the following elements:

Documentation Section
The documentation section is an important section but optional for a Java program.
It includes basic information about a Java program. The information includes the author's name,
date of creation, version, program name, company name, and description of the program. It
improves the readability of the program. Whatever we write in the documentation section, the Java
compiler ignores the statements during the execution of the program. To write the statements in the
documentation section, we use comments.
Comments there are three types
1. Single-line Comment: It starts with a pair of forwarding slash (//).

Example : //First Java Program

2. Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.

Example : /* It is an example of
multiline comment */
3. Documentation Comment: It starts with the delimiter (/**) and ends with */.
SAMPLE JAVA PROGRAM
/* This is First Java Program */
Class sample
{
public static void main(String args[])
{
System.out.println(“Hello Java Programming”);
}
}
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method.
The main method is executed by the JVM, so it doesn't require to create an object to invoke the main
method. So it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program execution
String[] args is used for command line argument.
System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class.
How to Compile and Run the Java Program
To Compile : javac Sample.java [ program name]
To Run : java Sample
Output : Hello Java Programming
EXECUTION PROCESS OF JAVA PROGRAM

WHAT IS JVM
Java Virtual Machine is the heart of entire java program execution process. It is responsible for taking
the .class file and converting each byte code instruction into the machine language instruction that can
be executed by the microprocessor.
DATA TYPES IN JAVA
Java programming language has a rich set of data types. The data type is a category of data stored in
variables. In java, data types are classified into two types and they are as follows.
 Primitive Data Types
 Non-primitive Data Types

Primitive Data Types


The primitive data types are built-in data types and they specify the type of value stored in a variable
and the memory size.
Integer Data Types
Integer Data Types represent integer numbers, i.e numbers without any fractional parts or decimal
points.
Minimum and Maximum
Data Type Memory Size Default Value
values

byte 1 byte -128 to +128 0

short 2 bytes -32768 to +32767 0

int 4 bytes -2147483648 to +2147483647 0

-9223372036854775808 to
long 8 bytes 0L
+9223372036854775807
Float Data Types
Float data types are represent numbers with decimal point.
Minimum and Maximum
Data Type Memory Size Default Value
values
-3.4e38 to -1.4e-45 and 1.4e-45
float 4 byte 0.0f
to 3.4e38
-1.8e308 to -4.9e-324 and 4.9e-
double 8 bytes 0.0d
324 to 1.8e308

Note: Float data type can represent up to 7 digits accurately after decimal point.
Double data type can represent up to 15 digits accurately after decimal point.
Character Data Type
Character data type are represents a single character like a, P, &, *,..etc.
Minimum and Maximum
Data Type Memory Size Default Value
values

char 2 bytes 0 to 65538 \u0000

Boolean Data Types


Boolean data types represent any of the two values, true or false. JVM uses 1 bit to represent a Boolean
value internally.
Minimum and Maximum
Data Type Memory Size Default Value
values

boolean 1 byte 0 or 1 0 ( false )


VARIABLES
Variable is a name given to a memory location where we can store different values of the same data
type during the program execution.
The following are the rules to specify a variable name...
 A variable name may contain letters, digits and underscore symbol
 Variable name should not start with digit.
 Keywords should not be used as variable names.
 Variable name should not contain any special symbols except underscore(_).
 Variable name can be of any length but compiler considers only the first 31 characters of the
variable name.
Declaration of Variable
Declaration of a variable tells to the compiler to allocate required amount of memory with specified
variable name and allows only specified datatype values into that memory location.
Syntax: datatype variablename;
Example : int a;
Syntax : data_type variable_name_1, variable_name_2,...;
Example : int a, b;
Initialization of a variable:
Syntax: datatype variablename = value;
Example : int a = 10;
Syntax : data_type variable_name_1=value, variable_name_2 = value;
Example : int a = 10, b = 20;
TYPES OF VARIABLES
There are three types of variables in Java:
 local variable
 instance variable
 static variable
Local Variables
 Variables declared inside the methods or constructors or blocks are called as local variables.
 The scope of local variables is within that particular method or constructor or block in which they
have been declared.
 Local variables are allocated memory when the method or constructor or block in which they are
declared is invoked and memory is released after that particular method or constructor or block is
executed.
 Stack memory is allocated for storing local variables.
 JVM takes no responsibility for assigning default value to the local variables. It is the responsibility
of the programmer to initialize the local variables explicitly before using them otherwise syntax
error is raised.
 Access modifiers cannot be assigned to local variables.
 It can’t be defined by a static keyword.
 Local variables can be accessed directly with their name.
Program
public class LocalVariables
{
public void show()
{
int a = 10;
System.out.println("Inside show method, a = " + a);
}
public void display()
{
int b = 20;
System.out.println("Inside display method, b = " + b);
//System.out.println("Inside display method, a = " + a); // error
}
public static void main(String args[])
{
LocalVariables obj = new LocalVariables();
obj.show();
obj.display();
}
}
Instance Variables:
 Variables declared outside the methods or constructors or blocks but inside the class are called
as instance variables.
 The scope of instance variables is inside the class and therefore all methods, constructors and
blocks can access them.
 Instance variables are allocated memory during object creation and memory is released during
object destruction. If no object is created, then no memory is allocated.
 For each object, a separate copy of instance variable is created.
 Heap memory is allocated for storing instance variables.
 Access modifiers can be assigned to instance variables.
 It is the responsibility of the JVM to assign default value to the instance variables as per the type of
 Variable.
 Instance variables can be called directly inside the instance area.
 Instance variables cannot be called directly inside the static area and necessarily requires an object
reference for calling them.
Program
class InstanceVariable
{
int x = 100;
public void show()
{
System.out.println("Inside show method, x = " + x);
x = x + 100;
}
public void display()
{
System.out.println("Inside display method, x = " + x);
}
public static void main(String args[])
{
ClassVariables obj = new ClassVariables();
obj.show();
obj.display();
}
}
Static variables
 Static variables are also known as class variable.
 Static variables are declared with the keyword ‘static ‘ .
 A static variable is a variable whose single copy in memory is shared by all the objects,any
modification to it will also effect other objects.
 Static keyword in java is used for memory management, i.e it saves memory.
 Static variables gets memory only once in the class area at the time of class loading.
 Static variables can be invoked without the need for creating an instance of a class.
 Static variables contain values by default. For integers, the default value is 0. For Booleans, it is
false. And for object references, it is null.
Syntax: static datatype variable name;
Example: static int x=100;
Syntax: classname.variablename;
Example1 : Without Static Variable

class Employee
{
int empid=500;
void emp1()
{
empid++;
System.out.println("Employee id:"+empid);
}
}
class Sample
{
public static void main(String args[])
{
Employee e1=new Employee();
e1.emp1();
e1.emp1();
e1.emp1();
Employee e2=new Employee();
e2.emp1();
e2.emp1();
e2.emp1();
}
}
Output:
Employee id:501
Employee id:502
Employee id:503
Employee id:501
Employee id:502
Employee id:503
Example2 With Static variable
class Employee
{
static int empid=500;
static void emp1()
{
empid++;
System.out.println("Employee id:"+empid);
}
}
class Sample
{
public static void main(String args[])
{
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();

}
}
Output:
Employee id:501
Employee id:502
Employee id:503
Employee id:504
Employee id:505
Employee id:506
ARRAYS
 An array is a collection of similar data values with a single name.
 An array can also be defined as, a special type of variable that holds multiple values of the same
data type at a time.
 In java, arrays are objects and they are created dynamically using new operator.
 Every array in java is organized using index values.
 The index value of an array starts with '0' and ends with 'zise-1'.
 We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
 One Dimensional Array

 Multi Dimensional Array

One Dimensional Array


In the java programming language, an array must be created using new operator and with a specific
size. The size must be an integer value but not a byte, short, or long. We use the following syntax to
create an array.
Syntax
data_type array_name[ ] = new data_type[size];
(or)
data_type[ ] array_name = new data_type[size];
Example
class Onedarray
{
public static void main(String args[])
{
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<5;i++)
System.out.println(a[i]);
}
}
 In java, an array can also be initialized at the time of its declaration.
 When an array is initialized at the time of its declaration, it need not specify the size of the array
and use of the new operator.
 Here, the size is automatically decided based on the number of values that are initialized.
Example
int list[ ] = {10, 20, 30, 40, 50};
Multidimensional Array
 In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
 In Java, multidimensional arrays are arrays of arrays.
 To create a multidimensional array variable, specify each additional index using another set of
square brackets.
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
 When an array is initialized at the time of declaration, it need not specify the size of the array and
use of the new operator.
 Here, the size is automatically decided based on the number of values that are initialized.
Example
class Twodarray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
OPERATORS
An operator is a symbol that performs an operation. An operator acts on some variables called
operands to get the desired result.
Example: a+b
Here a, b are operands and + is operator.
Types of Operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
7. Bit wise operators
1. Arithmetic Operators: Arithmetic Operators are used for mathematical calculations.

Operator Description

+ Addition
- Subtraction
* Multiplication
/ Division
% Modular

Program: Java Program to implement Arithmetic Operators


class ArithmeticOperators
{
public static void main(String[] args)
{
int a = 12, b = 5;
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("a % b = " + (a % b));
}
}
2. Relational Operators: Relational operators are used to compare two values and return a true or
false result based upon that comparison. Relational operators are of 6 types

Operator Description

> Greater than


>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to

Program: Java Program to implement Relational Operators


class RelationalOperator
{
public static void main(String[] args)
{
int a = 10;
int b = 3;
int c = 5;
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("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}
3. Logical Operator: The Logical operators are used to combine two or more conditions .Logical
operators are of three types
1. Logical AND (&&),
2. Logical OR (||)
3. Logician NOT (!)
1. Logical AND (&&) : Logical AND is denoted by double ampersand characters (&&).it is used to
check the combinations of more than one conditions. if any one condition false the complete condition
becomes false.
Truth table of Logical AND
Condition1 Condition2 Condition1 && Condition2
True True True
True False False
False True False
False False False

2. Logical OR ( || ) : Logical OR is denoted by double pipe characters (||). it is used to check the
combinations of more than one conditions. if any one condition true the complete condition becomes
true.
Truth table of Logical OR
Condition1 Condition2 Condition1 && Condition2
True True True
True False True
False True True
False False False
3. Logician NOT (!): Logical NOT is denoted by exclamatory characters (!), it is used to check the
opposite result of any given test condition. i.e, it makes a true condition false and false condition true.
Truth table of Logical NOT
Condition1 !Condition2
True False
False True

Example of Logical Operators


class LogicalOp
{
public static void main(String[] args)
{
int x=10;
System.out.println(x==10 && x>=5));
System.out.println(x==10 || x>=5));
System.out.println ( ! ( x==10 ));
}
}
4. Assignment Operator: Assignment operators are used to assign a value (or) an expression (or) a
value of a variable to another variable.
Syntax : variable name=expression (or) value
Example : x=10;
y=20;
The following list of Assignment operators are.

Operator Description Example Meaning

+= Addition Assignment x+=y x= x + y

-= Addition Assignment x-=y x= x - y

*= Addition Assignment x*=y x= x * y

/= Addition Assignment x/=y x= x / y

%= Addition Assignment x%=y x= x % y

Example of Assignment Operators


class AssignmentOperator
{
public static void main(String[] args)
{
int a = 4;
int var;
var = a;
System.out.println("var using =: " + var);
var += a;
System.out.println("var using +=: " + var);
var *= a;
System.out.println("var using *=: " + var);
}
}
5: Increment And Decrement Operators : The increment and decrement operators are very
useful. ++ and == are called increment and decrement operators used to add or subtract. Both are
unary operators.
The syntax of the operators is given below.
These operators in two forms : prefix (++x) and postfix(x++).
++<variable name> --<variable name>
<variable name>++ <variable name>--
Operator Meaning

++x Pre Increment


--x Pre Decrement
x++ Post Increment
x-- Post Decrement
Where
1 : ++x : Pre increment, first increment and then do the operation.
2 : - -x : Pre decrement, first decrements and then do the operation.
3 : x++ : Post increment, first do the operation and then increment.
4 : x- - : Post decrement, first do the operation and then decrement.
Example
class Increment
{
public static void main(String[] args)
{
int var=5;
System.out.println (var++);
System.out.println (++var);
System.out.println (var--);
System.out.println (--var);
}
}
6 : Conditional Operator: A conditional operator checks the condition and executes the statement
depending on the condition. Conditional operator consists of two symbols.
1 : question mark (?).
2 : colon ( : ).
Syntax: condition ? exp1 : exp2;
It first evaluate the condition, if it is true (non-zero) then the “exp1” is evaluated, if the condition is
false (zero) then the “exp2” is evaluated.
Example :
class ConditionalOperator
{
public static void main(String[] args)
{
int februaryDays = 29;
String result;
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
7. Bitwise Operators:
 Bitwise operators are used for manipulating a data at the bit level, also called as bit level
programming. Bit-level programming mainly consists of 0 and 1.
 They are used in numerical Computations to make the calculation process faster.
 The bitwise logical operators work on the data bit by bit.
 Starting from the least significant bit, i.e. LSB bit which is the rightmost bit, working towards the
MSB (Most Significant Bit) which is the leftmost bit.
A list of Bitwise operators as follows…

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
<< Left Shift
>> Right Shift
1. Bitwise AND (&):
 Bitwise AND operator is represented by a single ampersand sign (&).
 Two integer expressions are written on each side of the (&) operator.
 if any one condition false ( 0 ) the complete condition becomes false ( 0 ).

Truth table of Bitwise AND

Condition1 Condition2 Condition1 & Condition2

0 0 0
0 1 0
1 0 0
1 1 1

Example : int x = 10;


int y = 20;
x&y=?
x = 0000 1010
y = 0000 1011
x & y = 0000 1010 = 10
2. Bitwise OR:
 Bitwise OR operator is represented by a single vertical bar sign (|).
 Two integer expressions are written on each side of the (|) operator.
 if any one condition true ( 1 ) the complete condition becomes true ( 1 ).
Truth table of Bitwise OR
Condition1 Condition2 Condition1 | Condition2

0 0 0
0 1 1
1 0 1
1 1 1
Example : int x = 10;
int y = 20;
x|y=?
x = 0000 1010
y = 0000 1011
x | y = 0000 1011 = 11
3. Bitwise Exclusive OR :
 The XOR operator is denoted by a carrot (^) symbol.
 It takes two values and returns true if they are different; otherwise returns false.
 In binary, the true is represented by 1 and false is represented by 0.
Truth table of Bitwise XOR
Condition1 Condition2 Condition1 ^ Condition2
0 0 0
0 1 1
1 0 1
1 1 0

Example : int x = 10;


int y = 20;
x^y=?
x = 0000 1010
y = 0000 1011
x ^ y = 0000 0001 = 1
4. Bitwise Complement (~):
 The bitwise complement operator is a unary operator.
 It is denoted by ~, which is pronounced as tilde.
 It changes binary digits 1 to 0 and 0 to 1.
 bitwise complement of any integer N is equal to - (N + 1).
 Consider an integer 35. As per the rule, the bitwise complement of 35 should be -(35 + 1) = -36.
Example : int x = 10; find the ~x value.
x = 0000 1010
~x= 1111 0101
5. Bitwise Left Shift Operator ( << ) :
 This Bitwise Left shift operator (<<) is a binary operator.
 It shifts the bits of a number towards left a specified no.of times.
Example:
int x = 10;
x << 2 = ?

6. Bitwise Right Shift Operator ( >> ) :


 This Bitwise Right shift operator (>>) is a binary operator.
 It shifts the bits of a number towards right a specified no.of times.
Example:
int x = 10;
x >> 2 = ?
EXPRESSIONS
 In any programming language, if we want to perform any calculation or to frame any condition
etc., we use a set of symbols to perform the task. These set of symbols makes an expression.
In the java programming language, an expression is defined as follows..
 An expression is a collection of operators and operands that represents a specific value.
 In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.
 Infix Expression
 Postfix Expression
 Prefix Expression
The above classification is based on the operator position in the expression.
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
a+b
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.

Example

ab+
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
+ab
CONTROL STATEMENTS
 In java, the default execution flow of a program is a sequential order.
 But the sequential order of execution flow may not be suitable for all situations.
 Sometimes, we may want to jump from line to another line, we may want to skip a part of the
program, or sometimes we may want to execute a part of the program again and again.
 To solve this problem, java provides control statements.
Types of Control Statements

1. Selection Control Statements


In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed based on a
condition.
Java provides the following selection statements.
 if statement
 if-else statement
 if-elif statement
 nested if statement
 switch statement
if statement in java
 In java, we use the if statement to test a condition and decide the execution of a block of statements
based on that condition result.
 The if statement checks, the given condition then decides the execution of a block of statements. If
the condition is True, then the block of statements is executed and if it is False, then the block of
statements is ignored.
Syntax
if(condtion)
{
if-block of statements;
}
statement after if-block;
Example
public class IfStatementTest
{
public static void main(String[] args)
{
int x=10;
if(x>0)
x++;
System.out.println("x value is:"+x);
}
}
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the
condition is evaluated to False. Then the if statement ignores the execution of its block of statements.
if-else statement in java
 In java, we use the if-else statement to test a condition and pick the execution of a block of
statements out of two blocks based on that condition result.
 The if-else statement checks the given condition then decides which block of statements to be
executed based on the condition result.
 If the condition is True, then the true block of statements is executed and if it is False, then the false
block of statements is executed.
Syntax
if(condtion)
{
true-block of statements;
}
else
{
false-block of statements;
}
statement after if-block;
Example
public class IfElseStatementTest
{
public static void main(String[] args)
{
int a=29;
if(a % 2==0)
System.out.println("Even Number is :"+a);
else
System.out.println("Odd Number is :"+a);
}
}
Nested if statement in java
Writing an if statement inside another if-statement is called nested if statement.
Syntax
if(condition_1)
{
if(condition_2)
{
inner if-block of statements;
...
}
...
}
Example
public class NestedIfStatementTest
{
public static void main(String[] args)
{
int num=1;
if(num<10)
{
if(num==1)
{
System.out.print("The value is equal to 1);
}
else
{
System.out.print("The value is greater than 1");
}
}
else
{
System.out.print("The value is greater than 10");
}
System.out.print("Nested if - else statement ");
}
}
if-else if statement in java
Writing an if-statement inside else of an if statement is called if-else-if statement.
Syntax
if(condition_1)
{
condition_1 true-block;
...
}
else if(condition_2)
{
condition_2 true-block;
condition_1 false-block too;
...
}
Example
public class IfElseIfStatementTest
{
public static void main(String[] args)
{
int x = 30;
if( x == 10 )
{
System.out.print("Value of X is 10");
}
else if( x == 20 )
{
System.out.print("Value of X is 20");
}
else if( x == 30 )
{
System.out.print("Value of X is 30");
}
else
{
System.out.print("This is else statement");
}
}
}
Switch
 Using the switch statement, one can select only one option from more number of options very
easily.
 In the switch statement, we provide a value that is to be compared with a value associated with
each option. Whenever the given value matches the value associated with an option, the execution
starts from that option.
 In the switch statement, every option is defined as a case.
Syntax:
switch (expression)
{
case value1: // statement sequence
break;
case value2: // statement sequence
break;
….
case valueN:
}
Example
class SampleSwitch
{
public static void main(String args[])
{
char color ='g';
switch(color )
{
case 'r':
System.out.println("RED") ; break ;
case 'g':
System.out.println("GREEN") ; break ;
case 'b':
System.out.println("BLUE") ; break ;
case 'w':
System.out.println("WHITE") ; break ;
default:
System.out.println("No color") ;
}
}
}
2.Iteration Statements
 The java programming language provides a set of iterative statements that are used to execute a

statement or a block of statements repeatedly as long as the given condition is true.


 The iterative statements are also known as looping statements or repetitive statements. Java

provides the following iterative statements.


1. while statement
2. do-while statement
3. for statement
4. for-each statement
while statement in java
The while statement is used to execute a single statement or block of statements repeatedly as long as
the given condition is TRUE. The while statement is also known as Entry control looping statement.
Syntax
while(condition)
{
// body of loop
}
Example
public class WhileTest
{
public static void main(String[] args)
{
int num = 1;
while(num <= 10)
{
System.out.println(num);
num++;
}
System.out.println("Statement after while!");
}
}
do-while statement in java
 The do-while statement is used to execute a single statement or block of statements repeatedly
as long as given the condition is TRUE.
 The do-while statement is also known as the Exit control looping statement.
Syntax
do
{
// body of loop
} while (condition);
Example
public class DoWhileTest
{
public static void main(String[] args)
{
int num = 1;
do
{
System.out.println(num);
num++;
}while(num <= 10);
System.out.println("Statement after do-while!");
}
}
for statement in java
The for statement is used to execute a single statement or a block of statements repeatedly as long as
the given condition is TRUE.
Syntax
for(initialization; condition; inc/dec)
{
// body
}

If only one statement is being repeated, there is no need for the curly braces.
In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement. After the block of statements execution,
the modification statement gets executed, followed by condition again.
Example
public class ForTest
{
public static void main(String[] args)
{
for(int i = 0; i < 10; i++)
{
System.out.println("i = " + i);
}
System.out.println("Statement after for!");
}
}
3. Jump Statements
The java programming language supports jump statements that used to transfer execution control
from one line to another line.
The java programming language provides the following jump statements.
1. break statement
2. continue statement
break
When a break statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop.
Example
class BreakStatement
{
public static void main(String args[] )
{
int i;
i=1;
while(true)
{
if(i >10)
break;
System.out.print(i+" ");
i++;
}
}
}
Continue
This command skips the whole body of the loop and executes the loop with the next iteration. On
finding continue command, control leaves the rest of the statements in the loop and goes back to the
top of the loop to execute it with the next iteration (value).
Example
/* Print Number from 1 to 10 Except 5 */
class NumberExcept
{
public static void main(String args[] )
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
continue;
System.out.print(i +" ");
}
}
}
INTRODUCING CLASSES AND METHODS
 classes usually consist of two things: instance variables and methods.

 Java is an object-oriented programming language, so everything in java program must be based on

the object concept.


 In a java programming language, the class concept defines the skeleton of an object.

 The java class is a template of an object.

 The class defines the blueprint of an object.

 Every class in java forms a new data type.

 Once a class got created, we can generate as many objects as we want.

 Every class defines the properties and behaviors of an object.

 All the objects of a class have the same properties and behaviors that were defined in the class.

Every class of java programming language has the following characteristics.


 Identity - It is the name given to the class.
 State - Represents data values that are associated with an object.
 Behavior - Represents actions can be performed by an object.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as variables and
behaviors as methods.
Syntax
Class ClassName
{
Variables/Data members declaration;
Methods defination;
}
 The ClassName must begin with an alphabet, and the Upper-case letter is preferred.

 The ClassName must follow all naming rules.

Example
Here is a class called Box that defines three instance variables: width, height, and depth.
class Box
{
double width;
double height;
double depth;
void volume()
{
………………….
}
}
Creating an Object
 In java, an object is an instance of a class. When an object of a class is created, the class is said to be

instantiated.
 All the objects that are created using a single class have the same properties and methods.

 But the value of properties is different for every object.

Syntax
ClassName objectName = new ClassName( );
 The objectName must begin with an alphabet, and a Lower-case letter is preferred.

 The objectName must follow all naming rules.

Example
To actually create a Box object, you will use a statement like the following:
Box mybox = new Box();
The new operator dynamically allocates memory for an object.
Example
class Box
{
double width;
double height;
double depth;
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
METHODS
 A method is a block of statements under a name that gets executes only when it is called.

 Every method is used to perform a specific task. The major advantage of methods is code re-

usability (define the code once, and use it many times).


 In a java programming language, a method defined as a behavior of an object. That means, every

method in java must belong to a class.


 Every method in java must be declared inside a class.

Every method declaration has the following characteristics.


 returnType - Specifies the data type of a return value.
 name - Specifies a unique name to identify it.
 parameters - The data values it may accept or recieve.
 { } - Defienes the block belongs to the method.
Creating a method
A method is created inside the class
Syntax
class ClassName
{
returnType methodName( parameters )
{
// body of method
}
}
Calling a method
 In java, a method call precedes with the object name of the class to which it belongs and a dot
operator.
 It may call directly if the method defined with the static modifier.
 Every method call must be made, as to the method name with parentheses (), and it must
terminate with a semicolon.
Syntax
objectName.methodName(actualArguments );
Example
//Adding a Method to the Box Class
Class Box
{
double width, height, depth;
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume();
mybox2.volume();
}
}
STRING HANDLING
 A string is a sequence of characters surrounded by double quotations. In a java programming
language, a string is the object of a built-in class String.
 The string created using the String class can be extended. It allows us to add more characters after
its definition, and also it can be modified.
Example
String siteName = "javaprogramming";
siteName = "javaprogramminglanguage";
String handling methods
In java programming language, the String class contains various methods that can be used to handle
string data values.
The following table depicts all built-in methods of String class in java.
S.No Method Description
1 charAt(int) Finds the character at given index
2 length() Finds the length of given string
3 compareTo(String) Compares two strings
4 compareToIgnoreCase(String) Compares two strings, ignoring case
5 concat(String) Concatenates the object string with argument string.
6 contains(String) Checks whether a string contains sub-string
7 contentEquals(String) Checks whether two strings are same
8 equals(String) Checks whether two strings are same
9 equalsIgnoreCase(String) Checks whether two strings are same, ignoring case
10 startsWith(String) Checks whether a string starts with the specified string
11 isEmpty() Checks whether a string is empty or not
12 replace(String, String) Replaces the first string with second string
Replaces the first string with second string at all
replaceAll(String, String)
13 occurrences.
Extracts a sub-string from specified start and end index
substring(int, int)
14 values
15 toLowerCase() Converts a string to lower case letters
16 toUpperCase() Converts a string to upper case letters
17 trim() Removes whitespace from both ends
18 toString(int) Converts the value to a String object
Example
public class JavaStringExample
{
public static void main(String[] args)
{
String title = "Java Programming";
String siteName = "String Handling Methods";
System.out.println("Length of title: " + title.length());
System.out.println("Char at index 3: " + title.charAt(3));
System.out.println("Index of 'T': " + title.indexOf('T'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9, 14));
System.out.println("Upper case: " + siteName.toUpperCase());
}
}
INHERITANCE IN JAVA
 Inheritance is an important pillar of OOP(Object-Oriented Programming).
 The process of obtaining the data members and methods from one class to another class is known
as inheritance.
Important Terminologies Used in Java Inheritance
Class: Class is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. Class is not a real-world entity. It is just a template or blueprint or prototype
from which objects are created.
Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a
base class or a parent class).
Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived
class, extended class, or child class). The subclass can add its own fields and methods in addition to
the superclass fields and methods.
Why Do We Need Java Inheritance?
Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.
Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the
ways by which Java achieves Run Time Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all details is achieved
through inheritance. Abstraction only shows the functionality to the user.
How to Use Inheritance in Java?
 The extends keyword is used for inheritance in Java.
 Using the extends keyword indicates you are derived from an existing class. In other words,
“extends” refers to increased functionality.
Syntax
class SubclassName extends SuperclassName
{
//methods and fields
}
Tpyes of Inheritance
Based on number of ways inheriting the feature of base class into derived class we have five types of
inheritance they are:
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance
1.Single inheritance
In single inheritance there exists single base class and single derived class.

Example
class Animal
{
String name;
void show()
{
System.out.println(“Animal name is:"+name);
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Barking");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.name="DOG";
d.show();
d.bark();
}
}
2. Multilevel inheritances in Java
 When there is a chain of inheritance, it is known as multilevel inheritance.
 In Multilevel inheritances there exists single base class, single derived class and multiple
intermediate base classes.

Example
In the example, BabyDog class inherits the Dog class which again inherits the Animal class, so there is
a multilevel inheritance.
class Animal
{
String name;
void show()
{
System.out.println("Animal Name is"+name);
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Mother Dog Barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("Baby Dog weeping");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.name="MotherDog";
d.show();
d.bark();
d.weep();

}
}
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.
In the below image, class A serves as a base class for the derived class B, C and D.

Example
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{
System.out.println("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
4. Multiple inheritance

In multiple inheritance there exist multiple classes and singel derived class.

The concept of multiple inheritance is not supported in java through concept of classes but it can be
supported through the concept of interface.

5. Hybrid inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple
inheritances with classes, hybrid inheritance is also not possible with classes. In Java, we can achieve
hybrid inheritance only through Interfaces.
ACCESS CONTROL(MEMBER ACCESS)
In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier used
with the element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
 When no access modifier is specified for a class, method, or data member – It is said to be having
the default access modifier by default.
 The default modifier is accessible only within package.
 It cannot be accessed from outside the package.
 It provides more accessibility than private. But, it is more restrictive than protected, and public.
Example
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
2. private
 The private access modifier is accessible only within the class.
 The private access modifier is specified using the keyword private.
 The methods or data members declared as private are accessible only within the class in which
they are declared.
 Any other class of the same package will not be able to access these members.
 Top-level classes or interfaces can not be declared as private because private means “only visible
within the enclosing class”.
Example
 In this example, we have created two classes A and Simple.
 A class contains private data member and private method.
 We are accessing these private members from outside the class, so there is a compile-time error.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}

public class Simple


{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
3. protected
 The protected access modifier is accessible within package and outside the package but through
inheritance only.
 The protected access modifier is specified using the keyword protected.
Example
 In this example, we have created the two packages pack and mypack.
 The A class of pack package is public, so can be accessed from outside the package.
 But msg method of this package is declared as protected, so it can be accessed from outside the
class only through inheritance.
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
4. public
 The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
 The public access modifier is specified using the keyword public.
Example
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Table: class member access
Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private YES NO NO NO

Default YES YES NO NO

Protected YES YES YES NO

Public YES YES YES YES


CONSTRUCTORS
 Constructor in Java is a special member method which will be called automatically by the JVM
whenever an object is created for placing user defined values in place of default values.
 In a single word constructor is a special member method which will be called automatically
whenever object is created.
 The purpose of constructor is to initialize an object called object initialization. Initialization is a
process of assigning user defined values at the time of allocation of memory space.
Syntax
ClassName()
{
.......
.......
}
Types of constructors
Based on creating objects in Java constructor are classified in two types. They are
1. Default or no argument Constructor
2. Parameterized constructor
1. Default Constructor
 A constructor is said to be default constructor if and only if it never take any parameters.
 If any class does not contain at least one user defined constructor then the system will create a
default constructor at the time of compilation it is known as system defined default constructor.
Note: System defined default constructor is created by java compiler and does not have any statement
in the body part. This constructor will be executed every time whenever an object is created if that
class does not contain any user defined constructor.
Example
class Test
{
int a, b;
Test()
{
a=10;
b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
}
class TestDemo
{
public static void main(String args[])
{
Test t1=new Test();
}
}
2. Parameterized constructor
If any constructor contain list of variables in its signature is known as paremetrized constructor. A
parameterized constructor is one which takes some parameters.
Example
class Test
{
int a, b;
Test(int n1, int n2)
{
a=n1;
b=n2;
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
}
class TestDemo
{
public static void main(String args[])
{
Test t1=new Test(10, 20);
}
}
Difference between Method and Constructor

S.NSS Method Method Constructor Constructor

Method can be any user


1 Constructor must be class name
defined name

Method should have return


2 It should not have any return type (even void)
type

Method should be called


It will be called automatically whenever object
3 explicitly either with object
is created
reference or class reference

Method is not provided by The java compiler provides a default


4
compiler in any case. constructor if we do not have any constructor.
‘this’ KEYWORD IN JAVA
this is a reference variable that refers to the current object. It is a keyword in java language
represents current class object
Why use this keyword in java ?
 The main purpose of using this keyword is to differentiate the formal parameter and data members
of class, whenever the formal parameter and data members of the class are similar then JVM get
ambiguity (no clarity between formal parameter and member of the class).
 To differentiate between formal parameter and data member of the class, the data member of the
class must be preceded by "this".
Syntax: this.data member of current class.

Example without using this keyword


class Employee
{
int id;
String name;
Employee(int id,String name)
{
id = id;
name = name;
}
void show()
{
System.out.println(id+" "+name);
}
}
class ThisDemo1
{
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry");
e1.show();
}
}
Output: 0 null
In the above example, parameters (formal arguments) and instance variables are same. So, we are
using this keyword to distinguish local variable and instance variable.
Example of this keyword in java
class Employee
{
int id;
String name;
Employee(int id,String name)
{
this.id = id;
this.name = name;
}
void show()
{
System.out.println(id+" "+name);
}

class ThisDemo2
{
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry");
e1.show();
}
}

Output: 111 Harry


SUPER KEYWORD
Super keyword in java is a reference variable that is used to refer parent class features.
Usage of Java super Keyword
1. Super keyword At Variable Level

2. Super keyword At Method Level


3. Super keyword At Constructor Level
 Whenever the derived class is inherits the base class features, there is a possibility that base class
features are similar to derived class features and JVM gets an ambiguity.
 In order to differentiate between base class features and derived class features must be preceded
by super keyword.
Syntax
super.baseclass features
1. Super Keyword at Variable Level
 Whenever the derived class inherit base class data members there is a possibility that base class
data member are similar to derived class data member and JVM gets an ambiguity.
 In order to differentiate between the data member of base class and derived class, in the context
of derived class the base class data members must be preceded by super keyword.
Syntax
super.baseclass datamember name
Example
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}
2. Super Keyword at Method Level
 The super keyword can also be used to invoke or call parent class method.
 It should be use in case of method overriding. In other word super keyword use when base class
method name and derived class method name have same name.
Example
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}
3. Super keyword At Constructor Level
The super keyword can also be used to invoke the parent class constructor.
class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}
FINAL KEWWORD
 It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance.
 Final keyword is used to make a variable as a constant.
 This is similar to const in other language.
In java language final keyword can be used in following ways:
1. Final Keyword at Variable Level
2. Final Keyword at Method Level
3. Final Keyword at Class Level
1.Final at variable level
 A variable declared with the final keyword cannot be modified by the program after initialization.
 This is useful to universal constants, such as "PI".
Example
class Bike
{
final int speedlimit=90;
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}
Output: Compile Time Error
2.Final Keyword at method level
 It makes a method final, meaning that sub classes can not override this method. The compiler
checks and gives an error if you try to override the method.
 When we want to restrict overriding, then make a method as a final.
Example
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output: It gives an error
3.Final Keyword at Class Level
It makes a class final, meaning that the class can not be inheriting by other classes. When we want
to restrict inheritance then make class as a final.
Example
final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
}
}
Output: Compile Time Error
POLYMORPHISM
 The polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviors.
Types of Java polymorphism
The Java polymorphism is mainly divided into two types:
1. Compile-time Polymorphism(Method Overloading)
2. Runtime Polymorphism(Method Overriding)
Ad Hoc Polymorphism(Method Overloading)
Whenever same method name is exiting multiple times in the same class with different number of
parameter or different order of parameters or different types of parameters is known as method
overloading.
Example
class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
void sum(float a, float b)
{
System.out.println(a+b);
}
}
class Methodload
{
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
obj.sum(10.05f, 15.20f);
}
}
PURE POLYMORPHISM(METHOD OVERRIDING)
 Whenever same method name is existing in both base class and derived class with same types of
parameters or same order of parameters is known as method Overriding.
 In a java programming language, pure polymorphism carried out with a method overriding
concept.
Note: Without Inheritance method overriding is not possible.
Example
class Walking
{
void walk()
{
System.out.println("Man walking fastly");
}
}
class Man extends walking
{
void walk()
{
System.out.println("Man walking slowly");
}
}
class OverridingDemo
{
public static void main(String args[])
{
Walking obj = new Walking();
obj.walk();
}
}
Note:
 Whenever we are calling overridden method using derived class object reference the highest
priority is given to current class (derived class). We can see in the above example high priority is
derived class.
 super. (super dot) can be used to call base class overridden method in the derived class.
ABSTRACT CLASS
 A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).
 An abstract class must be declared with an abstract keyword.
 It cannot be instantiated.It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the method.
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.There are two ways to achieve abstraction in java.
1. Abstract class (0 to 100%)
2. Interface (100%)
Syntax
abstract class className
{
......
}
ABSTRACT METHOD
 An abstract method contains only declaration or prototype but it never contains body or definition.
 In order to make any undefined method as abstract whose declaration is must be predefined by
abstract keyword.
Syntax
abstract returntype methodName(List of formal parameter);
Example
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
class TestAbstraction1
{
static void main(String args[])
{
Shape s=new Circle1();
s.draw();
}
}

Example2
import java.util.*;
abstract class Shape
{
int length, breadth, radius;
Scanner input = new Scanner(System.in);
abstract void printArea();
}
class Rectangle extends Shape
{
void printArea()
{
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}
class Triangle extends Shape
{
void printArea()
{
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
}
}
class Cricle extends Shape
{
void printArea()
{
System.out.println("\n*** Finding the Area of Cricle ***");
System.out.print("Enter Radius: ");
radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius * radius);
}
}
public class AbstractClassExample
{
public static void main(String[] args)
{
Rectangle rec = new Rectangle();
rec.printArea();
Triangle tri = new Triangle();
tri.printArea();
Cricle cri = new Cricle();
cri.printArea();
}
}
OBJECT CLASS
 In java, the Object class is the super most class of any class hierarchy. The Object class in the java
programming language is present inside the java.lang package.
 Every class in the java programming language is a subclass of Object class by default.
 The Object class is useful when you want to refer to any object whose type you don't know. Because
it is the superclass of all other classes in java, it can refer to any type of object.

Return
Method Description
Value

getClass() Returns Class class object object

hashCode() returns the hashcode number for object being used. int

equals(Object obj) compares the argument object to calling object. boolean

clone() Compares two strings, ignoring case int

concat(String) Creates copy of invoking object object

toString() eturns the string representation of invoking object. String

notify() wakes up a thread, waiting on invoking object's monitor. void

notifyAll() wakes up all the threads, waiting on invoking object's monitor. void

wait() causes the current thread to wait, until another thread notifies. void

wait(long,int) causes the current thread to wait for the specified milliseconds and void
nanoseconds, until another thread notifies.

finalize() It is invoked by the garbage collector before an object is being void


garbage collected.
FORMS OF INHERITANCE
 The inheritance concept used for the number of purposes in the java programming language. One
of the main purposes is substitutability.
 The substitutability means that when a child class acquires properties from its parent class, the
object of the parent class may be substituted with the child class object.
 For example, if B is a child class of A, anywhere we expect an instance of A we can use an instance
of B.
 The substitutability can achieve using inheritance, whether using extends or implements
keywords.
The following are the differnt forms of inheritance in java.
 Specialization
 Specification
 Construction
 Eextension
 Limitation
 Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It holds the
principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent class just
specifies which methods should be available to the child class but doesn't implement them. The java
provides concepts like abstract and interfaces to support this form of inheritance. It holds the principle
of substitutability.
Construction
This is another form of inheritance where the child class may change the behavior defined by the
parent class (overriding). It does not hold the principle of substitutability.
Eextension
This is another form of inheritance where the child class may add its new properties. It holds the
principle of substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It does not hold
the principle of substitutability.
Combination
This is another form of inheritance where the subclass inherits properties from multiple parent
classes. Java does not support multiple inheritance type.
BENEFITS OF INHERITANCE
 Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.
 Inheritance can save time and effort as the main code need not be written again.
 Inheritance provides a clear model structure which is easy to understand.
 An inheritance leads to less development and maintenance costs.
 With inheritance, we will be able to override the methods of the base class so that the meaningful
implementation of the base class method can be designed in the derived class. An inheritance leads
to less development and maintenance costs.
 In inheritance base class can decide to keep some data private so that it cannot be altered by the
derived class.
THE COSTS OF INHERITANCE
 Inheritance decreases the execution speed due to the increased time and effort it takes, the
program to jump through all the levels of overloaded classes.
 Inheritance makes the two classes (base and inherited class) get tightly coupled. This means one
cannot be used independently of each other.
 The changes made in the parent class will affect the behavior of child class too.
 The overuse of inheritance makes the program more complex.

You might also like