0% found this document useful (0 votes)
56 views31 pages

My Java Notes Basic

- Java is a programming language and platform that is robust, object-oriented, and secure. It was developed by James Gosling at Sun Microsystems in 1991 and took 18 months to develop the first working version. - There are four main platforms or editions of Java: Java SE (Standard Edition), Java EE (Enterprise Edition), Java ME (Micro Edition), and JavaFX. Java SE includes core Java APIs, Java EE is for enterprise applications, Java ME is for embedded and mobile devices, and JavaFX is for rich internet applications. - Java can be used to create many types of applications including desktop applications, web applications, mobile applications, and enterprise applications. It has features like being simple,

Uploaded by

Divya Pawar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
56 views31 pages

My Java Notes Basic

- Java is a programming language and platform that is robust, object-oriented, and secure. It was developed by James Gosling at Sun Microsystems in 1991 and took 18 months to develop the first working version. - There are four main platforms or editions of Java: Java SE (Standard Edition), Java EE (Enterprise Edition), Java ME (Micro Edition), and JavaFX. Java SE includes core Java APIs, Java EE is for enterprise applications, Java ME is for embedded and mobile devices, and JavaFX is for rich internet applications. - Java can be used to create many types of applications including desktop applications, web applications, mobile applications, and enterprise applications. It has features like being simple,

Uploaded by

Divya Pawar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 31

1.

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.

Java is a platform-independent language because it has runtime environment i.e JRE


and API. Here platform means a hardware or software environment in which an
application runs.

2.Java Platforms / Editions


Java Editions or we can say the platform is a collection of programs which helps to
develop and run the programs that are written in Java Programming language. Java
Editions includes execution engine, compiler and set of libraries. As Java is Platform
independent language so it is not specific to any processor or operating system.

There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)


It includes Java programming APIs such as java.lang, java.io, java.net, java.util,
java.sql, java.math etc. It includes core topics like OOPs, String, Exception, Inner
classes, Multithreading, Networking, AWT, Swing, Collection, etc.
2) Java EE (Java Enterprise Edition)

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.

Example: e-commerce, accounting, banking information systems.


3) Java ME (Java Micro Edition)
Java Micro Edition is used for the development and deployment of portable codes
for the embedded and mobile devices .

Example: micro-controllers, sensors, gateways, mobile phones, printers etc.

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.

Q)New Features of JAVA 8


Below mentioned are some of the core upgrades done as a part of Java 8 release.

 Enhanced Productivity by providing Optional Classes feature, Lamda Expressions, Streams


etc.

 Ease of Use

 Improved Polyglot programming. A ploygot is a program or script, written in a form which


is valid in multiple programming languages and it performs the same operations in multiple
programming languages. So Java now supports such type of programming technique.

 Improved Security and performance

 New Collection Package java.util.stream to provide Stream API.

 Parallel Array Sorting

 The JDBC-ODBC Bridge has been removed etc

Q) What is JVM?

Java virtual Machine(JVM) is a virtual Machine It is called a virtual machine


because it doesn't physically exist. It is provides runtime environment to
execute java byte code. The JVM doesn't understand Java typo, that's why you
compile your *.java files to obtain *.class files that contain the bytecodes
understandable by the 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

The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

What is JVM
It is:

o A specification where working of Java Virtual Machine is specified.


o An implementation Its implementation is known as JRE (Java Runtime
Environment).
o Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created.

Q) JVM Architecture

1) Classloader

Classloader is a subsystem of JVM which is used to load class files.


Whenever we run the java program, it is loaded first by the classloader.
There are three built-in classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the


super class of Extension classloader. It loads the rt.jar file which
contains all class files of Java Standard Edition like java.lang package
classes, java.net package classes, java.util package classes, java.io
package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap
and parent classloader of System classloader. It loades the jar files
located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of
Extension classloader. It loads the classfiles from classpath.

2)Method area : Stores pre-class structure as constant pool.

3) Heap It is the runtime data area in which objects are allocated.

4)Stack : Local variables and partial results are store here. Each thread has
a private JVM stack created when the thread is created.

5) Program Counter Register PC (program counter) register contains the


address of the Java virtual machine instruction currently being executed.

7)Executive Engine : Execution engine controls the execute of


instructions contained in the methods of the classes.

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.

8)Native Method Interface : Native method interface gives an interface


between java code and native code during execution.

9)Native Method Libraries : Native Libraries consist of files required for


the execution of native code.

Q) Difference between JDK, JRE, and JVM

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

Compilation Flow:When we compile Java program using javac tool, the


Java compiler converts the source code into byte code.

class Hello
{
public static void main(String[] args)
{
System.out.println ("Hello World program");
}
}
Parameters used in First Java Program

class : class kyword is used to declare classes in Java

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.

static : static is again a keyword used to make a function static. To execute a


static function you do not have to create an Object of the class. The main() method
here is called by JVM, without creating any object for class.

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.

What happens if the main() method is written without String args[]?

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

So the main() method should always be written as:

1. public static void main(String args[])

We can interchange public and static and write it as follows:

1. static public void main(String args[])

We can also use the different name for the String type array and write it
as:

1. static public void main(String[] x)

Different ways of writing main() method are:

1. static public void main(String []x)


2. static public void main(String...args)

String...args: It allows the method to accept zero or multiple arguments.


There should be exactly three dots between String and array; otherwise, it
gives an error.

Example

A program that has no main() method, but compile and runs successfully.

1. abstract class DemoNoMain extends javafx.application.Application


2. {
3. static //static block
4. {
5. System.out.println("Java");
6. System.exit(0);
7. }
8. }
Output:

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:

main method invoked


6

System.out.println : In Java, System.out.println() is a statement which prints


the argument passed to it. The println() method display results on the
monitor
is used to print statement. Here, System is a class, out is an object of the PrintStream
class, println() is a method of the PrintStream class.

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.

Where System is the class name, it is declared as final. The out is an


instance of the System class and is of type PrintStream. Its access specifiers
are public and final. It is an instance of java.io.PrintStream. When we call
the member, a PrintStream class object creates internally.

So, we can call the print() method, as shown below:

1. System.out.print();

It creates the PrintStream class object. This object, by default, represents


the output device, i.e., the monitor.

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.

Now let us see What happens at Runtime

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:

1) By changing the sequence of the modifiers, method prototype is


not changed in Java.

Let's see the simple code of the main method.

1. static public void main(String args[])

2) The subscript notation in the Java array can be used after type,
before the variable or after the variable.

Let's see the different codes to write the main method.

1. public static void main(String[] args)


2. public static void main(String []args)
3. public static void main(String args[])

3) You can provide var-args support to the main() method by passing


3 ellipses (dots)

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. public static void main(String... args)

4) Having a semicolon at the end of class is optional in Java.

Let's see the simple code.

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)

Invalid Java main() method signature


1. public void main(String[] args)
2. static void main(String[] args)
3. public void static main(String[] args)
4. abstract 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:

To compile: javac Hard.java


To execute: java Simple

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?

Yes, like the figure given below illustrates:


Java Classes –
A class in Java is a set of objects which shares common characteristics/
behavior and common properties/ attributes. It is a user-defined blueprint or
prototype from which objects are created. For example, Student is a class
while a particular student named Ravi is an object.
Properties of Java Classes –
Class is not a real-world entity. It is just a template or blueprint or prototype
from which objects are created.
Class does not occupy memory.
Class is a group of variables of different data types and a group of methods.
A Class in Java can contain:
Data member
Method
Constructor
Nested Class
Interface

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 :

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


of an object.
Behavior: It is represented by the methods of an object. It also reflects the
response of an object with other objects.
Identity: It gives a unique name to an object and enables one object to interact
with other objects.
Method Declaration –
In general, method declarations have 6 components:
1. Modifier: It defines the access type of the method i.e. from where it can
be accessed in your application. In Java, there 4 types of access
specifiers.
public: It is accessible in all classes in your application.
protected: It is accessible within the class in which it is defined and in its
subclass
private: It is accessible only within the class in which it is defined.
default: It is declared/defined without using any modifier. It is accessible
within the same class and package within which its class is defined.
Access Modifiers in Java
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
Default – No keyword required
Private
Protected
Public

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.

How Java Constructors are Different From Java Methods?


Constructors must have the same name as the class within which it is defined it
is not necessary for the method in Java.
Constructors do not return any type while method(s) have the return type
or void if does not return any value.
Constructors are called only once at the time of Object creation while
method(s) can be called any number of times.
Types of Constructors in Java
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A
default constructor is invisible. And if we write a constructor with no
arguments, the compiler does not create a default constructor.
2. Parameterized Constructor in Java
A constructor that has parameters is known as parameterized constructor. If
we want to initialize fields of the class with our own values, then use a
parameterized constructor.
3. Copy Constructor in Java
Unlike other constructors copy constructor is passed with another object
which copies the data available from the passed object to the newly created
object.
Four Main Object Oriented Programming Concepts of Java
These concepts aim to implement real-world entities in programs.
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Abstraction is a process of hiding implementation details and exposes only the
functionality to the user. In abstraction, we deal with ideas and not events.
This means the user will only know “what it does” rather than “how it does”.
There are two ways to achieve abstraction in Java
Abstract class (0 to 100%)
Interface (100%)
Real-Life Example: A driver will focus on the car functionality (Start/Stop ->
Accelerate/ Break), he/she does not bother about how the Accelerate/ brake
mechanism works internally. And this is how the abstraction works.

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.

Why Do We Need Java Inheritance?


Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
Method Overriding: Method Overriding is achievable only through Inheritance.
It is one of the ways by which Java achieves Run Time Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all
details is achieved through inheritance. Abstraction only shows the
functionality to the user.

Java Inheritance Types


Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
Pillar 4: Polymorphism in java
Polymorphism is the ability to perform many things in many ways. The word
Polymorphism is from two different Greek words- poly and morphs. “Poly”
means many, and “Morphs” means forms.
Real-life Example:
A delivery person delivers items to the user. If it’s a postman he will deliver the
letters. If it’s a food delivery boy he will deliver the foods to the user. Like this
polymorphism implemented different ways for the delivery function.
There are two types of polymorphism as listed below:
1. Static or Compile-time Polymorphism(method overloading)
2. Dynamic or Run-time Polymorphism(method overriding)

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.

You might also like