03-Java Basic
03-Java Basic
1. [Link]
2. [Link]
Java Basics
5 Phases of the Java Program There are five phases needed to run the Java
program.
In this section, we will discuss those 5 phases of the Java program in detail.
These steps are to create and execute the Java application using a Java
development environment.
These phases are discussed in the context of JDK 6.0 from Sun Microscystems Inc.
JDK is the Java Development Kit and JDK6 is the version 6th version of JDK,
1. Edit
2. Compile
3. Load
4. Verify
5. Execute
Observe the below diagram for the 5 Phases of the Java Program:-
Let us see in detail the 5 Phases of the Java Program:-
Phase-1: Edit
When we write a Java program on any editor & save it, then it is stored in a disk with
an extension of .java. This .java file is platform-independent therefore a Java
program (.java file) written in one operating system can be used in any operating
system.
Phase-2: Compile
The compiler’s work is to convert the high-level language to bytecodes then store it
with an extension of .class. To compile we use the “javac” command.
After developing the Java program, we compile it through the “javac” command. The
compiler checks for syntax errors, and if everything is correct then it starts translating
the .java file else it gives a compile-time error. After compilation of the .java file,
the .java file is translated to .class file. Similar to the .java file, the .class file is also
platform-independent.
Phase-3: Load
The class loader reads the code, compiles it, and puts those bytecodes from the disk
to primary memory. From the class loader, the codes are stored in primary memory.
When we execute the “java” command to run the Java application then the .class file
(which contains bytecode) is loaded into the RAM, and this task is done by the class
loader.
Phase-4: Verify
This step confirms that the bytecodes are valid and make sure that they do not risk
the Java security restrictions.
Phase-5: Execute
In this step, the JVM (Java Virtual Machine) reads the byte and translates it to the
language that the machine can understand that is machine language then executes
the program and stores it in values in primary memory. This machine language will
be different for different operating
Let’s start with using online IDE provided via jDoodle - [Link]
java-compiler/
The below-given program is the most simple program of Java printing “Hello
World” to the screen. Let us try to understand every bit of code step by step.
1. Class definition
This line uses the keyword class to declare that a new class is being defined.
public class HelloWorld
2. HelloWorld
It is an identifier that is the name of the class. The entire class definition,
including all of its members, will be between the opening curly brace { and the
closing curly brace }.
3. main method:
In the Java programming language, every application must contain a main
method whose signature is:
public static void main(String[] args)
● public: So that JVM can execute the method from anywhere.
● static: The main method is to be called without an object. The
modifiers public and static can be written in either order.
● void: The main method doesn’t return anything.
● main(): Name configured in the JVM.
● String[]: The main method accepts a single argument, i.e., an array
of elements of type String.
Like in C/C++, the main method is the entry point for your application and will
subsequently invoke all the other methods required by your program. Every
programming language has a convention to define the entry point of the
project/ application.
Comments
They can either be multiline or single-line comments.
// This is a simple Java program.
// Call this file "[Link]".
Important Points
● The name of the class defined by the program is HelloWorld, which
is the same as the name of the file([Link]). This is not a
coincidence. In Java, all codes must reside inside a class, and there
is at most one public class which contains the main() method.
● By convention, the name of the main class(a class that contains the
main method) should match the name of the file that holds the
program.
For Advanced level, we will cover setting up Eclipse IDE on local machine.
[Link]
Detailed -
[Link]
Java Classes/Objects
Java is an object-oriented programming language.
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.
An object in Java is the physical as well as a logical entity, whereas, a class in Java
is a logical entity only.
● Identity: An object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. However, it is used internally by the
JVM to identify each object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its
state. It is used to write, so writing is its behavior.
Object Definitions:
Fields
Methods
Constructors
Blocks
1. class <class_name>{
2. field;
3. method;
4. }
Instance variable in Java
A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets
memory at runtime when an object or instance is created. That is why it is known as
an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an
object.
Advantage of Method
● Code Reusability
● Code Optimization
File: [Link]
Output:
0 null
We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name
with the class name which has main() method.
File: [Link]
1. By reference variable
2. By method
3. By constructor
File: [Link]
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. [Link]=101;
9. [Link]="Sonoo";
10. [Link]([Link]+" "+[Link]);//printing members with a white
space
11. }
12. }
Output:
101 Sonoo
ACTIVITY JB-1
Create Employee class with the following as the data members
We can also create multiple objects and store information in it through reference
variable.
File: [Link]
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent3{
6. public static void main(String args[]){
7. //Creating objects
8. Student s1=new Student();
9. Student s2=new Student();
10. //Initializing objects
11. [Link]=101;
12. [Link]="Sonoo";
13. [Link]=102;
14. [Link]="Amit";
15. //Printing data
16. [Link]([Link]+" "+[Link]);
17. [Link]([Link]+" "+[Link]);
18. }
Output:
101 Sonoo
102 Amit
1. class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){[Link](rollno+" "+name);}
9. }
10. class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. [Link](111,"Karan");
15. [Link](222,"Aryan");
16. [Link]();
17. [Link]();
18. }
19. }
Output
111 Karan
222 Aryan
As you can see in the above figure, object gets the memory in heap memory area.
The reference variable refers to the object allocated in the heap memory area. Here,
s1 and s2 both are reference variables that refer to the objects allocated in memory.
File: [Link]
1. class Employee{
2. int id;
3. String name;
4. float salary;
5. void insert(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){[Link](id+" "+name+" "+salary);}
11. }
12. public class TestEmployee {
13. public static void main(String[] args) {
14. Employee e1=new Employee();
15. Employee e2=new Employee();
16. Employee e3=new Employee();
17. [Link](101,"ajeet",45000);
18. [Link](102,"irfan",25000);
19. [Link](103,"nakul",55000);
20. [Link]();
21. [Link]();
22. [Link]();
23. }
24. }
Output:
File: [Link]
1. class Rectangle{
2. int length;
3. int width;
4. void insert(int l, int w){
5. length=l;
6. width=w;
7. }
8. void calculateArea(){[Link](length*width);}
9. }
10. class TestRectangle1{
11. public static void main(String args[]){
12. Rectangle r1=new Rectangle();
13. Rectangle r2=new Rectangle();
14. [Link](11,5);
15. [Link](3,15);
16. [Link]();
17. [Link]();
18. }
19. }
Output:
55 45
● By new keyword
● By newInstance() method
● By clone() method
● By deserialization
If you have to use an object only once, an anonymous object is a good approach. For
example:
1. new Calculation().fact(5);
1. class Calculation{
2. void fact(int n){
3. int fact=1;
4. for(int i=1;i<=n;i++){
5. fact=fact*i;
6. }
7. [Link]("factorial is "+fact);
8. }
9. public static void main(String args[]){
10. new Calculation().fact(5);//calling method with anonymous object
11. }
12. }
Output:
Factorial is 120
Output:
55
45
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.
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.
while declaring a constructor. It controls the object creation. In other words, we can have
private, protected, public or default constructor in Java.
2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
1. <class_name>(){}
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
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.
Output
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor. Here 0 and null values are provided by default
constructor.
111 Karan
222 Aryan
is a technique of having more than one constructor with different parameter lists. They are
arranged in a way that each constructor performs a different task. They are differentiated by
the compiler by the number of parameters in the list and their types.
Example of Constructor Overloading
1. //Java program to overload constructors
2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){[Link](id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. [Link]();
23. [Link]();
24. }
25. }
Output:
111 Karan 0
222 Aryan 25
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given
below.
A constructor must not have a return type. A method must have a return
type.
The constructor name must be same as the The method name may or may
class name. not be same as the class name.
Java 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:
● By constructor
In this example, we are going to copy the values of one object into another using
Java constructor.
1. //Java program to initialize the values from one object to another object.
2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = [Link];
13. name =[Link];
14. }
15. void display(){[Link](id+" "+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. [Link]();
21. [Link]();
22. }
23. }
Output
111 Karan
111 Karan
1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){[Link](id+" "+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. [Link]=[Link];
15. [Link]=[Link];
16. [Link]();
17. [Link]();
18. }
19. }
Output
111 Karan
111 Karan
Yes, it is the current class instance (You cannot use return type yet it returns a
value).
Yes, like object creation, starting a thread, calling a method, etc. You can perform any
operation in the constructor as you perform in the method.
Is there Constructor class in Java?
Yes.
Java provides a Constructor class which can be used to get the internal information
of a constructor in the class. It is found in the [Link] package.
In Java using a static keyword, we can have a static method, static class, static
block, static variable. This keyword is mainly used for the management of memory.
We can use static keyword with methods, variables, class, and blocks. It belongs to a
class rather than the instance of the class, It simply means that if you make any
variable static to can access it without its object.
1. Block
4. Class
static
number = 69;
[Link](sentence);
Output
Welcome to Dataflair
Value of Integer 69
Static Variable in Java
*This topic is already covered
package [Link];
class Employee
int empId;
String empName;
companyName = "DataFlair";
empId = id;
empName = name;
void display()
//creating objects
[Link]();
[Link]();
[Link]();
Output
Example-
// Helper class
class OuterClass {
// Input string
// static class
[Link](
// called
[Link](
+ msg);
// Class 2
// Main class
class GFG {
[Link] printer
= new [Link]();
// static class
[Link]();
[Link] inner=new
[Link]();
[Link]();
[Link] innerObject
[Link]();
Output:
// code to be executed....
}
Instance Methods vs Static Methods
in Java
1. The instance method requires the object of its class to be
created before it can be called. Static methods in Java can be
called without creating the object of the class.
3. The static method has a single copy for a class. But instance
methods have multiple copies depending on the number of
instances created for that particular class.
6. this can be used to return the current class instance from the method.
Suggestion: If you are beginner to java, lookup only three usages of this keyword.
The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.
Let's understand the problem if we don't use this keyword by the example given
below:
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){[Link](rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. [Link]();
17. [Link]();
18. }}
output
In the above example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and instance
variable.
You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while invoking
the method. Let's see the example
1. class A{
2. void m(){[Link]("hello m");}
3. void n(){
4. [Link]("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}
The this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor. In other words, it is used for constructor chaining.
1. class A{
2. A(){[Link]("hello a");}
3. A(int x){
4. this();
5. [Link](x);
6. }
7. }
8. class TestThis5{
9. public static void main(String args[]){
10. A a=new A(10);
11. }}
1. class A{
2. A(){
3. this(5);
4. [Link]("hello a");
5. }
6. A(int x){
7. [Link](x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}
Real usage of this() constructor call
The this() constructor call should be used to reuse the constructor from the
constructor. It maintains the chain between the constructors i.e. it is used for
constructor chaining. Let's see the example given below that displays the actual use
of this keyword.
1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. [Link]=rollno;
7. [Link]=name;
8. [Link]=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this(rollno,name,course);//reusing constructor
12. [Link]=fee;
13. }
14. void display(){[Link](rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis7{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. [Link]();
21. [Link]();
22. }}
1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. [Link]=rollno;
7. [Link]=name;
8. [Link]=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. [Link]=fee;
12. this(rollno,name,course);//[Link]
13. }
14. void display(){[Link](rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis8{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. [Link]();
21. [Link]();
22. }}
Output : Compile time error
The this keyword can also be passed as an argument in the method. It is mainly used
in the event handling. Let's see the example:
1. class S2{
2. void m(S2 obj){
3. [Link]("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }
We can pass the this keyword in the constructor also. It is useful if we have to use
one object in multiple classes. Let's see the example:
1. class B{
2. A4 obj;
3. B(A4 obj){
4. [Link]=obj;
5. }
6. void display(){
7. [Link]([Link]);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. [Link]();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }
Output: 10
We can return this keyword as a statement from the method. In such case, return
type of the method must be the class type (non-primitive). Let's see the example:
1. return_type method_name(){
2. return this;
3. }
Let's prove that this keyword refers to the current class instance variable. In this
program, we are printing the reference variable and this, output of both variables are
same.
1. class A5{
2. void m(){
3. [Link](this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. [Link](obj);//prints the reference ID
8. obj.m();
9. }
10. }