SlideShare a Scribd company logo
1 of 90
Download to read offline
What is Java Technology?
Java technology is:
A programming language
●
–
A development environment
An application environment
–
–
It is similar in syntax to C++.
It is used for developing both applets
●
and applications.●
Thanks to its scalable nature, Java has emerged as the most preferred language
in Web and Mobile application development
Primary Goals of the
Java Technology
Provides an easy-to-use language by:
Avoiding many pitfalls of other languages
●
–
Being object-oriented
Enabling users to create streamlined and clear code
–
–
Provides an interpreted environment for:Provides an interpreted environment for:
Improved speed of development
●
–
Code portability–
Primary Goals of the
Java Technology
Enables users to run more than one thread of activity
Loads classes dynamically; that is, at the time they are actually
needed
Supports changing programs dynamically during runtime by loading
classes from disparate sources
●
●
●
classes from disparate sources
Furnishes better security●
Primary Goals of the
Java Technology
The following features fulfill these goals:
The Java Virtual Machine (JVMTM) 1
Garbage collection
The Java Runtime Environment (JRE)
●
●
●
●
The Java Virtual Machine
a specification that provides runtime environment in which java byte
code can be executed.
Reads compiled byte codes that are platform-independent
JVMs are available for many hardware and software platforms.
JVM is platform dependent because configuration of each OS differs.
The Java Virtual Machine(JVM) make the code run in any platform, thereby
making it platform independent
JVM is platform dependent because configuration of each OS differs.
But, Java is platform independent
Garbage Collection
Allocated memory that is no longer needed should be deallocated.
In other languages, deallocation is the programmer’s responsibility.
The Java programming language provides a system-level thread to
track memory allocation.
●
●
●
Garbage Collection
Garbage collection has the following characteristics:
Checks for and frees memory no longer needed
Is done automatically
Can vary dramatically across JVM implementations
●
●
●
The Java Runtime
Environment
JVM Tasks
The JVM performs
Loads code
Verifies code
Executes code
three main tasks:
●
●
●
The Class Loader
Loads all classes necessary for the execution of a program
Maintains classes of the local file system in separate namespaces
●
●
The Bytecode Verifier
The
The
The
The
code
code
code
adheres to the JVM specification.
does not violate system integrity.
causes no operand stack overflows or underflows.
●
●
●
parameter types for all operational code are●
correct.
No illegal data conversions (the conversion of integers to pointers)
have occurred.
●
Simple
Object-Oriented
Platform independent
Features of Java
Secured
Robust
Architecture neutral
Multithreaded
Distributed
Simple Java Application
The TestGreeting.java Application
//
// Sample "Hello World" application
//
public class TestGreeting{public class TestGreeting{
public static void main (String[]
args)
Greeting hello = new Greeting();
hello.greet();
}
}
{
A Simple Java Application
The Greeting.java Class
public class Greeting {
public void greet() {
System.out.println(“hi”);
}
}
Compiling and Running
the TestGreeting Program
Compile TestGreeting.java:
javac TestGreeting.java
The Greeting.java is compiled
●
automatically.●
Run the application by using the following command:●
java TestGreeting
Locate common compile and runtime errors.●
Java Technology Runtime
Environment
Classes as Blueprints for
Objects
In Java technology, classes support three key features of object-
oriented programming (OOP):
Encapsulation
●
–
Inheritance
Polymorphism
–
– Polymorphism–
Declaring Java Technology
Classes
Basic syntax of a Java class:
<modifier>* class <class_name>
<attribute_declaration>*
<constructor_declaration>*
●
{
<method_declaration>*
}
Declaring Java Technology
Classes
public class Vehicle {
private double maxLoad;
public void setMaxLoad(double
maxLoad = value;
value) {
}
}
Declaring Attributes
Basic syntax of an attribute:●
<modifier>* <type>
<name>
[ = <initial_value>];
Examples:
public class Foo {
●
public class Foo {
private
private
private
}
int x;
float y = 10000.0F;
String name = "Bates Motel";
Declaring Methods
Basic syntax of a method:
<modifier>* <return_type>
<statement>*
}
<name> ( <argument>* ) {
Declaring Methods
public class Dog {
private int weight;
public int getWeight() {
return weight;
}}
public void setWeight(int
if ( newWeight > 0 ) {
weight = newWeight;
}
}
newWeight) {
Accessing Object Members
The dot notation is: <object>.<member>
This is used to access object members, including
methods.
Examples of dot notation are:
d.setWeight(42);
●
attributes and●
●
d.setWeight(42);
d.weight = 42; // only permissible if weight is public
Declaring Constructors
Basic syntax of a constructor:●
[<modifier>] <class_name>
<statement>*
}
Example:
( <argument>* ) {
●
public class Dog {
private int weight;
public Dog() {
weight = 42;
}
}
The Default Constructor
There is always at least one constructor in every class.
If the writer does not supply any constructors, the default
constructor is present automatically:
●
●
The default constructor takes no arguments
The default constructor body is empty
–
– The default constructor body is empty–
The default enables you to create object instances with new
Xxx()without having to write a constructor.
●
Source File Layout
Basic syntax of a Java source file is:
[<package_declaration>]
<import_declaration>*
<class_declaration>+
●
Source File Layout
package shipping.reports;
import
import
import
shipping.domain.*;
java.util.List;
java.io.*;import java.io.*;
public class VehicleCapacityReport
private List vehicles;
{
public void generateReport(Writer output)
{...}
}
Software Packages
Packages help manage large software systems.
Packages can contain classes and sub-packages.
●
●
The package Statement
Basic syntax of the package statement is: package
<top_pkg_name>[.<sub_pkg_name>]*;
●
–
Examples of the statement are:
package shipping.gui.reportscreens;
●
–
Specify the package declaration at the beginning of the source file.Specify the package declaration at the beginning of
Only one package declaration per source file.
the source file.●
●
If no package is declared, then the class is placed into the default
package.
Package names must be hierarchical and separated by dots.
●
●
The import Statement
Basic syntax of the import statement is:
Import<pkg_name>[.<sub_pkg_name>]*.<class_name>;
OR
import<pkg_name>[.<sub_pkg_name>]*.*;
●
Examples of the statement are:●
import
import
import
java.util.List;
java.io.*;
shipping.gui.reportscreens.*;
The import Statement
The import statement does the following:
Precedes all class declarations
Tells the compiler where to find classes
●
●
Comments
The three permissible
styles
program are:
// comment on one line
/* comment on one
of comment in a Java technology
/* comment on one
* or more lines
*/
/** documentation
comment
* can also span one or more
lines
*/
Semicolons, Blocks, and
White Space
A statement is one or more lines of code terminated by a semicolon (;):●
totals = a +
+ d + e + f;
A block is a
and closing
b + c
collection
braces:
of statements bound by opening●
and closing
{
x = y + 1;
y = x + 1;
}
braces:
Semicolons, Blocks, and
White Space
A class definition uses
public class MyDate {
a special block:
private
private
int
int
day;
month;
private
}
int year;
Semicolons, Blocks, and
White Space
You can nest block statements:
while ( i < large
a = a + i;
// nested block
if ( a == max ) {
) {
if ( a == max ) {
b = b + a;
a = 0;
}
i = i + 1;
}
Semicolons, Blocks, and
White Space
Any amount of white
For example:
{int x;x=23*54;}
is equivalent to:
space is permitted in a Java:
{
int x;
x = 23 * 54;
}
Identifiers
Identifiers have the following characteristics:
Are names given to a variable, class, or method
Can start with a Unicode letter, underscore (_),
or
●
dollar sign ($)●
Are case-sensitive
Examples:
and have no maximum length●
● Examples:
identifier
userName
user_name
_sys_var1
$change
●
Keywords
abstract continue for new switch●
assert default goto package
this
synchronized●
boolean do if private●
break
byte
double implements
else import public
protected
throws
throw●
● byte
case
catch
char
class
const
else import public throws●
enum instanceof return transient●
extends int short try●
final interface static void●
finally long strictfp volatile
while
●
floatnative super●
Primitive Types
The Java programming
Logical – boolean
Textual – char
language defines eight primitive types:
●
●
Integral – byte, short, int, and long●
Floating – double and float●
Java Reference Types
In Java technology, beyond primitive types all others are reference
types.
A reference variable contains a handle to an object.
●
●
Car c = new Car();
C is a reference variable
–
– C is a reference variable–
Constructing and
Initializing Objects
Calling new Xyz() performs the following actions:
a. Memory is allocated for the object.
b. Explicit attribute initialization is
performed.
c. A constructor is executed.
●
c. A constructor is executed.
d. The object reference is returned by the
new operator.
The reference to the object is assigned to a variable.
An example is:
MyDate my_birth = new MyDate(22, 7, 1964);
●
●
Memory Allocation and
Layout
A declaration allocates storage only for a reference:
MyDate my_birth = new MyDate(22, 7, 1964);
●
Use the new operator to allocate space for MyDate:
MyDate my_birth = new MyDate(22, 7, 1964);
●
Executing the Constructor
MyDate my_birth = new MyDate(22, 7, 1964);●
Assigning a Variable
Assign the newly created object to the reference variable as
follows:
MyDate my_birth = new MyDate(22, 7, 1964);
●
Assigning References
Two variables refer to a
int x = 7;
int y = x;
single object:
MyDate s = new MyDate(22, 7, 1964);
MyDate t = s;MyDate t = s;
Java Programming Language
Coding Conventions
Packages:
com.example.domain;
●
–
Classes, interfaces, and
SavingsAccount
enum types:●
–
Methods:●
Methods:
GetAccount()–
Variables:
currentCustomer
●
–
Constants:
HEAD_COUNT
●
–
Java Programming Language
Coding Conventions
Control structures:●
if ( condition
statement1;
} else {
) {
statement2;
}
Spacing:●
Use one statement per line.–
Use two or four spaces for indentation.–
Java Programming Language
Coding Conventions
Comments:
Use // to comment inline code.
●
–
Use /** documentation */ for class members.–
Variables and Scope
Local variables are:
Variables that are defined inside a method and are called local,
automatic, temporary, or stack variables
Variables that are created when the method is executed are
destroyed when the method is exited
●
●
destroyed when the method is exited
Variable initialization comprises the following:
Local variables require explicit initialization.
Instance variables are initialized automatically.
●
●
Variable Initialization
Initialization Before
Use Principle
The compiler
before used.
will verify that local variables have been initialized
int
int
int
x=8;
y;
z;int z;
z=x+y;
Operator Precedence
Logical Operators
The boolean operators
! – NOT
are:●
–
| – OR
& – AND
^ – XOR
–
–
^ – XOR–
The short-circuit
&& – AND
boolean operators are:●
–
|| – OR–
Bitwise Logical Operators
The integer bitwise operators
~ – Complement
are:●
–
^ – XOR
& – AND
| – OR
–
–
| – OR–
Bitwise Logical Operators:
Example
Right-Shift Operators >>
and >>>
Arithmetic or signed right
shift
Examples are:
( >> ) operator:●
●
128 >> 1 returns 128/2 1 = 64
256 >> 4 returns 256/2 4 = 16
-256 >> 4 returns -256/2 4 = -
–
–
-256 >> 4 returns -256/2 4 = -
16
–
The sign bit is copied during the shift.
Logical or unsigned right-shift ( >>> )
operator: This operator is used for bit
patterns.
●
●
–
The sign bit is not copied during the
shift.
–
Left-Shift Operator <<
Left-shift ( << ) operator works as follows:
128 << 1 returns 128 * 2 1 = 256
●
–
16 << 2 returns 16 * 2 2 = 64–
Shift Operator Examples
·101010101010101010101
0101010101010101010101
0101010101110111011101
13
57
)
)
5
s>
>
·l1l1l1l1l1l1l1l1l1l1l
1l1l1l1l1l1l1l1l1l1l1l
1l1l1l1l1lol1lol1lol1I
-
135
7
~1
~s,
s ·lololololol1l1l1l1l1l1
l1l1l1l1l1l1l1l1l1l1l1l
1l1l1l1lol1lol1lol1I
>>
>
1
3
"
5
·1°1°1°1°1°1°1°1°1°1°
1°1°1°1°1°1°111°11lol
1lolol1l1lol11ol01°1°1
°1
(
(
>
String Concatenation With +
The + operator works as follows:
Performs String concatenation
●
–
Produces a new String:–
String salutation = "Dr.";String
String
String
salutation = "Dr.";
name = "Pete" + " " + "Seymour";
title = salutation + " " + name;
Casting
If information might be lost in an assignment, the programmer
must
the assignment with a cast.
confirm●
The assignment between long and int requires
an
long bigValue = 99L;
explicit cast.●
int squashed = bigValue;// Wrong, needs a castint
int
squashed
squashed
=
=
bigValue;// Wrong, needs a cast
(int) bigValue; // OK
int
int
int
squashed
squashed
squashed
=
=
=
99L;// Wrong, needs a cast
(int) 99L;// OK, but...
99; // default integer literal
Promotion and Casting
of Expressions
Variables are promoted automatically to a longer form (such as int
to long).
●
Expression is assignment-compatible if the variable
as large
long bigval = 6;// 6 is an int type, OK
type is at least●
long bigval = 6;// 6 is an int type, OK
int smallval = 99L; // 99L is a long, illegal
double z = 12.414F;// 12.414F is float, OK
float z1 = 12.414; // 12.414 is double, illegal
Simple if, else Statements
The if statement syntax:
if ( <boolean_expression> )
<statement_or_block>
Example:
if ( x < 10 )
●
●
if ( x < 10 )
System.out.println("Are
or (recommended): if (
x < 10 ) {
System.out.println("Are
}
you finished yet?");
you finished yet?");
Complex if, else Statements
The if-else statement syntax:
if ( <boolean_expression> )
<statement_or_block>
else
<statement_or_block>
●
Example:
if ( x < 10 ) {
●
System.out.println("Are
} else {
you finished yet?");
System.out.println("Keep working...");
}
Complex if, else Statements
The if-else-if statement syntax:
if ( <boolean_expression> )
<statement_or_block>
else if ( <boolean_expression> )
●
<statement_or_block>
if-else-if statement: Example
Example:
int count = getCount(); // a method
defined if (count < 0) {
●
in the class
System.out.println("Error: count value is
negative.");
} else if (count > getMaxCount()) {
System.out.println("Error: count value is too
big.");
} else {
System.out.println("There will be " + count
+
" people for lunch today.");
}
Switch Statements
The switch statement syntax:
switch ( <expression> ) {
case <constant1>:
<statement_or_block>*
[break;]
case <constant2>:case <constant2>:
<statement_or_block>*
[break;]
default:
<statement_or_block>*
[break;]
}
Switch Statement Example
String carModel = ”STANDARD”;
switch ( carModel ) { case
DELUXE:
System.out.println(“DELUXE”);
break;
case STANDARD:
System.out.println(“Standard”);
break;
default:
System.out.println(“Default”);
}
Switch Statements
Without the break statements, the execution falls through each
subsequent case clause.
●
For Loop
The for loop syntax:
for ( <init_expr>; <test_expr>; <alter_expr> )
<statement_or_block>
●
For Loop Example
for ( int i = 0; i < 10; i++ )
System.out.println(i + " squared
or (recommended):
for ( int i = 0; i < 10; i++ ) {
is " + (i*i));
System.out.println(i + " squared
}
is " + (i*i));
While Loop
The while loop syntax:
while ( <test_expr> )
<statement_or_block>
While Loop Example
Example:
int i = 0;
while ( i < 10 ) {
System.out.println(i + " squared is " + (i*i));
i++;
}
The do/while Loop
The do/while loop syntax:
do
<statement_or_block>
while ( <test_expr> );
●
The do/while
Example
Loop:
Example:
int i = 0; do {
System.out.println(i
i++;
●
+ " squared is " + (i*i));
} while ( i < 10 );
Special Loop Flow
Control
The
The
The
break [<label>]; command
continue [<label>]; command
<label> : <statement> command, where <statement> should be
●
●
●
a loop
The break Statement
do {
statement;
if ( condition
break;
) {
}
statement;
} while ( test_expr );
The continue Statement
do {
statement;
if ( condition
continue;
) {
}
statement;
} while ( test_expr );
Using break
with Labels
Statements
outer:
do {
statement1
;
do {
statement2statement2
;
if ( condition ) {
break outer;
}
statement3;
} while ( test_expr
);
statement4;
} while ( test_expr
);
Using continue
with Labels
Statements
test:
do {
statement1;
do {
statement2;
if ( condition ) {if ( condition ) {
continue test;
}
statement3;
} while ( test_expr
statement4;
} while ( test_expr
);
);
Declaring Arrays
Group data objects of the same type.●
Declare arrays
char s[];
int p[];
of primitive or class types:●
char[] s;
int[] p;
Create space for a reference.●
An array is an object; it is created with new.●
Creating Arrays
Use the new keyword to create an arrayobject.
For example, a primitive (char) array:
public char[] createArray()
char[] s;
{
s = new char[26];
for ( int i=0; i<26; i++ ) {
s[i] = (char) (’A’ + i);
}
return s;
}
Creating an Array of
Character Primitives
Creating Reference Arrays
Another example, an object
array:
public Point[] createArray()
Point[] p;
p = new Point[10];
for ( int i=0; i<10; i++ ) {
{
for ( int i=0; i<10; i++ ) {
p[i] = new Point(i, i+1);
}
return p;
}
Initializing Arrays
Initialize an array element.
Create an array with initial
String[] names;
names = new String[3];
●
values.●
names[0]
names[1]
names[2]
=
=
=
"Georgianna";
"Jen";
"Simon";
Multidimensional Arrays
Arrays of arrays:
int[][] twoDim = new int[4][];
twoDim[0] = new int[5];
twoDim[1] = new int[5];
●
int[][] twoDim = new int[][4]; // illegal
Array of four arrays of five integers each:
int[][] twoDim = new int[4][5];
●
Array Bounds
All array subscripts begin at 0:
public void printElements(int[] list) {
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
}
Using the Enhanced
for Loop
Java 2 Platform, Standard Edition (J2SETM) version 5.0 introduced●
an enhanced for loop for iterating over
public void printElements(int[] list) {
for ( int element : list ) {
System.out.println(element);
arrays:
System.out.println(element);
}
}
Array Resizing
You
You
cannot resize an array.
can use the same reference variable to refer to an entirely new
●
●
array, such as:
int[] myArray = new int[6];
myArray = new int[10];myArray = new int[10];
Copying Arrays
The System.arraycopy() method to copy arrays
//original array
int[] myArray = { 1, 2, 3, 4, 5, 6 };
// new larger array
is:
int[] hold = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
// copy all of the myArray array to the hold
// array, starting with the 0th index
System.arraycopy(myArray, 0, hold, 0, myArray.length);

More Related Content

What's hot

Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Mr. Akaash
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programmingElizabeth Thomas
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and OperatorsMarwa Ali Eissa
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)Sujit Majety
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Java Lover
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 

What's hot (20)

Java Programming
Java ProgrammingJava Programming
Java Programming
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Operators in java
Operators in javaOperators in java
Operators in java
 
String in java
String in javaString in java
String in java
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
java token
java tokenjava token
java token
 
Basic of Java
Basic of JavaBasic of Java
Basic of Java
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 

Similar to Java Presentation For Syntax

Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT studentsPartnered Health
 
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.WebStackAcademy
 
Core Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting StartedCore Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting StartedWebStackAcademy
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)Shaharyar khan
 
Building an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache GroovyBuilding an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache Groovyjgcloudbees
 
The State of the Veil Framework
The State of the Veil FrameworkThe State of the Veil Framework
The State of the Veil FrameworkVeilFramework
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)Ron Munitz
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECSreedhar Chowdam
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java DevelopersMuhammad Abdullah
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 
Introduzione a junit + integrazione con archibus
Introduzione a junit + integrazione con archibusIntroduzione a junit + integrazione con archibus
Introduzione a junit + integrazione con archibusDavide Fella
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to javaSadhanaParameswaran
 
Java programming concept
Java programming conceptJava programming concept
Java programming conceptSanjay Gunjal
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test toolsAllan Huang
 

Similar to Java Presentation For Syntax (20)

Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
 
Core Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting StartedCore Java Programming Language (JSE) : Chapter I - Getting Started
Core Java Programming Language (JSE) : Chapter I - Getting Started
 
Java Tutorial 1
Java Tutorial 1Java Tutorial 1
Java Tutorial 1
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
 
Building an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache GroovyBuilding an Extensible, Resumable DSL on Top of Apache Groovy
Building an Extensible, Resumable DSL on Top of Apache Groovy
 
The State of the Veil Framework
The State of the Veil FrameworkThe State of the Veil Framework
The State of the Veil Framework
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)
 
Java Notes
Java Notes Java Notes
Java Notes
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Introduzione a junit + integrazione con archibus
Introduzione a junit + integrazione con archibusIntroduzione a junit + integrazione con archibus
Introduzione a junit + integrazione con archibus
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
 

Recently uploaded

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Recently uploaded (20)

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Java Presentation For Syntax

  • 1. What is Java Technology? Java technology is: A programming language ● – A development environment An application environment – – It is similar in syntax to C++. It is used for developing both applets ● and applications.● Thanks to its scalable nature, Java has emerged as the most preferred language in Web and Mobile application development
  • 2. Primary Goals of the Java Technology Provides an easy-to-use language by: Avoiding many pitfalls of other languages ● – Being object-oriented Enabling users to create streamlined and clear code – – Provides an interpreted environment for:Provides an interpreted environment for: Improved speed of development ● – Code portability–
  • 3. Primary Goals of the Java Technology Enables users to run more than one thread of activity Loads classes dynamically; that is, at the time they are actually needed Supports changing programs dynamically during runtime by loading classes from disparate sources ● ● ● classes from disparate sources Furnishes better security●
  • 4. Primary Goals of the Java Technology The following features fulfill these goals: The Java Virtual Machine (JVMTM) 1 Garbage collection The Java Runtime Environment (JRE) ● ● ● ●
  • 5. The Java Virtual Machine a specification that provides runtime environment in which java byte code can be executed. Reads compiled byte codes that are platform-independent JVMs are available for many hardware and software platforms. JVM is platform dependent because configuration of each OS differs. The Java Virtual Machine(JVM) make the code run in any platform, thereby making it platform independent JVM is platform dependent because configuration of each OS differs. But, Java is platform independent
  • 6. Garbage Collection Allocated memory that is no longer needed should be deallocated. In other languages, deallocation is the programmer’s responsibility. The Java programming language provides a system-level thread to track memory allocation. ● ● ●
  • 7. Garbage Collection Garbage collection has the following characteristics: Checks for and frees memory no longer needed Is done automatically Can vary dramatically across JVM implementations ● ● ●
  • 8.
  • 10. JVM Tasks The JVM performs Loads code Verifies code Executes code three main tasks: ● ● ●
  • 11. The Class Loader Loads all classes necessary for the execution of a program Maintains classes of the local file system in separate namespaces ● ●
  • 12. The Bytecode Verifier The The The The code code code adheres to the JVM specification. does not violate system integrity. causes no operand stack overflows or underflows. ● ● ● parameter types for all operational code are● correct. No illegal data conversions (the conversion of integers to pointers) have occurred. ●
  • 13. Simple Object-Oriented Platform independent Features of Java Secured Robust Architecture neutral Multithreaded Distributed
  • 14. Simple Java Application The TestGreeting.java Application // // Sample "Hello World" application // public class TestGreeting{public class TestGreeting{ public static void main (String[] args) Greeting hello = new Greeting(); hello.greet(); } } {
  • 15. A Simple Java Application The Greeting.java Class public class Greeting { public void greet() { System.out.println(“hi”); } }
  • 16. Compiling and Running the TestGreeting Program Compile TestGreeting.java: javac TestGreeting.java The Greeting.java is compiled ● automatically.● Run the application by using the following command:● java TestGreeting Locate common compile and runtime errors.●
  • 18. Classes as Blueprints for Objects In Java technology, classes support three key features of object- oriented programming (OOP): Encapsulation ● – Inheritance Polymorphism – – Polymorphism–
  • 19. Declaring Java Technology Classes Basic syntax of a Java class: <modifier>* class <class_name> <attribute_declaration>* <constructor_declaration>* ● { <method_declaration>* }
  • 20. Declaring Java Technology Classes public class Vehicle { private double maxLoad; public void setMaxLoad(double maxLoad = value; value) { } }
  • 21. Declaring Attributes Basic syntax of an attribute:● <modifier>* <type> <name> [ = <initial_value>]; Examples: public class Foo { ● public class Foo { private private private } int x; float y = 10000.0F; String name = "Bates Motel";
  • 22. Declaring Methods Basic syntax of a method: <modifier>* <return_type> <statement>* } <name> ( <argument>* ) {
  • 23. Declaring Methods public class Dog { private int weight; public int getWeight() { return weight; }} public void setWeight(int if ( newWeight > 0 ) { weight = newWeight; } } newWeight) {
  • 24. Accessing Object Members The dot notation is: <object>.<member> This is used to access object members, including methods. Examples of dot notation are: d.setWeight(42); ● attributes and● ● d.setWeight(42); d.weight = 42; // only permissible if weight is public
  • 25. Declaring Constructors Basic syntax of a constructor:● [<modifier>] <class_name> <statement>* } Example: ( <argument>* ) { ● public class Dog { private int weight; public Dog() { weight = 42; } }
  • 26. The Default Constructor There is always at least one constructor in every class. If the writer does not supply any constructors, the default constructor is present automatically: ● ● The default constructor takes no arguments The default constructor body is empty – – The default constructor body is empty– The default enables you to create object instances with new Xxx()without having to write a constructor. ●
  • 27. Source File Layout Basic syntax of a Java source file is: [<package_declaration>] <import_declaration>* <class_declaration>+ ●
  • 28. Source File Layout package shipping.reports; import import import shipping.domain.*; java.util.List; java.io.*;import java.io.*; public class VehicleCapacityReport private List vehicles; { public void generateReport(Writer output) {...} }
  • 29. Software Packages Packages help manage large software systems. Packages can contain classes and sub-packages. ● ●
  • 30. The package Statement Basic syntax of the package statement is: package <top_pkg_name>[.<sub_pkg_name>]*; ● – Examples of the statement are: package shipping.gui.reportscreens; ● – Specify the package declaration at the beginning of the source file.Specify the package declaration at the beginning of Only one package declaration per source file. the source file.● ● If no package is declared, then the class is placed into the default package. Package names must be hierarchical and separated by dots. ● ●
  • 31. The import Statement Basic syntax of the import statement is: Import<pkg_name>[.<sub_pkg_name>]*.<class_name>; OR import<pkg_name>[.<sub_pkg_name>]*.*; ● Examples of the statement are:● import import import java.util.List; java.io.*; shipping.gui.reportscreens.*;
  • 32. The import Statement The import statement does the following: Precedes all class declarations Tells the compiler where to find classes ● ●
  • 33. Comments The three permissible styles program are: // comment on one line /* comment on one of comment in a Java technology /* comment on one * or more lines */ /** documentation comment * can also span one or more lines */
  • 34. Semicolons, Blocks, and White Space A statement is one or more lines of code terminated by a semicolon (;):● totals = a + + d + e + f; A block is a and closing b + c collection braces: of statements bound by opening● and closing { x = y + 1; y = x + 1; } braces:
  • 35. Semicolons, Blocks, and White Space A class definition uses public class MyDate { a special block: private private int int day; month; private } int year;
  • 36. Semicolons, Blocks, and White Space You can nest block statements: while ( i < large a = a + i; // nested block if ( a == max ) { ) { if ( a == max ) { b = b + a; a = 0; } i = i + 1; }
  • 37. Semicolons, Blocks, and White Space Any amount of white For example: {int x;x=23*54;} is equivalent to: space is permitted in a Java: { int x; x = 23 * 54; }
  • 38. Identifiers Identifiers have the following characteristics: Are names given to a variable, class, or method Can start with a Unicode letter, underscore (_), or ● dollar sign ($)● Are case-sensitive Examples: and have no maximum length● ● Examples: identifier userName user_name _sys_var1 $change ●
  • 39. Keywords abstract continue for new switch● assert default goto package this synchronized● boolean do if private● break byte double implements else import public protected throws throw● ● byte case catch char class const else import public throws● enum instanceof return transient● extends int short try● final interface static void● finally long strictfp volatile while ● floatnative super●
  • 40. Primitive Types The Java programming Logical – boolean Textual – char language defines eight primitive types: ● ● Integral – byte, short, int, and long● Floating – double and float●
  • 41. Java Reference Types In Java technology, beyond primitive types all others are reference types. A reference variable contains a handle to an object. ● ● Car c = new Car(); C is a reference variable – – C is a reference variable–
  • 42. Constructing and Initializing Objects Calling new Xyz() performs the following actions: a. Memory is allocated for the object. b. Explicit attribute initialization is performed. c. A constructor is executed. ● c. A constructor is executed. d. The object reference is returned by the new operator. The reference to the object is assigned to a variable. An example is: MyDate my_birth = new MyDate(22, 7, 1964); ● ●
  • 43. Memory Allocation and Layout A declaration allocates storage only for a reference: MyDate my_birth = new MyDate(22, 7, 1964); ● Use the new operator to allocate space for MyDate: MyDate my_birth = new MyDate(22, 7, 1964); ●
  • 44. Executing the Constructor MyDate my_birth = new MyDate(22, 7, 1964);●
  • 45. Assigning a Variable Assign the newly created object to the reference variable as follows: MyDate my_birth = new MyDate(22, 7, 1964); ●
  • 46. Assigning References Two variables refer to a int x = 7; int y = x; single object: MyDate s = new MyDate(22, 7, 1964); MyDate t = s;MyDate t = s;
  • 47. Java Programming Language Coding Conventions Packages: com.example.domain; ● – Classes, interfaces, and SavingsAccount enum types:● – Methods:● Methods: GetAccount()– Variables: currentCustomer ● – Constants: HEAD_COUNT ● –
  • 48. Java Programming Language Coding Conventions Control structures:● if ( condition statement1; } else { ) { statement2; } Spacing:● Use one statement per line.– Use two or four spaces for indentation.–
  • 49. Java Programming Language Coding Conventions Comments: Use // to comment inline code. ● – Use /** documentation */ for class members.–
  • 50. Variables and Scope Local variables are: Variables that are defined inside a method and are called local, automatic, temporary, or stack variables Variables that are created when the method is executed are destroyed when the method is exited ● ● destroyed when the method is exited Variable initialization comprises the following: Local variables require explicit initialization. Instance variables are initialized automatically. ● ●
  • 52. Initialization Before Use Principle The compiler before used. will verify that local variables have been initialized int int int x=8; y; z;int z; z=x+y;
  • 54. Logical Operators The boolean operators ! – NOT are:● – | – OR & – AND ^ – XOR – – ^ – XOR– The short-circuit && – AND boolean operators are:● – || – OR–
  • 55. Bitwise Logical Operators The integer bitwise operators ~ – Complement are:● – ^ – XOR & – AND | – OR – – | – OR–
  • 57. Right-Shift Operators >> and >>> Arithmetic or signed right shift Examples are: ( >> ) operator:● ● 128 >> 1 returns 128/2 1 = 64 256 >> 4 returns 256/2 4 = 16 -256 >> 4 returns -256/2 4 = - – – -256 >> 4 returns -256/2 4 = - 16 – The sign bit is copied during the shift. Logical or unsigned right-shift ( >>> ) operator: This operator is used for bit patterns. ● ● – The sign bit is not copied during the shift. –
  • 58. Left-Shift Operator << Left-shift ( << ) operator works as follows: 128 << 1 returns 128 * 2 1 = 256 ● – 16 << 2 returns 16 * 2 2 = 64–
  • 59. Shift Operator Examples ·101010101010101010101 0101010101010101010101 0101010101110111011101 13 57 ) ) 5 s> > ·l1l1l1l1l1l1l1l1l1l1l 1l1l1l1l1l1l1l1l1l1l1l 1l1l1l1l1lol1lol1lol1I - 135 7 ~1 ~s, s ·lololololol1l1l1l1l1l1 l1l1l1l1l1l1l1l1l1l1l1l 1l1l1l1lol1lol1lol1I >> > 1 3 " 5 ·1°1°1°1°1°1°1°1°1°1° 1°1°1°1°1°1°111°11lol 1lolol1l1lol11ol01°1°1 °1 ( ( >
  • 60. String Concatenation With + The + operator works as follows: Performs String concatenation ● – Produces a new String:– String salutation = "Dr.";String String String salutation = "Dr."; name = "Pete" + " " + "Seymour"; title = salutation + " " + name;
  • 61. Casting If information might be lost in an assignment, the programmer must the assignment with a cast. confirm● The assignment between long and int requires an long bigValue = 99L; explicit cast.● int squashed = bigValue;// Wrong, needs a castint int squashed squashed = = bigValue;// Wrong, needs a cast (int) bigValue; // OK int int int squashed squashed squashed = = = 99L;// Wrong, needs a cast (int) 99L;// OK, but... 99; // default integer literal
  • 62. Promotion and Casting of Expressions Variables are promoted automatically to a longer form (such as int to long). ● Expression is assignment-compatible if the variable as large long bigval = 6;// 6 is an int type, OK type is at least● long bigval = 6;// 6 is an int type, OK int smallval = 99L; // 99L is a long, illegal double z = 12.414F;// 12.414F is float, OK float z1 = 12.414; // 12.414 is double, illegal
  • 63. Simple if, else Statements The if statement syntax: if ( <boolean_expression> ) <statement_or_block> Example: if ( x < 10 ) ● ● if ( x < 10 ) System.out.println("Are or (recommended): if ( x < 10 ) { System.out.println("Are } you finished yet?"); you finished yet?");
  • 64. Complex if, else Statements The if-else statement syntax: if ( <boolean_expression> ) <statement_or_block> else <statement_or_block> ● Example: if ( x < 10 ) { ● System.out.println("Are } else { you finished yet?"); System.out.println("Keep working..."); }
  • 65. Complex if, else Statements The if-else-if statement syntax: if ( <boolean_expression> ) <statement_or_block> else if ( <boolean_expression> ) ● <statement_or_block>
  • 66. if-else-if statement: Example Example: int count = getCount(); // a method defined if (count < 0) { ● in the class System.out.println("Error: count value is negative."); } else if (count > getMaxCount()) { System.out.println("Error: count value is too big."); } else { System.out.println("There will be " + count + " people for lunch today."); }
  • 67. Switch Statements The switch statement syntax: switch ( <expression> ) { case <constant1>: <statement_or_block>* [break;] case <constant2>:case <constant2>: <statement_or_block>* [break;] default: <statement_or_block>* [break;] }
  • 68. Switch Statement Example String carModel = ”STANDARD”; switch ( carModel ) { case DELUXE: System.out.println(“DELUXE”); break; case STANDARD: System.out.println(“Standard”); break; default: System.out.println(“Default”); }
  • 69. Switch Statements Without the break statements, the execution falls through each subsequent case clause. ●
  • 70. For Loop The for loop syntax: for ( <init_expr>; <test_expr>; <alter_expr> ) <statement_or_block> ●
  • 71. For Loop Example for ( int i = 0; i < 10; i++ ) System.out.println(i + " squared or (recommended): for ( int i = 0; i < 10; i++ ) { is " + (i*i)); System.out.println(i + " squared } is " + (i*i));
  • 72. While Loop The while loop syntax: while ( <test_expr> ) <statement_or_block>
  • 73. While Loop Example Example: int i = 0; while ( i < 10 ) { System.out.println(i + " squared is " + (i*i)); i++; }
  • 74. The do/while Loop The do/while loop syntax: do <statement_or_block> while ( <test_expr> ); ●
  • 75. The do/while Example Loop: Example: int i = 0; do { System.out.println(i i++; ● + " squared is " + (i*i)); } while ( i < 10 );
  • 76. Special Loop Flow Control The The The break [<label>]; command continue [<label>]; command <label> : <statement> command, where <statement> should be ● ● ● a loop
  • 77. The break Statement do { statement; if ( condition break; ) { } statement; } while ( test_expr );
  • 78. The continue Statement do { statement; if ( condition continue; ) { } statement; } while ( test_expr );
  • 79. Using break with Labels Statements outer: do { statement1 ; do { statement2statement2 ; if ( condition ) { break outer; } statement3; } while ( test_expr ); statement4; } while ( test_expr );
  • 80. Using continue with Labels Statements test: do { statement1; do { statement2; if ( condition ) {if ( condition ) { continue test; } statement3; } while ( test_expr statement4; } while ( test_expr ); );
  • 81. Declaring Arrays Group data objects of the same type.● Declare arrays char s[]; int p[]; of primitive or class types:● char[] s; int[] p; Create space for a reference.● An array is an object; it is created with new.●
  • 82. Creating Arrays Use the new keyword to create an arrayobject. For example, a primitive (char) array: public char[] createArray() char[] s; { s = new char[26]; for ( int i=0; i<26; i++ ) { s[i] = (char) (’A’ + i); } return s; }
  • 83. Creating an Array of Character Primitives
  • 84. Creating Reference Arrays Another example, an object array: public Point[] createArray() Point[] p; p = new Point[10]; for ( int i=0; i<10; i++ ) { { for ( int i=0; i<10; i++ ) { p[i] = new Point(i, i+1); } return p; }
  • 85. Initializing Arrays Initialize an array element. Create an array with initial String[] names; names = new String[3]; ● values.● names[0] names[1] names[2] = = = "Georgianna"; "Jen"; "Simon";
  • 86. Multidimensional Arrays Arrays of arrays: int[][] twoDim = new int[4][]; twoDim[0] = new int[5]; twoDim[1] = new int[5]; ● int[][] twoDim = new int[][4]; // illegal Array of four arrays of five integers each: int[][] twoDim = new int[4][5]; ●
  • 87. Array Bounds All array subscripts begin at 0: public void printElements(int[] list) { for (int i = 0; i < list.length; i++) { System.out.println(list[i]); } }
  • 88. Using the Enhanced for Loop Java 2 Platform, Standard Edition (J2SETM) version 5.0 introduced● an enhanced for loop for iterating over public void printElements(int[] list) { for ( int element : list ) { System.out.println(element); arrays: System.out.println(element); } }
  • 89. Array Resizing You You cannot resize an array. can use the same reference variable to refer to an entirely new ● ● array, such as: int[] myArray = new int[6]; myArray = new int[10];myArray = new int[10];
  • 90. Copying Arrays The System.arraycopy() method to copy arrays //original array int[] myArray = { 1, 2, 3, 4, 5, 6 }; // new larger array is: int[] hold = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; // copy all of the myArray array to the hold // array, starting with the 0th index System.arraycopy(myArray, 0, hold, 0, myArray.length);