Final Unit-1 Notes
Final Unit-1 Notes
UNIT - I
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop
concepts, coping with complexity,
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,
exceptions, parameter passing, recursion, nested and inner classes, exploring string
class.
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?
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
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.
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.
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 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).
Encapsulation
Inheritance
Polymorphism
Abstraction
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.
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
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code. Most of
the syntaxes in java follow basic programming language C and object-oriented programming
concepts are similar to C++. In a java programming language, many complicated features like
pointers, operator overloading, structures, unions, etc. have been removed. One of the most
useful features is the garbage collector it makes java more simple.
Secure:
Java is said to be more secure programming language because it does not have pointers
concept, java provides a feature "applet" which can be embedded into a web application. The
applet in java does not allow access to other parts of the computer, which keeps away from
harmful programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java 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
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.
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
Interpreted
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.
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.
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.
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.
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
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.
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.
As shown in the above architecture diagram, the JVM is divided into three main subsystems:
ClassLoader Subsystem
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
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).
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.
Example:
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.
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
changes it to native code. This native code will be used directly for repeated method calls,
which improve the performance of the system.
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:
Code:comments
{
/* in main function
Code will going
*/
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
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.
We can make integer long by adding ‗l‗ or ‗L‗ at the end of the number.
Code:
package unit1;
}
}
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;
}
}
Output:
Area of circle is 366.436224
float values is 1.1
}}
output:
ch1 contains X
ch1 is now Y
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;
b is false
b is true
This is executed.
10 > 9 is true
These are built-in data types These are created by the users
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.
Syntax:
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,...;
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.
Let's look at the following example java program to illustrate instance variable in java.
Let's look at the following example java program to illustrate static variable in java.
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
.
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.
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
}
}
Code:
package unit1;
public class Instance
{
double r;
public double getArea()
{
double area=3.14*r*r;
return area;
}
}
package unit1;
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
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
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.
Syntax:
data_type array_name[ ] = new data_type[size];
(or)
data_type[ ] array_name = new data_type[size];
Creating an array
In the java programming language, an array must be created using new operator and with a
specific size. The size must be an integer value but not a byte, short, or long. We use the
following syntax to create an array.
Multidimensional Array:
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any 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.
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.
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.
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
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.
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
b= 3
c=9
d=3
e=18
f=2
g=0
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
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.
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.
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.
++ 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
<< >>
shift 6 left to right
>>>
< <=
> >= relational
7 left to right
type comparison
instanceof
==
equality 8 left to right
!=
= += -=
*= /= %=
&= ^= |= assignment 15 right to left
<<= >>= >>>=
Source: (Precedence.java)
package day3;
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;
} }
Output:
9
--
--
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 {
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES
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 {
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
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 {
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");
}
}
}
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 {
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
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
}
Example:
public class Test {
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.
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 {
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
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 {
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
Syntax:
The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
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 {
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 {
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(",");
}
}
}
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 {
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
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
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
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
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.
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;
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.
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
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.
f = i;
The output:
i is 1234
f is 1234.0
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
package day3;
import java.util.Scanner;
int a;
float b;
double e;
long l;
String d;
short s;
a=sc.nextInt();
System.out.println("a="+a);
System.out.println("enter string");
d=sc.next();
System.out.println("d="+d);
b=sc.nextFloat();
System.out.println("b="+b);
char g = sc.next().charAt(0);
System.out.println("g= "+g);
e=sc.nextDouble();
System.out.println("e="+e);
l=sc.nextLong();
System.out.println("l="+l);
s=sc.nextShort();
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES
System.out.println("s="+s);
Output of program:
a=1
enter string
shiva
d=shiva
1.1
b=1.1
Enter a character:
g= d
2.3
e=2.3
12345
l=12345
s=1
Java Classes
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.
Look at the following picture to understand the class and object concept
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>{
methods defination;
The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
Example:
Pen.java
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.
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
The objectName must follow all naming rules
programs:
student.java
Student.java
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
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
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.
class Student{
int id;
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES
String name;
111 0
222 cse 25
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if you Method is not provided by compiler in
don't have any constructor. any case.
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
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();
}
}
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[])
{
int d;
Addition a=new Addition();
d=a.disp();
}
}
output: 30
Code:
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.
class A{
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
}
}
//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.
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
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
}
}
The default modifier is more restrictive than protected. That is why there is compile time error.
}
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
}
Output:
11
11
11
}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES
}
Output:
11
12
13
System.out.println(y);
change();
System.out.println(y);
}
}
Output:
20
100
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
static
{
b = a * 4;
meth(42);
x = 42
a=3
b=1
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
Here is an example. Inside main( ), the static method callme( ) and the static
class StaticDemo {
class StaticByName {
StaticDemo.callme();
a = 42
b = 99
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers
to the current object.
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.
class Student10{
int id;
String name;
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.
Output111 shiva
222 kumar
this keyword can also be used to return the current class instance
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.
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
• Garbage collection is the process by which java programs perform automatic memory
management.
• 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();
}
}
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.
Example
In the above example, the Student class constructor is overloaded with two different constructors,
I.e., default and parameterized.
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.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
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:
Understanding Type
Let's understand the type of instance.
1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }
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
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:
the mechanism of deriving a new class from an old one is called inheritance
Super class or
Parent class
Derived class or
Child class
the inheritance allows subclasses to inherit all the variables and methods of their parent
class
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
Java does not directly implement multiple inheritance in java however this concept is
implemented using a
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.
public class A
{
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.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance. Multiple Inheritances is supported in C++.
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.
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-
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
{
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
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
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:
to prevent inheritance
to prevent overriding
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");
}
}
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);
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:
Single word:
int count ;
--
--
Two words:
int personName;
int numberOfPeople;
Ex:
----
---
class names:
class Person
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES
----
----
constants:
Method Overriding:
Overriding is the concept of hiding the super class By the member of subclass the member may
be instance variable or methods
2) Method 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
class B extends A
System.out.print(―\n x=‖+x);
System.out.print(―\n x=‖+x);
class Override1
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
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
class A
class B extends A
System.out.print(―\n x=‖+super.x);
System.out.print(―\n x=‖+x);
class Super1
{
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
System.out.println(―show of A class‖);
class B extends A
System.out.println(―show of B class‖);
}
Notes by M Shiva Kumar CSE DEPT
CMRCET JAVA UNIT-1 NOTES
show();
show();
class Overrides2
B b=new B();
b.display();
Output:
Show of B class
Show of B class
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.
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,…]);
class A
System.out.println(―show of A class‖);
class B extends A
System.out.println(―show of B class‖);
super.Show();
show();
class Overrides2
B b=new B();
b.display();
Output:
Show of A class
Show of B class
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
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.
If the methods of super class and subclass are having the same name along with their
signature it is said to be method overriding
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
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
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.
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
The methodName must begin with an alphabet, and the Lower-case letter is preferred.
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 );
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;
{ int result;
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);
} } }
factorial of 6 is720
collection.
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.
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.
-> Memory allocation for strings is in string pool area for direct storing strings
Example:
String s1=‖hello‖
Example:
== and equals :
== compares addresses
Note1:
String s1=‖hello‖;
String s2=‖hello‖;
Note2:
�The String class constructor accepts both string and character array as an argument.
CharSequence... elements)
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
StringIndexOutOfBoundsException:
Internal implementation
return value[index];
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.
The java string format() method returns the formatted string by given locale, format and
arguments.
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
Returns
specified string
Signature
Returns
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
Parameter
Returns
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
Parameter
Returns
combined string
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
Parameters
Returns
replaced string
Exception Throws
The java string split() method splits this string against given regular expression and returns a
char array.
Signature
and,
Parameter
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
input provided:
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.
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.
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.
We Can have more than one main classes in java but JVM choose one main class only
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
There are two types of nested classes non-static and static nested classes. The non-static nested
classes are also known as inner classes.
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
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{
class Inner{
in.msg();
Output:
data is 30
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.
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 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.
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:
Interface
TestAnonymousInner.java
};
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.
};
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 classes are generic created via below listed two ways as follows:
Interface
Now let us take an example with which we will understand anonymous inner class, let us take a
simple program
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:
@Override
};
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.
Based on declaration and behavior, there are 3 types of anonymous Inner classes:
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:
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
interface.
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
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.
LocalInner1.java
LocalInner2.java
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
TestOuter2.java
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.
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-------------------------------------------------------------