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

Final Unit-1 Notes

Uploaded by

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

Final Unit-1 Notes

Uploaded by

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

CMRCET JAVA UNIT-1 NOTES

UNIT - I

Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop
concepts, coping with complexity,

abstraction mechanisms. A way of viewing world – Agents, responsibility, messages,


methods, History of Java, Java

buzzwords, data types, variables, scope and lifetime of variables, arrays, operators,
expressions, control statements,

type conversion and casting, simple java program, concepts of classes, objects,
constructors, methods, access control,

this keyword, garbage collection, overloading methods and constructors, method


binding, inheritance, overriding and

exceptions, parameter passing, recursion, nested and inner classes, exploring string
class.

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.

Let us consider a situation, I am at my office and I wish to get food to my family members
who are at my home from a hotel. Because of the distance from my office to home, there is
no possibility of getting food from a hotel myself. So, how do we solve the issue?

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Agents and Communities

To solve my food delivery problem, I used a solution by finding an appropriate agent


(Zomato) and pass a message containing my request. It is the responsibility of the agent
(Zomato) to satisfy my request. Here, the agent uses some method to do this. I do not need to
know the method that the agent has used to solve my request. This is usually hidden from me.

So, in object-oriented programming, problem-solving is the solution to our problem which


requires the help of many individuals in the community. We may describe agents and
communities as follows.

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.

In our example, the online food delivery system is a community in which the agents are
zomato and set of hotels. Each hotel provides a variety of services that can be used by other
members like zomato, myself, and my family in the community

Messages and Methods

To solve my problem, I started with a request to the agent zomato, which led to still more
requestes among the members of the community until my request has done. Here, the
members of a community interact with one another by making requests until the problem has
satisfied.

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.

Responsibilities

In object-oriented programming, behaviors of an object described in terms of responsibilities.

In our example, my request for action indicates only the desired outcome (food delivered to
my family). The agent (zomato) free to use any technique that solves my problem. By
discussing a problem in terms of responsibilities increases the level of abstraction. This
enables more independence between the objects in solving complex problems.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Classes and 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.

In our example, the zomato a class and all the hotels are sub-classes of it. For every request
(message), the class creates an instance of it and uses a suitable method to solve the problem.

Classes Hierarchies

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.

Method Binding, Overriding, and Exception

In the class hierarchy, both parent and child classes may have the same method which
implemented individually. Here, the implementation of the parent is overridden by the child.
Or a class may provide multiple definitions to a single method to work with different
arguments (overloading).

OOP Concepts in Java

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.

 Encapsulation

 Inheritance

 Polymorphism

 Abstraction

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

The popular object-oriented programming languages are Smalltalk, C++, Java, PHP, C#,
Python, etc.

Encapsulation

Encapsulation is the process of combining data and code into a single unit (object / class). 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. The parent class is also known as base
class or supre class. The child class is also known as derived class or sub class.

In the inheritance, the properties and behaviors of base class extended to its derived class, but
the base class never receive properties or behaviors from its derived class.

In java programming language the keyword extends is used to implement inheritance.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Java Buzz Words:

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 java team has listed the
following terms as java 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.

Java Programs run inside a virtual machine sandbox

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Portable

Portability is one of the core features of java which enables the java programs to run on any
computer or operating system. For example, an applet developed using java runs on a wide
variety of CPUs, operating systems, and browsers connected to the Internet.

Object-oriented

Java is said to be a pure object-oriented programming language. In java, everything is an


object. It supports all the features of the object-oriented programming paradigm. The
primitive data types java also implemented as objects using wrapper classes, but still, it
allows primitive data types to archive high-performance.

Robust

Java is more robust because the java code can be executed on a variety of environments, java
has a strong memory management mechanism (garbage collector), java is a strictly typed
language, it has a strong set of exception handling mechanism, and many more.

Architecture-neutral (or) Platform Independent

Java has invented to archive "write once; run anywhere, any time, forever". The java provides
JVM (Java Virtual Machine) to 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.

However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java

Multi-threaded

Java supports multi-threading programming, which allows us to write programs that do


multiple operations simultaneously.
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

Interpreted

Java enables the creation of cross-platform programs by compiling into an intermediate


representation called Java bytecode. The byte code is interpreted to any machine code so that
it runs on the native machine.

High performance

Java provides high performance with the help of features like JVM, interpretation, and its
simplicity.

Distributed

Java programming language supports TCP/IP protocols which enable the java to support the
distributed environment of the Internet. Java also supports Remote Method Invocation (RMI),
this feature enables a program to invoke methods across a network.

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 computer 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 invented by a team of 13 employees of Sun Microsystems, Inc. which is
lead by James Gosling, in 1991. The team includes persons like Patrick Naughton, Chris
Warth, Ed Frank, and Mike Sheridan, etc., Java was developed as a part of the Green project.
Initially, it was called Oak, later it was changed to Java in 1995.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

History of Java

 The C language developed in 1972 by Dennis Ritchie had taken a decade to become
the most popular language.
 In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language with
included OOP fundamentals and features.
 The history of Java starts with the Green Team. Java team members (also known as
Green Team), initiated this project to develop a language for digital devices such as
set-top boxes, televisions, etc. However, it was best suited for internet programming.
 The principles for creating Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded, Architecture
Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James
Gosling, who is known as the father of Java, in 1995. James Gosling and his team
members started the project in the early '90s.
 Currently, Java is used in internet programming, mobile devices, games, e-business
solutions, etc. Following are given significant points that describe the history of Java.

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.

Why Java was named as "Oak"?

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.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Why Java Programming named "Java"?

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.

Execution Process of Java Program


The following three steps are used to create and execute a java program.

 Create a source code (.java file).


 Compile the source code using javac command.
 Run or execute .class file uisng java command.

Java Version History:

JDK Alpha and Beta (1995)

JDK 1.0 (23rd Jan 1996)

JDK 1.1 (19th Feb 1997)

J2SE 1.2 (8th Dec 1998)

J2SE 1.3 (8th May 2000)

J2SE 1.4 (6th Feb 2002)

J2SE 5.0 (30th Sep 2004)

Java SE 6 (11th Dec 2006)

Java SE 7 (28th July 2011)


Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

Java SE 8 (18th Mar 2014)

Java SE 9 (21st Sep 2017)

Java SE 10 (20th Mar 2018)

Java SE 11 (September 2018)

Java SE 12 (March 2019)

Java SE 13 (September 2019)

Java SE 14 (Mar 2020)

Java SE 15 (September 2020)

Java SE 16 (Mar 2021)

Java SE 17 (September 2021)

Java SE 18 (to be released by March 2022)

What is JDK , JRE & JVM:

1. JDK (Java Development Kit) is a Kit that provides the environment to develop and
execute(run) the Java program. JDK is a kit(or package) that includes two things

Development Tools(to provide an environment to develop your java programs)

JRE (to execute your java program).

2. JRE (Java Runtime Environment) is an installation package that provides an environment


to only run(not develop) the java program(or application)onto your machine. JRE is only
used by those who only want to run Java programs that are end-users of your
system.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

3. JVM (Java Virtual Machine)

A Virtual Machine is a software implementation of a physical machine. Java was developed


with the concept of WORA (Write Once Run Anywhere), which runs on a VM. The compiler
compiles the Java file into a Java .class file, then that .class file is input into the JVM, which
loads and executes the class file. Below is a diagram of the

JVM is a very important part of both JDK and JRE because it is contained or inbuilt in both.
Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible for
executing the java program line by line, hence it is also known as an interpreter. Architecture
of the JVM.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Every Java developer knows that bytecode will be executed by the JRE (Java Runtime
Environment). But many don't know the fact that JRE is the implementation of Java Virtual
Machine (JVM), which analyzes the bytecode, interprets the code, and executes it. It is very
important, as a developer, that we know the architecture of the JVM, as it enables us to write
code more efficiently.

How Does the JVM Work?

As shown in the above architecture diagram, the JVM is divided into three main subsystems:

ClassLoader Subsystem

Runtime Data Area

Execution Engine

1. ClassLoader Subsystem

Java's dynamic class loading functionality is handled by the ClassLoader subsystem. It loads,
links. and initializes the class file when it refers to a class for the first time at runtime, not
compile time.

1.1 Loading

Classes will be loaded by this component. BootStrap ClassLoader, Extension ClassLoader,


and Application ClassLoader are the three ClassLoaders that will help in achieving it.

BootStrap ClassLoader – Responsible for loading classes from the bootstrap classpath,
nothing but rt.jar. Highest priority will be given to this loader.

Extension ClassLoader – Responsible for loading classes which are inside the ext folder
(jre\lib).

Application ClassLoader –Responsible for loading Application Level Classpath, path


mentioned Environment Variable, etc.

The above ClassLoaders will follow Delegation Hierarchy Algorithm while loading the class
files.

1.2 Linking

Verify – Bytecode verifier will verify whether the generated bytecode is proper or not if
verification fails we will get the verification error.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Byte code verifier using following command:

Example:

Type below command

javap –v sample.class

Bytecode verifier:

Prepare – For all static variables memory will be allocated and assigned with default values.

Resolve – All symbolic memory references are replaced with the original references from
Method Area.
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

1.3 Initialization

This is the final phase of ClassLoading; here, all static variables will be assigned with the
original values, and the static block will be executed.

2. Runtime Data Area

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

The Runtime Data Area is divided into five major components:

Method Area – All the class-level data will be stored here, including static variables. There is
only one method area per JVM, and it is a shared resource.

Heap Area – All the Objects and their corresponding instance variables and arrays will be
stored here. There is also one Heap Area per JVM. Since the Method and Heap areas share
memory for multiple threads, the data stored is not thread-safe.

Stack Area – For every thread, a separate runtime stack will be created. For every method
call, one entry will be made in the stack memory which is called Stack Frame. All local
variables will be created in the stack memory. The stack area is thread-safe since it is not a
shared resource. The Stack Frame is divided into three subentities:

Local Variable Array – Related to the method how many local variables are involved and the
corresponding values will be stored here.

Operand stack – If any intermediate operation is required to perform, operand stack acts as
runtime workspace to perform the operation.

Frame data – All symbols corresponding to the method is stored here. In the case of any
exception, the catch block information will be maintained in the frame data.

PC Registers – Each thread will have separate PC Registers, to hold the address of current
executing instruction once the instruction is executed the PC register will be updated with the
next instruction.

Native Method stacks – Native Method Stack holds native method information. For every
thread, a separate native method stack will be created.

3. Execution Engine

The bytecode, which is assigned to the Runtime Data Area, will be executed by the Execution
Engine. The Execution Engine reads the bytecode and executes it piece by piece.

Interpreter – The interpreter interprets the bytecode faster but executes slowly. The
disadvantage of the interpreter is that when one method is called multiple times, every time a
new interpretation is required.

JIT Compiler – The JIT Compiler neutralizes the disadvantage of the interpreter. The
Execution Engine will be using the help of the interpreter in converting byte code, but when
it finds repeated code it uses the JIT compiler, which compiles the entire bytecode and

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

changes it to native code. This native code will be used directly for repeated method calls,
which improve the performance of the system.

Intermediate Code Generator – Produces intermediate code

Code Optimizer – Responsible for optimizing the intermediate code generated above

Target Code Generator – Responsible for Generating Machine Code or Native Code

Profiler – A special component, responsible for finding hotspots, i.e. whether the method is
called multiple times or not.

Garbage Collector: Collects and removes unreferenced objects. Garbage Collection can be
triggered by calling System.gc(), but the execution is not guaranteed. Garbage collection of
the JVM collects the objects that are created.

Java Native Interface (JNI): JNI will be interacting with the Native Method Libraries and
provides the Native Libraries required for the Execution Engine.

Native Method Libraries: This is a collection of the Native Libraries, which is required for
the Execution Engine.

Comments in java:

The Java language supports three types of comments:

Name Comment Description


The compiler ignores everything from // to the end of
Single-line comment // text
the line.
Multiline comment /* text */ The compiler ignores everything from /* to */.

Documentary comment This is a documentation comment and in general


/**
called doc comment. The JDK javadoc tool uses doc
*text
comments when preparing automatically generated
*documentation */
documentation.

Code:comments

public class Sample


{
/** data members
* member function are
* declared here*/
public static void main(String args[])
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

{
/* in main function
Code will going
*/

System.out.println("hello ");//it is output function


}
}

Data Types, Variables and Constants :

2.1 Data types


2.1.1 Integer data type
2.1.2 Floating point data type
2.1.3 Character data type
2.1.4 Boolean data type
2.3 Variables
2.3.1 Variable name

2.4 Constants
2.4.1 Integer Constant
2.4.2 Real Constant
2.4.3 Character Constant
2.4.4 String Constant
2.4.5 Symbolic constant
2.4.6 Backslash character constant
2.5 Comments
2.6 Command line arguments

2.1 Data types:

A data type is a scheme for representing values. An example is int which is the
Integer, a data type. Values are not just numbers, but any manner of data that a computer
can process.
The data type defines the kind of data that is represented by a variable.

Java data types are case sensitive.

There are two types of data types


 primitive data type
 non-primitive data type

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

In primitive data types, there are two categories

 Numeric means Integer and Floating points


 Non-numeric means Character and Boolean

In non-primitive types, there are three categories


1. classes
2. arrays
3. interface

Following table shows the datatypes with their Size Range


size and ranges. Data type (byte)
byte 1 -128 to 127
boolean 1 True or false
char 2 A-Z,a-z,0-9,etc.
short 2 -32768 to 32767
Int 4 (about) -2 million to 2 million
long 8 (about) -10E18 to 10E18
float 4 -3.4E38 to 3.4E18
double 8 -1.7E308 to 1.7E308

Fig: Data types with size and range

2.1.1 Integer data type:


Integer data type can hold the numbers (the number can be positive number or negative
number). In Java, there are four types of integer as follows:
 byte
 short
 int
 long

We can make integer long by adding ‗l‗ or ‗L‗ at the end of the number.

Code:

package unit1;

public class Integral


{
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

public static void main(String args[])


{
byte a=10;
short b=1000;
int c=10000;
long d=100000;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);

}
}

Output:
10
1000
10000
100000
2.1.2 Floating point data type:

It is also called as Real number and when we require accuracy then we can use it.
There are two types of floating point data type.

 float
 double

It is represent single and double precision numbers. The float type is used for single
precision and it uses 4 bytes for storage space. It is very useful when we require accuracy
with small degree of precision. But in double type, it is used for double precision and uses
8 bytes of storage space. It is useful for large degree of precision.

Code:

package unit1;

public class Floating


{
public static void main(String args[]) {
float c=1.1f;
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
System.out.println("float values is " +c);
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

}
}

Output:
Area of circle is 366.436224
float values is 1.1

2.1.3 Character data type:

It is used to store single character in memory. It uses 2 bytes storage space.


Code:
// char variables behave like integers.
class CharDemo2 {
public static void main(String[] args)
{
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);

}}
output:
ch1 contains X
ch1 is now Y

2.1.4 Boolean data type:

It is used when we want to test a particular condition during the execution of the
program. There are only two values that a Boolean type can hold: true and false.
Boolean type is denoted by the keyword Boolean and uses only one bit of storage.
Following program shows the use of data types.

Code:

package unit1;

public class Boolean {

public static void main(String args[]) {


boolean b;
b = false;
System.out.println("b is " + b);
b = true;

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

System.out.println("b is " + b);


// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
Output:

b is false
b is true
This is executed.
10 > 9 is true

Differences Between primitive and non primitive datatypes:

Primitive Vs Non-primitive Data Types

Primitive Data Type Non-primitive Data Type

These are built-in data types These are created by the users

Does not support additional methods Support additional methods

Always has a value It can be null

Starts with lower-case letter Starts with upper-case letter

Size depends on the data type Same size for all

Java Variables:

A variable is a named memory location used to store a data value. A variable can be defined
as a container that holds a data value.

In java, we use the following syntax to create variables.

Syntax:

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;

In java programming language variables are clasiffied as follows.

 Local variables
 Instance variables or Member variables or Global variables
 Static variables or Class variables
 Final variables

Local variables
The variables declared inside a method or a block are known as local variables. A local
variable is visible within the method in which it is declared. The local variable is created
when execution control enters into the method or block and destroyed after the method or
block execution completed.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Instance variables or member variables or global variables


The variables declared inside a class and outside any method, constructor or block are known
as instance variables or member variables. These variables are visible to all the methods of
the class. The changes made to these variables by method affects all the methods in the class.
These variables are created separate copy for every object of that class.

Let's look at the following example java program to illustrate instance variable in java.

Static variables or Class variables:


A static variable is a variable that declared using static keyword. The instance variables can
be static variables but local variables can not. Static variables are initialized only once, at the
start of the program execution. The static variable only has one copy per class irrespective of
how many objects we create.

The static variable is access by using class name.

Let's look at the following example java program to illustrate static variable in java.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Final variables:
A final variable is a variable that declared using final keyword. The final variable is
initialized only once, and does not allow any method to change it's value again. The
.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Scope and life time of variable:


Defination:
 A block defines a scope.
 Thus, each time you start a new block, you are creating a new scope.
 A scope determines what objects are visible to other parts of your program.
 It also determines the lifetime ofthose objects.
 Many other computer languages define two general categories of scopes:
Local and global scope.
 Local scope variables works locally
 Global scope variables work globally
Now we will only examine the scopes defined by or within a method.

The scope defined by a method begins with opening curly brace. However, if that
method has parameters, they too are included within the method‘s scope. they work the same
as any other method variable.

As a general rule, variables declared inside a scope are not visible tocode that is
defined outside that scope.
.

Scopes can be nested. For example, each time you create a block of code, you are creating
a new, nested scope.

consider the following program:

class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

}
}

Scope of Instance variable:

 Instance variable need not to be initialized.


 Every object has own copy of instance variables.
 If not initialized then instance variables are given default values
 Instance variable are alive as long as the object is alive
 When no longer used it it is removed by garbage collector

Code:
package unit1;
public class Instance
{
double r;
public double getArea()
{
double area=3.14*r*r;
return area;
}
}
package unit1;

public class InstanceTest {


public static void main(String[] args) {
Instance mc=new Instance();
mc.r=1.1;
mc.getArea();
}
}

Constant:

Constant means fixed value which is not change at the time of execution of program. In Java,
there are two types of constant as follows:
Numeric Constants
1. Integer constant
2. Real constant
3. Character Constants
4. Character constant
5. String constant

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

2.3.1 Integer Constant:

An Integer constant refers to a series of dig . There are three types of integer as follows:
a) Decimal integer

Embedded spaces, commas and characters are not allwoed in between dig .
For example:
23 411
7,00,000
17.33
b) Octal integer

It allows us any sequence of numbers or dig from 0 to 7 with leading 0 and it is called as
Octal integer.
For example:
011
00
0425
c) Hexadecimal integer It allows the sequence which is preceded by 0X or 0x and it also
allows alphabets from ‗A‗ to ‗F‗ or ‗a‗ to ‗f‗ (‗A‗ to ‗F‗ stands for the numbers ‗10‗ to
‗15‗) it is called as Hexadecimal integer.
For example:
0x7
00X
0A2B

2.4.2 Real Constant


It allows us fractional data and it is also called as folating point constant.
It is used for percentage, height and so on.
For example:
0.0234
0.777
-1.23

2.4.3 Character Constant


It allows us single character within pair of single coute.
For example:
‗A‗
‗7‗
‗\‗

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

2.4.4 String Constant


It allows us the series of characters within pair of double coute.
For example:
―WELCOME‖
―END OF PROGRAM‖
―BYE …BYE‖
―A‖
2.4.5 Symbolic constant:
In Java program, there are many things which is requires repeatedly and if we want to make
changes then we have to make these changes in whole program where this variable is used.
For this purpose, Java provides ‗final‗ keyword to declare the value of variable as follows:
Syntax:
final type Symbolic_name=value;
For example:
If I want to declare the value of ‗PI‗ then:
final float PI=3.1459
the condition is, Symbolic_name will be in capital letter( it shows the difference between
normal variable and symblic name) and do not declare in method.

Java 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

Syntax:
data_type array_name[ ] = new data_type[size];
(or)
data_type[ ] array_name = new data_type[size];
Creating an array

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

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.

NullPointerException with Arrays


In java, an array created without size and initialized to null remains null only. It does not
allow us to assign a value. When we try to assign a value it generates
a NullPointerException.
Look at the following example program.

ArrayIndexOutOfBoundsException with Arrays

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

In java, the JVM (Java Virtual Machine) throws ArrayIndexOutOfBoundsException when an


array is trying to access with an index value of negative value, value equal to array size, or
value more than the array size.

Look at the following example program.

Looping through an array


An entire array is accessed using either simple for statement or for-each statement. Look at
the following example program to display sum of all the lements in a list.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

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. We use the
following syntax to create two-dimensional array.

Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];

When we create a two-dimensional array, it created with a separate index for rows and
columns. The individual element is accessed using the respective row index followed by the
column index. A multidimensional array can be initialized while it has created using the
following syntax.

Syntax
data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};

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
int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};

The above statement creates a two-dimensional array of three rows and two columns.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Tokens in Java
3.1 Introduction
3.2 Tokens in Java
3.2.1 Identifiers
3.2.2 Literals
3.2.3 Keywords
3.2.4 Operator
3.2.4.1 Arithmetic operators
3.2.4.2 Logical operators
3.2.4.3 Relational operators
3.2.4.4 Assignment operators
3.2.4.5 Conditional operators
3.2.4.6 Increment and decrement operators
3.2.4.7 Bit-wise operator
3.2.5 Separators
3.3 Operator Precedence in Java

3.1 Introduction:
A Java program is basically a set of classes. A class is defined by a set of declaration
statements and methods or functions. Most statements contain expressions, which express the
actions carried out on information or data. Smallest individual thing in a program are known
as tokens. The compiler recognizes them for building up expression and statements.
3.2 Tokens in Java:
There are five types of token as follows:
1. Literals
2. Identifiers
3. Operators
4. Separators
3.2.1 Literals:
Literals in Java are a sequence of characters (dig , letters and other characters) that
characterize constant values to be stored in variables. Java language specifies five major
types of literals are as follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
3.2.2 Identifiers:
Identifiers are programmer-created tokens. They are used for naming classes, methods,
variables, objects, labels, packages and interfaces in a program. Java identifiers follow the
following rules:
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not start with a digit.
3. Uppercase and lowercase letters are individual.
4. They can be of any length.

Identifier must be meaningful, easily understandable and descriptive.


For example:
Private and local variables like ―length‖.
Name of public methods and instance variables begin with lowercase letter like ―addition‖

3.2.3 Keywords:
Keywords are important part of Java. Java language has reserved 50 words as keywords.
Keywords have specific meaning in Java. We cannot use them as variable, classes and
method. Following table shows keywords.

abstract char catch boolean


default finally do implements
if long throw private
package static break double
this volatile import protected
class throws byte else
float final public transient
native instanceof case extends
int null const new

3.2.4 Operator:
Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in
programs to operate data and variables. They frequently form a part of mathematical or
logical expressions.
Categories of operators are as follows:
1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Conditional operators
6. Increment and decrement operators
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

7. Bit wise operators

3.2.4.1 Arithmetic operators:

Arithmetic operators are used to make mathematical expressions and the working out as same
in algebra. Java provides the fundamental arithmetic operators. These can operate on built in
data type of Java.
Following table shows the details of operators.

Operator Importance/ significance


+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo division or remainder

class AdditionInt
{
public static void main (String args[])
{
int a = 6,b=3,c,d,e,f,g;
System.out.println("a = " + a);
System.out.println("b =" + b);
c = a + b;
d=a-b;
e=a*b;
f=a/b;
g=a%b;
System.out.println("c= " + c);
System.out.println("d= " + d);
System.out.println("e= " + e);
System.out.println("f= " + f);
System.out.println("g= " + g);

}
}
Output:
a= 6

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

b= 3
c=9
d=3
e=18
f=2
g=0

3.2.4.2 Logical operators:


When we want to form compound conditions by combining two or more relations, then we
can use logical operators.
Following table shows the details of operators. Importance/ significance
Operators
|| Logical – OR
&& Logical –AND
! Logical –NOT
The logical expression defer a value of true or false. Following table shows the truth table of
Logical – OR and Logical – AND.

Truth table for Logical – OR operator:

Operand1 Operand3 Operand1 || Operand3


T T T
T F T
F T T
F F F

T - True
F - False
Truth table for Logical – AND operator:
Operand1 Operand3 Operand1 && Operand3
T T T
T F F
F T F
F F F
T - True
F – False
Now the following program shows the use of Logical operators.
class LogicalOptr
{
public static void main (String args[])
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

{
boolean a = true;
boolean b = false;
System.out.println("a||b = " +(a||b));
System.out.println("a&&b = "+(a&&b));
System.out.println("a! = "+(!a)); }
}
Output:
a||b = true
a&&b = false
a! = false

3.2.4.3 Relational Operators:

When evaluation of two numbers is performed depending upon their relation, assured
decisions are made.
The value of relational expression is either true or false.
If A=7 and A < 10 is true while 10 < A is false.
Following table shows the details of operators.

Operator Importance/ significance


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

Now, following examples show the actual use of operators.


1) If 10 > 30 then result is false
2) If 40 > 17 then result is true
3) If 10 >= 300 then result is false
4) If 10 <= 10 then result is true

Now the following program shows the use of operators.


(1) Program 1:

class Reloptr1
{
public static void main (String args[])
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

{
int a = 10;
int b = 30;
System.out.println("a>b = " +(a>b));
System.out.println("a<b = "+(a<b));
System.out.println("a<=b = "+(a<=b));
}
}
Output:
a>b = false
a<b = true
a<=b = true
(2) Program 3

class Reloptr3
{
public static void main (String args[])
{
int a = 10;
int b = 30;
int c = 30;
System.out.println("a>b = " +(a>b));
System.out.println("a<b = "+(a<b));
System.out.println("a<=c = "+(a<=c));
System.out.println("c>b = " +(c>b));
System.out.println("a<c = "+(a<c));
System.out.println("b<=c = "+(b<=c));
}
}
Output:
a>b = false
a<b = true
a<=c = true
c>b = true
a<c = true
b<=c = true
3.2.4.4 Assignment Operators:
Assignment Operators is used to assign the value of an expression to a variable and is also
called as Shorthand operators.
Variable_name binary_operator = expression
Following table show the use of assignment operators.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Simple Assignment Operator Statement with shorthand Operators


A=A+1 A+=1
A=A-1 A-=1
A=A*1 A*=1
A=A/1 A/=1
A=A%1 A%=1

These operators avoid repetition, easier to read and write.


Now the following program shows the use of operators.
class Assoptr
{
public static void main (String args[])
{
int a = 10;
int b = 30;
int c = 30;
a+=1;
b-=3;
c*=7;
System.out.println("a = " +a);
System.out.println("b = "+b);
System.out.println("c = "+c);
}
}
Output:
a = 11
b = 18
c = 310
3.2.4.5 Conditional Operators:
The character pair ?: is a ternary operator of Java, which is used to construct conditional
expressions of the following form:
Expression1 ? Expression3 : Expression3
The operator ? : works as follows:
Expression1 is evaluated if it is true then Expression3 is evaluated and becomes the value of
the conditional expression. If Expression1 is false then Expression3 is evaluated and value
becomes the conditional expression.
For example:
of operators.
class Coptr
{

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

public static void main (String args[])


{
int a = 10;
int b = 30;
int c;
c=(a>b)?a:b;
System.out.println("c = " +c);
c=(a<b)?a:b;
System.out.println("c = " +c);
}
}
Output:
c = 30
c = 10
program3:Write a program to check whether number is positive or negative.
class PosNeg
{
public static void main(String args[])
{
int a=10;
int flag=(a<0)?0:1;
if(flag==1)
System.out.println(―Number is positive‖);
else
System.out.println(―Number is negative‖);
}}
Output:
Number is positive
3.2.4.6 Increment and Decrement Operators:
The increment operator ++ adds 1 to a variable. Usually the variable is an integer type, but it
can be a floating point type. The two plus signs must not be split by any character. Usually
they are written immediately next to the variable.
Following table shows the use of operators.

Expression Process Example end result


A++ Add 1 to a variable int A=10,B; A=11
after use. B=A++; B=10
++A Add 1 to a variable int A=10,B; A=11
before use. B=++A; B=11
A-- Subtract 1 from a int A=10,B; A=9
variable after use. B=A--; B=10

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

--A Subtract 1 from a int A=10,B; A=9


variable before use. B=--A; B=9

Now the following program shows the use of operators.


class IncDecOp
{
public static void main(String args[])
{
int x=1,r;
int y=3;
int u;
int z;
u=++y;
z=x++;
r=++x + ++x;
System.out.println(x);
System.out.println(y);
System.out.println(u);
System.out.println(z);
System.out.println(r);
}
}
Output:
3
4
4
1
3.2.4.7 Bit Wise Operators:
Bit wise operator execute single bit of their operands. Following table shows bit wise
operator:

Operator Importance/ significance


| Bitwise OR
& Bitwise AND
&= Bitwise AND assignment
|= Bitwise OR assignment
^ Bitwise Exclusive OR
<< Left shift
>> Right shift
~ One‗s complement

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Now the following program shows the use of operators.


(1) Program 1
class Boptr1
{
public static void main (String args[])
{
int a = 4;
int b = a<<3;
System.out.println("a = " +a);
System.out.println("b = " +b);
}
}
Output:
a =4
b =16
(2) Program 3

Class Boptr3
{
public static void main (String args[])
{
int a = 16;
int b = a>>3;
System.out.println("a = " +a);
System.out.println("b = " +b);
}
}
Output:
a = 16
b=3

OPERATORS HIERACHY:
Java has well-defined rules for specifying the order in which the operators in an expression
are evaluated when the expression has several operators. For example, multiplication and
division have a higher precedence than addition and subtraction. Precedence rules can be
overridden by explicit parentheses.

Precedence order.
When two operators share an operand the operator with the higher precedence goes first. For
example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since
multiplication has a higher precedence than addition.
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

Associativity.
When an expression has two operators with the same precedence, the expression is evaluated
according to its precedense associativity. For example x = y = z = 17 is treated as x = (y = (z
= 17)), leaving all three variables with the value 17, since the = operator has right-to-left
associativity (and an assignment statement evaluates to the value on the right hand side). On
the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right
associativity.

Precedence and associativity of Java operators.


The table below shows all Java operators from highest to lowest precedence, along with their
associativity. Most programmers do not memorize them all, and even those that do still use
parentheses for clarity.

Operator Description Level Associativity

[] access array element


. access object member
() invoke a method 1 left to right
++ post-increment
-- post-decrement

++ pre-increment
-- pre-decrement
+ unary plus
2 right to left
- unary minus
! logical NOT
~ bitwise NOT

() cast
3 right to left
new object creation

*
/ multiplicative 4 left to right
%

+- additive
5 left to right
+ string concatenation

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

<< >>
shift 6 left to right
>>>

< <=
> >= relational
7 left to right
type comparison
instanceof

==
equality 8 left to right
!=

& bitwise AND 9 left to right

^ bitwise XOR 10 left to right

| bitwise OR 11 left to right

&& conditional AND 12 left to right

|| conditional OR 13 left to right

?: conditional 14 right to left

= += -=
*= /= %=
&= ^= |= assignment 15 right to left
<<= >>= >>>=

Source: (Precedence.java)
package day3;

public class Precedense {

public static void main(String[] args) {

System.out.println( 3 + 3 * 2 );

System.out.println( 3 * 3 - 2 );
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

System.out.println( 3 * 3 / 2 );

System.out.println("--");

System.out.println( 1 * 1 + 1 * 1);

System.out.println( 1 + 1 / 1 - 1);

System.out.println( 3 * 3 / 2 + 2);

System.out.println("--");

int x = 1;

System.out.println( x++ + x++ * --x );

} }

Output:
9

--

--

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Control structures in java:


1. conditional control structure
a.if b.if else c.nested if d.else if ladder
2. repetative or loopingor iterative control structure
a.while b.for c.do while
3. case control strucure
a.switch
4. unconditional control strucure
a.break b.continue c.goto

The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.

Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace)
will be executed.

Example:
public class Test {

public static void main(String args[]){


int x = 10;

if( x < 20 ){
System.out.print("This is if statement");
}
}
}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

This would produce the following result:


This is if statement

The if...else Statement:


An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.

Syntax:
The syntax of an if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}

Example:
public class Test {

public static void main(String args[]){


int x = 30;

if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}

This would produce the following result:


This is else statement

The if...else if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

1. An if can have zero or one else's and it must come after any else if's.
2. An if can have zero to many else if's and they must come before the else.
3. Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:
The syntax of an if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}

Example:
public class Test {

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");
}
}
}

This would produce the following result:


Value of X is 30

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Nested if...else Statement:


It is always legal to nest if-else statements which means you can use one if or else if statement
inside another if or else if statement.

Syntax:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}

You can nest else if...else in the similar way as we have nested if statement.

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");
}
}
}
}

This would produce the following result:


X = 30 and Y = 10

The switch Statement:


A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each case.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Syntax:
The syntax of enhanced for loop is:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

The following rules apply to a switch statement:


 The variable used in a switch statement can only be a byte, short, int, or char.
 You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the switch and it must
be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.

Example:
public class Test {

public static void main(String args[]){

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

char grade = 'C';

switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}

Compile and run above program using various command line arguments. This would produce the
following result:
$ java Test
Well done
Your grade is a C

There may be a situation when we need to execute a block of code several number of times, and
is often referred to as a loop.

Java has very flexible three looping mechanisms. You can use one of the following three loops:
 while Loop
 do...while Loop
 for Loop
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}

When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.

Example:
public class Test {

public static void main(String args[]) {


int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

This would produce the following result:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.

Syntax:
The syntax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in
the loop execute again. This process repeats until the Boolean expression is false.

Example:
public class Test {

public static void main(String args[]){


int x = 10;

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

This would produce the following result:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.

Syntax:
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}

Here is the flow of control in a for loop:


 The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long
as a semicolon appears.
 Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and flow of control jumps to the next
statement past the for loop.
 After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank, as long as a semicolon appears after the Boolean expression.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

 The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.

Example:
public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x+1) {


System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

This would produce the following result:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Enhanced for loop in Java:


This is mainly used for Arrays.

Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

 Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and value would be the same as the current array element.
 Expression: This evaluates to the array you need to loop through. The expression can be
an array variable or method call that returns an array.

Example:
public class Test {

public static void main(String args[]){


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}

This would produce the following result:


10,20,30,40,50,
James,Larry,Tom,Lacy,

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used inside any
loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line
of code after the block.

Syntax:
The syntax of a break is a single statement inside any loop:
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

break;

Example:
public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}

This would produce the following result:


10
20

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
 In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.
 In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.

Syntax:
The syntax of a continue is a single statement inside any loop:
continue;

Example:
public class Test {
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}

This would produce the following result:


10
20
40
50

Java data type conversion comes with 3 flavors.


1. Implicit conversion
2. Explicit conversation
3. Automatic conversion

1. Implicit conversion (widening conversion)


A data type of lower size (occupying less memory) is assigned to a data type of higher size.
This is done implicitly by the JVM. The lower size is widened to higher size. This is also named
as automatic type conversion.
Examples:
int x = 10; // occupies 4 bytes
double y = x; // occupies 8 bytes

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

System.out.println(y); // prints 10.0

In the above code 4 bytes integer value is assigned to 8 bytes double value.

byte –> short –> int –> long –> float –> double
like above format conversions is going

2. Explicit conversion (narrowing conversion)


A data type of higher size (occupying more memory) cannot be assigned to a data type of lower
size. This is not done implicitly by the JVM and requires explicit conversation; a conversion
operation to be performed by the programmer. The higher size is narrowed to lower size.
double x = 10.5; // 8 bytes
int y = x; // 4 bytes ; raises compilation error

In the above code, 8 bytes double value is narrowed to 4 bytes int value. It raises error. Let us
explicitly type cast it.
double x = 10.5;
int y = (int) x;

The double x is explicitly converted to int y. The thumb rule is, on both sides, the same data type
should exist.

byte <–short<– int<– long <– float <- double


like above format conversions is going

3. Boolean conversion
A boolean value cannot be assigned to any other data type. Except boolean, all the remaining 7
data types can be assigned to one another either implicitly or explicitly; but boolean cannot. We
say, boolean is incompatible for conversion. Maximum we can assign a boolean value to another
boolean.
Following raises error.
boolean x = true;

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

int y = x; // error

boolean x = true;
int y = (int) x; //
error

byte –> short –> int –> long –> float –> double
In the above statement, left to right can be assigned implicitly and right to left requires explicit
conversion. That is, byte can be assigned to short implicitly but short to byte requires explicit
conversion.
Following char operations are possible.

public class Demo


{
public static void main(String args[])
{
char ch1 = 'A';
double d1 = ch1;

System.out.println(d1); // prints 65.0


System.out.println(ch1 * ch1); // prints 4225 , 65 * 65

double d2 = 66.0;
char ch2 = (char) d2;
System.out.println(ch2); // prints B
}
}

If the two types are compatible, then Java will perform the conversion automatically.
For example, assign an int value to a long variable.
For incompatible types we must use a cast.
Conversion is an explicit conversion between incompatible types.
Automatic Conversions
An automatic type conversion will be used if the following two conditions are met:
4. The two types are compatible.
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

5. The destination type is larger than the source type.


int type is always large enough to hold all valid byte values, so an automatic type conversion
takes place.
Code:
public class Main {
public static void main(String[] argv) {
byte b = 10;
int i = 0;

i = b;
System.out.println("b is " + b);
System.out.println("i is " + i);
}
}The output:

b is 10

i is 10

For widening conversions, integer and floating-point types are compatible with each other.

public class Main {


public static void main(String[] argv) {
int i = 1234;
float f;

f = i;

System.out.println("i is " + i);


System.out.println("f is " + f);
}
}

The output:

i is 1234

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

f is 1234.0

Console Input And Output Opeartions:

This program tells you how to get input from user in a java program. We are using
Scanner class to get input from user. This program firstly asks the user to enter a string and then
the string is printed, then an integer and entered integer is also printed and finally a float and it is
also printed on the screen. Scanner class is present in java.util package so we import this package
in our program. We first create an object of Scanner class and then we use the methods of
Scanner class. Consider the statement
Scanner a = new Scanner(System.in);

Here Scanner is the class name, a is the name of object, new keyword is used to allocate the
memory and System.in is the input stream. Following methods of Scanner class are used in the
program below :-
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string

Java programming source code

package day3;

import java.util.Scanner;

public class Input

public static void main(String args[])

int a;

float b;

double e;

long l;

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

String d;

short s;

Scanner sc=new Scanner(System.in);

System.out.println("enter a integer number");

a=sc.nextInt();

System.out.println("a="+a);

System.out.println("enter string");

d=sc.next();

System.out.println("d="+d);

System.out.println("enter float number");

b=sc.nextFloat();

System.out.println("b="+b);

System.out.println("Enter a character: ");

char g = sc.next().charAt(0);

System.out.println("g= "+g);

System.out.println("enter double number");

e=sc.nextDouble();

System.out.println("e="+e);

System.out.println("enter long value");

l=sc.nextLong();

System.out.println("l="+l);

System.out.println("enter short value");

s=sc.nextShort();
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

System.out.println("s="+s);

Output of program:

enter a integer number

a=1

enter string

shiva

d=shiva

enter float number

1.1

b=1.1

Enter a character:

g= d

enter double number

2.3

e=2.3

enter long value

12345

l=12345

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

enter short value

s=1

Java Classes

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.

Look at the following picture to understand the class and object concept

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

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. Following is the syntax of class in the java.

Syntax:

class <ClassName>{

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:

Pen.java

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Book.java

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. Following is the syntax of class
in the java.

<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
programs:

student.java

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

In the same class datamembers , member function and main function :

Student.java

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

In above pen.java book.java and student java how to access these three classes into single class.

Constructor in Java

1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Copying the values of one object into another

Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

1. Constructor name must be same as class name


2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.

class A{
A() //constructor with out parameters is known as default constructor
{
System.out.println("constructer is created");
}
public static void main(String args[])
{
A b=new A();
}
}
Output:
Constructer is created

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.
What is the purpose of default constructor?
Default constructor provides the default values to the object like 0, null etc. depending on the
type.
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

Example of default constructor that displays the default values


class Student
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1=new Student();
Student3 s=new Student();
s1.display();
s2.display();
}
}
Output:
0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a
default constructor.Here 0 and null values are provided by default constructor.

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?


Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.

class Student{
int id;
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

String name;

Student(int i,String n){


id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111," ");
Student s2 = new Student(222,"cse");
s1.display();
s2.display();
}
}
Output:
111
222 cse

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

Example of Constructor Overloading


class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(111," ");
Student s2 = new Student(222,"cse",25);
s1.display();
s2.display();
} }
Output:

111 0
222 cse 25

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Method is used to expose behaviour of


Constructor is used to initialize the state of an object.
an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you Method is not provided by compiler in
don't have any constructor. any case.

Method name may or may not be same


Constructor name must be same as the class name.
as class name.

Java Methods:
A Java method is a collection of statements that are grouped together to perform an
operation. When you call the System.out.println method, for example, the system actually
executes several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke
a method with or without parameters, overload methods using the same names, and apply
method abstraction in the program design.

Creating Method:
Considering the following example to explain the syntax of a method:
public int funcName(int a, int b) {
// body
}

Here,
 public : modifier.
 int: return type
 funcName: function name
 a, b: formal parameters
 int a, int b: list of parameters
Methods are also known as Procedures or Functions:
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

 Procedures: They don't return any value.


 Functions: They return value.
Method definition consists of a method header and a method body. The same is shown below:
modifier returnType nameOfMethod (Parameter List) {
// method body
}

The syntax shown above includes:


 modifier: It defines the access type of the method and it is optional to use.
 returnType: Method may return a value.
 nameOfMethod: This is the method name. The method signature consists of the method
name and the parameter list.
 Parameter List: The list of parameters, it is the type, order, and number of parameters of
a method. These are optional, method may contain zero parameters.
 method body: The method body defines what the method does with statements.

Example:
class Addition
{
public void add()
{
int a=10,b=20,c;
c=a+b;
System.out.println(―c value is‖+c);
}
public static void main(String args[])
{
Addition a=new Addition();
a.add();
}

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

}
output:
c value is30

Method Calling:
For using a method, it should be called. There are two ways in which a method is called i.e.
method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the program control
gets transferred to the called method. This called method then returns control to the caller in two
conditions, when:
 return statement is executed.
 reaches the method ending closing brace.

Example:
Following is the example to demonstrate how to define a method and how to call it:
class Addition
{
public void add()
{
int c;
int a=10,b=20;
c=a+b;
void disp()
{
return c;
}
}
public static void main(String args[])

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

{
int d;
Addition a=new Addition();
d=a.disp();
}
}
output: 30
Code:

Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.

1) private access modifier


The private access modifier is accessible only within class.

Simple example of private access modifier


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 compile time error.

class A{

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

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
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

Note: A class cannot be private or protected except nested class.

2) default access modifier


If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Example of default access modifier


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.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

3) protected access modifier

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
Example of protected access modifier
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();
} }
Output:Hello

4) public access modifier


The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

Example of public access modifier


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Understanding all java access modifiers


Let's understand the access modifiers by a simple table.

outside package by subclass


Access Modifier within class within package outside package
only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Java access modifiers with method overriding


If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.
class A{
protected void msg(){System.out.println("Hello java");}
}

public class Simple extends A{


void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

}
}
The default modifier is more restrictive than protected. That is why there is compile time error.

Java static keyword:


The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to the
class than an instance of the class.
The static can be:
 Variable (also known as a class variable)
 Method (also known as a class method)
 Block
 Nested class
1) Java static variable
If you declare any variable as static, it is known as a static variable.
The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of students,
etc.
The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
import java.util.Scanner;

public class Student


{
String name;
int age;
double avg;
static String college="cmrcet";
void getData()
{
Scanner s=new Scanner(System.in);
name=s.next();
age=s.nextInt();
avg=s.nextDouble();
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

}
void displayData()
{
System.out.println(name+","+age+","+avg+","+college);
}
public static void main(String[] args)
{
Student s1=new Student();
s1.getData();
s1.displayData();
Student s2=new Student();
s2.getData();
s2.displayData();
}
}
Output:
abc
12
1.1
abc,12,1.1,cmrcet
xyz
23
2.2
xyz,23,2.2,cmrcet

Program without static variable:


In this example, we have created an instance variable named x which is incremented in the
method. Since instance variable gets the memory at the time of object creation, each object will
have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each
object will have the value 1 in the count variable.
public class MyClass3
{
int x=10;
void change()
{
x=x+1;
System.out.println(x);
}
public static void main(String[] args)
{
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

MyClass3 m3=new MyClass3();


m3.change();
MyClass3 m4=new MyClass3();
m4.change();
MyClass3 m5=new MyClass3();
m5.change();

}
Output:
11
11
11

Program with static variable


As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.

public class MyClass3


{
static int x=10;
void change()
{
x=x+1;
System.out.println(x);
}
public static void main(String[] args)
{
MyClass3 m3=new MyClass3();
m3.change();
MyClass3 m4=new MyClass3();
m4.change();
MyClass3 m5=new MyClass3();
m5.change();

}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

}
Output:
11
12
13

2) Java static method


If you apply static keyword with any method, it is known as static method.

public class MyClassStatic


{
int x=10;
static int y=20;
static int change()
{
y=100;
return 0;
}
public static void main(String args[])
{

System.out.println(y);
change();
System.out.println(y);

}
}

Output:
20
100

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Restrictions for the static method


There are two main restrictions for the static method. They are:

The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
public class MyClassStatic
{
int x=10;
public static void main(String args[])
{
System.out.println(x);
}
}
Output:error

3) Java static block


Is used to initialize the static data member.
It is executed before the main method at the time of classloading.
Example of static block
public class MyClassStatic
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}

static block is invoked


Hello main

// Demonstrate static variables, methods, and blocks.


in a single program
class UseStatic {

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

static int a=3;


static int b;
static void meth(int x)
{
System.out.println("x " + x);

System.out.println("a= " + a);

System.out.println("b= " + b);

static
{

System.out.println("Static block initialized.");

b = a * 4;

public static void main(String args[])


{

meth(42);

Here is the output of the program:

Static block initialized.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

x = 42

a=3

b=1

For example, if you wish to call a static method

from outside its class, you can do so using the following general form:
Syntax:
classname.method( )

Here, classname is the name of the class in which the static method is declared.

As you can see, this format is similar to that used to call non-static methods through

object- reference variables. A static variable can be accessed in the same way—by use

of the dot operator on the name of the class. This is how Java implements a controlled

version of global methods and global variables.

Here is an example. Inside main( ), the static method callme( ) and the static

variable b are accessed outside of their class.

class StaticDemo {

static int a = 42;

static int b = 99;

static void callme() {

System.out.println("a = " + a);

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

class StaticByName {

public static void main(String args[]) {

StaticDemo.callme();

System.out.println("b = " + StaticDemo.b);

Here is the output of this program:

a = 42

b = 99

this keyword in java

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers
to the current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.
1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Suggestion: If you are beginner to java, lookup only two usage of this keyword.

1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the
problem of ambiguity.

this keyword can be used to refer current class instance variable

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given below:

class Student10{
int id;
String name;

student(int id,String name){


id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student10 s1 = new Student10(111,"shiva");
Student10 s2 = new Student10(321,"kumar");
s1.display();
s2.display();
}
}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

Output:0 null
0 null

-->it is illegal in Java to declare two local variables with the same name

In the above example, parameter (formal arguments) and instance variables are same that is why
we are using this keyword to distinguish between local variable and instance variable.

Solution of the above problem by this keyword


//example of this keyword
class Student11{
int id;
String name;

Student11(int id,String name){


this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"shiva");
Student11 s2 = new Student11(222,"kumar");
s1.display();
s2.display();
}
}

Output111 shiva
222 kumar

1. this() can be used to invoke current class constructor.


2. this keyword can be used to invoke current class method (implicitly)
see below example

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

this can be passed as an argument in the method call. And


see below example:

this keyword can also be used to return the current class instance

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Java Garbage Collection


In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.

How can an object be unreferenced?


There are many ways:
o By nulling the reference
o By assigning a reference to another
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

o By anonymous object etc.

1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
2) By assigning a reference to another:
1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
1. new Employee();

finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
1. protected void finalize(){}

gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc()
is found in System and Runtime classes.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

INTRODUCTION:
• Garbage collection in Java is the automated process of deleting code that‘s no longer needed
or used. This automatically frees up memory space and ideally makes coding Java apps
easier for developers.
• Without garbage collection, the heap would eventually run out of memory.
• The garbage collector uses a mark-and-sweep algorithm to mark all unreachable objects as
garbage collection, then scans through live objects to find objects that are still reachable.
Mark-and-sweep
The Java garbage collection process uses a mark-and-sweep algorithm. Here‘s how that works:
• There are two phases in this algorithm: mark followed by sweep.
• When a Java object is created in the heap, it has a mark bit that is set to 0 (false).
• During the mark phase, the garbage collector traverses object trees starting at their roots.
When an object is reachable from the root, the mark bit is set to 1 (true). Meanwhile, the
mark bits for unreachable objects is unchanged.
• During the sweep phase, the garbage collector traverses the heap, reclaiming memory from
all items with a mark bit of 0 (false).
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

How does it work:


• During the garbage collection process, the collector scans different parts of the heap, looking
for objects that are no longer in use.
• If an object no longer has any references to it from elsewhere in the application, the collector
removes the object, freeing up memory in the heap.
• The JVM separates the heap into separate spaces, and then garbage collectors use a mark-
and-sweep algorithm to traverse these spaces and clear out unused objects.
• Heap space is used for the dynamic memory allocation of Java objects and JRE classes at
runtime. New objects are always created in heap space, and the references to these objects
are stored in stack memory.
• The reference objects have global access and we can access them from anywhere in the
application. We can break this memory model down into smaller parts, called generations.
1. Young Generation – this is where all new objects are allocated and aged. A minor Garbage
collection occurs when this fills up.
Eden: The eden space in Java is a memory pool where objects are created. When the eden
space is full, the garbage collector either removes objects if they are no longer in use or
stores them in the survivor space if they are still being used. This space is considered part of
the young generation in the memory heap.
Survivor: There are two survivor spaces in the JVM: survivor zero and survivor one. This
space is also part of the young generation.
2. Old Generation – this is where long surviving objects are stored. When objects are stored in
the Young Generation, a threshold for the object‘s age is set, and when that threshold is
reached, the object is moved to the old generation.
3. Permanent Generation – this consists of JVM metadata for the runtime classes and
application methods.

• Garbage collection is the process by which java programs perform automatic memory
management.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

• In languages like C and C++, the programmer is responsible for both creation and
destruction of objects.
Three Methods:
1.By nulling the reference
2.By assigning a reference to the another
3.By anonymous object
Example code:
package GC;
public class marks {
int marks;
public static void main(String[] args) {
//Set null to object
marks m=new marks();
m=null;
//By assigning a reference to another
marks m1=new marks();
marks m2=new marks();
m1=m2;
m1.marks=30;
System.out.println(m2.marks);
//By anonymous object
new marks();
}
}

TYPES OF GARBAGE COLLECTION IN JAVA:


Serial GC
A primitive implementation of GC using just a single thread. When Garbage Collection happens,
it pauses the application (commonly known as a "stop the world" event.) This is suitable for
applications that can withstand small pauses. Garbage Collection has a small footprint, so
this is the preferred GC type for embedded applications.
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

Parallel GC
Like Serial GC, this also uses a "stop the world" method. That means that while GC is
happening, application threads are paused. But in this case, there are multiple threads
performing GC operation. This type of GC is suitable for applications with medium to large
data sets running in a multithreaded and multiprocessor environment.

Benefits of garbage collection:


• Automatic memory management reduces the burden on developers to free memory
manually.
• It eliminates common programming errors like memory leaks and dangling pointers.
• Garbage collection helps in optimizing memory usage, leading to better performance
• It can also help in preventing memory leaks.

Constructor overloading and Method overloading in Java


In Java, we can overload constructors like methods. The constructor overloading can be defined
as the concept of having more than one constructor with different parameters so that every
constructor can perform a different task.
In Java, we can overload Methods. The method overloading can be defined as the concept of
having more than one method with same name with different parameters so that every method
can perform a different task.
Program:
Constructor overloading in Java
In Java, we can overload constructors like methods. The constructor overloading can be defined
as the concept of having more than one constructor with different parameters so that every
constructor can perform a different task.
Consider the following Java program, in which we have used different constructors in the class.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Example

In the above example, the Student class constructor is overloaded with two different constructors,
I.e., default and parameterized.

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and
b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
1) 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.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

In this example, we are creating static methods so that we don't need to create instance for calling
methods.

Advantage of method overloading


Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.


There are two types of binding
1. Static Binding (also known as Early Binding).
2. Dynamic Binding (also known as Late Binding).

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Understanding Type
Let's understand the type of instance.

1) variables have a type


Each variable has a type, it may be primitive and non-primitive.
1. int data=30;
Here data variable is a type of int.

2) References have a type

1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }

3) Objects have a type

An object is an instance of particular java class,but it is also an instance of its superclass.

1. class Animal{}
2. class Dog extends Animal{
3. public static void main(String args[]){
4. Dog d1=new Dog();
5. }
6. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding
When type of the object is determined at compiled time(by the compiler), it is known as static
binding.
If there is any private, final or static method in a class, there is static binding.
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

1.
In the above example object type cannot be determined by the compiler, because the instance of Dog
is also an instance of Animal. So compiler doesn't know its type, only its base type.

Inheritance in java:

 One class acquiring the properties of another class is known as Inheritance

 Reusability is yet another of oop paradigm

 Java classes can be reused in several ways

 the mechanism of deriving a new class from an old one is called inheritance

 the old class is known as the base class or

Super class or

Parent class

 the new class is known as the subclass or

Derived class or

Child class

 the inheritance allows subclasses to inherit all the variables and methods of their parent
class

 object of sub class can be treated as super class

 one super can any number of sub classes


Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

 variables /methods defined subclasses are only available inside the subclass and its
subclasses

 each sub class can became a super class for future sub classes

 subclass directly access direct class and indirect class

 Java does not directly implement multiple inheritance in java however this concept is
implemented using a

 Secondary inheritance path in the form of interfaces

Defining a sub class:

A subclass is defined as follows

class subclass name extends superclassname

variables declarations;

methods declarartions;

 The keyword extends signifies that the properties of a super class are extended to the
subclass name

 The subclass will now contain its own variables and methods as well those of the the
super class

Below are various types of inheritance in Java. We will see each one of them one by one with the
help of examples and flow diagrams.

Single Inheritance:

When a class extends another one class only then we call it a single inheritance. The below flow
diagram shows that class B extends only one class which is A. Here A is a parent class of B and
B would be a child class of A.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Single Inheritance example program in Java


package day1;

public class A
{

public void methodA()


{
System.out.println("Base class method");
}
int a=1;
}
class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
System.out.println(obj.a);
}
}

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

example2:

Multiple Inheritances

―Multiple Inheritance‖ refers to the concept of one class extending (Or inherits) more than one
base class. The inheritance we learnt earlier had the concept of one base class or parent. The
problem with ―multiple inheritance‖ is that the derived class will have to manage the dependency
otwo base classes.

Note 1: Multiple Inheritances is very rarely used in software projects. Using multiple
inheritances often leads to problems in the hierarchy. This results in unwanted complexity when
further extending the class.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritances is supported in C++.

Note: Multiple Inheritances we will see in interfaces

Multilevel Inheritance

Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class. As you can see
in below flow diagram C is subclass or child class of B and B is a child class of A.

Multilevel Inheritance example program in Java

package day1;

class X
{
public void methodX()
{
System.out.println("Class X method");
}
int a=10;
}
class Y extends X
{
public void methodY()
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

{
System.out.println("class Y method");
}
int b=20;
}
class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
System.out.println(obj.a);
System.out.println(obj.b);
}
}

Hierarchical Inheritance

In such kind of inheritance one class is inherited by many sub classes. In below example class
B,C and D inherits the same class A. A is parent class (or base class) of B,C & D.

I‘m using the above figure for implementing hierarchical inheritance in the below example-

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Example:

package day1;

class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class MyClass
{

public static void main(String args[])


{
B obj1 = new B();

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

C obj2 = new C();


D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
The above would run perfectly fine with no errors and the output would be –
method of Class A
method of Class A
method of Class A
“super” keyword in java

Super is used for following purposes

 Call super class methods

 Call super class constructors

 To invoke the constructor of super class

 To invoke the method of super class

Example super keyword with constructors

package day1;

public class My {
public static void main(String[] args) {
int r1,r2;
A1 a=new A1(5,6);
r1=a.multi();
System.out.println(r1);
B1 b=new B1(3,1,3);
r2=b.multi();
System.out.println(r2);

}
}
class A1
{
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

int a,b;
A1(int x,int y)
{
a=x;
b=y;
}
int multi()
{
return a*b;
}
}
class B1 extends A1
{
int c;
B1(int x,int y,int z)
{
super(x,y);
c=z;
}
int multi()
{
return a*b*c;
}
}
Output:

30

Example on super keyword with methods

package day1;

public class My {
public static void main(String[] args) {
int r1,r2;
B1 b1=new B1();
b1.display();
}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

}
class A1
{
void hello()
{
System.out.println("hello");
}
}
class B1 extends A1
{
void hello()
{
System.out.println("hi");
}
void display()
{
hello();
super.hello();
}
}

Output:

Hi

Hello

Example on super keyword with variables

package day1;

public class My {
public static void main(String[] args) {
int r1,r2;
B1 b1=new B1();
b1.display();
}
}
class A1
{
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

int a=7;
}
class B1 extends A1
{
int a=8;
void display()
{
System.out.println(super.a);
System.out.println(a);
}
}

Output:

Preventing inheritance:

Preventing inheritance is used for following purposes

 to prevent inheritance

 to prevent overriding

 to make the variable are constants

 final keyword with constants

Final keyword in java:

 final keyword can be used for 3 situations

 final keyword with variables

 final key word with methods

 final keyword with class

Example on final keyword with methods


Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

package day1;

public class My {
public static void main(String[] args) {
B obj=new B();
obj.show();
}
}
class A
{
public final void show()
{
System.out.println("show of A");
}
}
class B extends A
{
public void show()//error can't override
{
System.out.println("show of B");
}
}
Example on final keyword with classes

package day1;

public class My {
public static void main(String[] args) {
B obj=new B();
obj.show();
obj.display();
}
}
final class A
{
public void show()
{
System.out.println("show of A");
}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

}
class B extends A //final class can't inherit
{
public void display()
{
System.out.println("show of B");
}
}

Example on final keyword with variables

package day1;

public class My {
public static void main(String[] args) {
Sample1 s1=new Sample1();
System.out.println(s1.A);
s1.A=200;// value canot be assigned
}
}
class Sample1
{
final int A=10;
}

Encapsulation:

Binding its internal details and showing its functionally is known as ENCAPSULATION.

EXAMPLE:

package day1;

public class My {
public static void main(String[] args) {
Box b=new Box();
b.setlength(3);
b.setwidth(3);
b.setheight(3);

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

int area;
area=b.volume();
System.out.println(area);
}}
class Box
{
private int length;
private int width;
private int height;
public void setlength(int l)
{
length=l;
}
public void setwidth(int w)
{
width=w;
}
public void setheight(int h)
{
height=h;
}
public int volume()
{
return length*width*height;
}}

Output:
27
Naming conventions:

code easier and & understand

Names for methods and variables:

 An identifier is the name of variable ,method or class

 Variable & method should start with "lowercase letter

Single word:

Example for variables


Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

int count ;

Example for methods

public void add()

--

--

Two words:

Example for variables:

int personName;

 subsequent word capital

Example for methods

int numberOfPeople;

Ex:

public void downloadFromInternet()

----

---

class names:

class name should start with an "upper case letter";

Example for classes:

class Person
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

----

----

 don‘t use $ symbol in name

 subsequent words also capital

constants:

 upper case letters separated by underscore for multiple words

Example for constants:

final int PI=3.14;

final int NO_OF_TAREGETS=7;

Method Overriding:

Overriding is the concept of hiding the super class By the member of subclass the member may
be instance variable or methods

Overriding is of two types

1) Instance variable hiding

2) Method overriding

1) Instance variable overriding

In the inheritance if the instance variable of super class and instance variable of sub class have
same names then it is said to be instance variable overriding i.e the instance variable of sub class
overrides (hides)the instance variable of super class as a result inside the sub class only the
instance variable of sub class is accessed but not super class

class A

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

public int x=10;

class B extends A

public int x=20;

public void showvalues()

System.out.print(―\n x=‖+x);

System.out.print(―\n x=‖+x);

class Override1

public static void main(String args[])

B b=new B();

b.showvalues();

Output:

X=20

X=20

Drawback of overriding:
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

When super class variable and sub class variable have the same name then inside the
subclass only instance variables of subclass is accessed but not super

Solution for overriding is super keyword:

In java super keyword can be used to access the super class instance variables in the sub
class explicitly when the super and sub classes variables have same name

Syntax:

Super.instancevariable

Solution for the above code:

class A

public int x=10;

class B extends A

public int x=20;

public void showvalues()

System.out.print(―\n x=‖+super.x);

System.out.print(―\n x=‖+x);

class Super1

public static void main(String args[])

{
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

B b=new B();

b.showvalues();

Output:

X=10

X=20

Method overriding:

If the methods of super class and sub class have the same name along with their
signatures then it is said to be method overriding i.e method of sub class overrides or hides the
method of super class as a result inside the sub class only method of sub class is accessed but not
super class.

Example:

class A

Public void show()

System.out.println(―show of A class‖);

class B extends A

public void show()

System.out.println(―show of B class‖);

}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

public void display()

show();

show();

class Overrides2

public static void main(String args[])

B b=new B();

b.display();

Output:

Show of B class

Show of B class

Drawback of method overriding:

If the method of super and sub class have the same name then inside the subclass only method of
subclass only method of subclass is called but not the super class.

Solution for method overriding is super keyword

In java super key word is used to access the super class methods explicitly in the sub class when
super and the sub classes methods have the same name.

Syntax:
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

super.methodname([arg1,arg2,…]);

Solution for the above code :

class A

public void show()

System.out.println(―show of A class‖);

class B extends A

public void show()

System.out.println(―show of B class‖);

public void display()

super.Show();

show();

class Overrides2

public static void main(String args[])


Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

B b=new B();

b.display();

Output:

Show of A class

Show of B class

Dynamic Method Dispatch or Dynamic binding:

In java a method call can be bound to the actual function either at compile time or at
run time

Binding of method call to the called method if takes place at compile time then it is
known as compile time binding or early binding or static binding

Compile time binding is an example of compile time polymorphism.

Example:

Method overloading

Binding of method call with called method it takes ar runtime then it is known as runtime
binding or late binding or dynamic binding runtime binding is an example of runtime
polymorphism.

Example:

Method Overriding.

Runtime polymorphism allows to postpone the decisions of selecting the suitable


method until runtime.

If the methods of super class and subclass are having the same name along with their
signature it is said to be method overriding

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

When the methods are overriding and the super class reference points variable points to
the subclass object in this case if an overridden method is called using the super class reference
variable then the method of subclass is called but not the super class

 This happens so because the jvm checks the reference variable to which class object it
is pointing based on that it selects the method for execution as the reference variable is having
the reference of subclass object therefore it calls the method of sub class this is how runtime
binding is achieved

Dynamic method dispatch is important because this is how java implements runtime
polymorphism

A program on dynamic method dispatch:

package day1;
import java.io.*;
import java.lang.*;
public class D
{
public static void main(String args[])
{
A obja=new A();
B objb=new B();
C objc=new C();
A r;
r=obja;
r.show();
r=objb;
r.show();
r=objc;
r.show();
}
}
class A
{
public void show()
{
System.out.println("show of a");
}
}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

class B extends A
{
public void show()
{
System.out.println("show of b");
}
}
class C extends B
{
public void show()
{
System.out.println("show of c");
}}

Output:

show of a
show of b
show of c

Explanation with memory allocation

obja 1001 objb 2001 objc 3001

1001 2001 3001


A show() A show() A show()
B show() B show()
C show()

r 1001 2001 3001 memory

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Java 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 and it may be created with any access specifier. However,
specifying access specifier is optional.

Following is the syntax for creating methods in java.


Syntax:

class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

 The methodName must begin with an alphabet, and the Lower-case letter is preferred.

 The methodName must follow all naming rules.

 If you don't want to pass parameters, we ignore it.

 If a method defined with return type other than void, it must contain the return statement,
otherwise, it may be ignored.

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.

Synatx:

<objectName>.<methodName>( actualArguments );

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Parameter Passing :
Recursion:
Java supports recursion. Recursion is the process of defining something in terms of itself. As it
relates to java programming, recursion is the attribute that allows a method to call itself. A
method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The factorial of
a number N is the product of all the whole numbers between 1 and N. for example, 3 factorial is
1×2×3, or 6. Here is how a factorial can be computed by use of a recursive method.
package day3;

public class Recursion

{ public static void main(String args[])

{ int result;

Factorial f =new Factorial();

System.out.println("facorial of 5 is"+f.fact(5));

System.out.println("factorial of 6 is"+f.fact(6));
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

class Factorial

{ int fact(int n)

{ if(n==1)

return n;

else

return n*fact(n-1);

} } }

The output from this program is shown here:


facorial of 5 is120

factorial of 6 is720

for-each statement in java


The Java for-each statement was introduced since Java 5.0 version. It provides an approach to
traverse through an array or collection in Java. The for-each statement also known as enhanced
for statement. The for-each statement executes the block of statements for each element of the
given array or

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

collection.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Exploring String Class:


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.

In the background, the string values are organized as an array of a character data type.

The String class defined in the package java.lang package. The String class implements
Serializable, Comparable, and CharSequence interfaces.

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.

The String class defined in the package java.lang package. The String class implements
Serializable, Comparable, and CharSequence interfaces.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

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.

Let's look at the following example java code.

-> Memory allocation for strings is in string pool area for direct storing strings

Example:

String s1=‖hello‖

->Memory allocation is in area heap

Example:

String s2-new String(―hello‖);

== and equals :

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

== compares addresses

Equals compares data

Note1:

String s1=‖hello‖;

String s2=‖hello‖;

Above s1 and s2 strings both having common address

Note2:

String s2-new String(―hello‖);

String s3-new String(―hello‖);

Both strings are having different addresses

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

 �The String class constructor accepts both string and character array as an argument.

Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence of
char values.

No. Method Description

1 char charAt(int index) It returns char value for the


particular index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, It returns formatted string with


Object... args) given locale.

5 String substring(int beginIndex) It returns substring for given


begin index.

6 String substring(int beginIndex, int endIndex) It returns substring for given


begin index and end index.

7 boolean contains(CharSequence s) It returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence delimiter, It returns a joined string.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

CharSequence... elements)

9 static String join(CharSequence delimiter, It returns a joined string.


Iterable<? extends CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string


with the given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified


string.

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, CharSequence It replaces all occurrences of the


new) specified CharSequence.

15 static String equalsIgnoreCase(String another) It compares another string. It


doesn't check case.

16 String[] split(String regex) It returns a split string matching


regex.

17 String[] split(String regex, int limit) It returns a split string matching


regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value


index.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.

21 int indexOf(String substring) It returns the specified substring


index.

22 int indexOf(String substring, int fromIndex) It returns the specified substring


index starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase


using specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase


using specified locale.

27 String trim() It removes beginning and ending


spaces of this string.

28 static String valueOf(int value) It converts given type into string.


It is an overloaded method.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

STRING HANDLING FUNCTIONS:

If it is not in range following exception raised:

StringIndexOutOfBoundsException:

Internal implementation

public char charAt(int index) {

if ((index < 0) || (index >= value.length)) {

throw new StringIndexOutOfBoundsException(index);

return value[index];

Try following problem:

1.Print Characters Presented at Odd Positions by Using the charAt() Method

2. Counting Frequency of a character in a String by Using the charAt() Method

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

3. Counting the Number of Vowels in a String by Using the chatAt() Method

Java String length()

The Java String class length() method finds the length of a string. The length of the Java string is
the same as the Unicode code units of the string.

Java String format()

The java string format() method returns the formatted string by given locale, format and
arguments.

Java String substring()

The Java String class substring() method returns a part of the string.

We pass beginIndex and endIndex number position in the Java substring method where
beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex starts from 0,
whereas the endIndex starts from 1.

Parameters

startIndex : starting index is inclusive

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

endIndex : ending index is exclusive

Returns

specified string

of characters contained in a string is zero.

Signature

The signature or syntax of string isEmpty() method is given below:

public boolean isEmpty()

Returns

true if length is 0 otherwise false.

Java String equals()

The Java String class equals() method compares the two given strings based on the content of the
string. If any character is not matched, it returns false. If all characters are matched, it returns
true.

The String equals() method overrides the equals() method of the Object class.

Signature

publicboolean equals(Object anotherObject)

Parameter

anotherObject : another object, i.e., compared with this string.

Returns

true if characters of both strings are equal otherwise false.

Java String concat

The Java String class concat() method combines specified string at the end of this string. It
returns a combined string. It is like appending another string.

Signature

The signature of the string concat() method is given below:


Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

public String concat(String anotherString)

Parameter

anotherString : another string i.e., to be combined at the end of this string.

Returns

combined string

Java String replace()

The Java String class replace() method returns a string replacing all the old char or
CharSequence to new char or CharSequence.

Since JDK 1.5, a new replace() method is introduced that allows us to replace a sequence of char
values.

Signature

There are two types of replace() methods in Java String class.

public String replace(char oldChar, char newChar)

public String replace(CharSequence target, CharSequence replacement)

The second replace() method is added since JDK 1.5.

Parameters

oldChar : old character

newChar : new character

target : target sequence of characters

replacement : replacement sequence of characters

Returns

replaced string

Exception Throws

NullPointerException: if the replacement or target is equal to null

Java String split()


Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

The java string split() method splits this string against given regular expression and returns a
char array.

Signature

There are two signature for split() method in java string.

public String split(String regex)

and,

public String split(String regex, int limit)

Parameter

regex : regular expression to be applied on string.

limit : limit for the number of strings in array. If it is zero, it will returns all the strings matching
regex.

Returns

array of strings

ThrowsPatternSyntaxException if pattern for regular expression is


invalid

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Java String indexOf()


The Java String class indexOf() method returns the position of the first occurrence of the
specified character or string in a specified string.
Parameters
ch: It is a character value, e.g. 'a'
fromIndex: The index position from where the index of the char value or substring is returned.
substring: A substring to be searched in this string.
Returns
Index of the searched string or character.
Java String trim()
The Java String class trim() method eliminates leading and trailing spaces. The Unicode value
of space character is '\u0020'. The trim() method in Java string checks this Unicode value before
and after the string, if it exists then the method removes the spaces and returns the omitted string.
toLowerCase() and toLowerCase() and :

convert into lower and upper case letters based on a string

input provided:

Java String equalsIgnoreCase()

The Java String class equalsIgnoreCase() method compares the two given strings on the basis of
the content of the string irrespective of the case (lower and upper) of the string. It is just like the
equals() method but doesn't check the case sensitivity. If any character is not matched, it returns
false, else returns true.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Nested and Inner classes:

Java inner class or nested class is a class i.e. declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.

Additionally, it can access all the members of outer class including private data members and
methods.

Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

Before going to inner classes read following


Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

 We Can have more than one main classes in java but JVM choose one main class only

 We Can‘t create main method in inner classes

 We Can create static final abstract inner classes

 We Can create private public protected inner classes in java

Inner classes in java:

 Accessing private instance variables in inner class

 Creating object of inner class

 Create inner class object in a innerclass method

 Accessing private varible from outside class in inner class in java

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Accessing innerclass in innerclass1 with outer class:

Accessing two inner classes in another inner classes and that inner class will again access from main()
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES

 Can inner class extends non abstract class

 Can inner class extend abstract class

 can inner class implements interfae

 Can we extend one inner class with another inner class

 Can we extend inner class with outside of inner class

Types of Nested classes

There are two types of nested classes non-static and static nested classes. The non-static nested
classes are also known as inner classes.

 Non-static nested class (inner class)

 Member inner class

 Anonymous inner class

 Local inner class

 Static nested class

Java Member Inner class

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

A non-static class that is created inside a class but outside a method is called member inner class. It is also
known as a regular inner class. It can be declared with access modifiers like public, default, private, and
protected.

Syntax:

class Outer{

//code

class Inner{

//code

Java Member Inner Class Example

In this example, we are creating a msg() method in the member inner class that is accessing the private
data member of the outer class.

TestMemberOuter1.java

class TestMemberOuter1{

private int data=30;

class Inner{

void msg(){System.out.println("data is "+data);}

public static void main(String args[]){

TestMemberOuter1 obj=new TestMemberOuter1();

TestMemberOuter1.Inner in=obj.new Inner();

in.msg();

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Output:

data is 30

How to instantiate Member Inner class in Java?

An object or instance of a member's inner class always exists within an object of its outer class.
The new operator is used to create the object of member inner class with slightly different
syntax.

The general form of syntax to create an object of the member inner class is as follows:

Syntax:

OuterClassReference.new MemberInnerClassConstructor();

Example:

obj.new Inner();

Here, OuterClassReference is the reference of the outer class followed by a dot which is
followed by the new operator.

Internal working of Java member inner class

The java compiler creates two class files in the case of the inner class. The class file name of the
inner class is "Outer$Inner". If you want to instantiate the inner class, you must have to create
the instance of the outer class. In such a case, an instance of inner class is created inside the
instance of the outer class.

Java Anonymous inner class

Java anonymous inner class is an inner class without a name and for which only a single object is
created. An anonymous inner class can be useful when making an instance of an object with
certain "extras" such as overloading methods of a class or interface

Now let us do discuss the difference between regular class(normal classes) and Anonymous Inner
class

 A normal class can implement any number of interfaces but the anonymous inner class
can implement only one interface at a time.

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

 A regular class can extend a class and implement any number of interfaces
simultaneously. But anonymous Inner class can extend a class or can implement an
interface but not both at a time.

 For regular/normal class, we can write any number of constructors but we can‘t write any
constructor for anonymous Inner class because the anonymous class does not have any
name and while defining constructor class name and constructor name must be same.

 Like local classes, anonymous classes can capture variables; they have the same access to
local variables of the enclosing scope

In simple words, a class that has no name is known as an anonymous inner class in Java. It
should be used if you have to override a method of class or interface. Java Anonymous inner
class can be created in two ways:

 Class (may be abstract or concrete).

 Interface

Java anonymous inner class example using class

TestAnonymousInner.java

Internal working of given code

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Person p=new Person(){

void eat(){System.out.println("nice fruits");}

};

A class is created, but its name is decided by the compiler, which extends the Person class and
provides the implementation of the eat() method.

An object of the Anonymous class is created that is referred to by 'p,' a reference variable of
Person type.

Internal working of given code

Person p=new Person(){

void eat(){System.out.println("nice fruits");}

};

A class is created, but its name is decided by the compiler, which extends the Person class and
provides the implementation of the eat() method.

An object of the Anonymous class is created that is referred to by 'p,' a reference variable of
Person type.

Anonymous Inner Class example-2:

Anonymous inner classes are generic created via below listed two ways as follows:

 Class (may be abstract or concrete)

 Interface

Now let us take an example with which we will understand anonymous inner class, let us take a
simple program

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Output explanation:

In the above program, interface Age is created with getAge() method and x=21. Myclass is
written as an implementation class of Age interface. As done in Program, there is no need to
write a separate class Myclass. Instead, directly copy the code of Myclass into this parameter,
as shown here:

Age oj1 = new Age()

@Override

public void getAge()

System.out.print("Age is " + x);

};

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Here, an object to Age1 is not created but an object of Myclass is created and copied in the entire
class code as shown above. This is possible only with anonymous inner class. Such a class is
called ‗anonymous inner class‘, so here we call ‗Myclass‘ as anonymous inner class.

Types of Anonymous Inner Class

Based on declaration and behavior, there are 3 types of anonymous Inner classes:

 Anonymous Inner class that extends a class

 Anonymous Inner class that implements an interface

 Anonymous Inner class that defines inside method/constructor argument

Type 1: Anonymous Inner class that extends a class

We can have an anonymous inner class that extends a class. For example, we know that we can
create a thread by extending a Thread class. Suppose we need an immediate thread but we don‘t
want to create a class that extends Thread class all the time. With the help of this type of
Anonymous Inner class, we can define a ready thread.

Example:

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Type 2: Anonymous Inner class that implements an interface

We can also have an anonymous inner class that implements an interface. For example, we also
know that by implementing Runnable interface we can create a Thread. Here we use an
anonymous Inner class that implements an

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

interface.

Type 3: Anonymous Inner class that defines inside method/constructor argument

Anonymous inner classes in method/constructor arguments are often used in graphical user
interface (GUI) applications. To get you familiar with syntax lets have a look at the following
program that creates a thread using this type of Anonymous Inner class

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Java Local inner class

A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are
the inner classes that are defined inside a block. Generally, this block is a method body.
Sometimes this block can be a for loop, or an if clause. Local Inner classes are not a member of
any enclosing classes. They belong to the block they are defined within, due to which local inner
classes cannot have any access modifiers associated with them. However, they can be marked as
final or abstract. These classes have access to the fields of the class enclosing it.

If you want to invoke the methods of the local inner class, you must instantiate this class inside
the method.

Java local inner class example

LocalInner1.java

Example of local inner class with local variable

LocalInner2.java

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

Java static nested class:

A static class is a class that is created inside a class, is called a static nested class in Java. It
cannot access non-static data members and methods. It can be accessed by outer class name.

o It can access static data members of the outer class, including private.
o The static nested class cannot access non-static (instance) data members or

Java static nested class example with instance method

TestOuter2.java

Notes by M Shiva Kumar CSE DEPT


CMRCET JAVA UNIT-1 NOTES

In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of the Outer class because the nested class
is static and static properties, methods, or classes can be accessed without an object.

Java static nested class example with a static method

If you have the static member inside the static nested class, you don't need to create an instance
of the static nested class.

TestOuter2.java

--------------------------------------------------------UNIT-I END-------------------------------------------------------------

Notes by M Shiva Kumar CSE DEPT

You might also like