0% found this document useful (0 votes)
5 views

JAVA 2

Uploaded by

aelshahed2027
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

JAVA 2

Uploaded by

aelshahed2027
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

JAVA Programming

Fundamental & OOP


Eng. Nada Mohamed Sarhan
Outline
• Environment set up
• Object & Classes
• Modifiers
• Variables
• exception
• Decision making
• Loops
• Exercises
• Strings
• Arrays
• Inner class
• Exercises
• Assignment
• Bounce
Environment set up
• Assuming you have installed JAVA in c:\Program Files\java\jdk.
• Right-click on ‘My Computer’ and select ‘Properties’.
• Select the ‘Advanced ’ tab, then Click the ‘Environment variables’
button.
• Now, alter the ‘Path’ variable so that it also contains the path to the
Java executable. Example, if the path is currently set to
‘C:\WINDOWS\SYSTEM’, then change your path to read.
‘C:\WINDOWS\SYSTEM;c:\Program Files\java\jdk\bin’.
Environment set up
• To verify your java version open the CMD.
• Write command ‘java –version ’
Class & Object
• Object – have states and behaviors
• Class – template/blueprint that describe the behavior/state of the
object
• Method – is basically a behavior, class can contain many methods
JAVA variables
• Java variables:

• Local variables
• Class variables (static)
• Instance variables (non-static)
Local variable

• Local variables are declared in methods, constructors, or blocks.


• Local variables are created when the method, constructor or block is
entered and the variable will be destroyed once it exits the method,
constructor, or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor,
or block.
• There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.
Class variable

• Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
• Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program
stops.
Class variable

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

• Instance variables are declared in a class, but outside a method,


constructor or any block.
• Instance variables are created when an object is created with the use
of the keyword 'new' and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than
one method, constructor or block, or essential parts of an object's
state that must be present throughout the class.
• Access modifiers can be given for instance variables.
JAVA modifiers
• Java modifiers:

• Access modifiers – public, private, protected & default.


• Non-Access modifiers – final, static & abstract.
Access control modifiers

• Visible to the package, the (default). No modifiers are needed.


• Visible to the class only (private).
• Visible to the world (public).
• Visible to the package and all subclasses (protected).
Non-Access control modifiers

• The static modifier for creating class methods and variables.


• The final modifier for finalizing the implementations of classes,
methods, and variables.
• The abstract modifier for creating abstract classes and methods.
• The synchronized and volatile modifiers, which are used for threads.
• Java Keywords:
Exceptions
• Type of error:
• Compile time error:
• Prevent the code from running because of an incorrect syntax.
• Run time error:
• Detected during the execution of the program.
• Logical error:
• When your program compiles and executes, but does the wrong thing or
returns an incorrect result or no output when it should be returning an
output.
Exceptions
• An exception (or exceptional event) is a problem that arises during
the execution of a program.
• Exception (run time error).
• When an Exception occurs, the normal flow of the program is
disrupted and the program/Application terminates abnormally, which
is not recommended, therefore, these exceptions are to be handled.
Exceptions
• An exception can occur for many different reasons. 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.
Exceptions
• Based on these, we have three categories of Exceptions. You need to
understand them to know how exception handling works in Java:
• Checked exceptions
• Unchecked exceptions
• Errors
Exceptions
• Checked exceptions:
• A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions.
• These exceptions cannot simply be ignored at the time of compilation,
the programmer should take care of (handle) these exceptions.
• For example, if you use FileReader class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then
a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
• checked exceptions represent errors outside the control of the program.
Exceptions
• Unchecked exceptions:
• An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions.
• These include programming bugs, such as logic errors or improper
use of an API. Runtime exceptions are ignored at the time of
compilation.
• For example, if you have declared an array of size 5 in your
program, and trying to call the 6th element of the array then
an ArrayIndexOutOfBoundsExceptionexception occurs.
• it reflects some error inside the program logic.
Exceptions
• 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.
Exceptions
• 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 abnormal conditions that happen in case of severe failures, these
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.
Exceptions
• Exception Hierarchy :
Exceptions
• 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
• Syntax:
Exceptions
• Example:
Exceptions
• Multiple Catch Blocks:
• A try block can be followed by multiple catch blocks. The syntax for multiple
catch blocks
• Syntax:
Exceptions
• Example:
Exceptions
• User-defined Exceptions:
• You can create your own exceptions in Java.
• Keep the following points in mind when writing your own exception classes −
• All exceptions must be a child of Throwable.
• If you want to write a checked exception that is automatically enforced by the
Handle or Declare Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the
RuntimeException class.
Exceptions
• User-defined Exceptions:

• Syntax:

• You just need to extend the predefined Exception class to create your
own Exception. These are considered to be checked exceptions
Exercise time!
Exercise
• Write first java program (hello world).

1. Write program in notpad.


2. Save as .java file.
3. Open cmd
4. javac HelloWorld.java
5. java HelloWorld
Answer
Answer
Exercise
• Write a program in Java to check if a number is even or odd in Java?
(input 2 output true, input 3 : output false)
• A number is called even if it is completely divisible by two and odd if it’s not
completely divisible by two.
Answer
Exercise
• Write a Program to Find Factorial of a Number in Java.
• n! = n * (n-1) * (n-2) * (n-3) * ........ * 1
Answer
Exercise
• Write a program in Java to find out if a number is prime in Java?
(input 7: output true , input 9 : output false)
• A number is called prime if it is divisible by either itself or 1.
Answer
Exercise
• Write a Java program to calculate the sum of all numbers from 1 to n.
Answer
Strings
• Strings, which are widely used in Java programming, are a sequence
of characters. In Java programming language, strings are treated as
objects.
• Creating Strings:
• String greeting = “Hello Java”;
Strings
• As with any other object, you can create String objects by using the
new keyword and a constructor. The String class has 11 constructors
that allow you to provide the initial value of the string using different
sources, such as an array of characters.
• Note − The String class is immutable, so that once it is created a String
object cannot be changed. If there is a necessity to make a lot of
modifications to Strings of characters, then you should use
StringBuffer and StringBuilder Classes.
Strings
• String Length
• Methods used to obtain information about an object are known as
accessor methods. One accessor method that you can use with
strings is the length() method, which returns the number of
characters contained in the string object.
• Example:
Strings
String Pools:
• String objects that are created without using new keyword are said
belong to the “String Pool”
Arrays
• Java provides a data structure, the array, which stores a fixed-size
sequential collection of elements of the same type.
• An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same
type.
• Instead of declaring individual variables, such as number0,
number1, ..., and number99, you declare one array variable such as
numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables.
Arrays

• Declaring Array Variables:


• Syntax:
• dataType[] arrayRefVar; // preferred way.
• or
• dataType arrayRefVar[]; // works but not preferred way.
• Example
Arrays

• Creating Array:
• You can create an array by using the new operator with the following syntax
• arrayRefVar = new dataType[arraySize];
• Example:
Arrays

• Example:
Arrays

• Processing Arrays:
• When processing array elements, we often use either for loop or
foreach loop because all of the elements in an array are of the same
type and the size of the array is known
Arrays

• Example:
Arrays

• The Arrays Class:


• The java.util.Arrays class contains various static methods for sorting
and searching arrays, comparing arrays, and filling array elements.
These methods are overloaded for all primitive types.
Exercise time!
Exercise
• Write a Java Program to Compute the Sum of Array Elements.
• Write java program to Compare 2 String.
• Write a Java Program to Find the Largest Element in Array
• Write java program get 10 integer elements from user in array.
Assignment
• Write java String Program to Reverse a String.
• Write java program to sort an array in java in descending order.
Topic to search

• Difference between The Throws/Throw Keyword and Finally


• Difference between string object and string pool
• Diff bet stack and heap memory
Bounce
• Java String Program to Check Anagram.

You might also like