JAVA Overview Syntax

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 49

JAVA

1
History of JAVA
• James Gosling initiated the Java language project in June 1991
• Initially called Oak after an oak tree that stood outside Gosling's
office, also went by the name Green and ended up later being
renamed as Java,
• Sun released the first public implementation as Java 1.0 in 1995.
• Write Once, Run Anywhere (WORA), providing no-cost run-
times on popular platforms.
• On 13 November 2006, Sun released much of Java as free and
open source software under the terms of the GNU General
Public License (GPL).
• On 8 May 2007, Sun finished the process, making all of Java's
core code free and open-source, aside from a small portion of
code to which Sun did not hold the copyright.
2
Basic Syntax
• Java program, it can be defined as a collection of
objects that communicate via invoking each other's
methods.
• Object - Objects have states and behaviors.
Example: A dog has states-color, name, breed as well
as behaviors -wagging, barking, eating. An object is an
instance of a class.
• Class - A class can be defined as a template/blue print
that describes the behaviors/states that object of its
type support.
3
Basic Syntax
• 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.

4
Basic Syntax
Simple code:

public class MyFirstJavaProgram{


/* This is my first java program. * This will print 'Hello
World' as the output */
public static void main(String[]args){
System.out.println("Hello World"); // prints Hello World
}
}

5
public static void main(String[]args)
• public and static keyword are used in object-oriented
programming. Simplified, public makes this method
accessible from other classes and static ensures that there is
only one reference to this method used by every instance of
this program (class). Static method are also referred to as
class methods, because they refer to the class and not
specific instances of the class.
• void keyword means that this method does not return any
value when it is completed.
• main is the name of the method, it accepts a parameter—
String[]args. Specifically, it is an array (list) of command-
line arguments. As is the case with all methods, the
parameters must always appear within the parentheses that
follow the method name.
6
public static void main(String[]args)
• Within the curly braces of the main() method,
you list all the operations you want your
application to perform. Every Java application
requires a main() method. The main()
method is simply the driver for your
application.

7
Basic Syntax
• Case Sensitivity - which means identifier Hello and
hello would have different meaning in Java.
• Class Names - the first letter should be in Upper Case. If
several words are used to form a name of the class,
each inner word's first letter should be in Upper Case.
Example class MyFirstJavaClass
• Method Names - All method names should start with a
Lower Case letter. If several words are used to form the
name of the method, then each inner word's first letter
should be in Upper Case. Example public void
myMethodName()

8
Basic Syntax
• Program File Name - Name of the program file should
exactly match the class name. When saving the file,
you should save it using the class name (Remember
Java is case sensitive) and append '.java' to the end of
the name (if the file name and the class name do not
match your program will not compile). Example :
Assume 'MyFirstJavaProgram' is the class name, then
the file should be saved as'MyFirstJavaProgram.java'
• public static void main(String args[]) - Java program
processing starts from the main() method, which is a
mandatory part of every Java program.

9
JAVA Identifiers
All Java components require names. Names used for classes,
variables and methods are called identifiers. They are as
follows:
• All identifiers should begin with a letter (A to Z or a to z),
currency character ($) or an underscore (_).
• After the first character, identifiers can have any
combination of characters.
• A keyword cannot be used as an identifier.
• Most importantly identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value
Examples of illegal identifiers: 123abc, -salary

10
JAVA Modifiers
There are two categories of modifiers:

Access Modifiers: default, public, protected,


private

Non-access Modifiers: final, abstract, strictfp

11
JAVA Keywords
abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch synchronized this throw throws
transient try void volatile while

12
Basic Data Types

There are two data types available in Java:


• Primitive Data Types
• Reference/Object Data Types

13
Basic Data Types

• Primitive Data Types


There are eight primitive data types
supported by Java. Primitive data types
are predefined by the language and
named by a keyword.

14
(Basic Data Types) Primitive Data Types

1. byte
2. short
3. int
4. long
5. float
6. double
7. boolean
8. char
15
16
(Basic Data Types) Reference Data Types
• 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.
 Class objects and various types of array variables
come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any
object of the declared type or any compatible type.
 Example: Animal animal = new Animal("giraffe");

17
Java Literals
• A literal is a source code representation of a
fixed value. They are represented directly in
the code without any computation. Literals
can be assigned to any primitive type variable.
For example:
byte a =68;
char a ='A'

18
Java Literals
• byte, int, long, and short can be expressed in
decimal(base 10),hexadecimal(base 16) or
octal(base 8) number systems as well. Prefix 0 is
used to indicate octal and prefix 0x indicates
hexadecimal when using these number systems
for literals. For example:
int decimal=100;
int octal =0144;
int hexa =0x64;
19
String Literals
• String literals in Java are specified like they are in most
other languages by enclosing a sequence of characters
between a pair of double quotes. Examples of string
literals are: "Hello World“
"two\n lines"
"\"This is in quotes\“”
String and char types of literals can contain any Unicode
characters. For example:
char a ='\u0001';
String a ="\u0001";
20
String Literals

21
Variable

Variables are containers for storing data values.


• String - stores text, such as "Hello". String values are
surrounded by double quotes
• int - stores integers (whole numbers), without
decimals, such as 123 or -123
• float - stores floating point numbers, with decimals,
such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char
values are surrounded by single quotes
• boolean - stores values with two states: true or false

22
Variable Types

• The basic form of a variable declaration:


data type variable [ = value][, variable [= value] ...] ;
Here:
data type is one of Java's data types and variable is the name of
the variable. To declare more than one variable of the
specified type, you can use a comma-separated list. Examples :

int a, b, c; // Declares three ints, a, b, and c.


int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'

23
Variable Types
• Three kinds of variables in Java:

Local Variables
Instance Variables
Class/ static variables

24
Local Variables
• are declared in methods, constructors, or blocks.
• are created when the method, constructor or block is
entered and the variable will be destroyed once it exits
the method, constructor or block.
• Access modifiers cannot be used for local variables
• are visible only within the declared method,
constructor or block.
• are implemented at stack level internally.
• There is no default value for local variables so local
variables should be declared and an initial value should
be assigned before the first use.
25
Sample
public class Test{
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}
}
26
Instance Variables
• are declared in a class, but outside a method,
constructor or any block.
• When a space is allocated for an object in the heap, a
slot for each instance variable value is created.
• are created when an object is created with the use of
the keyword 'new' and destroyed when the object is
destroyed.
• hold values that must be referenced by more than
one method, constructor or block, or essential parts
of an object's state that must be present throughout
the class.
27
Instance Variables
• can be declared in class level before or after
use.
• Access modifiers can be given for instance
variables.
• are visible for all methods, constructors and
block in the class. Normally, it is
recommended to make these variables private
(access level). However visibility for subclasses
can be given for these variables with the use
of access modifiers.
28
Instance Variables
• have default values. For numbers the default
value is 0, for Booleans it is false and for object
references it is null. Values can be assigned
during the declaration or within the
constructor.
• can be accessed directly by calling the variable
name inside the class. However within static
methods and different class ( when instance
variables are given accessibility) should be
called using the fully qualified name .
ObjectReference.VariableName.
29
Sample

import java.io.*;
public class Employee{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName){
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}
30
Sample

// This method prints the employee details.


public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]){ Employee
empOne = new Employee("Ransika");
empOne.setSalary(1000);empOne.printEmp();
}
}
31
Class / Static Variables
• Class variables also known as Static Variables are
declared with the static keyword in a class, but outside a
method, constructor or a block.
• There would only be one copy of each class variable per
class, regardless of how many objects are created from it.
• are rarely used other than being declared as constants.
Constants are variables that are declared as
public/private, final and static. Constant variables never
change from their initial value.
• are stored in static memory. It is rare to use static
variables other than declared final and used as either
public or private constants.

32
Class / Static Variables
• are created when the program starts and destroyed
when the program stops.
• Visibility is similar to instance variables. However,
most static variables are declared public since they
must be available for users of the class.
• Default values are same as instance variables. For
numbers, the default value is 0; for Booleans, it is
false; and for object references, it is null. Values can
be assigned during the declaration or within the
constructor. Additionally values can be assigned in
special static initializer blocks.
33
Class / Static Variables
• can be accessed by calling with the class
name. ClassName.VariableName.
• When declaring class variables as public static
final, then variables names (constants) are all
in upper case. If the static variables are not
public and final the naming syntax is the same
as instance and local variables.

34
Example
import java.io.*;
public class Employee{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]){
salary = 1000; System.out.println(DEPARTMENT+"average
salary:"+salary);
}
}
Note: If the variables are access from an outside class the
constant should be accessed as Employee.DEPARTMENT

35
Final Variables
• You can add the final keyword if you don't
want others (or yourself) to overwrite existing
values (this will declare the variable as "final"
or "constant", which means unchangeable and
read-only)
Ex.
final int myNum = 15;
myNum = 20;

36
Basic Operators
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Misc Operators

37
Arithmetic Operator

38
Relational Operators

39
Bitwise Operators

40
Logical Operators

41
Assignment Operators

42
Assignment Operators

43
44
Misc Operators
There are few other operators supported by Java
Language.
Conditional Operator (?:) is also known as the ternary
operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The
goal of the operator is to decide which value should
be assigned to the variable.
The operator is written as:

variable x =(expression)? value iftrue: value iffalse


45
Sample
public class Test{
public static void main(String args[]){
int a , b;
a =10;
b =(a ==1)?20:30;
System.out.println("Value of b is : "+ b );
b =(a ==10)?20:30;
System.out.println("Value of b is : "+ b );
}
}

46
instanceof Operator:
• This operator is used only for object reference
variables. The operator checks whether the
object is of a particular type(class type or
interface type). instanceof operator is written
as: (Object reference variable ) instanceof
(class/interface type)

47
Example
Class Vehicle{
} public class Car extends Vehicle{
public static void main(String args[]){
Vehicle ab =newCar();
boolean result = ab instanceof Car;
System.out.println(result);
}
}

48
Precedence of Java Operators

49

You might also like