2. Java programming language was originally
developed by Sun Microsystems which was
initiated by James Gosling and released in
1995 as core component of Sun
Microsystems' Java platform (Java 1.0 [J2SE]).
Java is guaranteed to be Write Once,
Run Anywhere.
3. Features Of JAVA/Java
Buzzwords
3
Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
Robust − Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.
Multithreaded − With Java's multithreaded feature it is possible to write programs
that can perform many tasks simultaneously. This design feature allows the
developers to construct interactive applications that can run smoothly.
4. Features Of JAVA
4
Object Oriented − In Java, everything is an Object. Java can be easily
extended since it is based on the Object model.
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.
Simple − Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
Secure − With Java's secure feature it enables to develop virus-free,
tamper-free systems. Authentication techniques are based on public-key
encryption.
5. Java - Basic Syntax
5
Let us now briefly look into what do class, object, methods, and
instance variables mean.
Object − Objects have states and behaviors.
Example: A dog has states - color, name, breed as well as
behavior such as wagging their tail, barking, eating.
An object is an instance of a class.
6. Java - Basic Syntax
6
Class − A class can be defined as a template/blueprint that
describes the behavior/state that the object of its type supports.
Methods − A method is basically a behavior. A class can contain
many methods. It is in methods where the logics are written, data is
manipulated and all the actions are executed.
7. The basic structure of a program
p
c
k
7
Package declaration Import
statements Comments
Class definition
Class variables, Local variables
Methods/Behaviors
8. package abc; // A package declaration
8
import java.util.*; // declaration of an import statement
// This is a sample program to understnd basic structure of Java (Comment Section)
public class JavaProgramStructureTest {
int repeat = 4;
public static void main(String args[]) {
// class name
// global variable
// main method
JavaProgramStructureTest test = new
javaProgramStructureTest();
test.printMessage("Welcome to Tutorials Point"); }
public void printMessage(String msg) // method
{
Date date = new Date(); // variable local to method
for(int index = 0; index < repeat; index++) { // Here index - variable local to
for loop
System.out.println(msg + "From" + date.toGMTString());
} } }
9. Object-oriented programming System(OOPs) is a programming
paradigm based on the concept of “objects” that contain data and
methods.
The primary purpose of object-oriented programming is to increase
the flexibility and maintainability of programs
Object oriented programming brings together data and its
behaviour(methods) in a single location(object) makes it easier to
OOPs Concepts/features
9
unD
de
ep
a
rr
st
m
te
an
nto
dfC
S
hE
o,N
wS
C
E
aT
,
pT
h
re
on
i
gramworks.
10. What is an Object
10
Objects have two characteristics: They have states and behaviors.
Examples of states and behaviors
Example 1:
Object: House
State: Address, Color, Area
Behavior: Open door, close door
11. class House
{
11
String address;
String color;
double area;
void openDoor()
{
System.out.println(“open the door”);
}
void closeDoor()
{
System.out.println(“Close the door”);
}
public static void main(String a[])
{
House a = new House();
a.openDoor();
a.closeDoor();
}
12. Class
12
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can
create an individual object.
13. Inheritance
13
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance.
It provides code reusability.
The parent class is called the base class or super class. The child class that extends
the base class is called the derived class or sub class or child class.
The biggest advantage of Inheritance is that the code in base class need not be
rewritten in the child class.
The variables and methods of the base class can be used in the child class as well.
15. Types of Inheritance:
15
Single Inheritance
refers to a child and parent class relationship where a
class extends the another class.
Multilevel inheritance
refers to a child and parent class relationship where a class extends the
child class. For example class A extends class B and class B extends class C.
Hierarchical inheritance
refers to a child and parent class relationship where more than one classes
extends the same class. For example, class B extends class A and class C extends
class A.
17. Polymorphism
17
If one task is performed in different ways, it is known as
polymorphism.
In Java, we use method overloading and method overriding to
achieve polymorphism.
18. Abstraction
18
Hiding internal details and showing functionality is known as
abstraction. For example phone call, we don't know the internal
processing.
In Java, we use abstract class and interface to achieve abstraction.
19. Encapsulation
Binding (or wrapping) code and data together into a single unit are
known as encapsulation. For example, a capsule, it is wrapped with
different medicines.
19
20. SAMPLE PROGRAMS
20
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = reader.nextInt();
System.out.println("You entered: " + number);
}
}
OUTPUT:
Enter a number: 10
You entered: 10
21. FUNDEMENTAL PROGRAMMING STRUCTURES
IN JAVA
Keywords or Reserved words are the words in a language
that are used for some internal process or represent some
predefined actions.
These words are therefore not allowed to use as a
variable names or objects. Doing this will result into a compile
time error.
21
23. Variable
23
Variable is name of reserved area allocated in memory.
In other words, it is a name of memory location.
int data=50;//Here data is variable
24. Types of Variables
24
There are three types of variables in Java:
local variable
instance variable
static variable
25. Local Variable
A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.
25
A local variable cannot be defined with "static" keyword.
Instance Variable
A variable declared inside the class but outside the body of the method, is called
instance variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared
among instances.
Static variable
A variable which is declared as static is called static variable. It cannot be local. You
can create a single copy of static variable and share among all the instances of the
class. Memory allocation for static variable happens only once when the class is
loaded in the memory.
27. Data Types in Java
Primitive data types: The primitive data types include boolean,
char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
27
32. Control Statements
32
Control Statements in Java is one of the fundamentals required for Java
Programming. It allows the smooth flow of a program.
Decision Making Statements
Simple if statement
if-else statement
Nested if statement
Switch statement
Looping statements
While
Do-while
For
For-Each
Branching statements
Break
Continue
34. CONSTRUCTOR
34
In Java, a 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 constructor, memory for the object is
allocated in the memory.
It is a special type of method which is used to initialize the object.
35. There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and
synchronized
Rules for creating the
constructor
35
36. Types of Java constructors
36
There are two types of constructors in Java:
Default constructor (no-arg constructor)
Parameterized constructor
37. Java Default Constructor
37
A constructor is called "Default Constructor" when it doesn't have any parameter
class Bike1{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
} }
Output::
Bike is created
38. Java Parameterized Constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.
38
39. class Student4{
int id;
String name;
39
Student4(int i,String n){
id = i;
name = n; }
Voiddisplay(){
System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display(); } }
OUTPUT:
111 Karan
40. The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
Access Modifier
40
41. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
There are four types of Java access modifiers:
41
42.
43. Private
43
The private access modifier is accessible only within the class.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
44. Role of Private
44
If you make any class constructor private, you cannot create the instance of that
class from outside the class
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
45. Default
45
If you don't use any modifier, it is treated as default by default. The default modifier
is accessible only within package. It cannot be accessed from outside the package.
package pack;
class A{
void msg(){System.out.println("Hello");}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
46. Protected
46
The protected access modifier is accessible within package and outside the package but
through inheritance only.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
47. Public
47
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
48. The static keyword can be used with methods, fields, classes
(inner/nested), blocks.
What are static membe
rof a Java class?
In Java, static members are those which belongs to the class and
you can access these members without instantiating the class.
48
49. STATIC METHOD
49
You can create a static method by using the keyword static. Static methods can access only static fields,
methods. To access static methods there is no need to instantiate the class, you can do it just using the class
name as
public class MyClass
{
public static void sample()
{
System.out.println("Hello");
}
public static void main(String args[])
{
MyClass.sample();
}
}
50. Static Fields
50
You can create a static field by using the keyword static. The static fields have
the same value in all the instances of the class. These are created and initialized
when the class is loaded for the first time.
Just like static methods you can access static fields using the class name
public class MyClass {
public static int data = 20;
public static void main(String args[]){
51. Static Blocks
51
These are a block of codes with a static keyword. In general, these
are used to initialize the static members. JVM executes static blocks
before the main method at the time of class loading.
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){ System.out.println("This
is main method");
52. Java Comments
• The Java comments are the statements that are not executed by
the compiler and interpreter. The comments can be used to provide
information or explanation about the variable, method, class or any
statement. It can also be used to hide program code
52
53. Types of Java Comments
53
There are three types of comments in Kava.
Single Line Comment
Multi Line Comment
Documentation Comment
54. Java Single Line Comment
54
Syntax:
//This is single line comment
Example:
public class CommentExample1 {
public static void main(String[] args) {
int i=10;//Here, i is a variable
System.out.println(i);
}
}
Output:
10
55. Java Multi Line Comment
55
Syntax:
/*
This
is
multi line
comment
*/
Example:
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Output:
57. Example:
/** The Calculator class provides methods to get addition and subtraction
of given 2 numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;}
}
Compile it by javac tool:
javac Calculator.java
Create Documentation API by javadoc tool:
javadoc Calculator.java
57
58. ARRAYS
Java array is an object which contains elements of a similar data
type. Additionally, The elements of an array are stored in a
contiguous memory location.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is
stored at the 0th index, 2nd element is stored on 1st index and so
on.
58
60. Array Declaration
Example 1: Declaring an array which holds elements of integer type.
int aiMyArray[];
Different way of declaring an array –
int []aiMyArray;
int aiMyArray[];
The below statement declares, constructs and initializes the array.
int aiFirstArray[]={1,2,3,4,5,6};
60
61. dataType[] arrayName;
double[] data;
data = new Double[10];
The size of an array is also known as the length of an array.
Note: Once the length of the array is defined, it cannot be changed
in the program.
But, how many elements can array this hold?
61
62. Let's take another example:
int[] age;
age = new int[5];
Here, age is an array. It can hold 5 values of int type.
In Java, we can declare and allocate memory of an array in one
single statement. For example,
int[] age = new int[5];
62
63. class ArrayExample
{ public static void main(String[] args) {
int[] age = new int[5];
for (int i = 0; i < 5; ++i) {
System.out.println(age[i]);
} } }
Output:
0 0 0 0 0
63
64. class ArrayExample {
public static void main(String[] args) {
int[] age = {12, 4, 5, 2, 5};
for (int i = 0; i < 5; ++i) {
System.out.println("Element at index " + i +": " + age[i]);
} } }
Output:
Element at index 0: 12
Element at index 1: 4
Element at index 2: 5
Element at index 3: 2
Element at index 4: 5
64
65. How to access array elements?
class ArrayExample {
public static void main(String[] args)
{
int[] age = new int[5];
int age[2] = 14;
int age[0] = 34;
for (int i = 0; i < 5; ++i)
{
System.out.println("Element at index " + i +": " + age[i]); } } }
Output:
Element at index 0: 34
Element at index 1: 0
Element at index 2: 14
Element at index 3: 0
Element at index 4: 0
65
66. Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
66
67. class Testarray{
public static void main(String args[]){
int a[]=new int[5];
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}
Output:
10 20 70 40 50
67
68. Multidimensional Java Array
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
68
69. class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
69