Java Unit-I Notes
Java Unit-I Notes
me/jntuh
OOP CONCEPTS
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every
program is follows the concept of object. In other words, OOP is a way of writing programs based on
the object concept.
The object-oriented programming paradigm has the following core concepts.
Class
Object
Encapsulation
Inheritance
Polymorphism
Abstraction
Class
Class is a blue print which is containing only list of variables and methods and no memory is allocated
for them. A class is a group of objects that has common properties.
Object
Any entity that has state and behavior is known as an object.
For example a chair, pen, table, keyboard, bike, etc. It can be physical or logical. An Object can
be defined as an instance of a class.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Encapsulation
Encapsulation is the process of combining data and code into a single unit.
In OOP, every object is associated with its data and code.
In programming, data is defined as variables and code is defined as methods.
The java programming language uses the class concept to implement encapsulation.
Inheritance
Inheritance is the process of acquiring properties and behaviors from one object to another
object or one class to another class.
In inheritance, we derive a new class from the existing class. Here, the new class acquires the
properties and behaviors from the existing class.
In the inheritance concept, the class which provides properties is called as parent class and the
class which recieves the properties is called as child class.
Person
name,
designation
learn(),
walk(),
eat()
Abstraction
Abstraction is hiding the internal details and showing only essential functionality.
In the abstraction concept, we do not show the actual implementation to the end user, instead
we provide only essential things.
For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system
works? etc.
To solve the problem, let me call zomato (an agent in food delevery community), tell them the
variety and quantity of food and the hotel name from which I wish to delever the food to my family
members. 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.
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.
-9223372036854775808 to
long 8 bytes 0L
+9223372036854775807
Note: Float data type can represent up to 7 digits accurately after decimal point.
Double data type can represent up to 15 digits accurately after decimal point.
Character Data Type
Character data type are represents a single character like a, P, &, *,..etc.
Minimum and Maximum
Data Type Memory Size Default Value
values
VARIABLES
Variable is a name given to a memory location where we can store different values of the same data
type during the program execution.
The following are the rules to specify a variable name...
A variable name may contain letters, digits and underscore symbol
Variable name should not start with digit.
Keywords should not be used as variable names.
Variable name should not contain any special symbols except underscore(_).
Variable name can be of any length but compiler considers only the first 31 characters of the
variable name.
Declaration of Variable
Declaration of a variable tells to the compiler to allocate required amount of memory with specified
variable name and allows only specified datatype values into that memory location.
Syntax: datatype variablename;
Example : int a;
Syntax : data_type variable_name_1, variable_name_2,...;
Example : int a, b;
Initialization of a variable:
Syntax: datatype variablename = value;
Example : int a = 10;
Syntax : data_type variable_name_1=value, variable_name_2 = value;
Example : int a = 10, b = 20;
Local Variables
Variables declared inside the methods or constructors or blocks are called as local variables.
The scope of local variables is within that particular method or constructor or block in which they
have been declared.
Local variables are allocated memory when the method or constructor or block in which they are
declared is invoked and memory is released after that particular method or constructor or block is
executed.
Access modifiers cannot be assigned to local variables.
It can’t be defined by a static keyword.
Local variables can be accessed directly with their name.
Program
class LocalVariables
{
public void show()
{
int a = 10;
[Link]("Inside show method, a = " + a);
}
public void display()
{
int b = 20;
[Link]("Inside display method, b = " + b);
//[Link]("Inside display method, a = " + a); // error
}
public static void main(String args[])
{
LocalVariables obj = new LocalVariables();
[Link]();
[Link]();
}
}
Instance Variables:
Variables declared outside the methods or constructors or blocks but inside the class are called
as instance variables.
The scope of instance variables is inside the class and therefore all methods, constructors and
blocks can access them.
Instance variables are allocated memory during object creation and memory is released during
object destruction. If no object is created, then no memory is allocated.
For each object, a separate copy of instance variable is created.
Heap memory is allocated for storing instance variables.
Access modifiers can be assigned to instance variables.
It is the responsibility of the JVM to assign default value to the instance variables as per the type of
Variable.
Instance variables can be called directly inside the instance area.
Instance variables cannot be called directly inside the static area and necessarily requires an object
reference for calling them.
Program
class InstanceVariable
{
int x = 100;
public void show()
{
[Link]("Inside show method, x = " + x);
x = x + 100;
}
public void display()
{
[Link]("Inside display method, x = " + x);
}
public static void main(String args[])
{
ClassVariables obj = new ClassVariables();
[Link]();
[Link]();
}
}
Static variables
Static variables are also known as class variable.
Static variables are declared with the keyword ‘static ‘ .
A static variable is a variable whose single copy in memory is shared by all the objects, any
modification to it will also effect other objects.
Static keyword in java is used for memory management, i.e it saves memory.
Static variables gets memory only once in the class area at the time of class loading.
Static variables can be invoked without the need for creating an instance of a class.
Static variables contain values by default. For integers, the default value is 0. For Booleans, it is
false. And for object references, it is null.
Syntax: static datatype variable name;
Example: static int x=100;
Syntax: [Link];
Example
class Employee
{
static int empid=500;
static void emp1()
{
empid++;
[Link]("Employee id:"+empid);
}
}
class Sample
{
public static void main(String args[])
{
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
}
}
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
Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays.
To create a multidimensional array variable, specify each additional index using another set of
square brackets.
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
When an array is initialized at the time of declaration, it need not specify the size of the array and
use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Example
class Twodarray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
[Link](arr[i][j]+" ");
}
[Link]();
}
}
}
OPERATORS
An operator is a symbol that performs an operation. An operator acts on some variables called
operands to get the desired result.
Example: a+b
Here a, b are operands and + is operator.
Types of Operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
7. Bit wise operators
1. Arithmetic Operators: Arithmetic Operators are used for mathematical calculations.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
2. Relational Operators: Relational operators are used to compare two values and return a true or
false result based upon that comparison. Relational operators are of 6 types
Operator Description
1. Logical AND (&&) : Logical AND is denoted by double ampersand characters (&&).it is used to
check the combinations of more than one conditions. if any one condition false the complete condition
becomes false.
Truth table of Logical AND
Condition1 Condition2 Condition1 && Condition2
True True True
True False False
False True False
False False False
2. Logical OR ( || ) : Logical OR is denoted by double pipe characters (||). it is used to check the
combinations of more than one conditions. if any one condition true the complete condition becomes
true.
Truth table of Logical OR
Condition1 Condition2 Condition1 && Condition2
True True True
True False True
False True True
False False False
3. Logician NOT (!): Logical NOT is denoted by exclamatory characters (!), it is used to check the
opposite result of any given test condition. i.e, it makes a true condition false and false condition true.
Truth table of Logical NOT
Condition1 !Condition2
True False
False True
4. Assignment Operator: Assignment operators are used to assign a value (or) an expression (or) a
value of a variable to another variable.
Syntax : variable name=expression (or) value
Example : x=10;
y=20;
The following list of Assignment operators are.
5: Increment And Decrement Operators : The increment and decrement operators are very
useful. ++ and == are called increment and decrement operators used to add or subtract. Both are
unary operators.
The syntax of the operators is given below.
These operators in two forms : prefix (++x) and postfix(x++).
++<variable name> --<variable name>
<variable name>++ <variable name>--
Operator Meaning
6 : Conditional Operator: A conditional operator checks the condition and executes the statement
depending on the condition. Conditional operator consists of two symbols.
1 : question mark (?).
2 : colon ( : ).
Syntax: condition ? exp1 : exp2;
It first evaluate the condition, if it is true (non-zero) then the “exp1” is evaluated, if the condition is
false (zero) then the “exp2” is evaluated.
Example :
class ConditionalOperator
{
public static void main(String[] args)
{
int februaryDays = 29;
String result;
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
[Link](result);
}
}
7. Bitwise Operators:
Bitwise operators are used for manipulating a data at the bit level, also called as bit level
programming. Bit-level programming mainly consists of 0 and 1.
They are used in numerical Computations to make the calculation process faster.
The bitwise logical operators work on the data bit by bit.
Starting from the least significant bit, i.e. LSB bit which is the rightmost bit, working towards the
MSB (Most Significant Bit) which is the leftmost bit.
A list of Bitwise operators as follows…
Operator Meaning
0 0 0
0 1 0
1 0 0
1 1 1
0 0 0
0 1 1
1 0 1
1 1 1
EXPRESSIONS
In any programming language, if we want to perform any calculation or to frame any condition
etc., we use a set of symbols to perform the task. These set of symbols makes an expression.
In the java programming language, an expression is defined as follows..
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.
Infix Expression
Postfix Expression
Prefix Expression
The above classification is based on the operator position in the expression.
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
a+b
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example
ab+
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
+ab
CONTROL STATEMENTS
In java, the default execution flow of a program is a sequential order.
But the sequential order of execution flow may not be suitable for all situations.
Sometimes, we may want to jump from line to another line, we may want to skip a part of the
program, or sometimes we may want to execute a part of the program again and again.
To solve this problem, java provides control statements.
Types of Control Statements
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements
based on that condition result.
The if statement checks, the given condition then decides the execution of a block of statements. If
the condition is True, then the block of statements is executed and if it is False, then the block of
statements is ignored.
Syntax
if(condtion)
{
if-block of statements;
}
statement after if-block;
Example
public class IfStatementTest
{
public static void main(String[] args)
{
int x=10;
if(x>0)
x++;
[Link]("x value is:"+x);
}
}
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the
condition is evaluated to False. Then the if statement ignores the execution of its block of statements.
if-else statement in java
In java, we use the if-else statement to test a condition and pick the execution of a block of
statements out of two blocks based on that condition result.
The if-else statement checks the given condition then decides which block of statements to be
executed based on the condition result.
If the condition is True, then the true block of statements is executed and if it is False, then the false
block of statements is executed.
Syntax
if(condtion)
{
true-block of statements;
}
else
{
false-block of statements;
}
statement after if-block;
Example
public class IfElseStatementTest
{
public static void main(String[] args)
{
int a=29;
if(a % 2==0)
[Link]("Even Number is :"+a);
else
[Link]("Odd Number is :"+a);
}
}
Nested if statement in java
Writing an if statement inside another if-statement is called nested if statement.
Syntax
if(condition_1)
{
if(condition_2)
{
inner if-block of statements;
...
}
...
}
Example
public class NestedIfStatementTest
{
public static void main(String[] args)
{
int num=1;
if(num<10)
{
if(num==1)
{
[Link]("The value is equal to 1);
}
else
{
[Link]("The value is greater than 1");
}
}
else
{
[Link]("The value is greater than 10");
}
[Link]("Nested if - else statement ");
}
}
Switch
Using the switch statement, one can select only one option from more number of options very
easily.
In the switch statement, we provide a value that is to be compared with a value associated with
each option. Whenever the given value matches the value associated with an option, the execution
starts from that option.
In the switch statement, every option is defined as a case.
Syntax:
switch (expression)
{
case value1: // statement sequence
break;
case value2: // statement sequence
break;
….
case valueN:
}
Example
class SampleSwitch
{
public static void main(String args[])
{
char color ='g';
switch(color )
{
case 'r':
[Link]("RED") ; break ;
case 'g':
[Link]("GREEN") ; break ;
case 'b':
[Link]("BLUE") ; break ;
case 'w':
[Link]("WHITE") ; break ;
default:
[Link]("No color") ;
}
}
}
[Link] Statements
The java programming language provides a set of iterative statements that are used to execute a
statement or a block of statements repeatedly as long as the given condition is true.
The iterative statements are also known as looping statements or repetitive statements. Java
provides the following iterative statements.
[Link] statement
[Link]-while statement
3. for statement
4. for-each statement
while statement in java
The while statement is used to execute a single statement or block of statements repeatedly as long as
the given condition is TRUE. The while statement is also known as Entry control looping statement.
Syntax
while(condition)
{
// body of loop
}
Example
public class WhileTest
{
public static void main(String[] args)
{
int num = 1;
while(num <= 10)
{
[Link](num);
num++;
}
[Link]("Statement after while!");
}
}
do-while statement in java
The do-while statement is used to execute a single statement or block of statements repeatedly
as long as given the condition is TRUE.
The do-while statement is also known as the Exit control looping statement.
Syntax
do
{
// body of loop
} while (condition);
Example
public class DoWhileTest
{
public static void main(String[] args)
{
int num = 1;
do
{
[Link](num);
num++;
}while(num <= 10);
[Link]("Statement after do-while!");
}
}
for statement in java
The for statement is used to execute a single statement or a block of statements repeatedly as long as
the given condition is TRUE.
Syntax
for(initialization; condition; inc/dec)
{
// body
}
If only one statement is being repeated, there is no need for the curly braces.
In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement. After the block of statements execution,
the modification statement gets executed, followed by condition again.
Example
public class ForTest
{
public static void main(String[] args)
{
for(int i = 0; i < 10; i++)
{
[Link]("i = " + i);
}
[Link]("Statement after for!");
}
}
3. Jump Statements
The java programming language supports jump statements that used to transfer execution control
from one line to another line.
The java programming language provides the following jump statements.
1. break statement
2. continue statement
break
When a break statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop.
Example
class BreakStatement
{
public static void main(String args[] )
{
int i;
i=1;
while(true)
{
if(i >10)
break;
[Link](i+" ");
i++;
}
}
}
Continue
This command skips the whole body of the loop and executes the loop with the next iteration. On
finding continue command, control leaves the rest of the statements in the loop and goes back to the
top of the loop to execute it with the next iteration (value).
Example
/* Print Number from 1 to 10 Except 5 */
class NumberExcept
{
public static void main(String args[] )
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
continue;
[Link](i +" ");
}
}
}
Output
Before conversion: 166.66
After conversion into int type: 166
Type Conversion
If a data type is automatically converted into another data type at compile time is known as type
conversion.
The conversion is performed by the compiler if both data types are compatible with each other.
Remember that the destination data type should not be smaller than the source type.
It is also known as widening conversion of the data type.
Example
int a = 20;
Float b;
b = a; // Now the value of variable b is 20.000
Program
Output :
After conversion, the float value is: 7.0
Documentation Section
The documentation section is an important section but optional for a Java program.
It includes basic information about a Java program. The information includes the author's name,
date of creation, version, program name, company name, and description of the program. It
improves the readability of the program. Whatever we write in the documentation section, the Java
compiler ignores the statements during the execution of the program. To write the statements in the
documentation section, we use comments.
Comments there are three types
1. Single-line Comment: It starts with a pair of forwarding slash (//).
Example : //First Java Program
2. Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
Example : /* It is an example of
multiline comment */
3. Documentation Comment: It starts with the delimiter (/**) and ends with */.
SAMPLE JAVA PROGRAM
/* This is First Java Program */
Class sample
{
public static void main(String args[])
{
[Link](“Hello Java Programming”);
}
}
WHAT IS JVM
Java Virtual Machine is the heart of entire java program execution process. It is responsible for taking
the .class file and converting each byte code instruction into the machine language instruction that can
be executed by the microprocessor.
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are
used to represent real-world concepts and entities.
classes usually consist of two things: instance variables and methods.
The class represents a group of objects having similar properties and behavior.
For example, the animal type Dog is a class while a particular dog named Tommy is an object of
the Dog class.
It is a user-defined blueprint or prototype from which objects are created. For example, Student is
a class while a particular student named Ravi is an object.
The java class is a template 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.
Class 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.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects
are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
Data member
Method
Constructor
Nested Class
Interface
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as variables and
behaviors as methods.
Syntax
class className
{
data members declaration;
methods definition;
}
The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
The ClassName must follow all naming rules.
Example
Here is a class called Box that defines three instance variables: width, height, and depth.
class Box
{
double width;
double height;
double depth;
void volume()
{
………………….
}
}
OBJECT
In java, an object is an instance of a class.
Objects are the instances of a class that are created to use the attributes and methods of a class.
All the objects that are created using a single class have the same properties and methods. But the
value of properties is different for every object.
Syntax
ClassName objectName = new ClassName( );
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
The objectName must follow all naming rules.
Example
Box mybox = new Box();
The new operator dynamically allocates memory for an object.
Example
class Box
{
double width;
double height;
double depth;
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
[Link] = 10;
[Link] = 20;
[Link] = 15;
vol = [Link] * [Link] * [Link];
[Link]("Volume is " + vol);
}
}
METHODS
A method is a block of statements under a name that gets executes only when it is called.
Every method is used to perform a specific task. The major advantage of methods is code re-
usability (define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That means, every
method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.
returnType - Specifies the data type of a return value.
name - Specifies a unique name to identify it.
parameters - The data values it may accept or recieve.
{ } - Defienes the block belongs to the method.
Creating a method
A method is created inside the class
Syntax
class ClassName
{
returnType methodName( parameters )
{
// body of method
}
}
Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a dot
operator.
It may call directly if the method defined with the static modifier.
Every method call must be made, as to the method name with parentheses (), and it must
terminate with a semicolon.
Syntax
[Link](actualArguments );
Example
//Adding a Method to the Box Class
Class Box
{
double width, height, depth;
void volume()
{
[Link]("Volume is ");
[Link](width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link] = 3;
[Link] = 6;
[Link] = 9;
[Link]();
[Link]();
}
}
CONSTRUCTORS
Constructor in Java is a special member method which will be called automatically by the JVM
whenever an object is created for placing user defined values in place of default values.
In a single word constructor is a special member method which will be called automatically
whenever object is created.
The purpose of constructor is to initialize an object called object initialization. Initialization is a
process of assigning user defined values at the time of allocation of memory space.
Syntax
ClassName()
{
.......
.......
}
Types Of Constructors
Based on creating objects in Java constructor are classified in two types. They are
1. Default or no argument Constructor
2. Parameterized constructor
1. Default Constructor
A constructor is said to be default constructor if and only if it never take any parameters.
If any class does not contain at least one user defined constructor then the system will create a
default constructor at the time of compilation it is known as system defined default constructor.
Note: System defined default constructor is created by java compiler and does not have any statement
in the body part. This constructor will be executed every time whenever an object is created if that
class does not contain any user defined constructor.
Example
class Test
{
int a, b;
Test()
{
a=10;
b=20;
[Link]("Value of a: "+a);
[Link]("Value of b: "+b);
}
}
class TestDemo
{
public static void main(String args[])
{
Test t1=new Test();
}
}
2. Parameterized Constructor
If any constructor contain list of variables in its signature is known as paremetrized constructor. A
parameterized constructor is one which takes some parameters.
Example
class Test
{
int a, b;
Test(int n1, int n2)
{
a=n1;
b=n2;
[Link]("Value of a = "+a);
[Link]("Value of b = "+b);
}
}
class TestDemo
{
public static void main(String args[])
{
Test t1=new Test(10, 20);
}
}
//save by [Link]
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
[Link](); //Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
2. Private
The private access modifier is accessible only within the class.
The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in which
they are declared.
Any other class of the same package will not be able to access these members.
Top-level classes or interfaces can not be declared as private because private means “only visible
within the enclosing class”.
Example
In this example, we have created two classes A and Simple.
A class contains private data member and private method.
We are accessing these private members from outside the class, so there is a compile-time error.
class A
{
private int data=40;
private void msg()
{
[Link]("Hello java");}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
[Link]([Link]); //Compile Time Error
[Link](); //Compile Time Error
}
}
3. Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier is specified using the keyword protected.
Example
In this example, we have created the two packages pack and mypack.
The A class of pack package is public, so can be accessed from outside the package.
But msg method of this package is declared as protected, so it can be accessed from outside the
class only through inheritance.
//save by [Link]
package pack;
public class A
{
protected void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
[Link]();
}
}
4. Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
The public access modifier is specified using the keyword public.
Example
//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
3. By anonymous object:
1. new Employee();
OVERLOADING CONSTRUCTORS
Constructor overloading is a concept of having more than one constructor with different parameters
list, so that each constructor performs a different task.
Example
METHOD 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).
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.
Example
class Dog
{
private void eat(){[Link]("dog is eating...");}
public static void main(String args[])
{
Dog d1=new Dog();
[Link]();
}
}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example
class Animal
{
void eat()
{
[Link]("animal is eating...");
}
}
class Dog extends Animal
{
void eat()
{
[Link]("dog is eating...");
}
public static void main(String args[])
{
Animal a=new Dog();
[Link]();
}
}
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.
Call-by-Reference
call by reference" is a method of passing arguments to functions or methods where the memory
address (or reference) of the variable is passed rather than the value itself. This means that changes
made to the formal parameter within the function affect the actual parameter in the calling
environment.
In "call by reference," when a reference to a variable is passed, any modifications made to the
parameter inside the function are transmitted back to the caller. This is because the formal parameter
receives a reference (or pointer) to the actual data.
Example
class CallByReference
{
int a,b;
CallByReference(int x,int y)
{
a=x;
b=y;
}
void changeValue(CallByReference obj)
{
obj.a+=10;
obj.b+=20;
}
}
public class CallByReferenceExample
{
public static void main(String[] args)
{
CallByReference object=new CallByReference(10, 20);
[Link]("Value of a: "+object.a +" & b: " +object.b);
[Link](object);
[Link]("Value of a:"+object.a+ " & b: "+object.b);
}
}
Output:
Value of a: 10 & b: 20
Value of a: 20 & b: 40
RECURSION IN JAVA
Recursion in java is a process in which a method calls itself continuously. A method in java that calls
itself is called recursive method. It makes the code compact but complex to understand.
Syntax:
returntype methodname()
{
methodname();
}
Example
public class RecursionExample3
{
static int factorial(int n)
{
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args)
{
[Link]("Factorial of 5 is: "+factorial(5));
}
}
INNER CLASSES
Inner class means one class which is a member of another class.
We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
Syntax of Inner class
class Outer_class
{
//code
class Inner_class
{
//code
}
}
Types of Inner classes
There are four types of inner classes.
1. Member Inner class
2. Local inner classes
3. Anonymous inner classes
4. Static nested classes
1. MEMBER INNER CLASS
A non-static class that is created inside a class but outside a method is called member inner class.
Syntax:
class Outer
{
//code
class Inner
{
//code
}
}
Example
class TestMemberOuter
{
private int data=30;
class Inner
{
void msg()
{
[Link]("data is "+data);
}
}
public static void main(String args[])
{
TestMemberOuter obj=new TestMemberOuter();
[Link] in=[Link] Inner();
[Link]();
}
}
2. ANONYMOUS INNER CLASS
In Java, a class can contain another class known as nested class. It's possible to create a nested
class without giving any name.
A nested class that doesn't have any name is known as an anonymous class.
An anonymous class must be defined inside another class. Hence, it is also known as an
anonymous inner class.
Example
abstract class Person
{
abstract void eat();
}
class TestAnonymousInner
{
public static void main(String args[])
{
Person p=new Person()
{
void eat()
{
[Link]("nice fruits");
}
};
[Link]();
}
}
1. 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.
2. An object of the Anonymous class is created that is referred to by 'p,' a reference variable of Person
type.
3. LOCAL INNER CLASS
A class i.e. created inside a method is called local inner class in java.
If you want to invoke the methods of local inner class, you must instantiate this class inside the
method.
Example
public class localInner
{
private int data=30;
void display()
{
class Local
{
void msg()
{
[Link](data);
}
}
Local l=new Local();
[Link]();
}
public static void main(String args[])
{
localInner obj=new localInner();
[Link]();
}
}
Example
public class JavaStringExample
{
public static void main(String[] args)
{
String title = "Java Programming";
String siteName = "String Handling Methods";
[Link]("Length of title: " + [Link]());
[Link]("Char at index 3: " + [Link](3));
[Link]("Index of 'T': " + [Link]('T'));
[Link]("Empty: " + [Link]());
[Link]("Equals: " + [Link](title));
[Link]("Sub-string: " + [Link](9, 14));
[Link]("Upper case: " + [Link]());
}
}