0% found this document useful (0 votes)
11 views43 pages

Introduction to Java Programming Basics

Java is an object-oriented programming language developed by Sun Microsystems and released in 1995, known for its versatility in app development, desktop computing, and gaming. The document covers the history of Java, variable declaration, data types, control flow statements, loops, and the concept of classes and objects. It provides syntax examples and explanations for various programming constructs in Java.

Uploaded by

santhosh t
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views43 pages

Introduction to Java Programming Basics

Java is an object-oriented programming language developed by Sun Microsystems and released in 1995, known for its versatility in app development, desktop computing, and gaming. The document covers the history of Java, variable declaration, data types, control flow statements, loops, and the concept of classes and objects. It provides syntax examples and explanations for various programming constructs in Java.

Uploaded by

santhosh t
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit-I

1.1Introduction:
 Java is an Object-oriented Programming language originally developed by Sun Micro
System and released in 1995, later acquired by Oracle.
 Java is a popular and powerful language used in app development, desktop computing,
and gaming. It was created by James Gosling, Mike Sheridan, and Patrick Naughton.
 Java was developed as a part of the Green project. Initially, it was called Oak, later it was
changed to Java in 1995.
 Java was created based on C and C++. Java uses C syntax and many of the object-oriented
features are taken from C++.

1.2History of Java:
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
 Originally designed for small, embedded systems in electronic appliances like set-top
boxes.
 Firstly, it was called “Greentalk” by James Gosling, and file extension was .gt.
 After that, it was called Oak and was developed as a part of the Green project. In 1995,
Oak was renamed as “Java” because it was already a trademark by Oak Technologies.
 Java is an island of Indonesia It is famous for its coffee beans

1.3 VARIABLES
Variable is a symbolic name refer to a memory location used to store values that can change during the
execution of a program.

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


Syntax:
data_typevariable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_typevariable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;

Example:

Avariable declaration involves specifying the type (data type), name (identifier), and value(literal)
according to the type of the variable.

1.4 DATA TYPES :


Java programming language has a rich set of data types. The data type is a category of data stored in
variables. In java, data types are classified into two types and they are as follows.

 Primitive Data Types


 Non-primitive Data Types
Primitive Data Types
The primitive data types are built-in data types and they specify the type of value stored in a variable and
the memory size. The primitive data types do not have any additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.
The following table provides more description of each primitive data type.
Default
Data type Meaning Memory size Range
Value
Whole
Byte 1 byte -128 to +127 0
numbers
Whole
short 2 bytes -32768 to +32767 0
numbers
Whole
Int 4 bytes -2,147,483,648 to +2,147,483,647 0
numbers
Whole -9,223,372,036,854,775,808 to
Long 8 bytes 0
numbers +9,223,372,036,854,775,807
Fractional
Float 4 bytes - 0.0
numbers
Fractional
double 8 bytes - 0.0
numbers
Single
Char 2 bytes 0 to 65535 blank
character
unsigned
boolean 1 bit 0 or 1 0 (false)
char

class PrimitiveDt
{
public static void main(String args[])
{
[Link]("Size of byte is " + [Link] + " bits");
[Link]("Size of short is " + [Link] + " bits");
[Link]("Size of int is " + [Link]+ " bits");
[Link]("Size of long is " + [Link]+ " bits");
[Link]("Size of float is " + [Link]+ " bits");
[Link]("Size of double is " + [Link]+ " bits");
[Link]("Size of char is " + [Link]+ " bits");
}
}
 To find and print size of any primitive data type we take help of its associated wrapper
class.
 Inside each wrapper class (Except Boolean type) there is SIZE property, which returns
amount of memory being allocated for that specific type of data in bits.
1.5. FLOW OF CONTROL
Control flow statements help programmers make decisions about which statements to execute
and to change the flow of execution in a program.
The categories of control flow statements available in Java are
 Conditional
Statements
 Loops
 Branch Statements

1.5.1 Conditional Statements


In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed
based on a condition. Java provides the following selection statements.

 if statement
 if-else statement
 if-else if statement
 switch statement

[Link] if statement
It consists only true part, If the condition is True, then the block of statements is executed.
Syntax:
if(condition)
{
-------
------- //Block of Statements
}
Example Program:
class If
{
public static void main(String args[])
{
if(20>18)
[Link]("20 is greater than 18");
}
}

[Link] if…else statement


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(condition)
{
------- //Block of Statements
}
else
{
------- //Block of Statements
}

Example Program:

class Ifelse
{
public static void main(String
args[])
{
if(18>20)
[Link]("18 is greater than 20");
else
[Link]("18 is less than 20");
}
}
[Link] if else if statement
Writing an if-statement inside else of an if statement is called if-else-if statement.

Syntax:
if(condition)
{
------- //Block of Statements
}
else if(condition)
{
------- //Block of Statements
}
else
{
------- //Block of Statements
}
Example Program:
class Ifelseif
{
public static void main(String args[])
{
int x=20, y=18, z=22;
if(x>y && x>z)
{
[Link]("Largest Number is "+x);
}
else if(y>z)
{
[Link]("Largest Number is "+y);
}
else
{
[Link]("Largest Number is "+z);
}
}
}
[Link] Switch statement
Java has a shorthand for multiple if statement-the switch statement. Using the switch statement,
one can select only one option from more number of options very easily.

Syntax:
switch(condition or value)
{
case value1: statement 1;
break;
case value2: statement 2;
break;
.
.
default: statement n;
}

Example Program:

class SwitchCaseDemo
{
public static void main(String args[])
{
char c='B';
switch(c)
{
case 'A':[Link]("You entered Sunday");
break;
case 'B':[Link]("You entered Monday");
break;
case 'C':[Link]("You entered Tuesday");
break;
case 'D':[Link]("You entered Wednesday");
break;
case 'E':[Link]("You entered Thursday");
break;
case 'F':[Link]("You entered Friday");
break;
case 'G':[Link]("You entered Saturday");
break;
default:[Link]("Wrong choice");
}
}
}
1.5.2 Loops
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.
 while statement
 do-while statement
 for statement
 for-each statement
[Link] for Loop
The for statement is used to execute a single statement or a block of statements repeatedly as
long as the given condition is TRUE. To execute a code for a known number of times, for loop is
the right choice.
The for loop groups the following three common parts together into one statement:
(a) Initialization
(b) Condition
(c) Increment or decrement
Syntax:
for(initialization;Condition;Inc/Dec)
{
-------
------- //Block of Statements
}

Example :

Example Program 1:

class ForDemo
{
public static void main(String args[])
{
for(int i=1; i<=5; i++)
{
[Link]("Square of "+i+" is "+ (i*i));
}
}
}
Example Program 2:

class ForLoop
{
public static void main(String args[])
{
for(int i=0; i<=10; i++)
{
[Link]("i= "+i);
}
}
}

[Link] while Loop


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)
{
-------
------- //Block of Statements
}

Example Program 1:

class WhileDemo
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
[Link]("i= "+i);
i++;
}
}
}
Example Program 2:

class While
{
public static void main(String args[])
{
int i = 1;
while(i<=5)
{
[Link]("Square of " +i+ " is " +(i*i));
i++;
}
}
}

[Link] do-while Loop


A do-while loop is also used to repeatedly execute (iterate) a block of statements. But, in a do-while
loop the condition is evaluated at the end of the iteration. The do-while statement is also known as
the Exit control looping statement.

Syntax:
do
{
-------
------- //Block of Statements
}while(Condition);
Example Program 1:

class DoWhileDemo
{
public static void main(String args[])
{
int i = 1;
do
{
[Link]("Square of " +i+ " is " +(i*i));
i++;
}while(i<=5);
}
}
Example Program 2:

class DoWhile
{
public static void main(String args[])
{
int i=1;
do
{
[Link]("i= "+i);
i++;
}while(i<=10);
}
}

[Link] for-each Loop


The Java for-each statement was introduced since Java 5.0 version. It provides an approach to traverse
through an array or collection in Java. The for-each statement also known as enhanced
for statement.
This loop is used to access each value successively in a collection of values (like array).

Syntax:
for(datatype Variablename : Array)
{
-------
------- //Block of Statements
}
Example Program

class Foreach
{
public static void main(String args[])
{
int arr[]={10,20,30,40,50};
for(int i : arr)
{
[Link]("i= "+i);
}
}
}

1.5.3 Branching Mechanism


The java programming language supports jump statements that used to transfer execution control from
one line to another line.
Two types of branching statements are available in Java—break and continue.

[Link] break Statement


The break statement in java is used to terminate a switch or looping statement. That means the break
statement is used to come out of a switch statement and a looping statement like while, do-while, for,
and for-each.
Example Program 1:

class Break
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
{
break;
}
[Link]("i = "+i);
}
}
}

Example Program 2:

class BreakWhile
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
if(i==4)
{
break;
}
[Link]("i = "+i);
i++;
}
}
}
Example Program 3:

class Breakforeach
{
public static void main(String args[])
{
int numbers[] = {10, 20, 30, 40, 50};

for(int x : numbers )
{
if( x == 30 )
{
break;
}
[Link]( x );
}
}
}

Example Program for displaying prime numbers:

class PrimeDemo
{
public static void main(String[] args)
{
int i,j;
[Link]("Prime numbers between 1 to 30 : ");
for(i=1;i<30;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
break;
}
if(i==j)
{
[Link](j+ " ");
}
}
}}
[Link].1 Labeled break
The java programming language does not support goto statement, alternatively, the break and continue
statements can be used with label.
The labelled break statement terminates the block with specified label. The labeled continue statement
takes the execution control to the beginning of a loop with specified label.

Example Program 1:

class LabelledBreak
{
public static void main(String args[])
{
int i=7;
loop1:
while(i<20)
{
if(i==10)
break loop1;
[Link]("i ="+i);
i++;
}
[Link]("Out of the loop");
} }
Example Program 2:
class LabeledBreakDemo
{
public static void main(String args[])
{
Outer : for(int i = 0; i< 4; i++)
{
for(int j = 1; j < 4; j++)
{
[Link]("i:" + i + " j:" + j);
if(i == 2)
break Outer;
}
}
}
}

1.5.3. 2 continue Statement


The continue statement is used in loop control structure when you need to jump to the next iteration
of the loop immediately.
Example Program 1:
class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
[Link](i);
} } }
[Link].1 Labeled continue

class LabeledContinueDemo
{
public static void main(String args[])
{
Outer : for(int i = 0; i< 4; i++)
{
for(int j = 1; j < 4; j++)
{
[Link]("i:" + i + " j:" + j);
if(i == 2)
continue Outer;
}
}
}
}

1.6. Classes& Object


In a java programming language, the class concept defines the skeleton of an object.
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.
 An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
 An entity that has state and behavior is known as an object.
 The object is an instance of a class.
 An object is a real-world entity.
 A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity.
An object has the following characteristics.

 Identity - It is the name given to the class.


 State - Represents data values that are associated with an object.
 Behavior - Represents actions can be performed by an object.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is
used to write, so writing is its behavior.

1.6.1 Differences between Objects and Classes


CLASS OBJECT
A template for creating or instantiating
An Instance of a class
objects within a program
Logical Entity Physical Entity
Declared with the “class” keyword Created using the “new” keyword
Class doesn’t allocated memorywhen it is
Objects allocates memory when it is created
created
Object is created many times as per
A class is declared once
requirement
1.6.2 Creating a Class
A class can be declared using the keyword class followed by the name of the class that you
want to define.
A class in java contains properties as variables and behaviors as methods.
Syntax:
class classname
{
//Variables declaration
//Methods declaration
}
Example:
class GoodbyeWorld
{
public static void main(String args[])
{
[Link]("Goodbye World!");
}
}

All the member variables and methods are declared within the class. There are three types of variables in
Java: local variables, instance variables, and class variables.

 Local variables are defined inside a method.


 Instance variable is defined inside the class but outside the methods, and
 class variables aredeclared with the static modifier inside the class and outside the
methods.

Ex:-
class SalesTaxCalculator
{
float amount = 100.0f; // instance variable
float taxRate = 10.2f; // instance variable
}
1.6.3 Creating Objects
In java, an object is an instance of a class. When an object of a class is created, the class is said to be
instantiated. All the objects that are created using a single class have the same properties and methods.
But the value of properties is different for every object.

Syntax:
Classnameobjectname=new Classname();

[Link] Declaring an Object


Object declarations are same as variable declarations.
Syntax:
type name;

where typeis the type of the object (i.e., class name) and name is the name of the reference
variableused to refer the object.

[Link] Initializing an Object

Syn: objectname=new Classname();

Ex: Area a;
a= new Area();

we can also combine these 2 steps as follows


Area a=new Area();

class SalesTaxCalculator
{
float amount = 100.0f;
float taxRate = 10.2f;
public static void main (String args[ ])
{
SalesTaxCalculator obj1 = new SalesTaxCalculator();
SalesTaxCalculator obj2 = new SalesTaxCalculator();
[Link]("Amount in Object 1: "+ [Link]);
[Link]("Tax Rate in Object 1: "+ [Link]);
[Link]("Amount in Object 2: "+ [Link]);
[Link]("Tax Rate in Object 2: "+ [Link]);
}
}
2. OPERATORS :
 An operator performs an action on one or more operands.
 An operator that performs an action on one operand is called a unary operator (+, –, ++, – –).
 An operator that performs an actionon two operands is called a binary operator (+, –, / , * , and
more).
 An operator that performs anaction on three operands is called a ternary operator (? :).
 Java provides all the three operators.
2.1Binary Operators
Java providesarithmetic, assignment, relational, shift, conditional, bitwise, and member access
operators.

2.1.1 Arithmetic Operators


In java, arithmetic operators are used to performing basic mathematical operations like addition,
subtraction, multiplication, division, modulus, increment, decrement, etc.
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Modulus - Remainder of the Division 5%2=1

class ArithmeticDemo
{
public static void main(String args[])
{
int a=25,b=10;
[Link]("Addition is "+(a+b));
[Link]("Subtrction is "+(a-b));
[Link]("Multiplication is "+(a*b));
[Link]("Division is "+(a/b));
[Link]("Remainder is "+(a%b));
}
}
2.1.2 Relational Operators
The relational operators are the symbols that are used to compare two values. That means the relational
operators are used to check the relationship between two values. Every relational operator has two
possible results either TRUE or FALSE.

Operator Meaning Example


Returns TRUE if the first value is smaller than second value otherwise returns 10 < 5 is
<
FALSE FALSE
Returns TRUE if the first value is larger than second value otherwise returns 10 > 5 is
>
FALSE TRUE
Returns TRUE if the first value is smaller than or equal to second value 10 <= 5 is
<=
otherwise returns FALSE FALSE
Returns TRUE if the first value is larger than or equal to second value 10 >= 5 is
>=
otherwise returns FALSE TRUE
10 == 5 is
== Returns TRUE if both values are equal otherwise returns FALSE
FALSE
10 != 5 is
!= Returns TRUE if both values are not equal otherwise returns FALSE
TRUE
class RelationalDemo
{
public static void main(String args[])
{
int a=10,b=20;
[Link]("Equality Operator:a==b " +(a==b));
[Link]("Not Equality Operator:a!=b " +(a==b));
[Link]("Less Than Operator: a < b " +(a<b));
[Link]("Greater Than Operator: a > b " +(a>b));
[Link]("Less Than or equal to Operator: a <= b " +(a<=b));
[Link]("Greater Than or equal to Operator: a >= b "
+(a>=b));
}
}

2.1.3 Boolean Logical Operators


The logical operators are the symbols that are used to combine multiple conditions into one condition.
The following table provides information about logical operators.

Operator Meaning Example


Logical AND - Returns TRUE if all conditions are TRUE otherwise returns false & true
&
FALSE => false
false | true
| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns TRUE
=> true
true ^ true
^ Logical XOR - Returns FALSE if all conditions are same otherwise returns TRUE
=> false
Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it is !false =>
!
TRUE true
short-circuit AND - Similar to Logical AND (&), but once a decision is finalized false & true
&&
it does not evaluate remaining. => false
short-circuit OR - Similar to Logical OR (|), but once a decision is finalized it false | true
||
does not evaluate remaining. => true

class LogicalDemo
{
public static void main(String args[])
{
boolean a=true,b=false;
[Link]("Logical OR: "+ (a|b));
[Link]("Logical XOR: "+ (a^b));
[Link]("Logical AND: "+ (a&b));
[Link]("Logical NOT: "+ (!a));
}
}

2.1.4 Bitwise Operators


The bitwise operators are used to perform bit-level operations in the java programming language. When
we use the bitwise operators, the operations are performed based on binary values.
The following table describes all the bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Operator Meaning Example
A&B
& The result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0
⇒ 16 (10000)
A|B
| The result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1
⇒ 29 (11101)
A^B
^ The result of Bitwise XOR is 0 if all the bits are same otherwise it is 1
⇒ 13 (01101)
~A
~ The result of Bitwise once complement is negation of the bit (Flipping)
⇒ 6 (00110)
Shift the bits left by b positions. Zero bits are added from the LSB side. A << 2
<<
Bits are discarded from the MSB side. ⇒ 100 (1100100)
Shift the bits right by b positions. Sign bits are copied from the MSB side. A >> 2
>>
Bits discarded from the LSB side. ⇒ 6 (00110)
class BitwiseDemo
{
public static void main(String args[])
{
int a=25,b=20;
[Link]("Bitwise AND : "+(a&b));
[Link]("Bitwise OR: "+(a|b));
[Link]("Bitwise XOR: "+(a^b));
[Link]("Bitwise NOT: "+(~a));
[Link]("a<<2: "+(a<<2));
[Link]("a>>2: "+(a>>2));
}
}

2.1.5 Unary Operators

Unary operators, as the name suggest, are applied to only one operand. They are ++, - -, !, and ~.

Increment and decrement operators can be applied to all integers and floating-point types. They can be
used either in prefix (– –x, ++x) or postfix (x– –, x++) mode.
Prefix Increment/Decrement Operation
int x = 2;
int y = ++x; // x = 3, y = 3
int z = --x; // x = 1, z = 1
Postfix Increment/Decrement Operation
int x = 2;
int y = x++; // x == 3, y == 2
int z = x--; // x = 1, z = 2
2.1.6 Ternary Operators
Ternary operators are applied to three operands. This conditional operator (? :) decides, on the
basis of the first expression, which of the two expressions to be evaluated.

operand1 ? operand2 : operand3


operand1 must be of boolean type or an expression producing a boolean result. If operand1
is true, then operand2 is returned. If operand1 is false, then operand3 is returned.
class ConditionalOp
{
public static void main(String args[])
{
int a=10, b=20, c;
c=(a>b)?a:b;
[Link](c);
}
}

1.1Methods :
 The Word method is commonly used in Object-oriented programming. It is similar to a
function in any other programming language.
 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.

1.1.1 Method Type :


There are two types of methods in Java: instance methods and class methods.
→ Instance methods are used to access/manipulate the instance variables but can
also access class variables.
→ Class methods can access/manipulate class variables but cannot access the
instance variables unless and until they use an object for that purpose.
1.1.2 Method Declaration:
A method is created inside the class and it may be created with any access specifier.
However, specifying access specifier is optional.
Syntax:
accessspecifierreturntypemethodname(parameters)
{
Block of statements;
}

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 receive.
 { } - Defines the block belongs to the method.

1.1.3 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);

Formal Parameter :The Parameters declared in called function


(Function Definition) are said to be formal Parameters
Actual Parameter :The Parameter specified in calling function
(Function call) are said to be Actual Parameter.
The value of actual parameters is always copied into formal
parameters.

1.2Instance method Invocation:

The method of the class is known as an instance method. It is a non-static method defined in
the class. Before calling or invoking the instance method, it is necessary to create an object of
its class.

Example program 1:

class Circle
{
float pi = 3.14f; //Instance Variable initializer
float radius; //Instance variable declaration
void setRadius(float rad) // Instance Method
{
radius = rad;
}
float calculateArea() //Instance Method
{
float area = pi * radius * radius;
return (area);
}
}
class CallMethod
{
public static void main(String args[])
{
float area1;
Circle cirobj=new Circle(); //Object Creation
[Link](3.0f);
area1=[Link]();
[Link]("Area of Circle = " + area1);
}
}

Example program 2:

class InstanceAdd
{
int a=10, b=20; // Instance variable Initialization
void Add() // Instance Method
{
int sum=a+b;
[Link]("Addition = "+sum);
}
public static void main(String args[])
{
InstanceAddobj=new InstanceAdd();
[Link]();
}
}
1.3 Method Overloading :
 Two or more methods can have the same name inside the same class with a different
arguments. This feature is known as method overloading.
 Overloading allows us to perform the same action on different types of inputs.
 Method Overloading is one way to achieving polymorphism in Java.

Example Program1 :

class Overloaddemo
{
void add(int a,int b)
{
[Link]("Addition of Two integers "+(a+b));
}
void add(float p,float q)
{
[Link]("Addition of Two float arguments "+(p+q));
}
public static void main(String args[])
{
Overloaddemool=new Overloaddemo();
[Link](10,20);
[Link](43.3,35.5);
}
}

Example Program2 :
class Overloaddemo
{
void max(long a,long b)
{
[Link]("max method with long args invoked");
if(a>b)
[Link](a + " is Greater ");
else
[Link](b + " is Greater ");
}

void max(float a,float b)


{
[Link]("max method with float argsinvoked");
if(a>b)
[Link](a + " is Greater ");
else
[Link](b + " is Greater ");
}

void max(double a,double b)


{
[Link]("max method with double args invoked");
if(a>b)
[Link](a + " is Greater ");
else
[Link](b + " is Greater ");
}

public static void main(String args[])


{
Overloaddemool=new Overloaddemo();
[Link](23,12);
[Link](43.3,35.5);
[Link](54.0f,67.9f);
[Link](89L,45L);

}
}
1.12 Inheritance
 The inheritance is a very useful and powerful concept of object-oriented programming. In
java, using the inheritance concept, we can use the existing features of one class in
another class.
 The inheritance provides a great advantage called code re-usability.
 Inheritance means access the properties and features of one class into another class.

Inheritance Basics
 In inheritance, we use the terms like parent class, child class, base class, derived class,
superclass, and subclass.
 The Parent class is the class which provides features to another class. The parent class is
also known as Base class or Superclass.
 The Child class is the class which receives features from another class. The child class is
also known as the Derived Class or Subclass.

Types of Inheritance
There are five types of inheritances, and they are as follows.
• Simple Inheritance (or) Single Inheritance
• Multiple Inheritance
• Multi-Level Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
The java programming language does not support multiple inheritance type. However, it provides
an alternate with the concept of interfaces.

Creating Child Class in java


In java, we use the keyword extends to create a child class. The following syntax used to
create a child class in java.
Syntax :
class<ChildClassName>extends<ParentClassName>{
...
//Implementation of child class
...
}

In a java programming language, a class extends only one class. Extending multiple classes is not
allowed in java.
1.12.1 Single Inheritance
In this type of inheritance, one child class derives from one parent class.
Example Program:
class Parent
{
void display()
{
[Link]("Base class Method");
}
}
class Child extends Parent
{
void show()
{
[Link]("Child class Method");
}
}
class SingleInheritance
{
public static void main(String args[])
{
Child C=new Child();
[Link]();
[Link]();
}
}
1.12.2Multi-level Inheritance
In this type of inheritance, the child class derives from a class which already derived from
another class.

Example Program:
class Parent
{
void display()
{
[Link]("Base Class Method");
}
}
class Child1 extends Parent
{
void show1()
{
[Link]("Child1 Class Method");
}
}
class Child2 extends Child1
{
void show2()
{
[Link]("Child2 class Method ");
}
}
class MultilevelInheritance
{
public static void main(String args[])
{
Child2 obj=new Child2();
[Link]();
obj.show1(); obj.show2();
}
}
1.12.3Hierarchical Inheritance
In this type of inheritance, two or more child classes derive from one parent class.

Example Program:
class Parent
{
void display()
{
[Link]("Base Class Method");
}
}
class Child1 extends Parent
{
void show1()
{
[Link]("Child1 Class Method");
}
}
class Child2 extends Parent
{
void show2()
{
[Link]("Child2 class Method ");
}
}
class HierarchicalInheritance
{
public static void main(String args[])
{
Child1 obj1=new Child1();
[Link]();
obj1.show1();
Child2 obj2=new Child2();
[Link]();
obj2.show2();
}
}
1.12.4 Hybrid
Inheritance
The hybrid inheritance is the combination of more than one type of inheritance. We may use any
combination as a single with multiple inheritances, multi-level with multiple inheritances, etc.,

1.13 Overriding Method :


 The Method overriding is the process of re-defining a method in a child class that is
already defined in the parent class. When both parent and child classes have the same
method, then that method is said to be the overriding method.
 When an overridden method is called from within a child class, it will always refer to the
version of the method defined by the child class. The Parent class version of the method is
hidden.

Example Program:

class Parent
{
void display()
{
[Link]("Parent class Method ");
}
}
class Child extends Parent
{
void display()
{
[Link]("Child class Method ");
}
}
class Overriding
{
public static void main(String args[])
{
Child C=new Child();
[Link]();
}
}
1.17 Interfaces:
 In java, an interface is similar to a class, but it contains abstract methods and static final
variables only. The interface in Java is another mechanism to achieve abstraction.
 We may think of an interface as a completely abstract class. None of the methods in the
interface has an implementation, and all the variables in the interface are constants.
 The interface in java enables java to support multiple-inheritance. An interface may
extend only one interface, but a class may implement any number of interfaces.

Defining an interface in java


Defining an interface is similar to that of a class. We use the keyword interface to define an
interface. All the members of an interface are public by default.
Syntax:
interfaceInterfaceName
{
...
members declaration;
...
}
Implementing an Interface in java
 The class uses a keyword implements to implement an interface. A class can implement
any number of interfaces.
 When a class wants to implement more than one interface, we use the implements keyword
is followed by a comma-separated list of the interfaces implemented by the class.
Syntax:
classclassNameimplementsInterfaceName
{
...
boby-of-the-class
...
}

Example Program:
interface Cal
{
int add(int a,int b);
int sub(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);
}
class Calculator implements Cal
{
public int add(int a,int b)
{
return a+b;
}
public int sub(int a,int b)
{
return a-b;
}
public int multiply(int a, int b)
{
return a*b;
}
public int divide(int a, int b)
{
return a/b;
}
public static void main(String args[])
{
Calculator c=new Calculator();
[Link]("Value after Addition = "+[Link](5,2));
[Link]("Value after Subtraction = "+[Link](5,2));
[Link]("Value after Multiplication =
"+[Link](5,2));
[Link]("Value after division = "+[Link](5,2));
}
}
1.17.1 Extending Interfaces
Just like normal classes, interfaces can also be extended. An interface can inherit another
interfaceusing the same keyword extends, and not the keyword implements.
Example Program:
interface A
{
void showA();
}
interface B extends A
{
void showB();
}

class InDemo implements B


{
public void showA()
{
[Link]("Overriden method of Interface A");
}
public void showB()
{
[Link]("Overriden method of Interface B");
}
public static void main (String args[])
{
InDemo d = new InDemo();
[Link]();
[Link]();
}
}
1.18Packages:
 In java, a package is a container of classes, interfaces, and sub-packages. We may think of
it as a folder in a file directory.
 We use the packages to avoid naming conflicts and to organize project-related classes,
interfaces, and sub-packages into a bundle.
In java, the packages have divided into two types.

 Built-in Packages
 User-defined Packages

Built-in Packages
 The built-in packages are the packages from java API. The Java API is a library of pre-
defined classes, interfaces, and sub-packages. The built-in packages were included in the
JDK.
 There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax,
swing, net, sql, etc.

User-defined Packages
The user-defined packages are the packages created by the user. User is free to create their own
packages.

1.18.1 Defining a Package in java / Creating Packages


We use the package keyword to create or define a package in java programming language .

Syntax :-
packagepackageName;
🔔The package statement must be the first statement in the program.
🔔The package name must be a single word.
Package compilation command.
Syntax:
javac -[Link]
-dis used to create a new folder with package name and inside the package folder
[Link] will create .
. (dot)represents the current working directory.
Package running command with package name
Syntax:
java [Link]
Example:
package myPackage;
public class DefiningPackage
{
public static void main(String args[])
{
[Link]("This class belongs to myPackage.");
}
}
Now, save the above code in a file [Link], and compile it using the following
command.
javac -d . [Link]

The above command creates a directory with the package name myPackage, and the
[Link] saved into it.

Run the program use the following command.


java [Link]
1.18.2 Importing Packages in java

 In java, the import keyword used to import built-in and user-defined packages. When a
package has imported, we can refer to all the classes of that package using their name
directly.
 The import statement must be after the package statement, and before any other
statement.
 Using an import statement, we may import a specific class or all the classes from a
package.
🔔Using one import statement, we may import only one package or a class.
🔔 Using an import statement, we can not import a class directly, but it must be a part of a package.
🔔 A program may contain any number of import statements.

Importing specific class


Using an importing statement, we can import a specific class. The following syntax is employed
to import a specific class.

Syntax
[Link];

Example program on import statement to import a built-in package and Scanner class.
package myPackage;
import [Link];
public class ImportingExample
{
public static void main(String[] args)
{
Scanner read = new Scanner([Link]);
[Link]("Enter a number : ");
int i = [Link]();
[Link]("You have entered a number " + i);
}
}
In the above code, the class ImportingExamplebelongs to myPackagepackage, and it also
importing a class called Scanner from [Link].

Importing all the classes


Using an importing statement, we can import all the classes of a package. To import all the classes
of the package, we use * symbol. The following syntax is employed to import all the classes of a
package.
Syntax
importpackageName.*;

Accessing package from another class


Open Notepad type the following program

package package1;
public class Sample
{
public void display()
{
[Link]("Display Method");
}
}

Save Above file with [Link]

Open another Notepad type the following program

import [Link];
class Test
{
public static void main(String args[])
{
Sample s=new Sample();
[Link]();
}
}

Save Above file with [Link]

You might also like