22cs202-Unit 1 - PPT
22cs202-Unit 1 - PPT
JAVA PROGRAMMING
UNIT-1
JAVA FUNDAMENTALS
AN OVERVIEW OF JAVA
WHAT IS JAVA ??
• Programming Language
Why JAVA?
• Java was originally designed for interactive television, but it was too advanced
technology for the digital cable television industry at the time.
• However, it was best suited for internet programming.
• Later, Java technology was incorporated by Netscape .
HISTORY OF JAVA
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the green project.
Why Java was named as "Oak"?
5) Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France,
Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
HISTORY OF JAVA
• have been many additional features added to the language. Now Java is being
• used in Windows applications, Web applications, enterprise applications, mobile applications, cards, etc.
Each new version adds new features in Java.
CHARACTERISTICS OF JAVA
1. Simple
❖ Easy to write and more readable and eye catching.
❖ Has concise set of features that makes it easy to learn and use.
❖ Most of the concepts are drew from C++ thus making Java learning simpler.
2. Secure
❖ Cannot harm other system thus making it secure.
❖ Provides a secure means of creating Internet applications.
❖ Provides secure way to access web applications.
CHARACTERISTICS OF JAVA
3. Portable
❖ Can execute in any environment for which there is a Java run-time system.
❖ (JVM)
❖ Can be run on any platform (Linux,Window,Mac)
❖ Can be transferred over world wide web (e.g. applets)
4. Object-oriented
❖ Java is object-oriented programming language.
❖ Like C++ java provides most of the object oriented features.
❖ Pure OOP Language. (while C++ is semi object oriented)
CHARACTERISTICS OF JAVA
5. Robust
It uses strong memory management.
❖ There are lack of pointers that avoids security problems.
❖ There is automatic garbage collection in java which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
❖ There is exception handling and type checking mechanism in java. All these points makes
java robust
6. 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.
CHARACTERISTICS OF JAVA
7. Architecture-neutral
❖ Java is not tied to a specific machine or operating system architecture.
❖ Machine Independent i.e Java is independent of hardware.
❖ Interpreted
❖ Supports cross-platform code through the use of Java bytecode.
❖ Bytecode can be interpreted on any platform by JVM.
8. High performance
❖ Bytecodes are highly optimized.
❖ JVM can executed them much faster.
CHARACTERISTICS OF JAVA
9. Distributed
❖ Java was designed with the distributed environment.
❖ Java can transmit, run over internet.
10. Dynamic
❖ Java programs carry with them substantial amounts of run-time type information that is
used to verify and resolve accesses to objects at run time.
JAVA ENVIRONMENT
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed .
When you run the Java program, Java compiler first compiles your Java code to bytecode.
Then, the JVM translates bytecode into native machine code.
JRE-JAVA RUNTIME ENVIRONMENT
• JRE (Java Runtime Environment) is a software package that provides Java class libraries, along with Java
Virtual Machine (JVM), and other components to run applications written in Java programming. JRE is the
superset of JVM.
JDK (Java Development Kit)
•JDK (Java Development Kit) is a software development kit to develop applications in Java. When you
download JDK, JRE is also downloaded, and don't need to download it separately.
•In addition to JRE, JDK also contains number of development tools (compilers, JavaDoc, Java Debugger etc).
❖ public keyword is an access modifier which represents visibility, it means it is visible to all.
❖ static is a keyword, if we declare any method as static, it is known as static method. The core advantage of
static method is that there is no need to create object to invoke the static method. The main method is executed
by the JVM, so it doesn't require to create object to invoke the main method. So it saves memory.
❖ void is the return type of the method, it means it doesn't return any value.
3.Online compilers
Command Prompt Execution
(Refer:https://www.youtube.com/watch?v=zBF1M8dTftk)
1.Download and Install JDK
• (Refer: https://www.oracle.com/java/technologies/javase-downloads.html ) Installed in
C: Program Files Java JDK
2.Save the Source Code in any working space Let Working Space
be
• D:\My Java Programs\Week1
3.Set the Path in Command Prompt
• D:\My Java Programs\Week1> set path = “C:\Program Files\Java\
JDK\Bin”
4.Compile the Source Code
• D:\My Java Programs\Week1> javac Welcome.java
• On successful Compilation Welcome.class (Byte Code) is created
5.Interpret / Execute the Class File (Byte Code)
D:\My Java Programs\Week1> java Welcome
STEPS FOR COMPILE AND RUN JAVA
PROGRAM
• First Save Java program with same as class name with .java extension.
Example: Sum.java
ENCAPSULATION
❖ The wrapping up of data and methods into single unit.
❖ Data is not accessible outside the class. This can be done access specifiers.
❖ Provides the security that keeps data and methods safe from inadvertent changes.
❖ A java class is the example of encapsulation
INHERITANCE
❖ When one object (derived class) acquires all the properties and behavior's of parent object(base class), it
is known as inheritance.
POLYMORPHISM
Poly refers to many
The ability to take more than one form.
In java, we use method overloading and method overriding to achieve polymorphism.
Types of Polymorphism
❖ Data Types in Java Based on the data type of a variable, the operating system allocates
memory and decides what can be stored in the reserved memory.
❖ Therefore, by assigning different data types to variables, you can store integers, decimals, or
characters in these variables.
❖ Keywords are particular words that act as a key to a code. These are predefined words by Java so they
• Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
TYPES OF ARRAYS IN JAVA
• dataType[] arr;
• dataType []arr;
• dataType arr[];
arrayRefVar=new datatype[size];
Java Program to illustrate how to declare, instantiate, initialize and traverse
the Java array.
//Program
class Testarray
{
public static void main(String args[]) OUTPUT
{ 10
int a[]=new int[5]; //declaration and instantiation 20
a[0]=10; //initialization 70
a[1]=20; 40
a[2]=70; 50
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}
TWO-DIMENSIONAL ARRAY IN JAVA
Data is stored in a row and column-based index (also known as matrix form).
SYNTAX
dataType[][] arrayRefVar;
(or)
dataType [][]arrayRefVar;
(or)
dataType arrayRefVar[][];
Example to instantiate Multidimensional Array in Java
ADVANTAGES
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
DISADVANTAGES
• Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size
at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
Operators
Operators are the symbols used to perform specific operations. Various
operators can be used for different purposes.
The operators are categorized as:
Unary
Arithmetic
Relational
Logical
Ternary
Assignment
Bitwise
Unary Operators
Unary operators act upon only one operand and perform operations such
as increment, decrement, negating an expression, or inverting a Boolean value.
Operator Name Description
int x=10;
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}
}
Example: ~ and !
public class OperatorExample
{
public static void main(String args[]) Output:
-11
{
9
int a=10; false
int b=-10; true
boolean c=true;
boolean d=false;
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);
System.out.println(!d);
}}
Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10; int numTwo = 5;
boolean isTrue = true;
System.out.println(numOne++ + " h kj" + ++numOne); //Output will be 10 12
System.out.println(numTwo-- + " " + --numTwo); //Output will be 5 3
System.out.println(!isTrue + " " + ~numOne); //Output will be false -13
}
}
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and division.
Operator Description
+ Additive operator (also used for string concatenation)
- Subtractive operator
* Multiplication operator
/ Division operator
% Modulus operator
Example
class Welcome
int numTwo = 5;
}
Relational operators
Relational operators are used to compare two values. The result of all the
relational operations is either true or false.
Operator Description
== Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
Example
class Welcome
{
public static void main(String args[])
{
int numOne = 10;
int numTwo = 5;
System.out.println(numOne > numTwo);
}
}
Output:
true
Logical Operators
Logical operators are used to combine two or more relational expressions or
to negate the result of a relational expression.
Operator Name Description
The result will be true only if both
&& AND
expressions are true
The result will be true if any one of the
|| OR
expressions is true
The result will be false if the expression is
! NOT
true and vice versa
Operator Description
= Assigns the value on the right to the variable on the left
Adds the current value of the variable on the left to the value on the
+=
right and then assigns the result to the variable on the left
Subtracts the value of the variable on the right from the current value of
-=
the variable on left and then assigns the result to the variable on the left
Multiplies the current value of the variable on left to the value on the
*=
right and then assigns the result to the variable on the left
Divides the current value of the variable on left by the value on the
/=
right and then assign the result to the variable on the left
Example
import java.io.*;
class Welcome
{
public static void main(String args[])
{
int numOne = 10; //The value 10 is assigned to numOne
System.out.println(numOne); //Output will be 10
numOne + = 5;
System.out.println(numOne); //Output will be 15
numOne - = 5;
System.out.println(numOne); //Output will be 10
numOne * = 5;
System.out.println(numOne); //Output will be 50
numOne / = 5;
System.out.println(numOne); //Output will be 10
}
}
Bitwise Operators
Bitwise operators are used to perform manipulation of individual bits of a
number. Let us understand how to convert a decimal number to a binary number
and vice versa.
The decimal or the base 10 number system is used in everyday life but the
binary number system is the basis for representing data in computing systems.
Steps to convert a decimal number to a binary number.
•Step 1: Divide the decimal number by 2.
•Step 2: Write the number on the right-hand side. This will be either 1 or 0
•Step 3: Divide the result of the division again by 2 and write the remainder.
•Step 4: Continue this process until the result of the division is 0.
•Step 5: The first remainder that you received isa the least significant bit and
the last remainder is the most significant bit.
Steps to convert the binary number back to a decimal number.
•The decimal number is equal to the sum of binary digits (dn) times their
power of 2 (2n).
Let us take the example of 11001.
•11001 = 1*24+1*23+0*22+0*21+1*20 = 16+8+0+0+1 = 25
Bitwise OR (|)
•It returns bit by bit OR of the input values. If either of the bits is 1, then
it gives 1, else it gives 0.
• E.g. - The output of 10 | 5 is 15.
Output:
2) if-else statement
If the condition specified is true, the if block is executed. Otherwise, the
else block is executed.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Example Program:
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y < 10)
{
System.out.println("x + y is less than 10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
3) if-else-if ladder:
• The if statement is followed by multiple else-if blocks. We can create a decision
tree by using these control statements in Java in which the block where the
condition is true is executed and the rest of the ladder is ignored and not executed.
• If none of the conditions is true, the last else block is executed, if present.
Syntax
if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when all the conditions are false
Example Program:
public class Student
{
public static void main(String[] args)
{
String city = "Delhi"; Output:
if(city == "Meerut") Delhi
{
System.out.println("city is meerut");
}
else if (city == "Noida")
{
System.out.println("city is noida");
}
else if(city == "Agra")
{
System.out.println("city is agra");
}
else
{
System.out.println(city);
} }}
4. Nested if-statement
Java allows us to nest control statements within control statements.
Nested control statements mean an if-else statement inside
other if or else blocks. It is similar to an if-else statement but they are
defined inside another if-else statement.
Syntax:
if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
import java.io.*;
if(address.endsWith("India")) {
Output:
if(address.contains("Meerut")) { Delhi
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
}else {
System.out.println(address.split(",")[0]);
}else {
} } }
Switch Statements
• Switch Statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed
based on the variable which is being switched.
• The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
Notes to remember
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
• Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
• While using switch statements, we must notice that the case expression will be
of the same type as the variable. However, it will also be a constant value.
Syntax:
switch (expression)
{
case value1:
//code block of case with value1
break;
case value2:
//code block of case with value2
break;
.
.
case valueN:
//code block of case with valueN
break;
default:
//code block of default value
}
Example Program:
import java.io.*; case 5:
public class Sample { System.out.println("Thursday");
public static void main(String[] args) { break;
int weekday = Integer.parseInt(args[0]); case 6:
switch (weekday) { System.out.println("Friday");
case 1: break;
System.out.println("Sunday"); case 7:
break; System.out.println("Saturday");
case 2: break;
System.out.println("Monday"); default:
break; System.out.println("Invalid day");
case 3: }
System.out.println("Tuesday"); }
break; }
case 4: Output:
System.out.println("Wednesday");
If args[0] is 5 then the ouput is
break;
Thursday
Loop statements
• In programming, sometimes we need to execute the block of code
repeatedly while some condition evaluates to true.
• However, loop statements are used to execute the set of instructions in a
repeated order. The execution of the set of instructions depends upon a
particular condition.
• In Java, we have three types of loops that execute similarly. However, there
are differences in their syntax and condition checking time.
– for loop
– while loop
– do-while loop
while Loop
It’s a entry controlled loop, the condition in the while loop is evaluated,
and if the condition is true, the code within the block is executed. This
repeats until the condition becomes false
Syntax:
false
Boolean Condition
while(condition)
{ true
}
Example Program:
import java.io.*;
public class Sample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("i: " + i);
i = i + 1;
}
}}
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
do.. while Loop
It’s a exit controlled loop, the body of the loop gets executed first
followed by checking the condition. Continues with the body if the
condition is true, else loops gets terminated.
Syntax
Body of the loop
do
{
false
Boolean Condition
Body of the loop
Syntax:
}
Example Program:
import java.io.*;
public class Sample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
System.out.println("i: " + i);
}
}
}
Output:
i: 1
i: 2
i: 3
i: 4
i: 5
Enhanced For Loop or For Each Loop
Enhanced for loop used along with a
collection of data. Output:
Syntax:
i: 10
for(declaration : expression) {
i: 20
Body of loop
} i: 30
Example Program: i: 40
public class Sample i: 50
{
public static void main(String[] args)
{
int[] numbers = { 10, 20, 30, 40, 50 };
for (int i : numbers)
{
System.out.println("i: " + i);
} } }
Jump/Branching Statements
• Jump statements are used to transfer the control of the program to the
specific statements. In other words, jump statements transfer the execution
control to the other part of the program. There are two types of jump
statements in Java, i.e., break and continue.
1. Break Statement
• While the execution of program, the break statement will terminate the
iteration or switch case block.
• When a break statement is encountered in a loop, the loop is exited and the
program continues with the statements immediately following the loop.
• When the loops are nested, the break will only terminate the corresponding
loop body.
Example Program
import java.io.*;
public class Sample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
if (i == 2)
break;
System.out.println("i: " + i);
}
}}
Output:
i: 1
continue Statement
• In while and do loops, continue causes the control to go directly to the test-condition
and then continue the iteration process.
• In case of for loop, the increment section of the loop is executed before the test-
condition is evaluated. if (i == 3)
Example Program {
continue;
import java.io.*;
}
public class Sample
System.out.println("i: " + i);
{
} }}
public static void main(String[] args) Output:
{
i: 1
int[] numbers = { 1, 2, 3, 4, 5 };
i: 2
for (int i : numbers)
i: 4
{ i: 5
Class Fundamentals
Class in Java
•A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical entity. It
cannot be physical.
•A class in Java can contain: Example
Fields / Variable
Methods import java.io.*;
Constructors
Blocks
class Sample
Nested class and interface {
Syntax to declare a class: int a,b; //variable declaration
class <class_name> public:
{ void get(); //method1
field / variable; method; void display(); //method2
} }
Declaring Objects
Syntax:
ClassName object = new ClassName();
Example Program:
public class CreateObjectExample1
Output:
{
Welcome to javaTpoint
void show()
{
System.out.println("Welcome to javaTpoint");
}
public static void main(String[] args)
{
CreateObjectExample1 obj = new CreateObjectExample1();
obj.show();
}
}
Declaring Methods
•A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation. It is used to achieve
the reusability of code.
• 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
Syntax
return_type method_name(argument_list)
{
//statements;
}
Example:
Example Program:
class sample
{
public int addNumbers(int a, int b) // create a method
{
int sum = a + b; // return value return sum;
}
public static void main(String[] args)
{
int num1 = 25;
int num2 = 15; Output
sample obj = new sample(); // create an object of Main Sum is: 40
int result = obj.addNumbers(num1, num2); // calling method
System.out.println("Sum is: " + result);
}
}
I/O statements in Java
Java I/O (Input and Output) is used to process the input and produce the
output. Java uses the concept of a stream to make I/O operations fast. The java.io
package contains all the classes required for input and output operations.
Java Scanner Class
• Java Scanner class allows the user to take input from the console. It belongs
to java.util package. It is used to read the input of primitive types like int, double,
long, short, float, and byte. It is the easiest way to read input in a Java program.
Syntax
Scanner object_name=new Scanner(System.in);
Example
Scanner s=new Scanner(System.in);
Methods of Java Scanner Class
Method Description
byte nextByte() It is used to scan the next token of the input as a byte.
call is required
• Every class has a constructor, whether the programmer creates it or not.
• One constructor can invoke another constructor of the same class using the
keyword this().
● Parameterized constructor.
Example1: Constructor
class Rectangle
{
int length; int width;
Rectangle(int x,int y)//constructor method
{
length=x; width=y;
}
int rectArea()
{
return(length*width);
}
}
class RectangleArea
{
public static void main (String args[])
{
Rectangle rect1=new Rectangle(15,10);//calling constructor
int area1=rect1.rectArea();
System.out.println(“Area =” +area1);
}
}
Output:
Area=150
Example 2
class Complex
{
int real;
int imag;
Complex() //No argument or default constructor
{
real=0;
imag=0;
}
Complex(int r,int i) //Parameterized constructor
{
real=r;
imag=i;
}
public static void main(String[] args)
{
Complex c1=new Complex(); //invoked No argument
constructor
System.out.println(c1.real+"+"+c1.imag+"i"); //0+0i
Complex c2=new Complex(2,3); //invoked
parameterized constructor
System.out.println(c2.real+"+"+c2.imag+"i"); //2+3i
}
}
Example3
class complex
{
double real,imag;
complex() //simple or default constructor
{
real=0.0;
imag=0.0;
}
complex(double x,double y) //parameterized constructor
{
real=x;
imag=y;
}
complex add(complex a) //copy constructor
{
complex n=new complex();
n.real=this.real+a.real;
n.imag=this.imag+a.imag;
return n;
}
void display()
{
System.out.println(“The result is”+real+”+i”+imag);
}
}
class comclass
{
public static void main(String args[])
{
complex c1=new complex(10,20); complex c2=new complex(10,20);
complex c1=new complex(); c3=c1.add(c2);
c3.display();
}
}
Output
The result is 20.0+i40.0
This Keyword
• this: to refer current class instance variable
• this can be used to return the current class instance from the method.
Example
class Student
{
int rollno; String name; float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Output:
111 ankit 5000.0
112 sumit 6000.0
Method Overloading in Java
• If a class has multiple methods having the same name but different
parameters, it is known as Method Overloading.
In this example, we have created two methods, first, add() method performs
the addition of two numbers and second add() method performs the addition
of three numbers.
Example
class Adder
{
int add(int a,int b)
{
return a+b;
}
int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
Adder a=new Adder();
System.out.println(a.add(11,11));
System.out.println(a.add(11,11,11));
}
}
Output:
22
33
Method Overloading: changing data type of arguments
In this example, we have created two methods that differ in data type.
The first add method receives two integer arguments and the second
add method receives two double arguments.
Example
class Adder
{
int add(int a, int b)
{
return a+b;
}
double add(double a, double b)
{
return a+b;
}
}
class TestOverloading
{
public static void main(String[] args)
{
Adder a=new Adder();
System.out.println(a.add(11,11));
System.out.println(a.add(12.3,12.6));
}
}
Output:
22
24.9
Constructor Overloading
default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package No modifiers are needed.
private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
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.
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
Non access modifiers
• Java has seven Non-Access Modifiers. Non-Access Modifiers are used with
classes, methods, variables, constructors. Non-Access Modifiers are used to
provide information to JVM.
Seven Non-Access Modifiers are
• Static: The static keyword in Java is used for memory management mainly. We
can apply static keyword with variables, methods, blocks and nested classes.
The static keyword belongs to the class than an instance of the class
• Final: The final keyword in java is used to restrict the user. The java final
• Keyword: can be used in many contexts. Final can be variable, method and
class
• Abstract: The abstract keyword is used to achieve abstraction in Java. It is a non-access
modifier which is used to create abstract class and method. The role of an abstract class is
to contain abstract methods
• Synchronized: Java programming language provides a very handy way of creating threads
and synchronizing their task by using synchronized blocks to keep shared resources.
• Transient: Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
• Volatile: Volatile keyword is used to modify the value of a variable (either primitive type or
objects) by different threads. It is also used to make classes thread safe.
• Native: The native keyword is applied to a method to indicate that the method is
implemented in native code using JNI (Java Native Interface). Native is a modifier applicable
only for methods and cannot apply it anywhere else. The methods which are implemented
in C, C++ are called as native methods or foreign
Java Static Keyword
• The static variable gets memory only once in the class area at the
time of class loading.
Advantages of static variable
•A static method belongs to the class rather than the object of a class.
•A static method can access static data members and can change their
value of it.
Example of static method
//Java Program to get the cube of a given number using the static method
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result=Calculate.cube(5); System.out.println(result);
}
}
Output
125
Final Keyword in Java
•The final keyword in java is used to restrict the user. The java final
keyword can be used in many contexts. The Final can be:
1.variable
2.method
3.class
•The final keyword can be applied to the variables, a final variable that
have no value is called a blank final variable or uninitialized final variable.
•It can be initialized in the constructor only. The blank final variable can be
static also which will be initialized in the static block only.
Java final variable
Output
display() in Main cannot override display() in FinalDemo public final void
display() {
^
overridden method is final