Core Java
Java Version 8
What is Java?
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented programming
language.
Java is guaranteed to be Write Once, Run Anywhere
Where it is used?
Web Applications.
Enterprise Applications such as banking applications.
Mobile Applications
Embedded System
Smart Card
Robotics
Games etc.
History of Java
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java
language project in June 1991. The small team of sun engineers called Green
Team.
Originally designed for small, embedded systems in electronic appliances like
set-top boxes.
Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
After that, it was called Oak and was developed as a part of the Green project.
In 1995, Oak was renamed as "Java" because it was already a trademark by
Oak Technologies.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" and
Java etc
According to James Gosling "Java was one of the top choices along with Silk".
Since java was so unique, most of the team members preferred java.
JDK 1.0 released in(January 23, 1996).
Java Version History
JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan, 1996)
JDK 1.1 (19th Feb, 1997)
J2SE 1.2 (8th Dec, 1998)
J2SE 1.3 (8th May, 2000)
J2SE 1.4 (6th Feb, 2002)
J2SE 5.0 (30th Sep, 2004)
Java SE 6 (11th Dec, 2006)
Java SE 7 (28th July, 2011)
Java SE 8 (18th March, 2014)
Java Features
Simple: Java is designed to be easy to learn.
Object Oriented: In Java, everything is an Object.
Platform independent: Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by virtual Machine (JVM) on
whichever platform it is being run.
Secure: With Java's secure feature, it enables to develop virus-free, tamper free
systems. Authentication techniques are based on public-key encryption.
Architectural-neutral: Java compiler generates an architecture-neutral object
file format, which makes the compiled code to be executable on many
processors, with the presence of Java runtime system.
Multithreaded: With Java's multithreaded feature, it is possible to write programs
that can do many tasks simultaneously
Java Development Environmen
The Java development environment has two parts
–a Java compiler
–a Java interpreter
Software & Hardware Requirements
Pentium 200-MHz computer with a minimum of 64 MB of RAM.
Linux 7.1 or Windows 95/98/2000/XP/Windows 7/ Windows 8 operating
system.
Java JDK 8
Java Editor
What is Next?
Where you can obtain Java?
http://www.oracle.com/us/downloads/index.html
Where you can obtain Java Documentation?
http://docs.oracle.com/javase/8/docs/api/
How to install Java?
Run the .exe to install Java on your machine.
How to prepare an environment to develop Java applications?
Java Environment Setup
Setting up the path for windows
Assuming you have installed Java in C:\Program Files\java\jdkdirectory.
Right-click on 'My Computer' and select 'Properties‘
Click on the 'Environment variables' button under the 'Advanced' tab.
Add a New entry called “JAVA_HOME”
Now, alter the 'Path' variable so that it also contains the path to the Java
executable.
Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32',
then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Environment Setup Contd……
Setting up the path for Linux, UNIX, Solaris, FreeBSD
Environment variable PATH should be set to point to where the Java binaries
have been installed.
Example, if you use bash as your shell, then you would add the following line to
the end of your '.bashrc:
export PATH=/path/to/java:$PATH'
Popular Java Editors
Notepad
TextPad
Netbeans
Intellij
Eclipse
JDeveloper
How to Check Java is installed properly
Java Basic
Object-Objects have states and behaviours. –Example: A dog has states-color,
name, breed as well as behaviours -wagging, barking, eating. –An object is an
instance of a class.
Class-A class can be defined as a blue print that describes the
behaviours/states that object of its type support.
Methods-A method is basically a behaviour. A class can contain many
methods. It is in methods where the logics are written, data is manipulated and
all the actions are executed.
Instance Variables -Each object has its unique set of instance variables.
Structure of the Java Program
Save & Compile
Save your program as “className.java”
Compile the Java Program by using the following command in the
command prompt window
javac className.java
Run the Java Program by using the following Command in the command
prompt.
java className
Example
Steps..
Open notepad and add the code as above.
Save the file as: MyFirstJavaProgram.java
Open a command prompt window and go o the directory where you
saved the class.
–Assume it's C:\
Type ' javac MyFirstJavaProgram.java ' and press enter to compile your
code.
Now, type ' java MyFirstJavaProgram' to run your program.
It is very important to keep in mind the following points.
Case Sensitivity
Java is case sensitive, which means identifier Hello and hello would have different
meaning in Java.
Class Names
For all class names, the first letter should be in Upper Case.
It can be a Camel Case, if several words are used to form a name of the class
Example class MyFirstJavaClass.java
Method Names
All method names should start with a Lower Case letter
If several words are used to form the name of the method, then each inner
word's first letter should be in Upper Case.
Example public void myMethodName()
Program File Name
Name of the program file should exactly match the class name.
public static void main(String args[])
Java program processing starts from the main() method, which is a mandatory part of
every Java program
Java Identifiers
All Java components require names
Names used for classes, variables and methods are called identifiers
Points to be remembered about Identifiers
All identifiers should begin with a letter (A to Z or a to z), currency character
($) or an underscore (_).
–Examples of legalidentifiers: age, $salary, _value, __1_value –Examples of
illegalidentifiers: 123abc, -salary
After the first character, identifiers can have any combination of characters
A keyword cannot be used as an identifier.
Most importantly identifiers are case sensitive.
Java Modifiers
There are two categories of modifiers. –
Access Modifiers
default
public
protected
private
Non-access Modifiers
final
abstract
strictfp
Note : We will be looking into more details about modifiers in the later section
Java Variables
Local Variables –
Variables defined inside methods, constructors or blocks are called local variables.
The variable will be declared and initialized within the method.
These variables will be destroyed when the method has completed.
Class Variables (Static Variables)
Class variables are variables declared within a class, outside any method, with the static keyword.
Instance Variables (Non-static variables)
Instance variables are variables declared within a class but outside any method.
These variables are instantiated when the class is loaded.
Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Java Data Type & Keywords
Comments in Java
Java Object & Classes
What is Object?
An object is an instance of a class.
Real world example for Objects
Car
Dogs
Humans
Tree
All these objects have a state and behaviour
Objects have states and behaviours
Example: A dog has states-color, name, breed as well as behaviours -wagging,
barking, eating
What is class?
A class is a blue print from which individual objects are created.
A class can contain any of the following variable types
Local variables: Variables defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any
method. These variables are instantiated when the class is loaded. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Class variables: Class variables are variables declared within a class, outside any
method, with the static keyword.
Java Arrays
Arrays are objects that store multiple variables of the same type.
An array itself is an object
Java Literals
Escape Sequence
Operators
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Arithmetic Operators
Arithmetic operators are used in mathematical expressions.
Assume integer variable A holds 10 and variable B holds 20, then:
The Relational Operators
The Logical Operators
Assume Boolean variables A holds true and variable B holds false, then:
The Assignment Operators
Misc Operators
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator.
variable x = (expression) ? value if true : value if false
Int a , b; a = 10;
b = (a == 1) ? 20: 30;
Result : b holds the value as 30.
Instanceof Operator
Details will be provided later sections
Flow Control
The if-then and if-then-else Statements
The switch Statement
The while and do-while Statements
The for Statement
Branching Statements
If Statement
If then Else statement
Switch Statement
While Statement
Do --While Statement
The for Statement
Branching Statements
The break Statement
The continue Statement
The return Statement
Break Statement
Continue Statement
The return Statement
Java Package
Steps…..
Assume your root folder is C:\javaproject
Your java classes should be moved to corresponding package folder name
Dog.java class should be moved into the following folder
C:\javaproject\com\org\animal
How to compile the classes inside in the package
Go to Root folder say C:\javaproject
C:\javaproject > javac com\org\animal\Dog.java
How to run the class which is inside in the package
Go to Root folder say C:\javaproject
C:\javaproject> java com.org.animal.Dog
OOPs (Object Oriented Programming
System)
In the real world entity, Table, Fan, Bike,Pen, Keyboard etc., are the objects.
Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
It has some principles & concepts.
OOPs Concepts
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Constructors
Every class has a constructor
If we do not explicitly write a constructor for a class the Java compiler
builds a default constructor for that class.
Creating an Object
Class provides the blueprints for objects.
Object is created from a class.
There are three steps when creating an object from a class –Declaration: A
variable declaration with a variable name with an object type.
Instantiation: The 'new' keyword is used to create the object.
Instantiation: The 'new' keyword is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor.
Accessing Instance Variables and Methods
Source file declaration rules
There can be only one public class per source file.
A source file can have multiple non public classes. –Which is called inner
classes.
The public class name should be the name of the source file as well which
should be appended by .java at the end
For example : The class name is . public class loyee{} Then the source file should
be as loyee.java.
POJO Class
Assignments -1
Create an Person Class which contains the following local variables.
firstName of type String
lastNameof type String
age of type int
gender of type char
Create setter method and getter method of each variables.
Add a main method to initialize the Person class and invoke each the setter
method to set the values for each variables.
Note: Create this class under the package called “com.org.profile.user”
Assignment -2
Create an Address class with the following local variables
streetName
additionalStreetInfo
villageName
cityName
stateName
postalCode
countryName
addressType
Create setter method and getter method of each variables.
Add a main method to initialize the Address class and invoke each the setter
method to set the values for each variables.
Note: Create this class under the package called “com.org.profile.contact”
Inheritance
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.
You can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child
relationship.
Why use inheritance in java?
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Syntax of Java Inheritance
UML Notation
Adding Parameterized constructor in Super
Class
Invoking a constructor using ‘this’
Invoking super class constructor
Upcasting
When reference variable of Parent class refers to the object of Child class, it
is known as upcasting
Interface
AJ ava interface is a bit like a class, except you can only declare methods
and variables in the interface
All fields declared within an interface are implicitly public, static, and final.
Implementing Interfaces
By interface, we can support the functionality of multiple inheritance.
Multiple inheritance in Java by interface
Marker or Tagged interface
An interface that have no member is known as marker or tagged interface.
– Example
Serializable
Cloneable
Remote
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in
java.
It can have abstract and non-abstract methods (method with body).
Difference between abstract class and interface
Polymorphism
When one task is performed by different ways i.e. known as polymorphism
Polymorphism literally means taking more than one form.
Polymorphism is a characteristic of being able to assign a different
behaviour.
Polymorphism means—One name many form
Polymorphism Contd....
There are two types of polymorphism in java
Compile time polymorphism
If you overload static method in java, it is the example of compile time polymorphism
Runtime polymorphism.
We can perform polymorphism in java by
Method overloading
Method overriding.
Run time polymorphism
Compile Time Polymorpism
Overriding Example
Real example of Java Runtime Polymorphism
Abstraction
Hiding internal details and showing functionality is known as abstraction.
For example: phone call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation
Example , By providing only setter or getter method, you can make the
class read-only or write-only.
Naming Conventions
Object Cloning in Java
The object cloning is a way to create exact copy of an object.
clone() method of Object class is used to clone an object.
Access Modifiers in java
There are 4 types of java access modifiers
private
default
protected
public
Aggregation in Java
Final Keyword In Java
The final keyword in java is used to restrict the user.
The java final keyword can be used in many context.
Final can be:
variable
method
class
Java Inner Class
Java inner class or nested class is a class i.e. declared inside the class or
interface
Advantage of java inner classes
The advantages of inner classes
Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
Types of Inner classes
Member inner class
A class that is declared inside a class but outside a method is known as
member inner class.
Invocation of Member Inner class.
From within the class
From outside the class
Internal code generated by the compiler for member inner class –
The java compiler creates a class file named Outer$Inner in this case
Example of member inner class that is invoked
outside a class
Anonymous inner class
A class that have no name is known as anonymous inner class.
Anonymous class can be created by:
Class (may be abstract class also).
Interface
Program of anonymous inner class by
interface
Local inner class
A class that is created inside a method is known as local inner class.
Rules for Local Inner class
Local inner class cannot be invoked from outside the method.
Local inner class cannot access non-final local variable.
Static nested class
A static class that is created inside a class is known as static nested class.
It can access static data members of outer class including private.
static nested class cannot access non-static (instance) data member or
method
Nested Interface
An interface which is declared within another interface or class is known as
nested interface.
The nested interfaces are used to group related interfaces so that they can
be easy to maintain.
The nested interface must be referred by the outer interface or class.
It can't be accessed directly.
Java Command Line Arguments
Arguments values are passed at the time of running the java program.