0% found this document useful (0 votes)
7 views93 pages

Java_oops

Uploaded by

rishabhs604
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
Download as odt, pdf, or txt
0% found this document useful (0 votes)
7 views93 pages

Java_oops

Uploaded by

rishabhs604
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1/ 93

Java language fundamentals

Identifiers:

In programming languages, identifiers are used for identification


purposes. In Java, an identifier can be a class name, method name,
variable name, or label. For example :

public class Test


{
public static void main(String[] args)
{
int a = 20;

}
}

In the above java code, we have 5 identifiers namely :

 Test : class name.


 main : method name.
 String : predefined class name.
 args : variable name.
 a : variable name.

Rules for defining Java Identifiers


There are certain rules for defining a valid java identifier. These rules
must be followed, otherwise we get compile-time error. These rules are
also valid for other languages like C,C++.

 The only allowed characters for identifiers are all alphanumeric


characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘
(underscore).For example “geek@” is not a valid java identifier as it
contain ‘@’ special character.
 Identifiers should not start with digits([0-9]). For example
“123geeks” is a not a valid java identifier.
 Java identifiers are case-sensitive.
 There is no limit on the length of the identifier but it is advisable
to use an optimum length of 4 – 15 letters only.
 Reserved Words can’t be used as an identifier. For example “int
while = 20;” is an invalid statement as while is a reserved word.
There are 53 reserved words in Java.

Examples of valid 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.

List of Java Keywords


A list of Java keywords or reserved words are given below:
1. abstract

: Java abstract keyword is used to declare an abstract class. An abstract class


can provide the implementation of the interface. It can have abstract and
non-abstract methods.

2. boolean:

Java boolean keyword is used to declare a variable as a boolean type. It can


hold True and False values only.

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

: Java catch keyword is used to catch the exceptions generated by try


statements. It must be used after the try block only.

7. char

: Java char keyword is used to declare a variable that can hold unsigned 16-
bit Unicode characters

8. class

: Java class keyword is used to declare a 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

: Java do keyword is used in the control statement to declare a loop. It can


iterate a part of the program several times.

12. double

: Java double keyword is used to declare a variable that can hold 64-bit
floating-point number.

13. else

: Java else keyword is used to indicate the alternative branches in an if


statement.
14. enum

: Java enum keyword is used to define a fixed set of constants. Enum


constructors are always private or default.

15. extends

: Java extends keyword is used to indicate that a class is derived from


another class or interface.

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

: Java finally keyword indicates a block of code in a try-catch structure. This


block is always executed whether an exception is handled or not.

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

: Java implements keyword is used to implement an interface.

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

: Java interface keyword is used to declare an interface. It can have only


abstract methods.

26. long

: Java long keyword is used to declare a variable that can hold a 64-bit
integer.

27.native: Java native keyword is used to specify that a method is implemented


in native code using JNI (Java Native Interface).

28. new

: Java new keyword is used to create new objects.

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

: Java private keyword is an access modifier. It is used to indicate that a


method or variable may be accessed only in the class in which it is declared.

32. protected

: Java protected keyword is an access modifier. It can be accessible within the


package and outside the package but through inheritance only. It can't be
applied with the class.

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

: Java static keyword is used to indicate that a variable or method is a class


method. The static keyword in Java is mainly used for memory management.

37. strictfp

: Java strictfp is used to restrict the floating-point calculations to ensure


portability.

38. super

: Java super keyword is a reference variable that is used to refer to parent


class objects. It can be used to invoke the immediate parent class method.

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

: Java synchronized keyword is used to specify the critical sections or


methods in multithreaded code.

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

: The Java throws keyword is used to declare an exception. Checked


exceptions can be propagated with throws.

44. transient

: Java transient keyword is used in serialization. If you define any data


member as transient, it will not be serialized.

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

: Java volatile keyword is used to indicate that a variable may change


asynchronously.

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.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by


double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -
123
 float - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 boolean - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:

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":

String name = "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:

int myNum = 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:

int myNum = 15;

myNum = 20; // myNum is now 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;

myNum = 20; // will generate an error: cannot assign a value to


a final variable

Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;

float myFloatNum = 5.99f;

char myLetter = 'D';

boolean myBool = true;

String myText = "Hello";

Literal in Java

is a synthetic representation of boolean, numeric, character,


or string data. It is a means of expressing particular values in
the program, such as an integer variable named ‘’/count is
assigned an integer value in the following statement.
int count = 0;

A literal ‘0’ represents the value zero.


Thus, a constant value assigned to the variable can be
referred to as literal.
Literals in Java can be classified into six types, as below:
1. Integral Literals
2. Floating-point Literals
3. Char Literals
4. String Literals
5. Boolean Literals
6. Null Literals
Our learners also read: Free java course!
These literals are again specified in different sub-types, let us
see one by one in the article.

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.

Literals in Java help build basics in programming. Every Java


programmer must be aware of this fundamental and essential
concept that assigns values to the program’s variables. As
null literal is not much used, commonly only the first five
literal types are applied. It is necessary to follow the rules
and maintain the correct syntax while using any literal in
Java.

Data Types in Java


Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.

2. Non-primitive data types: The non-primitive data types include Classes

, Interfaces

, and Arrays

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java language
.

Java is a statically-typed programming language. It means, all variables


must be declared before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:


3.3K

Lumia 735 Hands-On

Next

o boolean data type

o byte data type

o char data type

o short data type

o int data type

o long data type

o float data type

o double data type

Data Type Default Value


boolean false

char '\u0000'
byte 0

short 0

int 0

long 0L

float 0.0f

double 0.0d

Boolean Data Type


The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.
Example:

1. Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed
two's complement integer. Its value-range lies between -128 to 127
(inclusive). Its minimum value is -128 and maximum value is 127. Its default
value is 0.
The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4 times
smaller than an integer. It can also be used in place of "int" data type.
Example:

1. byte a = 10, byte b = -20


Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive). Its minimum value is -
32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.
Example:

1. short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-
range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values
unless if there is no problem about memory.
Example:

1. int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies
between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used
when you need a range of values more than those provided by int.
Example:
1. long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its
value range is unlimited. It is recommended to use a float (instead of double)
if you need to save memory in large arrays of floating point numbers. The
float data type should never be used for precise values, such as currency. Its
default value is 0.0F.
Example:

1. float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its
value range is unlimited. The double data type is generally used for decimal
values just like float. The double data type also should never be used for
precise values, such as currency. Its default value is 0.0d.
Example:

1. double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is
used to store characters.
Example:
1. char letterA = 'A'

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 Ternary Operator and

o Assignment Operator.

Java Operator Precedence


Operator Type Category Precedence
Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^
bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<=

Java Unary Operator


The Java unary operators require only one operand. Unary operators are
used to perform various operations i.e.:
Skip Ad

o incrementing/decrementing a value by one

o negating an expression

o inverting the value of a boolean

Java Unary Operator Example: ++ and --


1. public class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}
Output:
10
12
12
10

Java Unary Operator Example 2: ++ and --


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}
Output:
22
21

Java Unary Operator Example: ~ and !


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0
)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10. System.out.println(!d);//true
11. }}
Output:
-11
9
false
true

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.
Java Arithmetic Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10. }}
Output:
15
5
50
2
0

Java Arithmetic Operator Example: Expression


1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/2);
4. }}
Output:
21

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the
left side of a specified number of times.
Java Left Shift Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}
Output:
40
80
80
240

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left
operand to right by the number of bits specified by the right operand.
Java Right Shift Operator Example
1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}
Output:
2
5
2

Java Shift Operator Example: >> vs >>>


1. public class OperatorExample{
2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}
Output:
5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &


The logical && operator doesn't check the second condition if the first
condition is false. It checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition
is true or false.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}
Output:
false
false

Java AND Operator Example: Logical && vs Bitwise &


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10. }}
Output:
false
10
false
11

Java OR Operator Example: Logical || and Bitwise |


The logical || operator doesn't check the second condition if the first
condition is true. It checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition
is true or false.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}
Output:
true
true
true
10
true
11

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else
statement and used a lot in Java programming. It is the only conditional
operator which takes three operands.
Java Ternary Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
2
Another Example:
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
5

Java Assignment Operator


Java assignment operator is one of the most common operators. It is used to
assign the value on its right to the operand on its left.
Java Assignment Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}
Output:
14
16

Java Assignment Operator Example


1. public class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}
Output:
13
9
18
9

Java Assignment Operator Example: Adding short


1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}
Output:
Compile time error
After type cast:
1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}
Output:
20

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).

This example uses a single-line comment before a line of code:

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

Java Multi-line Comments


Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the code:

Example
/* The code below will print the words Hello World

to the screen, and it is amazing */

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 :

while (boolean condition)


{
loop statements...
}
 Flowchart:

 While loop starts with the checking of condition. If it


evaluated to true, then the loop body statements are
executed otherwise first statement following the loop is
executed. For this reason it is also called Entry control
loop
 Once the condition is evaluated to true, the statements in
the loop body are executed. Normally the statements
contain an update value for the variable being processed for
the next iteration.
 When the condition becomes false, the loop terminates
which marks the end of its life cycle.
 for loop: for loop provides a concise way of writing the loop
structure. Unlike a while loop, a for statement consumes the
initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.

Syntax:
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
 Flowchart:

 Initialization condition: Here, we initialize the variable in


use. It marks the start of a for loop. An already declared
variable can be used or a variable can be declared, local to
loop only.
 Testing Condition: It is used for testing the exit condition
for a loop. It must return a boolean value. It is also an Entry
Control Loop as the condition is checked prior to the
execution of the loop statements.
 Statement execution: Once the condition is evaluated to
true, the statements in the loop body are executed.
 Increment/ Decrement: It is used for updating the
variable for next iteration.
 Loop termination:When the condition becomes false, the
loop terminates marking the end of its life cycle.
 do while: do while loop is similar to while loop with only
difference that it checks for condition after executing the
statements, and therefore is an example of Exit Control Loop.

Syntax:
do
{
statements..
}
while (condition);
 Flowchart:

do while loop starts with the execution of the statement(s).


There is no checking of any condition for the first time.
 After the execution of the statements, and update of the
variable value, the condition is checked for true or false
value. If it is evaluated to true, next iteration of loop starts.
 When the condition becomes false, the loop terminates
which marks the end of its life cycle.
 It is important to note that the do-while loop will execute its
statements atleast once before any condition is checked,
and therefore is an example of exit control loop.
Pitfalls of Loops
 Infinite loop: One of the most common mistakes while
implementing any sort of looping is that it may not ever exit, that is
the loop runs for infinite time. This happens when the condition fails
for some reason. Examples:
 Java

//Java program to illustrate various pitfalls.

public class LooppitfallsDemo

public static void main(String[] args)

// infinite loop because condition is not apt

// condition should have been i>0.

for (int i = 5; i != 0; i -= 2)

System.out.println(i);

int x = 5;

// infinite loop because update statement

// is not provided.

while (x == 5)

System.out.println("In the loop");


}

Another pitfall is that you might be adding something into you


collection object through loop and you can run out of memory. If you
try and execute the below program, after some time, out of memory
exception will be thrown.

 Java

//Java program for out of memory exception.

import java.util.ArrayList;

public class Integer1

public static void main(String[] args)

ArrayList<Integer> ar = new ArrayList<>();

for (int i = 0; i < Integer.MAX_VALUE; i++)

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)

Java Conditions and If Statements


The if Statement
Use the if statement to specify a block of Java code to be executed if a
condition is true.

Syntax
if (condition) {

// block of code to be executed if the condition is true

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) {

System.out.println("20 is greater than 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) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

Example
int time = 20;

if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

// Outputs "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) {

// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is false and


condition2 is true

} else {

// block of code to be executed if the condition1 is false and


condition2 is false

Example
int time = 22;

if (time < 10) {

System.out.println("Good morning.");

} else if (time < 20) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

// Outputs "Good evening."


Example explained
In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also false, so
we move on to the else condition since condition1 and condition2 is both false -
and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Java Switch Statements


Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later
in this chapter

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)

The break Keyword


When Java reaches a break keyword, it breaks out of the switch block.

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.

The default Keyword


The default keyword specifies some code to run if there is no case match:

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:

System.out.println("Looking forward to the Weekend");


}

// Outputs "Looking forward to the Weekend"

Note that if the default statement is used as the last statement in a switch
block, it does not need a break.

Java While Loop

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.

Java While Loop


The while loop loops through a block of code as long as a specified condition
is true:

Syntax
while (condition) {

// code block to be executed

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!

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.

Syntax
do {

// code block to be executed

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++;
}

while (i < 5);

Java For Loop

Java For Loop


When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

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) {

// code block to be executed

The following example outputs all elements in the cars array, using a "for-each"
loop:

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (String i : cars) {

System.out.println(i);

Java Break and Continue

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.

The break statement can also be used to jump out of a loop.


This example stops the loop when i is equal to 4:

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.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {

if (i == 4) {

continue;

System.out.println(i);

Type Casting in Java


In Java, type casting is a method or process that converts a data type into
another data type in both ways manually and automatically. The automatic
conversion is done by the compiler and manual conversion performed by the
programmer. In this section, we will discuss type casting and its types with
proper examples.

Type casting
Convert a value from one data type to another data type is known as type
casting.

Types of Type Casting


There are two types of type casting:
o Widening Type Casting

o Narrowing Type Casting

Widening Type Casting


Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down. It is done
automatically. It is safe because there is no chance to lose data. It takes
place when:
o Both data types must be compatible with each other.

o The target type must be larger than the source type.

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

Object Oriented Programming (OOPs) Concept in Java

OOP stands for Object-Oriented Programming.


Procedural programming is about writing procedures or methods that perform
operations on the data, while object-oriented programming is about creating
objects that contain both data and methods.
Object-oriented programming has several advantages over procedural
programming:
•OOP is faster and easier to execute
•OOP provides a clear structure for the programs
•OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
•OOP makes it possible to create full reusable applications with less code
and shorter development time
The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of
code. You should extract out the codes that are common for the application, and
place them at a single place and reuse them instead of repeating it.
Java - What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented programming.

So, a class is a template for objects, and an object is an instance of a class.


When the individual objects are created, they inherit all the variables and
methods from the class.
OOPS concepts are as follows:
1.Class

2.Object

3.Method and method passing

4.Pillars of OOPs
•Abstraction

•Encapsulation

•Inheritance

•Polymorphism

•Compile-time polymorphism
•Runtime polymorphism

A class is a user-defined blueprint or prototype from which objects are


created. It represents the set of properties or methods that are common
to all objects of one type. Using classes, you can create multiple objects
with the same behavior instead of writing their code multiple times. This
includes classes for objects occurring more than once in your code. In
general, class declarations can include these components in order:
1.Modifiers: A class can be public or have default access (Refer

to this for details).


2.Class name: The class name should begin with the initial letter

capitalized by convention.
3.Superclass (if any): The name of the class’s parent (superclass), if

any, preceded by the keyword extends. A class can only extend


(subclass) one parent.
4.Interfaces (if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
5.Body: The class body is surrounded by braces, { }.

An object is a basic unit of Object-Oriented Programming that represents


real-life entities. A typical Java program creates many objects, which as
you know, interact by invoking methods. The objects are what perform
your code, they are the part of your code visible to the viewer/user. An
object mainly consists of:
1.State: It is represented by the attributes of an object. It also reflects

the properties of an object.


2.Behavior: It is represented by the methods of an object. It also

reflects the response of an object to other objects.


3.Identity: It is a unique name given to an object that enables it to

interact with other objects.


4.Method: A method is a collection of statements that perform some

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,

which is similar to what data-hiding does. So, the terms


“encapsulation” and “data-hiding” are used interchangeably.
•Encapsulation can be achieved by declaring all the variables in a
class as private and writing public methods in the class to set and get
the values of the variables.
Pillar 3: Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming).
It is the mechanism in Java by which one class is allowed to inherit the
features (fields and methods) of another class.
Let us discuss some frequently used important terminologies:
•Superclass: The class whose features are inherited is known as

superclass (also known as base or parent class).


•Subclass: The class that inherits the other class is known as subclass

(also known as derived or extended or child class). The subclass can


add its own fields and methods in addition to the superclass fields
and methods.
•Reusability: Inheritance supports the concept of “reusability”, i.e.

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.

Note: Polymorphism in Java is mainly of 2 types:


1. Overloading

2. Overriding

Example
• Java
// Java program to Demonstrate
Polymorphism

// This class will contain


// 3 methods with same name,
// yet the program will
// compile & run successfully
public class Sum {

// 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

Classes and Objects in Java

Classes and Objects are basic concepts of Object Oriented Programming


that revolve around real life entities.

Class

A class is a user defined blueprint or prototype from which objects are


created. It represents the set of properties or methods that are common
to all objects of one type. In general, class declarations can include
these components, in order:
P Modifiers: A class can be public or has default access

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,

V preceded by the keyword extends. A class can only extend (subclass)


one parent.
i4. Interfaces(if any): A comma-separated list of interfaces implemented
d by the class, if any, preceded by the keyword implements. A class
e can implement more than one interface.
o5. Body: The class body is surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables
that provide the state of the class and its objects, and methods are used
to implement the behavior of the class and its objects.
There are various types of classes that are used in real time applications
such as nested classes, anonymous classes, lambda expressions.

Object

It is a basic unit of Object-Oriented Programming and represents real life


entities. A typical Java program creates many objects, which as you
know, interact by invoking methods. An object consists of :

1. State: It is represented by attributes of an object. It also reflects the

properties of an object.
2. Behavior: It is represented by methods of an object. It also reflects

the response of an object with other objects.


3. Identity: It gives a unique name to an object and enables one object

to interact with other objects.


Example of an object: dog

Objects correspond to things found in the real world. For example, a


graphics program may have objects such as “circle”, “square”, and
“menu”. An online shopping system might have objects such as
“shopping cart”, “customer”, and “product”.

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated.


All the instances share the attributes and the behavior of the class. But
the values of those attributes, i.e. the state are unique for each object. A
single class may have any number of instances.
Example:

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;

If we declare a reference variable(tuffy) like this, its value will be


undetermined(null) until an object is actually created and assigned to it.
Simply declaring a reference variable does not create an object.

Initializing an object

The new operator instantiates a class by allocating memory for a new


object and returning a reference to that memory. The new operator also
invokes the class constructor.

• Java
// Class Declaration

public class Dog


{
// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

// 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.

My breed,age and color are papillon,5,white

• This class contains a single constructor. We can recognize a


constructor because its declaration uses the same name as the class
and it has no return type. The Java compiler differentiates the
constructors based on the number and the type of the arguments.
The constructor in the Dog class takes four arguments. The following
statement provides “tuffy”,”papillon”,5,”white” as values for those
arguments:
Dog tuffy = new Dog("tuffy","papillon",5, "white");

• The result of executing this statement can be illustrated as :

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

an object in java. Example:


// creating object of class Test

Test t = new Test();

• Using Class.forName(String className) method: There is a pre-

defined class in java.lang package with name Class. The


forName(String className) method returns the Class object
associated with the class with the given string name. We have to give
a fully qualified name for a class. On calling new Instance() method
on this Class object returns new instance of the class with the given
string name.
// creating object of public class Test

// consider class Test present in com.p1 package


Test obj = (Test)Class.forName("com.p1.Test").newInstance();

• Using clone() method: clone() method is present in Object class. It

creates and returns a copy of the object.

// creating object of class Test

Test t1 = new Test();


// creating clone of above object

Test t2 = (Test)t1.clone();

• Deserialization: De-serialization is a technique of reading an object

from the saved state in a file. Refer Serialization/De-Serialization


in java

FileInputStream file = new FileInputStream(filename);

ObjectInputStream in = new ObjectInputStream(file);

Object obj = in.readObject();

Creating multiple objects by one type only (A good practice)

• In real-time, we need different objects of a class in different methods.

Creating a number of references for storing them is not a good


practice and therefore we declare a static reference variable and use
it whenever required. In this case, the wastage of memory is less. The
objects that are not referenced anymore will be destroyed
by Garbage Collector of java. Example:

Test test = new Test();

test = new Test();

• In inheritance system, we use parent class reference variable to store


a sub-class object. In this case, we can switch into different subclass
objects using same referenced variable. Example:
class Animal {}
class Dog extends Animal {}

class Cat extends Animal {}

public class Test

// using Dog object

Animal obj = new Dog();

// using Cat object

obj = new Cat();

Anonymous objects

Anonymous objects are objects that are instantiated but are not stored
in a reference variable.

• They are used for immediate method calling.


• They will be destroyed after method calling.
• They are widely used in different libraries. For example, in AWT
libraries, they are used to perform some action on capturing an
event(eg a key press).
• In the example below, when a key is button(referred by the btn) is
pressed, we are simply creating anonymous object of EventHandler
class for just calling handle method.
btn.setOnAction(new EventHandler()
{

public void handle(ActionEvent event)

System.out.println("Hello World!");

});

Reference Variable in Java


• Difficu
Before We Started with the Reference variable we should know about
the following facts.

1. When we create an object (instance) of class then space is reserved


in heap memory. Let’s understand with the help of an example.
Demo D1 = new Demo();

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).

Understanding Reference variable


1. Reference variable is used to point object/values.
2. Classes, interfaces, arrays, enumerations, and, annotations are
reference types in Java. Reference variables hold the objects/values of
reference types in Java.
3. Reference variable can also store null value. By default, if no object is
passed to a reference variable then it will store a null value.
4. You can access object members using a reference variable
using dot syntax.
<reference variable name >.<instance variable_name /
method_name>

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

Let us see what is actually happening step by step.


1. When we create an object of demo class new DEMO();, the default
constructor is called and returns a reference of the object, and simply
this reference will be stored to the reference variable D1 (As we know
that associativity is Right-hand side to left-hand side).

2. The value of a reference variable is a reference. When we attempt to


print the value of a reference variable, the output contains the type of
the variable and the hash code created for it by Java: the
string Demo@214c265e tells us that the given variable is of type Name
and its hexadecimal format of hash code is 214c265e.

3. At this point we will access the methods display() of the class demo
using our custom reference variable that we created.

BINDING UP : The constructor call returns a value that is a


reference to the newly-created object. The equality sign tells
the program that the value of the right-hand side expression is
to be copied as the value of the variable on the left-hand side.
The reference to the newly-created object, returned by the
constructor call, is copied as the value of the variable.

• 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

// Accessing instance methods

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();

Demo M1 = new Demo();

Demo Q1 = 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();

// point to same reference


Demo G1 = D1;

Demo M1 = new Demo();

Demo Q1 = M1;

// updating the value of x using


G!
// reference variable
G1.x = 25;

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.

In Java, a constructor is a block of codes similar to the method. It is


called when an instance of the class is created. At the time of calling the
constructor, memory for the object is allocated in the memory. It is a
special type of method which is used to initialize the object. Every time
an object is created using the new() keyword, at least one constructo

Note: It is not necessary to write a constructor for a class. It is because java

compiler creates a default constructor if your class doesn’t have any.


How Constructors are Different From Methods in Java?
• Constructors must have the same name as the class within which it is
defined while it is not necessary for the method in Java.
• Constructors do not return any type while method(s) have the return

type or void if does not return any value.


• Constructors are called only once at the time of Object creation while
method(s) can be called any number of times.
Now let us come up with the syntax for the constructor being invoked at
the time of object or instance creation.

class Ducat{

.......

// A Constructor

new Ducat() {

.......

// We can create an object of the above class

// using the below statement. This statement


// calls above constructor.

Ducat obj = new Ducat();

The first line of a constructor is a call to super() or this(), (a call to a


constructor of a super-class or an overloaded constructor), if you don’t
type in the call to super in your constructor the compiler will provide you
with a non-argument call to super at the first line of your code, the super
constructor must be called to create an object:

• 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).

When is a Constructor called?

Each time an object is created using a new() keyword, at least one


constructor (it could be the default constructor) is invoked to assign
initial values to the data members of the same class.
The rules for writing constructors are as follows:
• Constructor(s) of a class must have the same name as the class
name in which it resides.
• A constructor in Java can not be abstract, final, static, or
Synchronized.
• Access modifiers can be used in constructor declaration to control its
access i.e which other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s
state. Like methods, a constructor also contains a collection of
statements(i.e. instructions) that are executed at the time of Object
creation.

Types of Constructors in Java

Now is the correct time to discuss the types of the constructor, so


primarily there are two types of constructors in java:

• 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;

// this would be invoked while an object


// of that class is created.
Ducat() { System.out.println("Constructor
called"); }
}

class GFG {
public static void main(String[] args)
{
// this would invoke default constructor.
Ducat geek1 = new Ducat();

// Default constructor provides the default


// values to the object like 0, null
System.out.println(geek1.name);
System.out.println(geek1.num);
}
}
Output
Constructor called

null

2. Parameterized Constructor: A constructor that has parameters is


known as parameterized constructor. If we want to initialize fields of the
class with our own values, then use a parameterized constructor.
Example:

• Java
// Java Program to Illustrate Working of
// Parameterized Constructor

// Importing required inputoutput class


import java.io.*;

// Class 1
class Ducat {
// data members of the class.
String name;
int id;

// Constructor would initialize data members


// With the values of passed arguments while
// Object of that class created
Ducat(String name, int id)
{
this.name = name;
this.id = 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

Remember: Does constructor return any value?


There are no “return value” statements in the constructor, but
the constructor returns the current class instance. We can write
‘return’ inside a constructor.

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);
}

// constructor with two arguments


Ducat(String name, int age)
{

System.out.println("Constructor with two


arguments : " +
" String and Integer : " + name + " "+
age);

// Constructor with one argument but with different


// type than previous..
Ducat(long id)
{
System.out.println("Constructor with one argument :
" +
"Long : " +
id);
}
}

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

Constructor with two arguments : String and Integer : Dharmesh


26

Constructor with one argument : Long : 325614567

Instance variable In Java

Instance variables in Java are non-static variables which are defined in a


class outside any method, constructor or a block. Each instantiated object of
the class has a separate copy or instance of that variable. An instance
variable belongs to a class.
You must be wondering about what exactly is an Instance? Let me help you
by simplifying it.

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,

1Student student1 = new Student();


2Student student2 = new Student();
Then two instances of the class Student will be created.

Java Certification Training Course


• Instructor-led Sessions
• Real-life Case Studies
• Assignments
• Lifetime Access
Explore Curriculum
Now each student would have his own name and score right? So the value
that is stored inside ‘studentName’ and ‘studentScore’ would vary for
different students, they are called ‘variables’. And like you saw that these
variables hold their own value for each instance, they are called Instance
Variables in Java.

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.

Features of an instance variable?


The life of an instance variable depends on the life of an Object, i.e., when
the object is created, an instance variable also gets created and the same
happens when an object is destroyed.

•Instance Variable can be used only by creating objects


•Every object will have its own copy of Instance variables
•Initialization of instance variable is not compulsory. The default value
is zero
•The declaration is done in a class outside any method, constructor or
block
•Instance variables are used when the variable has to be known to
different methods in a class
•Access modifiers can be assigned to instance variables
After attaining theoretical knowledge, you might be pondering on how to
implement Instance variables in Java! Let’s understand that in our next topic.
How do you implement an instance variable in Java?
Implementation of Instance variables in Java is quite easy. I have written a
simple code that will help you to grasp the technical usage.

Here is a detailed code :

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!

Static variables in Java

•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 {

// salary variable is a private static variable


private static double salary;;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}

Output
This will produce the following result −

Development average salary:1000

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:

1. Accessing members and methods


2. Calling process
3. Binding process
4. Overriding process
5. Memory allocation
#1: Accessing members and methods
A static method can only access static data members and static
methods of another class or same class but cannot access non-static
methods and variables. Also, a static method can rewrite the values of
any static data member.
A non-static method can access static data members and static methods
as well as non-static members and methods of another class or same
class, also can change the values of any static data member

Example

• Java

// Java program to Illustrate Calling of a Static


Method

// 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 {

// Main driver method


public static void main(String[] args)
{
// Custom values for integer
// to be summed up
int n = 3, m = 6;

// Calling the static method of above class


// and storing sum in integer variable
int s = Helper.sum(n, m);

// Print and display the sum


System.out.print("sum is = " + s);
}
}
Output
sum is = 9

Example

• Java

// Java program to Illustrate Calling of a Non-Static


Method

// 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 {

// Main driver method


public static void main(String[] args)
{
// Input integers to be summed up
int n = 3, m = 6;

// Creating object of above class


Helper g = new Helper();

// Calling above method to compute sum


int s = g.sum(n, m);

// Calling the non-static method


System.out.print("sum is = " + s);
}
}
Output
sum is = 9

#2: Calling process


The memory of a static method is fixed in the ram, for this reason, we
don’t need the object of a class in which the static method is defined to
call the static method. To call the method we need to write the class
name followed by the name of the method

Syntax: Calling of static methods


class GFG{

public static void geek()

{ }

// calling

GFG.geek();

The memory of the non-static method is not fixed in the ram, so we


need a class object to call a non-static method. To call the method we
need to write the name of the method followed by the class object name

Syntax: Calling of non-static methods


class GFG{

public void geek()

{ }

}
// creating object

GFG g = new GFG();

g.geek();

// calling

#3: Binding process


In the static method, the method use compile-time or early binding. For
this reason, we can access the static method without creating an
instance. In a non-static method, the method use runtime or dynamic
binding. So that we cannot access a non-static method without creating
an instance.
#4: Overriding
In the static method, we cannot override a static method, because of
early binding.
Example:

• Java
// Override of static method
class Parent {

// static method
static void show()
{
System.out.println("Parent");
}
}

// Parent inherit in Child class


class Child extends Parent {

// override show() of Parent


void show()
{
System.out.println("Child");
}
}

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()

overridden method is static


In the non-static method, we can override a non-static method. Because
for override we need runtime polymorphism, which happens only in
runtime binding.
Example:

• Java

// Override of non-static method

class Parent {
void show()
{
System.out.println("Parent");
}
}

// Parent inherit in Child class


class Child extends Parent {

// override show() of Parent


void show()
{
System.out.println("Child");
}
}

class GFG {
public static void main(String[]
args)
{
Parent p = new Parent();
// calling Parent's show()
p.show();

Parent c = new Child();


// calling Child's show()
c.show();
}
}
Output: Error
Parent

Child

#5: Memory allocation


In the static method, memory allocation happens only once, because the
static keyword fixed a particular memory for that method in ram. So
when the method is called every time in a program, each time that
particular memory is used. For that reason, less memory is allocated.
In the non-static method, here memory allocation happens when the
method is invoked and the memory is allocated every time when the
method is called. So much memory is used here. Now, lastly plotting
table in order to grasp altogether

Points Static method Non-static method


A static method is a method that Every method in java defaults to a non-
belongs to a class, but it does not static method without a static keyword
belong to an instance of that class preceding it. non-static methods can
Definition
and this method can be called access any static method
without the instance or object of and static variable also, without using the
that class. object of the class.
In the static method, the method In the non-static method, the method
can only access only static data can access static data members and static
Accessing
members and static methods of methods as well as non-static members
members
another class or same class but and methods of another class or same
and methods
cannot access non-static methods class.
and variables.
Binding The static method uses compile- The non-static method uses runtime or
process time or early binding. dynamic binding.
The static method cannot be
The non-static method can be overridden
Overriding overridden because of early
because of runtime binding.
binding.
Memory In the static method, less memory In the non-static method, much memory
allocation is used for execution because is used for execution because here
memory allocation happens only memory allocation happens when the
Points Static method Non-static method
once because the static keyword method is invoked and the memory is
fixed a particular memory for that allocated every time when the method is
method in ram. called.

You might also like