Java_oops
Java_oops
Identifiers:
}
}
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of invalid identifiers :
My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character
Reserved Words
Any programming language reserves some words to represent
functionalities defined by that language. These words are called
reserved words.They can be briefly categorized into two
parts : keywords(50) and literals(3). Keywords define functionalities
and literals define a value. Identifiers are used by symbol tables in
various analyzing phases(like lexical, syntax, semantic) of a compiler
architecture.
Note: The keywords const and goto are reserved, even though they
are not currently used. In place of const, the final keyword is used.
Some keywords like strictfp are included in later versions of Java.
Java Keywords
Java keywords are also known as reserved words. Keywords are particular
words that act as a key to a code. These are predefined words by Java so
they cannot be used as a variable or object name or class name.
2. boolean:
3. break
: Java break keyword is used to break the loop or switch statement. It breaks
the current flow of the program at specified conditions.
4. byte
: Java byte keyword is used to declare a variable that can hold 8-bit data
values.
5. case
: Java case keyword is used with the switch statements to mark blocks of
text.
6. catch
7. char
: Java char keyword is used to declare a variable that can hold unsigned 16-
bit Unicode characters
8. class
9. continue
: Java continue keyword is used to continue the loop. It continues the current
flow of the program and skips the remaining code at the specified condition.
10. default
: Java default keyword is used to specify the default block of code in a switch
statement.
11. do
12. double
: Java double keyword is used to declare a variable that can hold 64-bit
floating-point number.
13. else
15. extends
16. final
: Java final keyword is used to indicate that a variable holds a constant value.
It is used with a variable. It is used to restrict the user from updating the
value of the variable.
17. finally
18. float
: Java float keyword is used to declare a variable that can hold a 32-bit
floating-point number.
19. for
: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the
number of iteration is fixed, it is recommended to use for loop.
20. if
: Java if keyword tests the condition. It executes the if block if the condition is
true.
21. implements
22. import
: Java import keyword makes classes and interfaces available and accessible
to the current source code.
23. instanceof
: Java instanceof keyword is used to test whether the object is an instance of
the specified class or implements an interface.
24. int
: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.
25. interface
26. long
: Java long keyword is used to declare a variable that can hold a 64-bit
integer.
28. new
29. null
: Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value.
30. package
: Java package keyword is used to declare a Java package that includes the
classes.
31. private
32. protected
33. public
: Java public keyword is an access modifier. It is used to indicate that an item
is accessible anywhere. It has the widest scope among all other modifiers.
34. return
: Java return keyword is used to return from a method when its execution is
complete.
35. short
: Java short keyword is used to declare a variable that can hold a 16-bit
integer.
36. static
37. strictfp
38. super
39. switch
: The Java switch keyword contains a switch statement that executes code
based on test value. The switch statement tests the equality of a variable
against multiple values.
40. synchronized
41. this
: Java this keyword can be used to refer the current object in a method or
constructor.
42. throw
: The Java throw keyword is used to explicitly throw an exception. The throw
keyword is mainly used to throw custom exceptions. It is followed by an
instance.
43. throws
44. transient
45. try
: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.
46.void: Java void keyword is used to specify that a method does not have a
return value.
47. volatile
48. while
: Java while keyword is used to start a while loop. This loop iterates a part of
the program several times. If the number of iteration is not fixed, it is
recommended to use the while loop.
Java Variables
Variables are containers for storing data values.
Syntax
type variableName = value;
Where type is one of Java's types (such as int or String), and variableName is
the name of the variable (such as x or name). The equal sign is used to assign
values to the variable.
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type String and assign it the value "John":
System.out.println(name);
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
System.out.println(myNum);
You can also declare a variable without assigning the value, and assign the
value later:
Example
int myNum;
myNum = 15;
System.out.println(myNum);
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Example
Change the value of myNum from 15 to 20:
System.out.println(myNum);
Final Variables
If you don't want others (or yourself) to overwrite existing values, use
the final keyword (this will declare the variable as "final" or "constant", which
means unchangeable and read-only):
Example
final int myNum = 15;
Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;
Literal in Java
1. Integral Literals
Integral literals are specified in four different ways, as
follows:
Decimal: It has base ten, and digits from 0 to 9.
For example,
Int x = 108;
Octal: It has base eight and allows digits from 0 to 7. While
assigning an octal literal in the Java code, a number must
have a prefix 0.
For example,
int x = 0745;
Hexadecimal:
It has base 16. Hexadecimal allows digits from 0 to 9, and
characters from A to F. Even though Java is case sensitive,
and it also provides an exception for using either uppercase
or lowercase characters in the code for hexadecimal literals.
For example,
int x = 0X123Fadd;
Binary:
It can be specified in binary literals, that is 0 and 1 with a
prefix 0b or 0B.
For example,
int x = 0b1011;
2. Floating-Point Literals
FLoating-point literals can be expressed using only decimal
fractions or as exponential notation.
For example,
decimalNumber = 89d;
decimalNumber = 3.14159e0;
decimalNumber = 1.0e-6D;
Floating-point literals can indicate a positive or negative
value, leading + or – sign respectively. If not specified, the
value is always considered positive. It can be represented in
the following formats:
-Integer digits (representing digits 0 through 9) followed by
either a suffix or an exponent to distinguish it from an
integral literal.
-Integer digit.
-integer digit. integer digit
– integer digit
An optional exponent of the form might be as below:
-an optional exponent sign + or –
-the exponent indicator e or E
–integer digit representing the integer exponent value
An optional floating-point suffix might be as below:
Single precision (4 bytes) floating-point number indicating
either for F
Double precision (8 bytes) floating-point number
indicating d or D
3. Char Literals
Character (Char) literals have the type char and are an
unsigned integer primitive type. They are constant value
character expressions in the Java program. These are
sixteen-bit Unicode characters that range from 0 to 65535.
Char literals are expressed as a single quote, a single closing
quote, and the character in Java.
Char literals are specified in four different ways, as given
below:
Single quote: Java literal is specified to a char data type as a
single character enclosed in a single quote.
For example,
char ch = ‘a’;
Char Literal: Java literal is specified as an integer literal
representing the Unicode value of a char. This integer can be
specified in octal, decimal, and hexadecimal, ranging from 0
to 65535.
For example,
char ch = 062;
Escape Sequence: Every escape char can be specified as char
literal.
For example,
char ch = ‘\n’;
Unicode Representation: Java literal is specified in Unicode
representation ‘\uzzz’, where zzzz are four hexadecimal
numbers.
For example,
char ch = ‘\u0061’;
4. String Literals
A sequence of (zero or more including Unicode characters)
characters within double quotes is referred to as string
literals.
For example,
String s = “Hello”;
String literals may not have unescaped line feed or newline
characters, but the Java compiler always evaluates compile-
time expressions. Unicode escape sequences or special
characters can be used within the string and character literal
as backlash characters to escape special characters, as
shown in the table below:
Name Character ASCII Hex
Single quote \’ 39 0x27
Double quote \” 34 0x22
Carriage control \r 13 0xd
Backlash \\ 92 0x5c
Newline \n 10 0x0a
NUL character \0 0 0x00
Backspace \b 8 0x08
TAB \t 9 0x09
5. Boolean Literals
Boolean literals allow only two values and thus are divided
into two literals:
True: it represents a real boolean value
False: it represents a false boolean value
For example,
boolean b = true;
boolean d = false;
6. Null Literals
Null literal is a particular literal in Java representing a null
value. This value refers to no object. Java
throws NullPointerException. Null often describe the
uninitialized state in the program. It is an error to attempt to
dereference the null value.
1. Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
, Interfaces
, and Arrays
Next
char '\u0000'
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
1. float f1 = 234.5f
1. double d1 = 12.3
Operators in Java
Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Assignment Operator.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
o negating an expression
Java Comments
Comments can be used to explain Java code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes ( //).
Any text between // and the end of the line is ignored by Java (will not be
executed).
Example
// This is a comment
System.out.println("Hello World");
This example uses a single-line comment at the end of a line of code:
Example
System.out.println("Hello World"); // This is a comment
This example uses a multi-line comment (a comment block) to explain the code:
Example
/* The code below will print the words Hello World
System.out.println("Hello World");
Loops in Java
Looping in programming languages is a feature which facilitates the
execution of a set of instructions/functions repeatedly while some
condition evaluates to true. Java provides three ways for executing the
loops. While all the ways provide similar basic functionality, they differ
in their syntax and condition checking time.
while loop: A while loop is a control flow statement that allows
code to be executed repeatedly based on a given Boolean condition.
The while loop can be thought of as a repeating if statement.
Syntax :
Syntax:
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
Flowchart:
Syntax:
do
{
statements..
}
while (condition);
Flowchart:
for (int i = 5; i != 0; i -= 2)
System.out.println(i);
int x = 5;
// is not provided.
while (x == 5)
Java
import java.util.ArrayList;
ar.add(i);
}
Output:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap
space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at article.Integer1.main(Integer1.java:9)
Syntax
if (condition) {
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.
In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:
Example
if (20 > 18) {
}
The else Statement
Use the else statement to specify a block of code to be executed if the condition
is false.
Syntax
if (condition) {
} else {
Example
int time = 20;
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
Example explained
In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".
The else if Statement
Use the else if statement to specify a new condition if the first condition
is false.
Syntax
if (condition1) {
} else if (condition2) {
} else {
Example
int time = 22;
System.out.println("Good morning.");
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
However, if the time was 14, our program would print "Good day."
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
A break can save a lot of execution time because it "ignores" the execution of all
the rest of the code in the switch block.
Example
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
Note that if the default statement is used as the last statement in a switch
block, it does not need a break.
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code
more readable.
Syntax
while (condition) {
In the example below, the code in the loop will run, over and over again, as long
as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
Note: Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
Syntax
do {
while (condition);
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:
Example
int i = 0;
do {
System.out.println(i);
i++;
}
Syntax
for (statement 1; statement 2; statement 3) {
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Java For Each Loop
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:
Syntax
for (type variableName : arrayName) {
The following example outputs all elements in the cars array, using a "for-each"
loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(i);
Java Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
System.out.println(i);
Java Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
System.out.println(i);
Type casting
Convert a value from one data type to another data type is known as type
casting.
1. byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean
is not done automatically. Also, the char and Boolean data types are not
compatible with each other. Let's see an example.
WideningTypeCastingExample.java
1. public class WideningTypeCastingExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 7;
6. //automatically converts the integer type into long type
7. long y = x;
8. //automatically converts the long type into float type
9. float z = y;
10. System.out.println("Before conversion, int value "+x);
11. System.out.println("After conversion, long value "+y);
12. System.out.println("After conversion, float value "+z);
13. }
14. }
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
In the above example, we have taken a variable x and converted it into a
long type. After that, the long type is converted into the float type.
Narrowing Type Casting
Converting a higher data type into a lower one is called narrowing type
casting. It is also known as explicit conversion or casting up. It is done
manually by the programmer. If we do not perform casting then the compiler
reports a compile-time error.
1. double -> float -> long -> int -> char -> short -> byte
Let's see an example of narrowing type casting.
In the following example, we have performed the narrowing type casting two
times. First, we have converted the double type into long data type after that
long data type is converted into int type.
NarrowingTypeCastingExample.java
1. public class NarrowingTypeCastingExample
2. {
3. public static void main(String args[])
4. {
5. double d = 166.66;
6. //converting double data type into long data type
7. long l = (long)d;
8. //converting long data type into int data type
9. int i = (int)l;
10. System.out.println("Before conversion: "+d);
11. //fractional part lost
12. System.out.println("After conversion into long type: "+l);
13. //fractional part lost
14. System.out.println("After conversion into int type: "+i);
15. }
16. }
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
2.Object
4.Pillars of OOPs
•Abstraction
•Encapsulation
•Inheritance
•Polymorphism
•Compile-time polymorphism
•Runtime polymorphism
capitalized by convention.
3.Superclass (if any): The name of the class’s parent (superclass), if
specific task and return the result to the caller. A method can perform
some specific task without returning anything. Methods allow us
to reuse the code without retyping it, which is why they are
considered time savers. In Java, every method must be part of some
class, which is different from languages like C, C++, and Python.
Let us now discuss the 4 pillars of OOPs:
Pillar 1: Abstraction
Data Abstraction is the property by virtue of which only the essential
details are displayed to the user. The trivial or non-essential units are
not displayed to the user. Ex: A car is viewed as a car rather than its
individual components.
Data Abstraction may also be defined as the process of identifying only
the required characteristics of an object, ignoring the irrelevant details.
The properties and behaviors of an object differentiate it from other
objects of similar type and also help in classifying/grouping the object.
Consider a real-life example of a man driving a car. The man only knows
that pressing the accelerators will increase the car speed or applying
brakes will stop the car, but he does not know how on pressing the
accelerator, the speed is actually increasing. He does not know about
the inner mechanism of the car or the implementation of the
accelerators, brakes etc. in the car. This is what abstraction is.
In Java, abstraction is achieved by interfaces and abstract classes.
We can achieve 100% abstraction using interfaces.
Pillar 2: Encapsulation
It is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together the code and the data it manipulates.
Another way to think about encapsulation is that it is a protective shield
that prevents the data from being accessed by the code outside this
shield.
•Technically, in encapsulation, the variables or the data in a class is
hidden from any other class and can be accessed only through any
member function of the class in which they are declared.
•In encapsulation, the data in a class is hidden from other classes,
when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Pillar 4: Polymorphism
It refers to the ability of object-oriented programming languages to
differentiate between entities with the same name efficiently. This is
done by Java with the help of the signature and declaration of these
entities.
2. Overriding
Example
• Java
// Java program to Demonstrate
Polymorphism
// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum().
// This sum takes two double
parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20,
30));
System.out.println(s.sum(10.5,
20.5));
}
}
Output:
30
60
31.0
Class
l
1. Class keyword: class keyword is used to create a class.
a2. Class name: The name should begin with an initial letter (capitalized
y by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any,
Object
properties of an object.
2. Behavior: It is represented by methods of an object. It also reflects
As we declare variables like (type name;). This notifies the compiler that
we will use the name to refer to data whose type is type. With a
primitive variable, this declaration also reserves the proper amount of
memory for the variable. So for reference variable, the type must be
strictly a concrete class name. In general, we can’t create objects of an
abstract class or an interface.
Dog tuffy;
Initializing an object
• Java
// Class Declaration
// method 1
public String getName()
{
return name;
}
// method 2
public String getBreed()
{
return breed;
}
// method 3
public int getAge()
{
return age;
}
// method 4
public String getColor()
{
return color;
}
Output:
Hi my name is tuffy.
Note : All classes have at least one constructor. If a class does not
explicitly declare any, the Java compiler automatically provides a no-
argument constructor, also called the default constructor. This default
constructor calls the class parent’s no-argument constructor (as it
contains only one statement i.e super();), or the Object class constructor
if the class has no other parent (as the Object class is the parent of all
classes either directly or indirectly).
Ways to create an object of a class
There are four ways to create objects in java. Strictly speaking there is
only one way(by using new keyword), and the rest internally
use new keyword.
• Using new keyword: It is the most common and general way to create
Test t2 = (Test)t1.clone();
Anonymous objects
Anonymous objects are objects that are instantiated but are not stored
in a reference variable.
System.out.println("Hello World!");
});
Now, The space in the heap Memory is created but the question is how
to access that space?.
Then, We create a Pointing element or simply called Reference
variable which simply points out the Object(the created space in a Heap
Memory).
Example:
• Java
// Java program to demonstrate reference
// variable in java
import java.io.*;
class Demo {
int x = 10;
int display()
{
System.out.println("x = " + x);
return 0;
}
}
class Main {
public static void main(String[] args)
{
Demo D1 = new Demo(); // point 1
System.out.println(D1); // point 2
System.out.println(D1.display()); //
point 3
}
}
Output
Demo@214c265e
x = 10
3. At this point we will access the methods display() of the class demo
using our custom reference variable that we created.
• Java
import java.io.*;
class Demo {
int x = 10;
int display()
{
System.out.println("x = " + x);
return 0;
}
}
class Main {
public static void main(String[] args)
{
// create instance
Demo D1 = new Demo();
// accessing instance(object)
variable
System.out.println(D1.x);
// point 3
// accessing instance(object)
method
D1.display();
}
}
Output
10
x = 10
• Java
import java.io.*;
class Demo {
int x = 10;
int display()
{
System.out.println("x = " +
x);
return 0;
}
}
class Main {
public static void main(String[]
args)
{
// create instances
Demo D1 = new Demo();
• Java
// Pointing to same instance memory
import java.io.*;
class Demo {
int x = 10;
int display()
{
System.out.println("x = " + x);
return 0;
}
}
class Main {
public static void main(String[]
args)
{
// create instance
Demo D1 = new Demo();
Demo Q1 = M1;
System.out.println(G1.x); //
Point 1
System.out.println(D1.x); //
Point 2
}
}
Output
25
25
Note:
Here we pass G1 and Q1 reference variable point out the same
object respectively. Secondly At Point 1 we try to get the value
of the object with G1 reference variable which shows it
as 25 and At Point 2 we try to get the value of an object with
D1 reference variable which shows it as 25 as well. This will
prove that the modification in the object can be done by using
any reference variable but the condition is it should hold the
same reference.
Constructors in Java
• Diffic
Java constructors or constructors in Java is a terminology been used to
construct something in our programs. A constructor in Java is a special
method that is used to initialize objects. The constructor is called when
an object of a class is created. It can be used to set initial values for
object attributes.
class Ducat{
.......
// A Constructor
new Ducat() {
.......
• Java
import java.io.*;
class Ducat {
Ducat() { super(); }
public static void main(String[]
args)
{
Ducat geek = new Ducat();
}
}
If you think your class is not a subclass it actually is, every class in java
is the subclass of a class object even if you don’t say extends object in
your class definition.
Need of Constructor
Think of a Box. If we talk about a box class then it will have some class
variables (say length, breadth, and height). But when it comes to
creating its object(i.e Box will now exist in the computer’s memory),
then can a box be there with no value defined for its dimensions. The
answer is no.
So constructors are used to assign values to the class variables at the
time of object creation, either explicitly done by the programmer or by
Java itself (default constructor).
• No-argument constructor
• Parameterized Constructor
1. No-argument constructor: A constructor that has no parameter is
known as the default constructor. If we don’t define a constructor in a
class, then the compiler creates a default constructor(with no
arguments) for the class. And if we write a constructor with arguments
or no arguments then the compiler does not create a default
constructor.
Note: Default constructor provides the default values to the
object like 0, null, etc. depending on the type.
Example:
• Java
// Java Program to illustrate calling a
// no-argument constructor
import java.io.*;
class Ducat {
int num;
String name;
class GFG {
public static void main(String[] args)
{
// this would invoke default constructor.
Ducat geek1 = new Ducat();
null
• Java
// Java Program to Illustrate Working of
// Parameterized Constructor
// Class 1
class Ducat {
// data members of the class.
String name;
int id;
// Class 2
class GFG {
// main driver method
public static void main(String[] args)
{
// This would invoke the parameterized
constructor.
Ducat geek1 = new Ducat("adam", 1);
System.out.println("DucatName :" + geek1.name
+ " and DucatId :" +
geek1.id);
}
}
Output
DucatName :adam and DucatId :1
Now the most important topic that comes into play is the strong
incorporation of OOPS with constructors known as constructor
overloading. JustLike methods, we can overload constructors for creating
objects in different ways. Compiler differentiates constructors on the
basis of numbers of parameters, types of the parameters, and order of
the parameters.
Example:
• Java
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.
import java.io.*;
class Ducat
{
// constructor with one argument
Ducat(String name)
{
System.out.println("Constructor with one " +
"argument - String : " + name);
}
class GFG
{
public static void main(String[] args)
{
// Creating the objects of the class named 'Ducat'
// by passing different arguments
Output
Constructor with one argument - String : Shikhar
When you create a new object of the class you create an instance. Consider,
if you have a STUDENT class, then
1class Student
2{
3String studentName;
4int studentScore;
5}
And if you create two STUDENT objects like,
Now that you have understood the meaning of Instance variables, let’s move
a step forward.
I will enlist the features of instance variables, which would help you in using
them in a java code with ease.
1package Ducat;
2
3import java.util.Scanner;
4
5public class Student
6{
7
8public String name;
9
1private int marks;
0
1public Student (String stuName) {
1name = stuName;
1}
2public void setMarks(int stuMar) {
1marks = stuMar;
3}
1
4// This method prints the student details.
1public void printStu() {
5System.out.println("Name: " + name );
1System.out.println("Marks:" + marks);
6}
1
7public static void main(String args[]) {
1Student StuOne = new Student("Ross");
8Student StuTwo = new Student("Rachel");
1Student StuThree = new Student("Phoebe");
9
2
StuOne.setMarks(98);
0
StuTwo.setMarks(89);
2
StuThree.setMarks(90);
1
2
StuOne.printStu();
2
StuTwo.printStu();
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0StuThree.printStu();
3
1}
3}
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
OUTPUT:
Name: Ross
Marks:98
Name: Rachel
Marks:89
Name: Phoebe
Marks:90
Explanation:
In the above code, as you can see I have created three instance variables,
namely, ‘StuOne’, ’StuTwo’, ’StuThree’. Likewise, you can create as
many variables as you need depending upon your requirement. Now as we
move further accumulating facts about instance variable, let me also
elaborate to you the differences between an instance variable and a class
variable!
•Class variables also known as static variables are declared with the
static keyword in a class, but outside a method, constructor or a block.
•There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
•Static variables are rarely used other than being declared as
constants. Constants are variables that are declared as public/private,
final, and static. Constant variables never change from their initial
value.
•Static variables are stored in the static memory. It is rare to use static
variables other than declared final and used as either public or private
constants.
•Static variables are created when the program starts and destroyed
when the program stops.
•Visibility is similar to instance variables. However, most static
variables are declared public since they must be available for users of
the class.
•Default values are same as instance variables. For numbers, the
default value is 0; for Booleans, it is false; and for object references, it
is null. Values can be assigned during the declaration or within the
constructor. Additionally, values can be assigned in special static
initializer blocks.
•Static variables can be accessed by calling with the class name
ClassName.VariableName.
•When declaring class variables as public static final, then variable
names (constants) are all in upper case. If the static variables are not
public and final, the naming syntax is the same as instance and local
variables.
Example
Online Demo
import java.io.*;,
public class Employee {
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
Output
This will produce the following result −
Note − If the variables are accessed from an outside class, the constant
should be accessed as Employee.DEPARTMENT
Difference between static and non-
static method in Java
• Difficu
A static method is a method that belongs to a class, but it does not
belong to an instance of that class and this method can be called
without the instance or object of that class. Every method in java
defaults to a non-static method without static keyword preceding
it. Non-static methods can access any static method and static variable,
without creating an instance of the object. Let us clarify the differences
Below are the various important differences among these pointers as
follows:
Example
• Java
// Class 1
// Helper class
class Helper {
// Static method
public static int sum(int a, int b)
{
// Simply returning the sum
return a + b;
}
}
// Class 2
class GFG {
Example
• Java
// Class 1
// Helper class
class Helper {
// Non-static method
public int sum(int a, int b)
{
// Returning sum of numbers
return a + b;
}
}
// Class 2
// Main class
class GFG {
{ }
// calling
GFG.geek();
{ }
}
// creating object
g.geek();
// calling
• Java
// Override of static method
class Parent {
// static method
static void show()
{
System.out.println("Parent");
}
}
class GFG {
public static void main(String[]
args)
{
Parent p = new Parent();
// calling Parent's show()
p.show();
// cannot override Parent's
show()
}
}
Output:
java:15: error: show() in Child cannot override show() in Parent
void show()
• Java
class Parent {
void show()
{
System.out.println("Parent");
}
}
class GFG {
public static void main(String[]
args)
{
Parent p = new Parent();
// calling Parent's show()
p.show();
Child