Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

Foundation of Programing

Object: An object is an instance of class.

Objects have states (Properties) and behaviors. Example: A dog has


states - color, name, breed as well as behaviors – wagging the tail,
barking, eating.

Class: A class is a blueprint from which individual objects are created.


OOPs Concepts (APIE)

1) Abstraction: Hiding internal details & showing functionalities


is known as abstraction.

Abstraction is "To represent the essential feature without


representing the back ground details."

In java we use abstract class & inheritance to achieve abstraction.


2) Encapsulation: This is the idea of surrounding something not just to keep content
together but also to protect those content.

Encapsulation in java: Encapsulation is the technique of making the fields in a class


private and providing access to the fields via public methods. If a field is declared
private, it cannot be accessed by anyone outside the class, thereby hiding the fields
within the class. For this reason, encapsulation is also referred to as data hiding.
3) Inheritance:

 It’s a mechanism in which one object


acquires all the properties and
behaviors of parent object.
 When you inherit from an existing
class, you can reuse methods and
fields of parent class, and you can
add new methods and fields also.

Types of inheritance in java

 On the basis of class, there can be


three types of inheritance in java: single, multilevel and hierarchical.
 In java programming, multiple and hybrid inheritance is supported through interface only.

Note: Multiple inheritance is not supported in java through class. When a class extends multiple
classes i.e. known as multiple inheritance. For Example:
Why multiple inheritance is not supported in java?

 To reduce the complexity and simplify the language, multiple inheritance is not supported
in java.
 Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object, there
will be ambiguity to call method of A or B class.
 Since compile time errors are better than runtime errors, java renders compile time error
if you inherit 2 classes. So whether you have same method or different, there will be
compile time error now.

4) Polymorphism:

 Polymorphism means one name many forms.


 One function behaves different forms.
 In other words, "Many forms of a single object is called Polymorphism."
Real World Example of Polymorphism:
Example-1:
A Teacher behaves to student.
A Teacher behaves to his/her seniors.
Here teacher is an object but attitude is different in different situation.

Example-2:
If a & b are int then in a+b “+ sign” act as addition, in other hand if a & b are strings then it will
act as concatenation.
Programming: “Programming is a set of instructions”

PROGRAMMING LANGUAGE:

 A vocabulary and set of grammatical rules for instructing a computer to perform specific
tasks.
 The term programming language usually refers to high-level languages, such as Java, C,
and C++.
 Each language has a unique set of keywords (words that it understands) and a special
syntax for organizing program instructions.

Types of Programing languages

1) Machine language: is the lowest-level programming language. Machine languages


are the only languages understood by computers. Machine code is different for different
Hardware.

Humans Don't Use Machine Language

 While easily understood by computers, machine languages are almost


impossible for humans to use because they consist entirely of numbers.
 Programmers, therefore, use either a high-level programming language or an
assembly language.
2) Assembly language (low level language): contains the same instructions as a machine
language, but the instructions and variables have names instead of being just numbers.

3) High-level language:

 It is a programming language such as C, C++ that enables a programmer to write


programs that are more or less independent of a particular type of computer.
 Such languages are considered high-level because they are closer to human languages
and further from machine languages.
 In contrast, assembly languages are considered low-level because they are very close to
machine languages.

So, this is why programing languages were invented because The CPU (Hardware) doesn’t
understand any of the Programming languages like assembly, high level. It can only understand
is Machine Code or Machine language.

Unstructured Programming Languages: The


most primitive of all programming languages
having sequentially flow of control. Code is
repeated throughout the program

It has repeating line of code for withdraw money


for bank application.

Structured Programming Languages: Has non-sequentially flow of control. Use of functions


allows for re-use of code. This languages are nothing but Object Oriented Programming:
Combines Data & Action Together.
Interpreter Vs Compiler

We generally write a computer program using a high-level language. A high-level


language is one which is understandable by us humans. It contains words and phrases
from the English (or other) language. But a computer does not understand high-level
language. It only understands program written in 0's and 1's in binary, called the
machine code. A program written in high-level language is called a source code. We
need to convert the source code into machine code and this is accomplished my
compilers and interpreters. Hence, a compiler or an interpreter is a program that
converts program written in high-level language into machine code understood by
the computer.

1) Compiler: It scans entire program & translate it as a whole into machine code,
i.e. into executable file. So that we can share only executable file & keep safe our
source code

2) Interpreter: Translate program one statement at a time. No machine code is


generated
The difference between an interpreter and a compiler is given below:

Interpreter Compiler
Translates program one statement at a Scans the entire program and translates it
time. as a whole into machine code.
It takes less amount of time to analyze It takes large amount of time to analyze
the source code but the overall execution the source code but the overall execution
time is slower. time is comparatively faster.
Generates intermediate object code
No intermediate object code is
which further requires linking, hence
generated, hence are memory efficient.
requires more memory.
Continues translating the program until It generates the error message only after
the first error is met, in which case it scanning the whole program. Hence
stops. Hence debugging is easy. debugging is comparatively hard.
Programming language like Python, Programming language like C, C++ use
Ruby, Java use interpreters. compilers.

Note: - In normal circumstances java compiler(javac) compiles java code to


bytecodes and java interpreter(java) interpretes these bytecodes(line by line),
convert it into machine language and execute.
Java Platform: "Java is a programming language as well as a Platform"

Suppose if you want to tell the computer to add two number (1+2) which is represented by some
binary numbers (10000011), how are you going to tell the computer? Yes, we going to use
assembly language to get our code executed.

"Assembly Language is the most elementary form of software development languages."

With advancement in software development languages, this entire assembly code could shrink
into just one line print f 1+2 A with the help of software called COMPILER. It is used to convert
your c language code into assembly code, and the assembler converts it into corresponding
machine code, and this machine code will be transmitted to the processor. The most common
processor used in PC or Computers are Intel processor.

Though present day compilers come bundled with assembler can directly convert your higher
language code into machine code.

Now, suppose Windows operating system is running on this Intel processor, a combination of
Operating System plus the processor is called the PLATFORM. The most common platform
in the world is the Windows and Intel called the Wintel Platform. The other popular platforms are
AMD and Linux, Power PC, and Mac OS X.

Now, with a change in processor, the assembly instructions will also change. For example the

 Add instruction in Intel may be called ADDITION for AMD


 OR Math ADD for Power PC

And obviously with a change in Operating System, the level and nature of O.S level calls will also
change.

As a developer, I want my software program to work on all platforms available, to maximize my


revenues. So I would have to buy separate compilers which convert my print f command into the
native machine code.
But compilers come expensive, and there is a chance of compatibility issues. So buying and
installing a separate compiler for different O.S and processor is not feasible. So, what can be an
alternative solution? Enter Java language.

By using Java Virtual Machine, these problem can be solved. But how it works on different
processors and O.S. Let's understand this process step by step.

Step 1) The code to display addition of two numbers is System.out.println(1+2), and saved as
.java file

Step 2) Using the java compiler (javac) the code is converted into an intermediate code called
the bytecode. The output is a .class file.

Step 3) this code is not understood by any platform, but only a virtual platform called the Java
Virtual Machine
Step 4) This Virtual Machine resides in the RAM of your operating system. When the Virtual
Machine is fed with this bytecode, it identifies the platform it is working on and java interprets the
bytecode (line by line) into the native machine code

In fact, while working on your PC or browsing the web whenever you see either of these icons be
assured the java virtual machine is loaded in your RAM. But what makes java lucrative is that
code once compiled can run not only on all PC platforms but also mobiles or other electronic
gadgets supporting java

Hence, java is a language as well as a platform (JVM)

Being interpreter language why java is faster?

BYTECODE (virtualized machine code which doesn’t actually exists)

Bytecode is computer object code that is processed by a program, usually referred to as a virtual
machine, rather than by the "real" computer machine, the hardware processor. The virtual
machine converts each generalized machine instruction into a specific machine instruction or
instructions that this computer's processor will understand. Bytecode is the result of compiling
source code written in a language that supports this approach.

Using a language that comes with a virtual machine for each platform, your source language
statements need to be compiled only once and will then run on any platform.

Rather than being interpreted one instruction at a time, Java bytecode can be recompiled at each
particular system platform by a just-in-time compiler. JIT used to speed up the execution time
by interpreting part of byte code that has similar functionality at same time. Usually, this will enable
the Java program to run faster. In Java, bytecode is contained in a binary file with a .CLASS suffix.

WORKING OF JAVA VIRTUAL MACHINE (JVM) & ITS ARCHITECTURE

In order to write and execute a software program you need the following

1) Editor – To type your program into, a notepad could be used for this

2) Compiler – To convert your high language program into native machine code

3) Linker – To combine different program files reference in your main program together.

4) Loader – To load the files from your secondary storage device like Hard Disk, Flash Drive, CD
into RAM for execution. The loading is automatically done when your execute your code.

5) Execution – Actual execution of the code which is handled by your OS & processor.
C code Compilation and Execution process

To understand the Java compiling process in Java. Let's first take


a quick look to compiling and linking process in C.

Suppose in the main, you have called two function f1 and f2. The
main function is stored in file a1.c.

Function f2 is stored
Function f1 is stored in a
in a file a3.c
file a2.c

All these files, i.e., a1.c, a2.c, and a3.c, is fed to the compiler. Whose output is the corresponding
object files which is the machine code.
The next step is integrating all these object files into a single .exe file with the help of linker. The
linker will club all these files together and produces the .exe file.

During program run a loader program will load a.exe into the
RAM for the execution.

Java code compilation and execution in Java VM

Let's look at the process for JAVA. In your main you have two
methods f1 and f2.

 main method is stored in file a1.java


 f1 is stored in file as a2.java
 f2 is stored in file as a3.java
The compiler will compile the three files and produces
a corresponding .class file which consists of BYTE
code. Unlike C, no linking is done.

The Java VM or Java Virtual Machine resides on the


RAM. During execution, using the class loader the class
files are brought on the RAM. The BYTE code is verified
for any security breaches.

Next, the execution engine will convert the Bytecode


into Native machine code. This is just in time
compiling. It is one of the main reason why Java is
comparatively slow.

NOTE: JIT or Just-in-time compiler used to improve


the performance.JIT compiles parts of the byte code
that have similar functionality at the same time, and
hence reduces the amount of time needed for
compilation. Here the term? Compiler? Refers to a
translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific
CPU.

What is JVM?

JVM stands for Java Virtual Machine. It is the engine that drives the Java Code. It converts Java
bytecode into machines language.

 In other programming language, the compiler produces code for a particular system. But
Java compiler produces code for a Virtual Machine.
 In JVM, Java code is compiled into bytecode. This bytecode gets interpreted on different
machines
 Between host system and Java source, Bytecode is an intermediary language.
 JVM is responsible for allocating a memory space.

Why is Java both interpreted and compiled language?

 A compiler is a program which converts a program from one level of language to another.
Example conversion of C++ program into machine code.
 The java compiler is a convert's high level java code into bytecode (which is also a type of
machine code).
 An interpreter is a program which converts a program at one level to another
programming language at the same level. Example conversion of Java program into C++
 In Java, the Just In Time Code generator converts the bytecode into the native machine
code which are at the same programming levels.
 Hence java is both compiled as well as interpreted language.
Why is Java slow?

 The two main reasons behind the slowness of Java are


 Dynamic Linking = Unlike C, linking is done at run-time, every time the program is run in
Java.
 Run-time Interpreter = the conversion of byte code into native machine code is done at
run-time in Java which furthers slows down the speed
 However, the latest version of Java have addressed the performance bottlenecks to a
great extent.

Summary:

 JVM or Java Virtual Machine is the engine that drives the Java Code. It converts
Java bytecode into machines language.
 In JVM, Java code is compiled to bytecode. This bytecode gets interpreted on
different machines
 JIT or Just-in-time compiler is the part of the Java Virtual Machine (JVM). It is used
to speed up the execution time
 In comparison to other compiler machine, Java may be slow in execution.

What is JDK, JRE and JVM?

JDK: - Java Development Kit (in short JDK) is Kit which


provides the environment to Develop and execute (run)
the Java program. For e.g. You (as Java Developer)
are developing an accounting application on your
machine, so what do you going to need into your
machine to develop and run this desktop app? You are
going to need J-D-K for that purpose for this you just
need to go to official website of sun or oracle to
download the latest version of JDK into your machine.

Hence, JDK is a kit(or package) which includes two


things i) Development Tools(to provide an environment
to develop your java programs) and ii) JRE (to execute
your java program). JDK is only used by Java
Developers.

JRE: - Java Runtime Environment (to say JRE) is an installation


package which provides environment to only run (not develop) the
java program (or application) onto your machine. For e.g.
(continuing with the same example) after developing your
accounting application, you want to run this application into your
client’s machine. Now in this case your client only need to run your
application into his/her machine so your client should install JRE
in-order to run your application into his machine.

Hence, JRE is only used by them who only wants to run the Java
Programs i.e. end users of your system.
JVM: - Java Virtual machine (JVM) is a very important part of both JDK and JRE because it is
contained or inbuilt in both. Whatever java program you run using JRE or JDK goes into JVM and
JVM is responsible to execute the java program line by line hence it is also known as
interpreter(we will discuss about interpreter later) . Hence you don’t need to install JVM separately
into your machine because it is inbuilt into your JDK or JRE installation package. We’ll explore
more about JVM soon.

Java is −

 Object Oriented − In Java, everything is an Object. Java can be easily extended since it
is based on the Object model.
 Platform Independent − unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and interpreted
by the Virtual Machine (JVM) on whichever platform it is being run on.
 Simple − Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master. Also syntax is similar to c, c++
 Secure − With Java's secure feature it enables
to develop virus-free, tamper-free systems.
Bytecode must run inside JVM, & cannot
access system directly. But in C language,
executable file is directly accessed by system
so, more possibility to make malicious
programs.

 Architecture-neutral − Java compiler


generates an architecture-neutral object file format, which makes the compiled code
executable on many processors, with the presence of Java runtime system.
 Portable –
It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular
platforms.

 Robust – Java helps you to write robust code which is non breaking.

 Multithreaded − With Java's multithreaded feature it is possible to write programs that


can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.
 Interpreted − Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
 High Performance − with the use of Just-In-Time compilers, Java enables high
performance.
 Distributed − Java is designed for the distributed environment of the internet.
 Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
First Java Program

 Class: keyword is used to declare a class in java.


 Public: It means that you can call this method from outside of the class you are currently
in. This is necessary because this method is being called by the Java runtime system
which is not located in your current class.
 Static: is a keyword, if we declare any method as static, it is known as static method. The
core advantage of static method is that there is no need to create object to invoke the
static method. The main method is executed by the JVM, so it doesn't require to create
object to invoke the main method. So it saves memory.
 Void: is the return type of the method, it means it doesn't return any value.
 Main: It's just the name of method. This name is fixed and as it's called by the JVM as
entry point for an application.
 System.out.println (): is used print statement.

 String [] args: is used for command line argument.

The command line argument is the argument passed to a program at the time when you run it.
To access the command-line argument inside a java program is quite easy, they are stored as
string in String array passed to the args parameter of main() method.
There are many ways to write a java program. The modifications that can be done in a java program are
given below:

1) By changing sequence of the modifiers, method prototype is not changed.

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

2) Subscript notation in java array can be used after type, before variable or after variable.

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


2. public static void main(String []args)
3. public static void main(String args[])

3) You can provide var-args support to main method by passing 3 ellipses (dots)

Let's see the simple code of using var-args in main method. We will learn about var-args later in Java
New Features chapter.

1. public static void main(String... args)

4) Having semicolon at the end of class in java is optional.

Let's see the simple code.

1. class A{
2. static public void main(String... args){
3. System.out.println("hello java4");
4. }
5. };

Valid java main method signature

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


2. public static void main(String []args)
3. public static void main(String args[])
4. public static void main(String... args)
5. static public void main(String[] args)
6. public static final void main(String[] args)
7. final public static void main(String[] args)
8. final strictfp public static void main(String[] args)

Invalid java main method signature

1. public void main(String[] args)


2. static void main(String[] args)
3. public void static main(String[] args)
4. abstract public static void main(String[] args)
INTERNAL DETAILS OF HELLO JAVA PROGRAM
1) What happens at compile time?

At compile time, java file is compiled by


Java Compiler (It does not interact with OS)
and converts the java code into bytecode.

2) What happens at runtime?


At runtime, following steps are performed:

Class loader: is the subsystem of JVM that is used


to load class files.
Bytecode Verifier: checks the code fragments for
illegal code that can violate access right to objects.
Interpreter: read bytecode stream then execute the
instructions.

Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
Can you have multiple classes in a java source file?
Yes, like the figure given below illustrates:

Basic Syntax

 Class Names − for all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.

Example: class MyFirstJavaClass

 Method Names − All method names should start with a Lower Case letter. If several words
are used to form the name of the method, then each inner word's first letter should be in
Upper Case.

Example: public void myMethodName()

 Program File Name − Name of the program file should exactly match the class name.

When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match, your program will not compile).

Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved
as 'MyFirstJavaProgram.java'

 public static void main(String args[]) − Java program processing starts from the main()
method which is a mandatory part of every Java program.
Java Identifiers

All Java components require names. Names used for classes, variables, and methods are called
identifiers.

In Java, there are several points to remember about identifiers. They are as follows −

 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
 After the first character, identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value.
 Examples of illegal identifiers: 123abc, -salary.

Java Modifiers

Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There
are two categories of modifiers −

 Access Modifiers − default, public, protected, private


 Non-access Modifiers − final, abstract, strictfp

Java Keywords abstract assert boolean break


byte case catch char
The following list shows the reserved words in Java. These
class const continue default
reserved words may not be used as constant or variable or
any other identifier names. do double else enum
extends final finally float
Comments in Java for goto if implements
import instanceof int interface
Java supports single-line and multi-line comments very long native new package
similar to C and C++. All characters available inside any private protected public return
comment are ignored by Java compiler. short static strictfp super
switch synchronized this throw
Example
public class MyFirstJavaProgram { throws transient try void
/* This is my first java program.
volatile while
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/

public static void main(String []args) {


// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}
Object & Classes
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:

 fields
 methods
 constructors
 blocks
 nested class and interface

A class describe Object i.e. its properties and behavior. Below e.g. explains how Ball class is
created from Simple English phrase to programming language

Objects Objects
reference
variable
A class can contain any of the following variable types.

 Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
 Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
 Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.

1) Local Variables

 Local variables are declared in methods,


constructors, or blocks.
 Local variables are created when the
method, constructor or block is entered and
the variable will be destroyed once it exits the
method, constructor, or block.
 Access modifiers cannot be used for local
variables.
 Local variables are visible only within the
declared method, constructor, or block.
 Local variables are implemented at stack
level internally.
 There is no default value for local variables,
so local variables should be declared and an
initial value should be assigned before the
first use.
2) Instance Variables

 Instance variables are declared in a class, but outside a method, constructor or any block.
 When a space is allocated for an object in the heap, a slot for each instance variable value
is created.
 Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present throughout
the class.
 Instance variables can be declared in class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access modifiers.
 Instance variables have default values. For numbers, the default value is 0, for Booleans
it is false, and for object references it is null. Values can be assigned during the declaration
or within the constructor.
 Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they
should be called using the fully qualified name. ObjectReference.VariableName.
Class/Static Variables

 Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
 Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
 Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program
stops.
 Visibility is similar to instance variables. However, most static variables are declared public
since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during
the declaration or within the constructor. Additionally, values can be assigned in special
static initializer blocks.
 Static variables can be accessed by calling with the class name
ClassName.VariableName.
 When declaring class variables as public static final, then variable names (constants) are
all in upper case. If the static variables are not public and final, the naming syntax is the
same as instance and local variables.

Here, value of i changes to 1 every time you called setInfo() method, but not j.
Methods

This is the general form of a method:

type name(parameter-list) {

// body of method

 Here, type specifies the type of data returned by the method.


 If the method does not return a value, its return type must be void.
 The name of the method is specified by name.
 Parameters are essentially variables that receive the value of the arguments passed to
the method when it is called.
 If the method has no parameters, then the parameter list will be empty.
 Methods that have a return type other than void return a value to the calling routine using
the following form of the return statement:

return value;

Here, value is the value returned.

JAVA STATIC METHOD: static methods in Java can be called without creating an object of
class. Have you noticed why we write static keyword when defining main it's because program
execution begins from main and no object has been created yet. Consider the example below to
improve your understanding of static methods.

Java static method vs instance method

Instance method requires an object of its class to be created before it can be called while static
method doesn't require object creation.
Using static method of another classes

If you wish to call static method of another class then you have to write class name while calling static
method as shown in example below.

Access Modifiers in java ( Note: A class cannot be private or protected except nested class.)

 There are two types of modifiers in java: access modifiers and non-access modifiers.
 The access modifiers in java specifies accessibility (scope) of a data member, method, constructor
or class.

There are 4 types of java access modifiers:


Access Modifier within class within package outside package by subclass only outside package
1. private Private Y N N N
2. default Default Y Y N N
3. protected Protected Y Y Y N
4. public
Public Y Y Y Y

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient
etc.

1) Private access modifier : The private access modifier is accessible only within class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is compile
time error.
2) Default access modifier: If you don't use any modifier, it is
treated as default by default. The default modifier is accessible
only within package.
Example of default access modifier
In this example, we have created two packages pack and
mypack. We are accessing the A class from outside its package,
since A class is not public, so it cannot be accessed from outside
the package.
In the this example, the scope of class A and its method msg() is
default so it cannot be accessed from outside the package.

3) Protected access modifier

 The protected access modifier is accessible within


package and outside the package but through
inheritance only.
 The protected access modifier can be applied on the data
member, method and constructor. It can't be applied on
the class.
Example of protected access modifier
In this example, we have created the two packages pack and
mypack. The A class of pack package is public, so can be
accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from
outside the class only through inheritance.

4) Public access modifier:


The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
NON ACCESS MODIFIERS

Java provides a number of non-access modifiers to achieve many other functionalities.

 The static modifier for creating class methods and variables.


 The final modifier for finalizing the implementations of classes, methods, and variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.

1) The Static Modifier

The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

a) Java static variable

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

 The static variable can be used to refer the common


property of all objects (that is not unique for each object)
e.g. company name of employees, college name of
students etc.
 The static variable gets memory only once in class area
at the time of class loading.

Advantage of static variable

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


memory).

Note: Java static property is shared to all


objects.

Suppose there are 500 students in my college,


now all instance data members will get memory
each time when object is created. All student have
its unique roll no and name so instance data
member is good. Here, college refers to the
common property of all objects. If we make it
static, this field will get memory only once.
b) Java static method

If you apply static keyword with any method, it is known as static method.

 It is a variable which belongs to the class and not to object (instance).


 A static method can access only static data. It cannot access non-static data (instance
variables)
 A static method can call only other static methods and cannot call a non-static method
from it.
 A static method can be accessed directly by the class name and doesn’t need any
object.
 Static method can access static data member and can change the value of it.

/Program of changing the common property of all objects (static field).

Restrictions for static method


There are two main restrictions for the static method. They are:
 The static method cannot use non static data member or call non-
static method directly.
 this and super cannot be used in static context.

Java static block

 Is used to initialize the static data member.


 It is executed before main method at the time of class loading.
2) The Final Modifier
Final Variables

 A final variable can be explicitly


initialized only once. A reference
variable declared final can never be
reassigned to refer to a different object.
 However, the data within the object can
be changed. So, the state of the object
can be changed but not the reference.
 With variables, the final modifier often
is used with static to make the constant
a class variable.
New keyword in Java

The new keyword is used to allocate memory at


run time. All objects get memory in Heap
memory area.

Ball b=new Ball ();

3 Ways to initialize object

There are 3 ways to initialize object in java.

1. By Object reference variable


2. By method
3. By constructor

Here new keyword creates reference for object b in memory

“Garbage Collection” as the name suggests is used to remove the objects that are no longer
needed by the Java application. The Java Garbage Collector will identify those objects and
remove those from the memory thereby freeing the memory for the new objects.

Shahukh don’t have any reference to it deleted to free memory.


Object and Class Example:
2) main outside class

In real time development, we create classes and use it from


1) main within class another class. It is a better approach than previous one.
Let's see a simple example, where we are having main()
 In this example, we have created a Student class that method in another class.
have two data members’ id and name. We are
creating the object of the Student class by new We can have multiple classes in different java files or single
keyword and printing the objects value. java file. If you define multiple classes in a single java
 Here, we are creating main() method inside the class. source file, it is a good idea to save the file name with the
class name which has main() method.

3 ways of initializing object:


1) Initialization through reference variable: Initializing object simply means storing data
into object. Let's see a simple example where we are going to initialize object through
reference variable.
2) Initialization through method: In this example, we are creating the two objects of Student
class and initializing the value to these objects by invoking the insertRecord method. Here,
we are displaying the state (data) of the objects by invoking the displayInformation() method.

As you can see in the above figure, object gets the


memory in heap memory area. The reference
variable refers to the object allocated in the heap
memory area. Here, s1 and s2 both are reference
variables that refer to the objects allocated in
memory.

Note: Try to make Data members as Private & Methods as public so that others cannot
change your data members i.e. using encapsulation. (i.e. always instantiate date members
through methods or constructors not by reference
variable.)
For E.g.
String color;
String Brand;
setInfo(String colour,String brand)
Ball b= new Ball();
b.setInfo(red, Nike);

Else, Hacker can set any false value if instantiated by reference variable as follows
b.color=Nike; b.Brand=Red;
3) Initialization through constructor

 Constructor in java is a special type of method that is used to initialize the object.
 Java constructor is invoked at the time of new object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

It can be classified into above three types for our understanding

1) Default Constructor:
 If there is no constructor in a class, compiler
automatically creates a default constructor.
 Default constructor provides the default values to the
object like 0, null etc. depending on the type.
2) Basic Constructor: A constructor that have no parameter is known as default constructor.

Default Constructor is defined

Output

3) Parameterized constructor:
 A constructor that have parameters is known as parameterized constructor.
 Parameterized constructor is used to provide different values to the distinct objects.

parameterized Constructor is defined


Constructor Overloading

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by taking
into account the number of parameters in the list and their type.

Method Overloading:

 If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
 If we have to perform only one operation, having same name of the methods increases
the readability of the program.
 Suppose you have to perform addition of the given numbers but there can be any number
of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int)
for three parameters then it may be difficult for you as well as other programmers to
understand the behavior of the method because its name differs.
 So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

 Method overloading increases the readability of the program.


 Different ways to overload the method
There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In java, Method Overloading is not possible by changing the return type of the method only.
1) 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.

2) 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.
Q) Why Method Overloading is not possible by changing the return type of method
only?

In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:

Here,System.out.println(Adder.add(11,11)); //Here, how can java determine which sum()


method should be called?

Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time
error if you declare the same method having same parameters.

Runtime and compile time are programming terms that refer to different stages of software
program development. In order to create a program, a developer first writes source code, which
defines how the program will function. Small programs may only contain a few hundred lines of
source code, while large programs may contain hundreds of thousands of lines of source code.
The source code must be compiled into machine code in order to become and executable
program. This compilation process is referred to as compile time.
A compiled program can be opened and run by a user. When an application is running, it
is called runtime.
The terms "runtime" and "compile time" are often used by programmers to refer to different types
of errors. A compile time error is a problem such as a syntax error or missing file reference that
prevents the program from successfully compiling. The compiler produces compile time errors
and usually indicates what line of the source code is causing the problem.
If a program's source code has already been compiled into an executable program, it may still
have bugs that occur while the program is running. Examples include features that don't work,
unexpected program behavior, or program crashes. These types of problems are called runtime
errors since they occur at runtime.
Method Overloading and Type Promotion

One type is promoted to another implicitly if no


matching datatype is found. Let's understand the
concept by the figure given below:

s displayed in the side diagram, byte can be promoted


to short, int, long, float or double. The short datatype
can be promoted to int,long,float or double. The char
datatype can be promoted to int,long,float or double
and so on.

1) Example of Method Overloading with Type 2) Example of Method Overloading with Type Promotion
Promotion if matching found

If there are matching type arguments in the method, type


promotion is not performed.

3) Example of Method Overloading with Type Promotion in case of ambiguity:If there are no
matching type arguments in the method, and each method promotes similar number of arguments,
there will be ambiguity.
Anonymous object

 Anonymous simply means nameless. An object which has no reference is known as


anonymous object. It can be used at the time of object creation only.
 If you have to use an object only once, anonymous object is a good approach.

For example:

new Calculation();//anonymous object

Calling method through reference:

Calculation c=new Calculation();

c.fact(5);

Calling method through anonymous object

new Calculation().fact(5);

Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.

Initialization of primitive variables: int a=10, b=20;

Initialization of reference variables: Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
Real World Example: Account
File: TestAccount.java
Summary of all above Terms

Output
JAVA NATIVE METHODS

The ability to write just one set of code in Java and have it run on every system with a Java run-
time is one of Java's primary strengths. But this platform independence has one key drawback:
What do we do with the vast amount of existing code? The trick is to use the so-called native
method interface.

Writing native methods involves importing C code into your Java application.

The method is implemented in "native" code. That is, code that does not run in the JVM. It's
typically written in C or C++. Native methods are usually used to interface with system calls or
libraries written in other programming languages.

this keyword in java


In java, this is a reference variable that refers to the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
1) this: to refer current class instance variable

The this keyword can be used to refer current class instance


variable. If there is ambiguity between the instance variables and
parameters, this keyword resolves the problem of ambiguity.
If local variables(formal arguments) and instance variables are
different, there is no need to use this keyword

2) 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. Let's see the example

3) this() : to invoke current class constructor


The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the
example given below that displays the actual use of this keyword.
4) 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. Let's see the example:

5) this: to pass as argument in the constructor call

We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes. Let's see the example:

6) this keyword can be used to return current class instance

Let's prove that this keyword refers to the current class instance variable. In this program, we are
printing the reference variable and this, output of both variables are same.

You might also like