0% found this document useful (0 votes)
17 views47 pages

Chapter 1

u

Uploaded by

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

Chapter 1

u

Uploaded by

nugusatola62
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Chapter 1

Introduction To Java
(Review)

Advanced Programming RVU Comp.Science Dept. 1


What is Java?
❖ Java is an object-oriented programming language
❖ The Java programming language was created by Sun
Microsystems, Inc.
❖ It was introduced in 1995 and it's popularity has grown quickly
since
❖ 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.
❖ Sun Microsystems has renamed the new J2 versions as Java SE,
Java EE and Java ME, respectively.
❖ Java is guaranteed to be Write Once, Run Anywhere.

Advanced Programming RVU Comp.Science Dept. 2


What is Java?….
❖ 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
communication.
❖ The Java Virtual Machine (JVM):
❖ Is in charge of executing your code in a specific environment.

Advanced Programming RVU Comp.Science Dept. 3


Cont’d….
❖ The JVM is what gives Java its cross-platform capabilities.
❖ The Java file is not compiled into a machine language, which is
different for each operating system and computer architecture.
❖ Java code is compiled into byte-code(platform independent).
❖ Java Virtual Machine is a software that interprets Java
bytecode.
Java Bytecode

Java Virtual
Machine

Any
Computer

Advanced Programming RVU Comp.Science Dept. 4


Characteristics of Java…
❖ Java is:
❖ Object Oriented: In Java, everything is an Object.
❖ Java can be easily extended since it is based on the Object
model.
❖ Platform independent: Unlike many other programming
languages including C and C++, when Java is compiled, it is not
compiled into platform specific machine, rather into platform
independent byte code.
❖ This byte code is distributed over the web and interpreted by
virtual Machine (JVM) on whichever platform it is being run.
❖ Simple: Java is designed to be easy to learn. If you understand the
basic concept of OOP, Java would be easy to master.

Advanced Programming RVU Comp.Science Dept. 5


Characteristics of Java…
❖ Secure: With Java's secure feature, it enables to develop virus-
free, tamper-free systems.
❖ Authentication techniques are based on public-key
encryption.
❖ Architectural-neutral: Java compiler generates an
architecture-neutral object file format, which makes the
compiled code to be executable on many processors, with the
presence of Java runtime system.
❖ Portable: Being architectural-neutral and having no
implementation dependent aspects of the specification makes
Java portable.
❖ Compiler in Java is written in ANSI C with a clean
portability boundary which is a POSIX subset.
Advanced Programming RVU Comp.Science Dept. 6
Characteristics of Java…
❖ Robust: Java makes an effort to eliminate error prone situations
by emphasizing mainly on compile time error checking and
runtime checking.
❖ Multithreaded: With Java's multithreaded feature, it is possible
to write programs that can do many tasks simultaneously.
❖ This design feature allows developers to construct smoothly
running interactive applications.

Advanced Programming RVU Comp.Science Dept. 7


Characteristics of Java…
❖ Interpreted: Java byte code is translated on the fly to native
machine instructions and is not stored anywhere.
❖ The development process is more rapid and analytical since
the linking is an incremental and lightweight process.
❖ High Performance: With the use of Just-In-Time compilers, Java
enables high performance.
❖ Distributed: Java is designed for the distributed environment of
the internet.
❖ Dynamic: Java is considered to be more dynamic than C or C++
since it is designed to adapt to an evolving environment.
❖ Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to
objects on run-time.

Advanced Programming RVU Comp.Science Dept. 8


Starting Java…
❖ Java Basic Syntax:
❖ 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 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.

Advanced Programming RVU Comp.Science Dept. 9


Starting Java …
❖ 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.

Advanced Programming RVU Comp.Science Dept. 10


Starting Java …
❖ First Java Program:
❖ Let us look at a simple code that would print the words Hello Java

Advanced Programming RVU Comp.Science Dept. 11


Basic Syntax…
❖ About Java programs, it is very important to keep in mind the
following points.
❖ Case Sensitivity - Java is case sensitive, which means identifier
Hi and hi would have different meaning in Java.
❖ Class Names - For all 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()
Advanced Programming RVU Comp.Science Dept. 12
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 ‘HelloJava' is the class name, then the file
should be saved as HelloJava.java'
❖ public static void main(String args[]) - Java program processing
starts from the main() method, which is a mandatory part of every
Java program.

Advanced Programming RVU Comp.Science Dept. 13


Java Identifiers…
❖ All Java components require names.
❖ Names used for classes, variables and methods are called
identifiers.
❖ In Java, there are several points to remember about 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

Advanced Programming RVU Comp.Science Dept. 14


Java Modifiers…
❖ Like other languages, it is possible to modify classes, methods,
etc., by using modifiers.
❖ Modifiers are keywords that you add to those definitions to
change their meanings.
❖ The Java language has a wide variety of modifiers, including the
following:
❖ Java Access Modifiers
❖ Java provides a number of access modifiers to set access levels for
classes, variables, methods and constructors.
❖ The four access levels are:
❖ Visible to the package, the default(No keyword).
❖ Visible to the class only (private).
❖ Visible to the world (public).
❖ Visible to the package and all subclasses (protected).
Advanced Programming RVU Comp.Science Dept.
15
Java Modifiers…
❖ Default access modifier means we do not explicitly declare an
access modifier for a class, field, method, etc.
❖ A variable or method declared without any access control modifier
is available to any other class in the same package.
❖ The fields in an interface are implicitly public static final and the
methods in an interface are by default public.
❖ No modifiers are needed if the modifiers are default.
❖ Example:
❖ Variables and methods can be declared without any modifiers, as
in the following examples:

Advanced Programming RVU Comp.Science Dept. 16


Java Data Types…
❖ Variables are nothing but reserved memory locations to store
values.
❖ This means that when you create a variable you reserve some
space in memory.
❖ Based on the data type of a variable, the operating system
allocates memory and decides what can be stored in the reserved
memory.
❖ Therefore, by assigning different data types to variables, you can
store integers, decimals, or characters in these variables.
❖ There are two data types available in Java:
❖ Primitive Data Types
❖ Reference/Object Data Types

Advanced Programming RVU Comp.Science Dept.


17
Java 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.
❖ The eight primitive data types are:
❖ Byte ,Short, Int, Long, Double, boolean, Char, float
❖ 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, Student, etc.

Advanced Programming RVU Comp.Science Dept.


18
Java Data Types…
❖ 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: Employee emp= new Employee(“Hailemeskel");

N.B : Other data types are Non primitive data types(String)


❖ Strings which are widely used in Java programming are a
sequence of characters.
❖ In the Java programming language, strings are objects.
❖ The Java platform provides the String class to create and
manipulate strings.
❖ Example String name =“Hailemeskel”;
Advanced Programming RVU Comp.Science Dept.
19
Java Variable Types…
❖ A variable provides us with named storage that our programs can
manipulate.
❖ Each variable in Java has a specific type, which determines the
size and layout of the variable's memory; the range of values that
can be stored within that memory; and the set of operations that
can be applied to the variable.
❖ You must declare all variables before they can be used.
❖ The basic form of a variable declaration is shown here:
❖ 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.

Advanced Programming RVU Comp.Science Dept.


20
Java Variable Types…
❖ Following are valid examples of variable declaration and
initialization in Java:

❖ There are three kinds of variables in Java:


❖ Local variables
❖ Instance variables
❖ Class/static variables

Advanced Programming RVU Comp.Science Dept.


21
Java Keywords…
❖ The following list shows the reserved words in Java.
❖ These reserved words may not be used as constant or variable
or any other identifier names.

Advanced Programming RVU Comp.Science Dept.


22
Java Object & Classes…
❖ Java is an Object-Oriented Language.
❖ As a language that has the Object Oriented feature, Java supports
the following fundamental concepts:
❖ Polymorphism
❖ Inheritance
❖ Encapsulation
❖ Abstraction
❖ Classes
❖ Objects
❖ Instance
❖ Method
❖ Message Parsing

Advanced Programming RVU Comp.Science Dept.


23
Java Object & Classes…
❖ 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.
❖ Objects in Java:
❖ Let us now look deep into what are objects. If we consider the
real-world we can find many objects around us, Cars, Dogs,
Humans, etc.
❖ All these objects have a state and behavior.
❖ If we consider a dog, then its state is - name, breed, color, and
the behavior is - barking, wagging, running If you compare the
software object with a real world object, they have very similar
characteristics.

Advanced Programming RVU Comp.Science Dept.


24
Java Object & Classes…
❖ Software objects also have a state and behavior.
❖ A software object's state is stored in fields and behavior is shown
via methods.
❖ So in software development, methods operate on the internal state
of an object and the object-to-object communication is done via
methods.
❖ Class - A class can be defined as a template/blue print that
describes the behaviors/states that object of its type support.
❖ Classes in Java:
❖ A class is a blue print from which individual objects are created.

Advanced Programming RVU Comp.Science Dept.


25
Java Object & Classes…
❖ A sample of a class is given below:

Advanced Programming RVU Comp.Science Dept.


26
Cont’d…
❖ A class can contain any of the following variable types.
❖ Local variables: Variables defined inside methods, constructors
or blocks are called local variables.
❖ The variable will be declared and initialized within the method
and the variable will be destroyed when the method has
completed.
❖ Instance variables: Instance variables are variables within a class
but outside any method. These variables
❖ are instantiated when the class is loaded. Instance variables can be
accessed from inside any method,
❖ constructor or blocks of that particular class.
❖ Class variables: Class variables are variables declared within a
class, outside any method, with the static keyword.

Advanced Programming RVU Comp.Science Dept.


27
Cont’d…
❖ A class can have any number of methods to access the value of
various kinds of methods.
❖ In the above example, barking(), hungry() and sleeping() are
methods.
❖ Below mentioned are some of the important topics that need to be
discussed when looking into classes of the Java Language.
❖ Constructors: When discussing about classes, one of the most
important subtopic would be constructors.
❖ 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.
❖ Each time a new object is created, at least one constructor will be
invoked.

Advanced Programming RVU Comp.Science Dept.


28
Cont’d…
❖ Example of constructor is given below:

Advanced Programming RVU Comp.Science Dept.


29
Exception Handling…
❖ An exception is a problem that arises during the execution of a
program. An exception can occur for many different reasons,
including the following:
❖ A user has entered 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.
❖ Some of these exceptions are caused by user error, others by
programmer error, and others by physical resources that have
failed in some manner.

Advanced Programming RVU Comp.Science Dept.


30
Exception Handling…
❖ To understand how exception handling works in Java, you need to
understand the three categories of exceptions:
❖ Checked exceptions: A checked exception is an exception that is
typically a user error or a problem that cannot be foreseen by the
programmer.
❖ For example, if a file is to be opened, but the file cannot be
found, an exception occurs.
❖ These exceptions cannot simply be ignored at the time of
compilation.
❖ Runtime exceptions: A runtime exception is an exception that
occurs that probably could have been avoided by the programmer.
❖ As opposed to checked exceptions, runtime exceptions are
ignored at the time of compilation.

Advanced Programming RVU Comp.Science Dept.


31
Exception Handling…
❖ Errors: These are not exceptions at all, but problems that arise
beyond the control of the user or the programmer.
❖ Errors are typically ignored in your code because you can
rarely do anything about an error.
❖ For example, if a stack overflow occurs, an error will arise.
❖ They are also ignored at the time of compilation.
❖ Exception Hierarchy: All exception classes are subtypes of the
java.lang.Exception class.
❖ The exception class is a subclass of the Throwable class.
❖ Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
❖ Errors are not normally trapped form the Java programs.

Advanced Programming RVU Comp.Science Dept.


32
Exception Handling…
❖ These conditions normally happen in case of several failures,
which are not handled by the java programs.
❖ Errors are generated to indicate errors generated by the runtime
environment.
❖ Example : JVM is out of Memory.
❖ Normally programs cannot recover from errors.
❖ The Exception class has two main subclasses: IOException
class and RuntimeException Class.
❖ Throwable

Exception
Error

IOException RunimeExcepton
Advanced Programming RVU Comp.Science Dept.
33
Exception Handling…
❖ Java’s Built-in Exceptions
❖ Java defines several exception classes inside the standard package
java.lang.
❖ The most general of these exceptions are subclasses of the
standard type RuntimeException.
❖ Since java.lang is implicitly imported into all Java programs,
most exceptions derived from RuntimeException are
automatically available.
❖ Java defines several other types of exceptions that relate to its
various class libraries.
❖ Following is the list of Java Unchecked RuntimeException.

Advanced Programming RVU Comp.Science Dept.


34
Exception Handling…

Advanced Programming RVU Comp.Science Dept.


35
Exception Handling…

Advanced Programming RVU Comp.Science Dept.


36
Exception Handling…

Advanced Programming RVU Comp.Science Dept.


37
Exception Handling…
❖ Catching Exceptions:
❖ A method catches an exception using a combination of the try and
catch keywords.
❖ A try/catch block is placed around the code that might generate an
exception.
❖ Code within a try/catch block is referred to as protected code, and
the syntax for using try/catch looks like the following:

Advanced Programming RVU Comp.Science Dept.


38
Exception Handling…
❖ A catch statement involves declaring the type of exception you are
trying to catch.
❖ If an exception occurs in protected code, the catch block (or
blocks) that follows the try is checked.
❖ If the type of exception that occurred is listed in a catch block, the
exception is passed to the catch block much as an argument is
passed into a method parameter.

Advanced Programming RVU Comp.Science Dept.


39
Exception Handling…
❖ Example:

Advanced Programming RVU Comp.Science Dept.


40
Exception Handling…
❖ The throws/throw Keywords:
❖ If a method does not handle a checked exception, the method must
declare it using the throws keyword.
❖ The throws keyword appears at the end of a method's signature.
❖ You can throw an exception, either a newly instantiated one or an
exception that you just caught, by using the throw keyword.
❖ Try to understand the different in throws and throw keywords.
❖ The following method declares that it throws a RemoteException:

Advanced Programming RVU Comp.Science Dept.


41
Exception Handling…
❖ Example:

Advanced Programming RVU Comp.Science Dept.


42
Exception Handling…
❖ The finally Keyword
❖ The finally keyword is used to create a block of code that follows
a try block.
❖ A finally block of code always executes, whether or not an
exception has occurred.
❖ Using a finally block allows you to run any cleanup-type
statements that you want to execute, no matter what happens in
the protected code.
❖ A finally block appears at the end of the catch blocks and has the
following syntax:

Advanced Programming RVU Comp.Science Dept.


43
Exception Handling…
❖ Example:

Advanced Programming RVU Comp.Science Dept.


44
Exception Handling…
❖ Note the following:
❖ A catch clause cannot exist without a try statement.
❖ It is not compulsory to have finally clauses whenever a try/catch
block is present.
❖ The try block cannot be present without either catch clause or
finally clause.
❖ Any code cannot be present in between the try, catch, finally
blocks.

Advanced Programming RVU Comp.Science Dept.


45
Pop Quiz
1. Which of the following are not valid identifiers?

A. A2 Valid
B. _123abc Valid
C. Abc_ac Valid
D. $_a Valid
E. 123a Invalid
F. -a Invalid
G. _a Valid

Advanced Programming RVU Comp.Science Dept.


46
1. Write the Java program to display the following output
Hint[use special characters like tab, space, new line back space,
forward space etc.]

Advanced Programming RVU Comp.Science Dept.


47

You might also like