[go: up one dir, main page]

0% found this document useful (0 votes)
19 views48 pages

Unit - 1

Uploaded by

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

Unit - 1

Uploaded by

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

UNIT -1 BASICS OF JAVA AND OVERLOADING

What are Access Modifiers?


In Java, access modifiers are used to set the accessibility (visibility) of
classes, interfaces, variables, methods, constructors, data members,
and the setter methods. For example,

class Animal {
public void method1() {...}

private void method2() {...}


}

In the above example, we have declared 2 methods: method1() and


method2(). Here,

 method1 is public - This means it can be accessed by other classes.


 method2 is private - This means it can not be accessed by other
classes.
Note the keyword public and private . These are access modifiers in
Java. They are also known as visibility modifiers.
Java Class and Objects
In this tutorial, you will learn about the concept of classes and objects in
Java with the help of examples.

Java is an object-oriented programming language. The core concept of


the object-oriented approach is to break complex problems into smaller
objects.
An object is any entity that has a state and behavior. For example,
a bicycle is an object. It has
 States: idle, first gear, etc
 Behaviors: braking, accelerating, etc.
Before we learn about objects, let's first know about classes in Java.

Java Class
A class is a blueprint for the object. Before we create an object, we first
need to define the class.

We can think of the class as a sketch (prototype) of a house. It contains


all the details about the floors, doors, windows, etc. Based on these
descriptions we build the house. House is the object.

Since many houses can be made from the same description, we can
create many objects from a class.
Create a class in Java
We can create a class in Java using the class keyword. For example,

class ClassName {
// fields
// methods
}

Here, fields (variables) and methods represent


the state and behavior of the object respectively.
 fields are used to store data

 methods are used to perform some operations

For our bicycle object, we can create the class as

class Bicycle {

// state or field
private int gear = 5;

// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}

In the above example, we have created a class named Bicycle . It


contains a field named gear and a method named braking() .
Here, Bicycle is a prototype. Now, we can create any number of
bicycles using the prototype. And, all the bicycles will share the fields
and methods of the prototype.

Note: We have used keywords private and public . These are known
as access modifiers. To learn more, visit Java access modifiers.

Java Objects
An object is called an instance of a class. For example,
suppose Bicycle is a class
then MountainBicycle , SportsBicycle , TouringBicycle , etc can be
considered as objects of the class.
Creating an Object in Java

Here is how we can create an object of a class.

className object = new className();

// for Bicycle class


Bicycle sportsBicycle = new Bicycle();

Bicycle touringBicycle = new Bicycle();


We have used the new keyword along with the constructor of the class
to create an object. Constructors are similar to methods and have the
same name as the class. For example, Bicycle() is the constructor of
the Bicycle class. To learn more, visit Java Constructors.
Here, sportsBicycle and touringBicycle are the names of objects. We
can use them to access fields and methods of the class.
As you can see, we have created two objects of the class. We can
create multiple objects of a single class in Java.

Note: Fields and methods of a class are also called members of the
class.

Access Members of a Class


We can use the name of objects along with the . operator to access
members of a class. For example,

class Bicycle {

// field of class
int gear = 5;

// method of class
void braking() {
...
}
}

// create object
Bicycle sportsBicycle = new Bicycle();

// access field and method


sportsBicycle.gear;
sportsBicycle.braking();

In the above example, we have created a class named Bicycle . It


includes a field named gear and a method named braking() . Notice the
statement,

Bicycle sportsBicycle = new Bicycle();

Here, we have created an object of Bicycle named sportsBicycle . We


then use the object to access the field and method of the class.
 sportsBicycle.gear - access the field gear

 sportsBicycle.braking() - access the method braking()

We have mentioned the word method quite a few times. You will learn
about Java methods in detail in the next chapter.
Now that we understand what is class and object. Let's see a fully
working example.
Example: Java Class and Objects
class Lamp {

// stores the value for light


// true if light is on
// false if light is off
boolean isOn;

// method to turn on the light


void turnOn() {
isOn = true;
System.out.println("Light on? " + isOn);

// method to turnoff the light


void turnOff() {
isOn = false;
System.out.println("Light on? " + isOn);
}
}

class Main {
public static void main(String[] args) {

// create objects led and halogen


Lamp led = new Lamp();
Lamp halogen = new Lamp();

// turn on the light by


// calling method turnOn()
led.turnOn();

// turn off the light by


// calling method turnOff()
halogen.turnOff();
}
}
Run Code

Output:

Light on? true


Light on? false

In the above program, we have created a class named Lamp . It contains


a variable: isOn and two methods: turnOn() and turnOff() .

Inside the Main class, we have created two objects: led and halogen of
the Lamp class. We then used the objects to call the methods of the
class.
 led.turnOn() - It sets the isOn variable to true and prints the output.
 halogen.turnOff() - It sets the isOn variable to false and prints the
output.
The variable isOn defined inside the class is also called an instance
variable. It is because when we create an object of the class, it is called
an instance of the class. And, each instance will have its own copy of
the variable.
That is, led and halogen objects will have their own copy of
the isOn variable.
Example: Create objects inside the same class
Note that in the previous example, we have created objects inside
another class and accessed the members from that class.

However, we can also create objects inside the same class.

class Lamp {

// stores the value for light


// true if light is on
// false if light is off
boolean isOn;

// method to turn on the light


void turnOn() {
isOn = true;
System.out.println("Light on? " + isOn);

public static void main(String[] args) {

// create an object of Lamp


Lamp led = new Lamp();

// access method using object


led.turnOn();
}
}
Run Code

Output

Light on? true


Here, we are creating the object inside the main() method of the same
class.

What is a Constructor?
A constructor in Java is similar to a method that is invoked when an
object of the class is created.

Unlike Java methods, a constructor has the same name as that of the
class and does not have any return type. For example,

class Test {

Test() {

// constructor body

Here, Test() is a constructor. It has the same name as that of the class
and doesn't have a return type.
Recommended Reading: Why do constructors not return values
Example 1: Java Constructor
class Main {
private String name;

// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
}

public static void main(String[] args) {

// constructor is invoked while


// creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
}
}
Run Code

Output:

Constructor Called:
The name is Programiz

In the above example, we have created a constructor named Main() .

Inside the constructor, we are initializing the value of the name variable.
Notice the statement of creating an object of the Main class.

Main obj = new Main();

Here, when the object is created, the Main() constructor is called. And,
the value of the name variable is initialized.
Hence, the program prints the value of the name variables as Programiz .
Types of Constructor

In Java, constructors can be divided into 3 types:

1. No-Arg Constructor

2. Parameterized Constructor

3. Default Constructor

1. Java No-Arg Constructors


Similar to methods, a Java constructor may or may not have any
parameters (arguments).

If a constructor does not accept any parameters, it is known as a no-


argument constructor. For example,

private Constructor() {
// body of the constructor
}
Example 2: Java private no-arg constructor
class Main {

int i;

// constructor with no parameter


private Main() {
i = 5;
System.out.println("Constructor is called");
}

public static void main(String[] args) {

// calling the constructor without any parameter


Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}
Run Code

Output:

Constructor is called
Value of i: 5

In the above example, we have created a constructor Main() . Here, the


constructor does not accept any parameters. Hence, it is known as a
no-arg constructor.
Notice that we have declared the constructor as private.
Once a constructor is declared private , it cannot be accessed from
outside the class. So, creating objects from outside the class is
prohibited using the private constructor.
Here, we are creating the object inside the same class. Hence, the
program is able to access the constructor. To learn more, visit Java
Implement Private Constructor.
However, if we want to create objects outside the class, then we need
to declare the constructor as public .

Example 3: Java public no-arg constructors


class Company {
String name;

// public constructor
public Company() {
name = "Programiz";
}
}

class Main {
public static void main(String[] args) {

// object is created in another class


Company obj = new Company();
System.out.println("Company name = " + obj.name);
}
}
Run Code

Output:

Company name = Programiz


Recommended Reading: Java Access Modifier

2. Java Parameterized Constructor


A Java constructor can also accept one or more parameters. Such
constructors are known as parameterized constructors (constructor with
parameters).

Example 4: Parameterized constructor


class Main {

String languages;

// constructor accepting single value


Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}

public static void main(String[] args) {

// call constructor by passing a single value


Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Run Code
Output:

Java Programming Language


Python Programming Language
C Programming Language

In the above example, we have created a constructor named Main() .

Here, the constructor takes a single parameter. Notice the expression,

Main obj1 = new Main("Java");

Here, we are passing the single value to the constructor. Based on the
argument passed, the language variable is initialized inside the
constructor.

3. Java Default Constructor


If we do not create any constructor, the Java compiler automatically
create a no-arg constructor during the execution of the program. This
constructor is called default constructor.

Example 5: Default Constructor


class Main {

int a;
boolean b;
public static void main(String[] args) {

// A default constructor is called


Main obj = new Main();

System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Run Code

Output:

Default Value:
a = 0
b = false

Here, we haven't created any constructors. Hence, the Java compiler


automatically creates the default constructor.

The default constructor initializes any uninitialized instance variables


with default values.

Type Default Value

boolean false

byte 0

short 0
int 0

long 0L

char \u0000

float 0.0f

double 0.0d

object Reference null

In the above program, the variables a and b are initialized with default
value 0 and false respectively.
The above program is equivalent to:

class Main {

int a;
boolean b;

Main() {
a = 0;
b = false;
}

public static void main(String[] args) {


// call the constructor
Main obj = new Main();

System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Run Code

The output of the program is the same as Example 5.

Important Notes on Java Constructors


 Constructors are invoked implicitly when you instantiate objects.

 The two rules for creating a constructor are:


The name of the constructor should be the same as the class.
A Java constructor must not have a return type.
 If a class doesn't have a constructor, the Java compiler automatically
creates a default constructor during run-time. The default constructor
initializes instance variables with default values. For example,
the int variable will be initialized to 0

 Constructor types:
No-Arg Constructor - a constructor that does not accept any
arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the
Java compiler if it is not explicitly defined.
 A constructor cannot be abstract or static or final .
 A constructor can be overloaded but can not be overridden.

Constructors Overloading in Java


Similar to Java method overloading, we can also create two or more
constructors with different parameters. This is called constructors
overloading.
Example 6: Java Constructor Overloading
class Main {

String language;

// constructor with no parameter


Main() {
this.language = "Java";
}

// constructor with a single parameter


Main(String language) {
this.language = language;
}

public void getName() {


System.out.println("Programming Langauage: " + this.language);
}

public static void main(String[] args) {

// call constructor with no parameter


Main obj1 = new Main();

// call constructor with a single parameter


Main obj2 = new Main("Python");

obj1.getName();
obj2.getName();
}
}
Run Code

Output:

Programming Language: Java


Programming Language: Python

In the above example, we have two


constructors: Main() and Main(String language) . Here, both the
constructor initialize the value of the variable language with different
values.
Based on the parameter passed during object creation, different
constructors are called and different values are assigned.

It is also possible to call one constructor from another constructor.

Java Method Overriding


In this tutorial, we will learn about method overriding in Java with the
help of examples.
In the last tutorial, we learned about inheritance. Inheritance is an OOP
property that allows us to derive a new class (subclass) from an
existing class (superclass). The subclass inherits the attributes and
methods of the superclass.

Now, if the same method is defined in both the superclass and the
subclass, then the method of the subclass class overrides the method
of the superclass. This is known as method overriding.

Example 1: Method Overriding


class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


@Override
public void displayInfo() {
System.out.println("I am a dog.");
}
}

class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Run Code

Output:

I am a dog.

In the above program, the displayInfo() method is present in both


the Animal superclass and the Dog subclass.
When we call displayInfo() using the d1 object (object of the
subclass), the method inside the subclass Dog is called.
The displayInfo() method of the subclass overrides the same method
of the superclass.

Notice the use of the @Override annotation in our example. In Java,


annotations are the metadata that we used to provide information to the
compiler. Here, the @Override annotation specifies the compiler that the
method after this annotation overrides the method of the superclass.
It is not mandatory to use @Override . However, when we use this, the
method should follow all the rules of overriding. Otherwise, the compiler
will generate an error.

Java Overriding Rules


 Both the superclass and the subclass must have the same method
name, the same return type and the same parameter list.

 We cannot override the method declared as final and static .

 We should always override abstract methods of the superclass (will be


discussed in later tutorials).

super Keyword in Java Overriding


A common question that arises while performing overriding in Java is:

Can we access the method of the superclass after overriding?


Well, the answer is Yes. To access the method of the superclass from
the subclass, we use the super keyword.
Example 2: Use of super Keyword
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


public void displayInfo() {
super.displayInfo();
System.out.println("I am a dog.");
}
}

class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Run Code

Output:

I am an animal.
I am a dog.

In the above example, the subclass Dog overrides the


method displayInfo() of the superclass Animal .

When we call the method displayInfo() using the d1 object of


the Dog subclass, the method inside the Dog subclass is called; the
method inside the superclass is not called.
Inside displayInfo() of the Dog subclass, we have
used super.displayInfo() to call displayInfo() of the superclass.

It is important to note that constructors in Java are not inherited. Hence,


there is no such thing as constructor overriding in Java.

However, we can call the constructor of the superclass from its


subclasses. For that, we use super() . To learn more, visit Java super
keyword.
Static Methods
Static methods are also called class methods. It is because a static
method belongs to the class rather than the object of a class.

And we can invoke static methods directly using the class name. For
example,

class Test {
// static method inside the Test class
public static void method() {...}
}

class Main {
// invoking the static method
Test.method();
}

Here, we can see that the static method can be accessed directly from
other classes using the class name.

In every Java program, we have declared the main method static . It is


because to run the program the JVM should be able to invoke the main
method during the initial phase where no objects exist in the memory.
Example 1: Java static and non-static Methods
class StaticTest {

// non-static method
int multiply(int a, int b){
return a * b;
}

// static method
static int add(int a, int b){
return a + b;
}
}

public class Main {

public static void main( String[] args ) {

// create an instance of the StaticTest class


StaticTest st = new StaticTest();

// call the nonstatic method


System.out.println(" 2 * 2 = " + st.multiply(2,2));

// call the static method


System.out.println(" 2 + 3 = " + StaticTest.add(2,3));
}
}
Run Code

Output:

2 * 2 = 4
2 + 3 = 5

In the above program, we have declared a non-static method


named multiply() and a static method named add() inside the
class StaticTest .

Inside the Main class, we can see that we are calling the non-static
method using the object of the class ( st.multiply(2, 2) ). However, we
are calling the static method by using the class name
( StaticTest.add(2, 3) ).

Static Variables
In Java, when we create objects of a class, then every object will have
its own copy of all the variables of the class. For example,

class Test {
// regular variable
int age;
}

class Main {
// create instances of Test
Test test1 = new Test();
Test test2 = new Test();
}

Here, both the objects test1 and test2 will have separate copies of the
variable age. And, they are different from each other.

However, if we declare a variable static, all objects of the class share


the same static variable. It is because like static methods, static
variables are also associated with the class. And, we don't need to
create objects of the class to access the static variables. For example,

class Test {
// static variable
static int age;
}
class Main {
// access the static variable
Test.age = 20;
}

Here, we can see that we are accessing the static variable from the
other class using the class name.

Example 2: Java static and non-static Variables


class Test {

// static variable
static int max = 10;

// non-static variable
int min = 5;
}

public class Main {


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

// access the non-static variable


System.out.println("min + 1 = " + (obj.min + 1));

// access the static variable


System.out.println("max + 1 = " + (Test.max + 1));
}
}
Run Code

Output:

min + 1 = 6
max + 1 = 11

In the above program, we have declared a non-static variable


named min and a static variable named max inside the class Test .

Inside the Main class, we can see that we are calling the non-static
variable using the object of the class ( obj.min + 1 ). However, we are
calling the static variable by using the class name ( Test.max + 1 ).

Note: Static variables are rarely used in Java. Instead, the static
constants are used. These static constants are defined by static
final keyword and represented in uppercase. This is why some people
prefer to use uppercase for static variables as well.

Access static Variables and Methods within the


Class
We are accessing the static variable from another class. Hence, we
have used the class name to access it. However, if we want to access
the static member from inside the class, it can be accessed directly. For
example,

public class Main {

// static variable
static int age;
// static method
static void display() {
System.out.println("Static Method");
}
public static void main(String[] args) {

// access the static variable


age = 30;
System.out.println("Age is " + age);

// access the static method


display();
}
}
Run Code

Output:

Age is 30
Static Method

Here, we are able to access the static variable and method directly
without using the class name. It is because static variables and
methods are by default public. And, since we are accessing from the
same class, we don't have to specify the class name.

Static Blocks
In Java, static blocks are used to initialize the static variables. For
example,

class Test {
// static variable
static int age;

// static block
static {
age = 23;
}
}
Here we can see that we have used a static block with the syntax:

static {
// variable initialization
}

The static block is executed only once when the class is loaded in
memory. The class is loaded if either the object of the class is
requested in code or the static members are requested in code.

A class can have multiple static blocks and each static block is
executed in the same sequence in which they have been written in a
program.

Example 3: Use of static block in java


class Main {

// static variables
static int a = 23;
static int b;
static int max;

// static blocks
static {
System.out.println("First Static block.");
b = a * 4;
}
static {
System.out.println("Second Static block.");
max = 30;
}

// static method
static void display() {

System.out.println("a = " + a);


System.out.println("b = " + b);
System.out.println("max = " + max);
}

public static void main(String args[]) {


// calling the static method
display();
}
}
Run Code

Output:

First Static block.


Second Static block.
a = 23
b = 92
max = 30

In the above program. as soon as the Main class is loaded,

 The value of a is set to 23 .

 The first static block is executed. Hence, the string First Static

block is printed and the value of b is set to a * 4.

 The second static block is executed. Hence, the string Second Static

block is printed and the value of max is set to 30 .

 And finally, the print statements inside the method display() are
executed.
Nested Static Class
In Java, we can declare a class inside another class. Such classes are
known as nested classes. Nested classes are of 2 types:

 Static Nested Classes

 Non-static Nested Classes

For example,

class OuterClass {
// static nested class
static class NestedClass {...}

// non-static nested class


class InnerClass {...}

Java String Class Methods


The java.lang.String class provides a lot of built-in methods that are
used to manipulate string in Java. By the help of these methods, we
can perform operations on String objects such as trimming,
concatenating, converting, comparing, replacing strings etc.

Java String is a powerful concept because everything is treated as a


String if you submit any form in window based, web based or mobile
application.
Let's use some important methods of String class.

Java String toUpperCase() and toLowerCase() method


The Java String toUpperCase() method converts this String into
uppercase letter and String toLowerCase() method into lowercase
letter.

Stringoperation1.java

1. public class Stringoperation1


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.toUpperCase());//SACHIN
7. System.out.println(s.toLowerCase());//sachin
8. System.out.println(s);//Sachin(no change in original)
9. }
10. }
Test it Now

Output:
SACHIN
sachin
Sachin

Java String trim() method


The String class trim() method eliminates white spaces before and
after the String.

Stringoperation2.java

1. public class Stringoperation2


2. {
3. public static void main(String ar[])
4. {
5. String s=" Sachin ";
6. System.out.println(s);// Sachin
7. System.out.println(s.trim());//Sachin
8. }
9. }
Test it Now

Output:
Sachin
Sachin

Java String startsWith() and endsWith() method


The method startsWith() checks whether the String starts with the
letters passed as arguments and endsWith() method checks whether
the String ends with the letters passed as arguments.

Stringoperation3.java

1. public class Stringoperation3


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.startsWith("Sa"));//true
7. System.out.println(s.endsWith("n"));//true
8. }
9. }
Test it Now

Output:
true
true
Java String charAt() Method
The String class charAt() method returns a character at specified
index.

Stringoperation4.java

1. public class Stringoperation4


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.charAt(0));//S
7. System.out.println(s.charAt(3));//h
8. }
9. }
Test it Now

Output:
S
h

Java String length() Method


The String class length() method returns length of the specified String.

Stringoperation5.java

1. public class Stringoperation5


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.length());//6
7. }
8. }
Test it Now

Output:
6

Java String intern() Method


A pool of strings, initially empty, is maintained privately by the class
String.

When the intern method is invoked, if the pool already contains a


String equal to this String object as determined by the equals(Object)
method, then the String from the pool is returned. Otherwise, this
String object is added to the pool and a reference to this String object
is returned.

Stringoperation6.java

1. public class Stringoperation6


2. {
3. public static void main(String ar[])
4. {
5. String s=new String("Sachin");
6. String s2=s.intern();
7. System.out.println(s2);//Sachin
8. }
9. }
Test it Now

Output:
Sachin

Java String valueOf() Method


The String class valueOf() method coverts given type such as int, long,
float, double, boolean, char and char array into String.

Stringoperation7.java
1. public class Stringoperation7
2. {
3. public static void main(String ar[])
4. {
5. int a=10;
6. String s=String.valueOf(a);
7. System.out.println(s+10);
8. }
9. }

Output:
1010

Java String replace() Method


The String class replace() method replaces all occurrence of first
sequence of character with second sequence of character.

Stringoperation8.java

1. public class Stringoperation8


2. {
3. public static void main(String ar[])
4. {
5. String s1="Java is a programming language. Java is a platform. Java is
an Island.";
6. String replaceString=s1.replace("Java","Kava");//replaces all occurrenc
es of "Java" to "Kava"
7. System.out.println(replaceString);
8. }
9. }

Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Java Command-Line Arguments

Example: Command-Line Arguments


class Main {
public static void main(String[] args) {
System.out.println("Command-Line arguments are");

// loop through all arguments


for(String str: args) {
System.out.println(str);
}
}
}
Run Code

Let's try to run this program using the command line.

1. To compile the code

javac Main.java

2. To run the code

java Main

Now suppose we want to pass some arguments while running the


program, we can pass the arguments after the class name. For
example,

java Main apple ball cat


Here apple , ball , and cat are arguments passed to the program
through the command line. Now, we will get the following output.

Command-Line arguments are


Apple
Ball
Cat

In the above program, the main() method includes an array of strings


named args as its parameter.

public static void main(String[] args) {...}

The String array stores all the arguments passed through the
command line.

Note: Arguments are always stored as strings and always separated


by white-space.

Passing Numeric Command-Line Arguments


The main() method of every Java program only accepts string
arguments. Hence it is not possible to pass numeric arguments through
the command line.
However, we can later convert string arguments into numeric values.
Example: Numeric Command-Line Arguments
class Main {
public static void main(String[] args) {

for(String str: args) {


// convert into integer type
int argument = Integer.parseInt(str);
System.out.println("Argument in integer form: " + argument);
}

}
}
Run Code

Let's try to run the program through the command line.

// compile the code


javac Main.java

// run the code


java Main 11 23

Here 11 and 23 are command-line arguments. Now, we will get the


following output.

Arguments in integer form


11
23

In the above example, notice the line

int argument = Intege.parseInt(str);


Here, the parseInt() method of the Integer class converts the string
argument into an integer.
Similarly, we can use the parseDouble() and parseFloat() method to
convert the string into double and float respectively.

Note: If the arguments cannot be converted into the specified numeric


value then an exception named NumberFormatException occurs.

Use of final Keyword in Java


In Java, final is a keyword that guarantees only the immutability
of primitive types. And also guarantees that a variable is assigned only
once. If an object is mutable, we can change the content of it even it is
defined as final. In this section, we will discuss the uses of the final
keyword in detail.

The keyword final is a non-access modifier. If we want to use the final


keyword, we must specify it before a variable, method, and class. It
restricts us to access the variable, method, and class. Note that the
final methods cannot be inherited and overridden. We must use the
final keyword if we want to store the value that does not require to
change throughout the execution of the program. Usually, it is used to
assign constant values. For example, the value of PI=3.14, g=9.8.
Remember the following points while dealing with the final keyword:

o Initialize a final variable when it is declared.


o A blank final variable can be initialized inside an instance-
initializer block or inside the constructor.
o A blank final static variable can be initialized inside a static block.

Let's discuss the use of the final keyword.

Use of final keyword with a Variable


A variable can be declared as final by using the final keyword. The
value of a final variable (constant) cannot be changed once assigned.
The final variable must be in uppercase. We can also use underscore to
separate two words. For example:

1. // a final variable
2. final double PRICE;
3. final int COUNT = 5;
4. // a final static variable PI
5. static final double PRICE;
6. static final double PI = 3.141;

When a final variable is a reference to an object, then this final variable


is called the reference final variable. For example, final
StringBuffer sb;

Note: In the case of the reference final variable, the internal state of the object pointed
by that reference variable can be changed but it is not re-assigning of a reference
variable. The mechanism is known as non-transitivity.

The mechanism can also be applied to an array as arrays are objects in


Java. Arrays prefix with final is called final arrays.
Use of final keyword with a Method
A method prefix with the keyword final is known as the final method.
Note that a final method cannot be overridden. For example, most of
the methods of the Java Object class are final.

1. class Demo
2. {
3. final void display()
4. {
5. System.out.println("Inside final method.");
6. }
7. }

Use of final keyword with a Class


The class declared as final is called final class. Note that the final
class cannot be inherited. There are two uses of the final class i.e. to
prevent inheritance and to make classes immutable. For
example, all wrapper classes are the final classes and the String
class is an immutable class.

1. final class Demo1


2. {
3. // variables, methods, and fields
4. }
5. // The following class is illegal
6. class Demo2 extends Demo1
7. {
8. // COMPILE-ERROR! Can't subclass A
9. }

You might also like