My Java Notes Basic
My Java Notes Basic
What is java
Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
Java was developed by James Ghosling, Patrick Naughton, Mike Sheridan at Sun
Microsystems Inc. in 1991. It took 18 months to develop the first working version.
The initial name was Oak but it was renamed to Java in 1995 as OAK was a registered
trademark of another Tech company
but it is not a pure object-oriented language because it supports primitive data types
like int, char etc.
It is an enterprise platform that is mainly used to develop web and enterprise applications. It
is built on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services,
EJB, JPA, etc.
the applications of Java Enterprise Edition run on reference runtimes. This reference
runtime handle transactions, security, scalability, concurrency and the management
of components to be deployed.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface
API.
3.Application of Java
Following are some other usage of Java :
1. Developing Desktop Applications
2. Web Applications like Linkedin.com, Snapdeal.com etc
3. Mobile Operating System like Android
4. Embedded Systems
5. Smart cards
6. Robotics and games etc.
Types of Java Applications There are mainly 4 type of applications that can be created using
java programming:
1) Standalone Application
It is also known as desktop application or window-based application. An application
that we need to install on every machine such as media player, antivirus etc. AWT
and Swing are used in java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating
web applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has
the advantage of high level security, load balancing and clustering. In java, EJB is
used for creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are
used for creating mobile applications
4. Features of Java
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.The
confusing and ambiguous concepts of C++ are either left out in Java or they have been re-
implemented in a cleaner way. Eg : Pointers and Operator Overloading are not there in java
but were an important part of C++.
2)Object Oriented
In java everything is Object which has some data and behaviour. Java can be easily
extended as it is based on Object Model.
3)Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time
error checking and runtime checking. But the main areas which Java improved were
Memory Management and mishandled Exceptions by introducing automatic Garbage
Collector and Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language. On
compilation Java program is compiled into bytecode. This bytecode is platform independent
and can be run on any machine, plus this bytecode format also provide security. Any
machine with Java Runtime Environment can run Java Programs.
5)Secure
When it comes to security, Java is always the first choice. With java secure features it
enable us to develop virus free, temper free system. Java program always runs in Java
runtime environment with almost null interaction with system OS, hence it is more secure.
6)Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other
resources to execute multiple threads at the same time, like While typing, grammatical
errors are checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or
C++. But, Java enables high performance with the use of just-in-time compiler.
Ease of Use
Q) What is JVM?
JVM control execution of every Java program. JVMs are available for many
hardware and software platforms. JVM, JRE and JDK are platform dependent
because configuration of each OS differs. But, Java is platform independent.
What it does
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
What is JVM
It is:
Q) JVM Architecture
1) Classloader
4)Stack : Local variables and partial results are store here. Each thread has
a private JVM stack created when the thread is created.
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance.
JIT compiles parts of the byte code that have similar functionality at
the same time, and hence reduces the amount of time needed for
compilation. Here, the term "compiler" refers to a translator from
the instruction set of a Java virtual machine (JVM) to the instruction
set of a specific CPU.
6) Native Method Stack It contains all the native methods used in the
application.
JRE
JRE is Java Runtime Environment. The Java Runtime Environment is a set
of software tools which are used for developing Java applications. It is
used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses
at runtime.
JDK
The JDK also called Java Development Kit is a superset of the JRE, and contains everything
that is in the JRE, plus tools such as the compilers and debuggers necessary for developing
applets and applications. It physically exists. Application.
Q)Java Hello World! Program
class Hello
{
public static void main(String[] args)
{
System.out.println ("Hello World program");
}
}
Parameters used in First Java Program
The main() is the starting point for JVM to start execution of a Java
program. Without the main() method, JVM will not execute the program.
The syntax of the main() method is:
public: It is an access specifier. We should use a public keyword before
the main() method so that JVM can identify the execution point of the
program. If we use private, protected, and default before the main()
method, it will not be visible to JVM.
void : It is the return type, meaning this function will not return anything. /
acknowledges the compiler that main() method does not return any value.
main : main() method is the most important method in a Java program. This is
the method which is executed, hence all the logic must be inside the main()
method. If a java class is not having a main() method, it causes compilation
error.
String[] args : This represents an array whose type is String and name is
args. It means that it can store a group of string. Remember, this array can
also store a group of numbers but in the form of string only. Values passed
to the main() method is called arguments. These arguments are stored
into args[] array, so the name args[] is generally used for it.
The program will compile, but not run, because JVM will not recognize the
main() method. Remember JVM always looks for the main() method with
a string type array as a parameter.
Execution Process
First, JVM executes the static block, then it executes static methods, and
then it creates the object needed by the program. Finally, it executes the
instance methods. JVM executes a static block on the highest priority
basis. It means JVM first goes to static block even before it looks for the
main() method in the program.
Example
1. class Demo
2. {
3. static //static block
4. {
5. System.out.println("Static block");
6. }
7. public static void main(String args[]) //static method
8. {
9. System.out.println("Static method");
10. }
11. }
Output:
Static block
Static method
We observe that JVM first executes the static block, if it is present in the
program. After that it searches for the main() method. If the main() method
is not found, it gives error.
Example
A program that does not have the main() method gives an error at run
time.
1. class DemoStaticBlock
2. {
3. Static //static block
4. {
5. System.out.println("Static block");
6. }
7. }
Output:
Error: Main method not found in the class Demo, please
define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend
javafx.application.Application
We can also use the different name for the String type array and write it
as:
Example
A program that has no main() method, but compile and runs successfully.
Java
Overloading of main() method
We can also overload the main() method. We can define any number of
main() method in the class, but the method signature must be different.
Example
1. class OverloadMain
2. {
3. public static void main(int a) //overloaded main method
4. {
5. System.out.println(a);
6. }
7. public static void main(String args[])
8. {
9. System.out.println("main method incoked");
10. main(6);
11. }
12. }
Output:
1. PrintStream obj.print("Hello");
But you cannot create the object to PrintStream class directly as above.
So, Java provides an alternative way to create the object of PrintStream
class that is System.out.
1. System.out.print();
Example
In the following example, we have used two print() methods, which gives
the result in one line. It means the first print() method displays the string
"Hello!" and retains the cursor at the same line. The second print() method
also displays the string "Java" at the same line adjacent to the previous
string.
1. class Demo
2. {
3. public static void main(String args[])
4. {
5. System.out.print("Hello!");
6. System.out.print("Java");
7. }
8. }
Output
Hello! Java
Java println() method
The println() method is similar to print() method except that it moves the
cursor to the next line after printing the result. It is used when you want
the result in two separate lines. It is called with "out" object.
If we want the result in two separate lines, then we should use the println()
method. It is also an overloaded method of PrintStream class. It throws
the cursor to the next line after displaying the result.
Example
The following example, the println() method display the string in two
separate lines.
1. class Demo
2. {
3. public static void main(String args[])
4. {
5. System.out.println("Hello!");
6. System.out.println("Java");
7. }
8. }
Output
Hello!
Java
Difference between print() and println() methods
Both methods are used to display the results on the monitor. The print()
method displays the result on the console and retains the cursor in the
same line. It works only with an argument. The println() method also
displays the result on the console but moves the cursor to the next line. It
can also work without arguments.
After writing your Java program, when you will try to compile it. Compiler will perform
some compilation operation on your program.
Once it is compiled successfully byte code(.class file) is generated by the compiler.
After compiling when you will try to run the byte code(.class file), the following steps are
performed at runtime:-
1. Class loader loads the java class. It is subsystem of JVM Java Virtual machine.
2. Byte Code verifier checks the code fragments for illegal codes that can violate access right
to the object.
3. Interpreter reads the byte code stream and then executes the instructions, step by step.
Q)In how many ways we can write a Java program?
There are many ways to write a Java program. The modifications that can
be done in a Java program are given below:
2) The subscript notation in the Java array can be used after type,
before the variable or after the variable.
Let's see the simple code of using var-args in the main() method. We will
learn about var-args later in the Java New Features chapter.
1. class A{
2. static public void main(String... args){
3. System.out.println("hello java4");
4. }
5. };
Valid Java main() method signature
1. public static void main(String[] args)
2. public static void main(String []args)
3. public static void main(String args[])
4. public static void main(String... args)
5. static public void main(String[] args)
6. public static final void main(String[] args)
7. final public static void main(String[] args)
8. final strictfp public static void main(String[] args)
Q) Can you save a Java source file by another name than the class name?
Yes, if the class is not public. It is explained in the figure given below:
Observe that, we have compiled the code with file name but running the
program with class name. Therefore, we can save a Java program other
than class name.
Q) Can you have multiple classes in a java source file?
Java Objects
An object in Java is a basic unit of Object-Oriented Programming and
represents real-life entities. Objects are the instances of a class that are
created to use the attributes and methods of a class.
An object consists of :
Java Constructors
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.
What are Constructors in Java?
In Java, 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 that is used to initialize the object. Every time an object is created
using the new() keyword, at least one constructor is called.
Pillar 2: Encapsulation
Encapsulation is the process of wrapping code and data together into a single
unit.
Real-Life Example:
A capsule which is mixed of several medicines. The medicines are hidden data
to the end user.
Pillar 3: Inheritance
Inheritance is the process of one class inheriting properties and methods from
another class in Java. Inheritance is used when we have is-a relationship
between objects. Inheritance in Java is implemented using extends keyword.
Real-life Example:
The planet Earth and Mars inherits the super class Solar System and Solar
system inherits the Milky Way Galaxy. So Milky Way Galaxy is the top super
class for Class Solar System, Earth and Mars.
Method Overloading –
Compile-time polymorphism can be achieved by method overloading in java.
When different functions in a class have the same name but different
signatures, it’s called method overloading.
Method Overriding –
Dynamic or Run-time Polymorphism occurs when the compiler is not able to
determine whether it’s superclass method or sub-class method it’s called run-
time polymorphism. The run-time polymorphism is achieved by method
overriding. When the superclass method is overridden in the subclass, it’s
called method overriding.
Composition-
Composition is a "belong-to" type of relationship in which one object is
logically related with other objects. It is also referred to as "has-
a" relationship.
Composition is a restricted form of Aggregation in which two entities (or you
can say classes) are highly dependent on each other. For e.g. Human and
Heart. A human needs heart to live and a heart needs a Human body to
survive.
We create a class College that contains variables, i.e., name and address. We
also create a class University that has a reference to refer to the list of
colleges. A University can have more than one collages. So, if a university is
permanently closed, then all colleges within that particular university will be
closed because colleges cannot exist without a university. The relationship
between the university and colleges is Composition.
Aggregation –
Aggregation is a special form of association. It is a relationship between two
classes like association, however its a directional association, which means it is
strictly a one way association. It represents a HAS-A relationship.
Why we need Aggregation?
To maintain code re-usability.