Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Java Syllabus

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

Java Syllabus

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

Introduction to Java

Explain different features of Java:-

1. Simple and familiar: it is simple to learn, understand, read, and write. Java
programs are easy to create & implement compared to other programming
languages such as C and C++
2. Object oriented: Java is a fully object-oriented language, unlike C++ which is
semi object-oriented. It supports every OOP concept such as Abstraction,
Encapsulation, Inheritance & Polymorphism.
3. Platform independent: It is means that Java programs compiled on one
machine or operating system can be executed on any other machine or operating
system without modifications.
4. Compiled & interpreted: When a Java program is created, the Java compiler
converts the java source code into byte code.
5. Multi-threaded: Java supports multi-threading programming that means
creating multiple threads to handle multiple tasks at the same time.
6. Dynamic: It allows programmers to dynamically link new class libraries, objects,
and methods.
7. Robust: Java is a robust language that can handle run-time errors as it checks
the code during the compile and runtime.
8. Secure: That ensures programs cannot take the access to memory locations
without authorization.

PRASHANT V KALE-PATIL
1
 Explain the programming concept of Core Java.

The main Method:


eg. public static void main(String args[ ])

This is similar to the main() function in c/c++. Every java application program
must include the main method.
This line contains a number of keywords public, static & void.
 public: It is a access specifier that means it will be accessed by publicly.
 static: It is access modifier that means when the java program is load then
it will create the space in memory automatically.
 void: It is a return type i.e it does not return any value.
 main (): It is a method or a function name.

e. The output line: e.g. Sytem.out.println(“Welcome”);

 Explain Java Tokens in detail.


A java program is defined basically a collection of classes. A class is defined by a
set of declaration statements & methods containing executable statements.

Token are,
1. Keywords
2. Identifiers
3. Literals
4. Separators
5. Operators – Operators are Symbols that is use to operate the operations

I.) Arithmetic operators: -


A) + Addition or unary plus
B) – subtraction or unary minus

C) X multiplication

D) / division e) % module division

II.) Relational Operators: -


These are used to compare two quantities. Java supports following types of
relational operators.

PRASHANT V KALE-PATIL
2
Operators Meaning.
a) < Less than

b) <= Less than or equal to

c) > greater than

d) >= greater than or equal to


e) == Equal to
f) != not equal to

III.) Assignment Operators: -


Assignment operators are used to assign the value of an expression to a
variable. We have seen the usual assignment operator =. eg. int a=5; a +=10;

IV.) Increment & Decrement operators: -


Java has following types of increment & decrement operators.
a) ++
b) - -
The operator ++ adds 1 to the operand, while -- subtracts 1
Int m=10;
Int n=20;
System.out.println(++m); 11
System.out.println(n++); 10

V.) Conditional operator: -


The operators ? and : are shown as conditional operators. These are also known
as ternary operators.
Syn : exp1 ? exp2 : exp3 Class Conop
{
public static void main(String args[ ])
{ int a=10; int b=15;
int x=(a<b) ? a : b;
System.out.println(x);
}}
Bitwise operator: -
These operators are used for testing the bits or shifting them to the right or left

Operators Meaning
& AND
|| OR

PRASHANT V KALE-PATIL
3
^ EXCLUSIVE OR
<< SHIFT LEFT
>> SHIFT RIGHT
>>> SHIFT RIGHT WITH
ZERO FILL
~ ONES COMPLEMENT

 Explain different mathematical functions.


Java support the basic math functions through Math class defined in the
java.lang package. These functions are as follows.
1. sin(x) Returns the sine of the angle x.

2. cos(x) Returns the cosine of the angle x.

3. pow(x,y) Returns x raised to x

4. exp(x) Returns e raised to x

5. sqrt(x) Returns the square root of x

6. ceil(x) Returns the smallest whole number greater than or equal to x.

7. floor(x) Returns the largest whole number less than or equal to x.

8. abs(x) Returns the absolute value of a.

9. max(a,b) Returns the maximum of a and b.

10. min(a,b) Returns the minimum of a and b.

// Math function demo Class Math demo


{
public static void main(String args[ ])
{ double a=10; double x=Math.sqrt(a); System.out.println(x);
}
}

 What is a constant?

PRASHANT V KALE-PATIL
4
Constant is nothing but the fixed values that don’t change during the execution
of progress. In java, there are different types of constants.
1. Numeric constants

2. Character constants.

1. Numeric Constants: It consists of two main constants as


a) Integer constants:
An integer constant refers to a sequence of digits. There are three types of
integer constants.
i) Decimal integer eg: 123, -235

ii) Octal integer: 037,456

iii) Hexadecimal integer: 0x2, 0x9f

b) Real Constants:
The real constants are also called as floating point constant. eg: 0.856, 0.86,
56.32
2. Character Constants:
There are three types of character constants.
a) Single character constants:
Single character enclosed within a single quote marks e.g: ‘X’, ‘8’, ‘h’
b) String constants:
It contains sequence of characters enclosed within a double quote.

eg: “Welcome”, “3545”, “core java” etc.

PRASHANT V KALE-PATIL
5
 Explain different data types in java?

 What are the Variables


Variables are identifiers that are used to store the data values.
Java variables are classified into three types.

1. Instance variable: Instance variables are declared inside a class.

2. Class variable: Class variables are global to a class & belong to the entire
set of objects that class creates.

3. Local variable: Variable declared & used inside methods are called local
variables.

PRASHANT V KALE-PATIL
6
 CONTROL STATEMENT

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statements
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o Break statement
o continue statement

Decision making statements: Java If-else Statement


if statement is used to test the condition. It checks Boolean.
Condition: True or False. There are various types of if statement in Java.

1. if statement
2. if-else statement
3. if-else-if ladder
4. nested if statement

The Java if statement tests the condition. It executes the if block if condition is
true.

PRASHANT V KALE-PATIL
7
1. If Statement:

Example:
Play Videos

Java Program to demonstate the use of if statement.


public class If_Example {

public static void main(String[] args) {

//defining an 'age' variable

int age=20;

//checking the age

if(age>18)

System.out.print("Age is greater than 18");

Output:

Age is greater than 1

PRASHANT V KALE-PATIL
8
2. if-else Statement:
The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
} else{
//code if condition is false
}

Example:
A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}
Else {
System.out.println("odd number");
}
}}

PRASHANT V KALE-PATIL
9
Leap Year Example:
A year is leap, if it is divisible by 4 and 400. But not by 100.
public class LeapYearExample {
public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else {
System.out.println("COMMON YEAR");
}
}
}
Output:
LEAP YEAR

PRASHANT V KALE-PATIL
10
3. if-else-if ladder
The if-else-if ladder statement executes one condition from multiple
statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}
else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3)
//code to be executed if condition3 is true
}
...
else {
//code to be executed if all the conditions are false
}

PRASHANT V KALE-PATIL
11
Example:
Java Program to demonstrate the use of “ If else-if ladder.”
//It is a program of grading system for fail, D grade, C grade, B grade, A grade
and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}

PRASHANT V KALE-PATIL
12
4. Nested if statement

The nested if statement represents the if block within another if block. Here,
the inner if block condition executes only when outer if block condition is
true.

Syntax:
if(condition) {
//code to be executed
if(condition){
//code to be executed
}
}

Example:
Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Test it now
Output:
You are eligible to donate blood

PRASHANT V KALE-PATIL
13
Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It
is like if-else-if Ladder statement.

The switch statement works with byte, short, int, long, enum types, String. In
other words, the switch statement tests the equality of a variable against
multiple values.

Points to Remember
There can be one or N number of case values for a switch expression.

Syntax:
switch (expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;

PRASHANT V KALE-PATIL
14
Example:

public class SwitchExample {


public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number) {
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}

PRASHANT V KALE-PATIL
15
Java WHILE LOOP

The Java while loop is used to repeated a part of the program until the specified
Boolean condition is true. As soon as the Boolean condition becomes false, the
loop automatically stops. It is ENTRY LOOP.

Syntax:
while (condition){
//code to be executed
Increment / decrement statement
}

Example:

public class While_Example {

public static void main(String[] args) {

int i=1;

while (i<=10){

System.out.println(i);

i++;

PRASHANT V KALE-PATIL
16
Java DO -WHILE Loop

The Java do-while loop is used to iterate a part of the program repeatedly, until
the specified condition is true. Java do-while loop is called an exit control loop.
Therefore, unlike while loop and for loop, the do-while check the condition at the
end of loop body.

Syntax:

do {

//code to be executed / loop body

//update statement

while (condition);

Example:

public class DoWhileExample {

public static void main(String[] args) {

int i=1;

do {

System.out.println(i);

i++;

} while(i<=10);

PRASHANT V KALE-PATIL
17
Java BREAK Statement

When a BREAK statement is encountered inside a loop, the loop is immediately


terminated. The Java break statement is used to break loop or switch statement.
It breaks the current flow of the program.

Example:

Java Program to demonstrate the use of break statement

// inside the for loop.

public class BreakExample {

public static void main(String[] args) {

//using for loop

for ( int i=1; i<=10; i++)

if(i==5){

//breaking the loop

break;

System.out.println(i);

PRASHANT V KALE-PATIL
18
Java CONTINUE Statement

The Java CONTINUE statement is used to continue the loop. It continues the
current flow of the program.

Example.

Java Program to demonstrate the use of CONTINUE statement.

// inside for loop.

public class ContinueExample {

public static void main(String[] args) {

//for loop

For (int i=1;i<=10;i++){

if (i==5){

// using continue statement

continue; // it will skip the rest statement

System.out.println (i);

PRASHANT V KALE-PATIL
19
PALINDROME Program in Java

A palindrome number is a number that is same after reverse.

For example 545, 151, 34543, 343, 171.

Example:

public class Palindrome_number_scanner {

public static void main(String[] args) {


int x;
Scanner sc = new Scanner(System.in);
System.out.println ("Enter the number");
x = sc.nextInt();
int reverse=0, remainder, temp;
temp=x;
while (x>0)
{
remainder= x%10;
reverse = reverse*10+remainder;
x=x/10;
}
if(temp==reverse)
{
System.out.println("The number is Palindrome = " +reverse);
}
else
{
System.out.println("The number is not Palindrome =" +reverse);
}
}
}

PRASHANT V KALE-PATIL
20
ARMSTRONG Number in Java

An Armstrong number is a positive m-digit number that is equal to the sum of


the mth powers of their digits.

Example:

3: 31 = 3

153: 13 + 53 + 33 = 1 + 125+ 27 = 153

125: 13 + 23 + 53 = 1 + 8 + 125 = 134 (Not an Armstrong Number)

1634: 14 + 64 + 34 + 44 = 1 + 1296 + 81 + 256 = 1643.

public static void main(String[] args) {


// Reverse number by ARMSTRONG Method

int x=153, remainder, cube, cubesum=0, temp;


temp=x;
while(x>0)
{
remainder=x%10;
cube=remainder*remainder*remainder;
cubesum = cubesum + cube;
x=x/10;
}
if(cubesum==temp)
{
System.out.println("The Armstrong number is ="+ cubesum);
}
else
{
System.out.println("Number is not Armstrong =" + cubesum );
}
}}

PRASHANT V KALE-PATIL
21
 OOP’s (Object-Oriented Programming System)

Object-Oriented Programming is a methodology to design a program using


classes and objects. It simplifies software development & maintenance by
providing some concepts:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

 Object: Any entity that has state and behaviour is known as an object.
An Object can be defined as an instance of a class. An object contains an
address and takes up some space in memory.
Example: public class CreateObject
{
void show()
{
System.out.println("Welcome");
}
public static void main(String[] args)
{
//creating an object using new keyword
CreateObject obj = new CreateObject ();
//invoking method using the object
obj.show();
}
}

 Class: Collection of objects is called class. It is a logical entity. A class


can also be defined as a blueprint from which we can create an individual
object. Class doesn't consume any space.

 Constructor: 1. Constructor is a special method whose name is same as


CLASS name.
2. A Constructor has no return type.
3. A Java constructor cannot be abstract, static, final, and synchronized
4. It is called when an instance of the class is created

PRASHANT V KALE-PATIL
22
https://www.javatpoint.com/java-constructor

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor: A constructor is called "Default Constructor" when


it doesn't have any parameter.
Rule: If there is no constructor in a class, compiler automatically creates a
default constructor.

2. Parameterized constructor: A constructor which has a specific number


of parameters is called a parameterized constructor.

Question: Why use the parameterized constructor?


The parameterized constructor is used to provide different values to
objects.
 Constructor Overriding: It is a technique of having more than one
constructor with different parameter lists. They are arranged in a way that
each constructor performs a different task.

Example of Constructor Overloading


Java program to overload constructors

class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5 (111,"Karan");
Student5 s2 = new Student5 (222,"Aryan",25);
s1.display();
s2.display();
}}

PRASHANT V KALE-PATIL
23
 Question: why constructor overriding is not possible in java?
Constructor Overriding is never possible in Java. This is because,
Constructor looks like a method but name should be as class name
and no return value. Overriding means what we have declared in Base
class, that exactly we have to declare in Derived class it is called
Overriding.

 What is Overloading and Overriding?

When two or more methods in the same class have the same name but
different parameters, it’s called Overloading. When the method name and
parameters are the same in the superclass and the child class, it’s called
Overriding.

Overriding vs. overloading

Overriding implements Runtime


Overriding implements Runtime
Polymorphism
Polymorphism
Overloading creates between
The method Overriding created
the methods in the same class.
between superclass & subclass
This Method has same names
Overriding method has same
but different parameters
names & parameters
Whereas if overloading breaks,
If overriding breaks, it can
the compile-time error will
cause serious issues in our
come and it’s easy to fix.
program because the effect will
be visible at runtime

PRASHANT V KALE-PATIL
24
Objects and Classes in Java

 What is an object in Java

An entity that has state and behaviour is known as an object.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. However, it is used
internally by the JVM to identify each object uniquely.

An object is an instance of a class. A class is a template or blueprint from


which objects are created. So, an object is the instance (result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

 What is a class in Java

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. It can't be
physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

PRASHANT V KALE-PATIL
25
 Instance variable in Java

A variable which is created inside the class but outside the method is known as
an instance variable. Instance variable doesn't get memory at compile time. It
gets memory at runtime when an object or instance is created

 Method in Java

In Java, a method is like a function which is used to expose the behavior of an


object.

Advantage of Method

o Code Reusability
o Code Optimization

 new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory
in Heap memory area.

 3 Ways to initialize object

There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:

o By new keyword
o By newInstance() method
o By clone() method
o By deserialization
o By factory method etc

PRASHANT V KALE-PATIL
26
 this keyword in Java

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

PRASHANT V KALE-PATIL
27
 The problem without this keyword

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

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:

0 null 0.0
0 null 0.0

PRASHANT V KALE-PATIL
28
 Solution of the above problem by this keyword

Here parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:

111 ankit 5000.0


112 sumit 6000.0

PRASHANT V KALE-PATIL
29
 Program where this keyword is not required

Here local variables (formal arguments) and instance variables are different,
there is no need to use this keyword like in the following program

class Student{
int rollno;
String name;
float fee;
Student(int r,String n,float f){
rollno=r;
name=n;
fee=f;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis3{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:

111 ankit 5000.0


112 sumit 6000.0

 this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If
you don't use the this keyword, compiler automatically adds this keyword while
invoking the method.

PRASHANT V KALE-PATIL
30
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}

Output:

hello n
hello m

 this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor.

Calling default constructor from parameterized constructor:

class A{
A(){System.out.println("hello a");}
A(int x) {
this();
System.out.println(x);
} }
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}

Hello
10

PRASHANT V KALE-PATIL
31
 this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is mainly
used in the event handling.

class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}

Output:

method is invoked

PRASHANT V KALE-PATIL
32
 Java static keyword

The static keyword is used for memory management mainly. We can apply
static keyword with variables.

The static keyword belongs to the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

 Java static variable

If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

PRASHANT V KALE-PATIL
33
Example of static variable

//Java Program to demonstrate the use of static variable


class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}

Output:

111 Karan ITS


222 Aryan ITS

PRASHANT V KALE-PATIL
34
 Program of the counter without static variable

In this example, we have created an instance variable named count which is


incremented in the constructor. Since instance variable gets the memory at the
time of object creation, each object will have the copy of the instance variable. If
it is incremented, it won't reflect other objects. So, each object will have the
value 1 in the count variable.

//Java Program to demonstrate the use of an instance variable


//which get memory each time when we create an object of the class.
class Counter{
int count=0;//will get memory each time when the instance is created

Counter(){
count++;//incrementing value
System.out.println(count);
}

public static void main(String args[]){


//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}

Output:

1
1
1

PRASHANT V KALE-PATIL
35
https://www.geeksforgeeks.org/inheritance-in-java/

Inheritance in Java
Inheritance is an important pillar of OOP (Object-Oriented Programming). It is
the mechanism in java by which one class is allowed to inherit or access the
features (fields and methods) of another class.

Important terminology:

 Super Class: The class whose features are inherited is known as a


superclass (or a base class or a parent class).
 Sub Class: The class that inherits the other class is known as a
subclass (or a derived class, extended class, or child class). The
subclass can add its own fields and methods in addition to the
superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when
we want to create a new class and there is already a class that includes
some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of
the existing class.

o Which class is the superclass for all the classes?

 The object class is the superclass of all other classes in Java.

PRASHANT V KALE-PATIL
36
Types of Inheritance in Java

Below are the different types of inheritance which are supported by Java.

1. Single Inheritance: In single inheritance, subclasses (Derived


Classes) inherit the features of one superclass (Base Classes). In the
image below, class A serves as a base class for the derived class B.

PRASHANT V KALE-PATIL
37
2. Multilevel Inheritance: In Multilevel Inheritance, A derived class will be
inheriting a base class and as well as the derived class also act as the base
class to other class. In the below image, class A serves as a base class for
the derived class B, which in turn serves as a base class for the derived class
C

PRASHANT V KALE-PATIL
38
3. Hierarchical Inheritance: In Hierarchical Inheritance, one class
acted as a superclass (base class) & there is more than one subclass.
In the below image class A serves as a base class for the derived class
B, C and D.

PRASHANT V KALE-PATIL
39
4. Multiple Inheritances (Through Interfaces): In Multiple inheritances, one
class can have more than one superclass and inherit features from all parent
classes. Please note that Java does not support multiple inheritances with
classes. In java, we can achieve multiple inheritances only through
Interfaces. In the image below, Class C is derived from interface A and B.

PRASHANT V KALE-PATIL
40
5. Hybrid Inheritance (Through Interfaces): It is a combination of Multilevel
and Hierarchical inheritances. Since java doesn’t support multiple
inheritances with classes, hybrid inheritance is also not possible with
classes. In java, we can achieve hybrid inheritance only through Interfaces.

Important facts about inheritance in Java

 Default superclass: Except Object class, which has no superclass,


every class has one and only one direct superclass (single
inheritance). In the absence of any other explicit superclass, every
class is implicitly a subclass of the Object class.
 Superclass can only be one: A superclass can have any number of
subclasses. But a subclass can have only one superclass. This is
because Java does not support multiple inheritances with classes.
Although with interfaces, multiple inheritances are supported by java.
 Inheriting Constructors: A subclass inherits all the members (fields,
methods, and nested classes) from its superclass. Constructors are
not members, so they are not inherited by subclasses, but the
constructor of the superclass can be invoked from the subclass.
 Private member inheritance: A subclass does not inherit the private
members of its parent class. However, if the superclass has public or
protected methods (like getters and setters) for accessing its private
fields, these can also be used by the subclass.

PRASHANT V KALE-PATIL
41
Java IS-A type of Relationship.

IS-A is a way of saying: This object is a type of that object. Let us see how the
extends keyword is used to achieve inheritance.

Now, based on the above example, in Object-Oriented terms, the following


are true:-

1. SolarSystem is the superclass of Earth class.


2. SolarSystem is the superclass of Mars class.
3. Earth and Mars are subclasses of SolarSystem class.
4. Moon is the subclass of both Earth and SolarSystem classes.

 Why is multiple inheritance not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

PRASHANT V KALE-PATIL
42
POLYMORPHISM

The word "poly" means many and "morphs" means forms. So Polymorphism
means "many forms" and it occurs when we have many classes that are related
to each other by inheritance. We can perform a single action in different ways.

There are two types of polymorphism in Java:

 Compile-time Polymorphism
 Runtime Polymorphism.

We can perform polymorphism in java by METHOD OVERLOADING & METHOD


OVERRIDING.

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs
addition of two numbers and second add method performs addition of three
numbers.In this example, we are creating static methods so that we don't need
to create instance for calling methods.

class Adder {
static int add(int a,int b) {return a+b;}
static int add(int a,int b,int c) {return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args) {
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

PRASHANT V KALE-PATIL
43
Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first
add method receives two integer arguments and second add method receives
two double arguments.

class Adder{

static int add(int a, int b) {return a+b;}

static double add (double a, double b) {return a+b;}

}
class TestOverloading2{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println (Adder.add(12.3,12.6));
}}

In java, method overloading is not possible by changing the return type of the
method only because of ambiguity.

class Adder{
static int add (int a,int b) {return a+b;}
static double add(int a,int b) {return a+b;}
}
class TestOverloading3 {
public static void main(String[] args) {
System.out.println (Adder.add(11,11)); //ambiguity
}}

Output:

Compile Time Error: method add(int,int) is already defined in class Adder

Can we overload java main () method?

Yes, by method overloading. You can have any number of main methods in a
class by method overloading. But JVM calls main() method which receives string
array as arguments only.

PRASHANT V KALE-PATIL
44
Method Overriding in Java

 Understanding the problem without method overriding


 Can we override the static method
 Method overloading vs. method overriding

If subclass (child class) has the same method as declared in the Superclass
(parent class), it is known as method overriding in Java.

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.

Here, we are calling the method of parent class with child


//class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]) {
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}

Output:

Vehicle is running

PRASHANT V KALE-PATIL
45
Can we override static method?

No, a static method cannot be overridden. It can be proved by runtime


polymorphism.

Why can we not override static method?

It is because the static method is bound with class whereas instance method is
bound with an object. Static belongs to the class area, and an instance belongs
to the heap area.

Can we override java main method?

No, because the main is a static method.

 METHOD OVERLOADING and METHOD OVERRIDING in java

Method Overloading Method Overriding

 Method overloading is a compile-time  Method overriding is a run-


polymorphism. time polymorphism.

 It is performed in two classes


 It occurs within the class. with inheritance

 Method overloading may or may not  Method overriding always


require inheritance. needs inheritance.

 In method overloading, methods must  In method overriding, methods


have the same name & different must have the same name and
parameter. same parameter.

 In method overloading, the return type  In method overriding, the


can or cannot be the same, but we just return type must be the same
have to change the parameter. or co-variant.

 Static binding is being used for  Dynamic binding is being used


overloaded methods. for overriding methods.

 It gives better performance.  Poor performance

PRASHANT V KALE-PATIL
46
 Super Keyword in Java

The super keyword refers to superclass (parent) objects. Whenever you


create the instance of subclass, an instance of parent class is created which is
referred by super reference variable.

Usage of Java super Keyword

1. Super can be used to refer immediate parent class instance variable.

2. Super can be used to invoke immediate parent class method.

3. Super () can be used to invoke immediate parent class constructor.

 We can use super keyword to access the data member or field of parent
class. It is used if parent class and child class have same fields.

class Animal {

String color="white";

}
class Dog extends Animal{

String color="black";

void printColor(){

System.out.println(color); //prints color of Dog class


System.out.println (super.color); //prints color of Animal class

class TestSuper1{

public static void main(String args[]){


Dog d=new Dog();

d.printColor();

}}
Output:
White
Black

PRASHANT V KALE-PATIL
47
Instance Initializer block is used to initialize the instance data member. It run
each time when object of the class is created.

 Rules for instance initializer block :

There are mainly three rules for the instance initializer block. They are as follows:

1. The instance initializer block is created when instance of the class is


created.
2. The instance initializer block is invoked after the parent class constructor
is invoked (i.e. after super() constructor call).
3. The instance initializer block comes in the order in which they appear.

Program of instance initializer block that is invoked after super ()

class A {
A() {
System.out.println("parent class constructor invoked");
}
}
class B2 extends A{
B2(){
super();
System.out.println("child class constructor invoked");
}
{System.out.println("instance initializer block is invoked");
}
public static void main(String args[]){
B2 b=new B2();
}
}
Output: parent class constructor invoked
instance initializer block is invoked
child class constructor invoked

PRASHANT V KALE-PATIL
48
The final keyword in java is used to restrict the user. The java final keyword
can be used in many contexts. Final can be:

1. variable
2. method
3. class

1) Java final variable

If you make any variable as final, you cannot change the value of final variable
(It will be constant).

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike


{
void run()
{System.out.println("running safely with 100kmph");
}

public static void main(String args[]) {


Honda honda= new Honda ();
honda.run();
}
} Output:Compile Time Error

PRASHANT V KALE-PATIL
49
Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which


a call to an overridden method is resolved at runtime rather than compile-time.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class (Super class) refers to the object of
Child class, it is known as upcasting.

class A{}
class B extends A{}

A a=new B(); //upcasting

class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("Running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
}

Output:

Running safely with 60km.

 What is Exception Handling?

Exception Handling is a mechanism that is used to handle runtime errors. It is


used primarily to handle checked exceptions. Exception handling maintains the
normal flow of the program. There are mainly two types of exceptions: checked
and unchecked.

PRASHANT V KALE-PATIL
50
There are the following differences between compile-time polymorphism and
runtime polymorphism.

compile-time polymorphism Runtime polymorphism

In compile-time polymorphism, call to a In runtime polymorphism, call to an overridden method


method is resolved at compile-time. at runtime.

It is also known as static binding, early It is also known as dynamic binding, late binding, overrid
binding, or overloading. dynamic method dispatch.

Overloading is a way to achieve compile-time Overriding is a way to achieve runtime polymorphism in


polymorphism in which, we can define can redefine some particular method or variable in the d
multiple methods or constructors with By using overriding, we can give some specific implemen
different signatures. base class properties in the derived class.

It provides fast execution because the type It provides slower execution as compare to compile-t
of an object is determined at compile-time. the type of an object is determined at run-time.

Compile-time polymorphism provides less Run-time polymorphism provides more flexibility bec
flexibility because all the things are resolved things are resolved at runtime.
at compile-time.

PRASHANT V KALE-PATIL
51
 ABSTRACTION

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have


abstract and non-abstract methods

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the
body of the method.

Abstract Method in Java

A method which is declared as abstract and does not have implementation is


known as an abstract method.

abstract class Bike {


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println ("running safely");}
public static void main(String args[]){
Bike obj = new Honda4 ();
obj.run ();
}
}
Output: safely
running safely

PRASHANT V KALE-PATIL
52
Abstract class having constructor, data member & methods

An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor and even main () method.

abstract class Bike {


Bike(){System.out.println("bike is created");
}
abstract void run();
void changeGear()
{
System.out.println("gear changed");
}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
bike is created
running safely..
gear changed

PRASHANT V KALE-PATIL
53
 Interface in Java

An interface in Java is a Blueprint of a class. The interface in Java is a


mechanism to achieve abstraction. Interfaces can have abstract methods &
variables. It cannot have a method body.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.

o By interface, we can support the functionality of multiple inheritances.

o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total


abstraction; means all the methods in an interface are declared with the empty
body.

PRASHANT V KALE-PATIL
54
Java Interface Example
interface printable {
void print();
}
class A6 implements printable {
public void print()
{
System.out.println("Hello");
}
public static void main(String args[]) {
A6 obj = new A6();
obj.print();
}
}

Multiple inheritance in Java by interface

If a class implements multiple interfaces or an interface extends multiple


interfaces, it is known as multiple inheritances.

PRASHANT V KALE-PATIL
55
interface Printable {
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print()
{System.out.println("Hello");}
public void show()
{System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

Output:

Hello

Q) Multiple inheritance is not supported through class in java, but it is


possible by an interface, why?
Multiple inheritance is not supported in the case of class because of ambiguity.
However, it is supported in case of an interface because there is no ambiguity. It
is because its implementation is provided by the implementation class.

interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable, Showable
{
public void print(){System.out.println("Hello");}
public static void main(String args[]) {

PRASHANT V KALE-PATIL
56
TestInterface3 obj = new TestInterface3();
obj.print();
} }
Output:
Hello

 Static Method in Interface

interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Output:
drawing rectangle
27

Q) What is marker or tagged interface?

An interface which has no member is known as a marker or tagged interface, for


example, Serializable, Cloneable, Remote, etc. They are used to provide some
essential information to the JVM so that JVM may perform some useful
operation.

1. //How Serializable interface is written?


2. public interface Serializable{

 Nested Interface in Java

Note: An interface can have another interface which is known as a nested


interface. We will learn it in detail in the nested classes chapter. For example:

PRASHANT V KALE-PATIL
57
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}

 Difference between abstract class and interface

Abstract class Interface


Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also
Abstract class doesn't support Interface supports multiple inheritance.
multiple inheritance.
Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
Abstract class can provide the Interface can't provide the
implementation of interface implementation of abstract class
The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only
interfaces.
An abstract class can be extended An interface can be implemented using
using keyword "extends" keyword "implements".
A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default

PRASHANT V KALE-PATIL
58
Encapsulation in Java
https://www.javatpoint.com/access-modifiers

Encapsulation in Java is a process of binding code and data together into a


single unit

We can create a fully encapsulated class in Java by making all the data members
of the class private. Now we can use setter and getter methods to set and get
the data in it.

 Advantage of Encapsulation in Java

1. By providing only a setter or getter method, we can make the class read-
only or write-only.
2. It provides you the control over the data.
3. It is a way to achieve data hiding in Java because other class will not be
able to access the data
4. The encapsulate class is easy to test. So, it is better for unit testing.
5. It is easy and fast to create an encapsulated class in Java.

//A Java class which is a fully encapsulated class.


//It has a private data member and getter and setter methods.
package Prashant;
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
this.name=name
}
}

PRASHANT V KALE-PATIL
59
Let's see another example of encapsulation that has only four fields with its
setter and getter methods.

//A Account class which is a fully encapsulated class.


//It has a private data member and getter and setter methods.
class Account {
//private data members
private long acc_no;
private String name,email;
private float amount;
//public getter and setter methods
public long getAcc_no() {
return acc_no;
}
public void setAcc_no(long acc_no) {
this.acc_no = acc_no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
}

PRASHANT V KALE-PATIL
60
Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type with square brackets:

String[] cars;

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

package Array_Class;

public class String_Upper_Lower {

public static void main(String[] args) {

String A= "Prashant"; // To upper class Alphabates


System.out.println(A.toUpperCase());
System.out.println(A.toLowerCase()); // To lower class Alphabates
System.out.println(A);

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

String B= "Prashant & Sanika"; //Java String is a built-in function that


eliminates leading and trailing spaces

System.out.println(B.trim());

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

String C= "Prashant_Sanika";
System.out.println(C.startsWith("P"));
System.out.println(C.endsWith("a"));
System.out.println(C.charAt(5)); // That defined the number the letter.

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

String D= "Prashant is a very good boy";


System.out.println (D.length()); // This defined length of the Array

String E = D.replace("Prashant", "Anna"); // To replace the words


System.out.println(E);
}

PRASHANT V KALE-PATIL
61
Loop Through an Array

Loop through the array elements with the for loop, and use the length property
to specify how many times the loop should run.

The following example outputs all elements in the cars array:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < cars.length; i++) {

System.out.println(cars[i]);

Multidimensional Arrays

A multidimensional array is an array of arrays.

To create a two-dimensional array, add each array within its own set of curly
braces:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

public class Main {

public static void main(String[] args) {

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int i = 0; i < myNumbers.length; ++i)

for(int j = 0; j < myNumbers[i].length; ++j)

System.out.println(myNumbers[i][j]);

}
}

PRASHANT V KALE-PATIL
62
 Sort Array in Ascending Order
The ascending order arranges the elements in the lowest to highest order.

import java.util.Arrays;
public class SortArrayExample1
{
public static void main(String[] args)
{

int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};

Arrays.sort(array);
System.out.println("Elements of array sorted in ascending order: ");
//prints array using the for loop
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
}
}

Output:

Array elements in ascending order:


5
12
22
23
34
67
90
109

PRASHANT V KALE-PATIL
63
 Sort Array in Descending Order

The descending order arranges the elements in the highest to lowest order.

import java.util.Arrays;
import java.util.Collections;
public class SortArrayExample4
{
public static void main(String[] args)
{
Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205};
// sorts array[] in descending order
Arrays.sort(array, Collections.reverseOrder());
System.out.println("Array descending order: " +Arrays.toString(array));
}
}

Output:

Array descending order: [205, 110, 102, 78, 23, 11, 6, 4, 0, -1, -9]

 Largest Number is Array

public class LargestElement_array {


public static void main(String[] args) {

int [] arr = new int [] {25, 11, 7, 75, 56};


//Initialize max with first element of array.
int max = arr[0];
//Loop through the array
for (int i = 0; i < arr.length; i++) {
//Compare elements of array with max
if(arr[i] > max)
max = arr[i];
}
System.out.println("Largest element present in given array: " + max);
}
}
Output : 75

PRASHANT V KALE-PATIL
64
 To find the maximum and minimum value

package Array_Class;

public class Min_Max_Numbers {

private static int i;

static int getmin(int arr[], int n)


{
int r = arr[0];
for(int i=1; i<n; i++)
r= Math.min(r, arr[i]);
return r;

}
static int getMax(int arr[], int n)
{
int r = arr[0];
for (i=1; i<n; i++)
r= Math.max(r, arr[i]);
return r;

}
public static void main(String[] args) {
int arr[]= {12, 1234, 14, 34};
int n = arr.length;

System.out.println("Min Array = " + getmin(arr, n) );


System.out.println("Max Array = " + getMax(arr, n));
}

Output:
Min = 12
Max = 1234

PRASHANT V KALE-PATIL
65

You might also like