Java All Examples Eng
Java All Examples Eng
Java All Examples Eng
• Methods:
These methods have signature but no body
Their implementation is most usually given by child classes
A method that has {} but no source code is not abstract!
• Methods:
A final method cannot be overridden by a sub class
• Variables:
In a final variable a value can be given only once. (Be careful: What
happens with reference variables?)
Static 1/2
• Used in nested classes, nested interfaces, methods and variables
• Nested class:
Static inside a top level class
Cannot access non static members
Refer to them using the outer class name
• Nested interfaces:
Are by default static so there is no need to declare them static
Static 1/2
• Methods:
Belong to the class, not to the object
Cannot access instance members
Refer using the outer class name
Static methods exist both in classes and interfaces (Java 8+)
• Variables:
Belong to the class, not to the object
Are shared between instances. We don’t need object instantiation for their
existence
All interface variables are by default static
In Java the used way to declare a constant is use a final static variable
Accessing can be achieved both through the class but also through the
instance (the second way is not recommended)
Accessing between static and
non-static members
• A static method and a static variable cannot access not statica ones
• The opposite is correct. Non static members can access static ones
• Be very careful!:
Even a null object can still access static variables and/or methods. This is
why we won’t get a NullPointerException in this case. Nevertheless, such
code should be avoided…
Static Vs Non-static
Variables in Java
Variable scope
• Java variables can be characterized by their scope
• Based on their scope we have 4 categories of Java variables:
Local variables (variables inside methods)
Method parameters
Instance Variables
Class Variables (Static variables)
Local variables – Method
parameters
• Have very short “life time” since they live inside methods, and even in loops
• Always look at the block ( { } ) inside which they are declared
• No access to them outside their block
Instance variables
• Inside class, outside methods
• Without static keyword
• All non static methods have access
• Each object has its own ones
Class variables
• Inside class, outside methods
• Using static keyword
• All methods (static and non static) have access
• Belong to the class. No object can have its own ones
Same names for variables
• We cannot have an instance variable and a static variable with the
same name
• We cannot have a method parameter and a local variable with the
same name
• We can have a static variable and a local variable with the same
name. Also an instance variable and a local variable with the same
name. But you should take care!..
Additional
Knowledge 1
Method return statement
Variable Arguments (varargs)
• Java 5+
• Are actually arrays
• They allow as to give arguments of any length to a method (of the same
type of course)
• Each method can have up to one vararg parameter
• If a varargs exists then it should be the last parameter of the method
(why?...)
Java instanceof Operator
• Binary operator
• true – false
• Used with objects
• Checks whether an object is of a specific Type (including interfaces)
• Used many times in order to avoid ClassCastException
• General type:
(object) instanceof (type)
Example 1/2
Example 2/2
Result
this and super
• Use this keyword in order to access members of the “current” class
• Use super to access members of the parent class
• Both words can be used for static and non static members
• Can also be used with constructors (Advanced Java)
Example
Example
Example
Example – Pay attention!
Method overloading
Constructors
• Used to instantiate objects
• Have the same name as the class, yet, BE CAREFULL, what makes them differ
is the fact that they do not return anything!!!
• Accept overloading
• Support all levels of access modifiers
Default constructors
Invoking constructor from
another constructor…
• Using the keyword this
Constructors - Important
Initializer Block (Advanced)
• Τhe initializer block is a piece of code that is always executed when a
new object is created
• We don’t know which constructor is going to be used. However, the
initializer block will always be executed
• It is executed before constructor
Java API
Java Strings
• Sequence of characters
• Inside " "
• Every String is an object
• There are many ways to declare a String (String s = "Hello";)
• Handling String correctly can help:
Reduce errors
Code optimization!
Multithreading enviroments
String pool
• For code optimization Java incorporates a String pool
Creating Strings
• Even with the existence of a String Pool, if you use the “new”
keyword, a new String will be created!
String handling methods
Important!
• String is Immutable
• All String methods do not change its actual String content!
String comparison
• Be very careful. Many mistakes by programmers
• == is used to compare variables address
• Some times == can give as equality due to the String Pool. It should
be avoided!
• Use the equals() method
Be careful!
Mutable Strings
• Basic class: StringBuilder
• Belongs to package: java.lang
• Used either when we have “big” strings or when we make many
changes to the string
• In this way we may optimize our code!
• StringBuilder constructor accepts many overloads (to use them)
StringBuilder Methods
StringBuilder Vs StringBuffer
• Class StringBuffer offers almost the same functionality as
StringBuilder
• Basic difference is that StringBuffer is synchronized and thus
«thread safe»
• Nevertheless, synchronized comes at a cost (time overhead)
Java ArrayList
• One of the most used classes in Java
• Tries to combine the benefits of (Arrays) and (Lists)
• Dynamic size
• Basic functionality:
Add elements to the list
Delete elements from the list
Change elements of the list
Access elements of the list
ArrayList Properties
ArrayList Creation
ArrayList – Add Items
ArrayList – Item Iteration
ArrayList – Item Iteration v2
using ListIterator
Exercise
• Using the aforementioned two ways of iteration inside an ArrayList
try to see if you can change the values of the elements while you
access them (inside the loop)
• Write down what you observe!
ArrayList - addAll() method
ArrayList – Access elements
Examples
Exercise
• Use the following two methods in ArrayList:
toArray()
clone()
Java Extras
Ternary Operator ?:
?:
• In computer programming, ?: is a ternary operator that is part of the
syntax for a basic conditional expression
• It is commonly referred to as the conditional operator, inline if (iif),
or ternary if
• Basic syntax:
condition ? value_if_true : value_if_false
• The condition is evaluated true or false as a Boolean expression
• The entire expression returns value_if_true if condition is true, but
value_if_false otherwise
examples
for(int i=0;i<intarray.length;i++)
System.out.println(intarray[i]);
Examples (with foreach loop)
for(int i : intarray)
System.out.println(i]);
Some limitations
for(int i=0;i<intarray.length;i+=2)
System.out.println(intarray[i]);
More examples 1/2
for(String s : strarray)
System.out.println(s);
More examples 2/2 (even
better…)
• Continue
Unlabeled
Labeled
• Return
With value
No value
Java Inheritance
Inheritance 1/3
Inheritance 2/3
Inheritance 3/3
Inheritance Notes
• In the Java language, classes can be derived from other classes,
thereby inheriting fields and methods from those classes
• A class that is derived from another class is called a subclass
• The class from which the subclass is derived is called a superclass
What can a Subclass do?
• The inherited fields can be used directly, just like any other
fields
• You can declare new fields in the subclass that are not in
the superclass
• The inherited methods can be used directly as they are
• You can write a new instance method in the subclass that
has the same signature as the one in the superclass, thus
overriding it
• You can declare new methods in the subclass that are not in
the superclass
Inheritance Example
IS-A vs HAS-A
• IS-A means is of type and denotes Inheritance
• HAS-A means composition between objects
Class Diagram
Java Method Overriding
• A method defined in a super class may be overridden by a method of
the same name defined in a sub class
• The overriding method has the same name, number and type of
parameters, and return type as the method that it overrides
Advantages of Inheritance
• Lower size of code for subclasses
• Easily modify methods and variables
• Expansibility
• Base class code testing
• Logical division of code
Object variables
Example
Through its class
Through its super class
Through the implementing
Interface
Through the Object class
Why do we have so many
capabilities?
Casting with
objects
What is Casting
• Using casting we can enforce a variable behave as another variable
• In class level casting occurs when there is a IS-A relationship
Example
Testing 1/2
Testing 2/2
Java Anonymous
Classes
Extending an existing class
Implementing an existing
interface
Using new without a variable
• Just use the instance, without the variable
• new Object()
• In this case, we actually have an anonymous variable, not a new
class
Examples
Extending an existing Class
Implementing an existing Interface
Simply using “new”
• We can also use a simple method returning an object
Using variables inside
anonymous classes
• An anonymous class has full access to member variables of its outer
class
• An anonymous class cannot access local variables that are not final
or “effectively final”
Examples
Anonymous class with no default
constructor
Anonymous class with instance
initializer
Declarations inside an
anonymous class
• Fields (instance, static need to be final and initialized)
• Extra methods (even if they do not implement any methods of the
supertype)
• Instance initializers
• Local classes (εσωτερικές τάξεις)
• We cannot include a nested interface…
Why anonymous object
• Used mostly as method parameters
Classes or subclasses of a specific Type
Implementing specific Interfaces