SlideShare a Scribd company logo
1 of 52
Page 1Classification: Restricted
Hadoop Training
A Quick Overview of Java
Page 2Classification: Restricted
Agenda
• What is Java?
• Variable and Data types in Java
Page 3Classification: Restricted
Java is a programming language developed by Sun Microsystems.
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
} }
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. 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.
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.
Instance Variables - Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.
What is Java?
Page 4Classification: Restricted
Variable and Data Type in Java
Variable is name of reserved area allocated in memory.
There are three types of variables in java
• local variable
• instance variable
• static variable
A variable that is declared inside the method is called local variable.
A variable that is declared inside the class but outside the method is called
instance variable . It is not declared as static.
A variable that is declared as static is called static variable. It cannot be local.
Page 5Classification: Restricted
Java static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees, college name of
students etc.
The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
class Student{
int rollno;
String name;
static String college ="ISBBM";
…………………….
all instance data members will get memory each time when object is created. All
student have its unique rollno and name so instance data member is good. Here,
college refers to the common property of all objects. If we make it static, this field will
get memory only once.
Page 6Classification: Restricted
• Int
• Short
• Long
• Char
• Float
• boolean
There are two data types available in Java:
Primitive Datatypes
Reference/Object Datatypes
Primitive Datatypes
Reference variables are created using defined constructors of the classes. They
are used to access objects. These variables are declared to be of a specific type
that cannot be changed. For example, Employee, Puppy, etc.
A reference variable can be used to refer any object of the declared type or any
compatible type.
Example:
Animal animal = new Animal("giraffe");
Data Types
Page 7Classification: Restricted
Java – Objects & Classes
Object - Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behaviors – wagging the tail, barking, eating. An object
is an instance of a class.
Class - A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.
If we consider a dog, then its state is - name, breed, color, and the behavior is -
barking, wagging the tail, running. If you compare the software object with a real-
world object, they have very similar characteristics. Software objects also have a
state and a behavior. A software object's state is stored in fields and behavior is
shown via methods
State: represents data (value) of an object.
A class is a group of objects that has common properties
In java, a method is like function i.e. used to expose behavior of an object
Page 8Classification: Restricted
public class Dog
{
String breed;
int ageC
String color;
void barking()
{
}
void hungry()
{
}
void sleeping()
{ }
}
A class is a blueprint from which
individual objects are created.
So in software development, methods operate on the internal state of an
object and the object-to-object communication is done via methods.
Java – Objects & Classes
Page 9Classification: Restricted
Java Operators
Many operators are present in java to operate on variables:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Example ::::::::
public class Test { public static void main(String args[]) {
int a = 10; int b = 20; int c = 25; int d = 25;
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
Arithmetic Operators ::::: + , - , * , / , % , ++ , --
Page 10Classification: Restricted
Checks if the values of two operands are equal or not, if yes then condition becomes true.
Example: (A == B) is not true
!= (not equal to)
< (less than) ::
Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true.
 (greater than)
 >= (greater than or equal to)
public class Test { public static void main(String args[])
{ int a = 10; int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) ); } }
O/P is ::: a == b = false a != b = true
a > b = false a < b = true b >= a = true b <= a = false
The Relational Operators == (equal to)
Page 11Classification: Restricted
The Logical Operators
&& (logical and) Called Logical AND operator. If both the operands are non-zero,
then the condition becomes true. Example: (A && B) is false.
|| (logical or)
! (logical not)
public class Test
{ public static void main(String args[])
{
boolean a = true; boolean b = false; System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) ); System.out.println("!(a && b) = " + !(a &&
b)); }
}
This will produce the following result: a && b = false a || b = true !(a && b) = true
The Assignment Operators
= Simple assignment operator. Assigns values from right side operands to left
side operand. Example: C = A + B will assign value of A + B into C
Page 12Classification: Restricted
The Logical Operators
+= Add AND assignment operator. It adds right operand to the left
operand and assign the result to left operand. Example: C += A is
equivalent to C = C + A
-= Subtract AND assignment operator
*= Multiply AND assignment operator
/= Divide AND assignment operator.
%= Modulus AND assignment operator
misc operator
class Vehicle {} public class Car extends Vehicle { public static void
main(String args[]){ Vehicle a = new Car(); boolean result = a instanceof
Car; System.out.println( result ); } }
This will produce the following result: true
Page 13Classification: Restricted
The Logical Operators
Java XXXValue Method Description
The method converts the value of the Number Object that invokes the
method to the primitive data type that is returned from the method.
Syntax
Here is a separate method for each primitive data type:
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
Parameters
Here is the detail of parameters: All these are default methods and
accepts no parameter. Return Value This method returns the primitive
data type that is given in the signature. Example
public class Test
{ public static void main(String args[])
{ Integer x = 5;
System.out.println( x.byteValue() );
Page 14Classification: Restricted
The Logical Operators
// Returns double primitive data type System.out.println(x.doubleValue());
System.out.println( x.longValue() ); } }
This will produce the following result: 5 5.0 5
Java –compareTo() Method Description The method compares the
Number object that invoked the method to the argument. It is possible to
compare Byte, Long, Integer, etc. However, two different types cannot be
compared, both the argument and the Number object invoking the
method should be of the same type.
Return Value
If the Integer is equal to the argument then 0 is returned.
If the Integer is less than the argument then -1 is returned.
If the Integer is greater than the argument then 1 is returned.
Page 15Classification: Restricted
The Logical Operators
public class Test{ public static void main(String args[]){ Integer x = 5;
System.out.println(x.compareTo(3)); System.out.println(x.compareTo(5));
System.out.println(x.compareTo(8)); } }
This will produce the following result: 1 0 -1
Java –equals() Method Description The method determines whether the
Number object that invokes the method is equal to the object that is
passed as an argument.
public class Test{ public static void main(String args[]){ Integer x = 5;
Integer y = 10; Integer z =5; Short a = 5; System.out.println(x.equals(y));
System.out.println(x.equals(z)); System.out.println(x.equals(a)); } }
This will produce the following result: false true false
Page 16Classification: Restricted
The Logical Operators
Java –parseInt() Method Description
This method is used to get the primitive data type of a certain String.
parseInt(String s): This returns an integer. Example
public class Test{ public static void main(String args[]){ int x
=Integer.parseInt("9"); System.out.println(x); } }
This will produce the following result: 9
Java –abs() Method Description The method gives the absolute value of
the argument. The argument can be int, float, long, double, short, byte
This method Returns the absolute value of the argument
Integer a = -8;
System.out.println(Math.abs(a));
This will produce the following result: 8
Page 17Classification: Restricted
The Logical Operators
Java –min() Method Description The method gives the smaller of the two
arguments. The argument can be int, float, long, double.
public class Test{ public static void main(String args[]){
System.out.println(Math.min(12.123, 12.456));
System.out.println(Math.min(23.12, 23.0)); } } This will produce the
following result: 12.123 23.0
Java –max() Method
Page 18Classification: Restricted
Methods on Characters in Java
Java –isLetter() Method
This method returns true if the passed character is really a character.
Example public class Test { public static void main(String args[]) {
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5')); } }
This will produce the following result: true false
Java –isDigit() Method Description The method determines whether the
specified char value is a digit.
public class Test { public static void main(String args[]) {
System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('5')); } }
This will produce the following result: false true
Java –isUpperCase() Method Description This method determines
whether the specified char value is uppercase.
Page 19Classification: Restricted
Methods on Characters in Java
Java –isLowerCase() Method
Java –toUpperCase() Method Description The method returns the
uppercase form of the specified char value.
public class Test{ public static void main(String args[]){
System.out.println(Character.toUpperCase('c'));
System.out.println(Character.toUpperCase('C')); } }
This will produce the following result: C
Page 20Classification: Restricted
String Methods
Strings, which are widely used in Java programming, are a sequence of
characters. In Java programming language, strings are treated as objects.
Java –String length() Method
This method returns the the length of the sequence of characters
represented by this object.
String Str1 = new String("Welcome "); String Str2 = new String("Tutorial" );
System.out.print("String Length :" ); System.out.println(Str1.length());
System.out.print("String Length :" ); System.out.println(Str2.length());
Java –String replace() Method
This method returns a new string resulting from replacing all occurrences
of oldChar in this string with newChar.
Page 21Classification: Restricted
String Methods
System.out.print("Return Value :" ); System.out.println(Str.replace('o',
'T'));
Java –String split() Method Description This method has two variants and
splits this string around matches of the given regular expression.
Here is the detail of parameters:
regex -- the delimiting regular expression.
limit -- the result threshold, which means how many strings to be
returned.
import java.io.*;
public class Test{ public static void main(String args[]){ String Str = new
String("Welcome-to-pune"); System.out.println("Return Value :" );
for (String retval: Str.split("-", 2))
Page 22Classification: Restricted
String Methods
This will produce the following result: Return Value : Welcome
to-pune
Java –String toLowerCase() Method
Java –String toUpperCase() Method
Java –String trim() Method
This method returns a copy of the string, with leading and trailing
whitespace omitted.
Java –String valueOf() Method This method has the following variants,
which depend on the passed parameters. This method returns the string
representation of the passed argument.
Page 23Classification: Restricted
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens.
It is simple way to break string.
Methods of StringTokenizer class
The 6 useful methods of StringTokenizer class are as follows:
Public method Description
boolean hasMoreTokens() checks if there is more tokens
available.
String nextToken() returns the next token from the
StringTokenizer object.
String nextToken(String delim) returns the next token based on
the delimeter.
boolean hasMoreElements() same as hasMoreTokens()
method.
Object nextElement() same as nextToken() but its
return type is Object.
int countTokens() returns the total number of
tokens.
Page 24Classification: Restricted
StringTokenizer in Java
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ")
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
} } }
Output:my
name
is
khan
StringTokenizer st = new StringTokenizer("my,name,is,khan");
System.out.println("Next token is : " + st.nextToken(","))
Output:Next token is : my
Page 25Classification: Restricted
Constructor
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values
i.e. provides data for the object that is why it is known as constructor
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.
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
Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class. A
class can have more than one constructor.
There are two types of constructors:
Default constructor (no-arg constructor)
Parameterized constructor
Page 26Classification: Restricted
Default Constructor
class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Page 27Classification: Restricted
Default Constructor
In the above class,you are not creating any constructor so compiler provides you
a default constructor.Here 0 and null values are provided by default constructor.
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
1.class Student4{
2. int id;
3. String name;
4.
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
Page 28Classification: Restricted
Default Constructor
10.
11. public static void main(String args[]){
12. Student4 s1 = new Student4(111,"Karan");
13. Student4 s2 = new Student4(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17.}
o/p::::::: 111 Karan
222 Aryan
Page 29Classification: Restricted
Default Constructor
public class Puppy
{
public Puppy(String name)
{ // This constructor has one parameter, name. System.out.println("Passed Name
is :" + name );
}
public static void main(String []args)
{ // Following statement would create an object myPuppy Puppy myPuppy = new
Puppy( "tommy" );
}
}
o/p:::::Passed Name is :tommy
Page 30Classification: Restricted
Default Constructor
This example explains how to access instance variables and methods of a class.
public class Puppy
{
int puppyAge;
public Puppy(String name)
{ // This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}
public void setAge( int age )
{
puppyAge = age;
}
public int getAge( )
{ System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
Page 31Classification: Restricted
Default Constructor
public static void main(String []args)
{
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );
/* Call class method to set puppy's age
*/ myPuppy.setAge( 2 ); /* Call another class method to get puppy's age */
myPuppy.getAge( ); /* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.puppyAge ); } }
Output :::::::
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
Page 32Classification: Restricted
If Statement
The if statement tests the condition. It executes the if statement if condition is
true.
if(condition){
//code to be executed
}
public class IfExample {
public static void main(String[] args) {
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
} } }
Page 33Classification: Restricted
Java If-else Statement
The if-else statement also tests the condition. It executes the if block if condition
is true otherwise else block.
if(condition){
//code if condition is true
}else{
//code if condition is false
}
public class IfElseExample {
public static void main(String[] args) {
int number=13;
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Page 34Classification: Restricted
Java Switch Statement
The Java switch statement executes one statement from multiple conditions
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
break; //optional
.default:
code to be executed if all cases are not matched;
}
public class SwitchExample {
public static void main(String[] args) { int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30"); } } }
Page 35Classification: Restricted
Java Simple for Loop
The simple for loop is same as C/C++. We can initialize variable, check condition
and increment/decrement value.
Syntax:
for(initialization;condition;incr/decr){
//code to be executed
}
public class ForExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
System.out.println(i);
}
} }
Page 36Classification: Restricted
Java While Loop
The Java while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
o/p :::::::::::::::: 1 2 3 4 5 6 7 8 9 10
Page 37Classification: Restricted
Java Access Modifiers
Java provides a number of access modifiers to set access levels for classes,
variables, methods, and constructors.
The access levels are:
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Visible to the package
Private Access Modifier - Private Methods, variables, and constructors that are
declared private can only be accessed within the declared class itself. Private
access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Public Access Modifier - Public A class, method, constructor, interface, etc.
declared public can be accessed from any other class. Therefore, fields, methods,
blocks declared inside a public class can be accessed from any class belonging to
the Java Universe.
Default
Page 38Classification: Restricted
Java Access Modifiers
Protected Access Modifier - Protected Variables, methods, and constructors,
which are declared protected in a superclass can be accessed only by the
subclasses in other package or any class within the package of the protected
members' class. The protected access modifier cannot be applied to class and
interfaces. Methods, fields can be declared protected
A protected method can be accessed from outside the class only through
inheritance.
A protected method can be accessed from outside the class only through
inheritance.
In this example, we have created two packages pack and mypack. We are
accessing the A class from outside its package, since A class is not public, so it
cannot be accessed from outside the package.
Page 39Classification: Restricted
Java Access Modifiers
Example of default access modifier
1.//save by A.java
2.package pack;
3.class A{
4. void msg(){System.out.println("Hello");}
5.}
1.//save by B.java
2.package mypack;
3.import pack.*;
4.class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9.}
In the above example, the scope of class A and its method msg() is default so it
cannot be accessed from outside the package.
Page 40Classification: Restricted
Inheritance
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order. The class which inherits
the properties of other is known as subclass (derived class, child class) and the
class whose properties are inherited is known as superclass (base class, parent
class). extends Keyword extends is the keyword used to inherit the properties of a
class.
extends Keyword extends is the keyword used to inherit the properties of a class.
Following is the syntax of extends keyword.
class Super
{ ..........
}
class Sub extends Super
{.......... }
Following is an example demonstrating Java inheritance. In this example, you can
observe two classes namely Calculation and My_Calculation. Using extends
keyword, the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.
Page 41Classification: Restricted
Inheritance
Copy and paste the following program in a file with name My_Calculation.java
class Calculation{ int z; public void addition(int x, int y){ z = x+y;
System.out.println("The sum of the given numbers:"+z); }
public void Substraction(int x,int y)
{
z = x-y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation
{
public void multiplication(int x, int y)
{
z = x*y;
System.out.println("The product of the given numbers:"+z);
} public static void main(String args[])
Page 42Classification: Restricted
Inheritance
{
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a, b); } }
In the given program, when an object to My_Calculation class is created, a copy
of the contents of the superclass is made within it. That is why, using the object
of the subclass you can access the members of a superclass.
A very important fact to remember is that Java does not support multiple
inheritance. This means that a class cannot extend more than one class.
Therefore following is illegal − public class extends Animal, Mammal{}
However, a class can implement one or more interfaces, which have helped Java
get rid of the impossibility of multiple inheritance.
Page 43Classification: Restricted
Interfaces
Generally, the implements keyword is used with classes to inherit the properties
of an interface. Interfaces can never be extended by a class. Example public
interface Animal { } public class Mammal implements Animal{ } public class Dog
extends Mammal{ }
It is similar to class. It is a collection of abstract methods. A class implements an
interface, thereby inheriting the abstract methods of the interface
Writing an interface is similar to writing a class. But a class describes the
attributes and behaviors of an object. And an interface contains behaviors that a
class implements.
The interface keyword is used to declare an interface. Here is a simple example to
declare an interface. Example Following is an example of an interface:
/* File name : NameOfInterface.java */
import java.lang.*; //Any number of import statements public interface
NameOfInterface { //Any number of final, static fields //Any number of abstract
method declarations }
Page 44Classification: Restricted
Interfaces
Methods in an interface are implicitly public.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the
declaration.
Page 45Classification: Restricted
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by
different ways. Polymorphism is derived from 2 greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
There are two types of polymorphism in java:
compile time polymorphism and
runtime polymorphism.
We can perform polymorphism in java by
method overloading and
method overriding.
If you overload static method in java, it is the example of compile time
polymorphism
Runtime polymorphism is a process in which a call to an overridden method is
resolved at runtime rather than compile-time
Page 46Classification: Restricted
Method overloading in Java
If a class have multiple methods by same name but different parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods
increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for you
as well as other programmers to understand the behaviour of the method
because its name differs. So, we perform method overloading to figure out the
program quickly.
Advantage of method overloading?
Method overloading increases the readability of the program.
There are two ways to overload the method in java
1.By changing number of arguments
2.By changing the data type
Page 47Classification: Restricted
Method overloading in Java
1)Example of Method Overloading by changing the no. of arguments
In this example, we have created two overloaded methods, first sum method
performs addition of two numbers and second sum method performs addition of
three numbers.
class Calculation{
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[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
} Output:30 40
Page 48Classification: Restricted
Method overloading in Java
2)Example of Method Overloading by changing data type of argument
In this example, we have created two overloaded methods that differs in data
type. The first sum method receives two integer arguments and second sum
method receives two double arguments.
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Output:21.0 40
Page 49Classification: Restricted
Method overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
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.
Usage 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 Java 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).
Because we have to provide a specific implementation of run() method in
subclass which is present in superclass that is why we use method overriding.
Page 50Classification: Restricted
Method overriding in Java
Consider a scenario, Bank is a class that provides functionality to get rate of
interest. But, rate of interest varies according to banks. For example, SBI, ICICI
and AXIS banks could provide 8%, 7% and 9% rate of interest
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
Page 51Classification: Restricted
Method overriding in Java
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInteres)); } }
Page 52Classification: Restricted
Thank you!

More Related Content

What's hot

Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7dplunkett
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and OperatorsMarwa Ali Eissa
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object ReferencesTareq Hasan
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and VariablesNilesh Dalvi
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Sagar Verma
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and objectFajar Baskoro
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Sagar Verma
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introductionSohanur63
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6dplunkett
 
3 java - variable type
3  java - variable type3  java - variable type
3 java - variable typevinay arora
 

What's hot (20)

Ap Power Point Chpt7
Ap Power Point Chpt7Ap Power Point Chpt7
Ap Power Point Chpt7
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
 
Object and class
Object and classObject and class
Object and class
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Array
ArrayArray
Array
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
3 java - variable type
3  java - variable type3  java - variable type
3 java - variable type
 

Similar to Overview of Java

Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh Madugula
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptmanish kumar
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Preexisting code, please useMain.javapublic class Main { p.pdf
Preexisting code, please useMain.javapublic class Main {    p.pdfPreexisting code, please useMain.javapublic class Main {    p.pdf
Preexisting code, please useMain.javapublic class Main { p.pdfrd1742
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1Asad Khan
 
Object Oriented Dbms
Object Oriented DbmsObject Oriented Dbms
Object Oriented Dbmsmaryeem
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentalsjavaease
 

Similar to Overview of Java (20)

Java session4
Java session4Java session4
Java session4
 
java tr.docx
java tr.docxjava tr.docx
java tr.docx
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Java
JavaJava
Java
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Preexisting code, please useMain.javapublic class Main { p.pdf
Preexisting code, please useMain.javapublic class Main {    p.pdfPreexisting code, please useMain.javapublic class Main {    p.pdf
Preexisting code, please useMain.javapublic class Main { p.pdf
 
Basic_Java_02.pptx
Basic_Java_02.pptxBasic_Java_02.pptx
Basic_Java_02.pptx
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Chapter3
Chapter3Chapter3
Chapter3
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Hibernate Training Session1
Hibernate Training Session1Hibernate Training Session1
Hibernate Training Session1
 
Object Oriented Dbms
Object Oriented DbmsObject Oriented Dbms
Object Oriented Dbms
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentals
 

More from AnandMHadoop

Session 09 - Flume
Session 09 - FlumeSession 09 - Flume
Session 09 - FlumeAnandMHadoop
 
Session 23 - Kafka and Zookeeper
Session 23 - Kafka and ZookeeperSession 23 - Kafka and Zookeeper
Session 23 - Kafka and ZookeeperAnandMHadoop
 
Session 19 - MapReduce
Session 19  - MapReduce Session 19  - MapReduce
Session 19 - MapReduce AnandMHadoop
 
Session 04 -Pig Continued
Session 04 -Pig ContinuedSession 04 -Pig Continued
Session 04 -Pig ContinuedAnandMHadoop
 
Session 04 pig - slides
Session 04   pig - slidesSession 04   pig - slides
Session 04 pig - slidesAnandMHadoop
 
Session 03 - Hadoop Installation and Basic Commands
Session 03 - Hadoop Installation and Basic CommandsSession 03 - Hadoop Installation and Basic Commands
Session 03 - Hadoop Installation and Basic CommandsAnandMHadoop
 
Session 02 - Yarn Concepts
Session 02 - Yarn ConceptsSession 02 - Yarn Concepts
Session 02 - Yarn ConceptsAnandMHadoop
 
Session 01 - Into to Hadoop
Session 01 - Into to HadoopSession 01 - Into to Hadoop
Session 01 - Into to HadoopAnandMHadoop
 

More from AnandMHadoop (9)

Session 14 - Hive
Session 14 - HiveSession 14 - Hive
Session 14 - Hive
 
Session 09 - Flume
Session 09 - FlumeSession 09 - Flume
Session 09 - Flume
 
Session 23 - Kafka and Zookeeper
Session 23 - Kafka and ZookeeperSession 23 - Kafka and Zookeeper
Session 23 - Kafka and Zookeeper
 
Session 19 - MapReduce
Session 19  - MapReduce Session 19  - MapReduce
Session 19 - MapReduce
 
Session 04 -Pig Continued
Session 04 -Pig ContinuedSession 04 -Pig Continued
Session 04 -Pig Continued
 
Session 04 pig - slides
Session 04   pig - slidesSession 04   pig - slides
Session 04 pig - slides
 
Session 03 - Hadoop Installation and Basic Commands
Session 03 - Hadoop Installation and Basic CommandsSession 03 - Hadoop Installation and Basic Commands
Session 03 - Hadoop Installation and Basic Commands
 
Session 02 - Yarn Concepts
Session 02 - Yarn ConceptsSession 02 - Yarn Concepts
Session 02 - Yarn Concepts
 
Session 01 - Into to Hadoop
Session 01 - Into to HadoopSession 01 - Into to Hadoop
Session 01 - Into to Hadoop
 

Recently uploaded

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 

Overview of Java

  • 1. Page 1Classification: Restricted Hadoop Training A Quick Overview of Java
  • 2. Page 2Classification: Restricted Agenda • What is Java? • Variable and Data types in Java
  • 3. Page 3Classification: Restricted Java is a programming language developed by Sun Microsystems. class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } } Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model. When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. 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. 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. Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables. What is Java?
  • 4. Page 4Classification: Restricted Variable and Data Type in Java Variable is name of reserved area allocated in memory. There are three types of variables in java • local variable • instance variable • static variable A variable that is declared inside the method is called local variable. A variable that is declared inside the class but outside the method is called instance variable . It is not declared as static. A variable that is declared as static is called static variable. It cannot be local.
  • 5. Page 5Classification: Restricted Java static variable If you declare any variable as static, it is known static variable. The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc. The static variable gets memory only once in class area at the time of class loading. Advantage of static variable It makes your program memory efficient (i.e it saves memory). class Student{ int rollno; String name; static String college ="ISBBM"; ……………………. all instance data members will get memory each time when object is created. All student have its unique rollno and name so instance data member is good. Here, college refers to the common property of all objects. If we make it static, this field will get memory only once.
  • 6. Page 6Classification: Restricted • Int • Short • Long • Char • Float • boolean There are two data types available in Java: Primitive Datatypes Reference/Object Datatypes Primitive Datatypes Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Puppy, etc. A reference variable can be used to refer any object of the declared type or any compatible type. Example: Animal animal = new Animal("giraffe"); Data Types
  • 7. Page 7Classification: Restricted Java – Objects & Classes Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support. If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running. If you compare the software object with a real- world object, they have very similar characteristics. Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods State: represents data (value) of an object. A class is a group of objects that has common properties In java, a method is like function i.e. used to expose behavior of an object
  • 8. Page 8Classification: Restricted public class Dog { String breed; int ageC String color; void barking() { } void hungry() { } void sleeping() { } } A class is a blueprint from which individual objects are created. So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods. Java – Objects & Classes
  • 9. Page 9Classification: Restricted Java Operators Many operators are present in java to operate on variables: Arithmetic Operators Relational Operators Logical Operators Assignment Operators Example :::::::: public class Test { public static void main(String args[]) { int a = 10; int b = 20; int c = 25; int d = 25; System.out.println("a + b = " + (a + b) ); System.out.println("a - b = " + (a - b) ); System.out.println("a * b = " + (a * b) ); System.out.println("b / a = " + (b / a) ); System.out.println("b % a = " + (b % a) ); System.out.println("c % a = " + (c % a) ); System.out.println("a++ = " + (a++) ); System.out.println("b-- = " + (a--) ); Arithmetic Operators ::::: + , - , * , / , % , ++ , --
  • 10. Page 10Classification: Restricted Checks if the values of two operands are equal or not, if yes then condition becomes true. Example: (A == B) is not true != (not equal to) < (less than) :: Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.  (greater than)  >= (greater than or equal to) public class Test { public static void main(String args[]) { int a = 10; int b = 20; System.out.println("a == b = " + (a == b) ); System.out.println("a != b = " + (a != b) ); System.out.println("a > b = " + (a > b) ); System.out.println("a < b = " + (a < b) ); System.out.println("b >= a = " + (b >= a) ); System.out.println("b <= a = " + (b <= a) ); } } O/P is ::: a == b = false a != b = true a > b = false a < b = true b >= a = true b <= a = false The Relational Operators == (equal to)
  • 11. Page 11Classification: Restricted The Logical Operators && (logical and) Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. Example: (A && B) is false. || (logical or) ! (logical not) public class Test { public static void main(String args[]) { boolean a = true; boolean b = false; System.out.println("a && b = " + (a&&b)); System.out.println("a || b = " + (a||b) ); System.out.println("!(a && b) = " + !(a && b)); } } This will produce the following result: a && b = false a || b = true !(a && b) = true The Assignment Operators = Simple assignment operator. Assigns values from right side operands to left side operand. Example: C = A + B will assign value of A + B into C
  • 12. Page 12Classification: Restricted The Logical Operators += Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. Example: C += A is equivalent to C = C + A -= Subtract AND assignment operator *= Multiply AND assignment operator /= Divide AND assignment operator. %= Modulus AND assignment operator misc operator class Vehicle {} public class Car extends Vehicle { public static void main(String args[]){ Vehicle a = new Car(); boolean result = a instanceof Car; System.out.println( result ); } } This will produce the following result: true
  • 13. Page 13Classification: Restricted The Logical Operators Java XXXValue Method Description The method converts the value of the Number Object that invokes the method to the primitive data type that is returned from the method. Syntax Here is a separate method for each primitive data type: short shortValue() int intValue() long longValue() float floatValue() double doubleValue() Parameters Here is the detail of parameters: All these are default methods and accepts no parameter. Return Value This method returns the primitive data type that is given in the signature. Example public class Test { public static void main(String args[]) { Integer x = 5; System.out.println( x.byteValue() );
  • 14. Page 14Classification: Restricted The Logical Operators // Returns double primitive data type System.out.println(x.doubleValue()); System.out.println( x.longValue() ); } } This will produce the following result: 5 5.0 5 Java –compareTo() Method Description The method compares the Number object that invoked the method to the argument. It is possible to compare Byte, Long, Integer, etc. However, two different types cannot be compared, both the argument and the Number object invoking the method should be of the same type. Return Value If the Integer is equal to the argument then 0 is returned. If the Integer is less than the argument then -1 is returned. If the Integer is greater than the argument then 1 is returned.
  • 15. Page 15Classification: Restricted The Logical Operators public class Test{ public static void main(String args[]){ Integer x = 5; System.out.println(x.compareTo(3)); System.out.println(x.compareTo(5)); System.out.println(x.compareTo(8)); } } This will produce the following result: 1 0 -1 Java –equals() Method Description The method determines whether the Number object that invokes the method is equal to the object that is passed as an argument. public class Test{ public static void main(String args[]){ Integer x = 5; Integer y = 10; Integer z =5; Short a = 5; System.out.println(x.equals(y)); System.out.println(x.equals(z)); System.out.println(x.equals(a)); } } This will produce the following result: false true false
  • 16. Page 16Classification: Restricted The Logical Operators Java –parseInt() Method Description This method is used to get the primitive data type of a certain String. parseInt(String s): This returns an integer. Example public class Test{ public static void main(String args[]){ int x =Integer.parseInt("9"); System.out.println(x); } } This will produce the following result: 9 Java –abs() Method Description The method gives the absolute value of the argument. The argument can be int, float, long, double, short, byte This method Returns the absolute value of the argument Integer a = -8; System.out.println(Math.abs(a)); This will produce the following result: 8
  • 17. Page 17Classification: Restricted The Logical Operators Java –min() Method Description The method gives the smaller of the two arguments. The argument can be int, float, long, double. public class Test{ public static void main(String args[]){ System.out.println(Math.min(12.123, 12.456)); System.out.println(Math.min(23.12, 23.0)); } } This will produce the following result: 12.123 23.0 Java –max() Method
  • 18. Page 18Classification: Restricted Methods on Characters in Java Java –isLetter() Method This method returns true if the passed character is really a character. Example public class Test { public static void main(String args[]) { System.out.println(Character.isLetter('c')); System.out.println(Character.isLetter('5')); } } This will produce the following result: true false Java –isDigit() Method Description The method determines whether the specified char value is a digit. public class Test { public static void main(String args[]) { System.out.println(Character.isDigit('c')); System.out.println(Character.isDigit('5')); } } This will produce the following result: false true Java –isUpperCase() Method Description This method determines whether the specified char value is uppercase.
  • 19. Page 19Classification: Restricted Methods on Characters in Java Java –isLowerCase() Method Java –toUpperCase() Method Description The method returns the uppercase form of the specified char value. public class Test{ public static void main(String args[]){ System.out.println(Character.toUpperCase('c')); System.out.println(Character.toUpperCase('C')); } } This will produce the following result: C
  • 20. Page 20Classification: Restricted String Methods Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. Java –String length() Method This method returns the the length of the sequence of characters represented by this object. String Str1 = new String("Welcome "); String Str2 = new String("Tutorial" ); System.out.print("String Length :" ); System.out.println(Str1.length()); System.out.print("String Length :" ); System.out.println(Str2.length()); Java –String replace() Method This method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
  • 21. Page 21Classification: Restricted String Methods System.out.print("Return Value :" ); System.out.println(Str.replace('o', 'T')); Java –String split() Method Description This method has two variants and splits this string around matches of the given regular expression. Here is the detail of parameters: regex -- the delimiting regular expression. limit -- the result threshold, which means how many strings to be returned. import java.io.*; public class Test{ public static void main(String args[]){ String Str = new String("Welcome-to-pune"); System.out.println("Return Value :" ); for (String retval: Str.split("-", 2))
  • 22. Page 22Classification: Restricted String Methods This will produce the following result: Return Value : Welcome to-pune Java –String toLowerCase() Method Java –String toUpperCase() Method Java –String trim() Method This method returns a copy of the string, with leading and trailing whitespace omitted. Java –String valueOf() Method This method has the following variants, which depend on the passed parameters. This method returns the string representation of the passed argument.
  • 23. Page 23Classification: Restricted StringTokenizer in Java The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string. Methods of StringTokenizer class The 6 useful methods of StringTokenizer class are as follows: Public method Description boolean hasMoreTokens() checks if there is more tokens available. String nextToken() returns the next token from the StringTokenizer object. String nextToken(String delim) returns the next token based on the delimeter. boolean hasMoreElements() same as hasMoreTokens() method. Object nextElement() same as nextToken() but its return type is Object. int countTokens() returns the total number of tokens.
  • 24. Page 24Classification: Restricted StringTokenizer in Java import java.util.StringTokenizer; public class Simple{ public static void main(String args[]){ StringTokenizer st = new StringTokenizer("my name is khan"," ") while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } } } Output:my name is khan StringTokenizer st = new StringTokenizer("my,name,is,khan"); System.out.println("Next token is : " + st.nextToken(",")) Output:Next token is : my
  • 25. Page 25Classification: Restricted Constructor Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor 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. 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 Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor. There are two types of constructors: Default constructor (no-arg constructor) Parameterized constructor
  • 26. Page 26Classification: Restricted Default Constructor class Student3{ int id; String name; void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); } } Output: 0 null 0 null
  • 27. Page 27Classification: Restricted Default Constructor In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor. In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. 1.class Student4{ 2. int id; 3. String name; 4. 5. Student4(int i,String n){ 6. id = i; 7. name = n; 8. } 9. void display(){System.out.println(id+" "+name);}
  • 28. Page 28Classification: Restricted Default Constructor 10. 11. public static void main(String args[]){ 12. Student4 s1 = new Student4(111,"Karan"); 13. Student4 s2 = new Student4(222,"Aryan"); 14. s1.display(); 15. s2.display(); 16. } 17.} o/p::::::: 111 Karan 222 Aryan
  • 29. Page 29Classification: Restricted Default Constructor public class Puppy { public Puppy(String name) { // This constructor has one parameter, name. System.out.println("Passed Name is :" + name ); } public static void main(String []args) { // Following statement would create an object myPuppy Puppy myPuppy = new Puppy( "tommy" ); } } o/p:::::Passed Name is :tommy
  • 30. Page 30Classification: Restricted Default Constructor This example explains how to access instance variables and methods of a class. public class Puppy { int puppyAge; public Puppy(String name) { // This constructor has one parameter, name. System.out.println("Name chosen is :" + name ); } public void setAge( int age ) { puppyAge = age; } public int getAge( ) { System.out.println("Puppy's age is :" + puppyAge ); return puppyAge; }
  • 31. Page 31Classification: Restricted Default Constructor public static void main(String []args) { /* Object creation */ Puppy myPuppy = new Puppy( "tommy" ); /* Call class method to set puppy's age */ myPuppy.setAge( 2 ); /* Call another class method to get puppy's age */ myPuppy.getAge( ); /* You can access instance variable as follows as well */ System.out.println("Variable Value :" + myPuppy.puppyAge ); } } Output ::::::: Name chosen is :tommy Puppy's age is :2 Variable Value :2
  • 32. Page 32Classification: Restricted If Statement The if statement tests the condition. It executes the if statement if condition is true. if(condition){ //code to be executed } public class IfExample { public static void main(String[] args) { int age=20; if(age>18){ System.out.print("Age is greater than 18"); } } }
  • 33. Page 33Classification: Restricted Java If-else Statement The if-else statement also tests the condition. It executes the if block if condition is true otherwise else block. if(condition){ //code if condition is true }else{ //code if condition is false } public class IfElseExample { public static void main(String[] args) { int number=13; if(number%2==0){ System.out.println("even number"); }else{ System.out.println("odd number"); } } }
  • 34. Page 34Classification: Restricted Java Switch Statement The Java switch statement executes one statement from multiple conditions switch(expression){ case value1: //code to be executed; break; //optional case value2: break; //optional .default: code to be executed if all cases are not matched; } public class SwitchExample { public static void main(String[] args) { int number=20; switch(number){ case 10: System.out.println("10");break; case 20: System.out.println("20");break; case 30: System.out.println("30");break; default:System.out.println("Not in 10, 20 or 30"); } } }
  • 35. Page 35Classification: Restricted Java Simple for Loop The simple for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value. Syntax: for(initialization;condition;incr/decr){ //code to be executed } public class ForExample { public static void main(String[] args) { for(int i=1;i<=10;i++){ System.out.println(i); } } }
  • 36. Page 36Classification: Restricted Java While Loop The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop. Syntax: while(condition){ //code to be executed } public class WhileExample { public static void main(String[] args) { int i=1; while(i<=10){ System.out.println(i); i++; } } } o/p :::::::::::::::: 1 2 3 4 5 6 7 8 9 10
  • 37. Page 37Classification: Restricted Java Access Modifiers Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. The access levels are: Visible to the class only (private). Visible to the world (public). Visible to the package and all subclasses (protected). Visible to the package Private Access Modifier - Private Methods, variables, and constructors that are declared private can only be accessed within the declared class itself. Private access modifier is the most restrictive access level. Class and interfaces cannot be private. Public Access Modifier - Public A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe. Default
  • 38. Page 38Classification: Restricted Java Access Modifiers Protected Access Modifier - Protected Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class. The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected A protected method can be accessed from outside the class only through inheritance. A protected method can be accessed from outside the class only through inheritance. In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.
  • 39. Page 39Classification: Restricted Java Access Modifiers Example of default access modifier 1.//save by A.java 2.package pack; 3.class A{ 4. void msg(){System.out.println("Hello");} 5.} 1.//save by B.java 2.package mypack; 3.import pack.*; 4.class B{ 5. public static void main(String args[]){ 6. A obj = new A();//Compile Time Error 7. obj.msg();//Compile Time Error 8. } 9.} In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.
  • 40. Page 40Classification: Restricted Inheritance Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class). extends Keyword extends is the keyword used to inherit the properties of a class. extends Keyword extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword. class Super { .......... } class Sub extends Super {.......... } Following is an example demonstrating Java inheritance. In this example, you can observe two classes namely Calculation and My_Calculation. Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of Calculation class.
  • 41. Page 41Classification: Restricted Inheritance Copy and paste the following program in a file with name My_Calculation.java class Calculation{ int z; public void addition(int x, int y){ z = x+y; System.out.println("The sum of the given numbers:"+z); } public void Substraction(int x,int y) { z = x-y; System.out.println("The difference between the given numbers:"+z); } } public class My_Calculation extends Calculation { public void multiplication(int x, int y) { z = x*y; System.out.println("The product of the given numbers:"+z); } public static void main(String args[])
  • 42. Page 42Classification: Restricted Inheritance { int a = 20, b = 10; My_Calculation demo = new My_Calculation(); demo.addition(a, b); demo.Substraction(a, b); demo.multiplication(a, b); } } In the given program, when an object to My_Calculation class is created, a copy of the contents of the superclass is made within it. That is why, using the object of the subclass you can access the members of a superclass. A very important fact to remember is that Java does not support multiple inheritance. This means that a class cannot extend more than one class. Therefore following is illegal − public class extends Animal, Mammal{} However, a class can implement one or more interfaces, which have helped Java get rid of the impossibility of multiple inheritance.
  • 43. Page 43Classification: Restricted Interfaces Generally, the implements keyword is used with classes to inherit the properties of an interface. Interfaces can never be extended by a class. Example public interface Animal { } public class Mammal implements Animal{ } public class Dog extends Mammal{ } It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements. The interface keyword is used to declare an interface. Here is a simple example to declare an interface. Example Following is an example of an interface: /* File name : NameOfInterface.java */ import java.lang.*; //Any number of import statements public interface NameOfInterface { //Any number of final, static fields //Any number of abstract method declarations }
  • 44. Page 44Classification: Restricted Interfaces Methods in an interface are implicitly public. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces. A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.
  • 45. Page 45Classification: Restricted Polymorphism in Java Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding. If you overload static method in java, it is the example of compile time polymorphism Runtime polymorphism is a process in which a call to an overridden method is resolved at runtime rather than compile-time
  • 46. Page 46Classification: Restricted Method overloading in Java If a class have multiple methods by same name but different parameters, it is known as Method Overloading. If we have to perform only one operation, having same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behaviour of the method because its name differs. So, we perform method overloading to figure out the program quickly. Advantage of method overloading? Method overloading increases the readability of the program. There are two ways to overload the method in java 1.By changing number of arguments 2.By changing the data type
  • 47. Page 47Classification: Restricted Method overloading in Java 1)Example of Method Overloading by changing the no. of arguments In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers. class Calculation{ 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[]){ Calculation obj=new Calculation(); obj.sum(10,10,10); obj.sum(20,20); } } Output:30 40
  • 48. Page 48Classification: Restricted Method overloading in Java 2)Example of Method Overloading by changing data type of argument In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments. class Calculation2{ void sum(int a,int b){System.out.println(a+b);} void sum(double a,double b){System.out.println(a+b);} public static void main(String args[]){ Calculation2 obj=new Calculation2(); obj.sum(10.5,10.5); obj.sum(20,20); } } Output:21.0 40
  • 49. Page 49Classification: Restricted Method overriding in Java If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. 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. Usage 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 Java 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). Because we have to provide a specific implementation of run() method in subclass which is present in superclass that is why we use method overriding.
  • 50. Page 50Classification: Restricted Method overriding in Java Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest class Bank{ int getRateOfInterest(){return 0;} } class SBI extends Bank{ int getRateOfInterest(){return 8;} } class ICICI extends Bank{ int getRateOfInterest(){return 7;} } class AXIS extends Bank{ int getRateOfInterest(){return 9;} }
  • 51. Page 51Classification: Restricted Method overriding in Java class Test2{ public static void main(String args[]){ SBI s=new SBI(); ICICI i=new ICICI(); AXIS a=new AXIS(); System.out.println("SBI Rate of Interest: "+s.getRateOfInterest()); System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest()); System.out.println("AXIS Rate of Interest: "+a.getRateOfInteres)); } }