100% found this document useful (1 vote)
184 views20 pages

Java Notes

The document provides an overview of the Java programming language, including its history, features, basic syntax, and object-oriented programming concepts. It discusses how Java was developed by Sun Microsystems and originally named Oak, then renamed Java. It also summarizes Java's platform independence, security, and portability. Sample code demonstrates a simple Java program and explains key elements like classes, objects, and methods.

Uploaded by

raj k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (1 vote)
184 views20 pages

Java Notes

The document provides an overview of the Java programming language, including its history, features, basic syntax, and object-oriented programming concepts. It discusses how Java was developed by Sun Microsystems and originally named Oak, then renamed Java. It also summarizes Java's platform independence, security, and portability. Sample code demonstrates a simple Java program and explains key elements like classes, objects, and methods.

Uploaded by

raj k
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/ 20

Java notes

Raj
History of JAVA
JAVA is a distributed technology developed by James Gosling, Patric Naugton, etc., at Sun Micro
System has released lot of rules for JAVA and those rules are implemented by JavaSoft Inc, USA (which is
the software division of Sun Micro System) in the year 1990. The original name of JAVA is OAK (which is
a tree name). In the year 1995, OAK was revised and developed software called JAVA (which is a coffee
seed name). JAVA released to the market in three categories J2SE (JAVA 2 Standard Edition), J2EE (JAVA
2 Enterprise Edition) and J2ME (JAVA 2 Micro/Mobile Edition). i. J2SE is basically used for developing
client side applications/programs. ii. J2EE is used for developing server side applications/programs. iii.
J2ME is used for developing server side applications/programs. If you exchange the data between client
and server programs (J2SE and J2EE), by default JAVA is having on internal support with a protocol called
http. J2ME is used for developing mobile applications and lower/system level applications. To develop
J2ME applications we must use a protocol called WAP (Wireless Applications Protocol).

What is Java?
Java is a programming language and platform. Platform any hardware or software environment in which
a program runs known as platform. Since java has its own Runtime Environment (JRE) and API, it is called
as platform.

Features of Java:
There is given many features of java. They are also known as java buzzwords. The Java Features given
below are simple and easy to understand.
 Simple
 Object-Oriented
 Platform independent
 Secured
 Robust
 Portable
 Interpreted
 High Performance
 Multithreaded
 Distributed

Sample Program:
public class SampleProgram {

public static void main(String[] args) {


System.out.println("Hello world");
}
}

Output: Hello world

2
Understanding first java program
 class keyword is used to declare a class in java.
 public keyword is an access modifier which represents visibility, it means it is visible to all.
 static is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static method.
The main method is executed by the JVM, so it doesn't require creating object to invoke the
main method.
 void is the return type of the method, it means it doesn't return any value.
 main represents startup of the program.
 String[] args is used for command line argument.
 System.out.println() is used print statement.

Pre-requisites: For developing any java program, you need to


 Install the JDK if you don't have installed it
 Set path of the JDK/bin directory.

Variable
Variable is a name of memory location. (OR) A variable is an identifier whose value will be changed
during execution of the program.
Types of Variable:
There are three types of variables in java
 local variable
A variable that is declared inside the method is called local variable.
 instance variable
A variable that is declared inside the class but outside the method is called instance variable . It
is not declared as static.
 static variable
A variable that is declared as static is called static variable. It cannot be local.

class A {
int data = 50;// instance variable
static int m = 100;// static variable

void method() {
int n = 90;// local variable
}
}

Constant: Constant is an identifier whose value cannot be changed during execution of the program.
 In JAVA to make the identifiers are as constants, we use a keyword called final.
 Final is a keyword which is playing an important role in three levels. They are at variable level, at
method level and at class level.

3
 When we don’t want to change the value of the variable, then that variable must be declared as
final.
 When the final variable is initialized, no more modifications or assignments are possible
Example:
final int a =10; //valid
final int b;
b=20; //invalid
Datatypes
There are two types of datatypes in java, primitive and non-primitive.

Object Oriented Programming concepts:


Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

4
Object based programming language:
Object based programming language follows all the features of OOPs except Inheritance. JavaScript and
VBScript are examples of object based programming languages.

Class and Object:


Class: Class is a way of binding the data and associated methods in a single unit.
Object: Object is an instance of a class where as Class is a template or blueprint from which objects are
created. So object is the instance (result) of a class.
An object has three characteristics:
 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, 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 etc. known as its state. It is used to
write, so writing is its behavior.

class Room {
int l;// data member (also instance variable)
int w;// data member (also instance variable)

public static void main(String args[]) {


Room rm1 = new Room();// creating an object of Room
System.out.println(rm1.l);
System.out.println(rm1.w);

Room rm2 = new Room();// creating an object of Room


System.out.println(rm2.l);
System.out.println(rm2.w);

}
}

new: The new keyword is used to allocate memory at runtime. This new operator is known as dynamic
memory allocation operator.
Object gets the memory in Heap area and 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. Method gets the memory in Stack. All constants of JAVA program available in associative
memory.
Anonymous object
Anonymous simply means nameless. An object that has no reference is known as anonymous
object.
If you have to use an object only once, anonymous object is a good approach.
class Calculation {

void fact(int n) {

5
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
System.out.println("factorial is " + fact);
}

public static void main(String args[]) {


new Calculation().fact(5);// calling method with annonymous object
}
}

Creating multiple objects by one type only:


We can create multiple objects by one type only as we do in case of primitives.

Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects

Method overloading:
If a class has multiple methods by same name but different parameters, it is known as Method
Overloading. Method overloading increases the readability of the program.
There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
Example 1:
class Calc {
void sum(int a, int b) {
System.out.println(a + b);
}

void sum(int a, int b, int c) {


System.out.println(a + b + c);
}

public static void main(String args[]) {


Calc cc = new Calc();
cc.sum(10, 10);
cc.sum(10, 20, 30);
}
}

Example2:
class Room {
void area(int l, int b) {
System.out.println(l * b);
}

void area(double l, double b) {


System.out.println(l * b);
}

public static void main(String args[]) {

6
Room rm = new Room();
rm.area(20, 20);
rm.area(10.5, 10.5);
}
}

Constructor
A constructor is a special member method which will be called by the JVM implicitly
(automatically) for placing user/programmer defined values instead of placing default values.
Constructors are meant for initializing the object.
Rules for creating constructor:
There are basically two rules defined for the constructor.
 Constructor name must be same as its class name
 Constructor must have no explicit return type
 Constructors should not be static since constructors will be called each and every time
whenever an object is creating.
 Constructor should not be private provided an object of one class is created in another class
(constructor can be private provided an object of one class created in the same class).
 Constructors will not be inherited at all.
 Constructors are called automatically whenever an object is creating.
Types of constructors:
There are two types of constructors:
 default constructor is one which will not take any parameters (no-arg constructor)
 parameterized constructor
Example1:
A constructor that has no parameter is known as default constructor.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
class Bike {

Bike() {
System.out.println("Bike is created");
}

public static void main(String args[]) {


Bike b = new Bike();
}
}

If there is no constructor in a class, compiler automatically creates a default


constructor.

7
Example 2:
class Bike {

Bike(String name) {
System.out.println("Bike is created name is :" + name);
}

public static void main(String args[]) {


Bike b = new Bike("Honda");
}
}

Static block
The static keyword is used in java mainly for memory management. We may apply static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than
instance of the class.
The static can be:
 variable (also known as class variable)
 method (also known as class method)
 block
 nested class

Inheritance
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. The idea behind inheritance in java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods and fields of
parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship,
also known as Parent-Child relationship.

class Superclass-name{
//methods and fields
}
class Subclass-name extends Superclass-name{
//methods and fields
}

The keyword extends indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a
subclass.

class Employee1 {
float salary = 40000;
}

class Programmer extends Employee1 {


int bonus = 10000;

8
public static void main(String args[]) {
Programmer p = new Programmer();
System.out.println("Programmer salary is:" + p.salary);
System.out.println("Bonus of Programmer is:" + p.bonus);
}
}

Method overriding
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding. In other words, If subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as Method Overriding.
Advantage of Java Method Overriding:
 Method Overriding is used to provide specific implementation of a method that is already
provided by its super class.
 Method Overriding is used for Runtime Polymorphism
Rules for Method Overriding:
 method must have same name as in the parent class
 method must have same parameter as in the parent class.
 must be IS-A relationship (inheritance).

class Bank {
int getRateOfInterest() {
return 0;
}
}
class SBI extends Bank {
int getRateOfInterest() {
return 7;
}
}
class ICICI extends Bank {
int getRateOfInterest() {
return 8;
}
}

class Customer {
public static void main(String args[]) {
SBI s = new SBI();
ICICI i = new ICICI();
System.out.println("SBI Rate of Interest: " + s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: " + i.getRateOfInterest());
}
}

Static method cannot be overridden because static method is bound with class whereas instance method
is bound with object. Static belongs to class area and instance belongs to heap area.

9
Super
The super is a reference variable that is used to refer immediate parent class object. Whenever
you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super
reference variable.
Usage of super Keyword:
 super is used to refer immediate parent class instance variable.
 super() is used to invoke immediate parent class constructor.
 super is used to invoke immediate parent class method.

class Account {
public Account() {
System.out.println("opening an account");
}
}

class Savings extends Account {


public Savings() {
super();
System.out.println("specifying the savings a/c to opened account");
}
}

class Customer {
public static void main(String args[]) {
Savings s = new Savings();

}
}

super() is added in each class constructor automatically by compiler.

this
‘this’ is an internal or implicit object created by JAVA for two purposes. They are
 ‘this’ object is internally pointing to current class object.
 Whenever the formal parameters and data members of the class are similar, to differentiate the
data members of the class from formal parameters, the data members of class must be
proceeded by ‘this’.

Final
The final keyword in java is used to restrict the user. The final keyword can be used in many
contexts. Final can be:
 variable
If you make any variable as final, you cannot change the value of final variable (It will be
constant).
 Method
If you make any method as final, you cannot override it.

10
 Class
If you make any class as final, you cannot extend it.

final method is inherited but you cannot override it

Runtime polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time. In this process, an overridden
method is called through the reference variable of a superclass. The determination of the method to be
called is based on the object being referred to by the reference variable.
In the below example, we are creating two classes Bike and Splender. Splender class extends
Bike class and overrides its run() method. We are calling the run method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent class
method, subclass method is invoked at runtime. Since method invocation is determined by the JVM not
compiler, it is known as runtime polymorphism.

Upcasting:
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.

example:

class Bike {
void run() {
System.out.println("running");
}
}

class Splender extends Bike {


void run() {
System.out.println("running safely with 60km");
}

public static void main(String args[]) {


Bike b = new Splender();// upcasting
b.run();
}
}

// Output:running safely with 60km.

11
Run time polymorphism can’t be achieved by data members.
Example:
class Bike {
int speedlimit = 90;
}

class Honda3 extends Bike {


int speedlimit = 150;

public static void main(String args[]) {


Bike obj = new Honda3();
System.out.println(obj.speedlimit); // 90
}
}

Static Binding and Dynamic Binding


Connecting a method call to the method body is known as binding.
There are two types of binding:
 Static binding (also known as early binding)
When type of the object is determined at compiled time(by the compiler), it is known as static
binding. If there is any private, final or static method in a class, there is static binding.
 Dynamic binding (also known as late binding)
When type of the object is determined at run-time, it is known as dynamic binding.

Example of static binding:


class Dog {
private void eat() {
System.out.println("dog is eating...");
}
public static void main(String args[]) {
Dog d1 = new Dog();
d1.eat();
}
}

Example of Dynamic binding:


class Animal {
void eat() {
System.out.println("animal is eating...");
}
}
class Dog extends Animal {
void eat() {
System.out.println("dog is eating...");
}

public static void main(String args[]) {

12
Animal a = new Dog();
a.eat();
}
}
//output: dog is eating…
In the above example object type cannot be determined by the compiler, because the instance of Dog is
also an instance of Animal. So compiler doesn't know its type, only its base type.

Interface
An interface in java is a blueprint of a class. It has static constants and abstract methods only. The
interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the
java interface not method body. It is used to achieve fully abstraction and multiple inheritances in Java.
There are mainly three reasons to use interface.
1) It is used to achieve fully abstraction.
2) By interface, we can support the functionality of multiple inheritances.
3) It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and public, static and
final keywords before data members. In other words, Interface fields are public, static and final by
default, and methods are public and abstract.

interface Bank {
int countryCode = 5; Demo.java
void savingsAc();
}

interface Bank {
After compiling public static final int countryCode = 5; Demo.class
public abstract void savingsAc();
}

Sample example of Java Interface:


interface printable {
void print();
}

class Account implements printable {


public void print() {
System.out.println("Hello");
}

public static void main(String args[]) {


Account obj = new Account();
obj.print();
}
}

13
Packages:
A java package is a group of similar types of classes, interfaces and sub-packages. Package in
java can be categorized in two form, built-in package and user-defined package. There are many built-in
packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package:


1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

Example:
A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}

B.java
package mypack;

import pack.*;

class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
//output: Hello

Encapsulation
Encapsulation in java is a process of wrapping code and data together into a single unit, for example
capsule i.e. mixed of several medicines. We can create a fully encapsulated class in java by making all
the data members of the class private. Now we can use setter and getter methods to set and get the
data in it.
Advantage of Encapsulation in java:
 By providing only setter or getter method, you can make the class read-only or write-only.
 It provides you the control over the data. Suppose you want to set the value of id i.e. greater
than 100 only, you can write the logic inside the setter method.
Student.java
package com.school;

public class Student {


private String name;

14
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}
}

Test.java
package com.school;

public class Test {

public static void main(String[] args) {


Student s = new Student();
s.setName("vijay");
System.out.println(s.getName());
}
}
// output: Vijay

Access Modifiers
There are two types of modifiers in java: access modifiers and non-access modifiers. The access
modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
1) private
2) default
3) protected
4) public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient
etc.
private access modifier
The private access modifier is accessible only within class. If we access these private members from
outside the class, so there is compile time error. If any class constructor is private, you cannot create the
instance of that class from outside the class.

class A {
private int data = 40;

private A() {
System.out.println("In construcotr...");
}

private void msg() {


System.out.println("Hello java");
}
}

15
public class AccessMod {
public static void main(String args[]) {
A obj = new A(); //// Compile Time Error
System.out.println(obj.data);// Compile Time Error
obj.msg();// Compile Time Error
}
}

default access modifier


If you don't use any modifier, it is treated as default by default. The default modifier is accessible only
within package. In the below example, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.
A.java
package com.school;

class A {
void msg() {
System.out.println("Hello java");
}
}

AccessMod.java
package com.college;
import com.school;

public class AccessMod {


public static void main(String args[]) {
A obj = new A(); // // Compile Time Error
obj.msg();// Compile Time Error
}
}

protected access modifier


The protected access modifier is accessible within package and outside the package but through
inheritance only. The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
Example of protected access modifier:
In the below example, we have created the two packages college and school. The B class of college
package is public, so can be accessed from outside the package. But msg method of this package is
declared as protected, so it can be accessed from outside the class only through inheritance.

B.java
package com.college;

public class B {
protected void msg() {
System.out.println("Hello world");
}

16
}

AccessMod.java
package com.school;
import com.college.*;

class AccessMod extends B {


public static void main(String args[]) {
AccessMod obj = new AccessMod();
obj.msg();
}
}

public access modifier


The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier
B.java
package com.college;
public class B {
public void msg() {
System.out.println("Hello");
}
}

AccessMod.java
package com.school;
import com.college.*;

class AccessMod {
public static void main(String args[]) {
B obj = new B();
obj.msg();
}
}

Access Modifier within class within package outside package by outside package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Exception Handling
The exception handling in java is one of the powerful mechanisms to handle the runtime errors so that
normal flow of the application can be maintained.

17
What is exception?
Def 1: Exception is an abnormal condition. In java, exception is an event that disrupts the normal flow of
the program. It is an object which is thrown at runtime.

Def 2: An exception is an event that occurs during the execution of a program and disrupts the normal
flow of the program’s instructions.

What is exception handling?


Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote
etc.

Advantage of Exception Handling:


The core advantage of exception handling is to maintain the normal flow of the application. Exception
normally disrupts the normal flow of the application that is why we use exception handling.

Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun Microsystems says there are three types of exceptions:
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as checked
exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Exception handling keywords:


 try
 catch
 finally
 throw
 throws

Try block
Enclose the code that might throw an exception in try block. It must be used within the method and
must be followed by either catch or finally block.
Syntax 1:
Catch block is used to handle the Exception. It must be used after the try block.

18
try{
........
........
}catch(exception_class_name reference){
........
........
}
Syntax 2:
The finally block is a block that is always executed. It is mainly used to perform some important tasks
such as closing connection, stream etc.
try{
........
........
}finally {
........
........
}
Note: finally must be followed by try or catch block.

throw
The throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked
exception. The throw keyword is mainly used to throw custom exception
public class Testing {

static void validate(int age) {


if (age > 18) {
System.out.println("eligible for voting");
} else {
throw new ArithmeticException("not valid");
}
}

public static void main(String[] args) {


validate(15);
}
}
//output: Exception in thread "main" java.lang.ArithmeticException: not valid

throws
This is the keyword which gives an indication to the calling function to keep the called function under try
and catch blocks.
Example 1:
class Testing1 {
public void div(String s1, String s2) throws ArithmeticException,
NumberFormatException {
int n1 = Integer.parseInt(s1);

19
int n2 = Integer.parseInt(s2);
int n3 = n1 / n2;
System.out.println("DIVISOIN = " + n3);
}
}

class Testing {
public static void main(String[] args) {
try {
String s1 = args[0];
String s2 = args[1];
Testing1 eo = new Testing1();
eo.div(s1, s2);
} catch (ArithmeticException Ae) {
System.out.println("DONT ENTER ZERO FOR DENOMINATOR");
} catch (NumberFormatException Nfe) {
System.out.println("PASS INTEGER VALUES ONLY");
} catch (ArrayIndexOutOfBoundsException Aioobe) {
System.out.println("PASS VALUES FROM COMMAND PROMPT");
}
}
};

// output: PASS VALUES FROM COMMAND PROMPT

Example 2:
import java.io.IOException;

public class Testing {

void m() throws IOException {


throw new IOException("device error...");
}

void n() throws IOException {


m();
}

void p() {
try {
n();
} catch (Exception e) {
System.out.println("exception handled");
}
}

public static void main(String[] args) {


Testing t = new Testing();
t.p();
}
}

//output: exception handled

20

You might also like