Static, this, super & final keyword
static keyword
In order to share the same method or variable of any given class, we use
the static keyword.
We can use it for blocks, variables, methods, and nested classes.
Static variable
A static variable is nothing but the class variable.
It is common for all objects of a class, or let’s say it is shared by all
objects of a class, whereas the non-static variable is different for
each object of a class.
E.g., static String name=” John”;
Static block
To initialize static variables, we use a static block.
It gets executed only once after class is loaded or an object is
created.
A class can contain multiple static blocks.
E.g. – static String name; static{ name = “Java”; }
Static method
A static method is one that can be invoked without creating object
of a class.
It can access static variables without using the object of the class.
It can access static and non-static methods directly. A non-static
method can access the static method, while a static method can
access the non-static method only through the object of a class.
Eg – public static void main(String args[]) { }
Static class
We can declare a class as static only if it is a nested class.
Non-static members of the Outer class are not accessible by the
static class.
Eg – class Vehicle{ //Static class static class Car{ } }
this keyword
“this” is basically just a reference variable referring to the current object.
It eliminates the confusion between class attributes and parameters with
the same name.
We can use it to –
refer class variable
invoke class method or constructor
passed as an argument in method or constructor
return current class object
E.g. –
this.name = name;
this.setName();
setName(this);
Person p = new Person(this);
return this;
super keyword
The “super” keyword is a reference variable in java, used to refer parent
class objects.
We can use the super keyword in three ways –
with variable
It is used when a derived class and base class has the same
data members. There is a possibility of ambiguity in such a
case.
This keyword helps us refer to the immediate parent class
instance variable.
Eg – System.out.println(super.speed);
with method
When we want to call the parent class method, and parent &
child class have same-named methods; then, to resolve
ambiguity, we use the super keyword to invoke the immediate
parent class method.
E.g., super.message();
with constructor
To invoke the immediate parent class constructor, we can use
it with a constructor.
It can call both parametric as well as non-parametric
constructors depending upon the situation.
Call to super() must be the first statement in a derived class
constructor.
Eg – Student() { super(); System.out.println(“constructor”); }
final keyword
To apply restrictions on user access, the final keyword is used.
There are three ways to use the final keyword –
final variable
Its value cannot be changed once initialized.
The compiler cannot assign a default value to a final variable.
Eg – final int count = 10;
final method
A final method cannot be overridden, nor can it be hidden by a
subclass.
Since the final method cannot be overridden so core
functionalities must be declared.
Eg – final void manageCount() { //code }
final class
It cannot be inherited.
We cannot declare a final class as abstract at the same time
as they are antonyms.
Eg – final class Car { //methods and fields }
Types of Methods in Java
The method in Java or Methods of Java is a collection of statements that
perform some specific tasks and return the result
Generally, there are two basic types of methods in Java, but
programmers can develop any kind of method depending on the
scenario.
Predefined methods
User-defined methods (Programmer-defined methods)
Predefined Methods in Java with Example
Predefined methods in Java are those methods that are already
defined in the Java API (Application Programming Interface) to use
in an application.
Look at some examples below:
1. print() is a predefined method present in the package
java.io.PrintSteam. The print(“….”) prints the string inside the
quotation marks.
2. sqrt() is a method of Math class which is present in package
java.lang. It calculates the square root of a number.
User-defined Methods in Java with Example
User-defined methods are those methods in Java that are defined
inside a class to perform a special task or function in an
application. Such methods are called user-defined methods.
A user-defined method is also known as programmer-defined
method. We can declare two types of user-defined methods in a
program.
Instance Method
Static Method
Instance Methods in Java
An instance method is used to implement behaviors of each
object/instance of the class. Since the instance method represents
behaviors of the objects. Therefore, instance method is linked
with an object.
Here is an example of an instance method declaration:
void m1()
{
.
}
Static Method in Java
When you declare any method with a static modifier, it is
called static method in Java. A static method is linked with class.
Therefore, it is also known as a class method. It is used to
implement the behavior of the class itself. Static methods load
into the memory during class loading and before object creation.
An example of a static method declaration is as follows:
static void m2()
{
What are Tokens in Java?
Tokens are the various elements in the Java program that are
identified by Java compiler. A token is the smallest individual
element (unit) in a program
Types of Tokens
Java language contains five types of tokens that are as follows:
Reserved Keywords
Identifiers
Literals,
Operators
Separators
(1) Tokens are the basic building blocks of a Java program, including identifiers,
keywords, literals, operators, and separators.
(2) Keywords represent reserved words predefined by the Java language. For
example, class, public, static, if, else, etc. You cannot use these words as identifiers
for the names of variables, methods, classes, etc.
(3) Identifiers represent names given to elements, such as variables, methods, classes,
and interfaces. Identifiers must start with a letter (A-Z or a-z), underscore (_), or
dollar sign ($), followed by any combination of letters, digits, underscores, or dollar
signs.
(4) Literals are constants or fixed values in the program that don’t change during the
execution of the program. They include integer, floating-point, character, string, and
boolean literals.
(5) Operators are symbols in Java or other programming languages that perform
various types of operations variables and values. Examples of operators are arithmetic
operators (+, -, *, /), comparison operators (<, >, ==, !=), logical operators (&&, ||),
etc.
(6) Separators (also known as delimiters) are characters that separate elements within
the program code. Examples of separators are parentheses (( )), braces ({ }), brackets
([ ]), semicolon (;), and comma (,).
(7) The process of breaking down the source code into valid tokens is known as
tokenization.
(8) Whitespace is used to separate tokens in Java but does not affect the execution of
the program. It includes spaces, tabs, and newline characters.
(9) Java is case-sensitive, meaning it distinguishes between uppercase and lowercase
letters. For example, myCollege and MyCollege are different identifiers.
Tags
Classes and Objects in Java
We know that Java is a true object-oriented programming
language. In the object-oriented programming language, we
design and develop an application program using classes and
objects.
What is Object in Java
an entity that has state and behavior is known as object in Java.
Here, the state represents properties, and behavior represents
actions
For example, book, pen, pencil, TV, fridge, washing machine,
mobile phone, etc. Objects consist of states or attributes (called
data members) and behaviors (called methods) in Java.
Characteristics of Object in Java
An object in Java has three characteristics:
1. State: State represents properties or attributes of an object. It
is represented by instance variable.
2. Behavior: Behavior represents functionality or actions. It is
represented by methods in Java.
3. Identity: Identity represents the unique name of an object. It
differentiates one object from the other.
What is Class in Java
A class in Java is a fundamental building block of object-oriented
programming (OOP) language.
According to OOPs concept in Java, a class is the
blueprint/template of an object. It contains the similar types of
objects having the same states (properties) and behavior.
In other words, a class can also be defined as “a class is a group
of objects
Syntax of Class in Java
A class can be declared using the keyword class followed by a
class name. It has also a body within braces. The general syntax
to declare a class in Java is shown below:
modifierName class className
{
// class body.
}
What is Package in Java?
A package is nothing but a physical folder structure (directory)
that contains a group of related classes, interfaces, and sub-
packages according to their functionality.
The Java language has various in-built packages.
For example, java.lang, java.util, java.io, and java.net.
Types of Packages in Java
There are mainly two types of packages available in Java. They
are:
User-defined package
Built-in package (also called predefined package)
User-defined Package in Java
The package which is defined by the user is called user-defined or
custom package in Java. It contains user-defined classes and
interfaces.
Creating User-defined Package
Java supports a keyword called “package” which is used to create
user-defined packages in Java programming. The general syntax
to create a package in Java is as:
package packageName;
For example:
package myPackage;
public class A {
// class body
}
In this example, myPackage is the name of a package. The
statement “package myPackage;” signifies that the class “A”
belongs to the “myPackage” package.
Predefined Packages in Java (Built-in Packages)
They are also called built-in packages. These packages consist of
a large number of predefined classes, interfaces, and methods
that are used by the programmer to perform any task
Java APIs contains the following predefined packages, as shown in
the below figure:
Java Packages Example Program
Let us take a simple example program where we will create a
user-defined package in a systematic manner.
package com.scientecheasy.java.corejava;
public class Example
{
public static void main(String[] args)
{
System.out.println("How to create a Java package");
}
}
How to Compile Package in Java?
If you are not using any Eclipse IDE, you follow the syntax given
below:
javac -d directory javafilename
n the above syntax,
1. javac means Java compiler.
2. -d means directory. It creates the folder structure.
3. .(dot) means the current directory. It places the folder structure
in the current working directory. For example:
javac -d.Example.java // Here, Example.java is the file name.
How to Run Java Package Program?
You have to use the fully qualified name to execute Java code.
The fully qualified name means class name with a complete
package structure. Use the below syntax to run Java code.
Syntax:
java completePackageName.className
JAVACopy code
Now run the above Java code. To Run:
java com.scientecheasy.java.corejava.Example
JAVACopy code
Output:
How to create a Java package
How to Import Package in Java
There are three approaches to import one package into another
package in Java.
1. import package.*;
2. import package.classname;
3. Using fully qualified name.
Using package.*
An import is a keyword that is used to make the classes and
interfaces of other packages accessible to the current package. If
we use package.*, all the classes and interfaces of this package
can be accessed (imported) from outside the packages.
Using packageName.className
If you import packageName.className, you can only access the
declared class of this package.
Using the fully qualified name
If you use the fully qualified name, there is no need to use an
import statement, but in this case, only the declared class of this
package can be accessible. It is generally used when two
packages have the same class name.
Constructors in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is
called.
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>()
{
1. }
Example of default constructor
1. class Bike1{
2.
3. Bike1()
4. {System.out.println("Bike is created");
5. }
6. public static void main(String args[]){
7. Bike1 b=new Bike1();
8. }
9. }
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
1. class Student4{
2. int id;
3. String name;
4. Student4(int i,String n){
5. id = i;
6. name = n;
7. }
8. void display(){System.out.println(id+" "+name);}
9.
10. public static void main(String args[]){
11. Student4 s1 = new Student4(111,"Karan");
12. s1.display();
13. }
14. }
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object
to another
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
o By assigning the values of one object into another
o For example
o
o class Student6{
o int id;
o String name;
o
o Student6(int i,String n){
o id = i;
o name = n;
o }
o
o
o void display(){System.out.println(id+" "+name);}
o
o public static void main(String args[]){
o Student6 s1 = new Student6(111,"Karan");
o s1.display();
o }
o }
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types.
Example of Constructor Overloading
1. class Student5{
2. int id;
3. String name;
4. int age;
5. Student5(int i,String n){
6. id = i;
7. name = n;
8. }
9.
10. Student5(int i,String n,int a){
11. id = i;
12. name = n;
13. age=a;
14. }
15. void display(){System.out.println(id+" "+name+" "+age);}
16.
17. public static void main(String args[]){
18. Student5 s1 = new Student5(111,"Karan");
19. Student5 s2 = new Student5(222,"Aryan",25);
20. s1.display();
21. s2.display();
22. }
23. }
Output:
111 Karan 0
222 Aryan 25
Difference between Constructor and Method in Java
There are the following difference between constructor and
method in Java that is explained in the below table:
S
Constructor Method
N
Constructor is a special type of
Method is used to expose
1. method that is used to initialize the
the behaviour of an object.
state of an object.
It has both void and return
2. It has no return type even void also.
type.
If we don’t provide any constructor
Method is not provided by
3. in the class, Java Compiler provides
the compiler in any case.
a default constructor for that class.
Method name may or may
Constructor’s name must be the
4. not be the same name as
same as the name of the class.
the class name.
The purpose of a method
The purpose of a constructor is to is to execute the
5.
create an object of a class. functionality of the
application.
They are not inherited by They are inherited by
6.
subclasses. subclasses.
Java Method Overloading
Method overloading is a feature in Java that allows a class to have more than one
method with the same name, provided their parameter lists are different. Itenables
methods to perform similar but distinct tasks. Method overloading is a form of compile-
time polymorphism, meaning that the compiler determines which method to call based
on the method signature (name and parameter list).
For example,
1. class OverloadingExample{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
Example 2
public class Calculator {
public int sum(int a, int b) {
return a + b;
}
public double sum(double a, double b) {
return a + b;
}
}
Key Rules of Method Overloading
The method parameters must change: either the
number or the type of parameters must be different
in the two methods.
Method Overriding in Java If subclass (child class) has the same method as declaeed in the paeent
class, it is known as method overriding in Java.
Usage of Java Method Overriding o Method oveeeiding is used to peovide the specifc
implementation of a method which is aleeady peovided by its supeeclass. o Method oveeeiding is
used foe euntime polymoephism Rules for Java Method Overriding 1. The method must have the
same name as in the paeent class 2. The method must have the same paeametee as in the paeent
class. 3. Theee must be an IS-A eelationship (inheeitance