Java Notes 1
Java Notes 1
Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, Inc. in 1991.
Java is related to C++, which is inherited from the language C.
The characters of Java is inherited from C and C++ language. It took approx. Eighteen months
to develop the first working version.
It was first named as “Oak” but was renamed as “Java” in 1995. It is publicly announced in
the spring of 1995.
The basic idea behind creating this language is to create a platform-independent language
that is used to develop software for consumer electronic devices such as microwave ovens,
remote controls, etc. Initially, it was not designed for Internet applications.
Evolution of Java:
Release
Version Features
Date
JDK
1995 —
Beta
January
JDK 1.0 This is the first stable version.
1996
In this version, added many new library elements, redefined the way of handling
JDK February events, and reconfigured most of the libraries of 1.0 and deprecated some
1.1 1997 features defined by 1.0. Added inner class, JavaBeans, JDBC, RMI, JIT (Just In
time) compiler.
J2SE December Added support for many features, such as Swing and Collection Framework. The
1.2 1998 methods suspend(), resume() and stop() of Thread class were deprecated.
J2SE 1.3 May 2000 A very small improvement, as it just improved the development environment.
It added some upgrades such as the new keyword assert, chained exception and
February
J2SE 1.4 a channel-based I/O subsystem. Also added some feature to the collection
2002
framework and the Networking classes.
The significant new features added to this version are – Generics, Annotation,
September
J2SE 5.0 Autoboxing and Auto-unboxing, Enumeration, for-each, variable-length
2004
argument, Static import, Formatted I/O, Concurrency utilities.
Java SE December In this version the API libraries and several new packages got enhanced and
6 2006 offered improvements to the run time. It supports JDBC 4.0.
Java SE July 2011 Added JVM support for dynamic language, String in the switch, Automatic
7 resource management in try-statement, support for underscore in integers,
binary integer literals etc…
Java SE
March 2014 Added Date and time API, Repeating annotation, JavaFX.
8
Java SE September Added Java platform module system update, jshell, XML Catalog, jlink, and the
9 2017 JavaDB was removed from JDK
Java SE Added features are local variable type interface, Application class data sharing,
March 2018
10 Garbage collector interface, etc…
Java SE September Feature added: Dynamic class file loader, HTTP client, and Transport layer
11 2018 security. JavaFX, Java EE, and CORBA modules have been removed from JDK.
Java SE Added Microbenchmark Suite, JVM Constant API, One AArch64 Port, Default
March 2019
12 CDS Archives etc.
Java Architecture
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the
process of interpretation and compilation. It defines all the processes involved in creating a
Java program. Java Architecture explains each and every step of how a program is compiled
and executed.
o After that, the JVM converts the byte code into machine code.
The following figure represents the Java Architecture in which each step is elaborate
graphically.
Components of Java Architecture
The Java architecture includes the three main components:
JVM, first of all, loads the code into memory and verifies it. After that, it executes the code
and provides a runtime environment. Java Virtual Machine (JVM) has its own architecture,
which is given below:
JVM Architecture
JVM is an abstract machine that provides the environment in which Java bytecode is executed.
The falling figure represents the architecture of the JVM.
.
ClassLoader: ClassLoader is a subsystem used to load class files. ClassLoader first loads the
Java code whenever we run it.
Class Method Area: In the memory, there is an area where the class data is stored during
the code's execution. Class method area holds the information of static variables, static
methods, static blocks, and instance methods.
Heap: The heap area is a part of the JVM memory and is created when the JVM starts up. Its
size cannot be static because it increase or decrease during the application runs.
Stack: It is also referred to as thread stack. It is created for a single execution thread. The
thread uses this area to store the elements like the partial result, local variable, data used for
calling method and returns etc.
Native Stack: It contains the information of all the native methods used in our application.
Execution Engine: It is the central part of the JVM. Its main task is to execute the byte code
and execute the Java classes. The execution engine has three main components used for
executing Java classes.
o Interpreter: It converts the byte code into native code and executes. It sequentially
executes the code. The interpreter interprets continuously and even the same method
multiple times. This reduces the performance of the system, and to solve this, the JIT
compiler is introduced.
o JIT Compiler: JIT compiler is introduced to remove the drawback of the interpreter. It
increases the speed of execution and improves performance.
o Garbage Collector: The garbage collector is used to manage the memory, and it is a
program written in Java. It works in two phases, i.e., Mark and Sweep. Mark is an
area where the garbage collector identifies the used and unused chunks of memory.
The Sweep removes the identified object from the Mark
Java Native Interface works as a mediator between Java method calls and native libraries.
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.
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
Variables in Java
A variable is a name given to a memory location. It is the basic unit of
storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations
done on the variable effects that memory location.
In Java, all the variables must be declared before use.
How to declare variables?
We can declare variables in java as follows:
TOKENS
The Java compiler breaks the line of code into text (words) is called Java tokens. These are
the smallest element of the Java program. The Java compiler identified these words as tokens.
These tokens are separated by the delimiters. It is useful for compilers to detect errors.
Remember that the delimiters are not part of the Java tokens.
In the above code snippet, public, class, Demo, {, static, void, main, (, String, args,
[, ], ), System, ., out, println, hello, etc. are the Java tokens.
The Java compiler translates these tokens into Java bytecode. Further, these bytecodes are
executed inside the interpreted Java environment.
Types of Tokens
Java token includes the following:
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the
following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final
21. import 22. instanceof 23. int 24. interface 25. long
26. native 27. new 28. package 29. private 30. protected
31. public 32. return 33. short 34. static 35. super
36. switch 37. synchronized 38. this 39. thro 40. throws
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier: Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user. It uses letters, underscores, or a dollar sign as the first character.
The label is also known as a special kind of identifier that is used in the goto statement.
Remember that the identifier name must be different from the reserved keywords. There are
some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid
Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is
defined by the programmer. Once it has been defined cannot be changed. Java provides five
types of literals are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type
23 int
9.86 double
"javatpoint" String
Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators that can be classified
according to the functionality they provide. There are eight types of operators in Java, are as
follows:
o Arithmetic Operators
o Assignment Operators
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Relational ==, != , < , >, <= , >=
Logical && , ||
Bitwise &,|,^,~
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators
Separators: The separators in Java is also known as punctuators. There are nine separators
in Java, are as follows:
1. separator <= ; | , | . | ( | ) | { | } | [ | ]
Note that the first three separators (; , and .) are tokens that separate other tokens, and the last six (3
pairs of braces) separators are also known as delimiters. For example, Math.pow(9, 3); contains nine
tokens.
o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the
two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Semicolon (;): It is the symbol that can be found at end of the statements. It
separates the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.
Comments: Comments allow us to specify information about the program inside our Java
code. Java compiler recognizes these comments as tokens but excludes it form further
processing. The Java compiler treats comments as whitespaces. Java provides the following
two types of comments:
float x;
byte y;
...
...
y=(byte)x; //Line 5
In Line 5: you can see that, we are converting float(source) data
type into byte(target) data type.
2. Type conversion :
In type conversion, a data type is automatically converted into another data
type by a compiler at the compiler time. In type conversion, the destination
data type cannot be smaller than the source data type, that’s why it is also
called widening conversion. One more important thing is that it can only be
applied to compatible data types.
Type Conversion example –
int x=30;
float y;
y=x; // y==30.000000.
Let’s see the difference between Type casting and Type conversion which are
given below:
S.N
O TYPE CASTING TYPE CONVERSION
Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
variable = value;
In many cases assignment operator can be combined with other operators to build
a shorter version of statement called Compound Statement. For example,
instead of a = a+5, we can write a += 5.
+=, for adding left operand with right operand and then assigning it to
variable on the left.
-=, for subtracting left operand with right operand and then assigning it
to variable on the left.
*=, for multiplying left operand with right operand and then assigning it
to variable on the left.
/=, for dividing left operand with right operand and then assigning it to
variable on the left.
%=, for assigning modulo of left operand with right operand and then
assigning it to variable on the left.
a < b;
Here, > operator is the relational operator. It checks if a is less than b or not.
class Main {
public static void main(String[] args) {
// create variables
int a = 7, b = 11;
// value of a and b
System.out.println("a is " + a + " and b is " + b);
// == operator
System.out.println(a == b); // false
// != operator
System.out.println(a != b); // true
// > operator
System.out.println(a > b); // false
// < operator
System.out.println(a < b); // true
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}
Note: Relational operators are used in decision making and loops.
! (Logical
!expression true if expression is false and vice versa
NOT)
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Java Ternary Operator
The ternary operator (conditional operator) is shorthand for the if-then-else statement. For
example,
variable = Expression ? expression1 : expression2
Here's how it works.
If the Expression is true , expression1 is assigned to the variable .
If the Expression is false , expression2 is assigned to the variable .
Let's see an example of a ternary operator.
class Java {
public static void main(String[] args) {
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Output
Leap year
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
0 0 0
0 1 1
1 0 1
1 1 1
The above table is known as the "Truth Table" for the bitwise OR operator.
Let's look at the bitwise OR operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Example 1: Bitwise OR
class Main {
public static void main(String[] args) {
0 0 0
0 1 0
1 0 0
1 1 1
Let's take a look at the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
0 0 0
0 1 1
1 0 1
1 1 0
Let's look at the bitwise XOR operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
2's Complement
In binary arithmetic, we can calculate the binary negative of an integer using 2's complement.
1's complement changes 0 to 1 and 1 to 0. And, if we add 1 to the result of the 1's complement,
we get the 2's complement of the original number. For example,
// compute the 2's complement of 36
36 = 00100100 (In Binary)
2's complement:
11011011
+ 1
_________
11011100
Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This value is equivalent to the
bitwise complement of 35.
Hence, we can say that the bitwise complement of 35 is -(35 + 1) = -36.
// bitwise complement of 35
result = ~number;
System.out.println(result); // prints -36
}
}
Java Shift Operators
There are three types of shift operators in Java:
Signed Left Shift (<<)
Signed Right Shift (>>)
Unsigned Right Shift (>>>)
In general, if we write a<<n, it means to shift the bits of a number toward the left with specified
position (n). In the terms of mathematics, we can represent the signed right shift operator as
follows:
Example 1: What will be the result after shifting a<<3. The value of a is 20.
a << 3 = 160
20 << 3
Example 2: What will be the result after shifting a<<2. The value of a is -10.
-10 << 3
SignedLeftShiftOperatorExample.java
Output
x<<1 = 24
In general, if we write a>>n, it means to shift the bits of a number toward the right with a specified
position (n). In the terms of mathematics, we can represent the signed right shift operator as
follows:
Note: When we apply right shift operator on a positive number, we get the positive number in the result
also. Similarly, when we apply right shift operator on a negative number, we get the negative number in the
result also.
Example: Apply the signed right shift operator with specified positions 4 if x = 256 and
x = -256.
If x = 256
256 >> 4
256/24 = 16
If x = -256
-256 >> 4
-256/24 = -16
In the above example, we have observed that after shifting the operator 256 converted into 16 and
-256 converted into -16.
SignedRightShiftOperatorExample.java
Output
x>>2 = 12
}
The left operand value is moved right by the number of bits specified by the right operand and the
shifted bits are filled up with zeros. Excess bits shifted off to the right are discarded.
Therefore, before shifting the bits the decimal value of a is 240, and after shifting the bits the
decimal value of a is 60.
UnsignedRightShiftOperatorExample.java
Output
x>>>2 = 5
Java Operator Precedence
Operator precedence determines the order in which the operators in an expression are
evaluated.
int myInt = 12 - 4 * 2;
What will be the value of myInt ? Will it be (12 - 4)*2 , that is, 16 ? Or it will be 12 - (4 *
2) , that is, 4 ?
When two operators share a common operand, 4 in this case, the operator with the
highest precedence is operated first.
In Java, the precedence of * is higher than that of - . Hence, the multiplication is
performed before subtraction, and the value of myInt will be 4.
Operators Precedence
Multiplicative */%
Additive +-
Shift << >> >>>
Equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ? :
= += -= *= /= %=
Assignment
&= ^= |= <<= >>= >>>=
If an expression has two operators with similar precedence, the expression is evaluated
according to its associativity (either left to right, or right to left). Let's take an example.
a = b = c;
= += -= *= /= %=
Assignment RIGHT TO LEFT
&= ^= |= <<= >>= >>>=
Arrays
An array is a collection of similar types of data.
For example, if we want to store the names of 100 people then we can create an array of the
string type that can store 100 names.
Syntax:
type var-name[];
OR
type[] var-name;
Example:
int intArray[];
or int[] intArray;
class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;
//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array. These are also known as Jagged Arrays. A multidimensional array
is created by appending one set of square brackets ([]) per dimension. Examples:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
class multiDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
// printing 2D array
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output:
279
361
742
Java Class
A class is a blueprint for the object. Before we create an object, we first need to define the
class.
Syntax
class ClassName {
// fields
// methods
}
Here, fields (variables) and methods represent the state and behavior of the object
respectively.
fields are used to store data
class Bicycle {
// state or field
private int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
Java Objects
An object is called an instance of a class. For example, suppose Bicycle is a class
then MountainBicycle , SportsBicycle , TouringBicycle , etc can be considered as objects
of the class.
Creating an Object in Java
class Lamp {
class Main {
public static void main(String[] args) {
Output:
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Note: It is called constructor because it constructs the values at the time of object creation. 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.
2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object c
Output:
Bike is created
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also.
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
Output:
111 Karan
222 Aryan
A constructor is used to initialize the state of an object. A method is used to expose the behavior
of an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you don't The method is not provided by the
have any constructor in a class. compiler in any case.
The constructor name must be same as the class name. The method name may or may not be
same as the class name.
NOTE: In Java, Method Overloading is not possible by changing the return type of the method only.
EXAMPLE:
public class overloadexample
{
public int sum(int x, int y)
{
return (x + y);
}
public int sum(int x, int y, int z)
{
return (x + y + z);
}
public double sum(double x, double y)
{
return (x + y);
}
Output :
30
60
31.0
Sometimes there is a need of initializing an object in different ways. This can be done using
constructor overloading.
// Driver code
public class Test
{
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
//Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
Output:
a = 10 b = 20
//Default constructor
Test()
{
this(10, 20);
System.out.println("Inside default constructor \n");
}
//Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
System.out.println("Inside parameterized constructor");
}
Output:
Inside parameterized constructor
Inside default constructor
void display()
{
// calling function show()
this.show();
void show() {
System.out.println("Inside show funcion");
}
Output :
Inside show funcion
Inside display function
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
1) By nulling a reference:
Employee e=new Employee();
e=null;
3) By anonymous object:
new Employee();
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.