0% found this document useful (0 votes)
5 views19 pages

Java Notes

Uploaded by

maanviverma516
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views19 pages

Java Notes

Uploaded by

maanviverma516
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Java

 Currently, Java is being used in Internet programming, e-business solutions, mobile


devices, games, etc.
 Introduced by James Gosling in 1991. The small team of Sun engineers was called Green
Team.
 Originally designed was small, embedded systems in electronic appliances like set-top
boxes.
 Firstly, it was called “Greentalk” by James Gosling
 After that , it was called Oak.
Why Oak for Java Language?
1. Oak is a symbol of strength and chosen as a national tree in many countries like
France, USA, Romania, Germany, etc.
2. In 1995, Oak was renamed as Java because it was already a trademark for Oak
technologies.
Why Java name for Java language?
 Java is an island of Indonesia where first coffee was produced.
 Originally released by James Gosling at Sun Microsystems in 1995.
 In 1995, Time Magazine called Java as one of the Ten Best Products of 1995.
 The team gathered to choose a new name. The suggested words were Silk,
dynamic, revolutionary, DNA, etc. But Java was unique.

Some of the applications of Java are:


1) Desktop-based applications like acrobat reader, antivirus, media player, etc.
2) Smart cards
3) Robotics
4) Games
5) Web applications
6) Enterprise applications
7) Mobile, etc.

Characteristics of Java:
1. Simple
2. Portable
3. Object-oriented
4. Secure: Java doesn't support pointer explicitly, But Java uses pointer implicitly.
Java is used in a networked and distributed environment. The following features make Java
a secure language:

 No use of explicit pointers


 Java Program runs inside a virtual sandbox (Java Virtual Machine or JVM).
 Classloader: The Java Runtime Environment (JRE) includes a classloader that is used
to dynamically load Java classes into the Java Virtual Machine. It improves security
by isolating the package for local file system classes from those imported from
network sources.
 Byte code verifier
 Security Manager: It determines the resources a class has access to, such as reading
and writing to the local disc.
5. Platform independent: If we use pointers the address of the variable varies in different
machines. Thus using pointers becomes invalid and provides different result in different
machine.
6. Robust- Java use strong memory management. Lack of pointers that avoid security
problem. Automatic garbage collection. Exception handling and type checking
7. Dynamic
8. Interpreted
9. High performance: Java’s performance and efficiency are remarkable since byte codes
are very close to machine code. However, it is still slower than languages like C++ which
are compiled. The fundamental reason is that Java applications, unlike C and C++
programs, run on a Java virtual machine (JVM) after compiling rather than directly on
the computer’s CPU as native code.
10. Architectural Neutral: In C programming, the int data type takes up two bytes in 32-bit
architecture and four bytes in 64-bit architecture. In Java, however, it takes up 4 bytes
of memory on both 32-bit and 64-bit architectures
11. Distributed- We can create distributed applications in Java. EJB are used for creating
distributed applications. We can access the files by calling the methods from any
machine on internet. Distributed computing involves the collaboration of multiple
computers over a network. Java was created with the goal of making distributed
computing simple. Because networking is inherent in Java, developing network
programs is as simple as sending and receiving data to and from a file.
12. Multithreaded- A thread is like a separate program executing concurrently. We can
write Java programs that can deal multiple tasks at once by creating multiple threads.
Threads share memory. Important in multimedia and web applications. For example,
while surfing the web, a user can listen to an audio recording. A server can serve many
clients at the same time in network programming. Similarly, there are a lot of things
going on in GUI programming at the same time. These simultaneous processes can be
implemented in Java through multi-threading.
 Java is not considered a pure object-oriented programming language.
 The main reason is it supports primitive type values. For an object-oriented programming
language, data should be represented in the form of objects. As Java uses primitive data
types, it is not considered a pure object-oriented programming language.
 It supports the use of the static keyword. Static variables and methods can be accessed
without an object or without creating an object of a class.
According to Sun, Java removed many features of C++ like operator overloading, explicit
pointers, etc.
Introduced Garbage Collector
Java code can run on multiple platforms. Its code is compiled and converted into bytecode
which is platform independent, i.e., Write Once and Run Anywhere (WORA).

JVM (Java Virtual Machine) Architecture

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
The JVM performs following operation:

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

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

JVM is the one that actually calls the main method present in a Java code. JVM is a part of
JRE(Java Runtime Environment). When we compile a .java file, .class files(contains byte-code)
with the same class names present in .java file are generated by the Java compiler.
This .class file goes into various steps when we run it. These steps together describe the
whole JVM.

1. Classloader

Classloader is a subsystem of JVM which is used to load class files. It is mainly responsible for
three activities.

 Loading
 Linking
 Initialization
Loading: The Class loader reads the “.class” file, generate the corresponding binary data and
save it in the method area. After loading the “.class” file, JVM creates an object of type Class
to represent this file in the heap memory. Please note that this object is of type Class
predefined in java.lang package. These Class object can be used by the programmer for
getting class level information like the name of the class, parent name, methods and variable
information etc. To get this object reference we can use getClass() method of Object class.
Linking: Performs verification, preparation, and (optionally) resolution.

 Verification: It ensures the correctness of the .class file i.e. it checks whether this file is
properly formatted and generated by a valid compiler or not. If verification fails, we get
run-time exception java.lang.VerifyError. This activity is done by the component
ByteCodeVerifier. Once this activity is completed then the class file is ready for
compilation.
 Preparation: JVM allocates memory for class static variables and initializing the memory to
default values.
 Resolution: It is the process of replacing symbolic references from the type with direct
references. It is done by searching into the method area to locate the referenced entity.
Initialization: In this phase, all static variables are assigned with their values defined in the
code and static block. This is executed from top to bottom in a class and from parent to child
in the class hierarchy.

JVM Memory
1. Method area: In the method area, all class level information like class name, immediate
parent class name, methods and variables information etc. are stored, including static
variables. There is only one method area per JVM, and it is a shared resource.
2. Heap area: Information of all objects is stored in the heap area. There is also one Heap
Area per JVM. It is also a shared resource.
4. Stack area: For every thread, JVM creates one run-time stack which is stored here. Every
block of this stack is called activation record/stack frame which stores methods calls. All
local variables of that method are stored in their corresponding frame. After a thread
terminates, its run-time stack will be destroyed by JVM.
5. PC Registers: Store address of current execution instruction of a thread. Obviously, each
thread has separate PC Registers.
5. Native method stacks: For every thread, a separate native stack is created. It stores native
method information.

Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses
data and information present in various memory area and executes instructions. It can be
classified into three parts:
 Interpreter: It interprets the bytecode line by line and then executes. The disadvantage
here is that when one method is called multiple times, every time interpretation is
required.
 Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It
compiles the entire bytecode and changes it to native code so whenever the interpreter
sees repeated method calls, JIT provides direct native code for that part so re-
interpretation is not required, thus efficiency is improved.
 Garbage Collector: It destroys un-referenced objects.

Native Method Libraries :


It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.

Java Variables:
1. Local variables: Variables declared inside the body of a method
2. Instance variables: Variables declared inside the class but outside the body of
method.
3. Static variable: Variable declared as static. It cannot be local. They are allocated
memory only one time when the class is loaded.

Java Tokens
1. Keywords
2. Identifiers
3. Constants/Literals
4. Special Symbols: [] () {}, ; * =
5. Operators
6. Comments
7. Separators

1.Keywords:
abstract assert boolean
break byte case
catch char class
const continue default
do double else
enum exports extends
final finally float
for goto if
implements import instanceof
int interface long
module native new
open opens package
private protected provides
public requires return
short static strictfp
super switch synchronized
this throw throws
to transient transitive
try uses void
volatile while with

1. Constants: Constants are also like normal variables. But the only difference is, their
values cannot be modified by the program once they are defined. Constants refer to
fixed values.
final int PI = 3.14; //Here final keyword is used to define the constant PI
2. Operators:
 Arithmetic Operators
 Unary Operators
 Assignment Operator
 Relational Operators
 Logical Operators
 Ternary Operator: variable = Expression1 ? Expression2: Expression3
 Bitwise Operators
 Shift Operators
 instance of operator
 Precedence and Associativity

instanceof Keyword in Java

// Java Program to Illustrate instanceof Keyword


// Importing required I/O classes
import java.io.*;

// Main class
class ABC {
public static void main(String[] args)
{
// Creating object of class inside main()
ABC object = new ABC();
// Returning instanceof
System.out.println(object instanceof ABC);
}
}
Output
true

// Java program to demonstrate working of instanceof Keyword

// Class 1
// Parent class
class Parent {
}

// Class 2
// Child class
class Child extends Parent {
}

// Class 3
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{

// Creating object of child class


Child cobj = new Child();

// A simple case
if (cobj instanceof Child)
System.out.println("cobj is instance of Child");
else
System.out.println("cobj is NOT instance of Child");

// instanceof returning true for Parent class also


if (cobj instanceof Parent)
System.out.println("cobj is instance of Parent");
else
System.out.println("cobj is NOT instance of Parent");

// instanceof returns true for all ancestors

// Note : Object is ancestor of all classes in Java


if (cobj instanceof Object)
System.out.println("cobj is instance of Object");
else
System.out.println("cobj is NOT instance of Object");
}
}
Output
cobj is instance of Child
cobj is instance of Parent
cobj is instance of Object

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance


variable.
We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class Test{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
class Animal{
void eat( ){
System.out.println("eating...");
}
}
class Dog extends Animal{
void eat( ){
System.out.println("eating bread...");
}
void bark( ){
System.out.println("barking...");
}
void work( ){
super.eat( );
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}
}

Output:

eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local. To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
class Animal{
Animal( ){
System.out.println("animal is created");
}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}
}

Output:

animal is created
dog is created
As we know well that default constructor is provided by compiler automatically if there is no
constructor. But, it also adds super( ) as the first statement.

Another example of super keyword where super( ) is provided by the compiler implicitly.

class Animal{
Animal ( ){
System.out.println("animal is created");
}
}
class Dog extends Animal{
Dog( ){
System.out.println("dog is created");
}
}
class TestSuper{
public static void main(String args[ ]){
Dog d=new Dog( );
}}

Output:
animal is created
dog is created

Creating a Multilevel Inheritance Hierarchy


in Java
Example
class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {
void funcB() {
System.out.println("This is class B");
}
}
class C extends B {
void funcC() {
System.out.println("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC();
}
}

Output
This is class A
This is class B
This is class C

Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";
The java.lang.String class is used to create a string object.

Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't
exist in the pool, a new string instance is created and placed in the pool. For example:

1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

Why Java uses the concept of String literal?

To make Java more memory efficient (because no new objects are created if it exists already in
the string constant pool).

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
A String in Java that is specified as immutable

import java.io.*;

class ABC {
public static void main(String[ ] args)
{
String s1 = "java";
s1.concat(" rules");

// Yes, s1 still refers to "java"


System.out.println("s1 refers to " + s1);
}
}
Output
s1 refers to java

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

An abstract class is a class that is declared abstract —it may or may not include abstract
methods. Abstract classes cannot be instantiated, but they can be subclassed. When an
abstract class is subclassed, the subclass usually provides implementations for all of the
abstract methods in its parent class.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an
abstract method.

1. abstract void print( );//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
abstract class Bike{
abstract void run( );
}
class Honda extends Bike{
void run(){
System.out.println("running safely");
}
public static void main(String args[ ]){
Bike obj = new Honda();
obj.run();
}
}
Any class that contains one or more abstract methods must also be declared abstract. To declare a class
abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class
declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator. Such objects would be useless, because an abstract class is not fully
defined. Also, you cannot declare abstract constructors, or abstract static methods.

Using final with Inheritance


The keyword final has three uses. First, it can be used to create the equivalent of a named constant. The
other two uses of final apply to inheritance.

Using final to Prevent Overriding While method overriding is one of Java’s most powerful features,
there will be times when you will want to prevent it from occurring. To disallow a method from being
overridden, specify final as a modifier at the start of its declaration.

Methods declared as final cannot be overridden.

class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() {
// ERROR! Can't override.
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time
error will result.

Using final to Prevent Inheritance

Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final, too.

Here is an example of a final class:

final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}

Package in Java is a mechanism to encapsulate a group of classes, sub packages and


interfaces. Packages are used for:
 Preventing naming conflicts. For example there can be two classes with name Employee in
two packages, college.staff.cse.Employee and college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces, enumerations and annotations
easier
 Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A
default member (without any access specifier) is accessible by classes in the same package
only.
 Packages can be considered as data encapsulation (or data-hiding).
A package is a container of a group of related classes where some of the classes are accessible
are exposed and others are kept for internal purpose.

How packages work?


Package names and directory structure are closely related. For example if a package name
is college.staff.cse, then there are three directories, college, staff and cse such that cse is
present in staff and staff is present inside college. Also, the directory college is accessible
through CLASSPATH variable.
Using interface, you can specify a set of methods that can be implemented by one or more
classes. The interface, itself, does not actually define any implementation. Although they are
similar to abstract classes, interfaces have an additional capability: A class can implement more
than one interface.
You can define classes inside a package that are not accessible by code outside that package.
You can also define class members that are only exposed to other members of the same package
Package naming conventions : Packages are named in reverse order of domain names

Subpackages: Packages that are inside another package are the subpackages. These are not
imported by default, they have to imported explicitly.

xample :
import java.util.*;
util is a subpackage created inside java package.

This is the general form of the package statement:


package pkg;
The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
package java.awt.image;
Accessing classes inside a package
Consider following two statements :
// import the Vector class from util package.
import java.util.vector;

// import all the classes from util package


import java.util.*;
// All the classes and interfaces of this package
// will be accessible but not subpackages.
import package.*;

// Only mentioned class of this package will be accessible.


import package.classname;

// Class name is generally used when two packages have the same
// class name. For example in below code both packages have
// date class so using a fully qualified name to avoid conflict
import java.util.Date;
import my.package.Date;
Access Protection
Access to a private member of a class is granted only to other members of that class. Packages
add another dimension to access control. As you will see, Java provides many levels of
protection to allow fine-grained control over the visibility of variables and methods within
classes, subclasses, and packages. Classes and packages are both means of encapsulating and
containing the name space and scope of variables and methods. Packages act as containers for
classes and other subordinate packages. Classes act as containers for data and code. The class is
Java’s smallest unit of abstraction.
Java addresses four categories of visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways to produce
the many levels of access required by these categories.
Anything declared public can be accessed from anywhere.
Anything declared private cannot be seen outside of its class. When a member does not have
an explicit access specification, it is visible to subclasses as well as to other classes in the same
package. This is the default access. If you want to allow an element to be seen outside your
current package, but only to classes that subclass your class directly, then declare that element
protected.

You might also like