0% found this document useful (0 votes)
9 views46 pages

Java Programming Fundamentals Overview

Uploaded by

Elshaday Abraham
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views46 pages

Java Programming Fundamentals Overview

Uploaded by

Elshaday Abraham
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Java Programming

Language
OOP Perspective

1
The History of Java
• Comes out of ‘Green Project’ in 1991.
• Created by ‘James Gosling’ and called it Oak.
• Released to the public in 1995 by Sun
Microsystems.
• It was completely processor-independent.
• Its primary feature is that it could function
nicely in a networked environment.
• The explosion of WWW created an
environment in which the language could
live.
2
The features of Java
Technology
• Java technology can be seen as both a language
and a platform.
• Using it you can write applications that can run on
practically any device, including a PC, PDA, a
cellular phone or a television.
• The Java platform is formed from two components:
 The Java application programming interface (Java API)
• Set if libraries that are used to accomplish tasks such as
creating GUIs, performing file I/O and establishing network
comm.
 The Java Virtual Machine (JVM)
• Is in charge of executing your code in a specific environment.

3
Features of Java
• Java is Simple
 Because of the stylistic simplicity of the language,
many people learn it quickly.
• Java is Object Oriented
 The OOP paradigm has risen in popularity and has
become the de facto standard for today’s software
dev’t.
• Java is both Compiled and Interpreted
 Java source code is passed to a compiler that
generates the bytecode.
• JVM interpretes the bytecode at runtime and executes it.

4
Features of Java ….
• Java is portable
 Java applications can run practically anywhere.
 You can truly write the code once and run it
anywhere.
• Java is Robust
 Robust code is reliable code.
 Java is considered a strongly typed language.
 JVM insures robustness managing all memory
automatically.
 Java also includes an extensible mechanism for
exception handling.
5
Features of Java …
• Java is Secure
 Because Java technology is so prevalent on
networks and in today’s enterprise systems, it
security aspects as vital.
• Java is Multithreaded
 Java provides feature with which you can develop
application that can do more than one thing at a
time.
• Java is High Performance
 Java versions have performed at the speed that
developers demand.

6
Fundamentals of Java…
• Identifiers
 Identifiers are the names used for variables, classes,
methods, packages, and interfaces to distinguish
them to the compiler.
 Identifiers in the Java language should always begin
with a letter of the alphabet, either upper or lower
case.
 The only exceptions to this rule are the underscore
symbol (_) and the dollar sign ($), which may also be
used.
 After the initial character you are allowed to use
numbers, but not all symbols.
 You must also be careful not to use any of the special
Java keywords. 7
Fundamentals of Java…
 Here are some examples of valid identifiers:
HelloWorld $Money TickerTape
_ME2 Chapter3 ABC123
• Keywords
 These are reserved for system use.
 They can’t be used as names for your classes,
variables, packages, or anything else.
 Keywords are used for a number of tasks such as
defining control structures (if, while, and for) and
declaring data types (int, char, and float).

8
Fundamentals of Java…
• Literals
 Literals are the values that you assign when
entering explicit values.
 For example, in an assignment statement like i =
10; the value 10 is a literal.
 Do not get literals confused with types.
• Types are used to define what type of data a variable can
hold, while literals are the values that are actually
assigned to those variables.
 Literals come in three flavors: numeric, character,
and boolean.
• Boolean literals are simply True and False.

9
Fundamentals of Java…
• Numeric Literals
 Numeric literals are just what they sound like - numbers.
 We can subdivide the numeric literals further into
integers and floating-point literals.
 Integer literals are usually represented in decimal
format.
 You can use the hexadecimal and octal format in Java.
• Octal integers simply begin with a zero (0).
• Hexadecimal integers begin with 0x or 0X.
 Integer literals are stored differently depending on their
size: int and long.
• The int data type is used to store 32-bit integer values.
• The long data type stores 64-bit integer values.

10
Fundamentals of Java…
 For Example: the followings are valid assignment
of literals.
int i;
i = 1; // All of these literals are of the integer type
i = 0xA11; // Using a hexadecimal literal
i = 07543; // Using an octal literal
i = 4.5; // This would be illegal because a floating-point.
 Floating-point values are any numbers that have
anything to the right of the decimal place.
 Similar to integers, floating-point values have 32-
bit (float) and 64-bit (double) representations.

11
Fundamentals of Java…
 For example: The followings are valid ways of
assigning floating point numbers
 float f;
f = 1.3; //All of these literals are of the floating-point
f = -9.0;
f = 1203131.1241234;
 double d;
d = 1.0D; //All of these literals are of the floating-point
type double(32-bit)
d = -9.3645e235;
d = 7.0001e52D;

12
Fundamentals of Java…
• Character Literals
 Character literals include single characters and
strings.
 Single character literals are enclosed in single
quotation marks while string literals are enclosed
in double quotes.
 For example:
• char ch;
– ch = 'a'; //All of these literals are characters
• String str;
– str = "Java string"; //String literals

13
Fundamentals of Java…
• Operators
 Operators are used to perform computations on
one or more variables or objects.
 For Example:
Operator Description
+ Addition
++ Increment
!= Not equal to
+= Assignment with addition

14
Fundamentals of Java…
• Separators
 Separators are used in Java to delineate blocks of code.
 For example, you use curly brackets
• to enclose a method’s implementation, and
• you use parentheses to enclose arguments being sent to a
method.
 For Example:
Separator Description
() Used to define blocks of arguments
[] Used to define arrays
{} Used to hold blocks of code
, Used to separate variables in a declaration
; Used to terminate lines of contiguous code

15
Fundamentals of Java…
• Types and Variables
 Variables are basically buckets that hold
information, while types describe what type of
information is in the bucket.
 A variable must have both a type and an
identifier.
 Similar to literals, types can be split into several
different categories including the numeric types -
byte, short, int, long, float, and double - and
the char and boolean types.

16
Fundamentals of Java…
• Primitive data types: e.g. char, int, double
• Reference/Object data types: e.g. Ball b;
Variable declarations
 Declaring variables in Java is very similar to
declaring variables in C/C++ as long as you are
using the primitive data types.
 Almost everything in Java is a class - except the
primitive data types.
 Here is what a standard declaration for a primitive
variable might look like: int i;

17
Fundamentals of Java…
• We have just declared a variable “i” to be an integer.
• Here are a few more examples:
byte i, j;
int a=7, b = a;
float f = 1.06;
String name = "Tony";

• For example, the following statement defines a variable


that can reference objects created from a class named
Ball:
Ball b;

18
Fundamentals of Java…
Types of Variables
Local Variables
• A local variable is a variable declared inside a method
body, block or constructor
• Only accessible inside the method, block or constructor
that declared it.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared
method, constructor, or block.
 Local variables are implemented at stack level
internally.
 Default values are not assigned to local variables in
Java.
19
Fundamentals of Java…
Instance Variables
• Instance variables are non-static variables and
are declared in a class outside any method,
constructor, or block.
 Instance variables are created when an object is
created with the use of the keyword 'new' and
destroyed when the object is destroyed.
 Access modifiers can be given for instance variables. If
we do not specify any access modifier, then the default
access modifier will be used.
 Initialization of instance variable is not mandatory. Its
default value is 0 for numbers, false for Booleans and
null for object references
20
Fundamentals of Java…
Class/Static Variables
• Class variables/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.
 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.

21
Fundamentals of Java…
For example:
public class VariableExample {
public static String myClassVar="class variable";
String myVar="instance variable";
public void myMethod(){
String myVar = "Inside Method";
[Link](myVar); }
public static void main(String args[]){
// Creating object
VariableExample obj = new VariableExample();

[Link]([Link]);
[Link]();
[Link]([Link]);
}
}
22
Fundamentals of Java…
• Decision and Repetition statements
 Decision making structures have one or more
conditions to be evaluated or tested by the
program, along with a statement or statements
that are to be executed if the condition is
determined to be true, and optionally, other
statements to be executed if the condition is
determined to be false.
 Java programming language provides following
types of decision making statements.
• conditional statement
• switch statement

23
Fundamentals of Java…
• Conditional statement: if
 An if statement consists of a Boolean expression
followed by one or more statements.
 Syntax:
if (condition)
Statement1;
 For example, the following fragment of code prints
"This is if statement" only if the value stored in
the x variable is indeed 100:
if( x ==100 ) {
[Link]("This is if statement");
}

24
Fundamentals of Java…
• Conditional structure: if…else
 An if else statement is a conditional statement that
runs a different set of statements depending on
whether an expression is true or false.
 Syntax:
if (condition)
Statement1;
else
Statement2;
 Example:
if (x == 100)
[Link] ("x is 100");
else
[Link] ("x is not 100");
25
Fundamentals of Java…
• Switch statement
 A switch statement allows a variable to be tested for
equality against a list of values. Each value is called a case,
and the variable being switched on is checked for each case.
 Syntax
switch(expression) {
case constant 1 :
Statements;
break; // optional
case constant 2:
Statements;
break; // optional

default: // Optional
Statements;
}
26
Fundamentals of Java…
case 6: monthString = "June";
public class SwitchDemo { break;
public static void main(String[] case 7: monthString = "July";
args) { break;
case 8: monthString = "August";
int month = 8; break;
String monthString; case 9: monthString =
switch (month) { "September";
break;
case 1: monthString =
case 10: monthString = "October";
"January"; break;
break; case 11: monthString =
case 2: monthString = "November";
"February"; break;
case 12: monthString =
break; "December";
case 3: monthString = "March"; break;
break; default: monthString = "Invalid
month";
case 4: monthString = "April"; break;
break; }
case 5: monthString = "May"; [Link](monthString); 27
}
Fundamentals of Java…
• Iterative statement(Loop)
 A loop statement allows us to execute a
statement or group of statements multiple times.
 Java programming language provides the
following types of loop to handle looping
requirements.
• while
• do…while
• for

28
Fundamentals of Java…
While Loop: executes a set of statements as long as the
condition specified at the beginning is true
Syntax:
while (condition) {
statement1;

statement n;
}
Example: to display numbers from 10 -20
int x = 10;
while( x < =20 ) {
[Link]("value of x : " + x );
x++; }
29
Fundamentals of Java…
• do-while loop is similar to while loop except the
loop always executed at least once, regardless of
whether the condition is true or not.
• Syntax
do {
Statements;
} while(Boolean_expression);
Example: do…while loop to display numbers from 10 -
20
int x = 10;
while( x < =20 ) {
[Link]("value of x : " + x );
x++; } 30
Fundamentals of Java…
• The for loop is similar to the while statement, but has two
additional components: an expression which is evaluated
only once before everything else, and an expression which
is evaluated once at the end of each iteration.
Syntax:
for(initialization; Boolean_expression; update) {
Statements;
}
Example: fragment of code to display numbers from 10-20
using for loop.
for(int x = 10; x <= 20; x = x + 1) {
[Link](x );
}
31
Fundamentals of Java…
• Using Arrays
 Java uses arrays in a much different manner than
other languages.
 Arrays in Java are actually objects that can be
treated just like any other Java object.
 Because arrays are objects that are derived from
a class, they have methods you can call to
retrieve information about the array or to
manipulate the array.

32
Fundamentals of Java…
• Declaring Arrays
 Since arrays are actually instances of classes
(objects), we need to use constructors to create
arrays much like we do with strings.
• First, we need to pick a variable name and declare it as an
array object and also specify which data type the array will
hold.
• Note that an array can only hold a single data type - you
can’t mix strings and integers within a single array.
• Here are a few examples of how array variables are
declared:
int intArray[];
String Names[];
• You could also put the brackets after the data type if you
think this approach makes your declarations more readable.
33
Fundamentals of Java…
• Sizing Arrays
 There are three ways to set the size of arrays.
• Taking a previously declared variable and setting the size
of the array.
Int Array[] = new int[10];
String Names[] = new String[100];
• You can size the array object when you declare it.
int intArray[] = new int[10];
String Names[] = new String[100];
• Finally, you can fill in the array with values at declaration
time:
String Names[] = {"Tony", "Dave", "Jon", "Ricardo"};
int[] intArray = {1, 2, 3, 4, 5};
34
Fundamentals of Java…
• Accessing Array Elements
 To access an array value, you simply need to know
its location.
 The indexing system used to access array elements
is zero-based, which means that the first value is
always located at position 0.
class MyArrays{
public static void main(String args[]){
int even[] = {2,4,6,8,10};
[Link]("The second even is: " + even[0]);
}
}
• Displays the first item in the array list by its specific
location within the list.
Fundamentals of Java…
• Exception-Handling
 An exception is an abnormal condition that arises in a
code sequence at run time.
 Following are some scenarios where an exception
occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of
communications or the JVM has run out of memory.
 Java’s exception handling avoids these problems
 Error: An Error indicates serious problem that a
reasonable application should not try to catch.
 Exception: Exception indicates conditions that a
reasonable application might try to catch.
• A programmer can handle such conditions and take
36
necessary corrective actions.
Fundamentals of Java…
• The core advantage of exception handling is to maintain the
normal flow of the application. Let's consider a scenario:
statement 1;
statement 2;
statement 3;
statement 4; //exception occurs
statement 5;
statement 6;
statement 7;

• Suppose there are 7 statements in a Java program and an


exception occurs at statement 4; the rest of the code will not be
executed. However, when we perform exception handling, the rest
of the statements will be executed. That is why we use exception
handling in Java.
37
Fundamentals of Java…
• Hierarchy of Java Exception classes

38
• Throwable
 It is the root class for the exception hierarchy in java.
 It is in the [Link] package.
 Error – Subclass of Throwable.
• Consist of abnormal condition that is out of one’s
control and depends on the environment
• They can’t be handled and will always result in the
halting of the program.
 Exception – Subclass of Throwable.
• Consist of abnormal conditions that can be handled
explicitly.
• If one handles the exception then our code will
continue to execute smoothly.
39
Fundamentals of Java…
• Exceptions can be of two types:
 Checked Exceptions: checked at compile time. If
some code within a method throws a checked
exception, then the method must either handle the
exception or it must specify the exception using the
throws keyword.
 Unchecked Exceptions: are not checked at compile
time. Conditions that reflect errors in your program's
logic and cannot be reasonably recovered from at
run time.

40
Fundamentals of Java…
• Exception-Handling Fundamentals
 When an exceptional condition arises, an object
representing that exception is created and thrown in
the method that caused the error. That method may
choose to handle the exception itself, or pass it on.
Either way, at some point, the exception is caught
and processed.
 Exceptions can be generated by the Java run-time
system, or they can be manually generated by your
code.
• Exceptions thrown by Java relate to fundamental errors that
violate the rules of the Java language or the constraints of the
Java execution environment.
• Manually generated exceptions are typically used to report
some error condition to the caller of a method. 41
Fundamentals of Java…

42
Fundamentals of Java…
Java exception handling is managed via five keywords: try,
catch, throw, throws, and finally.

Keyword Description
try used to specify a block where we should place an
exception code.
catch used to handle the exception.

finally used to execute the necessary code of the program.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions.


It specifies that there may occur an exception in the
method.
43
Fundamentals of Java…
• The general syntax is as follows:
try{
...
}
catch(ExceptionClass1 e){
...
}
catch(ExceptionClassLast e){
...
}
finally{
< Code to be executed whether or not an exception is
thrown or caught.>
}
44
Fundamentals of Java…
• Advantage of Exception Handling
 The main advantage of exception handling
technique is to maintain the normal flow of the
program.
 It provides flexibility in handling situations of
errors.
 It allows us to define a user-friendly message to
handle the exception.
 The exception handling technique helps to
separate “Error-Handling code” from “Regular
code.”

45
Fundamentals of Java…
• Basic Syntax
 Case Sensitivity - Java is case sensitive, which means
identifier Hello and hello would have different meaning in
Java.
 Class Names - For all class names the first letter should be
in upper case.
 Method Names - All method names should start with a
lower case letter.
 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.
 public static void main(String args[]) - Java program
processing starts from the main() method which is a
mandatory part of every Java program 46

You might also like