[go: up one dir, main page]

0% found this document useful (0 votes)
50 views74 pages

New 2

The document provides an overview of core Java concepts including its history, editions, and significance. It discusses how to install the JDK, write and run a basic Java program, and set the PATH environment variable. Key characteristics of Java like being object-oriented, platform independent, and featuring automatic memory management are also covered.

Uploaded by

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

New 2

The document provides an overview of core Java concepts including its history, editions, and significance. It discusses how to install the JDK, write and run a basic Java program, and set the PATH environment variable. Key characteristics of Java like being object-oriented, platform independent, and featuring automatic memory management are also covered.

Uploaded by

Vamshi Boddula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 74

corejava wednesday

CORE JAVA
`````````

java full stack corporate trainer from past 15+years


salesforce
mulesoft

for all mncs in pan india

infosys
wipro
tcs

...

java:
`````
what is java?

java is object oriented programming language

procedure oriented programming language


objet oriented programming-java
modula oriented programming language
scripiting oreitned programming langauge

purpose of programming lanaguage?

to develop the software/application.

what types of applications we have available in the market?

->desktop application
->distributed application

using java, what type of applications we can develop?

both types

java -> 1995 -> james gosling

->sun microsystem
->jse-java standard edition(core java)

->desktop/standalone applications

acrobatic reader,
antivirus,
calculator,
mspaint

standalone applications results are not sharable across the globe.

->jee-java enterprise edition

internet/distibuted applications

facebook.com
flipkart.com
gmail.com
etc..

internet based applications results are sharable across the globe &
standalone applications

because jee got implemented on top of jse

->jme-java micro/mobile edition

mobile applications/micro applications

android ->

significance of learning core java:


````````````````````````````````````

->to develop standalone applications


->to learn advanced java/jee
->to learn some tools like hadoop,tableu,salesforce,mulesoft...

programmers:

java program

c programmer -> turbo c


cpp programmer -> turbo cpp
java programmer -> jdk (java development kit)

java is open source


1995 sunmicrosystem

oracle purchased all the copyrights of sunmicrosystem

scjp
ocjp

url: www.oracle.com

how can we downlaod the this jdk :


```````````````````````````````````
https://www.oracle.com/in/java/technologies/downloads/#jdk19-windows

go to the above link and download the required jdk software

once it's done, install the jdk

once installation completed, to check whether it gets installed successfully or not

open the command prompt


and type below command

cmd:/>java -version

java version "19.0.1" 2022-10-18


Java(TM) SE Runtime Environment (build 19.0.1+10-21)
Java HotSpot(TM) 64-Bit Server VM (build 19.0.1+10-21, mixed mode, sharing)

java is case sensitive programming language

we have to follow the cases very strictly.

steps to follow to write the java program:


``````````````````````````````````````````
1.download the jdk software
2.install the software
3.select the editor
4.write the java program
4.save the java program (.java)
syntax: <filename>.java
saveas type: all files

6.compile the java program


7.run the java program

types of applications

jdk->java development kit

develop the java program


execute the java program

jdk provides two environments

1.development environment
2.runtime environment

jre -> it provies only runtime environment

java runtime environment

1.we are able to only execute the java applications

jvm -> java virtual machine

dhaaps
to connect -> runtime environment

rk
->jvm

jdk = jre + jvm

->purpose of learning programming langugage


->types of applications
->History of java
->different editions of java (jse,jee,jme)
->significance of learning core java
->how can we download the jdk software and installation process?
->steps to follow to write the java program
->jdk vs jre vs jvm

jdk -> java development kit

to develop java programs and to execute java programsm

oracle

www.oracle.com

structure of java program:

note: we should not question the syntaxes

syntax: it is a rule which is given by language vendor

as a programmer we have to follow otherwise we will get the errors.

class <classname>
{
public static void main(String[] args)
{
System.out.pritln("welcome to java sessions");
}//closing main method

}//class closing

what do you mean by compiling the java program?

as a programmer we have to follow syntaxes.

whether syntactially programmer follows correctly or not?


java compiler will check that

compile time errors.

compiler

only programmer wheenver he made mistakes syntactically then only


java compiler gave those errors.

java compiler ?

java compiler is the system defined java program which is running in the
background.

C:\Program Files\Java\jdk1.8.0_221\bin

how can we compile this java program?


`````````````````````````````````````

syntax: javac <filename>.java

javac Test.java

how can we execute the java program:


`````````````````````````````````````

syntax: java <classname>

java Demo

note:
while we are compiling the java program we should always gives filename
while we are executing/running the java program we should always
gives classname.

note: can we give both filename and class name are same?

yes
example:
``````````
class Demo
{

public static void main(String[] args)


{
//logic
System.out.println("welcome to java sessions");
}

structure of java program

we wrote the program

.java

filename.java

compile
execute

path:
`````
path is the location where java predefined tools are available.

C:\Program Files\Java\jdk-19\bin

location where all the java tools are available like


javac,javap,javadoc,java etc..

operating system couldn't recognize these predefined tools

to make it this as recognizable application, what we have to do?

we have to set the path

why should we set the path?

by default os couldn't recognize java commands, to make it recognize


by os we have to set the path(where all java tools are available)

how can we set the path?

we do have two ways are there to set the path

1.temporarily
2.permanently

set path ="C:\Program Files\Java\jdk-19\bin"


note:
once we set the path temporarily, till you close the command prompt
we can use all the java tools once you close it that session gets closed
again you will get error.

how to set the path permanently in java:


``````````````````````````````````````````
->click on start button

->click on edit the system environment variables

->click on environment variables button

->click on new button which is related to uservariables tab

->give the vairable name: path


viariable value: C:\Program Files\Java\jdk-19\bin

->click on ok(3 times)

if you specify a path as value for a system variable, that path


should be accessible to all user accounts.

if you set the path only in user variable , it will be effected only
to that particular user itself.

compiling the java program?

javac <filename>.java

who will compile this java program?


java compiler

what is java compiler?


it is a system defined java program

java compiler will cross check all the syntactical mistakes,


if programmer will not make any syntactical mistakes what java compiler will do?

java compiler will generate .class file from .java file

.java file ->source code -> developed by java programmer

.class file -> byte code -> generated by java compiler.

what is byte code:


`````````````````
byte code can be defined as intermediate code generated by the compiler
after the compilation of source code(java program).

******
this intermediate code makes java a platform independent language.
*******

.c
.exe
windows

unix operating system

.exe file in his unix os?


c programming language -> platform dependent programming language

java is platform independent programming language

irrespective of any os. we are allowed to run this .class file

to convert from one o.s -> other o.s

.class file generated based on the class name not based on the filename

.class file code is not human readable code.

who can read or who can understand this code?

answer: jvm(java virtual machine)

jre->it is providing runtime environment

jvm

java compiler input : file (.java)

how can we run this program:


``````````````````````````````
what jvm internally did?

jvm input -> class name(byte code)

jvm converts byte code into machinelevel code(binary code)

cd-> change the directory

to move to particular directory

cmd:/> e:

e:/>

cd.. -> move to back one directory


characterstics/features/buzzwords of java:
``````````````````````````````````````````

for notes download use below git link :


````````````````````````````````````````
https://github.com/somanapalli/dhaapps

-> java -> 1995

27years far
but still java is maintaining it's popularity

1.simple
2.object oriented
3.portable
4.platform independent
5.secured
6.Robust
7.Interpreted
8.Architectural neutral
9.High performance
10.Multithreaded
11.Distributed
12.Dynamic

data is getting stored inside an object


Garbage collector:
it is the system defined java program
which is running periodically
for the purpose of collecting unused memory spaces

why java is simple?

->syntax is based on c++


->java has removed some complex concepts such as explicit pointers,
operator overloading
->There is no need to remove unreferenced objects because
there is an automatic garbage collection in java.
->java syntaxes are very userfriendly.

object oriented:
```````````````

xyz
programming language

->oopl

have to follow some principles?


java is also one of the oopl
becaue it follows those principles
oops principles.->candain organization -> omg

->inheritance
->polymorphism
->abstraction
->encapuslation

everything in java is an object.

software /application
it is a combination of different objects that incorporate both data and behaviour.

Student

java is platform independent:


```````````````````````````````

wora ->write once run/reuse anywhere

irrespective of any o.s we are allowed to execute java programs.

bytecode->platform independent code

Robust:
````````
strong
java is strong

because in postivie scenario

and asweel as in negative scenario

->it uses strong memory management


->there is lack of pointer that avoids security problems
->java provides automatic garbage collection wich runs on the jvm to
get rid of objects which are not being used by a java application
any more.
->There are exception handling and the type checking mechanism in jaa.

any syntatical errors -> compile time errors


logically if you do any mistakes -> at runtime by the jvm

runtime errors ->exceptions

atm machine

account-> 5000

withdraw -> 7000 rs


java.lang.Exception on the console

atm console: insufficeint funds

architectural neutral:
``````````````````````
int -> 4 bytes

32 bit -> 64 bit

int -> 2 bytes -> 32 bit


int -> 4 bytes -> 64 bit

portable:
``````````
portable = pi + an

distributed:
`````````````````

RMI
EJB
spring ,springboot,microservices

-> DISTRIBUTED APPLICATIONS

this feature of java makes us able to access files by calling


the methods from any machine on the internet.

facebook.com

multithreaded:
````````````````

multiple threads

thread:
separate progam executing parallely.

1 programmer -> 20 days

20 programmers -> 1 day

we can write java programs that deal with many tasks at once
by defining multiple threads.

the main advantage of multi threading is that it doesn't occupy memory


for each thread.
it shares a common memory area.

threads are important for multimideia , web applications etc.


dynamic:
````````
it supports the dynamic loading of classes.

class supposed to be loaded in to the jvm


class loader subsystem
->jvm

->main memory
->RAM

-high performance

->secured

java is object oriented programming language

because it follows oops principles

inheritance
polymorphism
abstraction
encapuslation
-omg organization

in java language, how can we achieve the above principles?

by using these two concepts


class
object

note:
every java program should starts with by defining the class.

class:
``````
class is a collection of

-variables
-methods into a single unit.

main() is mandatory to execute the java program


because java execution starts from main() only.

jvm will internally call this main()

note:

without main() we can compile the java program but we can't execute
the java program
since java execution / jvm internally calls the main() when you
execute the java program.
variables:
``````````
100 in some specified user defined name
inetrnally java will allocate some address (system defined address)

it is highly recommended to store the data in our own variable names

we can easily access whenever you want.

readability will be improved.

purpose of variable:

to store the data.

stid =100;//valid or invalid

java is strongly typed programming language

we have to specify the datatype.

datatype:

what type of data we are storing we should specify that type


while we are storing the data.

int stid = 100;

syntax of varialbe declaration:

<datatypename> <variablename> = <value>;

java is case sensitive programming language


we have to take care about upper case and lower case variables.

rules to declare the variable name:


``````````````````````````````````````
1.variable name should always starts with alphabet
it should not start with numeric

2.no special characters are allowed except $ and _(underscore)

3.we are not allowed to use varaible names as java reserved words.

4.variable names are case sensitive.

5.blank spaces are not allowed while we are declaring the variables.

<datatypename> <variablename> = <value>;


different datatypes are available in java.

4 categories of datatypes

1. integer

2. characters

3.float category

4.boolean category

integer category datatypes:


```````````````````````````

are used to store numeric values.

we have 4 different integer datatypes are availble in java

1.byte -> 1 byte -> 8 bits


2.short -> 2 bytes -> 16 bits
3.int -> 4 bytes -> 32 bits
4.long -> 8 bytes -> 64 bits

the above datatypes are predefined datatypes /prmitive datatypes


which are given by sunmicrosystem

note:
`````
A primitive type is predefined by the language and is named by a reserved keyword.

note:

all the java reserved keywords must be always in lower case only.

note:
every datatype is maintaining two things

1.range

2.memory size

based on the value or range of data we are storing we are selecting


the corresponding datatype.

byte b = 100

to calculate any datatype range i have one formula

-2^n-1 to (2^n-1) - 1
where n -> no.of bits occupied by the datatype
range of the byte datatype.

byte -> 1 byte - > 8 bits

-2^7 to (2^7) -1

-128 to 127
is the range of the byte datatype.

byte b =128;

character category:
````````````````````
to store single character we have to use character category data.
note:
to store single character it is mandatory to store with in single quotes.

note: char is the datatype


memory size: 2 bytes of memory

because java internally follows unicode


java supports 18 international languages

class Demo
{

public static void main(String[] args)


{
//invalid : int 5stid=100;
//valid : int st$id=100;
//invalid: int st*id=100

//invalid : int int = 100;


//invalid: int st id=100;
//int stid=100;

//invalid :byte stid = 128;

//int stid = 100;

char stname ='r';

System.out.println(stname);

java is object oriented programming language

->since it follows oops principles which are given by omg


organization .

1.inheritance
2.polymorphism
3.abstraction
4.encapuslation
to achieve above principles we are using two concepts in java
1. class
2. object

class:
``````
class is a collectio of variables and methods into a single unit.
that single unit is known as class.

every java program should starts with by defining the class only.

class <classname>
{
//vairables

//methods

java doesn't support non member variables and non member methods

variable:

variable is used to store the data

<datatypename> <variablename> = <value>;

int stid = 100;

class is

-variables
-methods

method:
``````
method is the place where we are writing the logic
to perform some operation based on the requirement.

note
if you want to define your own logic , define your own method.

syntax
```````
[accessmodifier] <returntype> <methodname>([if any parameters])
{

//logic
}
ex:

public void display()


{
System.out.println("iam from display");
}

if a method is not returning any value to represent that we are using one return
type i.e void

int getAge()
{
return 23;
}

if a method is returning any value, using return keyword we are allowed to return
the value.

note:
return type and return value must be compatible with each other

public void sum(int x, int y)


{
System.out.println(x+y);
}

sum(4,5);

public int sum(int x, int y)


{
return x+y;
}

->define the method which returns name of the student?

String getStudentName()
{
return "rama";
}

->define the method whcih returns age of the student?

public int getStudentAge()


{
return 78;
}
->define the method which takes two integer parameters and return the sum value?

int getSum(int x,int y)


{
return x+y
}

->define the method which takes two string parameters and gives
concatination of the string?

String getConcatination(String x, String y)


{
return x+y;
}

getConcatination("rama","krishna");

ramakrishna

example:
`````````
class Student
{
//variable declaration
static int stid=100;
static String stname ="Rama";

//method definition
public static void display()
{
System.out.println(stid);
System.out.println(stname);

public static void main(String[] args)


{
//calling display()
display();

example on Employee class:


````````````````````````````
/*define the class Employee which declares empid and empname and display their
details?*/

class Employee
{
static int empId =100;
static String empName="manikbasha";
//define the method

public static void getDetails()


{
System.out.println(empId);
System.out.println(empName);
}
public static void main(String[] arg)
{
getDetails();
}
}

class is a collection of

-variables
-& methods into a single unit.

java is object oriented programming language


-> class

-> object

when we define a class, there is no memory space created


for the properties which we are declaring inside the class.

object:
``````
instance of a class is known as object.

instance:
````````
allocating suffficeint amount of memory space for the
properties of the class.

for a single class, how many objects we can create?

as many as we want based on the requirement

how can we create the object :

syntax:

<classname> <objectname> = new <classname>();

Student obj = new Student();

Student -> name of the class


obj -> object name
= -> assignment operator
new ->dynamic memory allocation operator
Student() -> constructor

the object for Employee

->define Account class with variables accountId,accountName


and display their details by using object?

hpw to define the class


how to create the object

class-
collection of
variables and methods into a single unit.

object
-instance of a class is known as object
-allocating sufficient amount of memeory space for the
properties of the class.

jvm

java program execution starts from main()


who will call main();

jvm will call this main()

note:
using object, we can access the properties and as well as
we can update the values based on the requirement.

example:
``````````
class Product
{
int productId = 100;
String productName ="soap";

public void getProductDetails()


{
System.out.println("Product id: " + productId);
System.out.println("Product Name: " + productName);

public static void main(String[] args)


{
//create the object for my class (Product)
Product p = new Product();

//using object we are chanigng the values


p.productId=101;
p.productName="laptop";

p.getProductDetails();

define Student class with stid, stname and update the values
with your own name using object?

we can create multiple objects for a single class, where each object is having
their own address.

example:
````````
class Product
{
int productId = 100;
String productName ="soap";

public void getProductDetails()


{
System.out.println("Product id: " + productId);
System.out.println("Product Name: " + productName);

public static void main(String[] args)


{
//create the object for my class (Product)
Product p1 = new Product();

Product p2 = new Product();

Product p3 = new Product();

System.out.println(p1);
System.out.println(p2);
System.out.println(p3);

}
}

College

1000 students

1 object is not enough to store 1000 students information


1000 objects are required

note:
`````

object name is always must be unique, you can't declare multiple


objects with the same name.

example:
`````````
class Employee
{

//variables
int empId=100;
String empName="rama";
double empSalary=9878.87;

//method
public void getEmpDetails()
{
System.out.println("====================");
System.out.println("employee id is: " + empId);
System.out.println("employee name is : " + empName);
System.out.println("employee salary is: " + empSalary);
}

//main method
public static void main(String[] args)
{

//create the object for the Employee class


Employee obj1 = new Employee();

//create the object for the Employee class


Employee obj2 = new Employee();

System.out.println(obj1);
System.out.println(obj2);
}
}

using object name, i want to change the values?

is it possible or not?

yes it is possible, please observe below program


class Employee
{

//variables
int empId=100;
String empName="rama";
double empSalary=9878.87;

//method
public void getEmpDetails()
{
System.out.println("====================");
System.out.println("employee id is: " + empId);
System.out.println("employee name is : " + empName);
System.out.println("employee salary is: " + empSalary);
}

//main method
public static void main(String[] args)
{

//create the object for the Employee class


Employee obj1 = new Employee();

//change the values using object name

obj1.empId=101;
obj1.empName="manik";
obj1.empSalary=8989.99;

//call the method


obj1.getEmpDetails();

}
}

instance(non static) vs static:


`````````````````````````````````

int a;//a is non static variable

static int a;//a is static variable

public void m1()//non static method or instance method


{
//instance area
}

public static void m1()//static method


{
//static area
}

by default main method is static or non static?


the area which belongs to non-static method is known
as non-static area or instance area

the area which belongs to static method is known as static area.

by default main method area is also static area

note1:
``````
from static area, to access non-static properties using object name we can access

note2:
``````
from static area or non-static area, to access static properties using
below way we can access

1.directly we can access


2.using classname we can access

note:
``````
whenever we create the object, memory locations will be created for
non-static or instance properties not for static properties.

q?
when should we declare any property as static property?

answer: if a property is common to all , then go and declare that


property as static

once we declare any property as static , then memory will be created


only once by the classloader subsystem
it is the sub part of jvm.

example:
````````
class Employee
{

//non-static variables
int empId=100;
String empName="rama";
double empSalary=9878.87;

//static property
static String companyName="infosys";

//instance method or non-static method


public void getEmployeeDetails()
{
//instance area

System.out.println("-------------------");
System.out.println("employee id : " + empId);
System.out.println("employee name: " + empName);
System.out.println("employee salary: " + empSalary);
System.out.println("employee company name: " + companyName);

//main method
public static void main(String[] args)
{
//static area
Employee obj = new Employee();
System.out.println("employee id: " + obj.empId);
System.out.println("employee name: " + obj.empName);
System.out.println("employee salary:" + obj.empSalary);

System.out.println("employee company name: " +companyName);

companyName="TCS";

System.out.println("employee company name: " +Employee.companyName);

//call the method using obect name

obj.getEmployeeDetails();

}
}

introduce ide:
integrated development environment

eclipse is one of the open source ide.

myeclipse
netbeans
intellij
etc..

how to download eclipse and install in your machine?


````````````````````````````````````````````````````
linK:
https://www.eclipse.org/downloads/

ctrl+ -> is to increase the font size


ctrl - -> is to decrease the font size

how can we create the java project:

click on file
|
new
|
project
|
java project
|
project name: corejava
|
uncheck module-info.java
|
click on finish

once we create the java project define the java class


by right click under src folder
click on new

|
class
|
name: Test1
|
click on finish

one important advantage of writing the code in eclipse:

whatever the code we are writing inside eclipse is autocompiled

we no need to compile the code separately

advantages of writing the code in eclipse:


````````````````````````````````````````````
note:
the code which you are writing inside ide, it is autocompiled
code or precompiled code.

1. Using IDE will cost you less time and effort .

2.Navigation is made easier.

3.Auto completion- one of the best features , you don’t have to remember all.

4.Refactoring

5.Error debugging is easy , you can easily navigate to Error line.

6.All files can be viewed and managed at same screen.

7.Organizing you imports.

8.Downloading requires packages at ease.

In addition to these specific Eclipse advantages are:

It is free and open source.


Industrial level of development
It supports many other languages other than JAVA.
Framework integration like Junit and TestNG and other plugins can be done easily.
Since Eclipse tools are open source, they are quickly updated with the latest
technology that can be integrated into existing code.
constructor:
`````````````
example without constructor:
````````````````````````````

public class Student {

//varaibles declaration
int stid;
String stname;

void setValues()
{
stid=100;
stname="Rama";

void display()
{
System.out.println("student id is : " + stid);
System.out.println("Student name is : " + stname);
}

//defining main method


public static void main(String[] args) {

Student obj = new Student();

obj.setValues();
obj.display();

}
}

constructor:
````````````
constructor is a special member method

->it must be similar to class name


->it doesn't return anything even void also.

purpose:
`````````
to initialize the object

object ->data
to initalize the data

int a;//variable declaration


a=100;//assigning the value

int a=100;//variable initialization

variable initialization= variable declaration + assigning the value.


in our class, if we don't have any constructor, if you create the object using
default constructor then java compiler first check
whether in our class constructors are there or not
if not , java compiler automatically generates one default constructor known as
system generated default constructor.

purpose of system generated default constructor:

it will intilize the default values


based on the datatype we have default values are there

for integer category datatypes default value is 0


for String datatype default value is null

for float -> 0.0


for character -> single space

note:
whenever we create the object corresponding constructor will be
invoked to intilzie the values.

it is not like normal method

example :
`````````

public class Student {

//varaibles declaration
int stid;
String stname;

//system generated default constructor


//purpose: it will assign the default values

/*public Student()
{
stid=0;
stname=null;
}*/

//user defined default constructor

Student()
{
stid=100;
stname="Rama";
}

public void display()


{
System.out.println("Student id is : " + stid);
System.out.println("Student name is: " + stname);
}
//defining main method
public static void main(String[] args) {

Student obj = new Student();

obj.display();

}
}

types of constructors:
`````````````````````````
->default constructor

->parameterized constructor

default constructor is again two types

1.system defined default constructor


-to intilize default values

2.user defined default constructor

-to initliize our own values

2.parameterized constructor:

constructor which takes parameters is known as


parameterized constructor.

example on parameterized constructor:


``````````````````````````````````````

public class Student {

//varaibles declaration
int stid;
String stname;

//define parameterized constructor


public Student(int x, String y)
{
stid=x;
stname=y;

}
public void display()
{
System.out.println("Student id is : " + stid);
System.out.println("Student name is: " + stname);
}

//defining main method


public static void main(String[] args) {

Student obj = new Student(100,"rama");

obj.display();

}
}

advantage of parameterized constructor:


````````````````````````````````````````
while we are creating the object only we can initilize the values.

can we define both default and parameterized constructor inside


a single class?

note:
default constructor is always availble in only one form
but we can define multiple parameterized constructors

default constructor we can define only once.

example:
````````

public class Student {

//user defined default constructor


public Student()
{
System.out.println("iam user defined default constructor");
}

//parameterized constructor
public Student(int x)
{
System.out.println("iam single parameterized constructor");
}

//defining main method


public static void main(String[] args) {

//create the object using default constructor

Student obj = new Student();

//create the object using parameterized cosntructor

Student obj1 = new Student(3);


}
}

i have 100 constructors are there inside my class, so to execute


these 100 constructors how many objects we have to create?

this:
````
'this' is a java reserved keyword used for the following
two purposes.

purpose:
it is always pointing to current class object.

1.it is used to differntiate class level variables and method level or


cosntructor level when both are same.

example:
``````````

public class Student {

int stid;
String stname;

public Student(int stid, String stname)


{
this.stid=stid;
this.stname=stname;
}
public void display()
{
System.out.println("student id is: " + this.stid);
System.out.println("student name is : " +this.stname);
}
//defining main method
public static void main(String[] args) {

//create the object using parameterized constructor

Student obj = new Student(100,"rama");

//calling display()
obj.display();

}
}
constructor chaining:

from one constructor if we call another constructor is the concept


of constructor chaining

it is possible by using following syntax using this keyword.

this() -> to call current class default constructor

this(...) -> to call current class parameterized constructor

example:
````````

public class Student {

public Student()
{
//call the parameterized constructor of the same class

this(100);

System.out.println("iam default constructor");

public Student(int x)
{

System.out.println("iam parameterized cosntructor");


}

//defining main method


public static void main(String[] args) {

//create the object for default constructor

Student obj = new Student();

}
}

note:
cosntructor call must be the first executable statement inside a
constructor otherwise we will get compile time error.

note:
if we keep on calling the constructors we will get compile time error
saying that recursive constructor invocation is not possible.

when we have 3 constructors:


public class Student {

public Student()
{
//call the double paramterized constructor

this(100,200);
System.out.println("iam default constructor");

}
public Student(int x)
{

System.out.println("iam parameterized cosntructor");


}

public Student(int x, int y)


{
//call the single paramterized constructor

this(100);
System.out.println("iam double parameterized constructor");
}

//defining main method


public static void main(String[] args) {

//create the object for default constructor

Student obj = new Student();

}
}

note:

constructor call always must be the top to bottom but execution


happen from bottom to top.

control statements/conditional statements


``````````````````````````````````````````
java compiler executes the code from top to bottom.

The statements in the code are executed according to the order


in which they appear.

However, java provides statements that can be used to control the


flow of the java code. such statements are called control statements
java provides three types of control statements

1.Decision making statements


2.loop statements
3.jump statements

1.Decision making statements:


`````````````````````````````

as the name suggests, decision making statements decide which statement


to execute and when.

Decision making statements evoluate boolean expression and


control the progrma flow depending upon the result of the condition
provided.

There are two types of decision making statemetns in java, i.e


-if
-switch

if statement:
``````````````
this staement is used to evoluate a condition.

the condition of the if statement gives a boolean value either true


or false.

in java, there are four types of if statements

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

1.simple if statement:
``````````````````````
syntax:

if(condition)
{
//statemetns
}

example:
````````

public class Student {

public static void main(String[] args) {


int x=10,y=20;

if(x+y>20) {
System.out.println("x+y is greater than 20");
}

}
}

2.if-else statement:
````````````````````
a block is a concept of in between { and }

if
{

if else staement is an extension of if statement, which uses


another block of code. i.e catch block.

The catch block is executed if the condition of the if block is


evlouated as false.

syntax:

if(condition){
//statement1;//executes when condition is true
}
else{
statement2 ;//executes when condition is false.
}

example:
`````````

public class Student {

public static void main(String[] args) {

int x=10,y=20;

if(x+y<20) {
System.out.println("x+y is less than 20");
}
else
{
System.out.println("x+y is greater than 20");
}
}
}

if-else-if ladder:
`````````````````````
it contains

1 if block

multiple else if blocks

1 else block

syntax:

if(condition1)
{
statement1;//executes when condition 1 is true
}
else if(condition2)
{
statement2;//executes when condition2 is true
}
else if(condition3)
{
statement3;//executes when conditio3 is true
}
else
{
statement4;//executes when all the condistions are false.
}

example:
`````````

public class Student {

public static void main(String[] args) {

String city="Agra";

if(city=="Chennaih") {
System.out.println("city is chenniah");
}
else if(city=="Hyderabad")
{
System.out.println("city is Hyderabad");
}
else if(city=="pune")
{
System.out.println("city is pune");
}
else
{
System.out.println(city);
}

}
}

nested if statement:
```````````````````
in nested if statement, the if staetment can contain a if

syntax:

if(condition1)
{
staetment1;//executes when condition1 is true

if(condition2)
{
statement2;//executes when condition2 is true
}
else
{
statement3;//executes when condition2 is false.

}
}

example:
`````````

public class Student {

public static void main(String[] args) {

int a=10,b=20;
if(a==10)
{
if(b!=20)
{
System.out.println("dhaaps");
}
else
{
System.out.println("ramakrishna");
}

}
}
}

switch statement:
````````````````

switch statement executes one statement from multiple conditions.


it is like if-else-if ladder statement.

1.there can be one or n number of case values for a switch expression.

2.the case value must be of switch expression type only.


the case value must be literal or constant.it doesn't allow
variables.

3.the case value must be unique, in case of duplicate value it will give you
compile time error.

4.java switch expression type must be of byte,short,int,long(with its


wrapper type),enums and string.

5.each case statement can have a break statement which is optional.

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 case values are not matched

example:
````````

public class Student {

public static void main(String[] args) {

int number=40;

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:System.out.println("not in 10,20 or 30");
}
}
}
loop statements:
`````````````````
Loops in Java is a feature used to execute a particular part of the program
repeatedly if a given condition evaluates to be true.

-for loop
-while loop
-do while loop

for loop:
`````````
purpose:

this for loop is used to iterate a part of the program several/multiple times.

when should you use for loop?

if the number of iteration is fixed, it is recommended to use


for loop.

-simple for loop


-nested for loop
-for each or enhanced for loop
-labelled for loop

simple for loop:


````````````````
we can initilize the variable,
check the condition ,
increment/decrement the value

it consitsts of four parts

1.initialization -it is an optional condition

2.condition

3.increment/decrement

4.statement

syntax:

for(initialization;condition;increment/decrement)
{
//statement
}

example:
```````
//program for displaying first 10 numbers using for loop
public class Test1 {

public static void main(String[] args)


{
int i=1;
for(i=1;i<=10;i++)
{
System.out.println(i);
}

}
}

//program to displaying first 10 numbers in reverse order?

example:
`````````
//program for displaying first 10 numbers using for loop
public class Test1 {

public static void main(String[] args)


{
int i=10;
for(;i>=1;i--)
{
System.out.println(i);
}

}
}

display even numbers from 1 to 10 using for loop and if statement?

10

example:
``````````
//program for displaying first 10 numbers using for loop
public class Test1 {

public static void main(String[] args)


{

for(int i=1;i<=10;i++) {
if(i%2==0)
{
System.out.println(i);
}

// % operator is giving you reminder

}
}

display odd numbers from 1 to 10 using for loop and if statement?

example:
````````
//program for displaying first 10 numbers using for loop
public class Test1 {

public static void main(String[] args)


{

for(int i=1;i<=10;i++) {
if(i%2!=0)
{
System.out.println(i);
}

// % operator is giving you reminder

}
}

nested for loop:


````````````````
defining for loop inside another for loop.

if we have a for loop inside another for loop, it is known as


nested for loop.

The inner for loop executes completely whenever outer for loop
executes.

once control comes from outerfor loop to inner for loop, it executes inner for loop
until the condition became false, once condition false
again it goes back to outerfor loop then comes to inner loop like this
flow is going on.

example:
````````
//program on nested for loop
public class Test2 {

public static void main(String[] args) {

// loop of i

for (int i = 1; i <= 3; i++) {


// loop of j
for (int j = 1; j <= 3; j++) {
System.out.println(i + " " + j);
}
}

}
}

/*output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3*/

output:
````````
*
* *
* * *
* * * *
* * * * *

example:
`````````

public class Test3 {

public static void main(String[] args) {

//define the outer for loop

//outer for loop


for(int i=1;i<=5;i++)
{
//inner for loop

for(int j=1;j<=i;j++)
{
System.out.print("*");
}

System.out.println();

}
}
}

output:
````````
* * * * * *
* * * * *
* * * *
* * *
* *
*

for each loop or enhanced for loop:


````````````````````````````````````

this enhanced for loop introduced from java 1.5 version onwards.

purpose:
``````````
it provides an alternative approach to traverse the array or collection in java.

it is mainly used to traverse the array or collection elements.

how the values will be stored inside an array variable?

based on the index

array index starts from 0th location .

int a[]={100,200,300};

sysout(a[0]);
sysout(a[1]);

note:
if the array length is 'n'
maximum index is 'n-1'
because array index starts from 0 th location

syntax of foreach loop:


````````````````````````
it consistes of datatype with the varaible followed by a colon (:) , then array or
collection varaible.

for(datatype variable:actualvaraible)
{

/body of for each loop


}

int a[]={10,20,30,40,50};
for(int b:a)
{
System.out.println(b);
}

example:
`````````
class Test4
{

public static void main(String[] args) {

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

System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);

System.out.println("=======using for loop displaying array


elements============");

for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}

System.out.println("======using for each loop displaying array


elements===");

for(int b:a)
{
System.out.println(b);
}

}
}

//using for each loop calculate total of array elements


int a[] ={1,2,3,4};

answer:
```````

public class Test5 {

public static void main(String[] args) {

int a[]= {1,2,3,4};


int sum=0;
for(int b:a)
{
sum=sum+b;
}
System.out.println("sum of array elements is : " + sum);
}

java labelled for loop:


```````````````````````
we can have a name of each java for loop.
To do so, we used label before the for loop.
it is useful while using the nested for loop as we can break/continue
specific for loop.

syntax:

labelname:

for(intialization;condition;increment/decrement)
{
//code to be executed
}

example:
`````````
//program on nested for loop
public class Test2 {

public static void main(String[] args) {

// using label for outer for loop


aa:
for (int i = 1; i <= 3; i++) {
// using label for inner forloop of j

bb:
for (int j = 1; j <= 3; j++) {

if(i==2&&j==2) {
break aa;
}
System.out.println(i + " " +j);
}
}

}
}

/*output:
1 1
1 2
1 3
2 1
*/

java while loop:


`````````````````
the java while loop is used to iterate a part of the program
repeatedly until the specified condition is true.
as soon as the condition becomes false, the loop automatically stops.

the while loop is considered as a repeating if statement.


if the number of iternation is not fixed, it is recommended to used the while
loop.

syntax:
```````
while(condition)
{
//code to be executed;
increment/decrement ;
}

write one java program displaying 1 to 10 numbers using while loop?

example:
````````

public class Test6 {

public static void main(String[] args) {

//initialization
int i=1;
//while loop

while(i<=10)
{
System.out.println(i);
i++;
}
}

do this program to display the 1 to 10 numbers in reverse order?

public class Test6 {

public static void main(String[] args) {

//initialization
int i=10;
//while loop

while(i>=1)
{
System.out.println(i);
i--;
}
}

do while loop:
``````````````
do while loop is used to iterate a part of the program repeatedly,until the
specified condition is true.

if the number of iteration is not fixed and you must have to execute
the loop at least once, it is recommended to use a do-while loop.

do while loop is called an exit control loop.

java do while loop is executed at least once because condition is


checked after loop body.

syntax:
```````
do{

//code to be executed/loop body


//update staetment

} while(condition);

example:
````````

public class Test7 {

public static void main(String[] args) {

int i=1;
do {
System.out.println(i);
i++;

} while (i>=10);

jump statements:
````````````````
Jump statements are one of the types of control statements in Java that directs the
flow of execution in a program.

break
continue

break statement:
````````````````
it is encountered inside a loop,
the loop is immediately terminated and the program control resumes at the next
statement following the loop.

break statement is used to break loop or switch statement.


it breaks the current flow of the program at specified condition.

in case of inner loop, it breaks only inner loop.

we can use java break statement in all types of loops such as

-for loop,
-while loop
-do while loop

syntax:

jump-statement;
break;

example:
````````

public class Test8 {

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

break statement with inner loop:

it breaks inner loop only if you use break statement inside


the inner loop.

example:
`````````

public class Test8 {

public static void main(String[] args) {

//using for loop


for(int i=1;i<=3;i++)
{
//inner loop
for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
break;
}
System.out.println(i + " " +j);
}

3 assignments:

use break statement inside labelled for loop?

use break statement inside while loop?

use break statement inside do-while loop?

continue statement:
````````````````````
it is used in loop control structure when you need to jump
to the next iteration of the loop immediately.

it can be used with all types of loops such as for,while and dowhile

purpose: it is used to continue the loop.

note:

it continues the current flow of the program and skips the remaining
code at the specified condition .

for(int i=1;i<=10;i++)
{
if(i==5){
continue;
}
sysout(i)
}
1
2
3
4
6
7
8
9
10

in case of an inner loop, it continues the inner loop only.

syntax:

jump-statement;
continue;

example:
````````
`
public class Test8 {

public static void main(String[] args) {

//using for loop


for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.println(i);

example of continue statement with inner for loop:


`````````````````````````````````````````````````````

public class Test8 {

public static void main(String[] args) {

//using for loop


for(int i=1;i<=3;i++)
{
//inner loop
for(int j=1;j<=3;j++)
{
if(i==2&&j==2) {
continue;
}
System.out.println(i + " " + j);
}

}
}

assignment:
```````````
use continue statement in labelled for loop?
use continue statement in while loop?
use continue staetment in do while loop?

type casting in java:


`````````````````````
in java, type casting is a method or process
that converts a datatype into another datatype.
in both ways

-manually
-automatically

the automatic conversion is done by the java compiler


manual conversion is done by the programmer .

there are two types of type castings

1.widening type casting


2.narrowing type casting

1.widening type casting:

converting a lower data type into a higher datatype is called


widening type casting.

it is also known as implicity conversion.

it is done automatically.

it is safe because there is no chance to lose the data.

widening type casting:


``````````````````````````
byte -> short -> int -> long -> float -> double

example:
`````````

public class Test9 {

public static void main(String[] args) {

int x=7;
//automatically converts the integer type into long type
long y = x;

//automatically converts the long type into float type


float z = y;

System.out.println("before conversion , int value " + x);


System.out.println("after conversion, long value: " + y);
System.out.println("after conversion, float value: " +z);

narrwoing type casting:


```````````````````````````

note:
in case of narrowing type casting, we might get a chance to lose the data in the
explicit conversion .

double->float->long->int->short->byte

converting a higher data type into a lower data type is called


narrowing type casting.

it is also called as explicit conversion

it is done manually by the programmer.

if we do not perform casting then the compiler gives you compile time
error.

example:
``````

public class Test9 {

public static void main(String[] args) {

double d= 234.5656;

//converting double datatype into long data type


long l =(long)d;

//converting long datatype into int datatype

int i = (int)l;

System.out.println("before conversion , double value " + d);


System.out.println("after conversion, long value: " + l);
System.out.println("after conversion, int value: " +i);

}
}

oops principles:
````````````````
->inheritance
->polymoprhism
->abstraction
->encapsulation

inheritance:
```````````
inheritane is the process of taking the properties from one class
to another class

class
i have some logic is there

the same logic if i wanted to use in anotehr class.?

if we redefine code duplication/redundancy will be increased

memory consumption also gets increased

performamnce of the application will be degraded

instead of redefining the logic, try to reuse it

parent class/base class/super class:

it is the class which is giving the properties

child class/sub class/derived class:


it is the class which is taking the properties

using "extends" keyword we can achieve the concept of inheritance.

note:
whenever we applied the concept of inheritance, it is highly
recommended to create the object for child class not for parent class

if we create the object for parent class, memory locations will be created only for
parent class properties.

so that , with the parent class object we are allowed to access only
parent class properties

whenever we crete the object for child class, memory locations will
be created for both parent and child class properties.
so with this child class object, we are allowed to access
both parent and child class proeprties.

what is the primary advanatage of inheritance:

1.reusability
2.code redundancy will be decreased
3.performance of the application will be improved.

types of inheritances:
`````````````````````
in java, we have 5 types of inheritances

1.single /simple inheritance


2.multilevel inheritance
3.multiple inheritance
4.hierarchical inheritance
5.hybrid inheritance

single / simple inheritace:

it is the inheritance which contains


-single base class/parent class
-single child class

A
|
B

multilevel inheritance:

it contains

single parent clas

multiple intermediate base classes

single child class

A
|
B
|
C

hierarchy:
`````````
class A
{
}
class B extends A
{
}
class C extends B
{
}
in one context, B class is acting as sub class or child class

but in anotehr context, same B class is acting as super class or


parent class.

such kind of classes are known as intermediate parent classe(s).

multiple inheritance:
`````````````````````

mutliple inhertiance contains

1.multiple parent classes


2.single child class

A B C D ....

hierarchy:
```````````
class Z extends A,B,C,D,...
{
}
in java, through classes multiple inheritance is not possible

why?

class A{
sum()
}
class B {sum();}

z obj = new z();


obj.sum();

Interface concept -> multiple inheritance.

hierarchical inheritance:

single parent class/base

mutliple child classe(s)

B C D E ....

hierarchy:
`````````
class A
{
}
class B extends A
{}
class C extends A{}
class D extends A{}
....

hybrid inheritance:
````````````````````
it is the combination of any two possible inheritance
types.

A
|
B
|
C D E

SINGLE + HIERARCHICAL = HYBRID INHERITANCE

hierarchy:
``````````

class A{}
class B extends A{}
class C extends B{}
class D extends B{}
class E extends B{}

assignments:
do one one program on top of each and every
inheritance type.

note:
when you apply inheitance concept, it is
highly recommende to create the object for
child class.

A.java:
```````
//parent class cum business logic class
public class A {
public A()
{
System.out.println(this.hashCode());
}
public void sum(int x, int y)
{
System.out.println("sum is : " + (x+y));
}

B.java
````````
//child class cum business logic class cum executin logic class
public class B extends A {
public void sub(int x, int y)
{
System.out.println("substraction: " +(x-y));
}

public static void main(String[] args) {

//child class object creation

B obj = new B();

obj.sum(2, 3);
obj.sub(5, 4);

}
note:
using extends keyword, we are allowed to extend from single class
to single class only not from more than 1 parent class,if we try for that, we will
get compile time error.

polymoprhism:
`````````````

one of the oop principle.

defintion:

Polymorphism is one of the core concepts of object-oriented programming (OOP) and


describes situations in which something occurs in several different forms.

In computer science, it describes the concept that you can access objects of
different types through the same interface

polymoprhism -> many forms

how can we achieve this polymoprhism:

we have two conecpts ,

1.method overloading
2.method overriding

method overloading:
```````````````````
method name is same
but signature is different

signature:

chanigng type of parameters


changing in no.of parameters
changin in order of parameters atleast
void sum(int x, float y)
{
}

void sum(float x, int y)


{
}
void sum(double x, double y)
{
}

void sum(int x, int y , int z)


{
}

how can we overload the method?

by defining the method name as same


and by changing signature.

advantage:

readability of the code improves.

Method overloading increases the readability of the program.

This provides flexibility to programmers so that they can call the same method for
different types of data.

example:
`````````

public class Demo1 {

public void sum(int x, int y)


{
System.out.println("integer sum is : " +(x+y));
}
public void sum(double x, double y)
{
System.out.println("double sum is : " +(x+y));

}
public static void main(String[] args) {
Demo1 obj = new Demo1();

obj.sum(10,20);

obj.sum(2.3,3.4);

}
note:
to achieve the concept of method overloading one class is enough.

we don't require more than one class.

assignment:

rewrite the above program or overload sum() method by changing

-no.of parameters
-order of parameters

method overriding:
````````````````````

method name is same

but logic is different from parent class to child class.

note:
to achieve the concept of method overriding minimum we require
two classes with parent-child relation.

note:
why should we go for this method overriding?

answer:

if i don't want to use existing logic or original logic which is available inside
parent class,
then i should go for method overriding because inside the child class
we will get a chance to override the exisitng logic

or
if i want my own logic then i can go for method overriding.

what is @Override annotation?

The @Override annotation denotes that the child class method overrides the base
class method.

For two reasons, the @Override annotation is useful.

If the annotated method does not actually override anything, the compiler issues a
warning.

It can help to make the source code more readable.

A.java:
````````
//PARENT CLASS
public class A {

public void sum(int x, int y)


{
System.out.println("sum is : " + (x+y));
}

B.java:
```````

//child class
public class B extends A{

@Override
public void sum(int x, int y)
{
System.out.println("substraction: " +(x-y));
}

public static void main(String[] args) {

B obj = new B();


obj.sum(4, 3);
}

polymorphism

method overloading
method overriding

in java, we have two types of polymoprhisms

1.compiletime polymoprhism

->polymorphism can be decided at compiletime is known as


compiletime polymoprhism

->method calling is binded or associated with specific method at compiletime


by using reference varaible only not based on the
object type.

->method overloading is the best example to achieve the concept


of compiletime polymoprhism.

example:
````````

public class Demo1 {

public void sum(int x, int y)


{
System.out.println("integer sum is : " +(x+y));
}
public void sum(double x, double y)
{
System.out.println("double sum is : " +(x+y));
}
public static void main(String[] args) {

//object declaration
Demo1 obj ;//available at compiletime

/*
* object referencing:
* the address of the memory location
* where the object is allocated) *
*/
obj= new Demo1();//available at runtime

obj.sum(10,20);

obj.sum(2.3,3.4);

->using method overloading , we are achieveing the concept of


compile time polymoprhism

2.runtime polymoprhism

->the polymoprhism can be decided at runtime based on the object type not based
on the reference varaible.

->method overriding is the best example to achieve the concept of


runtime polymoprhism.

->method calling is associated to a particular method based on the


object type not based on the reference variable.

note:
whenever we call any method, if that method is not available inside
child class, automatically control will look for that method inside
parent class this is the behaviour.

note:
````
which class object we are creating, that class method will be executing is the
concept of runtime polymoprhism.
A.java:
```````
//PARENT CLASS
public class A {

public void sum(int x, int y)


{
System.out.println("sum is : " + (x+y));
}

B.java:
```````

//child class
public class B extends A{

@Override
public void sum(int x, int y)
{
System.out.println("substraction: " +(x-y));
}

public static void main(String[] args) {

//case 1:A obj = new A();


//obj.sum(2, 3);

//case 2: B obj = new B();


//obj.sum(4, 3);

//case:3
//child object type to parent object type conversion
//automatic conversion
//upcasting
//obj is of A type
A obj;//obj is available at compiletime

//obj is pointing to B class object


obj= new B();

obj.sum(4, 3);

what is debugging:
`````````````````
Debugging is the process of finding and resolving defects
or problems with in a computer program that prevent correct
operation of computer software or a system.

It's a must have skill for any developer because it helps to find bugs that are not
visible during code reviews or that only happens when a specific condition occurs.

Debugging helps the developers in control flow analysis,


unit testing, integration testing, monitoring at the application execution flow
etc..

abstraction:
````````````

abstraction is one of the object oriented programming principle.

it is the process of retrieving the required details


by ignoring irrelevant details.

advantage:
using this we can achieve the concept of security

->abstract class
->interface

abstract class:

it is a java class which contains atleast one abstract method


undefined method
unimplemented method
no body method

it contains only method heading


no method body/logic.

abstract class Test{

//method declaration -only method heading


//abstract method/undefined method /unimplemeented method
public abstract void sum(int x, int y);

purpose:
`````````
Java Abstract class is used to provide common method implementation to all the
subclasses or to provide default implementation

which method is recommended to declare as an abstract method:

can we create the object for an abstract class?

no we can't create the object for an abstract class.

where should we define the logic for an abstract method?


inside implementation class
Demo1.java:
``````````
//abstract class
public abstract class Demo1 {
public abstract void sum(int x, int y);

Demo2.java:
`````````````

//implementation class or sub class


public class Demo2 extends Demo1{

@Override
public void sum(int x, int y) {
System.out.println("sum is: " +(x+y));

Demo3.java:
```````````
//implementaion class of Demo1
public class Demo3 extends Demo1 {

@Override
public void sum(int x, int y) {
System.out.println("substraction is: " +(x-y));

Demo4.java(execution logic class):


``````````````````````````````````
//execution logic class
public class Demo4 {

public static void main(String[] args) {


//runtime polymorphism
Demo1 obj = new Demo3();

obj.sum(3, 4);

note:
``````
when we inherit the abstract class, in the implemenation class we
have to implement all the abstract methods,if we didn't provide
atleast for one abstract method our implemenation class also
will become abstract class.

can we define the constructor inside an abstract class?

yes we can define and we can make it execute also by using super()
syntax.

super:
```````
super is oen of the java reserved keyword

super is pointing always parent class properties

we can use super keyword at three levels

1.super at variable level


2.super at method level
3.super at constructor level

super at variable level:


`````````````````````````
//parent class
public class Demo1 {

int x=100;

//child class
//Demo2.java

//child or sub class


public class Demo2 extends Demo1{
int x = 200;

public void display()


{
System.out.println(x);
System.out.println(super.x);
}
}

//Demo3.java
//execution logic class
public class Demo3 {

public static void main(String[] args) {

Demo2 obj = new Demo2();

obj.display();

}
}

super at method level:


```````````````````````
//parent class
public class Demo1 {

public void display()


{
System.out.println("superclass-display");
}

//Demo2.java:
``````````````

//child or sub class


public class Demo2 extends Demo1{

public void display()


{
System.out.println("child class-display");

//call the parent class method using following syntax

super.display();
}
}

Demo3.java:
```````````
//execution logic class
public class Demo3 {

public static void main(String[] args) {

Demo2 obj = new Demo2();

obj.display();

super at constructor level:


````````````````````````````
super -> to refer the parent class proeprties from the child class
context.

->constructor should not be inherited.

->constructor and class name must be same.

class A
{
public A()
{
}
}
class B extends A
{
public B()
{
}

If we inherit the constructor, we are violating the rule saying


that constructor name and class name must be same.

this() -> is used to call current class default constructor


super() -> is used to call parent class default constructor

this(..) -> is used to call current class parameterized constructor


super(..) -> is used to call parent class parameterized constructor.

note:
writing the super() is optional to call the parent class
default constructor.

writing the super(..) is mandatory to call the parent class


parameterized constructor.

Demo1.java:
```````````
//parent class
public class Demo1 {
//user defined default constructor
public Demo1()
{

System.out.println("iam default const-Demo1");


}

Demo2.java:
````````````

//child or sub class


public class Demo2 extends Demo1{

public Demo2()
{

//call the super class default constructor


//super();
System.out.println("default constructor -Demo2");
}

note:
for every constructor , java compiler will add super() as a first
statement.

writing the super keyword is mandatory to invoke parent class


parameterized constructor if parent class doesn't contains any
default constructor.

Demo1.java:
````````````
//parent class
public class Demo1 {
public Demo1(int x)
{
System.out.println("parameterized constructor-Demo1");
}

Demo2.java:
```````````

//child or sub class


public class Demo2 extends Demo1{

//user defined default constructor


public Demo2()
{

//call the super class parameterized constructor


super(100);
System.out.println("default constructor -Demo2");
}

Demo3.java:
```````````
//execution logic class
public class Demo3 {

public static void main(String[] args) {

//create the object for child class - Demo2

Demo2 obj = new Demo2();

}
interface:
``````````
interface is a collection of only abstract methods.

using interface , we can achieve 100% abstraction.

syntax:

interface <interfacename>
{
//abstract methods;
}

when can you define any method as an abstract method?

answer: if that method is common to all , then it is recommended to make


that method as abstract method.

note:
by default interface methods are public abstract, we no need to use
these keywords explicitly.

by default interface variables are public static final.

how can we take the properties from class to class ?

using extends keyword

how can we take the properties from interface to class?

using 'implements' keyword.

q: can we create the object for interface?

we can't create the object for interface.

Bank.java:
```````````

public interface Bank {

//method declaration
double getRateOfInterest();

Icici.java:
````````````

public class Icici implements Bank{


@Override
public double getRateOfInterest() {
// TODO Auto-generated method stub
return 6.5;
}

CityBank.java:
`````````````

public class CityBank implements Bank {

@Override
public double getRateOfInterest() {
// TODO Auto-generated method stub
return 5.5;
}

Demo3.java:
``````````
//execution logic class
public class Demo3 {

public static void main(String[] args) {

//runtime polymorphism
Bank obj = new Icici();
System.out.println("icici rateof interest is : " +
obj.getRateOfInterest());

Bank obj1 = new CityBank();


System.out.println("citybank rate of interst is : " +
obj1.getRateOfInterest());
}

to take the properties from either class to class or interface to


interface we are using extends keyword

to take the proeperties from interface to class


we have to use implements keyword.

inside the interface , can we define the constructor?

no, we can't define the constructor inside the interface.

note:

if the method is not available inside child class, then immediately


java compiler will look for that particular method inside parent class.
Object class is acting as super class in java for every class
whether it is predefined or userdefined class.

what are the different methods we have inside Object class?

11 methods
clone()
finalize()
hashCode()
equals()
toString()
getClass()
wait()(3)
notify()
notifyAll()

every class in java, is an example of what type of inheritance?

single/simple inheritance

class Test1
{
}

note:
if you are just displaying any java class object internally it invokes
toString() accordingly we will get the output.

toString() of Object class is giving you

classname@hexa value of hashCode

example:
````````
package com.infotech.object;
//example on Object class few methods
public class Test1 {

public static void main(String[] args) {

Test1 obj = new Test1();


Test1 obj1 = new Test1();

//toString()-returns string reprsentation of the Object


System.out.println(obj.toString());//com.infotech.object.Test1@515f550a
//ctrl+shift+t

System.out.println(obj);

System.out.println(obj.hashCode());
System.out.println(obj1.hashCode());
System.out.println(obj.getClass());

System.out.println(obj.equals(obj1));

note:
``````
for every new object, hashcode value is different

encapsulation:
``````````````
it is the process of wrapping up of variables and methods into a
single unit.

purpose: to achieve the concept of data hiding .

by declaring my variables inside the class as private.

how can we make normal class as an encapsulated class?

->we have to declare private variables


->we have to define public setters and getters methods for each and every
variable.

setter method purpose is to set the data into an object


or to update the existing data.

getter method purpose is to get the data from the object

make sure these two methods must be public.

Student.java:
``````````````

//encapsulated class
public class Student {
//private variables

private int stid;


private String stname;

public int getStid() {


return stid;
}

public void setStid(int stid) {


this.stid = stid;
}

public String getStname() {


return stname;
}

public void setStname(String stname) {


this.stname = stname;
}

Test10.java:
````````````

public class Test10 {

public static void main(String[] args) {

Student st = new Student();

//set the student id and student name value into my student object
//by calling setter methods

st.setStid(100);
st.setStname("Ram");

//by calling getter methods we are able to access the stid & stname
System.out.println("student id is : " + st.getStid());
System.out.println("student name is : " +st.getStname());
}

overriding toString() method to get the desired result:

Student.java:
``````````````
package com.infotech.object;

public class Student {

private int stid;


private String stname;

public int getStid() {


return stid;
}

public void setStid(int stid) {


this.stid = stid;
}
public String getStname() {
return stname;
}
public void setStname(String stname) {
this.stname = stname;
}

@Override
public String toString()
{
return stid + " " +stname;

Test2.java:
```````````
package com.infotech.object;

public class Test2 {

public static void main(String[] args) {

Student obj1 = new Student();


obj1.setStid(100);
obj1.setStname("khan");

System.out.println(obj1);

note:
`````
whenever we display any java class object, internally it invokes
toString() , if we override toString() inside our class then it will be executed
otherwise Object class toString() gets executed which gives
classname@hashcode value.

-Object class and it's few methods


-overriding toString() of Object class
-Encapsulation

You might also like