Ad Java CIE-1 Notes
Ad Java CIE-1 Notes
simple program, Type conversion and cas'ng, Arrays. Classes: Class fundamentals, declaring
Objects, assigning object reference variables. A Closer Look at Methods and Classes:
Introducing methods, constructors, this keyword, garbagecollec'on, the finalize () method.
Crea%on of Java
• Java is one of the most popular programming languages worldwide. It was created by
James Gosling and Patrick Naughton, employees of Sun Microsystems, with support from
Bill Joy, co-founder of Sun Microsystems.
• Sun officially presented the Java language at SunWorld on May 23, 1995. Then, in 2009,
the Oracle company bought the Sun company.
• The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic".
Byte code
• Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an
assembler which is an alias representation of a C++ code.
• As soon as a java program is compiled, java bytecode is generated. In more apt terms,
java bytecode is the machine code in the form of a .class file. With the help of java
bytecode we achieve platform independence in java.
• This essentially means that we only need to have basic java installation on any platforms
that we want to run our code on.
• Resources required to run the bytecode are made available by the Java Virtual Machine,
which calls the processor to allocate the required resources. JVM's are stack-based so
they stack implementation to read the codes.
• Bytecode is essentially the machine level language which runs on the Java Virtual
Machine.
• Whenever a class is loaded, it gets a stream of bytecode per method of the class.
Whenever that method is called during the execution of a program, the bytecode for that
method gets invoked.
• Javac not only compiles the program but also generates the bytecode for the program.
Thus, we have realized that the bytecode implementation makes Java a platform-
independent language.
• Portability ensures that Java can be implemented on a wide array of platforms like
desktops, mobile devices, severs and many more.
Java Buzzwords
• The primary objective of Java programming language creation was to make it portable,
simple and secure programming language.
• Apart from this, there are also some excellent features which play an important role in
the popularity of this language. The features of Java are also known as Java buzzwords.
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.
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:
Secured- Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader
o Bytecode Verifier
o Security Manager
• There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.
• The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:
• Runtime Environment
• API(Application Programming Interface)
• 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).
Portable- Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
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++.
Let's look at some real-life examples of the states and behaviors that objects can have.
Example 1:
• Object: car.
• State: color, brand, weight, model.
• Behavior: break, accelerate, turn, change gears.
Example 2:
• Object: house.
• State: address, color, location.
• Behavior: open door, close door, open blinds.
All object-oriented programming language provides mechanisms that help you implement the
object-oriented model. They are
• Encapsulation
• Inheritance
• Polymorphism
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.
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
• Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.
A simple program
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
Syntax/Declaration:-
des'na'on_datatype = (target_datatype)variable;
(): is a cas'ng operator.
Type conversion : In type conversion, a data type is automa'cally converted into another data
type by a compiler at the compiler 'me. In type conversion, the des'na'on data type cannot
be smaller than the source data type, that’s why it is also called widening conversion. One
more important thing is that it can only be applied to compa'ble data types.
int x=30;
float y;
y=x; // y==30.000000.
S.NO TYPE CASTING TYPE CONVERSION
Type casting takes place during the Whereas type conversion is done at
5.
program design by programmer. the compile time.
Arrays are used to store mul'ple values in a single variable, instead of declaring separate
variables for each value.
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, you can
place the values in a comma-separated list, inside curly braces:
System.out.println(cars[0]);
// Outputs Volvo
cars[0] = "Opel";
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use the length property:
System.out.println(cars.length);
// Outputs 4
To create an object of Main, specify the class name, followed by the object name, and
use the keyword new:
int x = 5;
System.out.println(Obj.x);
}
Multiple Objects
int x = 5;
System.out.println(myObj1.x);
System.out.println(myObj2.x);
Declaring Objects
An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The example
of an intangible object is the banking system.
In Java, a reference variable is a variable that holds the memory address of an object rather
than the actual object itself. It acts as a reference to the object and allows manipula'on of its
data and methods. Reference variables are declared with a specific type, which determines
the methods and fields that can be accessed through that variable.
When an object is created using the new keyword, memory is allocated on the heap to store
the object's data. The reference variable is then used to refer to this memory loca'on, making
it possible to access and manipulate the object's proper'es and behaviors.
class Car {
String brand;
int year;
}
public class ReferenceVariableExample {
public static void main(String[] args) {
// Declare a reference variable of type Car
Car myCar;
// Create a new Car object and assign its reference to myCar
myCar = new Car();
// Access and modify the object's properties
myCar.brand = "Toyota";
myCar.year = 2021;
// Use the reference variable to perform actions on the object
System.out.println("Brand: " + myCar.brand);
System.out.println("Year: " + myCar.year);
}
}
Benefits and Usage of Reference Variables
Introducing methods
In general, a method is a way to perform some task. Similarly, the method in Java is a
collec'on of instruc'ons that performs a specific task. It provides the reusability of code. We
can also easily modify code using methods.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the samepackage only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter,
left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercaseletter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:
It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any
of the predefined methods in our program, a series of codes related to the corresponding
method runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined
in the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Let's create a user defined method that checks the number is even or odd. First, we will define
the method.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Static Method
A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best example of a static method is
the main() method.
Instance Method
The method of the class is known as an instance method. It is a non-static method defined in
the class. Before calling or invoking the instance method, it is necessary to create an object
of its class. Let's see an example of an instance method.
Abstract Method
The method that does not has method body is known as abstract method. In other words,
without an implementation is known as abstract method. It always declares in the abstract
class. It means the class itself must be abstract if it has abstract method. To create an abstract
method, we use the keyword abstract.
Syntax
public Main() {
x = 5; // Set the initial value for the class attribute x
// Outputs 5
Constructor Parameters
Constructors can also take parameters, which is used to ini'alize ajributes.
The following example adds an int y parameter to the constructor. Inside the constructor we
set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5),
which will set the value of x to 5:
int x;
public Main(int y) {
x = y;
System.out.println(myObj.x);
// Outputs 5
this keyword
The most common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter). If you omit the keyword in the example above, the
output would be "0" instead of "5".
garbagecollection
Garbage collec'on in Java is the process by which Java programs perform automa'c memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine,
or JVM for short. When Java programs run on the JVM, objects are created on the heap, which
is a por'on of memory dedicated to the program.
How Does Garbage Collection in Java works?
Java garbage collec'on is an automa'c process. Automa'c garbage collec'on is the process
of looking at heap memory, iden'fying which objects are in use and which are not, and
dele'ng the unused objects. An in-use object, or a referenced object, means that some part
of your program s'll maintains a pointer to that object. An unused or unreferenced object is
no longer referenced by any part of your program.
Finalize() is the method of Object class. This method is called just before an object is garbage
collected. finalize() method overrides to dispose system resources, perform clean-up ac'vi'es
and minimize memory leaks.
Syntax
protected void finalize() throws Throwable
Protected method: protected is an access specifier for variables and methods in Java. When
a variable or method is protected, it can be accessed within the class where it's declared and
other derived classes of that class.
all classes inherit the Object class directly or indirectly in Java. The finalize() method is
protected in the Object class so that all classes in Java can override and use it.
Garbage collection is done automatically in Java, which the JVM handles. Java uses the
finalize method to release the resources of the object that has to be destroyed.
GC call the finalize method only once, if an exception is thrown by finalizing method or the
object revives itself from finalize(), the garbage collector will not call the finalize() method
again.
It's not guaranteed whether or when the finalized method will be called. Relying entirely on
finalization to release resources is not recommended.
There are other ways to release the resources used in Java, like the close() method for file
handling or the destroy() method. But, the issue with these methods is they don't work
automatically, we have to call them manually every time.
In such cases, to improve the chances of performing clean-up activity, we can use the
finalize() method in the final block. finally block will execute finalize() method even though
the user has used close() method manually.
We can use the finalize() method to release all the resources used by the object.* In the final
block, we can override the finalize() method.* An example of overriding the finalize method
in Java is given in the next section of this article.
@Override
protected void finalize()
{
System.out.println("Finalize method is called.");
}
}
Explanation:
In this example, the s1 object is eligible for garbage collection. When System.gc();
invokes the garbage collector, it calls the object class's finalize() method. The
overridden finalize() method of the Student class is called, and it prints Finalize
method is called.
2. Explicit Call to finalize() Method
When we call the finalize() method explicitly, the JVM treats it as a normal method; it cannot
remove the object from memory. The finalize() method can release memory and resources
related to an object only when a Garbage collector calls it. Compiler will ignore the finalize()
method if it's called explicitly and not invoked by the Garbage collector. Let's understand
this practically:
public class Demo
{
public static void main(String[] args)
{
Demo demo1 = new Demo();
Demo demo2 = new Demo();
demo1 = demo2;
demo1.finalize(); // Explicit call to finalize method
System.out.println("Garbage collector is called");
System.gc(); // Implicit call to finalize() method
}
@Override
protected void finalize()
{
System.out.println("Finalize() method is called");
}
}
Try to avoid the use of the finalize method. In case you need to use it, the following
are points to remember while using the finalize() method:
Do not use the finalize() method to execute time-critical application logic, as the
execution of the finalize method cannot be predicted.
Call the super.finalize() method in the finally block; it will ensure that the finalize
method will be executed even if any exception is caught. Refer to the following
finalize() method template:
@Override
protected void finalize() throws Throwable
{
try{
//release resources here
}catch(Throwable t){
throw t;
}finally{
super.finalize();
}
}
Conclusion
• finalize() is an Object class method in Java, and it can be used in all other classes
by overriding it.
• The garbage collector uses the finalize() method to complete the clean-up
activity before destroying the object.
• JVM allows invoking of the finalize() method in Java only once per object.
• Garbage collection is automated in Java and controlled by JVM.
• Garbage Collector calls the finalize method in java of that class whose object is
eligible for Garbage collection.
Method Overloading in Java
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.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder
{
static int add(int a,int b)
{
return a+b;}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
Consider the following Java program, in which we have used different constructors in the
class.
Student(){
System.out.println("this a default constructor");
}
There are two types of modifiers in Java: access modifiersand non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) Private
The private access modifier is accessible only within the class.
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 a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
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.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
3) Protected
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.
It provides more accessibility than the default modifer.
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.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
The sta)c keyword in Java is used for memory management mainly. We can apply sta'c
keyword with variables, methods, blocks and nested classes. The sta'c keyword belongs to
the class than an instance of the class
o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
Suppose there are 500 students in my college, now all instance data members will get memory
each 'me when the object is created. All students have its unique rollno and name, so
instance data member is good in such case. Here, "college" refers to the common property of
all objects. If we make it sta'c, this field will get the memory only once.
o A sta'c method belongs to the class rather than the object of a class.
o A sta'c method can be invoked without the need for crea'ng an instance of a class.
o A sta'c method can access sta'c data member and can change the value of it.
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or unini'alized final variable. It can be ini'alized in the constructor
only. The blank final variable can be sta'c also which will be ini'alized in the sta'c block only.
We will have detailed learning of these. Let's first learn the basics of final keyword.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class