0% found this document useful (0 votes)
6 views39 pages

Unit 1.1 Oops

The document discusses Object-Oriented Programming (OOP) concepts like objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It then describes Java programming language features such as being simple, object-oriented, portable, platform-independent, secured, robust, and distributed. The Java environment including JVM, JRE, and JDK is also explained.

Uploaded by

Harendra Tomar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views39 pages

Unit 1.1 Oops

The document discusses Object-Oriented Programming (OOP) concepts like objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It then describes Java programming language features such as being simple, object-oriented, portable, platform-independent, secured, robust, and distributed. The Java environment including JVM, JRE, and JDK is also explained.

Uploaded by

Harendra Tomar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 39

➔OOPs(Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and
maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

Object
Any entity that has state and behavior is known as an object. For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address
and takes up some space in memory. Objects can communicate without knowing the
details of each other's data or code. The only necessary thing is the type of message
accepted and the type of response returned by the objects.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

➔ What is Java?
Java is a programming language and a platform. Java is a high level, robust,
object-oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in
the year 1995. James Gosling is known as the father of Java. Before Java, its name
was Oak. Since Oak was already a registered company, so James Gosling and his
team changed the name from Oak to Java.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10.Multithreaded
11.Distributed
12.Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
1. Java is platform independent because it is different from other languages
like C, C++, etc. which are compiled into platform specific machines while
Java is a write once, run anywhere language.
2. Java code can be executed on multiple platforms, for example, Windows,
Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox

Robust
The English mining of Robust is strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
• There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
Architecture-neutral
• Java is architecture neutral because there are no implementation dependent
features, for example, the size of primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
• Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
High-performance
• Java is faster than other traditional interpreted programming languages
because Java bytecode is "close" to native code. It is still a little bit slower
than a compiled language (e.g., C++). Java is an interpreted language that is
why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
• Java is distributed because it facilitates users to create distributed applications
in Java. RMI and EJB are used for creating distributed applications. This
feature of Java makes us able to access files by calling the methods from any
machine on the internet.
Multi-threaded
• A thread is like a separate program, executing concurrently. 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 multi-
media, Web applications, etc.
Dynamic
• Java is a dynamic language. It supports the dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.
• Java supports dynamic compilation and automatic memory management
(garbage collection).
➔The Java Environment
We must understand the differences between JDK, JRE, and JVM before proceeding
further to Java.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
because it doesn't physically exist. It is a specification that provides a runtime
environment in which Java bytecode can be executed. It can also run those programs
which are written in other languages and compiled to Java bytecode.
The JVM performs the following main tasks:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE.
The Java Runtime Environment is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files
that JVM uses at runtime.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is
a software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:
• Standard Edition Java Platform
• Enterprise Edition Java Platform
• Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources
such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java
Application.
➔Java Source File Structure
Java source file structure describes that the Java source code file must follow a
schema or structure.
A Java program has the following structure:
1. package statements: A package in Java is a mechanism to encapsulate a group
of classes, sub-packages, and interfaces.
2. import statements: The import statement is used to import a package, class, or
interface.
3. class definition: A class is a user-defined blueprint or prototype from which
objects are created, and it is a passive entity.

Important Points to keep in mind while working with Java Source File
1. Number of classes in a Java source file:
Java allows us to create any number of classes in a program/File. But out of all the
classes, at most, one of them can be declared as a public class. In simple words, the
program can contain either zero public class, or if there is a public class present, it
cannot be more than one.
2. Name of the Java source file:
Java allows us to name the Java source file with anything if there is not a single class
that is declared as public. But if there is a class that is declared as public, the name
of the Java source file must be the same as the public class name. The Java source
file extension must be .java.
3. Number of .class files in a Java source file:
The number of .class files generated is equal to the number of classes declared in the
Java program.
Implementation of a Java application program involves a following step. They
include:
1. Creating the program
2. Compiling the program
3. Running the program
// FileName : "HelloWorld.java".
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello, World");
}
}
• Compiling the program
C:/> javac HelloWorld.java
Upon successful compilation a Helloworld.class file will produced.
• Running the program
C:/> java HelloWorld
➔Java Identifiers
In programming languages, identifiers are used for identification purposes. In Java,
an identifier can be a class name, method name, variable name, or label.
For example : we have 5 identifiers namely :

• Test : class name.


• main : method name.
• String : predefined class name.
• args : variable name.
• a : variable name.

There are certain rules for defining a valid java identifier. These rules must be
followed, otherwise we get compile-time error. The only allowed characters for
identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and
‘_‘ (underscore).For example “geek@” is not a valid java identifier as it contain ‘@’
special character.
• Identifiers should not start with digits([0-9]). For example “123geeks” is a not
a valid java identifier.
• Java identifiers are case-sensitive.
• There is no limit on the length of the identifier but it is advisable to use an
optimum length of 4 – 15 letters only.
• Reserved Words can’t be used as an identifier. For example “int while = 20;”
is an invalid statement as while is a reserved word. There are 53 reserved
words in Java.
• Examples of valid identifiers :

➔Java Reserved Keywords


• Java has a set of keywords that are reserved words that cannot be used as
variables, methods, classes, or any other identifiers.
• In java some words are reserved to represent some meaning or some
functionality. Such type of words are called as Reserved Words.
• There are 53 reserved words in java. 50 are keywords and 3 are literals (true,
false, null). The 50 keywords are classified in to following.
1. Reserved words for data types (8)
byte, short, int, long, float, double, boolean, char
2. Reserved words for flow control (11)
If, else, switch, case, default, while, do, for, break, continue, return
3. Reserved words for modifiers (11)
public, private, protected, final, abstract, static, synchronized, native, strictfp,
transient, volatile
4. Reserved words for Exception handling (6)
try, catch, finally, throw, throws, assert (Used for debugging purpose)
5. Reserved words for class related (6)
class, interface, package, import, extends, implements
6. Reserved words for object related (4)
new, instanceof, super, this
7. Reserved words for return type (1)
void
8. Unused keywords (2)
goto, const
we use final keyword instead of const.
9. enum keyword (1)
we can use enum to define a group of named constants.
E.g
enum Month { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV,
DEC;}
Note
1. All 53 reserved words in java contain only lower case alphabets
2. In java we have only new keyword but not delete keyword because destruction
of useless objects is the responsibility of Garbage Collector.
➔Data Types
1. Primitive Data Types
2. Reference/Object Data Types
1. Primitive Data Types
Primitive Data Types are again divided in to 2 types
1. Numeric Data types ( Integral and Floating point)
2. Non Numeric Data types (Char and boolean)
Integral – byte, short, int, long
Floating point – float, double
1. byte
• Byte data type is an 8-bit signed two’s complement integer.
• Minimum value is -128 (-2^7)
• Maximum value is 127 (inclusive)(2^7 -1)
• Default value is 0
• Range : – 128 to + 127
2. short
• Short data type is a 16-bit signed two’s complement integer.
• Minimum value is -32,768 (-2^15)
• Maximum value is 32,767 (inclusive) (2^15 -1)
• Default value is 0.
3. int
• int data type is a 32-bit signed two’s complement integer.
• Minimum value is – 2,147,483,648.(-2^31)
• Maximum value is 2,147,483,647(inclusive).(2^31 -1)
• int is generally used as the default data type for integral values unless there is
a concern about memory.
• Default value is 0.
4. Long
• Long data type is a 64-bit signed two’s complement integer.
• Minimum value is -9,223,372,036,854,775,808.(-2^63)
• Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
• This type is used when a wider range than int is needed.
• Default value is 0L.
5. float
• If you want 5 to 6 decimal places of accuracy then we should go for float.
• Float data type is a single-precision 32-bit IEEE 754 floating point.
• Float is mainly used to save memory in large arrays of floating point numbers.
• Default value is 0.0f.
• Float data type is never used for precise values such as currency.
• Range is -3.4 E38 to +3.4 E38
6. double
• double data type is a double-precision 64-bit IEEE 754 floating point.
• This data type is generally used as the default data type for decimal values,
generally the default choice.
• Double data type should never be used for precise values such as currency.
• Default value is 0.0d.
Range is -1.7 E308 to +1.7 E308
Non Numeric Data types
1. boolean
• boolean data type represents one bit of information.
• There are only two possible values: true and false.
• This data type is used for simple flags that track true/false conditions.
• Default value is false.
• Size : Not applicable (JVM dependent)
• Range : Not applicable (Allowed values are true or false)
2. char
in Java we can use Unicode characters which covers world wide all alphabets sets.
The number of Unicode characters is greater than 256 and hence 1 byte is not enough
to represent all characters. Hence we should go for 2 bytes.
• char data type is a single 16-bit Unicode character.
• Minimum value is ‘\u0000’ (or 0).
• Maximum value is ‘\uffff’ (or 65,535 inclusive).
• Char data type is used to store any character.
Reference Data Types
• Reference variables are created using new keywords. They are used to access
objects/arrays.
• Class objects, and various type of array variables come under reference data
type.
• Default value of any reference variable is null.
• A reference variable can be used to refer to any object of the declared type or
any compatible type.
null
null is the default value for object / array reference and we won’t apply for primitive
types. If we are trying to assign null value for primitive data types then we will get
compile time error.

➔Java Program Sample


public class Test
{
public static void main(String[] args)
{
System.out.println("Hi this is Java");
}
}

Main Method
Whether the class contains main() or not and whether the main() is properly declared
or not. These changes are not responsible of compiler.
At run time, JVM is responsible for these checking. If JVM unable to find required
main() then we will get run time exception saying NoSuchMethodError:main.
JVM always searches for main() method with the following signature.
public static void main(String[] args)
public --> To call by JVM from any where (Call from command line etc)
static --> Without existing object also JVM has to call this method
void --> Main method won't return anything to JVM
main --> Name of the method which is configured inside JVM
String[] args --> Command line arguments
The above syntax is very strict and if we perform any change then we will get
Runtime Exception saying NoSuchMethodError:main.
Even though above syntax is very strict the following changes are acceptable.
1. Instead of public static we can declare static public i.e., the order of modifier is
not important.
2. We can declare String[] in any acceptable form
main(String[] args)
main(String []args)
main(String args[])
3. Instead of args we can declare any Java valid identifier.
4. Instead of String[] we can take var arg String parameter
main(String... args)
5. main() can be declared with the following modifiers also
final
synchronized
Strictfp
public class Test
{
static final synchronized strictfp public void main(String... args)
{
System.out.println("Hi this is Java");
}
}
Inheritance concept is applicable for static methods including main() also.
Hence if the child class doesn’t contain main() then parent class main() will be
executed.
Example-1:
public class Parent
{
public static void main(String[] args)
{
System.out.println("This is Programming");
}
}
class Child extends Parent
{
}
javac Parent.java
java Parent
This is Programming
java Child
This is Programming
Example-2:
public class Parent
{
public static void main(String[] args)
{
System.out.println("This is OOPs");
}
}
class Child extends Parent
{
public static void main(String[] args)
{
System.out.println("This is Java");
}
}
It seems to be overriding concept is applicable for static methods, but it’s not
overriding but it is method hiding.
Overloading concept is applicable for main() but JVM always calls String[]
argument method only. The other method we have to call explicitly.
Example:
public class Parent
{
public static void main(String[] args)
{
System.out.println("This is OOPs");
}
public static void main(int[] args)
{
System.out.println("This is Java");
}
}
javac Parent.java
java Parent
This is OOPs

➔Static Control Flow and Instance Control Flow


Static Control Flow
Static Control Flow decides the sequence of activities that will be executed when we
run a java class that contains static variables, methods, and blocks.
static blocks
If we want to perform some activity at the time of class loading, Then we should
define that activity at static blocks because these(static blocks) will execute at the
time of class loading only.
Process of static control flow
1. Identification of static members from top to bottom. (1-6) Steps.
2. Execution of static variable assignments and static block from top to bottom (7-
12) Steps.
3. Execution of Main Method. (12-15) Steps.
Instance Control Flow
Instance Control Flow decides the sequence of activities that will be executed when
we run a java class containing instance variables, methods, and blocks.
Static control flow is only one-time activity, and that will execute at the time of class
loading. But instance control flow is not a one-time activity. And it will execute for
every object creation separately.
Process of instance control flow
Instance control flow will execute at the time of object creation. The following is the
sequence of statements that will execute at the time of object creation.
1. Identification of Instance members (1-8) Steps.
2. Execution of Instance variable assignments and Instance block from top to bottom.
(9-14) Steps.
3. Execution of Main Method. (15) Steps.
➔ Method Overloading
Two methods are said to be overloaded if the method names are the same, But
arguments are different (at least Order).
The overloading method resolution is the responsibility of the compiler based on
reference type and method arguments. Hence overloading is considered as compile-
time polymorphism or Early Binding.
Rules for Overloading in Java
• The first and foremost rule of Method overloading is that Methods need to
have the same name in a single class.
• Two or more methods in a class can be overloaded based on different
signatures, and signature includes the number of parameters, data types of
parameters, the sequence of parameters.
• The return type of a method is not a part of the signature, so overloading can
never be done based on the return type, and if done, this creates the compile-
time error.
• public class Test
• {
• public void m1()
• {
• System.out.println("no-args");
• }
• public void m1(int i)
• {
• System.out.println("int-args");
• }
• public void m2(double d)
• {
• System.out.println("double-args");
• }
• public static void main(String[] args)
• {
• Test t = new Test();
• t.m1();
• t.m1(10);
• t.m1(10.5);
• }
• }
➔ Access Modifiers
In Java, the access modifiers can be applied on two level- class level and member
level:
1. Access Modifiers for Class
2. Access Modifiers for Member
Key Points:-

▪ The only applicable modifier for local variables is final


▪ The modifiers which are applicable only for variables but not for
classes and methods are volatile and transient.
▪ The modifiers which are applicable only for methods but not for
classes and variables are native and synchronized.
▪ The modifiers which are applicable for top level classes, methods and
variables are public, <default>, final.
▪ The modifiers which are applicable for inner classes but not for outer
classes are private, protected, static.

Class Modifiers

Whenever we are writing our own java class compulsory we have to provide some
information about our class to the JVM like,

1. Whether our class can be accessible from any where or not


2. Whether child class creation is possible for our class or not.
3. Whether instantiation is possible or not etc

▪ We can specify this information by declaring with appropriate modifier.


▪ The only applicable modifiers for top level classes are
1. public
2. <default>
3. final
4. abstract
5. strictfp
▪ If we are using any other modifier we will get compile time error saying
“Modifier XXXX not allowed here”.

private class test {


public static void main(String[] args) {
int x = 0;
for(int y = 0; y<3; y++) {
x = x + y;
}
System.out.println(x);
}
}

C.E: Modifier private not allowed here

▪ But for the inner classes the following modifiers are allowed
1. public
2. <default>
3. final
4. abstract
5. strictfp
6. private
7. protected
8. static

public classes

If a class declared as the public then we can access that class from any where

package pack1;
public class A {
public void m1() {
System.out.println("Hai this is Java");
}
}
package pack2;
import pack1.A;
class B {
public static void main() {
A a = new A();
a.m1();
}
}

If we are not declaring class A as public then we will get compile time error while
compiling B class, saying pack1.A is not public in pack1 can’t be accessed from
outside package.

default classes

▪ If a class declared as default then we can access that class only with in that
current package i.e., from outside of the package we can’t access..
▪ If you don’t use any modifier, it is treated as default by default.

package pack1;
class A{
void msg(){
System.out.println("Hello This is Java");
}
}
package pack2;
import pack1.A;
class B
{
public static void main(String args[]){
A obj = new A();//C.E
obj.msg();//C.E
}
}

Final Modifier

Final is the modifier applicable for classes, methods and variables

Final Method

▪ Whatever methods parent has by default available to the child through


inheritance. If the child not satisfied with parent method implementation then
child is allowed to redefine that method based on it’s requirement. This
process is called overriding.
▪ If the parent class method is declared as final then we cannot override that
method in the child class because it’s implementation is final.

class P {
public void property() {
System.out.println("Money + Gold + Land");
}
public final void marry() {
System.out.println("Alekya");
}
}

class C extends P {
public void marry() {
System.out.println("Manasa");
}
}

C.E: marry() in C cannot override marry() in P; Overrider method is final

Final Class

If a class declared as final we cannot extend functionality of that class i.e., we can’t
create child class for that class. i.e., inheritance is not possible for final classes.

final class P {

class C extends P {

}
C.E: cannot inherit from final P
Note:-
Every method present inside a final class is always final by default. But every
variable present inside final class need not be final.

abstract modifier

abstract is the modifier applicable for classes and methods but not for variables.

abstract method

▪ Even though we don’t know about implementation still we can declare a


methods with abstract modifier i.e., abstract methods can have only
declaration but not implementation. Hence, every abstract method declaration
should compulsory ends with “;”.
▪ Child classes are responsible to provide implementation for parent class
abstract methods

E.g

abstract class Vechicle


{
public abstract int getNoOfWheels();
}

class Bus extends Vehicle


{
public int getNoOfWheels()
{
return 6;
}
}

class Auto extends Vehicle


{
public int getNoOfWheels()
{
return 3;
}
}

Notes:-

▪ abstract modifier never talks about implementation, if any modifier talks


about implementation then it is always illegal combination with abstract.
▪ Following are various illegal combinations of modifiers for methods.

abstract + final // Illegal


abstract + static // Illegal
abstract + synchronized // Illegal
abstract + native // Illegal
abstract + strictfp // Illegal
abstract + private // Illegal

srictfp modifier

▪ We can use strictfp for classes and methods but not for variables
▪ Usually the result of floating point arithmetic is varied from platform if we
want platform independent results for floating point arithmetic then we should
go for strictfp modifier

strictfp method

▪ If a method declared as strictfp all floating point calculations in that method


has to follow IEEE754 standard so that we will get platform independent
results.

strictfp class

▪ If a class declared as strictfp then every floating point calculation present in


every concrete method has to follow IEEE 754 standard so that we will get
platform independent results.
▪ We can declare abstract strictfp combination for classes i.e., abstract strictfp
combination is legal for classes but illegal for methods.
Member Level Modifiers

public members

If we declare a member as public then we can access that member from anywhere
but corresponding class should be visible (public) i.e., before checking member
visibility we have to check class visibility.

default members

If a member declared as the default, then we can access that member only with in
the current package and we cannot access from outside of the package. Hence,
default access is also known as package level access.

private members

▪ If a member declared as private then we can access that member only with in
the current class.
▪ abstract methods should be visible in child classes to provide implementation
where as private methods are not visible in child classes. Hence private-
abstract combination is illegal for methods.

protected members

If a member declared as protected then we can access that member with in the
current package any where but outside package only in child classes.

▪ With in the current package we can access protected members either by parent
reference or by child reference.

▪ But from outside package we can access protected members only by using
child reference. If we are trying to use parent reference then we will get
compile time error
final variables

▪ In general for instance and static variables it is not required to perform


initialization explicitly JVM will always provide default values.
▪ But for the local variables JVM won’t to provide ant default values
compulsory we should provide initialization before using that variable.

final instance variables

▪ If the value if a variable is varied from object to object such type of variables
are called instance variables.
▪ For every object a separate copy of instance variables will be created.
▪ For the normal instance variables it is not required to perform initialization
explicitly. JVM will provide default values.
▪ If the instance variable declared as the final then compulsory we should
perform initialization whether we are using or not otherwise we will get
compile time error.

Rule

For the final instance variables, we should perform initialization before constructor
compilation i.e., the following are various places for this,

1. At the time of declaration

E.g

class Test {

final int x = 10;

2. Inside instance block


class Test
{
final int x;
{
x = 10;
}
}
3. Inside Constructor
class Test
{
final int x;
Test()
{
x = 10;
}
}
Other than these if we are perform initialization any where else we will get compile
time error.

final static variables


• For the normal static variables it is not required to perform initialization
explicitly, JVM will always provide default values.
• But for final static variables we should perform initialization explicitly
otherwise we will get compile time error.
class Test
{
static int x; // Fine
}
class Test
{
final static int x; // C.E
}
Rule
For the final static variables we should perform initialization before class loading
compilation i.e., following are various places to perform this.
1. At the time of declaration
class Test
{
final static int x = 10;
}
2. Inside static block
class Test
{
final static int x;
static
{
x = 10;
}
}
If we are performing initialization any where else we will get compile time error
final local variables
• For the local variables JVM won’t provide any default values compulsory we
should perform initialization before using that variable.
class Test
{
public static void main(String args[])
{
int x;
System.out.println("Hai"); // Fine
}
}
class Test
{
public static void main(String args[])
{
int x;
System.out.println(x); // C.E: variable x might not have been
initialised.
}
}
• Even though local variable declared as the final it is not required to perform
initialization if we are not using that variable.
class Test
{
public static void main(String args[])
{
final int x;
System.out.println("Hai Chinni..!!"); // Fine
}
}
• Even though local variable declared as the final it is not required to perform
initialization if we are not using that variable.
• The only applicable modifier for local variables is final. If we are using any
other modifier we will get compile time error
static modifier

▪ static is the modifier applicable for variables and methods but not for classes
▪ If the value of a variable is same for all objects then we should go for static
variables. In the case of static variable only one copy will be created at class
level and share that copy for every object of that class.
▪ static members can be accessed from both instance as well as class name.
▪ For static methods compulsory implementation should be available where as
for abstract methods implementation should not be available hence abstract
static combination is illegal for methods.
▪ Inheritance concept is applicable for static methods including main() method.

synchronized modifier

▪ synchronized is the modifier applicable for methods and blocks. We cannot


declare class and variable with this keyword.
▪ If a method or block declared as syncronized then at a time only one thread is
allowed to operate on the given object.

native modifier

▪ native is the modifier applicable for methods but not for variables and classes
▪ The native methods are implemented in some other languages like c and c++
hence native methods also known as foreign methods.
▪ The main objectives of native keyword are
1. To improve performance of the system.
2. To use already existing legacy non java code.

▪ For native methods implementation is already available in other languages


and we are not responsible to provide implementation. Hence native method
declaration should compulsory ends with “;”

transient modifier

▪ transient is the modifier applicable only for variables and we cannot apply for
methods and classes.
▪ At the time of serialization, if we don’t want to save the value of a particular
variable to meet security, then we should go for transient keyword.
volatile modifier

▪ volatile is the modifier applicable only for variables but not for methods and
classes
▪ If the value of a variable keep on changing such type variables we have to
declare with volatile modifier.
▪ If a variable declared as volatile then for every thread a separate local copy
will be created.
▪ Every intermediate modification performed by that thread will takes place in
local copy instead of master copy.
▪ Once the value got finalized just before terminating the thread the master copy
value will be updated with local stable value.

➔Constructors in Java
Constructors in Java are special types of methods that are used to initialize the
objects of the class. Constructors are called at the time of object creation of the class.

Rules for Constructor

While writing constructors we should follow the following rules.

▪ The name of the constructor and the name of the class must be the same.
▪ The only allowed modifiers for the constructors are public, private, protected,
. If we are using any other modifier, we will get C.E(Compiler Error).
▪ The return type is not allowed for the constructors even void also. If we r
declaring return type, then the compiler treats it as a method, and hence there
is no Compilation Error and RuntimeError.

public class Test {


void Test() {
System.out.println("Hai .....");
}
public static void main(String arg[]) {
Test t = new Test();
}
}

It is legal but not recommended to have a method whose name is exactly the same
as the class name. Here it was treated as method.

Types of Constructors in Java


Now is the correct time to discuss the types of the constructor, so primarily there
are three types of constructors in Java are mentioned below:
No-Argument Constructor

• Parameterized Constructor
• Default Constructor
1. No-Argument Constructor in Java
A constructor that has no parameter is known as the No-argument or Zero argument
constructor. If we don’t define a constructor in a class, then the compiler creates
a constructor(with no arguments) for the class. And if we write a constructor
with no arguments, the compiler does not create a default constructor.
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If we
want to initialize fields of the class with our own values, then use a parameterized
constructor.
3. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the
compiler does not create a default constructor. It is taken out. It is being overloaded
and called a parameterized constructor. The default constructor changed into the
parameterized constructor. But Parameterized constructor can’t change the default
constructor.

You might also like