Unit 1-Java Final
Unit 1-Java Final
HISTORY OF JAVA
Java started out as a research project.
Research began in 1991 as the Green Project at Sun Microsystems, Inc.
Research efforts birthed a new language, OAK. ( A tree outside of the
window of James Gosling’s office at Sun).
It was developed as an embedded programming language, which would
enable embedded system application.
It was not really created as web programming language.
Java is available as jdk and it is an open source s/w.
Java Logo
Java Platforms
There are three main platforms for Java:
Java Terminology
Java Development Kit:
It contains one (or more) JRE's along with the various development tools like
the Java source compilers, bundling and deployment tools, debuggers,
development libraries, etc.
Java Virtual Machine:
An abstract machine architecture specified by the Java Virtual Machine
Specification.
It interprets the byte code into the machine code depending upon the
underlying OS and hardware combination.
JVM is platform dependent. (It uses the class libraries, and other supporting
files provided in JRE)
Java Runtime Environment:
A runtime environment which implements Java Virtual Machine, and provides all
class libraries and other facilities necessary to execute Java programs. This is the
software on your computer that actually runs Java programs.
JRE = JVM + Java Packages Classes (like util, math, lang, awt, swing etc)
+runtime libraries.
Binary form of a .class file(partial)
public class Hello
System.out.println("Hello, World!");
}
BYTE CODE
Byte Code can be defined as an intermediate code generated by the compiler
after the compilation of source code (JAVA Program). This intermediate
code makes Java a platform-independent language.
import java.io.*;
public classGFG {
public staticvoid main(String args[])
{
System.out.println("GFG!");
}
}
Output
GFG!
The above-written code is called JAVA source code.
The compiler compiles the source code.
Finally, Interpreter executes the compiled source code.
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and
code. Most of the syntaxes in java followbasic programming language C and
object-oriented programming concepts are similar to C++. In a java programming
language, many complicated features like pointers, operator overloading,
structures, unions, etc. have been removed. One of the most useful features is the
garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have
pointers concept, java provides a feature "applet" which can be embedded into a
web application. The applet in java does not allow access to other parts of the
computer, which keeps away from harmful programs like viruses and
unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to
run on any computer or operating system. For example, an applet developed
using java runs on a wide variety of CPUs, operating systems, and browsers
connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java,
everything is an object. It supports all the features of the object-oriented
programming paradigm. The primitive data types java also implemented as
objects using wrapper classes, but still, it allows primitive data types to archive
high-performance.
Robust
Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage
collector), java is a strictly typed language, it has a strong set of exception
handling mechanism, and many more.
Multi-threaded
Java supports multi-threading programming, which allows us to write
programs that do multiple operations simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode. The byte code is interpreted to
any machine code so that it runs on the native machine.
High performance
Java provides high performance with the help of features like JVM,
interpretation, and its simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to
support the distributed environment of the Internet. Java also supports Remote
Method Invocation (RMI), this feature enables a program to invoke methods
across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically
updated on a running system and it has a dynamic memory allocation and
deallocation (objects and garbage collector).
‘
DATA TYPES
Data types specify the different sizes and values that can be stored in the
variable.
Primitive data types - includes byte, short, int, long, float, double, boolean
and char
Non-primitive data types - such as String, Arrays and Classes
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are byte, short, int and long. Which type you should
use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or
more decimals. There are two types: float and double.
Even though there are many numeric types in Java, the most used for
numbers are int (for whole numbers) and double (for floating point numbers).
Integer Types
Byte
The byte data type can store whole numbers from -128 to 127. This can be used
instead of int or other integer types to save memory when you are certain that the
value will be within -128 and 127:
Example
public class Main {
System.out.println(myNum);
Short
The short data type can store whole numbers from -32768 to 32767:
Example
public class Main {
System.out.println(myNum);
}
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In
general, the int data type is the preferred data type when we create variables with a
numeric value.
Example
public class Main {
System.out.println(myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an "L":
Example
public class Main {
System.out.println(myNum);
}}
Floating Point Types
You should use a floating point type whenever you need a number with a decimal,
such as 9.99 or 3.14515.
The float and double data types can store fractional numbers. Note that you should
end the value with an "f" for floats and "d" for doubles:
Float Example
public class Main {
System.out.println(myNum);
}}
Double Example
public class Main {
System.out.println(myNum);
}}
Example
public class Main {
System.out.println(isJavaFun);
System.out.println(isFishTasty);
Java Characters
Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Example
public class Main {
public static void main(String[] args) {
char myGrade = 'B';
System.out.println(myGrade);}}
// Java Program to Demonstrate Char Primitive Data Type
// Class
class GFG {
// Main driver method
public static void main(String args[])
{
// Creating and initializing custom character
char a = 'G';
// Integer data type is generally
// used for numeric values
int i = 89;
// use byte and short
// if memory is a constraint
byte b = 4;
// this will give error as number is
// larger than byte range
// byte b1 = 7888888955;
short s = 56;
// this will give error as number is
// larger than short range
// short s1 = 87878787878;
// by default fraction value
// is double in java
double d = 4.355453532;
// for float use 'f' as suffix as standard
float f = 4.7333434f;
//need to hold big range of numbers then we need this data type
long l = 12121L;
System.out.println("char: " + a);
System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("long: " + l);
}
}
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
Java Non-Primitive Data Types
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to objects.
Java Strings
Strings are used for storing text.
Example
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
System.out.println(greeting);
}
}
Java Arrays
Arrays are used to storemultiple values in a single variable, instead of declaring
separate variables for each value.
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to
it, we can use an array literal - place the values in a comma-separated list, inside
curly braces:
String[] cars = {"Volvo", "BMW","Ford", "Mazda"};
Example
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}
}
Note: Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.
Everything in Java is associated with classes and objects, along with its attributes
and methods. For example: in real life, a car is an object. The car has attributes,
such as weight and color, and methods, such as drive and brake.
Create a Class
To create a class, use the keyword class:
Main.java
Create a class named "Main" with a variable x:
int x =5;
}
Remember from the Java Syntax chapter that a class should always start with an
uppercase first letter, and that the name of the java file should match the class
name.
Create an Object
In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.
To create an object of Main, specify the class name, followed by the object name,
and use the keyword new:
Example
Create an object called "myObj" and print the value of x:
Java Interface
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
VARIABLES
Variable in Java is a data container that saves the data values during Java
program execution. Every variable is assigned a data type that designates the
type and quantity of value it can hold.
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 affect that memory location.
In Java, all variables must be declared before use.
datatype name;
Eg:int count;
1. datatype: Type of data that can be stored in this variable.
2. data_name: Name given to the variable.
In this way, a name can only be given to a memory location. It can be assigned
values in two ways:
Variable Initialization
Assigning value by taking input
How to initialize variables?
It can be perceived with the help of 3 components that are as follows:
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
These variables are created when the block is entered, or the function is
called and destroyed after exiting from the block or when the call returns
from the function.
The scope of these variables exists only within the block in which the
variable is declared. i.e., we can access these variables only within that
block.
Initialization of the local variable is mandatory before using it in the
defined scope.
/*package whatever //do not write package name here */
// Contributed by Shubham Jain
import java.io.*;
class GFG {
public static void main(String[] args)
{
int var = 10; // Declared a Local Variable
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
Output
Local Variable: 10
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside
any method, constructor, or block.
As instance variables are declared in a class, these variables are created
when an object of the class is created and destroyed when the object is
destroyed.
Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier, then the default access specifier will
be used.
Initialization of instance variable is not mandatory. Its default value is 0.
Instance Variable can be accessed only by creating objects.
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public String geek; // Declared Instance Variable
public GFG()
{ // Default Constructor
this.geek = "Shubham Jain"; // initializing Instance Variable
}
//Main Method
public static void main(String[] args)
{
// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
}
}
Output
Geek name is: Shubham Jain
3. Static Variables
Static variables are also known as Class variables.
These variables are declared similarly as instance variables. The difference
is that static variables are declared using the static keyword within a class
outside any method constructor or block.
Unlike instance variables, we can only have one copy of a static variable per
class irrespective of how many objects we create.
Static variables are created at the start of program execution and destroyed
automatically when execution ends.
Initialization of static variable is not mandatory. Its default value is 0.
If we access the static variable like the instance variable (through an object),
the compiler will show the warning message, which won’t halt the
program. The compiler will replace the object name with the class name
automatically.
If we access the static variable without the class name, the compiler will
automatically append the class name.
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static String geek = "Shubham Jain"; //Declared static variable
public static void main (String[] args) {
//geek variable can be accessed withod object creation
//Displaying O/P
//GFG.geek --> using the static variable
System.out.println("Geek Name is : "+GFG.geek);
}
}
Output
Geek Name is : Shubham Jain
ARRAYS
An array is a collection of similar types of data.
For example, if we want to store the names of100 people then we can create an
array of the string type that can store100 names.
dataType[] arrayName;
dataType - it can be primitive data types like int, char, double, byte, etc.
arrayName - it is an identifier
For example,
double[] data;
Here, data is an array that can hold values of type double.
// declare an array
double[] data;
// allocate memory
data = new double[10];
Here, the array can store 10 elements. We can also say that the size or length of
the array is 10.
In Java, we can declare and allocate the memory of an array in one single
statement. For example,
Note that we have not provided the size of the array. In this case, the Java
compiler automatically specifies the size by counting the number of elements in
the array (i.e. 5).
In the Java array, each memory location is associated with a number. The number
is known as an array index. We can also initialize arrays in Java, using the index
number. For example,
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
If the size of an array is n, then the last element of the array will be at index
n-1.
How to Access Elements of an Array in Java?
We can access the element of an array using the index number. Here is the syntax
for accessing elements of an array,
// create an array
int[] age = {12, 4, 5, 2, 5};
Output
Accessing Elements of Array:
First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5
In the above example, notice that we are using the index number to access each
element of the array.
We can use loops to access all the elements of the array at once.
// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
System.out.println("Using for Loop:");
for(int i = 0; i < age.length; i++) {
System.out.println(age[i]);
}
}
}
Output
Using for Loop:
12
4
5
In the above example, we are using the for Loop in Java to iterate through each
element of the array. Notice the expression inside the loop,
age.length
Here, we are using the length property of the array to get the size of the array.
Multidimensional Arrays
Arrays we have mentioned till now are called one-dimensional arrays. However,
we can declare multidimensional arrays in Java.
Before we learn about the multidimensional array, make sure you know about Java
array.
A multidimensional array is an array of arrays. Each element of a
multidimensional array is an array itself. For example,
2-dimensional Array
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java
starts with 0 and not 1.
Let's take another example of the multidimensional array. This time we will be
creating a 3-dimensional array. For example,
Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
// create a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
// for..each loop to iterate through elements of 3d array
for (int[][] array2D: test) {
for (int[] array1D: array2D) {
for(int item: array1D) {
System.out.println(item);
}
}
}
}
}
Output:
1
-2
3
2
3
4
-4
-5
6
9
1
2
3
OPERATORS
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
public class Main {
public static void main(String[] args) {
int x = 100 + 50;
System.out.println(x);
}
}
Output:
150
Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or a
variable and another variable:
Example
public class Main {
public static void main(String[] args) {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
}
}
Output:
150
400
800
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Addition
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x + y);
}
}
Output:
8
Subtraction
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x - y);
}
}
Output:
2
Multiplication
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x * y);
}
}
Output:
15
Division
public class Main {
public static void main(String[] args) {
int x = 12;
int y = 3;
System.out.println(x / y);
}
}
Output:
4
Modulus
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 2;
System.out.println(x % y);
}
}
Output:
1
Increment
public class Main {
public static void main(String[] args) {
int x = 5;
++x;
System.out.println(x);
}
}
Output:
6
Decrement
public class Main {
public static void main(String[] args) {
int x = 5;
--x;
System.out.println(x);
}
}
Output:
4
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to
a variable called x:
Example
public class Main {
public static void main(String[] args) {
int x = 10;
System.out.println(x);
}
}
Output:
10
The addition assignment operator (+=) adds a value to a variable:
Example
public class Main {
public static void main(String[] args) {
int x = 10;
x += 5;
System.out.println(x);
}
}
Output:
15
A list of all assignment operators:
Comparison Operators
Comparison operators are used to compare two values:
Logical Operators
Logical operators are used to determine the logic between variables or values:
Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a =
60;
and b = 13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
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:
public class Main {
public static void main(String[] args) {
if (20 > 18) {
System.out.println("20 is greater than 18"); // obviously
}
}
}
OUTPUT:
20 is greater than 18
Syntax
if (condition) {
} else {
Example
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
OUTPUT:
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".
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
public class Main {
public static void main(String[] args) {
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.");
}
}
}
OUTPUT:
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."
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
The example below uses the weekday number to calculate the weekday name:
Example
public class Main {
public static void main(String[] args) {
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;
}
}
}
OUTPUT:
Thursday
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.
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handybecause they save time, reduce errors, and they make code more
readable.
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:
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
OUTPUT:
0
1
2
3
4
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
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
}
}
OUTPUT:
0
1
2
3
4
Do not forget to increase the variable used in the condition, otherwise the loop will
never end!
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
OUTPUT:
0
1
2
3
4
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.
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
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}
OUTPUT:
Volvo
BMW
Ford
Mazda
Java Break and Continue in For Loop
Java Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
Example
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
}
}
OUTPUT:
0
1
2
3
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
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
}
}
OUTPUT:
0
1
2
3
5
6
7
8
9
Syntax/Declaration:-
destination_datatype = (target_datatype)variable;
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 like float, double, integer, decimal.
Everything in Java is associated with classes and objects, along with its attributes
and methods. For example: in real life, a car is an object. The car has attributes,
such as weight and color, and methods, such as drive and brake.
Create a Class
To create a class, use the keyword class:
Main.java
Create a class named "Main" with a variable x:
int x =5;
Remember from the Java Syntax chapter that a class should always start with an
uppercase first letter, and that the name of the java file should match the class
name.
Create an Object
In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.
To create an object of Main, specify the class name, followed by the object name,
and use the keyword new:
Example
Create an object called "myObj" and print the value of x:
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory/folder:
Main.java
Second.java
Main.java
public class Main {
int x = 5;
}
Second.java
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
5
OBJECT ORIENTED PROGRAMMING CONCEPTS
Objects
Classes
Data abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic Binding
class object
The wrapping up of data and functions into a single unit ( called class) is
known as encapsulation. Data encapsulation is the most striking features
of a class.
Abstraction refers to the act of representing essential features without including
the background details or explanations
Inheritance is the process by which objects of one class acquire the properties of
another class. The concept of inheritance provides the reusability.
Polymorphism: It allows the single method to perform different actions based
on the parameters.
Dynamic Binding: When a method is called within a program, it associated with
the program at run time rather than at compile time is called dynamic binding.
Benefits of OOP
Through inheritance, we can eliminate redundant code and extend the use
of existing classes.
The principle of data hiding helps the programmer to build secure
programs.
It is easy to partition the work in a project based on objects.
Object oriented system easily upgraded from small to large systems.
Software complexity can be easily managed.
Applications of OOP
Real-time systems
Object-oriented databases
Neural networks and parallel programming
Decision support and office automation systems
CAD/CAM systems
Constructors
A constructor in Java is similar to a method that is invoked when an object of
the class is created.
Unlike Java methods, a constructor has the same name as that of the class and
does not have any return type.
For example,
class Test {
Test() {
// constructor body
}
}
Here, Test() is a constructor. It has the same name as that of the class and
doesn't have a return type.
Example 1:Java Constructor
class Main {
private String name;
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
}
}
Output
Constructor Called:
The name is Programiz
In the above example, we have created a constructor named Main(). Inside the
constructor, we are initializing the value of the name variable.
Notice the statement of creating an object of the Main class.
Main obj = new Main();
Here, when the object is created, the Main() constructor is called. And, the
value of the name variable is initialized.
Hence, the program prints the value of the name variables as Programiz.
Types of Constructor
In Java, constructors can be divided into 3 types:
1) No-Arg Constructor
2) Parameterized Constructor
3) Default Constructor
1. No-Arg Constructors
Similar to methods, a Java constructor may or maynot have any parameters
(arguments).
If a constructor does not accept any parameters, it is known as a no-argument
constructor. For example,
private Constructor() {
// body of the constructor
}
In the above example, we have created a constructor named Main(). Here, the
constructor takes a single parameter. Notice the expression,
Here, we are passing the single value to the constructor. Based on the argument
passed, the language variable is initialized inside the constructor.
3. Java Default Constructor
If we do not create any constructor, the Java compiler automatically create a
no-arg constructor during the execution of the program. This constructor is
called default constructor.
Example 5: Default Constructor
class Main {
int a;
boolean b;
public static void main(String[] args) {
// A default constructor is called
Main obj = new Main();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}}
Output
a=0
b = false
Here, we haven't created any constructors. Hence, the Java compiler
automatically creates the default constructor.
The default constructor initializes any uninitialized instance variables with
default values.
boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
In the above program, the variables a and b are initialized with default
value 0 and false respectively.
Constructor types:
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the Java
compiler if it is not explicitly defined.
Copy Constructor
There is no copy constructor in Java. However, we can copy the values from
one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They
are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using
Java constructor.
Static Variables
In Java, when we create objects of a class, then every object will have its own copy
of all the variables of the class. For example,
class Test {
// regular variable
int age;
}
class Main {
// create instances of Test
Test test1 = new Test();
Test test2 = new Test();
}
Here, both the objects test1 and test2 will have separate copies of the variable age.
And, they are different from each other.
However, if we declare a variable static, all objects of the class share the same
static variable. It is because like static methods, static variables are also associated
with the class. And, we don't need to create objects of the class to access the static
variables.
For example,
class Test {
// static variable
static int age;
}
class Main {
// access the static variable
Test.age = 20;
}
Output
Static Method
Age is 30
Static Method
Here, we are able to access the static variable and method directly without using
the class name. It is because static variables and methods are by default public.
And, since we are accessing from the same class, we don't have to specify the class
name.
Static Blocks
In Java, static blocks are used to initialize the static variables. For example,
class Test {
// static variable
static int age;
// static block
static {
age = 23;
}}
Here we can see that we have used a static block with the syntax:
static {
// variable initialization
}
The static block is executed only once when the class is loaded in memory.
The class is loaded if either the object of the class is requested in code or the static
members are requested in code.
A class can have multiple static blocks and each static block is executed in the
same sequence in which they have been written in a program.
The final keyword is useful when you want a variable to always store the same
value, like PI (3.14159...).
class Animal {
public void method1() {...}
private void method2() {...}
}
Modifier Description
package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
}
}
Here, the Logger class has the default access modifier. And the class is visible to
all the classes that belong to the defaultPackage package. However, if we try to use
the Logger class in another class outside of defaultPackage, we will get a
compilation error.
The error is generated because we are trying to access the private variable of
the Data class from the Main class.
You might be wondering what if we need to access those private variables. In this
case, we can use the getters and setters method. For example,
class Data {
private String name;
// getter method
public String getName() {
return this.name;
}
// setter method
public void setName(String name) {
this.name= name;
}}
public class Main {
public static void main(String[] main){
Data d = new Data();
// access the private variable using the getter and setter
d.setName("Programiz");
System.out.println(d.getName());
}}
Output:
The name is Programiz
In the above example, we have a private variable named name. In order to access
the variable from the outer class, we have used
methods: getName() and setName(). These methods are called getter and setter in
Java.
Here, we have used the setter method (setName()) to assign value to the variable
and the getter method (getName()) to access the variable.
We have used this keyword inside the setName() to refer to the variable of the
class. To learn more on this keyword, visit Java this Keyword.
Note: We cannot declare classes and interfaces private in Java. However, the
nested classes can be declared private.
class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}
class Dog extends Animal {
public static void main(String[] args) {
// create an object of Dog class
Dog dog = new Dog();
// access protected method
dog.display();
}
}
Output:
I am an animal
// public method
public void display() {
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}
// Main.java
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();
Output:
I am an animal.
I have 4 legs.
Here,
The most common use of the this keyword is to eliminate the confusion between
class attributes and parameters with the same name (because a class attribute is
shadowed by a method or constructor parameter). If you omit the keyword in the
example above, the output would be "0" instead of "5".
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.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.
1) By nulling a reference:
Employee e=new Employee();
e=null;
3) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in
Object class as:
s1=null;
s2=null;
System.gc();
}}
OUTPUT
object is garbage collected
object is garbage collected
In Java, you can define a class within another class. Such class is known as nested
class. For example,
class OuterClass {
// ...
class NestedClass {
// ...
}}
There are two types of nested classes you can create in Java.
Since the inner class exists within the outer class, you must instantiate the outer
class first, in order to instantiate the inner class.
double getCache(){
return 4.3;
}
}
// nested protected class
protected class RAM{
// members of protected nested class
double memory;
String manufacturer;
double getClockSpeed(){
return 5.5;
}
}
}
public class Main {
public static void main(String[] args) {
// create object of Outer class CPU
CPU cpu = new CPU();
// create an object of inner class Processor using outer class
CPU.Processor processor = cpu.new Processor();
// create an object of inner class RAM using outer class CPU
CPU.RAM ram = cpu.new RAM();
System.out.println("Processor Cache = " + processor.getCache());
System.out.println("Ram Clock speed = " + ram.getClockSpeed());
}
}
Output:
Processor Cache = 4.3
Ram Clock speed = 5.5
In the above program, there are two nested classes: Processor and RAM inside the
outer class: CPU. We can declare the inner class as protected. Hence, we have
declared the RAM class as protected.
Unlike inner class, a static nested class cannot access the member variables of the
outer class. It is because the static nested class doesn't require you to create an
instance of the outer class.
Here, we are creating an object of the static nested class by simply using the class
name of the outer class. Hence, the outer class cannot be referenced
using OuterClass.this.
Output:
Total Ports = 3
In the above program, we have created a static class named USB inside the
class MotherBoard. Notice the line,
MotherBoard.USB usb = new MotherBoard.USB();
Here, we are creating an object of USB using the name of the outer class.
JAVA STRINGS
In Java, a string is a sequence of characters. For example, "hello" is a string
containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use double quotes to represent a string in Java. For example,
// create a string
String type = "Java programming";
Here, we have created a string variable named type. The variable is initialized with
the string Java Programming.
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
OUTPUT
Java
Python
JavaScript
In the above example, we have created three strings named first, second, and third. Here,
we are directly creating strings like primitive types.
However, there is another way of creating Java strings (using the new keyword). We
will learn about that later in this tutorial.
Note: Strings in Java are not primitive types (like int , char , etc). Instead, all strings are
objects of a predefined class named String .
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}
OUTPUT
First String: Java
Second String: Programming
Joined String: Java Programming
In the above example, we have created two strings named first and second.
Notice the statement,
String joinedString = first.concat(second);
Here, the concat() method joins the second string to the first string and assigns it to
the joinedString variable.
We can also join two strings using the + operator in Java. To learn more, visit Java
String concat().
3. Compare two Strings
In Java, we can make comparisons between two strings using the equals() method.
For example,
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
// create a string
String example = "Hello! ";
Here, we have created a string variable named example. The variable holds the
string "Hello! ".
Now suppose we want to change the string.
Here, we are using the concat() method to add another string World to the
previous string.
It looks like we are able to change the value of the previous string. However, this is
not true.
Let's see what has happened here,
In the above example, we have created a string name using the new keyword.
Here, when we create a string object, the String() constructor is invoked. To learn
more about constructor, visit Java Constructor.
Note: The String class provides various other constructors to create strings. To
learn more, visit Java String (official Java documentation).